]> git.lizzy.rs Git - sqlite3-cmake.git/blob - src/shell.c
3.35.5
[sqlite3-cmake.git] / src / shell.c
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37
38 /*
39 ** 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   for(i=n=0; zUtf[i]; i++){
575     if( (zUtf[i]&0xc0)!=0x80 ){
576       n++;
577       if( n==aw ){
578         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
579         break;
580       }
581     }
582   }
583   if( n>=aw ){
584     utf8_printf(pOut, "%.*s", i, zUtf);
585   }else if( w<0 ){
586     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
587   }else{
588     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
589   }
590 }
591
592
593 /*
594 ** Determines if a string is a number of not.
595 */
596 static int isNumber(const char *z, int *realnum){
597   if( *z=='-' || *z=='+' ) z++;
598   if( !IsDigit(*z) ){
599     return 0;
600   }
601   z++;
602   if( realnum ) *realnum = 0;
603   while( IsDigit(*z) ){ z++; }
604   if( *z=='.' ){
605     z++;
606     if( !IsDigit(*z) ) return 0;
607     while( IsDigit(*z) ){ z++; }
608     if( realnum ) *realnum = 1;
609   }
610   if( *z=='e' || *z=='E' ){
611     z++;
612     if( *z=='+' || *z=='-' ) z++;
613     if( !IsDigit(*z) ) return 0;
614     while( IsDigit(*z) ){ z++; }
615     if( realnum ) *realnum = 1;
616   }
617   return *z==0;
618 }
619
620 /*
621 ** Compute a string length that is limited to what can be stored in
622 ** lower 30 bits of a 32-bit signed integer.
623 */
624 static int strlen30(const char *z){
625   const char *z2 = z;
626   while( *z2 ){ z2++; }
627   return 0x3fffffff & (int)(z2 - z);
628 }
629
630 /*
631 ** Return the length of a string in characters.  Multibyte UTF8 characters
632 ** count as a single character.
633 */
634 static int strlenChar(const char *z){
635   int n = 0;
636   while( *z ){
637     if( (0xc0&*(z++))!=0x80 ) n++;
638   }
639   return n;
640 }
641
642 /*
643 ** Return true if zFile does not exist or if it is not an ordinary file.
644 */
645 #ifdef _WIN32
646 # define notNormalFile(X) 0
647 #else
648 static int notNormalFile(const char *zFile){
649   struct stat x;
650   int rc;
651   memset(&x, 0, sizeof(x));
652   rc = stat(zFile, &x);
653   return rc || !S_ISREG(x.st_mode);
654 }
655 #endif
656
657 /*
658 ** This routine reads a line of text from FILE in, stores
659 ** the text in memory obtained from malloc() and returns a pointer
660 ** to the text.  NULL is returned at end of file, or if malloc()
661 ** fails.
662 **
663 ** If zLine is not NULL then it is a malloced buffer returned from
664 ** a previous call to this routine that may be reused.
665 */
666 static char *local_getline(char *zLine, FILE *in){
667   int nLine = zLine==0 ? 0 : 100;
668   int n = 0;
669
670   while( 1 ){
671     if( n+100>nLine ){
672       nLine = nLine*2 + 100;
673       zLine = realloc(zLine, nLine);
674       if( zLine==0 ) shell_out_of_memory();
675     }
676     if( fgets(&zLine[n], nLine - n, in)==0 ){
677       if( n==0 ){
678         free(zLine);
679         return 0;
680       }
681       zLine[n] = 0;
682       break;
683     }
684     while( zLine[n] ) n++;
685     if( n>0 && zLine[n-1]=='\n' ){
686       n--;
687       if( n>0 && zLine[n-1]=='\r' ) n--;
688       zLine[n] = 0;
689       break;
690     }
691   }
692 #if defined(_WIN32) || defined(WIN32)
693   /* For interactive input on Windows systems, translate the
694   ** multi-byte characterset characters into UTF-8. */
695   if( stdin_is_interactive && in==stdin ){
696     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
697     if( zTrans ){
698       int nTrans = strlen30(zTrans)+1;
699       if( nTrans>nLine ){
700         zLine = realloc(zLine, nTrans);
701         if( zLine==0 ) shell_out_of_memory();
702       }
703       memcpy(zLine, zTrans, nTrans);
704       sqlite3_free(zTrans);
705     }
706   }
707 #endif /* defined(_WIN32) || defined(WIN32) */
708   return zLine;
709 }
710
711 /*
712 ** Retrieve a single line of input text.
713 **
714 ** If in==0 then read from standard input and prompt before each line.
715 ** If isContinuation is true, then a continuation prompt is appropriate.
716 ** If isContinuation is zero, then the main prompt should be used.
717 **
718 ** If zPrior is not NULL then it is a buffer from a prior call to this
719 ** routine that can be reused.
720 **
721 ** The result is stored in space obtained from malloc() and must either
722 ** be freed by the caller or else passed back into this routine via the
723 ** zPrior argument for reuse.
724 */
725 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
726   char *zPrompt;
727   char *zResult;
728   if( in!=0 ){
729     zResult = local_getline(zPrior, in);
730   }else{
731     zPrompt = isContinuation ? continuePrompt : mainPrompt;
732 #if SHELL_USE_LOCAL_GETLINE
733     printf("%s", zPrompt);
734     fflush(stdout);
735     zResult = local_getline(zPrior, stdin);
736 #else
737     free(zPrior);
738     zResult = shell_readline(zPrompt);
739     if( zResult && *zResult ) shell_add_history(zResult);
740 #endif
741   }
742   return zResult;
743 }
744
745
746 /*
747 ** Return the value of a hexadecimal digit.  Return -1 if the input
748 ** is not a hex digit.
749 */
750 static int hexDigitValue(char c){
751   if( c>='0' && c<='9' ) return c - '0';
752   if( c>='a' && c<='f' ) return c - 'a' + 10;
753   if( c>='A' && c<='F' ) return c - 'A' + 10;
754   return -1;
755 }
756
757 /*
758 ** Interpret zArg as an integer value, possibly with suffixes.
759 */
760 static sqlite3_int64 integerValue(const char *zArg){
761   sqlite3_int64 v = 0;
762   static const struct { char *zSuffix; int iMult; } aMult[] = {
763     { "KiB", 1024 },
764     { "MiB", 1024*1024 },
765     { "GiB", 1024*1024*1024 },
766     { "KB",  1000 },
767     { "MB",  1000000 },
768     { "GB",  1000000000 },
769     { "K",   1000 },
770     { "M",   1000000 },
771     { "G",   1000000000 },
772   };
773   int i;
774   int isNeg = 0;
775   if( zArg[0]=='-' ){
776     isNeg = 1;
777     zArg++;
778   }else if( zArg[0]=='+' ){
779     zArg++;
780   }
781   if( zArg[0]=='0' && zArg[1]=='x' ){
782     int x;
783     zArg += 2;
784     while( (x = hexDigitValue(zArg[0]))>=0 ){
785       v = (v<<4) + x;
786       zArg++;
787     }
788   }else{
789     while( IsDigit(zArg[0]) ){
790       v = v*10 + zArg[0] - '0';
791       zArg++;
792     }
793   }
794   for(i=0; i<ArraySize(aMult); i++){
795     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
796       v *= aMult[i].iMult;
797       break;
798     }
799   }
800   return isNeg? -v : v;
801 }
802
803 /*
804 ** A variable length string to which one can append text.
805 */
806 typedef struct ShellText ShellText;
807 struct ShellText {
808   char *z;
809   int n;
810   int nAlloc;
811 };
812
813 /*
814 ** Initialize and destroy a ShellText object
815 */
816 static void initText(ShellText *p){
817   memset(p, 0, sizeof(*p));
818 }
819 static void freeText(ShellText *p){
820   free(p->z);
821   initText(p);
822 }
823
824 /* zIn is either a pointer to a NULL-terminated string in memory obtained
825 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
826 ** added to zIn, and the result returned in memory obtained from malloc().
827 ** zIn, if it was not NULL, is freed.
828 **
829 ** If the third argument, quote, is not '\0', then it is used as a
830 ** quote character for zAppend.
831 */
832 static void appendText(ShellText *p, char const *zAppend, char quote){
833   int len;
834   int i;
835   int nAppend = strlen30(zAppend);
836
837   len = nAppend+p->n+1;
838   if( quote ){
839     len += 2;
840     for(i=0; i<nAppend; i++){
841       if( zAppend[i]==quote ) len++;
842     }
843   }
844
845   if( p->n+len>=p->nAlloc ){
846     p->nAlloc = p->nAlloc*2 + len + 20;
847     p->z = realloc(p->z, p->nAlloc);
848     if( p->z==0 ) shell_out_of_memory();
849   }
850
851   if( quote ){
852     char *zCsr = p->z+p->n;
853     *zCsr++ = quote;
854     for(i=0; i<nAppend; i++){
855       *zCsr++ = zAppend[i];
856       if( zAppend[i]==quote ) *zCsr++ = quote;
857     }
858     *zCsr++ = quote;
859     p->n = (int)(zCsr - p->z);
860     *zCsr = '\0';
861   }else{
862     memcpy(p->z+p->n, zAppend, nAppend);
863     p->n += nAppend;
864     p->z[p->n] = '\0';
865   }
866 }
867
868 /*
869 ** Attempt to determine if identifier zName needs to be quoted, either
870 ** because it contains non-alphanumeric characters, or because it is an
871 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
872 ** that quoting is required.
873 **
874 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
875 */
876 static char quoteChar(const char *zName){
877   int i;
878   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
879   for(i=0; zName[i]; i++){
880     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
881   }
882   return sqlite3_keyword_check(zName, i) ? '"' : 0;
883 }
884
885 /*
886 ** Construct a fake object name and column list to describe the structure
887 ** of the view, virtual table, or table valued function zSchema.zName.
888 */
889 static char *shellFakeSchema(
890   sqlite3 *db,            /* The database connection containing the vtab */
891   const char *zSchema,    /* Schema of the database holding the vtab */
892   const char *zName       /* The name of the virtual table */
893 ){
894   sqlite3_stmt *pStmt = 0;
895   char *zSql;
896   ShellText s;
897   char cQuote;
898   char *zDiv = "(";
899   int nRow = 0;
900
901   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
902                          zSchema ? zSchema : "main", zName);
903   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
904   sqlite3_free(zSql);
905   initText(&s);
906   if( zSchema ){
907     cQuote = quoteChar(zSchema);
908     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
909     appendText(&s, zSchema, cQuote);
910     appendText(&s, ".", 0);
911   }
912   cQuote = quoteChar(zName);
913   appendText(&s, zName, cQuote);
914   while( sqlite3_step(pStmt)==SQLITE_ROW ){
915     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
916     nRow++;
917     appendText(&s, zDiv, 0);
918     zDiv = ",";
919     cQuote = quoteChar(zCol);
920     appendText(&s, zCol, cQuote);
921   }
922   appendText(&s, ")", 0);
923   sqlite3_finalize(pStmt);
924   if( nRow==0 ){
925     freeText(&s);
926     s.z = 0;
927   }
928   return s.z;
929 }
930
931 /*
932 ** SQL function:  shell_module_schema(X)
933 **
934 ** Return a fake schema for the table-valued function or eponymous virtual
935 ** table X.
936 */
937 static void shellModuleSchema(
938   sqlite3_context *pCtx,
939   int nVal,
940   sqlite3_value **apVal
941 ){
942   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
943   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
944   UNUSED_PARAMETER(nVal);
945   if( zFake ){
946     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
947                         -1, sqlite3_free);
948     free(zFake);
949   }
950 }
951
952 /*
953 ** SQL function:  shell_add_schema(S,X)
954 **
955 ** Add the schema name X to the CREATE statement in S and return the result.
956 ** Examples:
957 **
958 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
959 **
960 ** Also works on
961 **
962 **    CREATE INDEX
963 **    CREATE UNIQUE INDEX
964 **    CREATE VIEW
965 **    CREATE TRIGGER
966 **    CREATE VIRTUAL TABLE
967 **
968 ** This UDF is used by the .schema command to insert the schema name of
969 ** attached databases into the middle of the sqlite_schema.sql field.
970 */
971 static void shellAddSchemaName(
972   sqlite3_context *pCtx,
973   int nVal,
974   sqlite3_value **apVal
975 ){
976   static const char *aPrefix[] = {
977      "TABLE",
978      "INDEX",
979      "UNIQUE INDEX",
980      "VIEW",
981      "TRIGGER",
982      "VIRTUAL TABLE"
983   };
984   int i = 0;
985   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
986   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
987   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
988   sqlite3 *db = sqlite3_context_db_handle(pCtx);
989   UNUSED_PARAMETER(nVal);
990   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
991     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
992       int n = strlen30(aPrefix[i]);
993       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
994         char *z = 0;
995         char *zFake = 0;
996         if( zSchema ){
997           char cQuote = quoteChar(zSchema);
998           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
999             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1000           }else{
1001             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1002           }
1003         }
1004         if( zName
1005          && aPrefix[i][0]=='V'
1006          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1007         ){
1008           if( z==0 ){
1009             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1010           }else{
1011             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1012           }
1013           free(zFake);
1014         }
1015         if( z ){
1016           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1017           return;
1018         }
1019       }
1020     }
1021   }
1022   sqlite3_result_value(pCtx, apVal[0]);
1023 }
1024
1025 /*
1026 ** The source code for several run-time loadable extensions is inserted
1027 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1028 ** code, we need to override some macros to make the included program code
1029 ** work here in the middle of this regular program.
1030 */
1031 #define SQLITE_EXTENSION_INIT1
1032 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1033
1034 #if defined(_WIN32) && defined(_MSC_VER)
1035 /************************* Begin test_windirent.h ******************/
1036 /*
1037 ** 2015 November 30
1038 **
1039 ** The author disclaims copyright to this source code.  In place of
1040 ** a legal notice, here is a blessing:
1041 **
1042 **    May you do good and not evil.
1043 **    May you find forgiveness for yourself and forgive others.
1044 **    May you share freely, never taking more than you give.
1045 **
1046 *************************************************************************
1047 ** This file contains declarations for most of the opendir() family of
1048 ** POSIX functions on Win32 using the MSVCRT.
1049 */
1050
1051 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1052 #define SQLITE_WINDIRENT_H
1053
1054 /*
1055 ** We need several data types from the Windows SDK header.
1056 */
1057
1058 #ifndef WIN32_LEAN_AND_MEAN
1059 #define WIN32_LEAN_AND_MEAN
1060 #endif
1061
1062 #include "windows.h"
1063
1064 /*
1065 ** We need several support functions from the SQLite core.
1066 */
1067
1068 /* #include "sqlite3.h" */
1069
1070 /*
1071 ** We need several things from the ANSI and MSVCRT headers.
1072 */
1073
1074 #include <stdio.h>
1075 #include <stdlib.h>
1076 #include <errno.h>
1077 #include <io.h>
1078 #include <limits.h>
1079 #include <sys/types.h>
1080 #include <sys/stat.h>
1081
1082 /*
1083 ** We may need several defines that should have been in "sys/stat.h".
1084 */
1085
1086 #ifndef S_ISREG
1087 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1088 #endif
1089
1090 #ifndef S_ISDIR
1091 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1092 #endif
1093
1094 #ifndef S_ISLNK
1095 #define S_ISLNK(mode) (0)
1096 #endif
1097
1098 /*
1099 ** We may need to provide the "mode_t" type.
1100 */
1101
1102 #ifndef MODE_T_DEFINED
1103   #define MODE_T_DEFINED
1104   typedef unsigned short mode_t;
1105 #endif
1106
1107 /*
1108 ** We may need to provide the "ino_t" type.
1109 */
1110
1111 #ifndef INO_T_DEFINED
1112   #define INO_T_DEFINED
1113   typedef unsigned short ino_t;
1114 #endif
1115
1116 /*
1117 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1118 */
1119
1120 #ifndef NAME_MAX
1121 #  ifdef FILENAME_MAX
1122 #    define NAME_MAX (FILENAME_MAX)
1123 #  else
1124 #    define NAME_MAX (260)
1125 #  endif
1126 #endif
1127
1128 /*
1129 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1130 */
1131
1132 #ifndef NULL_INTPTR_T
1133 #  define NULL_INTPTR_T ((intptr_t)(0))
1134 #endif
1135
1136 #ifndef BAD_INTPTR_T
1137 #  define BAD_INTPTR_T ((intptr_t)(-1))
1138 #endif
1139
1140 /*
1141 ** We need to provide the necessary structures and related types.
1142 */
1143
1144 #ifndef DIRENT_DEFINED
1145 #define DIRENT_DEFINED
1146 typedef struct DIRENT DIRENT;
1147 typedef DIRENT *LPDIRENT;
1148 struct DIRENT {
1149   ino_t d_ino;               /* Sequence number, do not use. */
1150   unsigned d_attributes;     /* Win32 file attributes. */
1151   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1152 };
1153 #endif
1154
1155 #ifndef DIR_DEFINED
1156 #define DIR_DEFINED
1157 typedef struct DIR DIR;
1158 typedef DIR *LPDIR;
1159 struct DIR {
1160   intptr_t d_handle; /* Value returned by "_findfirst". */
1161   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1162   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1163 };
1164 #endif
1165
1166 /*
1167 ** Provide a macro, for use by the implementation, to determine if a
1168 ** particular directory entry should be skipped over when searching for
1169 ** the next directory entry that should be returned by the readdir() or
1170 ** readdir_r() functions.
1171 */
1172
1173 #ifndef is_filtered
1174 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1175 #endif
1176
1177 /*
1178 ** Provide the function prototype for the POSIX compatiable getenv()
1179 ** function.  This function is not thread-safe.
1180 */
1181
1182 extern const char *windirent_getenv(const char *name);
1183
1184 /*
1185 ** Finally, we can provide the function prototypes for the opendir(),
1186 ** readdir(), readdir_r(), and closedir() POSIX functions.
1187 */
1188
1189 extern LPDIR opendir(const char *dirname);
1190 extern LPDIRENT readdir(LPDIR dirp);
1191 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1192 extern INT closedir(LPDIR dirp);
1193
1194 #endif /* defined(WIN32) && defined(_MSC_VER) */
1195
1196 /************************* End test_windirent.h ********************/
1197 /************************* Begin test_windirent.c ******************/
1198 /*
1199 ** 2015 November 30
1200 **
1201 ** The author disclaims copyright to this source code.  In place of
1202 ** a legal notice, here is a blessing:
1203 **
1204 **    May you do good and not evil.
1205 **    May you find forgiveness for yourself and forgive others.
1206 **    May you share freely, never taking more than you give.
1207 **
1208 *************************************************************************
1209 ** This file contains code to implement most of the opendir() family of
1210 ** POSIX functions on Win32 using the MSVCRT.
1211 */
1212
1213 #if defined(_WIN32) && defined(_MSC_VER)
1214 /* #include "test_windirent.h" */
1215
1216 /*
1217 ** Implementation of the POSIX getenv() function using the Win32 API.
1218 ** This function is not thread-safe.
1219 */
1220 const char *windirent_getenv(
1221   const char *name
1222 ){
1223   static char value[32768]; /* Maximum length, per MSDN */
1224   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1225   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1226
1227   memset(value, 0, sizeof(value));
1228   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1229   if( dwRet==0 || dwRet>dwSize ){
1230     /*
1231     ** The function call to GetEnvironmentVariableA() failed -OR-
1232     ** the buffer is not large enough.  Either way, return NULL.
1233     */
1234     return 0;
1235   }else{
1236     /*
1237     ** The function call to GetEnvironmentVariableA() succeeded
1238     ** -AND- the buffer contains the entire value.
1239     */
1240     return value;
1241   }
1242 }
1243
1244 /*
1245 ** Implementation of the POSIX opendir() function using the MSVCRT.
1246 */
1247 LPDIR opendir(
1248   const char *dirname
1249 ){
1250   struct _finddata_t data;
1251   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1252   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1253
1254   if( dirp==NULL ) return NULL;
1255   memset(dirp, 0, sizeof(DIR));
1256
1257   /* TODO: Remove this if Unix-style root paths are not used. */
1258   if( sqlite3_stricmp(dirname, "/")==0 ){
1259     dirname = windirent_getenv("SystemDrive");
1260   }
1261
1262   memset(&data, 0, sizeof(struct _finddata_t));
1263   _snprintf(data.name, namesize, "%s\\*", dirname);
1264   dirp->d_handle = _findfirst(data.name, &data);
1265
1266   if( dirp->d_handle==BAD_INTPTR_T ){
1267     closedir(dirp);
1268     return NULL;
1269   }
1270
1271   /* TODO: Remove this block to allow hidden and/or system files. */
1272   if( is_filtered(data) ){
1273 next:
1274
1275     memset(&data, 0, sizeof(struct _finddata_t));
1276     if( _findnext(dirp->d_handle, &data)==-1 ){
1277       closedir(dirp);
1278       return NULL;
1279     }
1280
1281     /* TODO: Remove this block to allow hidden and/or system files. */
1282     if( is_filtered(data) ) goto next;
1283   }
1284
1285   dirp->d_first.d_attributes = data.attrib;
1286   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1287   dirp->d_first.d_name[NAME_MAX] = '\0';
1288
1289   return dirp;
1290 }
1291
1292 /*
1293 ** Implementation of the POSIX readdir() function using the MSVCRT.
1294 */
1295 LPDIRENT readdir(
1296   LPDIR dirp
1297 ){
1298   struct _finddata_t data;
1299
1300   if( dirp==NULL ) return NULL;
1301
1302   if( dirp->d_first.d_ino==0 ){
1303     dirp->d_first.d_ino++;
1304     dirp->d_next.d_ino++;
1305
1306     return &dirp->d_first;
1307   }
1308
1309 next:
1310
1311   memset(&data, 0, sizeof(struct _finddata_t));
1312   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1313
1314   /* TODO: Remove this block to allow hidden and/or system files. */
1315   if( is_filtered(data) ) goto next;
1316
1317   dirp->d_next.d_ino++;
1318   dirp->d_next.d_attributes = data.attrib;
1319   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1320   dirp->d_next.d_name[NAME_MAX] = '\0';
1321
1322   return &dirp->d_next;
1323 }
1324
1325 /*
1326 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1327 */
1328 INT readdir_r(
1329   LPDIR dirp,
1330   LPDIRENT entry,
1331   LPDIRENT *result
1332 ){
1333   struct _finddata_t data;
1334
1335   if( dirp==NULL ) return EBADF;
1336
1337   if( dirp->d_first.d_ino==0 ){
1338     dirp->d_first.d_ino++;
1339     dirp->d_next.d_ino++;
1340
1341     entry->d_ino = dirp->d_first.d_ino;
1342     entry->d_attributes = dirp->d_first.d_attributes;
1343     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1344     entry->d_name[NAME_MAX] = '\0';
1345
1346     *result = entry;
1347     return 0;
1348   }
1349
1350 next:
1351
1352   memset(&data, 0, sizeof(struct _finddata_t));
1353   if( _findnext(dirp->d_handle, &data)==-1 ){
1354     *result = NULL;
1355     return ENOENT;
1356   }
1357
1358   /* TODO: Remove this block to allow hidden and/or system files. */
1359   if( is_filtered(data) ) goto next;
1360
1361   entry->d_ino = (ino_t)-1; /* not available */
1362   entry->d_attributes = data.attrib;
1363   strncpy(entry->d_name, data.name, NAME_MAX);
1364   entry->d_name[NAME_MAX] = '\0';
1365
1366   *result = entry;
1367   return 0;
1368 }
1369
1370 /*
1371 ** Implementation of the POSIX closedir() function using the MSVCRT.
1372 */
1373 INT closedir(
1374   LPDIR dirp
1375 ){
1376   INT result = 0;
1377
1378   if( dirp==NULL ) return EINVAL;
1379
1380   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1381     result = _findclose(dirp->d_handle);
1382   }
1383
1384   sqlite3_free(dirp);
1385   return result;
1386 }
1387
1388 #endif /* defined(WIN32) && defined(_MSC_VER) */
1389
1390 /************************* End test_windirent.c ********************/
1391 #define dirent DIRENT
1392 #endif
1393 /************************* Begin ../ext/misc/shathree.c ******************/
1394 /*
1395 ** 2017-03-08
1396 **
1397 ** The author disclaims copyright to this source code.  In place of
1398 ** a legal notice, here is a blessing:
1399 **
1400 **    May you do good and not evil.
1401 **    May you find forgiveness for yourself and forgive others.
1402 **    May you share freely, never taking more than you give.
1403 **
1404 ******************************************************************************
1405 **
1406 ** This SQLite extension implements functions that compute SHA3 hashes.
1407 ** Two SQL functions are implemented:
1408 **
1409 **     sha3(X,SIZE)
1410 **     sha3_query(Y,SIZE)
1411 **
1412 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1413 ** X is NULL.
1414 **
1415 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
1416 ** and returns a hash of their results.
1417 **
1418 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1419 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1420 ** 384, or 512, to determine SHA3 hash variant that is computed.
1421 */
1422 /* #include "sqlite3ext.h" */
1423 SQLITE_EXTENSION_INIT1
1424 #include <assert.h>
1425 #include <string.h>
1426 #include <stdarg.h>
1427
1428 #ifndef SQLITE_AMALGAMATION
1429 /* typedef sqlite3_uint64 u64; */
1430 #endif /* SQLITE_AMALGAMATION */
1431
1432 /******************************************************************************
1433 ** The Hash Engine
1434 */
1435 /*
1436 ** Macros to determine whether the machine is big or little endian,
1437 ** and whether or not that determination is run-time or compile-time.
1438 **
1439 ** For best performance, an attempt is made to guess at the byte-order
1440 ** using C-preprocessor macros.  If that is unsuccessful, or if
1441 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1442 ** at run-time.
1443 */
1444 #ifndef SHA3_BYTEORDER
1445 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1446      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1447      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1448      defined(__arm__)
1449 #   define SHA3_BYTEORDER    1234
1450 # elif defined(sparc)    || defined(__ppc__)
1451 #   define SHA3_BYTEORDER    4321
1452 # else
1453 #   define SHA3_BYTEORDER 0
1454 # endif
1455 #endif
1456
1457
1458 /*
1459 ** State structure for a SHA3 hash in progress
1460 */
1461 typedef struct SHA3Context SHA3Context;
1462 struct SHA3Context {
1463   union {
1464     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1465     unsigned char x[1600];    /* ... or 1600 bytes */
1466   } u;
1467   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1468   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1469   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1470 };
1471
1472 /*
1473 ** A single step of the Keccak mixing function for a 1600-bit state
1474 */
1475 static void KeccakF1600Step(SHA3Context *p){
1476   int i;
1477   u64 b0, b1, b2, b3, b4;
1478   u64 c0, c1, c2, c3, c4;
1479   u64 d0, d1, d2, d3, d4;
1480   static const u64 RC[] = {
1481     0x0000000000000001ULL,  0x0000000000008082ULL,
1482     0x800000000000808aULL,  0x8000000080008000ULL,
1483     0x000000000000808bULL,  0x0000000080000001ULL,
1484     0x8000000080008081ULL,  0x8000000000008009ULL,
1485     0x000000000000008aULL,  0x0000000000000088ULL,
1486     0x0000000080008009ULL,  0x000000008000000aULL,
1487     0x000000008000808bULL,  0x800000000000008bULL,
1488     0x8000000000008089ULL,  0x8000000000008003ULL,
1489     0x8000000000008002ULL,  0x8000000000000080ULL,
1490     0x000000000000800aULL,  0x800000008000000aULL,
1491     0x8000000080008081ULL,  0x8000000000008080ULL,
1492     0x0000000080000001ULL,  0x8000000080008008ULL
1493   };
1494 # define a00 (p->u.s[0])
1495 # define a01 (p->u.s[1])
1496 # define a02 (p->u.s[2])
1497 # define a03 (p->u.s[3])
1498 # define a04 (p->u.s[4])
1499 # define a10 (p->u.s[5])
1500 # define a11 (p->u.s[6])
1501 # define a12 (p->u.s[7])
1502 # define a13 (p->u.s[8])
1503 # define a14 (p->u.s[9])
1504 # define a20 (p->u.s[10])
1505 # define a21 (p->u.s[11])
1506 # define a22 (p->u.s[12])
1507 # define a23 (p->u.s[13])
1508 # define a24 (p->u.s[14])
1509 # define a30 (p->u.s[15])
1510 # define a31 (p->u.s[16])
1511 # define a32 (p->u.s[17])
1512 # define a33 (p->u.s[18])
1513 # define a34 (p->u.s[19])
1514 # define a40 (p->u.s[20])
1515 # define a41 (p->u.s[21])
1516 # define a42 (p->u.s[22])
1517 # define a43 (p->u.s[23])
1518 # define a44 (p->u.s[24])
1519 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1520
1521   for(i=0; i<24; i+=4){
1522     c0 = a00^a10^a20^a30^a40;
1523     c1 = a01^a11^a21^a31^a41;
1524     c2 = a02^a12^a22^a32^a42;
1525     c3 = a03^a13^a23^a33^a43;
1526     c4 = a04^a14^a24^a34^a44;
1527     d0 = c4^ROL64(c1, 1);
1528     d1 = c0^ROL64(c2, 1);
1529     d2 = c1^ROL64(c3, 1);
1530     d3 = c2^ROL64(c4, 1);
1531     d4 = c3^ROL64(c0, 1);
1532
1533     b0 = (a00^d0);
1534     b1 = ROL64((a11^d1), 44);
1535     b2 = ROL64((a22^d2), 43);
1536     b3 = ROL64((a33^d3), 21);
1537     b4 = ROL64((a44^d4), 14);
1538     a00 =   b0 ^((~b1)&  b2 );
1539     a00 ^= RC[i];
1540     a11 =   b1 ^((~b2)&  b3 );
1541     a22 =   b2 ^((~b3)&  b4 );
1542     a33 =   b3 ^((~b4)&  b0 );
1543     a44 =   b4 ^((~b0)&  b1 );
1544
1545     b2 = ROL64((a20^d0), 3);
1546     b3 = ROL64((a31^d1), 45);
1547     b4 = ROL64((a42^d2), 61);
1548     b0 = ROL64((a03^d3), 28);
1549     b1 = ROL64((a14^d4), 20);
1550     a20 =   b0 ^((~b1)&  b2 );
1551     a31 =   b1 ^((~b2)&  b3 );
1552     a42 =   b2 ^((~b3)&  b4 );
1553     a03 =   b3 ^((~b4)&  b0 );
1554     a14 =   b4 ^((~b0)&  b1 );
1555
1556     b4 = ROL64((a40^d0), 18);
1557     b0 = ROL64((a01^d1), 1);
1558     b1 = ROL64((a12^d2), 6);
1559     b2 = ROL64((a23^d3), 25);
1560     b3 = ROL64((a34^d4), 8);
1561     a40 =   b0 ^((~b1)&  b2 );
1562     a01 =   b1 ^((~b2)&  b3 );
1563     a12 =   b2 ^((~b3)&  b4 );
1564     a23 =   b3 ^((~b4)&  b0 );
1565     a34 =   b4 ^((~b0)&  b1 );
1566
1567     b1 = ROL64((a10^d0), 36);
1568     b2 = ROL64((a21^d1), 10);
1569     b3 = ROL64((a32^d2), 15);
1570     b4 = ROL64((a43^d3), 56);
1571     b0 = ROL64((a04^d4), 27);
1572     a10 =   b0 ^((~b1)&  b2 );
1573     a21 =   b1 ^((~b2)&  b3 );
1574     a32 =   b2 ^((~b3)&  b4 );
1575     a43 =   b3 ^((~b4)&  b0 );
1576     a04 =   b4 ^((~b0)&  b1 );
1577
1578     b3 = ROL64((a30^d0), 41);
1579     b4 = ROL64((a41^d1), 2);
1580     b0 = ROL64((a02^d2), 62);
1581     b1 = ROL64((a13^d3), 55);
1582     b2 = ROL64((a24^d4), 39);
1583     a30 =   b0 ^((~b1)&  b2 );
1584     a41 =   b1 ^((~b2)&  b3 );
1585     a02 =   b2 ^((~b3)&  b4 );
1586     a13 =   b3 ^((~b4)&  b0 );
1587     a24 =   b4 ^((~b0)&  b1 );
1588
1589     c0 = a00^a20^a40^a10^a30;
1590     c1 = a11^a31^a01^a21^a41;
1591     c2 = a22^a42^a12^a32^a02;
1592     c3 = a33^a03^a23^a43^a13;
1593     c4 = a44^a14^a34^a04^a24;
1594     d0 = c4^ROL64(c1, 1);
1595     d1 = c0^ROL64(c2, 1);
1596     d2 = c1^ROL64(c3, 1);
1597     d3 = c2^ROL64(c4, 1);
1598     d4 = c3^ROL64(c0, 1);
1599
1600     b0 = (a00^d0);
1601     b1 = ROL64((a31^d1), 44);
1602     b2 = ROL64((a12^d2), 43);
1603     b3 = ROL64((a43^d3), 21);
1604     b4 = ROL64((a24^d4), 14);
1605     a00 =   b0 ^((~b1)&  b2 );
1606     a00 ^= RC[i+1];
1607     a31 =   b1 ^((~b2)&  b3 );
1608     a12 =   b2 ^((~b3)&  b4 );
1609     a43 =   b3 ^((~b4)&  b0 );
1610     a24 =   b4 ^((~b0)&  b1 );
1611
1612     b2 = ROL64((a40^d0), 3);
1613     b3 = ROL64((a21^d1), 45);
1614     b4 = ROL64((a02^d2), 61);
1615     b0 = ROL64((a33^d3), 28);
1616     b1 = ROL64((a14^d4), 20);
1617     a40 =   b0 ^((~b1)&  b2 );
1618     a21 =   b1 ^((~b2)&  b3 );
1619     a02 =   b2 ^((~b3)&  b4 );
1620     a33 =   b3 ^((~b4)&  b0 );
1621     a14 =   b4 ^((~b0)&  b1 );
1622
1623     b4 = ROL64((a30^d0), 18);
1624     b0 = ROL64((a11^d1), 1);
1625     b1 = ROL64((a42^d2), 6);
1626     b2 = ROL64((a23^d3), 25);
1627     b3 = ROL64((a04^d4), 8);
1628     a30 =   b0 ^((~b1)&  b2 );
1629     a11 =   b1 ^((~b2)&  b3 );
1630     a42 =   b2 ^((~b3)&  b4 );
1631     a23 =   b3 ^((~b4)&  b0 );
1632     a04 =   b4 ^((~b0)&  b1 );
1633
1634     b1 = ROL64((a20^d0), 36);
1635     b2 = ROL64((a01^d1), 10);
1636     b3 = ROL64((a32^d2), 15);
1637     b4 = ROL64((a13^d3), 56);
1638     b0 = ROL64((a44^d4), 27);
1639     a20 =   b0 ^((~b1)&  b2 );
1640     a01 =   b1 ^((~b2)&  b3 );
1641     a32 =   b2 ^((~b3)&  b4 );
1642     a13 =   b3 ^((~b4)&  b0 );
1643     a44 =   b4 ^((~b0)&  b1 );
1644
1645     b3 = ROL64((a10^d0), 41);
1646     b4 = ROL64((a41^d1), 2);
1647     b0 = ROL64((a22^d2), 62);
1648     b1 = ROL64((a03^d3), 55);
1649     b2 = ROL64((a34^d4), 39);
1650     a10 =   b0 ^((~b1)&  b2 );
1651     a41 =   b1 ^((~b2)&  b3 );
1652     a22 =   b2 ^((~b3)&  b4 );
1653     a03 =   b3 ^((~b4)&  b0 );
1654     a34 =   b4 ^((~b0)&  b1 );
1655
1656     c0 = a00^a40^a30^a20^a10;
1657     c1 = a31^a21^a11^a01^a41;
1658     c2 = a12^a02^a42^a32^a22;
1659     c3 = a43^a33^a23^a13^a03;
1660     c4 = a24^a14^a04^a44^a34;
1661     d0 = c4^ROL64(c1, 1);
1662     d1 = c0^ROL64(c2, 1);
1663     d2 = c1^ROL64(c3, 1);
1664     d3 = c2^ROL64(c4, 1);
1665     d4 = c3^ROL64(c0, 1);
1666
1667     b0 = (a00^d0);
1668     b1 = ROL64((a21^d1), 44);
1669     b2 = ROL64((a42^d2), 43);
1670     b3 = ROL64((a13^d3), 21);
1671     b4 = ROL64((a34^d4), 14);
1672     a00 =   b0 ^((~b1)&  b2 );
1673     a00 ^= RC[i+2];
1674     a21 =   b1 ^((~b2)&  b3 );
1675     a42 =   b2 ^((~b3)&  b4 );
1676     a13 =   b3 ^((~b4)&  b0 );
1677     a34 =   b4 ^((~b0)&  b1 );
1678
1679     b2 = ROL64((a30^d0), 3);
1680     b3 = ROL64((a01^d1), 45);
1681     b4 = ROL64((a22^d2), 61);
1682     b0 = ROL64((a43^d3), 28);
1683     b1 = ROL64((a14^d4), 20);
1684     a30 =   b0 ^((~b1)&  b2 );
1685     a01 =   b1 ^((~b2)&  b3 );
1686     a22 =   b2 ^((~b3)&  b4 );
1687     a43 =   b3 ^((~b4)&  b0 );
1688     a14 =   b4 ^((~b0)&  b1 );
1689
1690     b4 = ROL64((a10^d0), 18);
1691     b0 = ROL64((a31^d1), 1);
1692     b1 = ROL64((a02^d2), 6);
1693     b2 = ROL64((a23^d3), 25);
1694     b3 = ROL64((a44^d4), 8);
1695     a10 =   b0 ^((~b1)&  b2 );
1696     a31 =   b1 ^((~b2)&  b3 );
1697     a02 =   b2 ^((~b3)&  b4 );
1698     a23 =   b3 ^((~b4)&  b0 );
1699     a44 =   b4 ^((~b0)&  b1 );
1700
1701     b1 = ROL64((a40^d0), 36);
1702     b2 = ROL64((a11^d1), 10);
1703     b3 = ROL64((a32^d2), 15);
1704     b4 = ROL64((a03^d3), 56);
1705     b0 = ROL64((a24^d4), 27);
1706     a40 =   b0 ^((~b1)&  b2 );
1707     a11 =   b1 ^((~b2)&  b3 );
1708     a32 =   b2 ^((~b3)&  b4 );
1709     a03 =   b3 ^((~b4)&  b0 );
1710     a24 =   b4 ^((~b0)&  b1 );
1711
1712     b3 = ROL64((a20^d0), 41);
1713     b4 = ROL64((a41^d1), 2);
1714     b0 = ROL64((a12^d2), 62);
1715     b1 = ROL64((a33^d3), 55);
1716     b2 = ROL64((a04^d4), 39);
1717     a20 =   b0 ^((~b1)&  b2 );
1718     a41 =   b1 ^((~b2)&  b3 );
1719     a12 =   b2 ^((~b3)&  b4 );
1720     a33 =   b3 ^((~b4)&  b0 );
1721     a04 =   b4 ^((~b0)&  b1 );
1722
1723     c0 = a00^a30^a10^a40^a20;
1724     c1 = a21^a01^a31^a11^a41;
1725     c2 = a42^a22^a02^a32^a12;
1726     c3 = a13^a43^a23^a03^a33;
1727     c4 = a34^a14^a44^a24^a04;
1728     d0 = c4^ROL64(c1, 1);
1729     d1 = c0^ROL64(c2, 1);
1730     d2 = c1^ROL64(c3, 1);
1731     d3 = c2^ROL64(c4, 1);
1732     d4 = c3^ROL64(c0, 1);
1733
1734     b0 = (a00^d0);
1735     b1 = ROL64((a01^d1), 44);
1736     b2 = ROL64((a02^d2), 43);
1737     b3 = ROL64((a03^d3), 21);
1738     b4 = ROL64((a04^d4), 14);
1739     a00 =   b0 ^((~b1)&  b2 );
1740     a00 ^= RC[i+3];
1741     a01 =   b1 ^((~b2)&  b3 );
1742     a02 =   b2 ^((~b3)&  b4 );
1743     a03 =   b3 ^((~b4)&  b0 );
1744     a04 =   b4 ^((~b0)&  b1 );
1745
1746     b2 = ROL64((a10^d0), 3);
1747     b3 = ROL64((a11^d1), 45);
1748     b4 = ROL64((a12^d2), 61);
1749     b0 = ROL64((a13^d3), 28);
1750     b1 = ROL64((a14^d4), 20);
1751     a10 =   b0 ^((~b1)&  b2 );
1752     a11 =   b1 ^((~b2)&  b3 );
1753     a12 =   b2 ^((~b3)&  b4 );
1754     a13 =   b3 ^((~b4)&  b0 );
1755     a14 =   b4 ^((~b0)&  b1 );
1756
1757     b4 = ROL64((a20^d0), 18);
1758     b0 = ROL64((a21^d1), 1);
1759     b1 = ROL64((a22^d2), 6);
1760     b2 = ROL64((a23^d3), 25);
1761     b3 = ROL64((a24^d4), 8);
1762     a20 =   b0 ^((~b1)&  b2 );
1763     a21 =   b1 ^((~b2)&  b3 );
1764     a22 =   b2 ^((~b3)&  b4 );
1765     a23 =   b3 ^((~b4)&  b0 );
1766     a24 =   b4 ^((~b0)&  b1 );
1767
1768     b1 = ROL64((a30^d0), 36);
1769     b2 = ROL64((a31^d1), 10);
1770     b3 = ROL64((a32^d2), 15);
1771     b4 = ROL64((a33^d3), 56);
1772     b0 = ROL64((a34^d4), 27);
1773     a30 =   b0 ^((~b1)&  b2 );
1774     a31 =   b1 ^((~b2)&  b3 );
1775     a32 =   b2 ^((~b3)&  b4 );
1776     a33 =   b3 ^((~b4)&  b0 );
1777     a34 =   b4 ^((~b0)&  b1 );
1778
1779     b3 = ROL64((a40^d0), 41);
1780     b4 = ROL64((a41^d1), 2);
1781     b0 = ROL64((a42^d2), 62);
1782     b1 = ROL64((a43^d3), 55);
1783     b2 = ROL64((a44^d4), 39);
1784     a40 =   b0 ^((~b1)&  b2 );
1785     a41 =   b1 ^((~b2)&  b3 );
1786     a42 =   b2 ^((~b3)&  b4 );
1787     a43 =   b3 ^((~b4)&  b0 );
1788     a44 =   b4 ^((~b0)&  b1 );
1789   }
1790 }
1791
1792 /*
1793 ** Initialize a new hash.  iSize determines the size of the hash
1794 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1795 ** can be zero to use the default hash size of 256 bits.
1796 */
1797 static void SHA3Init(SHA3Context *p, int iSize){
1798   memset(p, 0, sizeof(*p));
1799   if( iSize>=128 && iSize<=512 ){
1800     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1801   }else{
1802     p->nRate = (1600 - 2*256)/8;
1803   }
1804 #if SHA3_BYTEORDER==1234
1805   /* Known to be little-endian at compile-time. No-op */
1806 #elif SHA3_BYTEORDER==4321
1807   p->ixMask = 7;  /* Big-endian */
1808 #else
1809   {
1810     static unsigned int one = 1;
1811     if( 1==*(unsigned char*)&one ){
1812       /* Little endian.  No byte swapping. */
1813       p->ixMask = 0;
1814     }else{
1815       /* Big endian.  Byte swap. */
1816       p->ixMask = 7;
1817     }
1818   }
1819 #endif
1820 }
1821
1822 /*
1823 ** Make consecutive calls to the SHA3Update function to add new content
1824 ** to the hash
1825 */
1826 static void SHA3Update(
1827   SHA3Context *p,
1828   const unsigned char *aData,
1829   unsigned int nData
1830 ){
1831   unsigned int i = 0;
1832 #if SHA3_BYTEORDER==1234
1833   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1834     for(; i+7<nData; i+=8){
1835       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1836       p->nLoaded += 8;
1837       if( p->nLoaded>=p->nRate ){
1838         KeccakF1600Step(p);
1839         p->nLoaded = 0;
1840       }
1841     }
1842   }
1843 #endif
1844   for(; i<nData; i++){
1845 #if SHA3_BYTEORDER==1234
1846     p->u.x[p->nLoaded] ^= aData[i];
1847 #elif SHA3_BYTEORDER==4321
1848     p->u.x[p->nLoaded^0x07] ^= aData[i];
1849 #else
1850     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1851 #endif
1852     p->nLoaded++;
1853     if( p->nLoaded==p->nRate ){
1854       KeccakF1600Step(p);
1855       p->nLoaded = 0;
1856     }
1857   }
1858 }
1859
1860 /*
1861 ** After all content has been added, invoke SHA3Final() to compute
1862 ** the final hash.  The function returns a pointer to the binary
1863 ** hash value.
1864 */
1865 static unsigned char *SHA3Final(SHA3Context *p){
1866   unsigned int i;
1867   if( p->nLoaded==p->nRate-1 ){
1868     const unsigned char c1 = 0x86;
1869     SHA3Update(p, &c1, 1);
1870   }else{
1871     const unsigned char c2 = 0x06;
1872     const unsigned char c3 = 0x80;
1873     SHA3Update(p, &c2, 1);
1874     p->nLoaded = p->nRate - 1;
1875     SHA3Update(p, &c3, 1);
1876   }
1877   for(i=0; i<p->nRate; i++){
1878     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1879   }
1880   return &p->u.x[p->nRate];
1881 }
1882 /* End of the hashing logic
1883 *****************************************************************************/
1884
1885 /*
1886 ** Implementation of the sha3(X,SIZE) function.
1887 **
1888 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1889 ** size is 256.  If X is a BLOB, it is hashed as is.  
1890 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1891 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1892 ** of a NULL value is NULL.
1893 */
1894 static void sha3Func(
1895   sqlite3_context *context,
1896   int argc,
1897   sqlite3_value **argv
1898 ){
1899   SHA3Context cx;
1900   int eType = sqlite3_value_type(argv[0]);
1901   int nByte = sqlite3_value_bytes(argv[0]);
1902   int iSize;
1903   if( argc==1 ){
1904     iSize = 256;
1905   }else{
1906     iSize = sqlite3_value_int(argv[1]);
1907     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1908       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1909                                     "384 512", -1);
1910       return;
1911     }
1912   }
1913   if( eType==SQLITE_NULL ) return;
1914   SHA3Init(&cx, iSize);
1915   if( eType==SQLITE_BLOB ){
1916     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1917   }else{
1918     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1919   }
1920   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1921 }
1922
1923 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1924 ** of 50 bytes and add it to the hash.
1925 */
1926 static void hash_step_vformat(
1927   SHA3Context *p,                 /* Add content to this context */
1928   const char *zFormat,
1929   ...
1930 ){
1931   va_list ap;
1932   int n;
1933   char zBuf[50];
1934   va_start(ap, zFormat);
1935   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1936   va_end(ap);
1937   n = (int)strlen(zBuf);
1938   SHA3Update(p, (unsigned char*)zBuf, n);
1939 }
1940
1941 /*
1942 ** Implementation of the sha3_query(SQL,SIZE) function.
1943 **
1944 ** This function compiles and runs the SQL statement(s) given in the
1945 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1946 ** size is 256.
1947 **
1948 ** The format of the byte stream that is hashed is summarized as follows:
1949 **
1950 **       S<n>:<sql>
1951 **       R
1952 **       N
1953 **       I<int>
1954 **       F<ieee-float>
1955 **       B<size>:<bytes>
1956 **       T<size>:<text>
1957 **
1958 ** <sql> is the original SQL text for each statement run and <n> is
1959 ** the size of that text.  The SQL text is UTF-8.  A single R character
1960 ** occurs before the start of each row.  N means a NULL value.
1961 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1962 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1963 ** B means blobs of <size> bytes.  T means text rendered as <size>
1964 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1965 ** text integers.
1966 **
1967 ** For each SQL statement in the X input, there is one S segment.  Each
1968 ** S segment is followed by zero or more R segments, one for each row in the
1969 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1970 ** one for each column in the result set.  Segments are concatentated directly
1971 ** with no delimiters of any kind.
1972 */
1973 static void sha3QueryFunc(
1974   sqlite3_context *context,
1975   int argc,
1976   sqlite3_value **argv
1977 ){
1978   sqlite3 *db = sqlite3_context_db_handle(context);
1979   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1980   sqlite3_stmt *pStmt = 0;
1981   int nCol;                   /* Number of columns in the result set */
1982   int i;                      /* Loop counter */
1983   int rc;
1984   int n;
1985   const char *z;
1986   SHA3Context cx;
1987   int iSize;
1988
1989   if( argc==1 ){
1990     iSize = 256;
1991   }else{
1992     iSize = sqlite3_value_int(argv[1]);
1993     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1994       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1995                                     "384 512", -1);
1996       return;
1997     }
1998   }
1999   if( zSql==0 ) return;
2000   SHA3Init(&cx, iSize);
2001   while( zSql[0] ){
2002     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2003     if( rc ){
2004       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2005                                    zSql, sqlite3_errmsg(db));
2006       sqlite3_finalize(pStmt);
2007       sqlite3_result_error(context, zMsg, -1);
2008       sqlite3_free(zMsg);
2009       return;
2010     }
2011     if( !sqlite3_stmt_readonly(pStmt) ){
2012       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2013       sqlite3_finalize(pStmt);
2014       sqlite3_result_error(context, zMsg, -1);
2015       sqlite3_free(zMsg);
2016       return;
2017     }
2018     nCol = sqlite3_column_count(pStmt);
2019     z = sqlite3_sql(pStmt);
2020     if( z ){
2021       n = (int)strlen(z);
2022       hash_step_vformat(&cx,"S%d:",n);
2023       SHA3Update(&cx,(unsigned char*)z,n);
2024     }
2025
2026     /* Compute a hash over the result of the query */
2027     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2028       SHA3Update(&cx,(const unsigned char*)"R",1);
2029       for(i=0; i<nCol; i++){
2030         switch( sqlite3_column_type(pStmt,i) ){
2031           case SQLITE_NULL: {
2032             SHA3Update(&cx, (const unsigned char*)"N",1);
2033             break;
2034           }
2035           case SQLITE_INTEGER: {
2036             sqlite3_uint64 u;
2037             int j;
2038             unsigned char x[9];
2039             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2040             memcpy(&u, &v, 8);
2041             for(j=8; j>=1; j--){
2042               x[j] = u & 0xff;
2043               u >>= 8;
2044             }
2045             x[0] = 'I';
2046             SHA3Update(&cx, x, 9);
2047             break;
2048           }
2049           case SQLITE_FLOAT: {
2050             sqlite3_uint64 u;
2051             int j;
2052             unsigned char x[9];
2053             double r = sqlite3_column_double(pStmt,i);
2054             memcpy(&u, &r, 8);
2055             for(j=8; j>=1; j--){
2056               x[j] = u & 0xff;
2057               u >>= 8;
2058             }
2059             x[0] = 'F';
2060             SHA3Update(&cx,x,9);
2061             break;
2062           }
2063           case SQLITE_TEXT: {
2064             int n2 = sqlite3_column_bytes(pStmt, i);
2065             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2066             hash_step_vformat(&cx,"T%d:",n2);
2067             SHA3Update(&cx, z2, n2);
2068             break;
2069           }
2070           case SQLITE_BLOB: {
2071             int n2 = sqlite3_column_bytes(pStmt, i);
2072             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2073             hash_step_vformat(&cx,"B%d:",n2);
2074             SHA3Update(&cx, z2, n2);
2075             break;
2076           }
2077         }
2078       }
2079     }
2080     sqlite3_finalize(pStmt);
2081   }
2082   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2083 }
2084
2085
2086 #ifdef _WIN32
2087
2088 #endif
2089 int sqlite3_shathree_init(
2090   sqlite3 *db,
2091   char **pzErrMsg,
2092   const sqlite3_api_routines *pApi
2093 ){
2094   int rc = SQLITE_OK;
2095   SQLITE_EXTENSION_INIT2(pApi);
2096   (void)pzErrMsg;  /* Unused parameter */
2097   rc = sqlite3_create_function(db, "sha3", 1,
2098                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2099                       0, sha3Func, 0, 0);
2100   if( rc==SQLITE_OK ){
2101     rc = sqlite3_create_function(db, "sha3", 2,
2102                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2103                       0, sha3Func, 0, 0);
2104   }
2105   if( rc==SQLITE_OK ){
2106     rc = sqlite3_create_function(db, "sha3_query", 1,
2107                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2108                       0, sha3QueryFunc, 0, 0);
2109   }
2110   if( rc==SQLITE_OK ){
2111     rc = sqlite3_create_function(db, "sha3_query", 2,
2112                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2113                       0, sha3QueryFunc, 0, 0);
2114   }
2115   return rc;
2116 }
2117
2118 /************************* End ../ext/misc/shathree.c ********************/
2119 /************************* Begin ../ext/misc/fileio.c ******************/
2120 /*
2121 ** 2014-06-13
2122 **
2123 ** The author disclaims copyright to this source code.  In place of
2124 ** a legal notice, here is a blessing:
2125 **
2126 **    May you do good and not evil.
2127 **    May you find forgiveness for yourself and forgive others.
2128 **    May you share freely, never taking more than you give.
2129 **
2130 ******************************************************************************
2131 **
2132 ** This SQLite extension implements SQL functions readfile() and
2133 ** writefile(), and eponymous virtual type "fsdir".
2134 **
2135 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2136 **
2137 **   If neither of the optional arguments is present, then this UDF
2138 **   function writes blob DATA to file FILE. If successful, the number
2139 **   of bytes written is returned. If an error occurs, NULL is returned.
2140 **
2141 **   If the first option argument - MODE - is present, then it must
2142 **   be passed an integer value that corresponds to a POSIX mode
2143 **   value (file type + permissions, as returned in the stat.st_mode
2144 **   field by the stat() system call). Three types of files may
2145 **   be written/created:
2146 **
2147 **     regular files:  (mode & 0170000)==0100000
2148 **     symbolic links: (mode & 0170000)==0120000
2149 **     directories:    (mode & 0170000)==0040000
2150 **
2151 **   For a directory, the DATA is ignored. For a symbolic link, it is
2152 **   interpreted as text and used as the target of the link. For a
2153 **   regular file, it is interpreted as a blob and written into the
2154 **   named file. Regardless of the type of file, its permissions are
2155 **   set to (mode & 0777) before returning.
2156 **
2157 **   If the optional MTIME argument is present, then it is interpreted
2158 **   as an integer - the number of seconds since the unix epoch. The
2159 **   modification-time of the target file is set to this value before
2160 **   returning.
2161 **
2162 **   If three or more arguments are passed to this function and an
2163 **   error is encountered, an exception is raised.
2164 **
2165 ** READFILE(FILE):
2166 **
2167 **   Read and return the contents of file FILE (type blob) from disk.
2168 **
2169 ** FSDIR:
2170 **
2171 **   Used as follows:
2172 **
2173 **     SELECT * FROM fsdir($path [, $dir]);
2174 **
2175 **   Parameter $path is an absolute or relative pathname. If the file that it
2176 **   refers to does not exist, it is an error. If the path refers to a regular
2177 **   file or symbolic link, it returns a single row. Or, if the path refers
2178 **   to a directory, it returns one row for the directory, and one row for each
2179 **   file within the hierarchy rooted at $path.
2180 **
2181 **   Each row has the following columns:
2182 **
2183 **     name:  Path to file or directory (text value).
2184 **     mode:  Value of stat.st_mode for directory entry (an integer).
2185 **     mtime: Value of stat.st_mtime for directory entry (an integer).
2186 **     data:  For a regular file, a blob containing the file data. For a
2187 **            symlink, a text value containing the text of the link. For a
2188 **            directory, NULL.
2189 **
2190 **   If a non-NULL value is specified for the optional $dir parameter and
2191 **   $path is a relative path, then $path is interpreted relative to $dir. 
2192 **   And the paths returned in the "name" column of the table are also 
2193 **   relative to directory $dir.
2194 */
2195 /* #include "sqlite3ext.h" */
2196 SQLITE_EXTENSION_INIT1
2197 #include <stdio.h>
2198 #include <string.h>
2199 #include <assert.h>
2200
2201 #include <sys/types.h>
2202 #include <sys/stat.h>
2203 #include <fcntl.h>
2204 #if !defined(_WIN32) && !defined(WIN32)
2205 #  include <unistd.h>
2206 #  include <dirent.h>
2207 #  include <utime.h>
2208 #  include <sys/time.h>
2209 #else
2210 #  include "windows.h"
2211 #  include <io.h>
2212 #  include <direct.h>
2213 /* #  include "test_windirent.h" */
2214 #  define dirent DIRENT
2215 #  ifndef chmod
2216 #    define chmod _chmod
2217 #  endif
2218 #  ifndef stat
2219 #    define stat _stat
2220 #  endif
2221 #  define mkdir(path,mode) _mkdir(path)
2222 #  define lstat(path,buf) stat(path,buf)
2223 #endif
2224 #include <time.h>
2225 #include <errno.h>
2226
2227
2228 /*
2229 ** Structure of the fsdir() table-valued function
2230 */
2231                  /*    0    1    2     3    4           5             */
2232 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2233 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
2234 #define FSDIR_COLUMN_MODE     1     /* Access mode */
2235 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
2236 #define FSDIR_COLUMN_DATA     3     /* File content */
2237 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
2238 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
2239
2240
2241 /*
2242 ** Set the result stored by context ctx to a blob containing the 
2243 ** contents of file zName.  Or, leave the result unchanged (NULL)
2244 ** if the file does not exist or is unreadable.
2245 **
2246 ** If the file exceeds the SQLite blob size limit, through an
2247 ** SQLITE_TOOBIG error.
2248 **
2249 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
2250 ** off of disk.
2251 */
2252 static void readFileContents(sqlite3_context *ctx, const char *zName){
2253   FILE *in;
2254   sqlite3_int64 nIn;
2255   void *pBuf;
2256   sqlite3 *db;
2257   int mxBlob;
2258
2259   in = fopen(zName, "rb");
2260   if( in==0 ){
2261     /* File does not exist or is unreadable. Leave the result set to NULL. */
2262     return;
2263   }
2264   fseek(in, 0, SEEK_END);
2265   nIn = ftell(in);
2266   rewind(in);
2267   db = sqlite3_context_db_handle(ctx);
2268   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
2269   if( nIn>mxBlob ){
2270     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
2271     fclose(in);
2272     return;
2273   }
2274   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
2275   if( pBuf==0 ){
2276     sqlite3_result_error_nomem(ctx);
2277     fclose(in);
2278     return;
2279   }
2280   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
2281     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
2282   }else{
2283     sqlite3_result_error_code(ctx, SQLITE_IOERR);
2284     sqlite3_free(pBuf);
2285   }
2286   fclose(in);
2287 }
2288
2289 /*
2290 ** Implementation of the "readfile(X)" SQL function.  The entire content
2291 ** of the file named X is read and returned as a BLOB.  NULL is returned
2292 ** if the file does not exist or is unreadable.
2293 */
2294 static void readfileFunc(
2295   sqlite3_context *context,
2296   int argc,
2297   sqlite3_value **argv
2298 ){
2299   const char *zName;
2300   (void)(argc);  /* Unused parameter */
2301   zName = (const char*)sqlite3_value_text(argv[0]);
2302   if( zName==0 ) return;
2303   readFileContents(context, zName);
2304 }
2305
2306 /*
2307 ** Set the error message contained in context ctx to the results of
2308 ** vprintf(zFmt, ...).
2309 */
2310 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2311   char *zMsg = 0;
2312   va_list ap;
2313   va_start(ap, zFmt);
2314   zMsg = sqlite3_vmprintf(zFmt, ap);
2315   sqlite3_result_error(ctx, zMsg, -1);
2316   sqlite3_free(zMsg);
2317   va_end(ap);
2318 }
2319
2320 #if defined(_WIN32)
2321 /*
2322 ** This function is designed to convert a Win32 FILETIME structure into the
2323 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2324 */
2325 static sqlite3_uint64 fileTimeToUnixTime(
2326   LPFILETIME pFileTime
2327 ){
2328   SYSTEMTIME epochSystemTime;
2329   ULARGE_INTEGER epochIntervals;
2330   FILETIME epochFileTime;
2331   ULARGE_INTEGER fileIntervals;
2332
2333   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2334   epochSystemTime.wYear = 1970;
2335   epochSystemTime.wMonth = 1;
2336   epochSystemTime.wDay = 1;
2337   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2338   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2339   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2340
2341   fileIntervals.LowPart = pFileTime->dwLowDateTime;
2342   fileIntervals.HighPart = pFileTime->dwHighDateTime;
2343
2344   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2345 }
2346
2347 /*
2348 ** This function attempts to normalize the time values found in the stat()
2349 ** buffer to UTC.  This is necessary on Win32, where the runtime library
2350 ** appears to return these values as local times.
2351 */
2352 static void statTimesToUtc(
2353   const char *zPath,
2354   struct stat *pStatBuf
2355 ){
2356   HANDLE hFindFile;
2357   WIN32_FIND_DATAW fd;
2358   LPWSTR zUnicodeName;
2359   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2360   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2361   if( zUnicodeName ){
2362     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
2363     hFindFile = FindFirstFileW(zUnicodeName, &fd);
2364     if( hFindFile!=NULL ){
2365       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2366       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2367       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2368       FindClose(hFindFile);
2369     }
2370     sqlite3_free(zUnicodeName);
2371   }
2372 }
2373 #endif
2374
2375 /*
2376 ** This function is used in place of stat().  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 stat().
2379 */
2380 static int fileStat(
2381   const char *zPath,
2382   struct stat *pStatBuf
2383 ){
2384 #if defined(_WIN32)
2385   int rc = stat(zPath, pStatBuf);
2386   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2387   return rc;
2388 #else
2389   return stat(zPath, pStatBuf);
2390 #endif
2391 }
2392
2393 /*
2394 ** This function is used in place of lstat().  On Windows, special handling
2395 ** is required in order for the included time to be returned as UTC.  On all
2396 ** other systems, this function simply calls lstat().
2397 */
2398 static int fileLinkStat(
2399   const char *zPath,
2400   struct stat *pStatBuf
2401 ){
2402 #if defined(_WIN32)
2403   int rc = lstat(zPath, pStatBuf);
2404   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2405   return rc;
2406 #else
2407   return lstat(zPath, pStatBuf);
2408 #endif
2409 }
2410
2411 /*
2412 ** Argument zFile is the name of a file that will be created and/or written
2413 ** by SQL function writefile(). This function ensures that the directory
2414 ** zFile will be written to exists, creating it if required. The permissions
2415 ** for any path components created by this function are set in accordance
2416 ** with the current umask.
2417 **
2418 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2419 ** SQLITE_OK is returned if the directory is successfully created, or
2420 ** SQLITE_ERROR otherwise.
2421 */
2422 static int makeDirectory(
2423   const char *zFile
2424 ){
2425   char *zCopy = sqlite3_mprintf("%s", zFile);
2426   int rc = SQLITE_OK;
2427
2428   if( zCopy==0 ){
2429     rc = SQLITE_NOMEM;
2430   }else{
2431     int nCopy = (int)strlen(zCopy);
2432     int i = 1;
2433
2434     while( rc==SQLITE_OK ){
2435       struct stat sStat;
2436       int rc2;
2437
2438       for(; zCopy[i]!='/' && i<nCopy; i++);
2439       if( i==nCopy ) break;
2440       zCopy[i] = '\0';
2441
2442       rc2 = fileStat(zCopy, &sStat);
2443       if( rc2!=0 ){
2444         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
2445       }else{
2446         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2447       }
2448       zCopy[i] = '/';
2449       i++;
2450     }
2451
2452     sqlite3_free(zCopy);
2453   }
2454
2455   return rc;
2456 }
2457
2458 /*
2459 ** This function does the work for the writefile() UDF. Refer to 
2460 ** header comments at the top of this file for details.
2461 */
2462 static int writeFile(
2463   sqlite3_context *pCtx,          /* Context to return bytes written in */
2464   const char *zFile,              /* File to write */
2465   sqlite3_value *pData,           /* Data to write */
2466   mode_t mode,                    /* MODE parameter passed to writefile() */
2467   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
2468 ){
2469 #if !defined(_WIN32) && !defined(WIN32)
2470   if( S_ISLNK(mode) ){
2471     const char *zTo = (const char*)sqlite3_value_text(pData);
2472     if( symlink(zTo, zFile)<0 ) return 1;
2473   }else
2474 #endif
2475   {
2476     if( S_ISDIR(mode) ){
2477       if( mkdir(zFile, mode) ){
2478         /* The mkdir() call to create the directory failed. This might not
2479         ** be an error though - if there is already a directory at the same
2480         ** path and either the permissions already match or can be changed
2481         ** to do so using chmod(), it is not an error.  */
2482         struct stat sStat;
2483         if( errno!=EEXIST
2484          || 0!=fileStat(zFile, &sStat)
2485          || !S_ISDIR(sStat.st_mode)
2486          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2487         ){
2488           return 1;
2489         }
2490       }
2491     }else{
2492       sqlite3_int64 nWrite = 0;
2493       const char *z;
2494       int rc = 0;
2495       FILE *out = fopen(zFile, "wb");
2496       if( out==0 ) return 1;
2497       z = (const char*)sqlite3_value_blob(pData);
2498       if( z ){
2499         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2500         nWrite = sqlite3_value_bytes(pData);
2501         if( nWrite!=n ){
2502           rc = 1;
2503         }
2504       }
2505       fclose(out);
2506       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2507         rc = 1;
2508       }
2509       if( rc ) return 2;
2510       sqlite3_result_int64(pCtx, nWrite);
2511     }
2512   }
2513
2514   if( mtime>=0 ){
2515 #if defined(_WIN32)
2516 #if !SQLITE_OS_WINRT
2517     /* Windows */
2518     FILETIME lastAccess;
2519     FILETIME lastWrite;
2520     SYSTEMTIME currentTime;
2521     LONGLONG intervals;
2522     HANDLE hFile;
2523     LPWSTR zUnicodeName;
2524     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2525
2526     GetSystemTime(&currentTime);
2527     SystemTimeToFileTime(&currentTime, &lastAccess);
2528     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2529     lastWrite.dwLowDateTime = (DWORD)intervals;
2530     lastWrite.dwHighDateTime = intervals >> 32;
2531     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2532     if( zUnicodeName==0 ){
2533       return 1;
2534     }
2535     hFile = CreateFileW(
2536       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2537       FILE_FLAG_BACKUP_SEMANTICS, NULL
2538     );
2539     sqlite3_free(zUnicodeName);
2540     if( hFile!=INVALID_HANDLE_VALUE ){
2541       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2542       CloseHandle(hFile);
2543       return !bResult;
2544     }else{
2545       return 1;
2546     }
2547 #endif
2548 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2549     /* Recent unix */
2550     struct timespec times[2];
2551     times[0].tv_nsec = times[1].tv_nsec = 0;
2552     times[0].tv_sec = time(0);
2553     times[1].tv_sec = mtime;
2554     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2555       return 1;
2556     }
2557 #else
2558     /* Legacy unix */
2559     struct timeval times[2];
2560     times[0].tv_usec = times[1].tv_usec = 0;
2561     times[0].tv_sec = time(0);
2562     times[1].tv_sec = mtime;
2563     if( utimes(zFile, times) ){
2564       return 1;
2565     }
2566 #endif
2567   }
2568
2569   return 0;
2570 }
2571
2572 /*
2573 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.  
2574 ** Refer to header comments at the top of this file for details.
2575 */
2576 static void writefileFunc(
2577   sqlite3_context *context,
2578   int argc,
2579   sqlite3_value **argv
2580 ){
2581   const char *zFile;
2582   mode_t mode = 0;
2583   int res;
2584   sqlite3_int64 mtime = -1;
2585
2586   if( argc<2 || argc>4 ){
2587     sqlite3_result_error(context, 
2588         "wrong number of arguments to function writefile()", -1
2589     );
2590     return;
2591   }
2592
2593   zFile = (const char*)sqlite3_value_text(argv[0]);
2594   if( zFile==0 ) return;
2595   if( argc>=3 ){
2596     mode = (mode_t)sqlite3_value_int(argv[2]);
2597   }
2598   if( argc==4 ){
2599     mtime = sqlite3_value_int64(argv[3]);
2600   }
2601
2602   res = writeFile(context, zFile, argv[1], mode, mtime);
2603   if( res==1 && errno==ENOENT ){
2604     if( makeDirectory(zFile)==SQLITE_OK ){
2605       res = writeFile(context, zFile, argv[1], mode, mtime);
2606     }
2607   }
2608
2609   if( argc>2 && res!=0 ){
2610     if( S_ISLNK(mode) ){
2611       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2612     }else if( S_ISDIR(mode) ){
2613       ctxErrorMsg(context, "failed to create directory: %s", zFile);
2614     }else{
2615       ctxErrorMsg(context, "failed to write file: %s", zFile);
2616     }
2617   }
2618 }
2619
2620 /*
2621 ** SQL function:   lsmode(MODE)
2622 **
2623 ** Given a numberic st_mode from stat(), convert it into a human-readable
2624 ** text string in the style of "ls -l".
2625 */
2626 static void lsModeFunc(
2627   sqlite3_context *context,
2628   int argc,
2629   sqlite3_value **argv
2630 ){
2631   int i;
2632   int iMode = sqlite3_value_int(argv[0]);
2633   char z[16];
2634   (void)argc;
2635   if( S_ISLNK(iMode) ){
2636     z[0] = 'l';
2637   }else if( S_ISREG(iMode) ){
2638     z[0] = '-';
2639   }else if( S_ISDIR(iMode) ){
2640     z[0] = 'd';
2641   }else{
2642     z[0] = '?';
2643   }
2644   for(i=0; i<3; i++){
2645     int m = (iMode >> ((2-i)*3));
2646     char *a = &z[1 + i*3];
2647     a[0] = (m & 0x4) ? 'r' : '-';
2648     a[1] = (m & 0x2) ? 'w' : '-';
2649     a[2] = (m & 0x1) ? 'x' : '-';
2650   }
2651   z[10] = '\0';
2652   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2653 }
2654
2655 #ifndef SQLITE_OMIT_VIRTUALTABLE
2656
2657 /* 
2658 ** Cursor type for recursively iterating through a directory structure.
2659 */
2660 typedef struct fsdir_cursor fsdir_cursor;
2661 typedef struct FsdirLevel FsdirLevel;
2662
2663 struct FsdirLevel {
2664   DIR *pDir;                 /* From opendir() */
2665   char *zDir;                /* Name of directory (nul-terminated) */
2666 };
2667
2668 struct fsdir_cursor {
2669   sqlite3_vtab_cursor base;  /* Base class - must be first */
2670
2671   int nLvl;                  /* Number of entries in aLvl[] array */
2672   int iLvl;                  /* Index of current entry */
2673   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
2674
2675   const char *zBase;
2676   int nBase;
2677
2678   struct stat sStat;         /* Current lstat() results */
2679   char *zPath;               /* Path to current entry */
2680   sqlite3_int64 iRowid;      /* Current rowid */
2681 };
2682
2683 typedef struct fsdir_tab fsdir_tab;
2684 struct fsdir_tab {
2685   sqlite3_vtab base;         /* Base class - must be first */
2686 };
2687
2688 /*
2689 ** Construct a new fsdir virtual table object.
2690 */
2691 static int fsdirConnect(
2692   sqlite3 *db,
2693   void *pAux,
2694   int argc, const char *const*argv,
2695   sqlite3_vtab **ppVtab,
2696   char **pzErr
2697 ){
2698   fsdir_tab *pNew = 0;
2699   int rc;
2700   (void)pAux;
2701   (void)argc;
2702   (void)argv;
2703   (void)pzErr;
2704   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2705   if( rc==SQLITE_OK ){
2706     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2707     if( pNew==0 ) return SQLITE_NOMEM;
2708     memset(pNew, 0, sizeof(*pNew));
2709     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
2710   }
2711   *ppVtab = (sqlite3_vtab*)pNew;
2712   return rc;
2713 }
2714
2715 /*
2716 ** This method is the destructor for fsdir vtab objects.
2717 */
2718 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2719   sqlite3_free(pVtab);
2720   return SQLITE_OK;
2721 }
2722
2723 /*
2724 ** Constructor for a new fsdir_cursor object.
2725 */
2726 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2727   fsdir_cursor *pCur;
2728   (void)p;
2729   pCur = sqlite3_malloc( sizeof(*pCur) );
2730   if( pCur==0 ) return SQLITE_NOMEM;
2731   memset(pCur, 0, sizeof(*pCur));
2732   pCur->iLvl = -1;
2733   *ppCursor = &pCur->base;
2734   return SQLITE_OK;
2735 }
2736
2737 /*
2738 ** Reset a cursor back to the state it was in when first returned
2739 ** by fsdirOpen().
2740 */
2741 static void fsdirResetCursor(fsdir_cursor *pCur){
2742   int i;
2743   for(i=0; i<=pCur->iLvl; i++){
2744     FsdirLevel *pLvl = &pCur->aLvl[i];
2745     if( pLvl->pDir ) closedir(pLvl->pDir);
2746     sqlite3_free(pLvl->zDir);
2747   }
2748   sqlite3_free(pCur->zPath);
2749   sqlite3_free(pCur->aLvl);
2750   pCur->aLvl = 0;
2751   pCur->zPath = 0;
2752   pCur->zBase = 0;
2753   pCur->nBase = 0;
2754   pCur->nLvl = 0;
2755   pCur->iLvl = -1;
2756   pCur->iRowid = 1;
2757 }
2758
2759 /*
2760 ** Destructor for an fsdir_cursor.
2761 */
2762 static int fsdirClose(sqlite3_vtab_cursor *cur){
2763   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2764
2765   fsdirResetCursor(pCur);
2766   sqlite3_free(pCur);
2767   return SQLITE_OK;
2768 }
2769
2770 /*
2771 ** Set the error message for the virtual table associated with cursor
2772 ** pCur to the results of vprintf(zFmt, ...).
2773 */
2774 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2775   va_list ap;
2776   va_start(ap, zFmt);
2777   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2778   va_end(ap);
2779 }
2780
2781
2782 /*
2783 ** Advance an fsdir_cursor to its next row of output.
2784 */
2785 static int fsdirNext(sqlite3_vtab_cursor *cur){
2786   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2787   mode_t m = pCur->sStat.st_mode;
2788
2789   pCur->iRowid++;
2790   if( S_ISDIR(m) ){
2791     /* Descend into this directory */
2792     int iNew = pCur->iLvl + 1;
2793     FsdirLevel *pLvl;
2794     if( iNew>=pCur->nLvl ){
2795       int nNew = iNew+1;
2796       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
2797       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
2798       if( aNew==0 ) return SQLITE_NOMEM;
2799       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2800       pCur->aLvl = aNew;
2801       pCur->nLvl = nNew;
2802     }
2803     pCur->iLvl = iNew;
2804     pLvl = &pCur->aLvl[iNew];
2805     
2806     pLvl->zDir = pCur->zPath;
2807     pCur->zPath = 0;
2808     pLvl->pDir = opendir(pLvl->zDir);
2809     if( pLvl->pDir==0 ){
2810       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2811       return SQLITE_ERROR;
2812     }
2813   }
2814
2815   while( pCur->iLvl>=0 ){
2816     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2817     struct dirent *pEntry = readdir(pLvl->pDir);
2818     if( pEntry ){
2819       if( pEntry->d_name[0]=='.' ){
2820        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2821        if( pEntry->d_name[1]=='\0' ) continue;
2822       }
2823       sqlite3_free(pCur->zPath);
2824       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2825       if( pCur->zPath==0 ) return SQLITE_NOMEM;
2826       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2827         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2828         return SQLITE_ERROR;
2829       }
2830       return SQLITE_OK;
2831     }
2832     closedir(pLvl->pDir);
2833     sqlite3_free(pLvl->zDir);
2834     pLvl->pDir = 0;
2835     pLvl->zDir = 0;
2836     pCur->iLvl--;
2837   }
2838
2839   /* EOF */
2840   sqlite3_free(pCur->zPath);
2841   pCur->zPath = 0;
2842   return SQLITE_OK;
2843 }
2844
2845 /*
2846 ** Return values of columns for the row at which the series_cursor
2847 ** is currently pointing.
2848 */
2849 static int fsdirColumn(
2850   sqlite3_vtab_cursor *cur,   /* The cursor */
2851   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2852   int i                       /* Which column to return */
2853 ){
2854   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2855   switch( i ){
2856     case FSDIR_COLUMN_NAME: {
2857       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2858       break;
2859     }
2860
2861     case FSDIR_COLUMN_MODE:
2862       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2863       break;
2864
2865     case FSDIR_COLUMN_MTIME:
2866       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2867       break;
2868
2869     case FSDIR_COLUMN_DATA: {
2870       mode_t m = pCur->sStat.st_mode;
2871       if( S_ISDIR(m) ){
2872         sqlite3_result_null(ctx);
2873 #if !defined(_WIN32) && !defined(WIN32)
2874       }else if( S_ISLNK(m) ){
2875         char aStatic[64];
2876         char *aBuf = aStatic;
2877         sqlite3_int64 nBuf = 64;
2878         int n;
2879
2880         while( 1 ){
2881           n = readlink(pCur->zPath, aBuf, nBuf);
2882           if( n<nBuf ) break;
2883           if( aBuf!=aStatic ) sqlite3_free(aBuf);
2884           nBuf = nBuf*2;
2885           aBuf = sqlite3_malloc64(nBuf);
2886           if( aBuf==0 ){
2887             sqlite3_result_error_nomem(ctx);
2888             return SQLITE_NOMEM;
2889           }
2890         }
2891
2892         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2893         if( aBuf!=aStatic ) sqlite3_free(aBuf);
2894 #endif
2895       }else{
2896         readFileContents(ctx, pCur->zPath);
2897       }
2898     }
2899     case FSDIR_COLUMN_PATH:
2900     default: {
2901       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
2902       ** always return their values as NULL */
2903       break;
2904     }
2905   }
2906   return SQLITE_OK;
2907 }
2908
2909 /*
2910 ** Return the rowid for the current row. In this implementation, the
2911 ** first row returned is assigned rowid value 1, and each subsequent
2912 ** row a value 1 more than that of the previous.
2913 */
2914 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2915   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2916   *pRowid = pCur->iRowid;
2917   return SQLITE_OK;
2918 }
2919
2920 /*
2921 ** Return TRUE if the cursor has been moved off of the last
2922 ** row of output.
2923 */
2924 static int fsdirEof(sqlite3_vtab_cursor *cur){
2925   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2926   return (pCur->zPath==0);
2927 }
2928
2929 /*
2930 ** xFilter callback.
2931 **
2932 ** idxNum==1   PATH parameter only
2933 ** idxNum==2   Both PATH and DIR supplied
2934 */
2935 static int fsdirFilter(
2936   sqlite3_vtab_cursor *cur, 
2937   int idxNum, const char *idxStr,
2938   int argc, sqlite3_value **argv
2939 ){
2940   const char *zDir = 0;
2941   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2942   (void)idxStr;
2943   fsdirResetCursor(pCur);
2944
2945   if( idxNum==0 ){
2946     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2947     return SQLITE_ERROR;
2948   }
2949
2950   assert( argc==idxNum && (argc==1 || argc==2) );
2951   zDir = (const char*)sqlite3_value_text(argv[0]);
2952   if( zDir==0 ){
2953     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2954     return SQLITE_ERROR;
2955   }
2956   if( argc==2 ){
2957     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2958   }
2959   if( pCur->zBase ){
2960     pCur->nBase = (int)strlen(pCur->zBase)+1;
2961     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2962   }else{
2963     pCur->zPath = sqlite3_mprintf("%s", zDir);
2964   }
2965
2966   if( pCur->zPath==0 ){
2967     return SQLITE_NOMEM;
2968   }
2969   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2970     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2971     return SQLITE_ERROR;
2972   }
2973
2974   return SQLITE_OK;
2975 }
2976
2977 /*
2978 ** SQLite will invoke this method one or more times while planning a query
2979 ** that uses the generate_series virtual table.  This routine needs to create
2980 ** a query plan for each invocation and compute an estimated cost for that
2981 ** plan.
2982 **
2983 ** In this implementation idxNum is used to represent the
2984 ** query plan.  idxStr is unused.
2985 **
2986 ** The query plan is represented by values of idxNum:
2987 **
2988 **  (1)  The path value is supplied by argv[0]
2989 **  (2)  Path is in argv[0] and dir is in argv[1]
2990 */
2991 static int fsdirBestIndex(
2992   sqlite3_vtab *tab,
2993   sqlite3_index_info *pIdxInfo
2994 ){
2995   int i;                 /* Loop over constraints */
2996   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
2997   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
2998   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
2999   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
3000   const struct sqlite3_index_constraint *pConstraint;
3001
3002   (void)tab;
3003   pConstraint = pIdxInfo->aConstraint;
3004   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3005     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3006     switch( pConstraint->iColumn ){
3007       case FSDIR_COLUMN_PATH: {
3008         if( pConstraint->usable ){
3009           idxPath = i;
3010           seenPath = 0;
3011         }else if( idxPath<0 ){
3012           seenPath = 1;
3013         }
3014         break;
3015       }
3016       case FSDIR_COLUMN_DIR: {
3017         if( pConstraint->usable ){
3018           idxDir = i;
3019           seenDir = 0;
3020         }else if( idxDir<0 ){
3021           seenDir = 1;
3022         }
3023         break;
3024       }
3025     } 
3026   }
3027   if( seenPath || seenDir ){
3028     /* If input parameters are unusable, disallow this plan */
3029     return SQLITE_CONSTRAINT;
3030   }
3031
3032   if( idxPath<0 ){
3033     pIdxInfo->idxNum = 0;
3034     /* The pIdxInfo->estimatedCost should have been initialized to a huge
3035     ** number.  Leave it unchanged. */
3036     pIdxInfo->estimatedRows = 0x7fffffff;
3037   }else{
3038     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
3039     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
3040     if( idxDir>=0 ){
3041       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
3042       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
3043       pIdxInfo->idxNum = 2;
3044       pIdxInfo->estimatedCost = 10.0;
3045     }else{
3046       pIdxInfo->idxNum = 1;
3047       pIdxInfo->estimatedCost = 100.0;
3048     }
3049   }
3050
3051   return SQLITE_OK;
3052 }
3053
3054 /*
3055 ** Register the "fsdir" virtual table.
3056 */
3057 static int fsdirRegister(sqlite3 *db){
3058   static sqlite3_module fsdirModule = {
3059     0,                         /* iVersion */
3060     0,                         /* xCreate */
3061     fsdirConnect,              /* xConnect */
3062     fsdirBestIndex,            /* xBestIndex */
3063     fsdirDisconnect,           /* xDisconnect */
3064     0,                         /* xDestroy */
3065     fsdirOpen,                 /* xOpen - open a cursor */
3066     fsdirClose,                /* xClose - close a cursor */
3067     fsdirFilter,               /* xFilter - configure scan constraints */
3068     fsdirNext,                 /* xNext - advance a cursor */
3069     fsdirEof,                  /* xEof - check for end of scan */
3070     fsdirColumn,               /* xColumn - read data */
3071     fsdirRowid,                /* xRowid - read data */
3072     0,                         /* xUpdate */
3073     0,                         /* xBegin */
3074     0,                         /* xSync */
3075     0,                         /* xCommit */
3076     0,                         /* xRollback */
3077     0,                         /* xFindMethod */
3078     0,                         /* xRename */
3079     0,                         /* xSavepoint */
3080     0,                         /* xRelease */
3081     0,                         /* xRollbackTo */
3082     0,                         /* xShadowName */
3083   };
3084
3085   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
3086   return rc;
3087 }
3088 #else         /* SQLITE_OMIT_VIRTUALTABLE */
3089 # define fsdirRegister(x) SQLITE_OK
3090 #endif
3091
3092 #ifdef _WIN32
3093
3094 #endif
3095 int sqlite3_fileio_init(
3096   sqlite3 *db, 
3097   char **pzErrMsg, 
3098   const sqlite3_api_routines *pApi
3099 ){
3100   int rc = SQLITE_OK;
3101   SQLITE_EXTENSION_INIT2(pApi);
3102   (void)pzErrMsg;  /* Unused parameter */
3103   rc = sqlite3_create_function(db, "readfile", 1, 
3104                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3105                                readfileFunc, 0, 0);
3106   if( rc==SQLITE_OK ){
3107     rc = sqlite3_create_function(db, "writefile", -1,
3108                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3109                                  writefileFunc, 0, 0);
3110   }
3111   if( rc==SQLITE_OK ){
3112     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
3113                                  lsModeFunc, 0, 0);
3114   }
3115   if( rc==SQLITE_OK ){
3116     rc = fsdirRegister(db);
3117   }
3118   return rc;
3119 }
3120
3121 /************************* End ../ext/misc/fileio.c ********************/
3122 /************************* Begin ../ext/misc/completion.c ******************/
3123 /*
3124 ** 2017-07-10
3125 **
3126 ** The author disclaims copyright to this source code.  In place of
3127 ** a legal notice, here is a blessing:
3128 **
3129 **    May you do good and not evil.
3130 **    May you find forgiveness for yourself and forgive others.
3131 **    May you share freely, never taking more than you give.
3132 **
3133 *************************************************************************
3134 **
3135 ** This file implements an eponymous virtual table that returns suggested
3136 ** completions for a partial SQL input.
3137 **
3138 ** Suggested usage:
3139 **
3140 **     SELECT DISTINCT candidate COLLATE nocase
3141 **       FROM completion($prefix,$wholeline)
3142 **      ORDER BY 1;
3143 **
3144 ** The two query parameters are optional.  $prefix is the text of the
3145 ** current word being typed and that is to be completed.  $wholeline is
3146 ** the complete input line, used for context.
3147 **
3148 ** The raw completion() table might return the same candidate multiple
3149 ** times, for example if the same column name is used to two or more
3150 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
3151 ** the DISTINCT and ORDER BY are recommended.
3152 **
3153 ** This virtual table operates at the speed of human typing, and so there
3154 ** is no attempt to make it fast.  Even a slow implementation will be much
3155 ** faster than any human can type.
3156 **
3157 */
3158 /* #include "sqlite3ext.h" */
3159 SQLITE_EXTENSION_INIT1
3160 #include <assert.h>
3161 #include <string.h>
3162 #include <ctype.h>
3163
3164 #ifndef SQLITE_OMIT_VIRTUALTABLE
3165
3166 /* completion_vtab is a subclass of sqlite3_vtab which will
3167 ** serve as the underlying representation of a completion virtual table
3168 */
3169 typedef struct completion_vtab completion_vtab;
3170 struct completion_vtab {
3171   sqlite3_vtab base;  /* Base class - must be first */
3172   sqlite3 *db;        /* Database connection for this completion vtab */
3173 };
3174
3175 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3176 ** serve as the underlying representation of a cursor that scans
3177 ** over rows of the result
3178 */
3179 typedef struct completion_cursor completion_cursor;
3180 struct completion_cursor {
3181   sqlite3_vtab_cursor base;  /* Base class - must be first */
3182   sqlite3 *db;               /* Database connection for this cursor */
3183   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
3184   char *zPrefix;             /* The prefix for the word we want to complete */
3185   char *zLine;               /* The whole that we want to complete */
3186   const char *zCurrentRow;   /* Current output row */
3187   int szRow;                 /* Length of the zCurrentRow string */
3188   sqlite3_stmt *pStmt;       /* Current statement */
3189   sqlite3_int64 iRowid;      /* The rowid */
3190   int ePhase;                /* Current phase */
3191   int j;                     /* inter-phase counter */
3192 };
3193
3194 /* Values for ePhase:
3195 */
3196 #define COMPLETION_FIRST_PHASE   1
3197 #define COMPLETION_KEYWORDS      1
3198 #define COMPLETION_PRAGMAS       2
3199 #define COMPLETION_FUNCTIONS     3
3200 #define COMPLETION_COLLATIONS    4
3201 #define COMPLETION_INDEXES       5
3202 #define COMPLETION_TRIGGERS      6
3203 #define COMPLETION_DATABASES     7
3204 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
3205 #define COMPLETION_COLUMNS       9
3206 #define COMPLETION_MODULES       10
3207 #define COMPLETION_EOF           11
3208
3209 /*
3210 ** The completionConnect() method is invoked to create a new
3211 ** completion_vtab that describes the completion virtual table.
3212 **
3213 ** Think of this routine as the constructor for completion_vtab objects.
3214 **
3215 ** All this routine needs to do is:
3216 **
3217 **    (1) Allocate the completion_vtab object and initialize all fields.
3218 **
3219 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3220 **        result set of queries against completion will look like.
3221 */
3222 static int completionConnect(
3223   sqlite3 *db,
3224   void *pAux,
3225   int argc, const char *const*argv,
3226   sqlite3_vtab **ppVtab,
3227   char **pzErr
3228 ){
3229   completion_vtab *pNew;
3230   int rc;
3231
3232   (void)(pAux);    /* Unused parameter */
3233   (void)(argc);    /* Unused parameter */
3234   (void)(argv);    /* Unused parameter */
3235   (void)(pzErr);   /* Unused parameter */
3236
3237 /* Column numbers */
3238 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
3239 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
3240 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
3241 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
3242
3243   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
3244   rc = sqlite3_declare_vtab(db,
3245       "CREATE TABLE x("
3246       "  candidate TEXT,"
3247       "  prefix TEXT HIDDEN,"
3248       "  wholeline TEXT HIDDEN,"
3249       "  phase INT HIDDEN"        /* Used for debugging only */
3250       ")");
3251   if( rc==SQLITE_OK ){
3252     pNew = sqlite3_malloc( sizeof(*pNew) );
3253     *ppVtab = (sqlite3_vtab*)pNew;
3254     if( pNew==0 ) return SQLITE_NOMEM;
3255     memset(pNew, 0, sizeof(*pNew));
3256     pNew->db = db;
3257   }
3258   return rc;
3259 }
3260
3261 /*
3262 ** This method is the destructor for completion_cursor objects.
3263 */
3264 static int completionDisconnect(sqlite3_vtab *pVtab){
3265   sqlite3_free(pVtab);
3266   return SQLITE_OK;
3267 }
3268
3269 /*
3270 ** Constructor for a new completion_cursor object.
3271 */
3272 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3273   completion_cursor *pCur;
3274   pCur = sqlite3_malloc( sizeof(*pCur) );
3275   if( pCur==0 ) return SQLITE_NOMEM;
3276   memset(pCur, 0, sizeof(*pCur));
3277   pCur->db = ((completion_vtab*)p)->db;
3278   *ppCursor = &pCur->base;
3279   return SQLITE_OK;
3280 }
3281
3282 /*
3283 ** Reset the completion_cursor.
3284 */
3285 static void completionCursorReset(completion_cursor *pCur){
3286   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
3287   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
3288   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3289   pCur->j = 0;
3290 }
3291
3292 /*
3293 ** Destructor for a completion_cursor.
3294 */
3295 static int completionClose(sqlite3_vtab_cursor *cur){
3296   completionCursorReset((completion_cursor*)cur);
3297   sqlite3_free(cur);
3298   return SQLITE_OK;
3299 }
3300
3301 /*
3302 ** Advance a completion_cursor to its next row of output.
3303 **
3304 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3305 ** record the current state of the scan.  This routine sets ->zCurrentRow
3306 ** to the current row of output and then returns.  If no more rows remain,
3307 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3308 ** table that has reached the end of its scan.
3309 **
3310 ** The current implementation just lists potential identifiers and
3311 ** keywords and filters them by zPrefix.  Future enhancements should
3312 ** take zLine into account to try to restrict the set of identifiers and
3313 ** keywords based on what would be legal at the current point of input.
3314 */
3315 static int completionNext(sqlite3_vtab_cursor *cur){
3316   completion_cursor *pCur = (completion_cursor*)cur;
3317   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
3318   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
3319   pCur->iRowid++;
3320   while( pCur->ePhase!=COMPLETION_EOF ){
3321     switch( pCur->ePhase ){
3322       case COMPLETION_KEYWORDS: {
3323         if( pCur->j >= sqlite3_keyword_count() ){
3324           pCur->zCurrentRow = 0;
3325           pCur->ePhase = COMPLETION_DATABASES;
3326         }else{
3327           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
3328         }
3329         iCol = -1;
3330         break;
3331       }
3332       case COMPLETION_DATABASES: {
3333         if( pCur->pStmt==0 ){
3334           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3335                              &pCur->pStmt, 0);
3336         }
3337         iCol = 1;
3338         eNextPhase = COMPLETION_TABLES;
3339         break;
3340       }
3341       case COMPLETION_TABLES: {
3342         if( pCur->pStmt==0 ){
3343           sqlite3_stmt *pS2;
3344           char *zSql = 0;
3345           const char *zSep = "";
3346           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3347           while( sqlite3_step(pS2)==SQLITE_ROW ){
3348             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3349             zSql = sqlite3_mprintf(
3350                "%z%s"
3351                "SELECT name FROM \"%w\".sqlite_schema",
3352                zSql, zSep, zDb
3353             );
3354             if( zSql==0 ) return SQLITE_NOMEM;
3355             zSep = " UNION ";
3356           }
3357           sqlite3_finalize(pS2);
3358           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3359           sqlite3_free(zSql);
3360         }
3361         iCol = 0;
3362         eNextPhase = COMPLETION_COLUMNS;
3363         break;
3364       }
3365       case COMPLETION_COLUMNS: {
3366         if( pCur->pStmt==0 ){
3367           sqlite3_stmt *pS2;
3368           char *zSql = 0;
3369           const char *zSep = "";
3370           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3371           while( sqlite3_step(pS2)==SQLITE_ROW ){
3372             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3373             zSql = sqlite3_mprintf(
3374                "%z%s"
3375                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
3376                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
3377                " WHERE sm.type='table'",
3378                zSql, zSep, zDb, zDb
3379             );
3380             if( zSql==0 ) return SQLITE_NOMEM;
3381             zSep = " UNION ";
3382           }
3383           sqlite3_finalize(pS2);
3384           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3385           sqlite3_free(zSql);
3386         }
3387         iCol = 0;
3388         eNextPhase = COMPLETION_EOF;
3389         break;
3390       }
3391     }
3392     if( iCol<0 ){
3393       /* This case is when the phase presets zCurrentRow */
3394       if( pCur->zCurrentRow==0 ) continue;
3395     }else{
3396       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3397         /* Extract the next row of content */
3398         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3399         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
3400       }else{
3401         /* When all rows are finished, advance to the next phase */
3402         sqlite3_finalize(pCur->pStmt);
3403         pCur->pStmt = 0;
3404         pCur->ePhase = eNextPhase;
3405         continue;
3406       }
3407     }
3408     if( pCur->nPrefix==0 ) break;
3409     if( pCur->nPrefix<=pCur->szRow
3410      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
3411     ){
3412       break;
3413     }
3414   }
3415
3416   return SQLITE_OK;
3417 }
3418
3419 /*
3420 ** Return values of columns for the row at which the completion_cursor
3421 ** is currently pointing.
3422 */
3423 static int completionColumn(
3424   sqlite3_vtab_cursor *cur,   /* The cursor */
3425   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3426   int i                       /* Which column to return */
3427 ){
3428   completion_cursor *pCur = (completion_cursor*)cur;
3429   switch( i ){
3430     case COMPLETION_COLUMN_CANDIDATE: {
3431       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
3432       break;
3433     }
3434     case COMPLETION_COLUMN_PREFIX: {
3435       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3436       break;
3437     }
3438     case COMPLETION_COLUMN_WHOLELINE: {
3439       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3440       break;
3441     }
3442     case COMPLETION_COLUMN_PHASE: {
3443       sqlite3_result_int(ctx, pCur->ePhase);
3444       break;
3445     }
3446   }
3447   return SQLITE_OK;
3448 }
3449
3450 /*
3451 ** Return the rowid for the current row.  In this implementation, the
3452 ** rowid is the same as the output value.
3453 */
3454 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3455   completion_cursor *pCur = (completion_cursor*)cur;
3456   *pRowid = pCur->iRowid;
3457   return SQLITE_OK;
3458 }
3459
3460 /*
3461 ** Return TRUE if the cursor has been moved off of the last
3462 ** row of output.
3463 */
3464 static int completionEof(sqlite3_vtab_cursor *cur){
3465   completion_cursor *pCur = (completion_cursor*)cur;
3466   return pCur->ePhase >= COMPLETION_EOF;
3467 }
3468
3469 /*
3470 ** This method is called to "rewind" the completion_cursor object back
3471 ** to the first row of output.  This method is always called at least
3472 ** once prior to any call to completionColumn() or completionRowid() or 
3473 ** completionEof().
3474 */
3475 static int completionFilter(
3476   sqlite3_vtab_cursor *pVtabCursor, 
3477   int idxNum, const char *idxStr,
3478   int argc, sqlite3_value **argv
3479 ){
3480   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3481   int iArg = 0;
3482   (void)(idxStr);   /* Unused parameter */
3483   (void)(argc);     /* Unused parameter */
3484   completionCursorReset(pCur);
3485   if( idxNum & 1 ){
3486     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3487     if( pCur->nPrefix>0 ){
3488       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3489       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3490     }
3491     iArg = 1;
3492   }
3493   if( idxNum & 2 ){
3494     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3495     if( pCur->nLine>0 ){
3496       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3497       if( pCur->zLine==0 ) return SQLITE_NOMEM;
3498     }
3499   }
3500   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3501     int i = pCur->nLine;
3502     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3503       i--;
3504     }
3505     pCur->nPrefix = pCur->nLine - i;
3506     if( pCur->nPrefix>0 ){
3507       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3508       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3509     }
3510   }
3511   pCur->iRowid = 0;
3512   pCur->ePhase = COMPLETION_FIRST_PHASE;
3513   return completionNext(pVtabCursor);
3514 }
3515
3516 /*
3517 ** SQLite will invoke this method one or more times while planning a query
3518 ** that uses the completion virtual table.  This routine needs to create
3519 ** a query plan for each invocation and compute an estimated cost for that
3520 ** plan.
3521 **
3522 ** There are two hidden parameters that act as arguments to the table-valued
3523 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
3524 ** is available and bit 1 is set if "wholeline" is available.
3525 */
3526 static int completionBestIndex(
3527   sqlite3_vtab *tab,
3528   sqlite3_index_info *pIdxInfo
3529 ){
3530   int i;                 /* Loop over constraints */
3531   int idxNum = 0;        /* The query plan bitmask */
3532   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
3533   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3534   int nArg = 0;          /* Number of arguments that completeFilter() expects */
3535   const struct sqlite3_index_constraint *pConstraint;
3536
3537   (void)(tab);    /* Unused parameter */
3538   pConstraint = pIdxInfo->aConstraint;
3539   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3540     if( pConstraint->usable==0 ) continue;
3541     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3542     switch( pConstraint->iColumn ){
3543       case COMPLETION_COLUMN_PREFIX:
3544         prefixIdx = i;
3545         idxNum |= 1;
3546         break;
3547       case COMPLETION_COLUMN_WHOLELINE:
3548         wholelineIdx = i;
3549         idxNum |= 2;
3550         break;
3551     }
3552   }
3553   if( prefixIdx>=0 ){
3554     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3555     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3556   }
3557   if( wholelineIdx>=0 ){
3558     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3559     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3560   }
3561   pIdxInfo->idxNum = idxNum;
3562   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3563   pIdxInfo->estimatedRows = 500 - 100*nArg;
3564   return SQLITE_OK;
3565 }
3566
3567 /*
3568 ** This following structure defines all the methods for the 
3569 ** completion virtual table.
3570 */
3571 static sqlite3_module completionModule = {
3572   0,                         /* iVersion */
3573   0,                         /* xCreate */
3574   completionConnect,         /* xConnect */
3575   completionBestIndex,       /* xBestIndex */
3576   completionDisconnect,      /* xDisconnect */
3577   0,                         /* xDestroy */
3578   completionOpen,            /* xOpen - open a cursor */
3579   completionClose,           /* xClose - close a cursor */
3580   completionFilter,          /* xFilter - configure scan constraints */
3581   completionNext,            /* xNext - advance a cursor */
3582   completionEof,             /* xEof - check for end of scan */
3583   completionColumn,          /* xColumn - read data */
3584   completionRowid,           /* xRowid - read data */
3585   0,                         /* xUpdate */
3586   0,                         /* xBegin */
3587   0,                         /* xSync */
3588   0,                         /* xCommit */
3589   0,                         /* xRollback */
3590   0,                         /* xFindMethod */
3591   0,                         /* xRename */
3592   0,                         /* xSavepoint */
3593   0,                         /* xRelease */
3594   0,                         /* xRollbackTo */
3595   0                          /* xShadowName */
3596 };
3597
3598 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3599
3600 int sqlite3CompletionVtabInit(sqlite3 *db){
3601   int rc = SQLITE_OK;
3602 #ifndef SQLITE_OMIT_VIRTUALTABLE
3603   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3604 #endif
3605   return rc;
3606 }
3607
3608 #ifdef _WIN32
3609
3610 #endif
3611 int sqlite3_completion_init(
3612   sqlite3 *db, 
3613   char **pzErrMsg, 
3614   const sqlite3_api_routines *pApi
3615 ){
3616   int rc = SQLITE_OK;
3617   SQLITE_EXTENSION_INIT2(pApi);
3618   (void)(pzErrMsg);  /* Unused parameter */
3619 #ifndef SQLITE_OMIT_VIRTUALTABLE
3620   rc = sqlite3CompletionVtabInit(db);
3621 #endif
3622   return rc;
3623 }
3624
3625 /************************* End ../ext/misc/completion.c ********************/
3626 /************************* Begin ../ext/misc/appendvfs.c ******************/
3627 /*
3628 ** 2017-10-20
3629 **
3630 ** The author disclaims copyright to this source code.  In place of
3631 ** a legal notice, here is a blessing:
3632 **
3633 **    May you do good and not evil.
3634 **    May you find forgiveness for yourself and forgive others.
3635 **    May you share freely, never taking more than you give.
3636 **
3637 ******************************************************************************
3638 **
3639 ** This file implements a VFS shim that allows an SQLite database to be
3640 ** appended onto the end of some other file, such as an executable.
3641 **
3642 ** A special record must appear at the end of the file that identifies the
3643 ** file as an appended database and provides the offset to the first page
3644 ** of the exposed content. (Or, it is the length of the content prefix.)
3645 ** For best performance page 1 should be located at a disk page boundary,
3646 ** though that is not required.
3647 **
3648 ** When opening a database using this VFS, the connection might treat
3649 ** the file as an ordinary SQLite database, or it might treat it as a
3650 ** database appended onto some other file.  The decision is made by
3651 ** applying the following rules in order:
3652 **
3653 **  (1)  An empty file is an ordinary database.
3654 **
3655 **  (2)  If the file ends with the appendvfs trailer string
3656 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
3657 **
3658 **  (3)  If the file begins with the standard SQLite prefix string
3659 **       "SQLite format 3", that file is an ordinary database.
3660 **
3661 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
3662 **       set, then a new database is appended to the already existing file.
3663 **
3664 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
3665 **
3666 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3667 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
3668 ** This VFS will not read or write past the 1GiB mark.  This restriction
3669 ** might be lifted in future versions.  For now, if you need a larger
3670 ** database, then keep it in a separate file.
3671 **
3672 ** If the file being opened is a plain database (not an appended one), then
3673 ** this shim is a pass-through into the default underlying VFS. (rule 3)
3674 **/
3675 /* #include "sqlite3ext.h" */
3676 SQLITE_EXTENSION_INIT1
3677 #include <string.h>
3678 #include <assert.h>
3679
3680 /* The append mark at the end of the database is:
3681 **
3682 **     Start-Of-SQLite3-NNNNNNNN
3683 **     123456789 123456789 12345
3684 **
3685 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3686 ** the offset to page 1, and also the length of the prefix content.
3687 */
3688 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
3689 #define APND_MARK_PREFIX_SZ  17
3690 #define APND_MARK_FOS_SZ      8
3691 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
3692
3693 /*
3694 ** Maximum size of the combined prefix + database + append-mark.  This
3695 ** must be less than 0x40000000 to avoid locking issues on Windows.
3696 */
3697 #define APND_MAX_SIZE  (0x40000000)
3698
3699 /*
3700 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
3701 */
3702 #ifndef APND_ROUNDUP
3703 #define APND_ROUNDUP 4096
3704 #endif
3705 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
3706 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
3707
3708 /*
3709 ** Forward declaration of objects used by this utility
3710 */
3711 typedef struct sqlite3_vfs ApndVfs;
3712 typedef struct ApndFile ApndFile;
3713
3714 /* Access to a lower-level VFS that (might) implement dynamic loading,
3715 ** access to randomness, etc.
3716 */
3717 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
3718 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3719
3720 /* An open appendvfs file
3721 **
3722 ** An instance of this structure describes the appended database file.
3723 ** A separate sqlite3_file object is always appended. The appended
3724 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
3725 ** the entire file, including the prefix, the database, and the
3726 ** append-mark.
3727 **
3728 ** The structure of an AppendVFS database is like this:
3729 **
3730 **   +-------------+---------+----------+-------------+
3731 **   | prefix-file | padding | database | append-mark |
3732 **   +-------------+---------+----------+-------------+
3733 **                           ^          ^
3734 **                           |          |
3735 **                         iPgOne      iMark
3736 **
3737 **
3738 ** "prefix file" -  file onto which the database has been appended.
3739 ** "padding"     -  zero or more bytes inserted so that "database"
3740 **                  starts on an APND_ROUNDUP boundary
3741 ** "database"    -  The SQLite database file
3742 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
3743 **                  the offset from the start of prefix-file to the start
3744 **                  of "database".
3745 **
3746 ** The size of the database is iMark - iPgOne.
3747 **
3748 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
3749 ** of iPgOne stored as a big-ending 64-bit integer.
3750 **
3751 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
3752 ** Or, iMark is -1 to indicate that it has not yet been written.
3753 */
3754 struct ApndFile {
3755   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
3756   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
3757   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
3758   /* Always followed by another sqlite3_file that describes the whole file */
3759 };
3760
3761 /*
3762 ** Methods for ApndFile
3763 */
3764 static int apndClose(sqlite3_file*);
3765 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3766 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3767 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3768 static int apndSync(sqlite3_file*, int flags);
3769 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3770 static int apndLock(sqlite3_file*, int);
3771 static int apndUnlock(sqlite3_file*, int);
3772 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3773 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3774 static int apndSectorSize(sqlite3_file*);
3775 static int apndDeviceCharacteristics(sqlite3_file*);
3776 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3777 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3778 static void apndShmBarrier(sqlite3_file*);
3779 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3780 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3781 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3782
3783 /*
3784 ** Methods for ApndVfs
3785 */
3786 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3787 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3788 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3789 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3790 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3791 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3792 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3793 static void apndDlClose(sqlite3_vfs*, void*);
3794 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3795 static int apndSleep(sqlite3_vfs*, int microseconds);
3796 static int apndCurrentTime(sqlite3_vfs*, double*);
3797 static int apndGetLastError(sqlite3_vfs*, int, char *);
3798 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3799 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3800 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3801 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3802
3803 static sqlite3_vfs apnd_vfs = {
3804   3,                            /* iVersion (set when registered) */
3805   0,                            /* szOsFile (set when registered) */
3806   1024,                         /* mxPathname */
3807   0,                            /* pNext */
3808   "apndvfs",                    /* zName */
3809   0,                            /* pAppData (set when registered) */ 
3810   apndOpen,                     /* xOpen */
3811   apndDelete,                   /* xDelete */
3812   apndAccess,                   /* xAccess */
3813   apndFullPathname,             /* xFullPathname */
3814   apndDlOpen,                   /* xDlOpen */
3815   apndDlError,                  /* xDlError */
3816   apndDlSym,                    /* xDlSym */
3817   apndDlClose,                  /* xDlClose */
3818   apndRandomness,               /* xRandomness */
3819   apndSleep,                    /* xSleep */
3820   apndCurrentTime,              /* xCurrentTime */
3821   apndGetLastError,             /* xGetLastError */
3822   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
3823   apndSetSystemCall,            /* xSetSystemCall */
3824   apndGetSystemCall,            /* xGetSystemCall */
3825   apndNextSystemCall            /* xNextSystemCall */
3826 };
3827
3828 static const sqlite3_io_methods apnd_io_methods = {
3829   3,                              /* iVersion */
3830   apndClose,                      /* xClose */
3831   apndRead,                       /* xRead */
3832   apndWrite,                      /* xWrite */
3833   apndTruncate,                   /* xTruncate */
3834   apndSync,                       /* xSync */
3835   apndFileSize,                   /* xFileSize */
3836   apndLock,                       /* xLock */
3837   apndUnlock,                     /* xUnlock */
3838   apndCheckReservedLock,          /* xCheckReservedLock */
3839   apndFileControl,                /* xFileControl */
3840   apndSectorSize,                 /* xSectorSize */
3841   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
3842   apndShmMap,                     /* xShmMap */
3843   apndShmLock,                    /* xShmLock */
3844   apndShmBarrier,                 /* xShmBarrier */
3845   apndShmUnmap,                   /* xShmUnmap */
3846   apndFetch,                      /* xFetch */
3847   apndUnfetch                     /* xUnfetch */
3848 };
3849
3850 /*
3851 ** Close an apnd-file.
3852 */
3853 static int apndClose(sqlite3_file *pFile){
3854   pFile = ORIGFILE(pFile);
3855   return pFile->pMethods->xClose(pFile);
3856 }
3857
3858 /*
3859 ** Read data from an apnd-file.
3860 */
3861 static int apndRead(
3862   sqlite3_file *pFile, 
3863   void *zBuf, 
3864   int iAmt, 
3865   sqlite_int64 iOfst
3866 ){
3867   ApndFile *paf = (ApndFile *)pFile;
3868   pFile = ORIGFILE(pFile);
3869   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
3870 }
3871
3872 /*
3873 ** Add the append-mark onto what should become the end of the file.
3874 *  If and only if this succeeds, internal ApndFile.iMark is updated.
3875 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
3876 */
3877 static int apndWriteMark(
3878   ApndFile *paf,
3879   sqlite3_file *pFile,
3880   sqlite_int64 iWriteEnd
3881 ){
3882   sqlite_int64 iPgOne = paf->iPgOne;
3883   unsigned char a[APND_MARK_SIZE];
3884   int i = APND_MARK_FOS_SZ;
3885   int rc;
3886   assert(pFile == ORIGFILE(paf));
3887   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3888   while( --i >= 0 ){
3889     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
3890     iPgOne >>= 8;
3891   }
3892   iWriteEnd += paf->iPgOne;
3893   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
3894                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
3895     paf->iMark = iWriteEnd;
3896   }
3897   return rc;
3898 }
3899
3900 /*
3901 ** Write data to an apnd-file.
3902 */
3903 static int apndWrite(
3904   sqlite3_file *pFile,
3905   const void *zBuf,
3906   int iAmt,
3907   sqlite_int64 iOfst
3908 ){
3909   ApndFile *paf = (ApndFile *)pFile;
3910   sqlite_int64 iWriteEnd = iOfst + iAmt;
3911   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
3912   pFile = ORIGFILE(pFile);
3913   /* If append-mark is absent or will be overwritten, write it. */
3914   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
3915     int rc = apndWriteMark(paf, pFile, iWriteEnd);
3916     if( SQLITE_OK!=rc ) return rc;
3917   }
3918   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
3919 }
3920
3921 /*
3922 ** Truncate an apnd-file.
3923 */
3924 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3925   ApndFile *paf = (ApndFile *)pFile;
3926   pFile = ORIGFILE(pFile);
3927   /* The append mark goes out first so truncate failure does not lose it. */
3928   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
3929   /* Truncate underlying file just past append mark */
3930   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
3931 }
3932
3933 /*
3934 ** Sync an apnd-file.
3935 */
3936 static int apndSync(sqlite3_file *pFile, int flags){
3937   pFile = ORIGFILE(pFile);
3938   return pFile->pMethods->xSync(pFile, flags);
3939 }
3940
3941 /*
3942 ** Return the current file-size of an apnd-file.
3943 ** If the append mark is not yet there, the file-size is 0.
3944 */
3945 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3946   ApndFile *paf = (ApndFile *)pFile;
3947   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
3948   return SQLITE_OK;
3949 }
3950
3951 /*
3952 ** Lock an apnd-file.
3953 */
3954 static int apndLock(sqlite3_file *pFile, int eLock){
3955   pFile = ORIGFILE(pFile);
3956   return pFile->pMethods->xLock(pFile, eLock);
3957 }
3958
3959 /*
3960 ** Unlock an apnd-file.
3961 */
3962 static int apndUnlock(sqlite3_file *pFile, int eLock){
3963   pFile = ORIGFILE(pFile);
3964   return pFile->pMethods->xUnlock(pFile, eLock);
3965 }
3966
3967 /*
3968 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3969 */
3970 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3971   pFile = ORIGFILE(pFile);
3972   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3973 }
3974
3975 /*
3976 ** File control method. For custom operations on an apnd-file.
3977 */
3978 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3979   ApndFile *paf = (ApndFile *)pFile;
3980   int rc;
3981   pFile = ORIGFILE(pFile);
3982   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
3983   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3984   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3985     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
3986   }
3987   return rc;
3988 }
3989
3990 /*
3991 ** Return the sector-size in bytes for an apnd-file.
3992 */
3993 static int apndSectorSize(sqlite3_file *pFile){
3994   pFile = ORIGFILE(pFile);
3995   return pFile->pMethods->xSectorSize(pFile);
3996 }
3997
3998 /*
3999 ** Return the device characteristic flags supported by an apnd-file.
4000 */
4001 static int apndDeviceCharacteristics(sqlite3_file *pFile){
4002   pFile = ORIGFILE(pFile);
4003   return pFile->pMethods->xDeviceCharacteristics(pFile);
4004 }
4005
4006 /* Create a shared memory file mapping */
4007 static int apndShmMap(
4008   sqlite3_file *pFile,
4009   int iPg,
4010   int pgsz,
4011   int bExtend,
4012   void volatile **pp
4013 ){
4014   pFile = ORIGFILE(pFile);
4015   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
4016 }
4017
4018 /* Perform locking on a shared-memory segment */
4019 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
4020   pFile = ORIGFILE(pFile);
4021   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
4022 }
4023
4024 /* Memory barrier operation on shared memory */
4025 static void apndShmBarrier(sqlite3_file *pFile){
4026   pFile = ORIGFILE(pFile);
4027   pFile->pMethods->xShmBarrier(pFile);
4028 }
4029
4030 /* Unmap a shared memory segment */
4031 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
4032   pFile = ORIGFILE(pFile);
4033   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
4034 }
4035
4036 /* Fetch a page of a memory-mapped file */
4037 static int apndFetch(
4038   sqlite3_file *pFile,
4039   sqlite3_int64 iOfst,
4040   int iAmt,
4041   void **pp
4042 ){
4043   ApndFile *p = (ApndFile *)pFile;
4044   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
4045     return SQLITE_IOERR; /* Cannot read what is not yet there. */
4046   }
4047   pFile = ORIGFILE(pFile);
4048   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
4049 }
4050
4051 /* Release a memory-mapped page */
4052 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
4053   ApndFile *p = (ApndFile *)pFile;
4054   pFile = ORIGFILE(pFile);
4055   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
4056 }
4057
4058 /*
4059 ** Try to read the append-mark off the end of a file.  Return the
4060 ** start of the appended database if the append-mark is present.
4061 ** If there is no valid append-mark, return -1;
4062 **
4063 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
4064 ** indicates that the appended database contains at least one page.  The
4065 ** start-of-database value must be a multiple of 512.
4066 */
4067 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
4068   int rc, i;
4069   sqlite3_int64 iMark;
4070   int msbs = 8 * (APND_MARK_FOS_SZ-1);
4071   unsigned char a[APND_MARK_SIZE];
4072
4073   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
4074   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
4075   if( rc ) return -1;
4076   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
4077   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
4078   for(i=1; i<8; i++){
4079     msbs -= 8;
4080     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
4081   }
4082   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
4083   if( iMark & 0x1ff ) return -1;
4084   return iMark;
4085 }
4086
4087 static const char apvfsSqliteHdr[] = "SQLite format 3";
4088 /*
4089 ** Check to see if the file is an appendvfs SQLite database file.
4090 ** Return true iff it is such. Parameter sz is the file's size.
4091 */
4092 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
4093   int rc;
4094   char zHdr[16];
4095   sqlite3_int64 iMark = apndReadMark(sz, pFile);
4096   if( iMark>=0 ){
4097     /* If file has the correct end-marker, the expected odd size, and the
4098     ** SQLite DB type marker where the end-marker puts it, then it
4099     ** is an appendvfs database.
4100     */
4101     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
4102     if( SQLITE_OK==rc
4103      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
4104      && (sz & 0x1ff) == APND_MARK_SIZE
4105      && sz>=512+APND_MARK_SIZE
4106     ){
4107       return 1; /* It's an appendvfs database */
4108     }
4109   }
4110   return 0;
4111 }
4112
4113 /*
4114 ** Check to see if the file is an ordinary SQLite database file.
4115 ** Return true iff so. Parameter sz is the file's size.
4116 */
4117 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
4118   char zHdr[16];
4119   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
4120    || (sz & 0x1ff) != 0
4121    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
4122    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
4123   ){
4124     return 0;
4125   }else{
4126     return 1;
4127   }
4128 }
4129
4130 /*
4131 ** Open an apnd file handle.
4132 */
4133 static int apndOpen(
4134   sqlite3_vfs *pApndVfs,
4135   const char *zName,
4136   sqlite3_file *pFile,
4137   int flags,
4138   int *pOutFlags
4139 ){
4140   ApndFile *pApndFile = (ApndFile*)pFile;
4141   sqlite3_file *pBaseFile = ORIGFILE(pFile);
4142   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
4143   int rc;
4144   sqlite3_int64 sz = 0;
4145   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
4146     /* The appendvfs is not to be used for transient or temporary databases.
4147     ** Just use the base VFS open to initialize the given file object and
4148     ** open the underlying file. (Appendvfs is then unused for this file.)
4149     */
4150     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
4151   }
4152   memset(pApndFile, 0, sizeof(ApndFile));
4153   pFile->pMethods = &apnd_io_methods;
4154   pApndFile->iMark = -1;    /* Append mark not yet written */
4155
4156   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
4157   if( rc==SQLITE_OK ){
4158     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
4159   }
4160   if( rc ){
4161     pBaseFile->pMethods->xClose(pBaseFile);
4162     pFile->pMethods = 0;
4163     return rc;
4164   }
4165   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
4166     /* The file being opened appears to be just an ordinary DB. Copy
4167     ** the base dispatch-table so this instance mimics the base VFS. 
4168     */
4169     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
4170     return SQLITE_OK;
4171   }
4172   pApndFile->iPgOne = apndReadMark(sz, pFile);
4173   if( pApndFile->iPgOne>=0 ){
4174     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
4175     return SQLITE_OK;
4176   }
4177   if( (flags & SQLITE_OPEN_CREATE)==0 ){
4178     pBaseFile->pMethods->xClose(pBaseFile);
4179     rc = SQLITE_CANTOPEN;
4180     pFile->pMethods = 0;
4181   }else{
4182     /* Round newly added appendvfs location to #define'd page boundary. 
4183     ** Note that nothing has yet been written to the underlying file.
4184     ** The append mark will be written along with first content write.
4185     ** Until then, paf->iMark value indicates it is not yet written.
4186     */
4187     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
4188   }
4189   return rc;
4190 }
4191
4192 /*
4193 ** Delete an apnd file.
4194 ** For an appendvfs, this could mean delete the appendvfs portion,
4195 ** leaving the appendee as it was before it gained an appendvfs.
4196 ** For now, this code deletes the underlying file too.
4197 */
4198 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
4199   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
4200 }
4201
4202 /*
4203 ** All other VFS methods are pass-thrus.
4204 */
4205 static int apndAccess(
4206   sqlite3_vfs *pVfs, 
4207   const char *zPath, 
4208   int flags, 
4209   int *pResOut
4210 ){
4211   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
4212 }
4213 static int apndFullPathname(
4214   sqlite3_vfs *pVfs, 
4215   const char *zPath, 
4216   int nOut, 
4217   char *zOut
4218 ){
4219   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
4220 }
4221 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
4222   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
4223 }
4224 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
4225   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
4226 }
4227 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
4228   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
4229 }
4230 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
4231   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
4232 }
4233 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
4234   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
4235 }
4236 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
4237   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
4238 }
4239 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
4240   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
4241 }
4242 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
4243   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
4244 }
4245 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
4246   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
4247 }
4248 static int apndSetSystemCall(
4249   sqlite3_vfs *pVfs,
4250   const char *zName,
4251   sqlite3_syscall_ptr pCall
4252 ){
4253   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
4254 }
4255 static sqlite3_syscall_ptr apndGetSystemCall(
4256   sqlite3_vfs *pVfs,
4257   const char *zName
4258 ){
4259   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
4260 }
4261 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
4262   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
4263 }
4264
4265   
4266 #ifdef _WIN32
4267
4268 #endif
4269 /* 
4270 ** This routine is called when the extension is loaded.
4271 ** Register the new VFS.
4272 */
4273 int sqlite3_appendvfs_init(
4274   sqlite3 *db, 
4275   char **pzErrMsg, 
4276   const sqlite3_api_routines *pApi
4277 ){
4278   int rc = SQLITE_OK;
4279   sqlite3_vfs *pOrig;
4280   SQLITE_EXTENSION_INIT2(pApi);
4281   (void)pzErrMsg;
4282   (void)db;
4283   pOrig = sqlite3_vfs_find(0);
4284   apnd_vfs.iVersion = pOrig->iVersion;
4285   apnd_vfs.pAppData = pOrig;
4286   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4287   rc = sqlite3_vfs_register(&apnd_vfs, 0);
4288 #ifdef APPENDVFS_TEST
4289   if( rc==SQLITE_OK ){
4290     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4291   }
4292 #endif
4293   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4294   return rc;
4295 }
4296
4297 /************************* End ../ext/misc/appendvfs.c ********************/
4298 /************************* Begin ../ext/misc/memtrace.c ******************/
4299 /*
4300 ** 2019-01-21
4301 **
4302 ** The author disclaims copyright to this source code.  In place of
4303 ** a legal notice, here is a blessing:
4304 **
4305 **    May you do good and not evil.
4306 **    May you find forgiveness for yourself and forgive others.
4307 **    May you share freely, never taking more than you give.
4308 **
4309 *************************************************************************
4310 **
4311 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
4312 ** mechanism to add a tracing layer on top of SQLite.  If this extension
4313 ** is registered prior to sqlite3_initialize(), it will cause all memory
4314 ** allocation activities to be logged on standard output, or to some other
4315 ** FILE specified by the initializer.
4316 **
4317 ** This file needs to be compiled into the application that uses it.
4318 **
4319 ** This extension is used to implement the --memtrace option of the
4320 ** command-line shell.
4321 */
4322 #include <assert.h>
4323 #include <string.h>
4324 #include <stdio.h>
4325
4326 /* The original memory allocation routines */
4327 static sqlite3_mem_methods memtraceBase;
4328 static FILE *memtraceOut;
4329
4330 /* Methods that trace memory allocations */
4331 static void *memtraceMalloc(int n){
4332   if( memtraceOut ){
4333     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n", 
4334             memtraceBase.xRoundup(n));
4335   }
4336   return memtraceBase.xMalloc(n);
4337 }
4338 static void memtraceFree(void *p){
4339   if( p==0 ) return;
4340   if( memtraceOut ){
4341     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
4342   }
4343   memtraceBase.xFree(p);
4344 }
4345 static void *memtraceRealloc(void *p, int n){
4346   if( p==0 ) return memtraceMalloc(n);
4347   if( n==0 ){
4348     memtraceFree(p);
4349     return 0;
4350   }
4351   if( memtraceOut ){
4352     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
4353             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
4354   }
4355   return memtraceBase.xRealloc(p, n);
4356 }
4357 static int memtraceSize(void *p){
4358   return memtraceBase.xSize(p);
4359 }
4360 static int memtraceRoundup(int n){
4361   return memtraceBase.xRoundup(n);
4362 }
4363 static int memtraceInit(void *p){
4364   return memtraceBase.xInit(p);
4365 }
4366 static void memtraceShutdown(void *p){
4367   memtraceBase.xShutdown(p);
4368 }
4369
4370 /* The substitute memory allocator */
4371 static sqlite3_mem_methods ersaztMethods = {
4372   memtraceMalloc,
4373   memtraceFree,
4374   memtraceRealloc,
4375   memtraceSize,
4376   memtraceRoundup,
4377   memtraceInit,
4378   memtraceShutdown,
4379   0
4380 };
4381
4382 /* Begin tracing memory allocations to out. */
4383 int sqlite3MemTraceActivate(FILE *out){
4384   int rc = SQLITE_OK;
4385   if( memtraceBase.xMalloc==0 ){
4386     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
4387     if( rc==SQLITE_OK ){
4388       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
4389     }
4390   }
4391   memtraceOut = out;
4392   return rc;
4393 }
4394
4395 /* Deactivate memory tracing */
4396 int sqlite3MemTraceDeactivate(void){
4397   int rc = SQLITE_OK;
4398   if( memtraceBase.xMalloc!=0 ){
4399     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
4400     if( rc==SQLITE_OK ){
4401       memset(&memtraceBase, 0, sizeof(memtraceBase));
4402     }
4403   }
4404   memtraceOut = 0;
4405   return rc;
4406 }
4407
4408 /************************* End ../ext/misc/memtrace.c ********************/
4409 /************************* Begin ../ext/misc/uint.c ******************/
4410 /*
4411 ** 2020-04-14
4412 **
4413 ** The author disclaims copyright to this source code.  In place of
4414 ** a legal notice, here is a blessing:
4415 **
4416 **    May you do good and not evil.
4417 **    May you find forgiveness for yourself and forgive others.
4418 **    May you share freely, never taking more than you give.
4419 **
4420 ******************************************************************************
4421 **
4422 ** This SQLite extension implements the UINT collating sequence.
4423 **
4424 ** UINT works like BINARY for text, except that embedded strings
4425 ** of digits compare in numeric order.
4426 **
4427 **     *   Leading zeros are handled properly, in the sense that
4428 **         they do not mess of the maginitude comparison of embedded
4429 **         strings of digits.  "x00123y" is equal to "x123y".
4430 **
4431 **     *   Only unsigned integers are recognized.  Plus and minus
4432 **         signs are ignored.  Decimal points and exponential notation
4433 **         are ignored.
4434 **
4435 **     *   Embedded integers can be of arbitrary length.  Comparison
4436 **         is *not* limited integers that can be expressed as a
4437 **         64-bit machine integer.
4438 */
4439 /* #include "sqlite3ext.h" */
4440 SQLITE_EXTENSION_INIT1
4441 #include <assert.h>
4442 #include <string.h>
4443 #include <ctype.h>
4444
4445 /*
4446 ** Compare text in lexicographic order, except strings of digits
4447 ** compare in numeric order.
4448 */
4449 static int uintCollFunc(
4450   void *notUsed,
4451   int nKey1, const void *pKey1,
4452   int nKey2, const void *pKey2
4453 ){
4454   const unsigned char *zA = (const unsigned char*)pKey1;
4455   const unsigned char *zB = (const unsigned char*)pKey2;
4456   int i=0, j=0, x;
4457   (void)notUsed;
4458   while( i<nKey1 && j<nKey2 ){
4459     x = zA[i] - zB[j];
4460     if( isdigit(zA[i]) ){
4461       int k;
4462       if( !isdigit(zB[j]) ) return x;
4463       while( i<nKey1 && zA[i]=='0' ){ i++; }
4464       while( j<nKey2 && zB[j]=='0' ){ j++; }
4465       k = 0;
4466       while( i+k<nKey1 && isdigit(zA[i+k])
4467              && j+k<nKey2 && isdigit(zB[j+k]) ){
4468         k++;
4469       }
4470       if( i+k<nKey1 && isdigit(zA[i+k]) ){
4471         return +1;
4472       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
4473         return -1;
4474       }else{
4475         x = memcmp(zA+i, zB+j, k);
4476         if( x ) return x;
4477         i += k;
4478         j += k;
4479       }
4480     }else if( x ){
4481       return x;
4482     }else{
4483       i++;
4484       j++;
4485     }
4486   }
4487   return (nKey1 - i) - (nKey2 - j);
4488 }
4489
4490 #ifdef _WIN32
4491
4492 #endif
4493 int sqlite3_uint_init(
4494   sqlite3 *db, 
4495   char **pzErrMsg, 
4496   const sqlite3_api_routines *pApi
4497 ){
4498   SQLITE_EXTENSION_INIT2(pApi);
4499   (void)pzErrMsg;  /* Unused parameter */
4500   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
4501 }
4502
4503 /************************* End ../ext/misc/uint.c ********************/
4504 /************************* Begin ../ext/misc/decimal.c ******************/
4505 /*
4506 ** 2020-06-22
4507 **
4508 ** The author disclaims copyright to this source code.  In place of
4509 ** a legal notice, here is a blessing:
4510 **
4511 **    May you do good and not evil.
4512 **    May you find forgiveness for yourself and forgive others.
4513 **    May you share freely, never taking more than you give.
4514 **
4515 ******************************************************************************
4516 **
4517 ** Routines to implement arbitrary-precision decimal math.
4518 **
4519 ** The focus here is on simplicity and correctness, not performance.
4520 */
4521 /* #include "sqlite3ext.h" */
4522 SQLITE_EXTENSION_INIT1
4523 #include <assert.h>
4524 #include <string.h>
4525 #include <ctype.h>
4526 #include <stdlib.h>
4527
4528 /* Mark a function parameter as unused, to suppress nuisance compiler
4529 ** warnings. */
4530 #ifndef UNUSED_PARAMETER
4531 # define UNUSED_PARAMETER(X)  (void)(X)
4532 #endif
4533
4534
4535 /* A decimal object */
4536 typedef struct Decimal Decimal;
4537 struct Decimal {
4538   char sign;        /* 0 for positive, 1 for negative */
4539   char oom;         /* True if an OOM is encountered */
4540   char isNull;      /* True if holds a NULL rather than a number */
4541   char isInit;      /* True upon initialization */
4542   int nDigit;       /* Total number of digits */
4543   int nFrac;        /* Number of digits to the right of the decimal point */
4544   signed char *a;   /* Array of digits.  Most significant first. */
4545 };
4546
4547 /*
4548 ** Release memory held by a Decimal, but do not free the object itself.
4549 */
4550 static void decimal_clear(Decimal *p){
4551   sqlite3_free(p->a);
4552 }
4553
4554 /*
4555 ** Destroy a Decimal object
4556 */
4557 static void decimal_free(Decimal *p){
4558   if( p ){
4559     decimal_clear(p);
4560     sqlite3_free(p);
4561   }
4562 }
4563
4564 /*
4565 ** Allocate a new Decimal object.  Initialize it to the number given
4566 ** by the input string.
4567 */
4568 static Decimal *decimal_new(
4569   sqlite3_context *pCtx,
4570   sqlite3_value *pIn,
4571   int nAlt,
4572   const unsigned char *zAlt
4573 ){
4574   Decimal *p;
4575   int n, i;
4576   const unsigned char *zIn;
4577   int iExp = 0;
4578   p = sqlite3_malloc( sizeof(*p) );
4579   if( p==0 ) goto new_no_mem;
4580   p->sign = 0;
4581   p->oom = 0;
4582   p->isInit = 1;
4583   p->isNull = 0;
4584   p->nDigit = 0;
4585   p->nFrac = 0;
4586   if( zAlt ){
4587     n = nAlt,
4588     zIn = zAlt;
4589   }else{
4590     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
4591       p->a = 0;
4592       p->isNull = 1;
4593       return p;
4594     }
4595     n = sqlite3_value_bytes(pIn);
4596     zIn = sqlite3_value_text(pIn);
4597   }
4598   p->a = sqlite3_malloc64( n+1 );
4599   if( p->a==0 ) goto new_no_mem;
4600   for(i=0; isspace(zIn[i]); i++){}
4601   if( zIn[i]=='-' ){
4602     p->sign = 1;
4603     i++;
4604   }else if( zIn[i]=='+' ){
4605     i++;
4606   }
4607   while( i<n && zIn[i]=='0' ) i++;
4608   while( i<n ){
4609     char c = zIn[i];
4610     if( c>='0' && c<='9' ){
4611       p->a[p->nDigit++] = c - '0';
4612     }else if( c=='.' ){
4613       p->nFrac = p->nDigit + 1;
4614     }else if( c=='e' || c=='E' ){
4615       int j = i+1;
4616       int neg = 0;
4617       if( j>=n ) break;
4618       if( zIn[j]=='-' ){
4619         neg = 1;
4620         j++;
4621       }else if( zIn[j]=='+' ){
4622         j++;
4623       }
4624       while( j<n && iExp<1000000 ){
4625         if( zIn[j]>='0' && zIn[j]<='9' ){
4626           iExp = iExp*10 + zIn[j] - '0';
4627         }
4628         j++;
4629       }
4630       if( neg ) iExp = -iExp;
4631       break;
4632     }
4633     i++;
4634   }
4635   if( p->nFrac ){
4636     p->nFrac = p->nDigit - (p->nFrac - 1);
4637   }
4638   if( iExp>0 ){
4639     if( p->nFrac>0 ){
4640       if( iExp<=p->nFrac ){
4641         p->nFrac -= iExp;
4642         iExp = 0;
4643       }else{
4644         iExp -= p->nFrac;
4645         p->nFrac = 0;
4646       }
4647     }
4648     if( iExp>0 ){   
4649       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
4650       if( p->a==0 ) goto new_no_mem;
4651       memset(p->a+p->nDigit, 0, iExp);
4652       p->nDigit += iExp;
4653     }
4654   }else if( iExp<0 ){
4655     int nExtra;
4656     iExp = -iExp;
4657     nExtra = p->nDigit - p->nFrac - 1;
4658     if( nExtra ){
4659       if( nExtra>=iExp ){
4660         p->nFrac += iExp;
4661         iExp  = 0;
4662       }else{
4663         iExp -= nExtra;
4664         p->nFrac = p->nDigit - 1;
4665       }
4666     }
4667     if( iExp>0 ){
4668       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
4669       if( p->a==0 ) goto new_no_mem;
4670       memmove(p->a+iExp, p->a, p->nDigit);
4671       memset(p->a, 0, iExp);
4672       p->nDigit += iExp;
4673       p->nFrac += iExp;
4674     }
4675   }
4676   return p;
4677
4678 new_no_mem:
4679   if( pCtx ) sqlite3_result_error_nomem(pCtx);
4680   sqlite3_free(p);
4681   return 0;
4682 }
4683
4684 /*
4685 ** Make the given Decimal the result.
4686 */
4687 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
4688   char *z;
4689   int i, j;
4690   int n;
4691   if( p==0 || p->oom ){
4692     sqlite3_result_error_nomem(pCtx);
4693     return;
4694   }
4695   if( p->isNull ){
4696     sqlite3_result_null(pCtx);
4697     return;
4698   }
4699   z = sqlite3_malloc( p->nDigit+4 );
4700   if( z==0 ){
4701     sqlite3_result_error_nomem(pCtx);
4702     return;
4703   }
4704   i = 0;
4705   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
4706     p->sign = 0;
4707   }
4708   if( p->sign ){
4709     z[0] = '-';
4710     i = 1;
4711   }
4712   n = p->nDigit - p->nFrac;
4713   if( n<=0 ){
4714     z[i++] = '0';
4715   }
4716   j = 0;
4717   while( n>1 && p->a[j]==0 ){
4718     j++;
4719     n--;
4720   }
4721   while( n>0  ){
4722     z[i++] = p->a[j] + '0';
4723     j++;
4724     n--;
4725   }
4726   if( p->nFrac ){
4727     z[i++] = '.';
4728     do{
4729       z[i++] = p->a[j] + '0';
4730       j++;
4731     }while( j<p->nDigit );
4732   }
4733   z[i] = 0;
4734   sqlite3_result_text(pCtx, z, i, sqlite3_free);
4735 }
4736
4737 /*
4738 ** SQL Function:   decimal(X)
4739 **
4740 ** Convert input X into decimal and then back into text
4741 */
4742 static void decimalFunc(
4743   sqlite3_context *context,
4744   int argc,
4745   sqlite3_value **argv
4746 ){
4747   Decimal *p = decimal_new(context, argv[0], 0, 0);
4748   UNUSED_PARAMETER(argc);
4749   decimal_result(context, p);
4750   decimal_free(p);
4751 }
4752
4753 /*
4754 ** Compare to Decimal objects.  Return negative, 0, or positive if the
4755 ** first object is less than, equal to, or greater than the second.
4756 **
4757 ** Preconditions for this routine:
4758 **
4759 **    pA!=0
4760 **    pA->isNull==0
4761 **    pB!=0
4762 **    pB->isNull==0
4763 */
4764 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4765   int nASig, nBSig, rc, n;
4766   if( pA->sign!=pB->sign ){
4767     return pA->sign ? -1 : +1;
4768   }
4769   if( pA->sign ){
4770     const Decimal *pTemp = pA;
4771     pA = pB;
4772     pB = pTemp;
4773   }
4774   nASig = pA->nDigit - pA->nFrac;
4775   nBSig = pB->nDigit - pB->nFrac;
4776   if( nASig!=nBSig ){
4777     return nASig - nBSig;
4778   }
4779   n = pA->nDigit;
4780   if( n>pB->nDigit ) n = pB->nDigit;
4781   rc = memcmp(pA->a, pB->a, n);
4782   if( rc==0 ){
4783     rc = pA->nDigit - pB->nDigit;
4784   }
4785   return rc;
4786 }
4787
4788 /*
4789 ** SQL Function:   decimal_cmp(X, Y)
4790 **
4791 ** Return negative, zero, or positive if X is less then, equal to, or
4792 ** greater than Y.
4793 */
4794 static void decimalCmpFunc(
4795   sqlite3_context *context,
4796   int argc,
4797   sqlite3_value **argv
4798 ){
4799   Decimal *pA = 0, *pB = 0;
4800   int rc;
4801
4802   UNUSED_PARAMETER(argc);
4803   pA = decimal_new(context, argv[0], 0, 0);
4804   if( pA==0 || pA->isNull ) goto cmp_done;
4805   pB = decimal_new(context, argv[1], 0, 0);
4806   if( pB==0 || pB->isNull ) goto cmp_done;
4807   rc = decimal_cmp(pA, pB);
4808   if( rc<0 ) rc = -1;
4809   else if( rc>0 ) rc = +1;
4810   sqlite3_result_int(context, rc);
4811 cmp_done:
4812   decimal_free(pA);
4813   decimal_free(pB);
4814 }
4815
4816 /*
4817 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4818 ** digits to the right of the decimal point.
4819 */
4820 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4821   int nAddSig;
4822   int nAddFrac;
4823   if( p==0 ) return;
4824   nAddFrac = nFrac - p->nFrac;
4825   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4826   if( nAddFrac==0 && nAddSig==0 ) return;
4827   p->a = sqlite3_realloc64(p->a, nDigit+1);
4828   if( p->a==0 ){
4829     p->oom = 1;
4830     return;
4831   }
4832   if( nAddSig ){
4833     memmove(p->a+nAddSig, p->a, p->nDigit);
4834     memset(p->a, 0, nAddSig);
4835     p->nDigit += nAddSig;
4836   }
4837   if( nAddFrac ){
4838     memset(p->a+p->nDigit, 0, nAddFrac);
4839     p->nDigit += nAddFrac;
4840     p->nFrac += nAddFrac;
4841   }
4842 }
4843
4844 /*
4845 ** Add the value pB into pA.
4846 **
4847 ** Both pA and pB might become denormalized by this routine.
4848 */
4849 static void decimal_add(Decimal *pA, Decimal *pB){
4850   int nSig, nFrac, nDigit;
4851   int i, rc;
4852   if( pA==0 ){
4853     return;
4854   }
4855   if( pA->oom || pB==0 || pB->oom ){
4856     pA->oom = 1;
4857     return;
4858   }
4859   if( pA->isNull || pB->isNull ){
4860     pA->isNull = 1;
4861     return;
4862   }
4863   nSig = pA->nDigit - pA->nFrac;
4864   if( nSig && pA->a[0]==0 ) nSig--;
4865   if( nSig<pB->nDigit-pB->nFrac ){
4866     nSig = pB->nDigit - pB->nFrac;
4867   }
4868   nFrac = pA->nFrac;
4869   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4870   nDigit = nSig + nFrac + 1;
4871   decimal_expand(pA, nDigit, nFrac);
4872   decimal_expand(pB, nDigit, nFrac);
4873   if( pA->oom || pB->oom ){
4874     pA->oom = 1;
4875   }else{
4876     if( pA->sign==pB->sign ){
4877       int carry = 0;
4878       for(i=nDigit-1; i>=0; i--){
4879         int x = pA->a[i] + pB->a[i] + carry;
4880         if( x>=10 ){
4881           carry = 1;
4882           pA->a[i] = x - 10;
4883         }else{
4884           carry = 0;
4885           pA->a[i] = x;
4886         }
4887       }
4888     }else{
4889       signed char *aA, *aB;
4890       int borrow = 0;
4891       rc = memcmp(pA->a, pB->a, nDigit);
4892       if( rc<0 ){
4893         aA = pB->a;
4894         aB = pA->a;
4895         pA->sign = !pA->sign;
4896       }else{
4897         aA = pA->a;
4898         aB = pB->a;
4899       }
4900       for(i=nDigit-1; i>=0; i--){
4901         int x = aA[i] - aB[i] - borrow;
4902         if( x<0 ){
4903           pA->a[i] = x+10;
4904           borrow = 1;
4905         }else{
4906           pA->a[i] = x;
4907           borrow = 0;
4908         }
4909       }
4910     }
4911   }
4912 }
4913
4914 /*
4915 ** Compare text in decimal order.
4916 */
4917 static int decimalCollFunc(
4918   void *notUsed,
4919   int nKey1, const void *pKey1,
4920   int nKey2, const void *pKey2
4921 ){
4922   const unsigned char *zA = (const unsigned char*)pKey1;
4923   const unsigned char *zB = (const unsigned char*)pKey2;
4924   Decimal *pA = decimal_new(0, 0, nKey1, zA);
4925   Decimal *pB = decimal_new(0, 0, nKey2, zB);
4926   int rc;
4927   UNUSED_PARAMETER(notUsed);
4928   if( pA==0 || pB==0 ){
4929     rc = 0;
4930   }else{
4931     rc = decimal_cmp(pA, pB);
4932   }
4933   decimal_free(pA);
4934   decimal_free(pB);
4935   return rc;
4936 }
4937
4938
4939 /*
4940 ** SQL Function:   decimal_add(X, Y)
4941 **                 decimal_sub(X, Y)
4942 **
4943 ** Return the sum or difference of X and Y.
4944 */
4945 static void decimalAddFunc(
4946   sqlite3_context *context,
4947   int argc,
4948   sqlite3_value **argv
4949 ){
4950   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4951   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4952   UNUSED_PARAMETER(argc);
4953   decimal_add(pA, pB);
4954   decimal_result(context, pA);
4955   decimal_free(pA);
4956   decimal_free(pB);
4957 }
4958 static void decimalSubFunc(
4959   sqlite3_context *context,
4960   int argc,
4961   sqlite3_value **argv
4962 ){
4963   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4964   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4965   UNUSED_PARAMETER(argc);
4966   if( pB==0 ) return;
4967   pB->sign = !pB->sign;
4968   decimal_add(pA, pB);
4969   decimal_result(context, pA);
4970   decimal_free(pA);
4971   decimal_free(pB);
4972 }
4973
4974 /* Aggregate funcion:   decimal_sum(X)
4975 **
4976 ** Works like sum() except that it uses decimal arithmetic for unlimited
4977 ** precision.
4978 */
4979 static void decimalSumStep(
4980   sqlite3_context *context,
4981   int argc,
4982   sqlite3_value **argv
4983 ){
4984   Decimal *p;
4985   Decimal *pArg;
4986   UNUSED_PARAMETER(argc);
4987   p = sqlite3_aggregate_context(context, sizeof(*p));
4988   if( p==0 ) return;
4989   if( !p->isInit ){
4990     p->isInit = 1;
4991     p->a = sqlite3_malloc(2);
4992     if( p->a==0 ){
4993       p->oom = 1;
4994     }else{
4995       p->a[0] = 0;
4996     }
4997     p->nDigit = 1;
4998     p->nFrac = 0;
4999   }
5000   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
5001   pArg = decimal_new(context, argv[0], 0, 0);
5002   decimal_add(p, pArg);
5003   decimal_free(pArg);
5004 }
5005 static void decimalSumInverse(
5006   sqlite3_context *context,
5007   int argc,
5008   sqlite3_value **argv
5009 ){
5010   Decimal *p;
5011   Decimal *pArg;
5012   UNUSED_PARAMETER(argc);
5013   p = sqlite3_aggregate_context(context, sizeof(*p));
5014   if( p==0 ) return;
5015   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
5016   pArg = decimal_new(context, argv[0], 0, 0);
5017   if( pArg ) pArg->sign = !pArg->sign;
5018   decimal_add(p, pArg);
5019   decimal_free(pArg);
5020 }
5021 static void decimalSumValue(sqlite3_context *context){
5022   Decimal *p = sqlite3_aggregate_context(context, 0);
5023   if( p==0 ) return;
5024   decimal_result(context, p);
5025 }
5026 static void decimalSumFinalize(sqlite3_context *context){
5027   Decimal *p = sqlite3_aggregate_context(context, 0);
5028   if( p==0 ) return;
5029   decimal_result(context, p);
5030   decimal_clear(p);
5031 }
5032
5033 /*
5034 ** SQL Function:   decimal_mul(X, Y)
5035 **
5036 ** Return the product of X and Y.
5037 **
5038 ** All significant digits after the decimal point are retained.
5039 ** Trailing zeros after the decimal point are omitted as long as
5040 ** the number of digits after the decimal point is no less than
5041 ** either the number of digits in either input.
5042 */
5043 static void decimalMulFunc(
5044   sqlite3_context *context,
5045   int argc,
5046   sqlite3_value **argv
5047 ){
5048   Decimal *pA = decimal_new(context, argv[0], 0, 0);
5049   Decimal *pB = decimal_new(context, argv[1], 0, 0);
5050   signed char *acc = 0;
5051   int i, j, k;
5052   int minFrac;
5053   UNUSED_PARAMETER(argc);
5054   if( pA==0 || pA->oom || pA->isNull
5055    || pB==0 || pB->oom || pB->isNull 
5056   ){
5057     goto mul_end;
5058   }
5059   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
5060   if( acc==0 ){
5061     sqlite3_result_error_nomem(context);
5062     goto mul_end;
5063   }
5064   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
5065   minFrac = pA->nFrac;
5066   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
5067   for(i=pA->nDigit-1; i>=0; i--){
5068     signed char f = pA->a[i];
5069     int carry = 0, x;
5070     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
5071       x = acc[k] + f*pB->a[j] + carry;
5072       acc[k] = x%10;
5073       carry = x/10;
5074     }
5075     x = acc[k] + carry;
5076     acc[k] = x%10;
5077     acc[k-1] += x/10;
5078   }
5079   sqlite3_free(pA->a);
5080   pA->a = acc;
5081   acc = 0;
5082   pA->nDigit += pB->nDigit + 2;
5083   pA->nFrac += pB->nFrac;
5084   pA->sign ^= pB->sign;
5085   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
5086     pA->nFrac--;
5087     pA->nDigit--;
5088   }
5089   decimal_result(context, pA);
5090
5091 mul_end:
5092   sqlite3_free(acc);
5093   decimal_free(pA);
5094   decimal_free(pB);
5095 }
5096
5097 #ifdef _WIN32
5098
5099 #endif
5100 int sqlite3_decimal_init(
5101   sqlite3 *db, 
5102   char **pzErrMsg, 
5103   const sqlite3_api_routines *pApi
5104 ){
5105   int rc = SQLITE_OK;
5106   static const struct {
5107     const char *zFuncName;
5108     int nArg;
5109     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5110   } aFunc[] = {
5111     { "decimal",       1,   decimalFunc        },
5112     { "decimal_cmp",   2,   decimalCmpFunc     },
5113     { "decimal_add",   2,   decimalAddFunc     },
5114     { "decimal_sub",   2,   decimalSubFunc     },
5115     { "decimal_mul",   2,   decimalMulFunc     },
5116   };
5117   unsigned int i;
5118   (void)pzErrMsg;  /* Unused parameter */
5119
5120   SQLITE_EXTENSION_INIT2(pApi);
5121
5122   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5123     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
5124                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5125                    0, aFunc[i].xFunc, 0, 0);
5126   }
5127   if( rc==SQLITE_OK ){
5128     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
5129                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
5130                    decimalSumStep, decimalSumFinalize,
5131                    decimalSumValue, decimalSumInverse, 0);
5132   }
5133   if( rc==SQLITE_OK ){
5134     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
5135                                   0, decimalCollFunc);
5136   }
5137   return rc;
5138 }
5139
5140 /************************* End ../ext/misc/decimal.c ********************/
5141 /************************* Begin ../ext/misc/ieee754.c ******************/
5142 /*
5143 ** 2013-04-17
5144 **
5145 ** The author disclaims copyright to this source code.  In place of
5146 ** a legal notice, here is a blessing:
5147 **
5148 **    May you do good and not evil.
5149 **    May you find forgiveness for yourself and forgive others.
5150 **    May you share freely, never taking more than you give.
5151 **
5152 ******************************************************************************
5153 **
5154 ** This SQLite extension implements functions for the exact display
5155 ** and input of IEEE754 Binary64 floating-point numbers.
5156 **
5157 **   ieee754(X)
5158 **   ieee754(Y,Z)
5159 **
5160 ** In the first form, the value X should be a floating-point number.
5161 ** The function will return a string of the form 'ieee754(Y,Z)' where
5162 ** Y and Z are integers such that X==Y*pow(2,Z).
5163 **
5164 ** In the second form, Y and Z are integers which are the mantissa and
5165 ** base-2 exponent of a new floating point number.  The function returns
5166 ** a floating-point value equal to Y*pow(2,Z).
5167 **
5168 ** Examples:
5169 **
5170 **     ieee754(2.0)             ->     'ieee754(2,0)'
5171 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5172 **     ieee754(2, 0)            ->     2.0
5173 **     ieee754(181, -2)         ->     45.25
5174 **
5175 ** Two additional functions break apart the one-argument ieee754()
5176 ** result into separate integer values:
5177 **
5178 **     ieee754_mantissa(45.25)  ->     181
5179 **     ieee754_exponent(45.25)  ->     -2
5180 **
5181 ** These functions convert binary64 numbers into blobs and back again.
5182 **
5183 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5184 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5185 **
5186 ** In all single-argument functions, if the argument is an 8-byte blob
5187 ** then that blob is interpreted as a big-endian binary64 value.
5188 **
5189 **
5190 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5191 ** -----------------------------------------------
5192 **
5193 ** This extension in combination with the separate 'decimal' extension
5194 ** can be used to compute the exact decimal representation of binary64
5195 ** values.  To begin, first compute a table of exponent values:
5196 **
5197 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5198 **    WITH RECURSIVE c(x,v) AS (
5199 **      VALUES(0,'1')
5200 **      UNION ALL
5201 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5202 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5203 **    WITH RECURSIVE c(x,v) AS (
5204 **      VALUES(-1,'0.5')
5205 **      UNION ALL
5206 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5207 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5208 **
5209 ** Then, to compute the exact decimal representation of a floating
5210 ** point value (the value 47.49 is used in the example) do:
5211 **
5212 **    WITH c(n) AS (VALUES(47.49))
5213 **          ---------------^^^^^---- Replace with whatever you want
5214 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5215 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5216 **
5217 ** Here is a query to show various boundry values for the binary64
5218 ** number format:
5219 **
5220 **    WITH c(name,bin) AS (VALUES
5221 **       ('minimum positive value',        x'0000000000000001'),
5222 **       ('maximum subnormal value',       x'000fffffffffffff'),
5223 **       ('mininum positive nornal value', x'0010000000000000'),
5224 **       ('maximum value',                 x'7fefffffffffffff'))
5225 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5226 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5227 **
5228 */
5229 /* #include "sqlite3ext.h" */
5230 SQLITE_EXTENSION_INIT1
5231 #include <assert.h>
5232 #include <string.h>
5233
5234 /* Mark a function parameter as unused, to suppress nuisance compiler
5235 ** warnings. */
5236 #ifndef UNUSED_PARAMETER
5237 # define UNUSED_PARAMETER(X)  (void)(X)
5238 #endif
5239
5240 /*
5241 ** Implementation of the ieee754() function
5242 */
5243 static void ieee754func(
5244   sqlite3_context *context,
5245   int argc,
5246   sqlite3_value **argv
5247 ){
5248   if( argc==1 ){
5249     sqlite3_int64 m, a;
5250     double r;
5251     int e;
5252     int isNeg;
5253     char zResult[100];
5254     assert( sizeof(m)==sizeof(r) );
5255     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5256      && sqlite3_value_bytes(argv[0])==sizeof(r)
5257     ){
5258       const unsigned char *x = sqlite3_value_blob(argv[0]);
5259       unsigned int i;
5260       sqlite3_uint64 v = 0;
5261       for(i=0; i<sizeof(r); i++){
5262         v = (v<<8) | x[i];
5263       }
5264       memcpy(&r, &v, sizeof(r));
5265     }else{
5266       r = sqlite3_value_double(argv[0]);
5267     }
5268     if( r<0.0 ){
5269       isNeg = 1;
5270       r = -r;
5271     }else{
5272       isNeg = 0;
5273     }
5274     memcpy(&a,&r,sizeof(a));
5275     if( a==0 ){
5276       e = 0;
5277       m = 0;
5278     }else{
5279       e = a>>52;
5280       m = a & ((((sqlite3_int64)1)<<52)-1);
5281       if( e==0 ){
5282         m <<= 1;
5283       }else{
5284         m |= ((sqlite3_int64)1)<<52;
5285       }
5286       while( e<1075 && m>0 && (m&1)==0 ){
5287         m >>= 1;
5288         e++;
5289       }
5290       if( isNeg ) m = -m;
5291     }
5292     switch( *(int*)sqlite3_user_data(context) ){
5293       case 0:
5294         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5295                          m, e-1075);
5296         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5297         break;
5298       case 1:
5299         sqlite3_result_int64(context, m);
5300         break;
5301       case 2:
5302         sqlite3_result_int(context, e-1075);
5303         break;
5304     }
5305   }else{
5306     sqlite3_int64 m, e, a;
5307     double r;
5308     int isNeg = 0;
5309     m = sqlite3_value_int64(argv[0]);
5310     e = sqlite3_value_int64(argv[1]);
5311
5312     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5313     if( e>10000 ){
5314       e = 10000;
5315     }else if( e<-10000 ){
5316       e = -10000;
5317     }
5318
5319     if( m<0 ){
5320       isNeg = 1;
5321       m = -m;
5322       if( m<0 ) return;
5323     }else if( m==0 && e>-1000 && e<1000 ){
5324       sqlite3_result_double(context, 0.0);
5325       return;
5326     }
5327     while( (m>>32)&0xffe00000 ){
5328       m >>= 1;
5329       e++;
5330     }
5331     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5332       m <<= 1;
5333       e--;
5334     }
5335     e += 1075;
5336     if( e<=0 ){
5337       /* Subnormal */
5338       m >>= 1-e;
5339       e = 0;
5340     }else if( e>0x7ff ){
5341       e = 0x7ff;
5342     }
5343     a = m & ((((sqlite3_int64)1)<<52)-1);
5344     a |= e<<52;
5345     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5346     memcpy(&r, &a, sizeof(r));
5347     sqlite3_result_double(context, r);
5348   }
5349 }
5350
5351 /*
5352 ** Functions to convert between blobs and floats.
5353 */
5354 static void ieee754func_from_blob(
5355   sqlite3_context *context,
5356   int argc,
5357   sqlite3_value **argv
5358 ){
5359   UNUSED_PARAMETER(argc);
5360   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5361    && sqlite3_value_bytes(argv[0])==sizeof(double)
5362   ){
5363     double r;
5364     const unsigned char *x = sqlite3_value_blob(argv[0]);
5365     unsigned int i;
5366     sqlite3_uint64 v = 0;
5367     for(i=0; i<sizeof(r); i++){
5368       v = (v<<8) | x[i];
5369     }
5370     memcpy(&r, &v, sizeof(r));
5371     sqlite3_result_double(context, r);
5372   }
5373 }
5374 static void ieee754func_to_blob(
5375   sqlite3_context *context,
5376   int argc,
5377   sqlite3_value **argv
5378 ){
5379   UNUSED_PARAMETER(argc);
5380   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5381    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5382   ){
5383     double r = sqlite3_value_double(argv[0]);
5384     sqlite3_uint64 v;
5385     unsigned char a[sizeof(r)];
5386     unsigned int i;
5387     memcpy(&v, &r, sizeof(r));
5388     for(i=1; i<=sizeof(r); i++){
5389       a[sizeof(r)-i] = v&0xff;
5390       v >>= 8;
5391     }
5392     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5393   }
5394 }
5395
5396
5397 #ifdef _WIN32
5398
5399 #endif
5400 int sqlite3_ieee_init(
5401   sqlite3 *db, 
5402   char **pzErrMsg, 
5403   const sqlite3_api_routines *pApi
5404 ){
5405   static const struct {
5406     char *zFName;
5407     int nArg;
5408     int iAux;
5409     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5410   } aFunc[] = {
5411     { "ieee754",           1,   0, ieee754func },
5412     { "ieee754",           2,   0, ieee754func },
5413     { "ieee754_mantissa",  1,   1, ieee754func },
5414     { "ieee754_exponent",  1,   2, ieee754func },
5415     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5416     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5417
5418   };
5419   unsigned int i;
5420   int rc = SQLITE_OK;
5421   SQLITE_EXTENSION_INIT2(pApi);
5422   (void)pzErrMsg;  /* Unused parameter */
5423   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5424     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,    
5425                                SQLITE_UTF8|SQLITE_INNOCUOUS,
5426                                (void*)&aFunc[i].iAux,
5427                                aFunc[i].xFunc, 0, 0);
5428   }
5429   return rc;
5430 }
5431
5432 /************************* End ../ext/misc/ieee754.c ********************/
5433 /************************* Begin ../ext/misc/series.c ******************/
5434 /*
5435 ** 2015-08-18
5436 **
5437 ** The author disclaims copyright to this source code.  In place of
5438 ** a legal notice, here is a blessing:
5439 **
5440 **    May you do good and not evil.
5441 **    May you find forgiveness for yourself and forgive others.
5442 **    May you share freely, never taking more than you give.
5443 **
5444 *************************************************************************
5445 **
5446 ** This file demonstrates how to create a table-valued-function using
5447 ** a virtual table.  This demo implements the generate_series() function
5448 ** which gives similar results to the eponymous function in PostgreSQL.
5449 ** Examples:
5450 **
5451 **      SELECT * FROM generate_series(0,100,5);
5452 **
5453 ** The query above returns integers from 0 through 100 counting by steps
5454 ** of 5.
5455 **
5456 **      SELECT * FROM generate_series(0,100);
5457 **
5458 ** Integers from 0 through 100 with a step size of 1.
5459 **
5460 **      SELECT * FROM generate_series(20) LIMIT 10;
5461 **
5462 ** Integers 20 through 29.
5463 **
5464 ** HOW IT WORKS
5465 **
5466 ** The generate_series "function" is really a virtual table with the
5467 ** following schema:
5468 **
5469 **     CREATE TABLE generate_series(
5470 **       value,
5471 **       start HIDDEN,
5472 **       stop HIDDEN,
5473 **       step HIDDEN
5474 **     );
5475 **
5476 ** Function arguments in queries against this virtual table are translated
5477 ** into equality constraints against successive hidden columns.  In other
5478 ** words, the following pairs of queries are equivalent to each other:
5479 **
5480 **    SELECT * FROM generate_series(0,100,5);
5481 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5482 **
5483 **    SELECT * FROM generate_series(0,100);
5484 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5485 **
5486 **    SELECT * FROM generate_series(20) LIMIT 10;
5487 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5488 **
5489 ** The generate_series virtual table implementation leaves the xCreate method
5490 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5491 ** TABLE command with "generate_series" as the USING argument.  Instead, there
5492 ** is a single generate_series virtual table that is always available without
5493 ** having to be created first.
5494 **
5495 ** The xBestIndex method looks for equality constraints against the hidden
5496 ** start, stop, and step columns, and if present, it uses those constraints
5497 ** to bound the sequence of generated values.  If the equality constraints
5498 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5499 ** xBestIndex returns a small cost when both start and stop are available,
5500 ** and a very large cost if either start or stop are unavailable.  This
5501 ** encourages the query planner to order joins such that the bounds of the
5502 ** series are well-defined.
5503 */
5504 /* #include "sqlite3ext.h" */
5505 SQLITE_EXTENSION_INIT1
5506 #include <assert.h>
5507 #include <string.h>
5508
5509 #ifndef SQLITE_OMIT_VIRTUALTABLE
5510
5511
5512 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5513 ** serve as the underlying representation of a cursor that scans
5514 ** over rows of the result
5515 */
5516 typedef struct series_cursor series_cursor;
5517 struct series_cursor {
5518   sqlite3_vtab_cursor base;  /* Base class - must be first */
5519   int isDesc;                /* True to count down rather than up */
5520   sqlite3_int64 iRowid;      /* The rowid */
5521   sqlite3_int64 iValue;      /* Current value ("value") */
5522   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
5523   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
5524   sqlite3_int64 iStep;       /* Increment ("step") */
5525 };
5526
5527 /*
5528 ** The seriesConnect() method is invoked to create a new
5529 ** series_vtab that describes the generate_series virtual table.
5530 **
5531 ** Think of this routine as the constructor for series_vtab objects.
5532 **
5533 ** All this routine needs to do is:
5534 **
5535 **    (1) Allocate the series_vtab object and initialize all fields.
5536 **
5537 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5538 **        result set of queries against generate_series will look like.
5539 */
5540 static int seriesConnect(
5541   sqlite3 *db,
5542   void *pUnused,
5543   int argcUnused, const char *const*argvUnused,
5544   sqlite3_vtab **ppVtab,
5545   char **pzErrUnused
5546 ){
5547   sqlite3_vtab *pNew;
5548   int rc;
5549
5550 /* Column numbers */
5551 #define SERIES_COLUMN_VALUE 0
5552 #define SERIES_COLUMN_START 1
5553 #define SERIES_COLUMN_STOP  2
5554 #define SERIES_COLUMN_STEP  3
5555
5556   (void)pUnused;
5557   (void)argcUnused;
5558   (void)argvUnused;
5559   (void)pzErrUnused;
5560   rc = sqlite3_declare_vtab(db,
5561      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5562   if( rc==SQLITE_OK ){
5563     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5564     if( pNew==0 ) return SQLITE_NOMEM;
5565     memset(pNew, 0, sizeof(*pNew));
5566     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5567   }
5568   return rc;
5569 }
5570
5571 /*
5572 ** This method is the destructor for series_cursor objects.
5573 */
5574 static int seriesDisconnect(sqlite3_vtab *pVtab){
5575   sqlite3_free(pVtab);
5576   return SQLITE_OK;
5577 }
5578
5579 /*
5580 ** Constructor for a new series_cursor object.
5581 */
5582 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5583   series_cursor *pCur;
5584   (void)pUnused;
5585   pCur = sqlite3_malloc( sizeof(*pCur) );
5586   if( pCur==0 ) return SQLITE_NOMEM;
5587   memset(pCur, 0, sizeof(*pCur));
5588   *ppCursor = &pCur->base;
5589   return SQLITE_OK;
5590 }
5591
5592 /*
5593 ** Destructor for a series_cursor.
5594 */
5595 static int seriesClose(sqlite3_vtab_cursor *cur){
5596   sqlite3_free(cur);
5597   return SQLITE_OK;
5598 }
5599
5600
5601 /*
5602 ** Advance a series_cursor to its next row of output.
5603 */
5604 static int seriesNext(sqlite3_vtab_cursor *cur){
5605   series_cursor *pCur = (series_cursor*)cur;
5606   if( pCur->isDesc ){
5607     pCur->iValue -= pCur->iStep;
5608   }else{
5609     pCur->iValue += pCur->iStep;
5610   }
5611   pCur->iRowid++;
5612   return SQLITE_OK;
5613 }
5614
5615 /*
5616 ** Return values of columns for the row at which the series_cursor
5617 ** is currently pointing.
5618 */
5619 static int seriesColumn(
5620   sqlite3_vtab_cursor *cur,   /* The cursor */
5621   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5622   int i                       /* Which column to return */
5623 ){
5624   series_cursor *pCur = (series_cursor*)cur;
5625   sqlite3_int64 x = 0;
5626   switch( i ){
5627     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
5628     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
5629     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
5630     default:                   x = pCur->iValue;  break;
5631   }
5632   sqlite3_result_int64(ctx, x);
5633   return SQLITE_OK;
5634 }
5635
5636 /*
5637 ** Return the rowid for the current row. In this implementation, the
5638 ** first row returned is assigned rowid value 1, and each subsequent
5639 ** row a value 1 more than that of the previous.
5640 */
5641 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5642   series_cursor *pCur = (series_cursor*)cur;
5643   *pRowid = pCur->iRowid;
5644   return SQLITE_OK;
5645 }
5646
5647 /*
5648 ** Return TRUE if the cursor has been moved off of the last
5649 ** row of output.
5650 */
5651 static int seriesEof(sqlite3_vtab_cursor *cur){
5652   series_cursor *pCur = (series_cursor*)cur;
5653   if( pCur->isDesc ){
5654     return pCur->iValue < pCur->mnValue;
5655   }else{
5656     return pCur->iValue > pCur->mxValue;
5657   }
5658 }
5659
5660 /* True to cause run-time checking of the start=, stop=, and/or step= 
5661 ** parameters.  The only reason to do this is for testing the
5662 ** constraint checking logic for virtual tables in the SQLite core.
5663 */
5664 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5665 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5666 #endif
5667
5668 /*
5669 ** This method is called to "rewind" the series_cursor object back
5670 ** to the first row of output.  This method is always called at least
5671 ** once prior to any call to seriesColumn() or seriesRowid() or 
5672 ** seriesEof().
5673 **
5674 ** The query plan selected by seriesBestIndex is passed in the idxNum
5675 ** parameter.  (idxStr is not used in this implementation.)  idxNum
5676 ** is a bitmask showing which constraints are available:
5677 **
5678 **    1:    start=VALUE
5679 **    2:    stop=VALUE
5680 **    4:    step=VALUE
5681 **
5682 ** Also, if bit 8 is set, that means that the series should be output
5683 ** in descending order rather than in ascending order.  If bit 16 is
5684 ** set, then output must appear in ascending order.
5685 **
5686 ** This routine should initialize the cursor and position it so that it
5687 ** is pointing at the first row, or pointing off the end of the table
5688 ** (so that seriesEof() will return true) if the table is empty.
5689 */
5690 static int seriesFilter(
5691   sqlite3_vtab_cursor *pVtabCursor, 
5692   int idxNum, const char *idxStrUnused,
5693   int argc, sqlite3_value **argv
5694 ){
5695   series_cursor *pCur = (series_cursor *)pVtabCursor;
5696   int i = 0;
5697   (void)idxStrUnused;
5698   if( idxNum & 1 ){
5699     pCur->mnValue = sqlite3_value_int64(argv[i++]);
5700   }else{
5701     pCur->mnValue = 0;
5702   }
5703   if( idxNum & 2 ){
5704     pCur->mxValue = sqlite3_value_int64(argv[i++]);
5705   }else{
5706     pCur->mxValue = 0xffffffff;
5707   }
5708   if( idxNum & 4 ){
5709     pCur->iStep = sqlite3_value_int64(argv[i++]);
5710     if( pCur->iStep==0 ){
5711       pCur->iStep = 1;
5712     }else if( pCur->iStep<0 ){
5713       pCur->iStep = -pCur->iStep;
5714       if( (idxNum & 16)==0 ) idxNum |= 8;
5715     }
5716   }else{
5717     pCur->iStep = 1;
5718   }
5719   for(i=0; i<argc; i++){
5720     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
5721       /* If any of the constraints have a NULL value, then return no rows.
5722       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
5723       pCur->mnValue = 1;
5724       pCur->mxValue = 0;
5725       break;
5726     }
5727   }
5728   if( idxNum & 8 ){
5729     pCur->isDesc = 1;
5730     pCur->iValue = pCur->mxValue;
5731     if( pCur->iStep>0 ){
5732       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
5733     }
5734   }else{
5735     pCur->isDesc = 0;
5736     pCur->iValue = pCur->mnValue;
5737   }
5738   pCur->iRowid = 1;
5739   return SQLITE_OK;
5740 }
5741
5742 /*
5743 ** SQLite will invoke this method one or more times while planning a query
5744 ** that uses the generate_series virtual table.  This routine needs to create
5745 ** a query plan for each invocation and compute an estimated cost for that
5746 ** plan.
5747 **
5748 ** In this implementation idxNum is used to represent the
5749 ** query plan.  idxStr is unused.
5750 **
5751 ** The query plan is represented by bits in idxNum:
5752 **
5753 **  (1)  start = $value  -- constraint exists
5754 **  (2)  stop = $value   -- constraint exists
5755 **  (4)  step = $value   -- constraint exists
5756 **  (8)  output in descending order
5757 */
5758 static int seriesBestIndex(
5759   sqlite3_vtab *tabUnused,
5760   sqlite3_index_info *pIdxInfo
5761 ){
5762   int i, j;              /* Loop over constraints */
5763   int idxNum = 0;        /* The query plan bitmask */
5764   int unusableMask = 0;  /* Mask of unusable constraints */
5765   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
5766   int aIdx[3];           /* Constraints on start, stop, and step */
5767   const struct sqlite3_index_constraint *pConstraint;
5768
5769   /* This implementation assumes that the start, stop, and step columns
5770   ** are the last three columns in the virtual table. */
5771   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
5772   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
5773   (void)tabUnused;
5774   aIdx[0] = aIdx[1] = aIdx[2] = -1;
5775   pConstraint = pIdxInfo->aConstraint;
5776   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
5777     int iCol;    /* 0 for start, 1 for stop, 2 for step */
5778     int iMask;   /* bitmask for those column */
5779     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
5780     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
5781     assert( iCol>=0 && iCol<=2 );
5782     iMask = 1 << iCol;
5783     if( pConstraint->usable==0 ){
5784       unusableMask |=  iMask;
5785       continue;
5786     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
5787       idxNum |= iMask;
5788       aIdx[iCol] = i;
5789     }
5790   }
5791   for(i=0; i<3; i++){
5792     if( (j = aIdx[i])>=0 ){
5793       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
5794       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
5795     }
5796   }
5797   if( (unusableMask & ~idxNum)!=0 ){
5798     /* The start, stop, and step columns are inputs.  Therefore if there
5799     ** are unusable constraints on any of start, stop, or step then
5800     ** this plan is unusable */
5801     return SQLITE_CONSTRAINT;
5802   }
5803   if( (idxNum & 3)==3 ){
5804     /* Both start= and stop= boundaries are available.  This is the 
5805     ** the preferred case */
5806     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
5807     pIdxInfo->estimatedRows = 1000;
5808     if( pIdxInfo->nOrderBy==1 ){
5809       if( pIdxInfo->aOrderBy[0].desc ){
5810         idxNum |= 8;
5811       }else{
5812         idxNum |= 16;
5813       }
5814       pIdxInfo->orderByConsumed = 1;
5815     }
5816   }else{
5817     /* If either boundary is missing, we have to generate a huge span
5818     ** of numbers.  Make this case very expensive so that the query
5819     ** planner will work hard to avoid it. */
5820     pIdxInfo->estimatedRows = 2147483647;
5821   }
5822   pIdxInfo->idxNum = idxNum;
5823   return SQLITE_OK;
5824 }
5825
5826 /*
5827 ** This following structure defines all the methods for the 
5828 ** generate_series virtual table.
5829 */
5830 static sqlite3_module seriesModule = {
5831   0,                         /* iVersion */
5832   0,                         /* xCreate */
5833   seriesConnect,             /* xConnect */
5834   seriesBestIndex,           /* xBestIndex */
5835   seriesDisconnect,          /* xDisconnect */
5836   0,                         /* xDestroy */
5837   seriesOpen,                /* xOpen - open a cursor */
5838   seriesClose,               /* xClose - close a cursor */
5839   seriesFilter,              /* xFilter - configure scan constraints */
5840   seriesNext,                /* xNext - advance a cursor */
5841   seriesEof,                 /* xEof - check for end of scan */
5842   seriesColumn,              /* xColumn - read data */
5843   seriesRowid,               /* xRowid - read data */
5844   0,                         /* xUpdate */
5845   0,                         /* xBegin */
5846   0,                         /* xSync */
5847   0,                         /* xCommit */
5848   0,                         /* xRollback */
5849   0,                         /* xFindMethod */
5850   0,                         /* xRename */
5851   0,                         /* xSavepoint */
5852   0,                         /* xRelease */
5853   0,                         /* xRollbackTo */
5854   0                          /* xShadowName */
5855 };
5856
5857 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5858
5859 #ifdef _WIN32
5860
5861 #endif
5862 int sqlite3_series_init(
5863   sqlite3 *db, 
5864   char **pzErrMsg, 
5865   const sqlite3_api_routines *pApi
5866 ){
5867   int rc = SQLITE_OK;
5868   SQLITE_EXTENSION_INIT2(pApi);
5869 #ifndef SQLITE_OMIT_VIRTUALTABLE
5870   if( sqlite3_libversion_number()<3008012 ){
5871     *pzErrMsg = sqlite3_mprintf(
5872         "generate_series() requires SQLite 3.8.12 or later");
5873     return SQLITE_ERROR;
5874   }
5875   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
5876 #endif
5877   return rc;
5878 }
5879
5880 /************************* End ../ext/misc/series.c ********************/
5881 #ifdef SQLITE_HAVE_ZLIB
5882 /************************* Begin ../ext/misc/zipfile.c ******************/
5883 /*
5884 ** 2017-12-26
5885 **
5886 ** The author disclaims copyright to this source code.  In place of
5887 ** a legal notice, here is a blessing:
5888 **
5889 **    May you do good and not evil.
5890 **    May you find forgiveness for yourself and forgive others.
5891 **    May you share freely, never taking more than you give.
5892 **
5893 ******************************************************************************
5894 **
5895 ** This file implements a virtual table for reading and writing ZIP archive
5896 ** files.
5897 **
5898 ** Usage example:
5899 **
5900 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
5901 **
5902 ** Current limitations:
5903 **
5904 **    *  No support for encryption
5905 **    *  No support for ZIP archives spanning multiple files
5906 **    *  No support for zip64 extensions
5907 **    *  Only the "inflate/deflate" (zlib) compression method is supported
5908 */
5909 /* #include "sqlite3ext.h" */
5910 SQLITE_EXTENSION_INIT1
5911 #include <stdio.h>
5912 #include <string.h>
5913 #include <assert.h>
5914
5915 #include <zlib.h>
5916
5917 #ifndef SQLITE_OMIT_VIRTUALTABLE
5918
5919 #ifndef SQLITE_AMALGAMATION
5920
5921 /* typedef sqlite3_int64 i64; */
5922 /* typedef unsigned char u8; */
5923 typedef unsigned short u16;
5924 typedef unsigned long u32;
5925 #define MIN(a,b) ((a)<(b) ? (a) : (b))
5926
5927 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
5928 # define ALWAYS(X)      (1)
5929 # define NEVER(X)       (0)
5930 #elif !defined(NDEBUG)
5931 # define ALWAYS(X)      ((X)?1:(assert(0),0))
5932 # define NEVER(X)       ((X)?(assert(0),1):0)
5933 #else
5934 # define ALWAYS(X)      (X)
5935 # define NEVER(X)       (X)
5936 #endif
5937
5938 #endif   /* SQLITE_AMALGAMATION */
5939
5940 /*
5941 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
5942 **
5943 ** In some ways it would be better to obtain these values from system 
5944 ** header files. But, the dependency is undesirable and (a) these
5945 ** have been stable for decades, (b) the values are part of POSIX and
5946 ** are also made explicit in [man stat], and (c) are part of the 
5947 ** file format for zip archives.
5948 */
5949 #ifndef S_IFDIR
5950 # define S_IFDIR 0040000
5951 #endif
5952 #ifndef S_IFREG
5953 # define S_IFREG 0100000
5954 #endif
5955 #ifndef S_IFLNK
5956 # define S_IFLNK 0120000
5957 #endif
5958
5959 static const char ZIPFILE_SCHEMA[] = 
5960   "CREATE TABLE y("
5961     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
5962     "mode,"              /* 1: POSIX mode for file */
5963     "mtime,"             /* 2: Last modification time (secs since 1970)*/
5964     "sz,"                /* 3: Size of object */
5965     "rawdata,"           /* 4: Raw data */
5966     "data,"              /* 5: Uncompressed data */
5967     "method,"            /* 6: Compression method (integer) */
5968     "z HIDDEN"           /* 7: Name of zip file */
5969   ") WITHOUT ROWID;";
5970
5971 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
5972 #define ZIPFILE_BUFFER_SIZE (64*1024)
5973
5974
5975 /*
5976 ** Magic numbers used to read and write zip files.
5977 **
5978 ** ZIPFILE_NEWENTRY_MADEBY:
5979 **   Use this value for the "version-made-by" field in new zip file
5980 **   entries. The upper byte indicates "unix", and the lower byte 
5981 **   indicates that the zip file matches pkzip specification 3.0. 
5982 **   This is what info-zip seems to do.
5983 **
5984 ** ZIPFILE_NEWENTRY_REQUIRED:
5985 **   Value for "version-required-to-extract" field of new entries.
5986 **   Version 2.0 is required to support folders and deflate compression.
5987 **
5988 ** ZIPFILE_NEWENTRY_FLAGS:
5989 **   Value for "general-purpose-bit-flags" field of new entries. Bit
5990 **   11 means "utf-8 filename and comment".
5991 **
5992 ** ZIPFILE_SIGNATURE_CDS:
5993 **   First 4 bytes of a valid CDS record.
5994 **
5995 ** ZIPFILE_SIGNATURE_LFH:
5996 **   First 4 bytes of a valid LFH record.
5997 **
5998 ** ZIPFILE_SIGNATURE_EOCD
5999 **   First 4 bytes of a valid EOCD record.
6000 */
6001 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
6002 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
6003 #define ZIPFILE_NEWENTRY_REQUIRED 20
6004 #define ZIPFILE_NEWENTRY_FLAGS    0x800
6005 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
6006 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
6007 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
6008
6009 /*
6010 ** The sizes of the fixed-size part of each of the three main data 
6011 ** structures in a zip archive.
6012 */
6013 #define ZIPFILE_LFH_FIXED_SZ      30
6014 #define ZIPFILE_EOCD_FIXED_SZ     22
6015 #define ZIPFILE_CDS_FIXED_SZ      46
6016
6017 /*
6018 *** 4.3.16  End of central directory record:
6019 ***
6020 ***   end of central dir signature    4 bytes  (0x06054b50)
6021 ***   number of this disk             2 bytes
6022 ***   number of the disk with the
6023 ***   start of the central directory  2 bytes
6024 ***   total number of entries in the
6025 ***   central directory on this disk  2 bytes
6026 ***   total number of entries in
6027 ***   the central directory           2 bytes
6028 ***   size of the central directory   4 bytes
6029 ***   offset of start of central
6030 ***   directory with respect to
6031 ***   the starting disk number        4 bytes
6032 ***   .ZIP file comment length        2 bytes
6033 ***   .ZIP file comment       (variable size)
6034 */
6035 typedef struct ZipfileEOCD ZipfileEOCD;
6036 struct ZipfileEOCD {
6037   u16 iDisk;
6038   u16 iFirstDisk;
6039   u16 nEntry;
6040   u16 nEntryTotal;
6041   u32 nSize;
6042   u32 iOffset;
6043 };
6044
6045 /*
6046 *** 4.3.12  Central directory structure:
6047 ***
6048 *** ...
6049 ***
6050 ***   central file header signature   4 bytes  (0x02014b50)
6051 ***   version made by                 2 bytes
6052 ***   version needed to extract       2 bytes
6053 ***   general purpose bit flag        2 bytes
6054 ***   compression method              2 bytes
6055 ***   last mod file time              2 bytes
6056 ***   last mod file date              2 bytes
6057 ***   crc-32                          4 bytes
6058 ***   compressed size                 4 bytes
6059 ***   uncompressed size               4 bytes
6060 ***   file name length                2 bytes
6061 ***   extra field length              2 bytes
6062 ***   file comment length             2 bytes
6063 ***   disk number start               2 bytes
6064 ***   internal file attributes        2 bytes
6065 ***   external file attributes        4 bytes
6066 ***   relative offset of local header 4 bytes
6067 */
6068 typedef struct ZipfileCDS ZipfileCDS;
6069 struct ZipfileCDS {
6070   u16 iVersionMadeBy;
6071   u16 iVersionExtract;
6072   u16 flags;
6073   u16 iCompression;
6074   u16 mTime;
6075   u16 mDate;
6076   u32 crc32;
6077   u32 szCompressed;
6078   u32 szUncompressed;
6079   u16 nFile;
6080   u16 nExtra;
6081   u16 nComment;
6082   u16 iDiskStart;
6083   u16 iInternalAttr;
6084   u32 iExternalAttr;
6085   u32 iOffset;
6086   char *zFile;                    /* Filename (sqlite3_malloc()) */
6087 };
6088
6089 /*
6090 *** 4.3.7  Local file header:
6091 ***
6092 ***   local file header signature     4 bytes  (0x04034b50)
6093 ***   version needed to extract       2 bytes
6094 ***   general purpose bit flag        2 bytes
6095 ***   compression method              2 bytes
6096 ***   last mod file time              2 bytes
6097 ***   last mod file date              2 bytes
6098 ***   crc-32                          4 bytes
6099 ***   compressed size                 4 bytes
6100 ***   uncompressed size               4 bytes
6101 ***   file name length                2 bytes
6102 ***   extra field length              2 bytes
6103 ***   
6104 */
6105 typedef struct ZipfileLFH ZipfileLFH;
6106 struct ZipfileLFH {
6107   u16 iVersionExtract;
6108   u16 flags;
6109   u16 iCompression;
6110   u16 mTime;
6111   u16 mDate;
6112   u32 crc32;
6113   u32 szCompressed;
6114   u32 szUncompressed;
6115   u16 nFile;
6116   u16 nExtra;
6117 };
6118
6119 typedef struct ZipfileEntry ZipfileEntry;
6120 struct ZipfileEntry {
6121   ZipfileCDS cds;            /* Parsed CDS record */
6122   u32 mUnixTime;             /* Modification time, in UNIX format */
6123   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
6124   i64 iDataOff;              /* Offset to data in file (if aData==0) */
6125   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
6126   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
6127 };
6128
6129 /* 
6130 ** Cursor type for zipfile tables.
6131 */
6132 typedef struct ZipfileCsr ZipfileCsr;
6133 struct ZipfileCsr {
6134   sqlite3_vtab_cursor base;  /* Base class - must be first */
6135   i64 iId;                   /* Cursor ID */
6136   u8 bEof;                   /* True when at EOF */
6137   u8 bNoop;                  /* If next xNext() call is no-op */
6138
6139   /* Used outside of write transactions */
6140   FILE *pFile;               /* Zip file */
6141   i64 iNextOff;              /* Offset of next record in central directory */
6142   ZipfileEOCD eocd;          /* Parse of central directory record */
6143
6144   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
6145   ZipfileEntry *pCurrent;    /* Current entry */
6146   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
6147 };
6148
6149 typedef struct ZipfileTab ZipfileTab;
6150 struct ZipfileTab {
6151   sqlite3_vtab base;         /* Base class - must be first */
6152   char *zFile;               /* Zip file this table accesses (may be NULL) */
6153   sqlite3 *db;               /* Host database connection */
6154   u8 *aBuffer;               /* Temporary buffer used for various tasks */
6155
6156   ZipfileCsr *pCsrList;      /* List of cursors */
6157   i64 iNextCsrid;
6158
6159   /* The following are used by write transactions only */
6160   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
6161   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
6162   FILE *pWriteFd;            /* File handle open on zip archive */
6163   i64 szCurrent;             /* Current size of zip archive */
6164   i64 szOrig;                /* Size of archive at start of transaction */
6165 };
6166
6167 /*
6168 ** Set the error message contained in context ctx to the results of
6169 ** vprintf(zFmt, ...).
6170 */
6171 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
6172   char *zMsg = 0;
6173   va_list ap;
6174   va_start(ap, zFmt);
6175   zMsg = sqlite3_vmprintf(zFmt, ap);
6176   sqlite3_result_error(ctx, zMsg, -1);
6177   sqlite3_free(zMsg);
6178   va_end(ap);
6179 }
6180
6181 /*
6182 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
6183 ** is not quoted, do nothing.
6184 */
6185 static void zipfileDequote(char *zIn){
6186   char q = zIn[0];
6187   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
6188     int iIn = 1;
6189     int iOut = 0;
6190     if( q=='[' ) q = ']';
6191     while( ALWAYS(zIn[iIn]) ){
6192       char c = zIn[iIn++];
6193       if( c==q && zIn[iIn++]!=q ) break;
6194       zIn[iOut++] = c;
6195     }
6196     zIn[iOut] = '\0';
6197   }
6198 }
6199
6200 /*
6201 ** Construct a new ZipfileTab virtual table object.
6202 ** 
6203 **   argv[0]   -> module name  ("zipfile")
6204 **   argv[1]   -> database name
6205 **   argv[2]   -> table name
6206 **   argv[...] -> "column name" and other module argument fields.
6207 */
6208 static int zipfileConnect(
6209   sqlite3 *db,
6210   void *pAux,
6211   int argc, const char *const*argv,
6212   sqlite3_vtab **ppVtab,
6213   char **pzErr
6214 ){
6215   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
6216   int nFile = 0;
6217   const char *zFile = 0;
6218   ZipfileTab *pNew = 0;
6219   int rc;
6220
6221   /* If the table name is not "zipfile", require that the argument be
6222   ** specified. This stops zipfile tables from being created as:
6223   **
6224   **   CREATE VIRTUAL TABLE zzz USING zipfile();
6225   **
6226   ** It does not prevent:
6227   **
6228   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
6229   */
6230   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
6231   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
6232     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
6233     return SQLITE_ERROR;
6234   }
6235
6236   if( argc>3 ){
6237     zFile = argv[3];
6238     nFile = (int)strlen(zFile)+1;
6239   }
6240
6241   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
6242   if( rc==SQLITE_OK ){
6243     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
6244     if( pNew==0 ) return SQLITE_NOMEM;
6245     memset(pNew, 0, nByte+nFile);
6246     pNew->db = db;
6247     pNew->aBuffer = (u8*)&pNew[1];
6248     if( zFile ){
6249       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
6250       memcpy(pNew->zFile, zFile, nFile);
6251       zipfileDequote(pNew->zFile);
6252     }
6253   }
6254   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
6255   *ppVtab = (sqlite3_vtab*)pNew;
6256   return rc;
6257 }
6258
6259 /*
6260 ** Free the ZipfileEntry structure indicated by the only argument.
6261 */
6262 static void zipfileEntryFree(ZipfileEntry *p){
6263   if( p ){
6264     sqlite3_free(p->cds.zFile);
6265     sqlite3_free(p);
6266   }
6267 }
6268
6269 /*
6270 ** Release resources that should be freed at the end of a write 
6271 ** transaction.
6272 */
6273 static void zipfileCleanupTransaction(ZipfileTab *pTab){
6274   ZipfileEntry *pEntry;
6275   ZipfileEntry *pNext;
6276
6277   if( pTab->pWriteFd ){
6278     fclose(pTab->pWriteFd);
6279     pTab->pWriteFd = 0;
6280   }
6281   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
6282     pNext = pEntry->pNext;
6283     zipfileEntryFree(pEntry);
6284   }
6285   pTab->pFirstEntry = 0;
6286   pTab->pLastEntry = 0;
6287   pTab->szCurrent = 0;
6288   pTab->szOrig = 0;
6289 }
6290
6291 /*
6292 ** This method is the destructor for zipfile vtab objects.
6293 */
6294 static int zipfileDisconnect(sqlite3_vtab *pVtab){
6295   zipfileCleanupTransaction((ZipfileTab*)pVtab);
6296   sqlite3_free(pVtab);
6297   return SQLITE_OK;
6298 }
6299
6300 /*
6301 ** Constructor for a new ZipfileCsr object.
6302 */
6303 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
6304   ZipfileTab *pTab = (ZipfileTab*)p;
6305   ZipfileCsr *pCsr;
6306   pCsr = sqlite3_malloc(sizeof(*pCsr));
6307   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
6308   if( pCsr==0 ){
6309     return SQLITE_NOMEM;
6310   }
6311   memset(pCsr, 0, sizeof(*pCsr));
6312   pCsr->iId = ++pTab->iNextCsrid;
6313   pCsr->pCsrNext = pTab->pCsrList;
6314   pTab->pCsrList = pCsr;
6315   return SQLITE_OK;
6316 }
6317
6318 /*
6319 ** Reset a cursor back to the state it was in when first returned
6320 ** by zipfileOpen().
6321 */
6322 static void zipfileResetCursor(ZipfileCsr *pCsr){
6323   ZipfileEntry *p;
6324   ZipfileEntry *pNext;
6325
6326   pCsr->bEof = 0;
6327   if( pCsr->pFile ){
6328     fclose(pCsr->pFile);
6329     pCsr->pFile = 0;
6330     zipfileEntryFree(pCsr->pCurrent);
6331     pCsr->pCurrent = 0;
6332   }
6333
6334   for(p=pCsr->pFreeEntry; p; p=pNext){
6335     pNext = p->pNext;
6336     zipfileEntryFree(p);
6337   }
6338 }
6339
6340 /*
6341 ** Destructor for an ZipfileCsr.
6342 */
6343 static int zipfileClose(sqlite3_vtab_cursor *cur){
6344   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6345   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
6346   ZipfileCsr **pp;
6347   zipfileResetCursor(pCsr);
6348
6349   /* Remove this cursor from the ZipfileTab.pCsrList list. */
6350   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
6351   *pp = pCsr->pCsrNext;
6352
6353   sqlite3_free(pCsr);
6354   return SQLITE_OK;
6355 }
6356
6357 /*
6358 ** Set the error message for the virtual table associated with cursor
6359 ** pCsr to the results of vprintf(zFmt, ...).
6360 */
6361 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
6362   va_list ap;
6363   va_start(ap, zFmt);
6364   sqlite3_free(pTab->base.zErrMsg);
6365   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
6366   va_end(ap);
6367 }
6368 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
6369   va_list ap;
6370   va_start(ap, zFmt);
6371   sqlite3_free(pCsr->base.pVtab->zErrMsg);
6372   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
6373   va_end(ap);
6374 }
6375
6376 /*
6377 ** Read nRead bytes of data from offset iOff of file pFile into buffer
6378 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
6379 ** otherwise. 
6380 **
6381 ** If an error does occur, output variable (*pzErrmsg) may be set to point
6382 ** to an English language error message. It is the responsibility of the
6383 ** caller to eventually free this buffer using
6384 ** sqlite3_free().
6385 */
6386 static int zipfileReadData(
6387   FILE *pFile,                    /* Read from this file */
6388   u8 *aRead,                      /* Read into this buffer */
6389   int nRead,                      /* Number of bytes to read */
6390   i64 iOff,                       /* Offset to read from */
6391   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
6392 ){
6393   size_t n;
6394   fseek(pFile, (long)iOff, SEEK_SET);
6395   n = fread(aRead, 1, nRead, pFile);
6396   if( (int)n!=nRead ){
6397     *pzErrmsg = sqlite3_mprintf("error in fread()");
6398     return SQLITE_ERROR;
6399   }
6400   return SQLITE_OK;
6401 }
6402
6403 static int zipfileAppendData(
6404   ZipfileTab *pTab,
6405   const u8 *aWrite,
6406   int nWrite
6407 ){
6408   if( nWrite>0 ){
6409     size_t n = nWrite;
6410     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
6411     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
6412     if( (int)n!=nWrite ){
6413       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
6414       return SQLITE_ERROR;
6415     }
6416     pTab->szCurrent += nWrite;
6417   }
6418   return SQLITE_OK;
6419 }
6420
6421 /*
6422 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
6423 */
6424 static u16 zipfileGetU16(const u8 *aBuf){
6425   return (aBuf[1] << 8) + aBuf[0];
6426 }
6427
6428 /*
6429 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
6430 */
6431 static u32 zipfileGetU32(const u8 *aBuf){
6432   return ((u32)(aBuf[3]) << 24)
6433        + ((u32)(aBuf[2]) << 16)
6434        + ((u32)(aBuf[1]) <<  8)
6435        + ((u32)(aBuf[0]) <<  0);
6436 }
6437
6438 /*
6439 ** Write a 16-bit little endiate integer into buffer aBuf.
6440 */
6441 static void zipfilePutU16(u8 *aBuf, u16 val){
6442   aBuf[0] = val & 0xFF;
6443   aBuf[1] = (val>>8) & 0xFF;
6444 }
6445
6446 /*
6447 ** Write a 32-bit little endiate integer into buffer aBuf.
6448 */
6449 static void zipfilePutU32(u8 *aBuf, u32 val){
6450   aBuf[0] = val & 0xFF;
6451   aBuf[1] = (val>>8) & 0xFF;
6452   aBuf[2] = (val>>16) & 0xFF;
6453   aBuf[3] = (val>>24) & 0xFF;
6454 }
6455
6456 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
6457 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
6458
6459 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
6460 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
6461
6462 /*
6463 ** Magic numbers used to read CDS records.
6464 */
6465 #define ZIPFILE_CDS_NFILE_OFF        28
6466 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
6467
6468 /*
6469 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
6470 ** if the record is not well-formed, or SQLITE_OK otherwise.
6471 */
6472 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
6473   u8 *aRead = aBuf;
6474   u32 sig = zipfileRead32(aRead);
6475   int rc = SQLITE_OK;
6476   if( sig!=ZIPFILE_SIGNATURE_CDS ){
6477     rc = SQLITE_ERROR;
6478   }else{
6479     pCDS->iVersionMadeBy = zipfileRead16(aRead);
6480     pCDS->iVersionExtract = zipfileRead16(aRead);
6481     pCDS->flags = zipfileRead16(aRead);
6482     pCDS->iCompression = zipfileRead16(aRead);
6483     pCDS->mTime = zipfileRead16(aRead);
6484     pCDS->mDate = zipfileRead16(aRead);
6485     pCDS->crc32 = zipfileRead32(aRead);
6486     pCDS->szCompressed = zipfileRead32(aRead);
6487     pCDS->szUncompressed = zipfileRead32(aRead);
6488     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
6489     pCDS->nFile = zipfileRead16(aRead);
6490     pCDS->nExtra = zipfileRead16(aRead);
6491     pCDS->nComment = zipfileRead16(aRead);
6492     pCDS->iDiskStart = zipfileRead16(aRead);
6493     pCDS->iInternalAttr = zipfileRead16(aRead);
6494     pCDS->iExternalAttr = zipfileRead32(aRead);
6495     pCDS->iOffset = zipfileRead32(aRead);
6496     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
6497   }
6498
6499   return rc;
6500 }
6501
6502 /*
6503 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
6504 ** if the record is not well-formed, or SQLITE_OK otherwise.
6505 */
6506 static int zipfileReadLFH(
6507   u8 *aBuffer,
6508   ZipfileLFH *pLFH
6509 ){
6510   u8 *aRead = aBuffer;
6511   int rc = SQLITE_OK;
6512
6513   u32 sig = zipfileRead32(aRead);
6514   if( sig!=ZIPFILE_SIGNATURE_LFH ){
6515     rc = SQLITE_ERROR;
6516   }else{
6517     pLFH->iVersionExtract = zipfileRead16(aRead);
6518     pLFH->flags = zipfileRead16(aRead);
6519     pLFH->iCompression = zipfileRead16(aRead);
6520     pLFH->mTime = zipfileRead16(aRead);
6521     pLFH->mDate = zipfileRead16(aRead);
6522     pLFH->crc32 = zipfileRead32(aRead);
6523     pLFH->szCompressed = zipfileRead32(aRead);
6524     pLFH->szUncompressed = zipfileRead32(aRead);
6525     pLFH->nFile = zipfileRead16(aRead);
6526     pLFH->nExtra = zipfileRead16(aRead);
6527   }
6528   return rc;
6529 }
6530
6531
6532 /*
6533 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
6534 ** Scan through this buffer to find an "extra-timestamp" field. If one
6535 ** exists, extract the 32-bit modification-timestamp from it and store
6536 ** the value in output parameter *pmTime.
6537 **
6538 ** Zero is returned if no extra-timestamp record could be found (and so
6539 ** *pmTime is left unchanged), or non-zero otherwise.
6540 **
6541 ** The general format of an extra field is:
6542 **
6543 **   Header ID    2 bytes
6544 **   Data Size    2 bytes
6545 **   Data         N bytes
6546 */
6547 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
6548   int ret = 0;
6549   u8 *p = aExtra;
6550   u8 *pEnd = &aExtra[nExtra];
6551
6552   while( p<pEnd ){
6553     u16 id = zipfileRead16(p);
6554     u16 nByte = zipfileRead16(p);
6555
6556     switch( id ){
6557       case ZIPFILE_EXTRA_TIMESTAMP: {
6558         u8 b = p[0];
6559         if( b & 0x01 ){     /* 0x01 -> modtime is present */
6560           *pmTime = zipfileGetU32(&p[1]);
6561           ret = 1;
6562         }
6563         break;
6564       }
6565     }
6566
6567     p += nByte;
6568   }
6569   return ret;
6570 }
6571
6572 /*
6573 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
6574 ** fields of the CDS structure passed as the only argument to a 32-bit
6575 ** UNIX seconds-since-the-epoch timestamp. Return the result.
6576 **
6577 ** "Standard" MS-DOS time format:
6578 **
6579 **   File modification time:
6580 **     Bits 00-04: seconds divided by 2
6581 **     Bits 05-10: minute
6582 **     Bits 11-15: hour
6583 **   File modification date:
6584 **     Bits 00-04: day
6585 **     Bits 05-08: month (1-12)
6586 **     Bits 09-15: years from 1980 
6587 **
6588 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
6589 */
6590 static u32 zipfileMtime(ZipfileCDS *pCDS){
6591   int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
6592   int M = ((pCDS->mDate >> 5) & 0x0F);
6593   int D = (pCDS->mDate & 0x1F);
6594   int B = -13;
6595
6596   int sec = (pCDS->mTime & 0x1F)*2;
6597   int min = (pCDS->mTime >> 5) & 0x3F;
6598   int hr = (pCDS->mTime >> 11) & 0x1F;
6599   i64 JD;
6600
6601   /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
6602
6603   /* Calculate the JD in seconds for noon on the day in question */
6604   if( M<3 ){
6605     Y = Y-1;
6606     M = M+12;
6607   }
6608   JD = (i64)(24*60*60) * (
6609       (int)(365.25 * (Y + 4716))
6610     + (int)(30.6001 * (M + 1))
6611     + D + B - 1524
6612   );
6613
6614   /* Correct the JD for the time within the day */
6615   JD += (hr-12) * 3600 + min * 60 + sec;
6616
6617   /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
6618   return (u32)(JD - (i64)(24405875) * 24*60*6);
6619 }
6620
6621 /*
6622 ** The opposite of zipfileMtime(). This function populates the mTime and
6623 ** mDate fields of the CDS structure passed as the first argument according
6624 ** to the UNIX timestamp value passed as the second.
6625 */
6626 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
6627   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
6628   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
6629
6630   int A, B, C, D, E;
6631   int yr, mon, day;
6632   int hr, min, sec;
6633
6634   A = (int)((JD - 1867216.25)/36524.25);
6635   A = (int)(JD + 1 + A - (A/4));
6636   B = A + 1524;
6637   C = (int)((B - 122.1)/365.25);
6638   D = (36525*(C&32767))/100;
6639   E = (int)((B-D)/30.6001);
6640
6641   day = B - D - (int)(30.6001*E);
6642   mon = (E<14 ? E-1 : E-13);
6643   yr = mon>2 ? C-4716 : C-4715;
6644
6645   hr = (mUnixTime % (24*60*60)) / (60*60);
6646   min = (mUnixTime % (60*60)) / 60;
6647   sec = (mUnixTime % 60);
6648
6649   if( yr>=1980 ){
6650     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
6651     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
6652   }else{
6653     pCds->mDate = pCds->mTime = 0;
6654   }
6655
6656   assert( mUnixTime<315507600 
6657        || mUnixTime==zipfileMtime(pCds) 
6658        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) 
6659        /* || (mUnixTime % 2) */
6660   );
6661 }
6662
6663 /*
6664 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
6665 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
6666 ** then pFile is a file-handle open on a zip file. In either case, this
6667 ** function creates a ZipfileEntry object based on the zip archive entry
6668 ** for which the CDS record is at offset iOff.
6669 **
6670 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
6671 ** the new object. Otherwise, an SQLite error code is returned and the
6672 ** final value of (*ppEntry) undefined.
6673 */
6674 static int zipfileGetEntry(
6675   ZipfileTab *pTab,               /* Store any error message here */
6676   const u8 *aBlob,                /* Pointer to in-memory file image */
6677   int nBlob,                      /* Size of aBlob[] in bytes */
6678   FILE *pFile,                    /* If aBlob==0, read from this file */
6679   i64 iOff,                       /* Offset of CDS record */
6680   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
6681 ){
6682   u8 *aRead;
6683   char **pzErr = &pTab->base.zErrMsg;
6684   int rc = SQLITE_OK;
6685
6686   if( aBlob==0 ){
6687     aRead = pTab->aBuffer;
6688     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
6689   }else{
6690     aRead = (u8*)&aBlob[iOff];
6691   }
6692
6693   if( rc==SQLITE_OK ){
6694     sqlite3_int64 nAlloc;
6695     ZipfileEntry *pNew;
6696
6697     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
6698     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
6699     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
6700
6701     nAlloc = sizeof(ZipfileEntry) + nExtra;
6702     if( aBlob ){
6703       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
6704     }
6705
6706     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
6707     if( pNew==0 ){
6708       rc = SQLITE_NOMEM;
6709     }else{
6710       memset(pNew, 0, sizeof(ZipfileEntry));
6711       rc = zipfileReadCDS(aRead, &pNew->cds);
6712       if( rc!=SQLITE_OK ){
6713         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
6714       }else if( aBlob==0 ){
6715         rc = zipfileReadData(
6716             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
6717         );
6718       }else{
6719         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
6720       }
6721     }
6722
6723     if( rc==SQLITE_OK ){
6724       u32 *pt = &pNew->mUnixTime;
6725       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); 
6726       pNew->aExtra = (u8*)&pNew[1];
6727       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
6728       if( pNew->cds.zFile==0 ){
6729         rc = SQLITE_NOMEM;
6730       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
6731         pNew->mUnixTime = zipfileMtime(&pNew->cds);
6732       }
6733     }
6734
6735     if( rc==SQLITE_OK ){
6736       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
6737       ZipfileLFH lfh;
6738       if( pFile ){
6739         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
6740       }else{
6741         aRead = (u8*)&aBlob[pNew->cds.iOffset];
6742       }
6743
6744       rc = zipfileReadLFH(aRead, &lfh);
6745       if( rc==SQLITE_OK ){
6746         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
6747         pNew->iDataOff += lfh.nFile + lfh.nExtra;
6748         if( aBlob && pNew->cds.szCompressed ){
6749           pNew->aData = &pNew->aExtra[nExtra];
6750           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
6751         }
6752       }else{
6753         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", 
6754             (int)pNew->cds.iOffset
6755         );
6756       }
6757     }
6758
6759     if( rc!=SQLITE_OK ){
6760       zipfileEntryFree(pNew);
6761     }else{
6762       *ppEntry = pNew;
6763     }
6764   }
6765
6766   return rc;
6767 }
6768
6769 /*
6770 ** Advance an ZipfileCsr to its next row of output.
6771 */
6772 static int zipfileNext(sqlite3_vtab_cursor *cur){
6773   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6774   int rc = SQLITE_OK;
6775
6776   if( pCsr->pFile ){
6777     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
6778     zipfileEntryFree(pCsr->pCurrent);
6779     pCsr->pCurrent = 0;
6780     if( pCsr->iNextOff>=iEof ){
6781       pCsr->bEof = 1;
6782     }else{
6783       ZipfileEntry *p = 0;
6784       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
6785       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
6786       if( rc==SQLITE_OK ){
6787         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
6788         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
6789       }
6790       pCsr->pCurrent = p;
6791     }
6792   }else{
6793     if( !pCsr->bNoop ){
6794       pCsr->pCurrent = pCsr->pCurrent->pNext;
6795     }
6796     if( pCsr->pCurrent==0 ){
6797       pCsr->bEof = 1;
6798     }
6799   }
6800
6801   pCsr->bNoop = 0;
6802   return rc;
6803 }
6804
6805 static void zipfileFree(void *p) { 
6806   sqlite3_free(p); 
6807 }
6808
6809 /*
6810 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
6811 ** size is nOut bytes. This function uncompresses the data and sets the
6812 ** return value in context pCtx to the result (a blob).
6813 **
6814 ** If an error occurs, an error code is left in pCtx instead.
6815 */
6816 static void zipfileInflate(
6817   sqlite3_context *pCtx,          /* Store result here */
6818   const u8 *aIn,                  /* Compressed data */
6819   int nIn,                        /* Size of buffer aIn[] in bytes */
6820   int nOut                        /* Expected output size */
6821 ){
6822   u8 *aRes = sqlite3_malloc(nOut);
6823   if( aRes==0 ){
6824     sqlite3_result_error_nomem(pCtx);
6825   }else{
6826     int err;
6827     z_stream str;
6828     memset(&str, 0, sizeof(str));
6829
6830     str.next_in = (Byte*)aIn;
6831     str.avail_in = nIn;
6832     str.next_out = (Byte*)aRes;
6833     str.avail_out = nOut;
6834
6835     err = inflateInit2(&str, -15);
6836     if( err!=Z_OK ){
6837       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
6838     }else{
6839       err = inflate(&str, Z_NO_FLUSH);
6840       if( err!=Z_STREAM_END ){
6841         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
6842       }else{
6843         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
6844         aRes = 0;
6845       }
6846     }
6847     sqlite3_free(aRes);
6848     inflateEnd(&str);
6849   }
6850 }
6851
6852 /*
6853 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
6854 ** compresses it and sets (*ppOut) to point to a buffer containing the
6855 ** compressed data. The caller is responsible for eventually calling
6856 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) 
6857 ** is set to the size of buffer (*ppOut) in bytes.
6858 **
6859 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
6860 ** code is returned and an error message left in virtual-table handle
6861 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
6862 ** case.
6863 */
6864 static int zipfileDeflate(
6865   const u8 *aIn, int nIn,         /* Input */
6866   u8 **ppOut, int *pnOut,         /* Output */
6867   char **pzErr                    /* OUT: Error message */
6868 ){
6869   int rc = SQLITE_OK;
6870   sqlite3_int64 nAlloc;
6871   z_stream str;
6872   u8 *aOut;
6873
6874   memset(&str, 0, sizeof(str));
6875   str.next_in = (Bytef*)aIn;
6876   str.avail_in = nIn;
6877   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
6878
6879   nAlloc = deflateBound(&str, nIn);
6880   aOut = (u8*)sqlite3_malloc64(nAlloc);
6881   if( aOut==0 ){
6882     rc = SQLITE_NOMEM;
6883   }else{
6884     int res;
6885     str.next_out = aOut;
6886     str.avail_out = nAlloc;
6887     res = deflate(&str, Z_FINISH);
6888     if( res==Z_STREAM_END ){
6889       *ppOut = aOut;
6890       *pnOut = (int)str.total_out;
6891     }else{
6892       sqlite3_free(aOut);
6893       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
6894       rc = SQLITE_ERROR;
6895     }
6896     deflateEnd(&str);
6897   }
6898
6899   return rc;
6900 }
6901
6902
6903 /*
6904 ** Return values of columns for the row at which the series_cursor
6905 ** is currently pointing.
6906 */
6907 static int zipfileColumn(
6908   sqlite3_vtab_cursor *cur,   /* The cursor */
6909   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6910   int i                       /* Which column to return */
6911 ){
6912   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6913   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
6914   int rc = SQLITE_OK;
6915   switch( i ){
6916     case 0:   /* name */
6917       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
6918       break;
6919     case 1:   /* mode */
6920       /* TODO: Whether or not the following is correct surely depends on
6921       ** the platform on which the archive was created.  */
6922       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
6923       break;
6924     case 2: { /* mtime */
6925       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
6926       break;
6927     }
6928     case 3: { /* sz */
6929       if( sqlite3_vtab_nochange(ctx)==0 ){
6930         sqlite3_result_int64(ctx, pCDS->szUncompressed);
6931       }
6932       break;
6933     }
6934     case 4:   /* rawdata */
6935       if( sqlite3_vtab_nochange(ctx) ) break;
6936     case 5: { /* data */
6937       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
6938         int sz = pCDS->szCompressed;
6939         int szFinal = pCDS->szUncompressed;
6940         if( szFinal>0 ){
6941           u8 *aBuf;
6942           u8 *aFree = 0;
6943           if( pCsr->pCurrent->aData ){
6944             aBuf = pCsr->pCurrent->aData;
6945           }else{
6946             aBuf = aFree = sqlite3_malloc64(sz);
6947             if( aBuf==0 ){
6948               rc = SQLITE_NOMEM;
6949             }else{
6950               FILE *pFile = pCsr->pFile;
6951               if( pFile==0 ){
6952                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
6953               }
6954               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
6955                   &pCsr->base.pVtab->zErrMsg
6956               );
6957             }
6958           }
6959           if( rc==SQLITE_OK ){
6960             if( i==5 && pCDS->iCompression ){
6961               zipfileInflate(ctx, aBuf, sz, szFinal);
6962             }else{
6963               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
6964             }
6965           }
6966           sqlite3_free(aFree);
6967         }else{
6968           /* Figure out if this is a directory or a zero-sized file. Consider
6969           ** it to be a directory either if the mode suggests so, or if
6970           ** the final character in the name is '/'.  */
6971           u32 mode = pCDS->iExternalAttr >> 16;
6972           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
6973             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
6974           }
6975         }
6976       }
6977       break;
6978     }
6979     case 6:   /* method */
6980       sqlite3_result_int(ctx, pCDS->iCompression);
6981       break;
6982     default:  /* z */
6983       assert( i==7 );
6984       sqlite3_result_int64(ctx, pCsr->iId);
6985       break;
6986   }
6987
6988   return rc;
6989 }
6990
6991 /*
6992 ** Return TRUE if the cursor is at EOF.
6993 */
6994 static int zipfileEof(sqlite3_vtab_cursor *cur){
6995   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6996   return pCsr->bEof;
6997 }
6998
6999 /*
7000 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
7001 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
7002 ** is guaranteed to be a file-handle open on a zip file.
7003 **
7004 ** This function attempts to locate the EOCD record within the zip archive
7005 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
7006 ** returned if successful. Otherwise, an SQLite error code is returned and
7007 ** an English language error message may be left in virtual-table pTab.
7008 */
7009 static int zipfileReadEOCD(
7010   ZipfileTab *pTab,               /* Return errors here */
7011   const u8 *aBlob,                /* Pointer to in-memory file image */
7012   int nBlob,                      /* Size of aBlob[] in bytes */
7013   FILE *pFile,                    /* Read from this file if aBlob==0 */
7014   ZipfileEOCD *pEOCD              /* Object to populate */
7015 ){
7016   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
7017   int nRead;                      /* Bytes to read from file */
7018   int rc = SQLITE_OK;
7019
7020   if( aBlob==0 ){
7021     i64 iOff;                     /* Offset to read from */
7022     i64 szFile;                   /* Total size of file in bytes */
7023     fseek(pFile, 0, SEEK_END);
7024     szFile = (i64)ftell(pFile);
7025     if( szFile==0 ){
7026       memset(pEOCD, 0, sizeof(ZipfileEOCD));
7027       return SQLITE_OK;
7028     }
7029     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
7030     iOff = szFile - nRead;
7031     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
7032   }else{
7033     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
7034     aRead = (u8*)&aBlob[nBlob-nRead];
7035   }
7036
7037   if( rc==SQLITE_OK ){
7038     int i;
7039
7040     /* Scan backwards looking for the signature bytes */
7041     for(i=nRead-20; i>=0; i--){
7042       if( aRead[i]==0x50 && aRead[i+1]==0x4b 
7043        && aRead[i+2]==0x05 && aRead[i+3]==0x06 
7044       ){
7045         break;
7046       }
7047     }
7048     if( i<0 ){
7049       pTab->base.zErrMsg = sqlite3_mprintf(
7050           "cannot find end of central directory record"
7051       );
7052       return SQLITE_ERROR;
7053     }
7054
7055     aRead += i+4;
7056     pEOCD->iDisk = zipfileRead16(aRead);
7057     pEOCD->iFirstDisk = zipfileRead16(aRead);
7058     pEOCD->nEntry = zipfileRead16(aRead);
7059     pEOCD->nEntryTotal = zipfileRead16(aRead);
7060     pEOCD->nSize = zipfileRead32(aRead);
7061     pEOCD->iOffset = zipfileRead32(aRead);
7062   }
7063
7064   return rc;
7065 }
7066
7067 /*
7068 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry 
7069 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
7070 ** to the end of the list. Otherwise, it is added to the list immediately
7071 ** before pBefore (which is guaranteed to be a part of said list).
7072 */
7073 static void zipfileAddEntry(
7074   ZipfileTab *pTab, 
7075   ZipfileEntry *pBefore, 
7076   ZipfileEntry *pNew
7077 ){
7078   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
7079   assert( pNew->pNext==0 );
7080   if( pBefore==0 ){
7081     if( pTab->pFirstEntry==0 ){
7082       pTab->pFirstEntry = pTab->pLastEntry = pNew;
7083     }else{
7084       assert( pTab->pLastEntry->pNext==0 );
7085       pTab->pLastEntry->pNext = pNew;
7086       pTab->pLastEntry = pNew;
7087     }
7088   }else{
7089     ZipfileEntry **pp;
7090     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
7091     pNew->pNext = pBefore;
7092     *pp = pNew;
7093   }
7094 }
7095
7096 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
7097   ZipfileEOCD eocd;
7098   int rc;
7099   int i;
7100   i64 iOff;
7101
7102   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
7103   iOff = eocd.iOffset;
7104   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
7105     ZipfileEntry *pNew = 0;
7106     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
7107
7108     if( rc==SQLITE_OK ){
7109       zipfileAddEntry(pTab, 0, pNew);
7110       iOff += ZIPFILE_CDS_FIXED_SZ;
7111       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
7112     }
7113   }
7114   return rc;
7115 }
7116
7117 /*
7118 ** xFilter callback.
7119 */
7120 static int zipfileFilter(
7121   sqlite3_vtab_cursor *cur, 
7122   int idxNum, const char *idxStr,
7123   int argc, sqlite3_value **argv
7124 ){
7125   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
7126   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7127   const char *zFile = 0;          /* Zip file to scan */
7128   int rc = SQLITE_OK;             /* Return Code */
7129   int bInMemory = 0;              /* True for an in-memory zipfile */
7130
7131   zipfileResetCursor(pCsr);
7132
7133   if( pTab->zFile ){
7134     zFile = pTab->zFile;
7135   }else if( idxNum==0 ){
7136     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
7137     return SQLITE_ERROR;
7138   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
7139     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
7140     int nBlob = sqlite3_value_bytes(argv[0]);
7141     assert( pTab->pFirstEntry==0 );
7142     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
7143     pCsr->pFreeEntry = pTab->pFirstEntry;
7144     pTab->pFirstEntry = pTab->pLastEntry = 0;
7145     if( rc!=SQLITE_OK ) return rc;
7146     bInMemory = 1;
7147   }else{
7148     zFile = (const char*)sqlite3_value_text(argv[0]);
7149   }
7150
7151   if( 0==pTab->pWriteFd && 0==bInMemory ){
7152     pCsr->pFile = fopen(zFile, "rb");
7153     if( pCsr->pFile==0 ){
7154       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
7155       rc = SQLITE_ERROR;
7156     }else{
7157       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
7158       if( rc==SQLITE_OK ){
7159         if( pCsr->eocd.nEntry==0 ){
7160           pCsr->bEof = 1;
7161         }else{
7162           pCsr->iNextOff = pCsr->eocd.iOffset;
7163           rc = zipfileNext(cur);
7164         }
7165       }
7166     }
7167   }else{
7168     pCsr->bNoop = 1;
7169     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
7170     rc = zipfileNext(cur);
7171   }
7172
7173   return rc;
7174 }
7175
7176 /*
7177 ** xBestIndex callback.
7178 */
7179 static int zipfileBestIndex(
7180   sqlite3_vtab *tab,
7181   sqlite3_index_info *pIdxInfo
7182 ){
7183   int i;
7184   int idx = -1;
7185   int unusable = 0;
7186
7187   for(i=0; i<pIdxInfo->nConstraint; i++){
7188     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
7189     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
7190     if( pCons->usable==0 ){
7191       unusable = 1;
7192     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
7193       idx = i;
7194     }
7195   }
7196   pIdxInfo->estimatedCost = 1000.0;
7197   if( idx>=0 ){
7198     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
7199     pIdxInfo->aConstraintUsage[idx].omit = 1;
7200     pIdxInfo->idxNum = 1;
7201   }else if( unusable ){
7202     return SQLITE_CONSTRAINT;
7203   }
7204   return SQLITE_OK;
7205 }
7206
7207 static ZipfileEntry *zipfileNewEntry(const char *zPath){
7208   ZipfileEntry *pNew;
7209   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
7210   if( pNew ){
7211     memset(pNew, 0, sizeof(ZipfileEntry));
7212     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
7213     if( pNew->cds.zFile==0 ){
7214       sqlite3_free(pNew);
7215       pNew = 0;
7216     }
7217   }
7218   return pNew;
7219 }
7220
7221 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
7222   ZipfileCDS *pCds = &pEntry->cds;
7223   u8 *a = aBuf;
7224
7225   pCds->nExtra = 9;
7226
7227   /* Write the LFH itself */
7228   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
7229   zipfileWrite16(a, pCds->iVersionExtract);
7230   zipfileWrite16(a, pCds->flags);
7231   zipfileWrite16(a, pCds->iCompression);
7232   zipfileWrite16(a, pCds->mTime);
7233   zipfileWrite16(a, pCds->mDate);
7234   zipfileWrite32(a, pCds->crc32);
7235   zipfileWrite32(a, pCds->szCompressed);
7236   zipfileWrite32(a, pCds->szUncompressed);
7237   zipfileWrite16(a, (u16)pCds->nFile);
7238   zipfileWrite16(a, pCds->nExtra);
7239   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
7240
7241   /* Add the file name */
7242   memcpy(a, pCds->zFile, (int)pCds->nFile);
7243   a += (int)pCds->nFile;
7244
7245   /* The "extra" data */
7246   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
7247   zipfileWrite16(a, 5);
7248   *a++ = 0x01;
7249   zipfileWrite32(a, pEntry->mUnixTime);
7250
7251   return a-aBuf;
7252 }
7253
7254 static int zipfileAppendEntry(
7255   ZipfileTab *pTab,
7256   ZipfileEntry *pEntry,
7257   const u8 *pData,
7258   int nData
7259 ){
7260   u8 *aBuf = pTab->aBuffer;
7261   int nBuf;
7262   int rc;
7263
7264   nBuf = zipfileSerializeLFH(pEntry, aBuf);
7265   rc = zipfileAppendData(pTab, aBuf, nBuf);
7266   if( rc==SQLITE_OK ){
7267     pEntry->iDataOff = pTab->szCurrent;
7268     rc = zipfileAppendData(pTab, pData, nData);
7269   }
7270
7271   return rc;
7272 }
7273
7274 static int zipfileGetMode(
7275   sqlite3_value *pVal, 
7276   int bIsDir,                     /* If true, default to directory */
7277   u32 *pMode,                     /* OUT: Mode value */
7278   char **pzErr                    /* OUT: Error message */
7279 ){
7280   const char *z = (const char*)sqlite3_value_text(pVal);
7281   u32 mode = 0;
7282   if( z==0 ){
7283     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
7284   }else if( z[0]>='0' && z[0]<='9' ){
7285     mode = (unsigned int)sqlite3_value_int(pVal);
7286   }else{
7287     const char zTemplate[11] = "-rwxrwxrwx";
7288     int i;
7289     if( strlen(z)!=10 ) goto parse_error;
7290     switch( z[0] ){
7291       case '-': mode |= S_IFREG; break;
7292       case 'd': mode |= S_IFDIR; break;
7293       case 'l': mode |= S_IFLNK; break;
7294       default: goto parse_error;
7295     }
7296     for(i=1; i<10; i++){
7297       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
7298       else if( z[i]!='-' ) goto parse_error;
7299     }
7300   }
7301   if( ((mode & S_IFDIR)==0)==bIsDir ){
7302     /* The "mode" attribute is a directory, but data has been specified.
7303     ** Or vice-versa - no data but "mode" is a file or symlink.  */
7304     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
7305     return SQLITE_CONSTRAINT;
7306   }
7307   *pMode = mode;
7308   return SQLITE_OK;
7309
7310  parse_error:
7311   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
7312   return SQLITE_ERROR;
7313 }
7314
7315 /*
7316 ** Both (const char*) arguments point to nul-terminated strings. Argument
7317 ** nB is the value of strlen(zB). This function returns 0 if the strings are
7318 ** identical, ignoring any trailing '/' character in either path.  */
7319 static int zipfileComparePath(const char *zA, const char *zB, int nB){
7320   int nA = (int)strlen(zA);
7321   if( nA>0 && zA[nA-1]=='/' ) nA--;
7322   if( nB>0 && zB[nB-1]=='/' ) nB--;
7323   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
7324   return 1;
7325 }
7326
7327 static int zipfileBegin(sqlite3_vtab *pVtab){
7328   ZipfileTab *pTab = (ZipfileTab*)pVtab;
7329   int rc = SQLITE_OK;
7330
7331   assert( pTab->pWriteFd==0 );
7332   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
7333     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
7334     return SQLITE_ERROR;
7335   }
7336
7337   /* Open a write fd on the file. Also load the entire central directory
7338   ** structure into memory. During the transaction any new file data is 
7339   ** appended to the archive file, but the central directory is accumulated
7340   ** in main-memory until the transaction is committed.  */
7341   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
7342   if( pTab->pWriteFd==0 ){
7343     pTab->base.zErrMsg = sqlite3_mprintf(
7344         "zipfile: failed to open file %s for writing", pTab->zFile
7345         );
7346     rc = SQLITE_ERROR;
7347   }else{
7348     fseek(pTab->pWriteFd, 0, SEEK_END);
7349     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
7350     rc = zipfileLoadDirectory(pTab, 0, 0);
7351   }
7352
7353   if( rc!=SQLITE_OK ){
7354     zipfileCleanupTransaction(pTab);
7355   }
7356
7357   return rc;
7358 }
7359
7360 /*
7361 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
7362 ** time(2)).
7363 */
7364 static u32 zipfileTime(void){
7365   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
7366   u32 ret;
7367   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
7368     i64 ms;
7369     pVfs->xCurrentTimeInt64(pVfs, &ms);
7370     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
7371   }else{
7372     double day;
7373     pVfs->xCurrentTime(pVfs, &day);
7374     ret = (u32)((day - 2440587.5) * 86400);
7375   }
7376   return ret;
7377 }
7378
7379 /*
7380 ** Return a 32-bit timestamp in UNIX epoch format.
7381 **
7382 ** If the value passed as the only argument is either NULL or an SQL NULL,
7383 ** return the current time. Otherwise, return the value stored in (*pVal)
7384 ** cast to a 32-bit unsigned integer.
7385 */
7386 static u32 zipfileGetTime(sqlite3_value *pVal){
7387   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
7388     return zipfileTime();
7389   }
7390   return (u32)sqlite3_value_int64(pVal);
7391 }
7392
7393 /*
7394 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
7395 ** linked list.  Remove it from the list and free the object.
7396 */
7397 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
7398   if( pOld ){
7399     ZipfileEntry **pp;
7400     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
7401     *pp = (*pp)->pNext;
7402     zipfileEntryFree(pOld);
7403   }
7404 }
7405
7406 /*
7407 ** xUpdate method.
7408 */
7409 static int zipfileUpdate(
7410   sqlite3_vtab *pVtab, 
7411   int nVal, 
7412   sqlite3_value **apVal, 
7413   sqlite_int64 *pRowid
7414 ){
7415   ZipfileTab *pTab = (ZipfileTab*)pVtab;
7416   int rc = SQLITE_OK;             /* Return Code */
7417   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
7418
7419   u32 mode = 0;                   /* Mode for new entry */
7420   u32 mTime = 0;                  /* Modification time for new entry */
7421   i64 sz = 0;                     /* Uncompressed size */
7422   const char *zPath = 0;          /* Path for new entry */
7423   int nPath = 0;                  /* strlen(zPath) */
7424   const u8 *pData = 0;            /* Pointer to buffer containing content */
7425   int nData = 0;                  /* Size of pData buffer in bytes */
7426   int iMethod = 0;                /* Compression method for new entry */
7427   u8 *pFree = 0;                  /* Free this */
7428   char *zFree = 0;                /* Also free this */
7429   ZipfileEntry *pOld = 0;
7430   ZipfileEntry *pOld2 = 0;
7431   int bUpdate = 0;                /* True for an update that modifies "name" */
7432   int bIsDir = 0;
7433   u32 iCrc32 = 0;
7434
7435   if( pTab->pWriteFd==0 ){
7436     rc = zipfileBegin(pVtab);
7437     if( rc!=SQLITE_OK ) return rc;
7438   }
7439
7440   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
7441   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
7442     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
7443     int nDelete = (int)strlen(zDelete);
7444     if( nVal>1 ){
7445       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
7446       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
7447         bUpdate = 1;
7448       }
7449     }
7450     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
7451       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
7452         break;
7453       }
7454       assert( pOld->pNext );
7455     }
7456   }
7457
7458   if( nVal>1 ){
7459     /* Check that "sz" and "rawdata" are both NULL: */
7460     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
7461       zipfileTableErr(pTab, "sz must be NULL");
7462       rc = SQLITE_CONSTRAINT;
7463     }
7464     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
7465       zipfileTableErr(pTab, "rawdata must be NULL"); 
7466       rc = SQLITE_CONSTRAINT;
7467     }
7468
7469     if( rc==SQLITE_OK ){
7470       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
7471         /* data=NULL. A directory */
7472         bIsDir = 1;
7473       }else{
7474         /* Value specified for "data", and possibly "method". This must be
7475         ** a regular file or a symlink. */
7476         const u8 *aIn = sqlite3_value_blob(apVal[7]);
7477         int nIn = sqlite3_value_bytes(apVal[7]);
7478         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
7479
7480         iMethod = sqlite3_value_int(apVal[8]);
7481         sz = nIn;
7482         pData = aIn;
7483         nData = nIn;
7484         if( iMethod!=0 && iMethod!=8 ){
7485           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
7486           rc = SQLITE_CONSTRAINT;
7487         }else{
7488           if( bAuto || iMethod ){
7489             int nCmp;
7490             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
7491             if( rc==SQLITE_OK ){
7492               if( iMethod || nCmp<nIn ){
7493                 iMethod = 8;
7494                 pData = pFree;
7495                 nData = nCmp;
7496               }
7497             }
7498           }
7499           iCrc32 = crc32(0, aIn, nIn);
7500         }
7501       }
7502     }
7503
7504     if( rc==SQLITE_OK ){
7505       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
7506     }
7507
7508     if( rc==SQLITE_OK ){
7509       zPath = (const char*)sqlite3_value_text(apVal[2]);
7510       if( zPath==0 ) zPath = "";
7511       nPath = (int)strlen(zPath);
7512       mTime = zipfileGetTime(apVal[4]);
7513     }
7514
7515     if( rc==SQLITE_OK && bIsDir ){
7516       /* For a directory, check that the last character in the path is a
7517       ** '/'. This appears to be required for compatibility with info-zip
7518       ** (the unzip command on unix). It does not create directories
7519       ** otherwise.  */
7520       if( nPath<=0 || zPath[nPath-1]!='/' ){
7521         zFree = sqlite3_mprintf("%s/", zPath);
7522         zPath = (const char*)zFree;
7523         if( zFree==0 ){
7524           rc = SQLITE_NOMEM;
7525           nPath = 0;
7526         }else{
7527           nPath = (int)strlen(zPath);
7528         }
7529       }
7530     }
7531
7532     /* Check that we're not inserting a duplicate entry -OR- updating an
7533     ** entry with a path, thereby making it into a duplicate. */
7534     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
7535       ZipfileEntry *p;
7536       for(p=pTab->pFirstEntry; p; p=p->pNext){
7537         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
7538           switch( sqlite3_vtab_on_conflict(pTab->db) ){
7539             case SQLITE_IGNORE: {
7540               goto zipfile_update_done;
7541             }
7542             case SQLITE_REPLACE: {
7543               pOld2 = p;
7544               break;
7545             }
7546             default: {
7547               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
7548               rc = SQLITE_CONSTRAINT;
7549               break;
7550             }
7551           }
7552           break;
7553         }
7554       }
7555     }
7556
7557     if( rc==SQLITE_OK ){
7558       /* Create the new CDS record. */
7559       pNew = zipfileNewEntry(zPath);
7560       if( pNew==0 ){
7561         rc = SQLITE_NOMEM;
7562       }else{
7563         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
7564         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
7565         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
7566         pNew->cds.iCompression = (u16)iMethod;
7567         zipfileMtimeToDos(&pNew->cds, mTime);
7568         pNew->cds.crc32 = iCrc32;
7569         pNew->cds.szCompressed = nData;
7570         pNew->cds.szUncompressed = (u32)sz;
7571         pNew->cds.iExternalAttr = (mode<<16);
7572         pNew->cds.iOffset = (u32)pTab->szCurrent;
7573         pNew->cds.nFile = (u16)nPath;
7574         pNew->mUnixTime = (u32)mTime;
7575         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
7576         zipfileAddEntry(pTab, pOld, pNew);
7577       }
7578     }
7579   }
7580
7581   if( rc==SQLITE_OK && (pOld || pOld2) ){
7582     ZipfileCsr *pCsr;
7583     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
7584       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
7585         pCsr->pCurrent = pCsr->pCurrent->pNext;
7586         pCsr->bNoop = 1;
7587       }
7588     }
7589
7590     zipfileRemoveEntryFromList(pTab, pOld);
7591     zipfileRemoveEntryFromList(pTab, pOld2);
7592   }
7593
7594 zipfile_update_done:
7595   sqlite3_free(pFree);
7596   sqlite3_free(zFree);
7597   return rc;
7598 }
7599
7600 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
7601   u8 *a = aBuf;
7602   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
7603   zipfileWrite16(a, p->iDisk);
7604   zipfileWrite16(a, p->iFirstDisk);
7605   zipfileWrite16(a, p->nEntry);
7606   zipfileWrite16(a, p->nEntryTotal);
7607   zipfileWrite32(a, p->nSize);
7608   zipfileWrite32(a, p->iOffset);
7609   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
7610
7611   return a-aBuf;
7612 }
7613
7614 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
7615   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
7616   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
7617   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
7618 }
7619
7620 /*
7621 ** Serialize the CDS structure into buffer aBuf[]. Return the number
7622 ** of bytes written.
7623 */
7624 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
7625   u8 *a = aBuf;
7626   ZipfileCDS *pCDS = &pEntry->cds;
7627
7628   if( pEntry->aExtra==0 ){
7629     pCDS->nExtra = 9;
7630   }
7631
7632   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
7633   zipfileWrite16(a, pCDS->iVersionMadeBy);
7634   zipfileWrite16(a, pCDS->iVersionExtract);
7635   zipfileWrite16(a, pCDS->flags);
7636   zipfileWrite16(a, pCDS->iCompression);
7637   zipfileWrite16(a, pCDS->mTime);
7638   zipfileWrite16(a, pCDS->mDate);
7639   zipfileWrite32(a, pCDS->crc32);
7640   zipfileWrite32(a, pCDS->szCompressed);
7641   zipfileWrite32(a, pCDS->szUncompressed);
7642   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
7643   zipfileWrite16(a, pCDS->nFile);
7644   zipfileWrite16(a, pCDS->nExtra);
7645   zipfileWrite16(a, pCDS->nComment);
7646   zipfileWrite16(a, pCDS->iDiskStart);
7647   zipfileWrite16(a, pCDS->iInternalAttr);
7648   zipfileWrite32(a, pCDS->iExternalAttr);
7649   zipfileWrite32(a, pCDS->iOffset);
7650
7651   memcpy(a, pCDS->zFile, pCDS->nFile);
7652   a += pCDS->nFile;
7653
7654   if( pEntry->aExtra ){
7655     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
7656     memcpy(a, pEntry->aExtra, n);
7657     a += n;
7658   }else{
7659     assert( pCDS->nExtra==9 );
7660     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
7661     zipfileWrite16(a, 5);
7662     *a++ = 0x01;
7663     zipfileWrite32(a, pEntry->mUnixTime);
7664   }
7665
7666   return a-aBuf;
7667 }
7668
7669 static int zipfileCommit(sqlite3_vtab *pVtab){
7670   ZipfileTab *pTab = (ZipfileTab*)pVtab;
7671   int rc = SQLITE_OK;
7672   if( pTab->pWriteFd ){
7673     i64 iOffset = pTab->szCurrent;
7674     ZipfileEntry *p;
7675     ZipfileEOCD eocd;
7676     int nEntry = 0;
7677
7678     /* Write out all entries */
7679     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
7680       int n = zipfileSerializeCDS(p, pTab->aBuffer);
7681       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
7682       nEntry++;
7683     }
7684
7685     /* Write out the EOCD record */
7686     eocd.iDisk = 0;
7687     eocd.iFirstDisk = 0;
7688     eocd.nEntry = (u16)nEntry;
7689     eocd.nEntryTotal = (u16)nEntry;
7690     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
7691     eocd.iOffset = (u32)iOffset;
7692     rc = zipfileAppendEOCD(pTab, &eocd);
7693
7694     zipfileCleanupTransaction(pTab);
7695   }
7696   return rc;
7697 }
7698
7699 static int zipfileRollback(sqlite3_vtab *pVtab){
7700   return zipfileCommit(pVtab);
7701 }
7702
7703 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
7704   ZipfileCsr *pCsr;
7705   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
7706     if( iId==pCsr->iId ) break;
7707   }
7708   return pCsr;
7709 }
7710
7711 static void zipfileFunctionCds(
7712   sqlite3_context *context,
7713   int argc,
7714   sqlite3_value **argv
7715 ){
7716   ZipfileCsr *pCsr;
7717   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
7718   assert( argc>0 );
7719
7720   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
7721   if( pCsr ){
7722     ZipfileCDS *p = &pCsr->pCurrent->cds;
7723     char *zRes = sqlite3_mprintf("{"
7724         "\"version-made-by\" : %u, "
7725         "\"version-to-extract\" : %u, "
7726         "\"flags\" : %u, "
7727         "\"compression\" : %u, "
7728         "\"time\" : %u, "
7729         "\"date\" : %u, "
7730         "\"crc32\" : %u, "
7731         "\"compressed-size\" : %u, "
7732         "\"uncompressed-size\" : %u, "
7733         "\"file-name-length\" : %u, "
7734         "\"extra-field-length\" : %u, "
7735         "\"file-comment-length\" : %u, "
7736         "\"disk-number-start\" : %u, "
7737         "\"internal-attr\" : %u, "
7738         "\"external-attr\" : %u, "
7739         "\"offset\" : %u }",
7740         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
7741         (u32)p->flags, (u32)p->iCompression,
7742         (u32)p->mTime, (u32)p->mDate,
7743         (u32)p->crc32, (u32)p->szCompressed,
7744         (u32)p->szUncompressed, (u32)p->nFile,
7745         (u32)p->nExtra, (u32)p->nComment,
7746         (u32)p->iDiskStart, (u32)p->iInternalAttr,
7747         (u32)p->iExternalAttr, (u32)p->iOffset
7748     );
7749
7750     if( zRes==0 ){
7751       sqlite3_result_error_nomem(context);
7752     }else{
7753       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
7754       sqlite3_free(zRes);
7755     }
7756   }
7757 }
7758
7759 /*
7760 ** xFindFunction method.
7761 */
7762 static int zipfileFindFunction(
7763   sqlite3_vtab *pVtab,            /* Virtual table handle */
7764   int nArg,                       /* Number of SQL function arguments */
7765   const char *zName,              /* Name of SQL function */
7766   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
7767   void **ppArg                    /* OUT: User data for *pxFunc */
7768 ){
7769   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
7770     *pxFunc = zipfileFunctionCds;
7771     *ppArg = (void*)pVtab;
7772     return 1;
7773   }
7774   return 0;
7775 }
7776
7777 typedef struct ZipfileBuffer ZipfileBuffer;
7778 struct ZipfileBuffer {
7779   u8 *a;                          /* Pointer to buffer */
7780   int n;                          /* Size of buffer in bytes */
7781   int nAlloc;                     /* Byte allocated at a[] */
7782 };
7783
7784 typedef struct ZipfileCtx ZipfileCtx;
7785 struct ZipfileCtx {
7786   int nEntry;
7787   ZipfileBuffer body;
7788   ZipfileBuffer cds;
7789 };
7790
7791 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
7792   if( pBuf->n+nByte>pBuf->nAlloc ){
7793     u8 *aNew;
7794     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
7795     int nReq = pBuf->n + nByte;
7796
7797     while( nNew<nReq ) nNew = nNew*2;
7798     aNew = sqlite3_realloc64(pBuf->a, nNew);
7799     if( aNew==0 ) return SQLITE_NOMEM;
7800     pBuf->a = aNew;
7801     pBuf->nAlloc = (int)nNew;
7802   }
7803   return SQLITE_OK;
7804 }
7805
7806 /*
7807 ** xStep() callback for the zipfile() aggregate. This can be called in
7808 ** any of the following ways:
7809 **
7810 **   SELECT zipfile(name,data) ...
7811 **   SELECT zipfile(name,mode,mtime,data) ...
7812 **   SELECT zipfile(name,mode,mtime,data,method) ...
7813 */
7814 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
7815   ZipfileCtx *p;                  /* Aggregate function context */
7816   ZipfileEntry e;                 /* New entry to add to zip archive */
7817
7818   sqlite3_value *pName = 0;
7819   sqlite3_value *pMode = 0;
7820   sqlite3_value *pMtime = 0;
7821   sqlite3_value *pData = 0;
7822   sqlite3_value *pMethod = 0;
7823
7824   int bIsDir = 0;
7825   u32 mode;
7826   int rc = SQLITE_OK;
7827   char *zErr = 0;
7828
7829   int iMethod = -1;               /* Compression method to use (0 or 8) */
7830
7831   const u8 *aData = 0;            /* Possibly compressed data for new entry */
7832   int nData = 0;                  /* Size of aData[] in bytes */
7833   int szUncompressed = 0;         /* Size of data before compression */
7834   u8 *aFree = 0;                  /* Free this before returning */
7835   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
7836
7837   char *zName = 0;                /* Path (name) of new entry */
7838   int nName = 0;                  /* Size of zName in bytes */
7839   char *zFree = 0;                /* Free this before returning */
7840   int nByte;
7841
7842   memset(&e, 0, sizeof(e));
7843   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
7844   if( p==0 ) return;
7845
7846   /* Martial the arguments into stack variables */
7847   if( nVal!=2 && nVal!=4 && nVal!=5 ){
7848     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
7849     rc = SQLITE_ERROR;
7850     goto zipfile_step_out;
7851   }
7852   pName = apVal[0];
7853   if( nVal==2 ){
7854     pData = apVal[1];
7855   }else{
7856     pMode = apVal[1];
7857     pMtime = apVal[2];
7858     pData = apVal[3];
7859     if( nVal==5 ){
7860       pMethod = apVal[4];
7861     }
7862   }
7863
7864   /* Check that the 'name' parameter looks ok. */
7865   zName = (char*)sqlite3_value_text(pName);
7866   nName = sqlite3_value_bytes(pName);
7867   if( zName==0 ){
7868     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
7869     rc = SQLITE_ERROR;
7870     goto zipfile_step_out;
7871   }
7872
7873   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
7874   ** deflate compression) or NULL (choose automatically).  */
7875   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
7876     iMethod = (int)sqlite3_value_int64(pMethod);
7877     if( iMethod!=0 && iMethod!=8 ){
7878       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
7879       rc = SQLITE_ERROR;
7880       goto zipfile_step_out;
7881     }
7882   }
7883
7884   /* Now inspect the data. If this is NULL, then the new entry must be a
7885   ** directory.  Otherwise, figure out whether or not the data should
7886   ** be deflated or simply stored in the zip archive. */
7887   if( sqlite3_value_type(pData)==SQLITE_NULL ){
7888     bIsDir = 1;
7889     iMethod = 0;
7890   }else{
7891     aData = sqlite3_value_blob(pData);
7892     szUncompressed = nData = sqlite3_value_bytes(pData);
7893     iCrc32 = crc32(0, aData, nData);
7894     if( iMethod<0 || iMethod==8 ){
7895       int nOut = 0;
7896       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
7897       if( rc!=SQLITE_OK ){
7898         goto zipfile_step_out;
7899       }
7900       if( iMethod==8 || nOut<nData ){
7901         aData = aFree;
7902         nData = nOut;
7903         iMethod = 8;
7904       }else{
7905         iMethod = 0;
7906       }
7907     }
7908   }
7909
7910   /* Decode the "mode" argument. */
7911   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
7912   if( rc ) goto zipfile_step_out;
7913
7914   /* Decode the "mtime" argument. */
7915   e.mUnixTime = zipfileGetTime(pMtime);
7916
7917   /* If this is a directory entry, ensure that there is exactly one '/'
7918   ** at the end of the path. Or, if this is not a directory and the path
7919   ** ends in '/' it is an error. */
7920   if( bIsDir==0 ){
7921     if( nName>0 && zName[nName-1]=='/' ){
7922       zErr = sqlite3_mprintf("non-directory name must not end with /");
7923       rc = SQLITE_ERROR;
7924       goto zipfile_step_out;
7925     }
7926   }else{
7927     if( nName==0 || zName[nName-1]!='/' ){
7928       zName = zFree = sqlite3_mprintf("%s/", zName);
7929       if( zName==0 ){
7930         rc = SQLITE_NOMEM;
7931         goto zipfile_step_out;
7932       }
7933       nName = (int)strlen(zName);
7934     }else{
7935       while( nName>1 && zName[nName-2]=='/' ) nName--;
7936     }
7937   }
7938
7939   /* Assemble the ZipfileEntry object for the new zip archive entry */
7940   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
7941   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
7942   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
7943   e.cds.iCompression = (u16)iMethod;
7944   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
7945   e.cds.crc32 = iCrc32;
7946   e.cds.szCompressed = nData;
7947   e.cds.szUncompressed = szUncompressed;
7948   e.cds.iExternalAttr = (mode<<16);
7949   e.cds.iOffset = p->body.n;
7950   e.cds.nFile = (u16)nName;
7951   e.cds.zFile = zName;
7952
7953   /* Append the LFH to the body of the new archive */
7954   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
7955   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
7956   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
7957
7958   /* Append the data to the body of the new archive */
7959   if( nData>0 ){
7960     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
7961     memcpy(&p->body.a[p->body.n], aData, nData);
7962     p->body.n += nData;
7963   }
7964
7965   /* Append the CDS record to the directory of the new archive */
7966   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
7967   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
7968   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
7969
7970   /* Increment the count of entries in the archive */
7971   p->nEntry++;
7972
7973  zipfile_step_out:
7974   sqlite3_free(aFree);
7975   sqlite3_free(zFree);
7976   if( rc ){
7977     if( zErr ){
7978       sqlite3_result_error(pCtx, zErr, -1);
7979     }else{
7980       sqlite3_result_error_code(pCtx, rc);
7981     }
7982   }
7983   sqlite3_free(zErr);
7984 }
7985
7986 /*
7987 ** xFinalize() callback for zipfile aggregate function.
7988 */
7989 void zipfileFinal(sqlite3_context *pCtx){
7990   ZipfileCtx *p;
7991   ZipfileEOCD eocd;
7992   sqlite3_int64 nZip;
7993   u8 *aZip;
7994
7995   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
7996   if( p==0 ) return;
7997   if( p->nEntry>0 ){
7998     memset(&eocd, 0, sizeof(eocd));
7999     eocd.nEntry = (u16)p->nEntry;
8000     eocd.nEntryTotal = (u16)p->nEntry;
8001     eocd.nSize = p->cds.n;
8002     eocd.iOffset = p->body.n;
8003
8004     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
8005     aZip = (u8*)sqlite3_malloc64(nZip);
8006     if( aZip==0 ){
8007       sqlite3_result_error_nomem(pCtx);
8008     }else{
8009       memcpy(aZip, p->body.a, p->body.n);
8010       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
8011       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
8012       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
8013     }
8014   }
8015
8016   sqlite3_free(p->body.a);
8017   sqlite3_free(p->cds.a);
8018 }
8019
8020
8021 /*
8022 ** Register the "zipfile" virtual table.
8023 */
8024 static int zipfileRegister(sqlite3 *db){
8025   static sqlite3_module zipfileModule = {
8026     1,                         /* iVersion */
8027     zipfileConnect,            /* xCreate */
8028     zipfileConnect,            /* xConnect */
8029     zipfileBestIndex,          /* xBestIndex */
8030     zipfileDisconnect,         /* xDisconnect */
8031     zipfileDisconnect,         /* xDestroy */
8032     zipfileOpen,               /* xOpen - open a cursor */
8033     zipfileClose,              /* xClose - close a cursor */
8034     zipfileFilter,             /* xFilter - configure scan constraints */
8035     zipfileNext,               /* xNext - advance a cursor */
8036     zipfileEof,                /* xEof - check for end of scan */
8037     zipfileColumn,             /* xColumn - read data */
8038     0,                         /* xRowid - read data */
8039     zipfileUpdate,             /* xUpdate */
8040     zipfileBegin,              /* xBegin */
8041     0,                         /* xSync */
8042     zipfileCommit,             /* xCommit */
8043     zipfileRollback,           /* xRollback */
8044     zipfileFindFunction,       /* xFindMethod */
8045     0,                         /* xRename */
8046   };
8047
8048   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
8049   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
8050   if( rc==SQLITE_OK ){
8051     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, 
8052         zipfileStep, zipfileFinal
8053     );
8054   }
8055   return rc;
8056 }
8057 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8058 # define zipfileRegister(x) SQLITE_OK
8059 #endif
8060
8061 #ifdef _WIN32
8062
8063 #endif
8064 int sqlite3_zipfile_init(
8065   sqlite3 *db, 
8066   char **pzErrMsg, 
8067   const sqlite3_api_routines *pApi
8068 ){
8069   SQLITE_EXTENSION_INIT2(pApi);
8070   (void)pzErrMsg;  /* Unused parameter */
8071   return zipfileRegister(db);
8072 }
8073
8074 /************************* End ../ext/misc/zipfile.c ********************/
8075 /************************* Begin ../ext/misc/sqlar.c ******************/
8076 /*
8077 ** 2017-12-17
8078 **
8079 ** The author disclaims copyright to this source code.  In place of
8080 ** a legal notice, here is a blessing:
8081 **
8082 **    May you do good and not evil.
8083 **    May you find forgiveness for yourself and forgive others.
8084 **    May you share freely, never taking more than you give.
8085 **
8086 ******************************************************************************
8087 **
8088 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
8089 ** for working with sqlar archives and used by the shell tool's built-in
8090 ** sqlar support.
8091 */
8092 /* #include "sqlite3ext.h" */
8093 SQLITE_EXTENSION_INIT1
8094 #include <zlib.h>
8095 #include <assert.h>
8096
8097 /*
8098 ** Implementation of the "sqlar_compress(X)" SQL function.
8099 **
8100 ** If the type of X is SQLITE_BLOB, and compressing that blob using
8101 ** zlib utility function compress() yields a smaller blob, return the
8102 ** compressed blob. Otherwise, return a copy of X.
8103 **
8104 ** SQLar uses the "zlib format" for compressed content.  The zlib format
8105 ** contains a two-byte identification header and a four-byte checksum at
8106 ** the end.  This is different from ZIP which uses the raw deflate format.
8107 **
8108 ** Future enhancements to SQLar might add support for new compression formats.
8109 ** If so, those new formats will be identified by alternative headers in the
8110 ** compressed data.
8111 */
8112 static void sqlarCompressFunc(
8113   sqlite3_context *context,
8114   int argc,
8115   sqlite3_value **argv
8116 ){
8117   assert( argc==1 );
8118   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
8119     const Bytef *pData = sqlite3_value_blob(argv[0]);
8120     uLong nData = sqlite3_value_bytes(argv[0]);
8121     uLongf nOut = compressBound(nData);
8122     Bytef *pOut;
8123
8124     pOut = (Bytef*)sqlite3_malloc(nOut);
8125     if( pOut==0 ){
8126       sqlite3_result_error_nomem(context);
8127       return;
8128     }else{
8129       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
8130         sqlite3_result_error(context, "error in compress()", -1);
8131       }else if( nOut<nData ){
8132         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
8133       }else{
8134         sqlite3_result_value(context, argv[0]);
8135       }
8136       sqlite3_free(pOut);
8137     }
8138   }else{
8139     sqlite3_result_value(context, argv[0]);
8140   }
8141 }
8142
8143 /*
8144 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
8145 **
8146 ** Parameter SZ is interpreted as an integer. If it is less than or
8147 ** equal to zero, then this function returns a copy of X. Or, if
8148 ** SZ is equal to the size of X when interpreted as a blob, also
8149 ** return a copy of X. Otherwise, decompress blob X using zlib
8150 ** utility function uncompress() and return the results (another
8151 ** blob).
8152 */
8153 static void sqlarUncompressFunc(
8154   sqlite3_context *context,
8155   int argc,
8156   sqlite3_value **argv
8157 ){
8158   uLong nData;
8159   uLongf sz;
8160
8161   assert( argc==2 );
8162   sz = sqlite3_value_int(argv[1]);
8163
8164   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
8165     sqlite3_result_value(context, argv[0]);
8166   }else{
8167     const Bytef *pData= sqlite3_value_blob(argv[0]);
8168     Bytef *pOut = sqlite3_malloc(sz);
8169     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
8170       sqlite3_result_error(context, "error in uncompress()", -1);
8171     }else{
8172       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
8173     }
8174     sqlite3_free(pOut);
8175   }
8176 }
8177
8178
8179 #ifdef _WIN32
8180
8181 #endif
8182 int sqlite3_sqlar_init(
8183   sqlite3 *db, 
8184   char **pzErrMsg, 
8185   const sqlite3_api_routines *pApi
8186 ){
8187   int rc = SQLITE_OK;
8188   SQLITE_EXTENSION_INIT2(pApi);
8189   (void)pzErrMsg;  /* Unused parameter */
8190   rc = sqlite3_create_function(db, "sqlar_compress", 1, 
8191                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
8192                                sqlarCompressFunc, 0, 0);
8193   if( rc==SQLITE_OK ){
8194     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
8195                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
8196                                  sqlarUncompressFunc, 0, 0);
8197   }
8198   return rc;
8199 }
8200
8201 /************************* End ../ext/misc/sqlar.c ********************/
8202 #endif
8203 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
8204 /*
8205 ** 2017 April 07
8206 **
8207 ** The author disclaims copyright to this source code.  In place of
8208 ** a legal notice, here is a blessing:
8209 **
8210 **    May you do good and not evil.
8211 **    May you find forgiveness for yourself and forgive others.
8212 **    May you share freely, never taking more than you give.
8213 **
8214 *************************************************************************
8215 */
8216 #if !defined(SQLITEEXPERT_H)
8217 #define SQLITEEXPERT_H 1
8218 /* #include "sqlite3.h" */
8219
8220 typedef struct sqlite3expert sqlite3expert;
8221
8222 /*
8223 ** Create a new sqlite3expert object.
8224 **
8225 ** If successful, a pointer to the new object is returned and (*pzErr) set
8226 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
8227 ** an English-language error message. In this case it is the responsibility
8228 ** of the caller to eventually free the error message buffer using
8229 ** sqlite3_free().
8230 */
8231 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
8232
8233 /*
8234 ** Configure an sqlite3expert object.
8235 **
8236 ** EXPERT_CONFIG_SAMPLE:
8237 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
8238 **   each candidate index. This involves scanning and sorting the entire
8239 **   contents of each user database table once for each candidate index
8240 **   associated with the table. For large databases, this can be 
8241 **   prohibitively slow. This option allows the sqlite3expert object to
8242 **   be configured so that sqlite_stat1 data is instead generated based on a
8243 **   subset of each table, or so that no sqlite_stat1 data is used at all.
8244 **
8245 **   A single integer argument is passed to this option. If the value is less
8246 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
8247 **   the analysis - indexes are recommended based on the database schema only.
8248 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
8249 **   generated for each candidate index (this is the default). Finally, if the
8250 **   value falls between 0 and 100, then it represents the percentage of user
8251 **   table rows that should be considered when generating sqlite_stat1 data.
8252 **
8253 **   Examples:
8254 **
8255 **     // Do not generate any sqlite_stat1 data
8256 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
8257 **
8258 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
8259 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
8260 */
8261 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
8262
8263 #define EXPERT_CONFIG_SAMPLE 1    /* int */
8264
8265 /*
8266 ** Specify zero or more SQL statements to be included in the analysis.
8267 **
8268 ** Buffer zSql must contain zero or more complete SQL statements. This
8269 ** function parses all statements contained in the buffer and adds them
8270 ** to the internal list of statements to analyze. If successful, SQLITE_OK
8271 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
8272 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
8273 ** may be set to point to an English language error message. In this case
8274 ** the caller is responsible for eventually freeing the error message buffer
8275 ** using sqlite3_free().
8276 **
8277 ** If an error does occur while processing one of the statements in the
8278 ** buffer passed as the second argument, none of the statements in the
8279 ** buffer are added to the analysis.
8280 **
8281 ** This function must be called before sqlite3_expert_analyze(). If a call
8282 ** to this function is made on an sqlite3expert object that has already
8283 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
8284 ** immediately and no statements are added to the analysis.
8285 */
8286 int sqlite3_expert_sql(
8287   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
8288   const char *zSql,               /* SQL statement(s) to add */
8289   char **pzErr                    /* OUT: Error message (if any) */
8290 );
8291
8292
8293 /*
8294 ** This function is called after the sqlite3expert object has been configured
8295 ** with all SQL statements using sqlite3_expert_sql() to actually perform
8296 ** the analysis. Once this function has been called, it is not possible to
8297 ** add further SQL statements to the analysis.
8298 **
8299 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
8300 ** an error occurs, an SQLite error code is returned and (*pzErr) set to 
8301 ** point to a buffer containing an English language error message. In this
8302 ** case it is the responsibility of the caller to eventually free the buffer
8303 ** using sqlite3_free().
8304 **
8305 ** If an error does occur within this function, the sqlite3expert object
8306 ** is no longer useful for any purpose. At that point it is no longer
8307 ** possible to add further SQL statements to the object or to re-attempt
8308 ** the analysis. The sqlite3expert object must still be freed using a call
8309 ** sqlite3_expert_destroy().
8310 */
8311 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
8312
8313 /*
8314 ** Return the total number of statements loaded using sqlite3_expert_sql().
8315 ** The total number of SQL statements may be different from the total number
8316 ** to calls to sqlite3_expert_sql().
8317 */
8318 int sqlite3_expert_count(sqlite3expert*);
8319
8320 /*
8321 ** Return a component of the report.
8322 **
8323 ** This function is called after sqlite3_expert_analyze() to extract the
8324 ** results of the analysis. Each call to this function returns either a
8325 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
8326 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
8327 ** #define constants defined below.
8328 **
8329 ** For some EXPERT_REPORT_* parameters, the buffer returned contains 
8330 ** information relating to a specific SQL statement. In these cases that
8331 ** SQL statement is identified by the value passed as the second argument.
8332 ** SQL statements are numbered from 0 in the order in which they are parsed.
8333 ** If an out-of-range value (less than zero or equal to or greater than the
8334 ** value returned by sqlite3_expert_count()) is passed as the second argument
8335 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
8336 **
8337 ** EXPERT_REPORT_SQL:
8338 **   Return the text of SQL statement iStmt.
8339 **
8340 ** EXPERT_REPORT_INDEXES:
8341 **   Return a buffer containing the CREATE INDEX statements for all recommended
8342 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL 
8343 **   is returned.
8344 **
8345 ** EXPERT_REPORT_PLAN:
8346 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
8347 **   iStmt after the proposed indexes have been added to the database schema.
8348 **
8349 ** EXPERT_REPORT_CANDIDATES:
8350 **   Return a pointer to a buffer containing the CREATE INDEX statements 
8351 **   for all indexes that were tested (for all SQL statements). The iStmt
8352 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
8353 */
8354 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
8355
8356 /*
8357 ** Values for the third argument passed to sqlite3_expert_report().
8358 */
8359 #define EXPERT_REPORT_SQL        1
8360 #define EXPERT_REPORT_INDEXES    2
8361 #define EXPERT_REPORT_PLAN       3
8362 #define EXPERT_REPORT_CANDIDATES 4
8363
8364 /*
8365 ** Free an (sqlite3expert*) handle and all associated resources. There 
8366 ** should be one call to this function for each successful call to 
8367 ** sqlite3-expert_new().
8368 */
8369 void sqlite3_expert_destroy(sqlite3expert*);
8370
8371 #endif  /* !defined(SQLITEEXPERT_H) */
8372
8373 /************************* End ../ext/expert/sqlite3expert.h ********************/
8374 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
8375 /*
8376 ** 2017 April 09
8377 **
8378 ** The author disclaims copyright to this source code.  In place of
8379 ** a legal notice, here is a blessing:
8380 **
8381 **    May you do good and not evil.
8382 **    May you find forgiveness for yourself and forgive others.
8383 **    May you share freely, never taking more than you give.
8384 **
8385 *************************************************************************
8386 */
8387 /* #include "sqlite3expert.h" */
8388 #include <assert.h>
8389 #include <string.h>
8390 #include <stdio.h>
8391
8392 #ifndef SQLITE_OMIT_VIRTUALTABLE 
8393
8394 /* typedef sqlite3_int64 i64; */
8395 /* typedef sqlite3_uint64 u64; */
8396
8397 typedef struct IdxColumn IdxColumn;
8398 typedef struct IdxConstraint IdxConstraint;
8399 typedef struct IdxScan IdxScan;
8400 typedef struct IdxStatement IdxStatement;
8401 typedef struct IdxTable IdxTable;
8402 typedef struct IdxWrite IdxWrite;
8403
8404 #define STRLEN  (int)strlen
8405
8406 /*
8407 ** A temp table name that we assume no user database will actually use.
8408 ** If this assumption proves incorrect triggers on the table with the
8409 ** conflicting name will be ignored.
8410 */
8411 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
8412
8413 /*
8414 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
8415 ** any other type of single-ended range constraint on a column).
8416 **
8417 ** pLink:
8418 **   Used to temporarily link IdxConstraint objects into lists while
8419 **   creating candidate indexes.
8420 */
8421 struct IdxConstraint {
8422   char *zColl;                    /* Collation sequence */
8423   int bRange;                     /* True for range, false for eq */
8424   int iCol;                       /* Constrained table column */
8425   int bFlag;                      /* Used by idxFindCompatible() */
8426   int bDesc;                      /* True if ORDER BY <expr> DESC */
8427   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
8428   IdxConstraint *pLink;           /* See above */
8429 };
8430
8431 /*
8432 ** A single scan of a single table.
8433 */
8434 struct IdxScan {
8435   IdxTable *pTab;                 /* Associated table object */
8436   int iDb;                        /* Database containing table zTable */
8437   i64 covering;                   /* Mask of columns required for cov. index */
8438   IdxConstraint *pOrder;          /* ORDER BY columns */
8439   IdxConstraint *pEq;             /* List of == constraints */
8440   IdxConstraint *pRange;          /* List of < constraints */
8441   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
8442 };
8443
8444 /*
8445 ** Information regarding a single database table. Extracted from 
8446 ** "PRAGMA table_info" by function idxGetTableInfo().
8447 */
8448 struct IdxColumn {
8449   char *zName;
8450   char *zColl;
8451   int iPk;
8452 };
8453 struct IdxTable {
8454   int nCol;
8455   char *zName;                    /* Table name */
8456   IdxColumn *aCol;
8457   IdxTable *pNext;                /* Next table in linked list of all tables */
8458 };
8459
8460 /*
8461 ** An object of the following type is created for each unique table/write-op
8462 ** seen. The objects are stored in a singly-linked list beginning at
8463 ** sqlite3expert.pWrite.
8464 */
8465 struct IdxWrite {
8466   IdxTable *pTab;
8467   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
8468   IdxWrite *pNext;
8469 };
8470
8471 /*
8472 ** Each statement being analyzed is represented by an instance of this
8473 ** structure.
8474 */
8475 struct IdxStatement {
8476   int iId;                        /* Statement number */
8477   char *zSql;                     /* SQL statement */
8478   char *zIdx;                     /* Indexes */
8479   char *zEQP;                     /* Plan */
8480   IdxStatement *pNext;
8481 };
8482
8483
8484 /*
8485 ** A hash table for storing strings. With space for a payload string
8486 ** with each entry. Methods are:
8487 **
8488 **   idxHashInit()
8489 **   idxHashClear()
8490 **   idxHashAdd()
8491 **   idxHashSearch()
8492 */
8493 #define IDX_HASH_SIZE 1023
8494 typedef struct IdxHashEntry IdxHashEntry;
8495 typedef struct IdxHash IdxHash;
8496 struct IdxHashEntry {
8497   char *zKey;                     /* nul-terminated key */
8498   char *zVal;                     /* nul-terminated value string */
8499   char *zVal2;                    /* nul-terminated value string 2 */
8500   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
8501   IdxHashEntry *pNext;            /* Next entry in hash */
8502 };
8503 struct IdxHash {
8504   IdxHashEntry *pFirst;
8505   IdxHashEntry *aHash[IDX_HASH_SIZE];
8506 };
8507
8508 /*
8509 ** sqlite3expert object.
8510 */
8511 struct sqlite3expert {
8512   int iSample;                    /* Percentage of tables to sample for stat1 */
8513   sqlite3 *db;                    /* User database */
8514   sqlite3 *dbm;                   /* In-memory db for this analysis */
8515   sqlite3 *dbv;                   /* Vtab schema for this analysis */
8516   IdxTable *pTable;               /* List of all IdxTable objects */
8517   IdxScan *pScan;                 /* List of scan objects */
8518   IdxWrite *pWrite;               /* List of write objects */
8519   IdxStatement *pStatement;       /* List of IdxStatement objects */
8520   int bRun;                       /* True once analysis has run */
8521   char **pzErrmsg;
8522   int rc;                         /* Error code from whereinfo hook */
8523   IdxHash hIdx;                   /* Hash containing all candidate indexes */
8524   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
8525 };
8526
8527
8528 /*
8529 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). 
8530 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
8531 */
8532 static void *idxMalloc(int *pRc, int nByte){
8533   void *pRet;
8534   assert( *pRc==SQLITE_OK );
8535   assert( nByte>0 );
8536   pRet = sqlite3_malloc(nByte);
8537   if( pRet ){
8538     memset(pRet, 0, nByte);
8539   }else{
8540     *pRc = SQLITE_NOMEM;
8541   }
8542   return pRet;
8543 }
8544
8545 /*
8546 ** Initialize an IdxHash hash table.
8547 */
8548 static void idxHashInit(IdxHash *pHash){
8549   memset(pHash, 0, sizeof(IdxHash));
8550 }
8551
8552 /*
8553 ** Reset an IdxHash hash table.
8554 */
8555 static void idxHashClear(IdxHash *pHash){
8556   int i;
8557   for(i=0; i<IDX_HASH_SIZE; i++){
8558     IdxHashEntry *pEntry;
8559     IdxHashEntry *pNext;
8560     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
8561       pNext = pEntry->pHashNext;
8562       sqlite3_free(pEntry->zVal2);
8563       sqlite3_free(pEntry);
8564     }
8565   }
8566   memset(pHash, 0, sizeof(IdxHash));
8567 }
8568
8569 /*
8570 ** Return the index of the hash bucket that the string specified by the
8571 ** arguments to this function belongs.
8572 */
8573 static int idxHashString(const char *z, int n){
8574   unsigned int ret = 0;
8575   int i;
8576   for(i=0; i<n; i++){
8577     ret += (ret<<3) + (unsigned char)(z[i]);
8578   }
8579   return (int)(ret % IDX_HASH_SIZE);
8580 }
8581
8582 /*
8583 ** If zKey is already present in the hash table, return non-zero and do
8584 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
8585 ** the hash table passed as the second argument. 
8586 */
8587 static int idxHashAdd(
8588   int *pRc, 
8589   IdxHash *pHash, 
8590   const char *zKey,
8591   const char *zVal
8592 ){
8593   int nKey = STRLEN(zKey);
8594   int iHash = idxHashString(zKey, nKey);
8595   int nVal = (zVal ? STRLEN(zVal) : 0);
8596   IdxHashEntry *pEntry;
8597   assert( iHash>=0 );
8598   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
8599     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
8600       return 1;
8601     }
8602   }
8603   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
8604   if( pEntry ){
8605     pEntry->zKey = (char*)&pEntry[1];
8606     memcpy(pEntry->zKey, zKey, nKey);
8607     if( zVal ){
8608       pEntry->zVal = &pEntry->zKey[nKey+1];
8609       memcpy(pEntry->zVal, zVal, nVal);
8610     }
8611     pEntry->pHashNext = pHash->aHash[iHash];
8612     pHash->aHash[iHash] = pEntry;
8613
8614     pEntry->pNext = pHash->pFirst;
8615     pHash->pFirst = pEntry;
8616   }
8617   return 0;
8618 }
8619
8620 /*
8621 ** If zKey/nKey is present in the hash table, return a pointer to the 
8622 ** hash-entry object.
8623 */
8624 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
8625   int iHash;
8626   IdxHashEntry *pEntry;
8627   if( nKey<0 ) nKey = STRLEN(zKey);
8628   iHash = idxHashString(zKey, nKey);
8629   assert( iHash>=0 );
8630   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
8631     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
8632       return pEntry;
8633     }
8634   }
8635   return 0;
8636 }
8637
8638 /*
8639 ** If the hash table contains an entry with a key equal to the string
8640 ** passed as the final two arguments to this function, return a pointer
8641 ** to the payload string. Otherwise, if zKey/nKey is not present in the
8642 ** hash table, return NULL.
8643 */
8644 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
8645   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
8646   if( pEntry ) return pEntry->zVal;
8647   return 0;
8648 }
8649
8650 /*
8651 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
8652 ** variable to point to a copy of nul-terminated string zColl.
8653 */
8654 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
8655   IdxConstraint *pNew;
8656   int nColl = STRLEN(zColl);
8657
8658   assert( *pRc==SQLITE_OK );
8659   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
8660   if( pNew ){
8661     pNew->zColl = (char*)&pNew[1];
8662     memcpy(pNew->zColl, zColl, nColl+1);
8663   }
8664   return pNew;
8665 }
8666
8667 /*
8668 ** An error associated with database handle db has just occurred. Pass
8669 ** the error message to callback function xOut.
8670 */
8671 static void idxDatabaseError(
8672   sqlite3 *db,                    /* Database handle */
8673   char **pzErrmsg                 /* Write error here */
8674 ){
8675   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
8676 }
8677
8678 /*
8679 ** Prepare an SQL statement.
8680 */
8681 static int idxPrepareStmt(
8682   sqlite3 *db,                    /* Database handle to compile against */
8683   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
8684   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
8685   const char *zSql                /* SQL statement to compile */
8686 ){
8687   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
8688   if( rc!=SQLITE_OK ){
8689     *ppStmt = 0;
8690     idxDatabaseError(db, pzErrmsg);
8691   }
8692   return rc;
8693 }
8694
8695 /*
8696 ** Prepare an SQL statement using the results of a printf() formatting.
8697 */
8698 static int idxPrintfPrepareStmt(
8699   sqlite3 *db,                    /* Database handle to compile against */
8700   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
8701   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
8702   const char *zFmt,               /* printf() format of SQL statement */
8703   ...                             /* Trailing printf() arguments */
8704 ){
8705   va_list ap;
8706   int rc;
8707   char *zSql;
8708   va_start(ap, zFmt);
8709   zSql = sqlite3_vmprintf(zFmt, ap);
8710   if( zSql==0 ){
8711     rc = SQLITE_NOMEM;
8712   }else{
8713     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
8714     sqlite3_free(zSql);
8715   }
8716   va_end(ap);
8717   return rc;
8718 }
8719
8720
8721 /*************************************************************************
8722 ** Beginning of virtual table implementation.
8723 */
8724 typedef struct ExpertVtab ExpertVtab;
8725 struct ExpertVtab {
8726   sqlite3_vtab base;
8727   IdxTable *pTab;
8728   sqlite3expert *pExpert;
8729 };
8730
8731 typedef struct ExpertCsr ExpertCsr;
8732 struct ExpertCsr {
8733   sqlite3_vtab_cursor base;
8734   sqlite3_stmt *pData;
8735 };
8736
8737 static char *expertDequote(const char *zIn){
8738   int n = STRLEN(zIn);
8739   char *zRet = sqlite3_malloc(n);
8740
8741   assert( zIn[0]=='\'' );
8742   assert( zIn[n-1]=='\'' );
8743
8744   if( zRet ){
8745     int iOut = 0;
8746     int iIn = 0;
8747     for(iIn=1; iIn<(n-1); iIn++){
8748       if( zIn[iIn]=='\'' ){
8749         assert( zIn[iIn+1]=='\'' );
8750         iIn++;
8751       }
8752       zRet[iOut++] = zIn[iIn];
8753     }
8754     zRet[iOut] = '\0';
8755   }
8756
8757   return zRet;
8758 }
8759
8760 /* 
8761 ** This function is the implementation of both the xConnect and xCreate
8762 ** methods of the r-tree virtual table.
8763 **
8764 **   argv[0]   -> module name
8765 **   argv[1]   -> database name
8766 **   argv[2]   -> table name
8767 **   argv[...] -> column names...
8768 */
8769 static int expertConnect(
8770   sqlite3 *db,
8771   void *pAux,
8772   int argc, const char *const*argv,
8773   sqlite3_vtab **ppVtab,
8774   char **pzErr
8775 ){
8776   sqlite3expert *pExpert = (sqlite3expert*)pAux;
8777   ExpertVtab *p = 0;
8778   int rc;
8779
8780   if( argc!=4 ){
8781     *pzErr = sqlite3_mprintf("internal error!");
8782     rc = SQLITE_ERROR;
8783   }else{
8784     char *zCreateTable = expertDequote(argv[3]);
8785     if( zCreateTable ){
8786       rc = sqlite3_declare_vtab(db, zCreateTable);
8787       if( rc==SQLITE_OK ){
8788         p = idxMalloc(&rc, sizeof(ExpertVtab));
8789       }
8790       if( rc==SQLITE_OK ){
8791         p->pExpert = pExpert;
8792         p->pTab = pExpert->pTable;
8793         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
8794       }
8795       sqlite3_free(zCreateTable);
8796     }else{
8797       rc = SQLITE_NOMEM;
8798     }
8799   }
8800
8801   *ppVtab = (sqlite3_vtab*)p;
8802   return rc;
8803 }
8804
8805 static int expertDisconnect(sqlite3_vtab *pVtab){
8806   ExpertVtab *p = (ExpertVtab*)pVtab;
8807   sqlite3_free(p);
8808   return SQLITE_OK;
8809 }
8810
8811 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
8812   ExpertVtab *p = (ExpertVtab*)pVtab;
8813   int rc = SQLITE_OK;
8814   int n = 0;
8815   IdxScan *pScan;
8816   const int opmask = 
8817     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
8818     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
8819     SQLITE_INDEX_CONSTRAINT_LE;
8820
8821   pScan = idxMalloc(&rc, sizeof(IdxScan));
8822   if( pScan ){
8823     int i;
8824
8825     /* Link the new scan object into the list */
8826     pScan->pTab = p->pTab;
8827     pScan->pNextScan = p->pExpert->pScan;
8828     p->pExpert->pScan = pScan;
8829
8830     /* Add the constraints to the IdxScan object */
8831     for(i=0; i<pIdxInfo->nConstraint; i++){
8832       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
8833       if( pCons->usable 
8834        && pCons->iColumn>=0 
8835        && p->pTab->aCol[pCons->iColumn].iPk==0
8836        && (pCons->op & opmask) 
8837       ){
8838         IdxConstraint *pNew;
8839         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
8840         pNew = idxNewConstraint(&rc, zColl);
8841         if( pNew ){
8842           pNew->iCol = pCons->iColumn;
8843           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
8844             pNew->pNext = pScan->pEq;
8845             pScan->pEq = pNew;
8846           }else{
8847             pNew->bRange = 1;
8848             pNew->pNext = pScan->pRange;
8849             pScan->pRange = pNew;
8850           }
8851         }
8852         n++;
8853         pIdxInfo->aConstraintUsage[i].argvIndex = n;
8854       }
8855     }
8856
8857     /* Add the ORDER BY to the IdxScan object */
8858     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
8859       int iCol = pIdxInfo->aOrderBy[i].iColumn;
8860       if( iCol>=0 ){
8861         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
8862         if( pNew ){
8863           pNew->iCol = iCol;
8864           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
8865           pNew->pNext = pScan->pOrder;
8866           pNew->pLink = pScan->pOrder;
8867           pScan->pOrder = pNew;
8868           n++;
8869         }
8870       }
8871     }
8872   }
8873
8874   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
8875   return rc;
8876 }
8877
8878 static int expertUpdate(
8879   sqlite3_vtab *pVtab, 
8880   int nData, 
8881   sqlite3_value **azData, 
8882   sqlite_int64 *pRowid
8883 ){
8884   (void)pVtab;
8885   (void)nData;
8886   (void)azData;
8887   (void)pRowid;
8888   return SQLITE_OK;
8889 }
8890
8891 /* 
8892 ** Virtual table module xOpen method.
8893 */
8894 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
8895   int rc = SQLITE_OK;
8896   ExpertCsr *pCsr;
8897   (void)pVTab;
8898   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
8899   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
8900   return rc;
8901 }
8902
8903 /* 
8904 ** Virtual table module xClose method.
8905 */
8906 static int expertClose(sqlite3_vtab_cursor *cur){
8907   ExpertCsr *pCsr = (ExpertCsr*)cur;
8908   sqlite3_finalize(pCsr->pData);
8909   sqlite3_free(pCsr);
8910   return SQLITE_OK;
8911 }
8912
8913 /*
8914 ** Virtual table module xEof method.
8915 **
8916 ** Return non-zero if the cursor does not currently point to a valid 
8917 ** record (i.e if the scan has finished), or zero otherwise.
8918 */
8919 static int expertEof(sqlite3_vtab_cursor *cur){
8920   ExpertCsr *pCsr = (ExpertCsr*)cur;
8921   return pCsr->pData==0;
8922 }
8923
8924 /* 
8925 ** Virtual table module xNext method.
8926 */
8927 static int expertNext(sqlite3_vtab_cursor *cur){
8928   ExpertCsr *pCsr = (ExpertCsr*)cur;
8929   int rc = SQLITE_OK;
8930
8931   assert( pCsr->pData );
8932   rc = sqlite3_step(pCsr->pData);
8933   if( rc!=SQLITE_ROW ){
8934     rc = sqlite3_finalize(pCsr->pData);
8935     pCsr->pData = 0;
8936   }else{
8937     rc = SQLITE_OK;
8938   }
8939
8940   return rc;
8941 }
8942
8943 /* 
8944 ** Virtual table module xRowid method.
8945 */
8946 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8947   (void)cur;
8948   *pRowid = 0;
8949   return SQLITE_OK;
8950 }
8951
8952 /* 
8953 ** Virtual table module xColumn method.
8954 */
8955 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
8956   ExpertCsr *pCsr = (ExpertCsr*)cur;
8957   sqlite3_value *pVal;
8958   pVal = sqlite3_column_value(pCsr->pData, i);
8959   if( pVal ){
8960     sqlite3_result_value(ctx, pVal);
8961   }
8962   return SQLITE_OK;
8963 }
8964
8965 /* 
8966 ** Virtual table module xFilter method.
8967 */
8968 static int expertFilter(
8969   sqlite3_vtab_cursor *cur, 
8970   int idxNum, const char *idxStr,
8971   int argc, sqlite3_value **argv
8972 ){
8973   ExpertCsr *pCsr = (ExpertCsr*)cur;
8974   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
8975   sqlite3expert *pExpert = pVtab->pExpert;
8976   int rc;
8977
8978   (void)idxNum;
8979   (void)idxStr;
8980   (void)argc;
8981   (void)argv;
8982   rc = sqlite3_finalize(pCsr->pData);
8983   pCsr->pData = 0;
8984   if( rc==SQLITE_OK ){
8985     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
8986         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
8987     );
8988   }
8989
8990   if( rc==SQLITE_OK ){
8991     rc = expertNext(cur);
8992   }
8993   return rc;
8994 }
8995
8996 static int idxRegisterVtab(sqlite3expert *p){
8997   static sqlite3_module expertModule = {
8998     2,                            /* iVersion */
8999     expertConnect,                /* xCreate - create a table */
9000     expertConnect,                /* xConnect - connect to an existing table */
9001     expertBestIndex,              /* xBestIndex - Determine search strategy */
9002     expertDisconnect,             /* xDisconnect - Disconnect from a table */
9003     expertDisconnect,             /* xDestroy - Drop a table */
9004     expertOpen,                   /* xOpen - open a cursor */
9005     expertClose,                  /* xClose - close a cursor */
9006     expertFilter,                 /* xFilter - configure scan constraints */
9007     expertNext,                   /* xNext - advance a cursor */
9008     expertEof,                    /* xEof */
9009     expertColumn,                 /* xColumn - read data */
9010     expertRowid,                  /* xRowid - read data */
9011     expertUpdate,                 /* xUpdate - write data */
9012     0,                            /* xBegin - begin transaction */
9013     0,                            /* xSync - sync transaction */
9014     0,                            /* xCommit - commit transaction */
9015     0,                            /* xRollback - rollback transaction */
9016     0,                            /* xFindFunction - function overloading */
9017     0,                            /* xRename - rename the table */
9018     0,                            /* xSavepoint */
9019     0,                            /* xRelease */
9020     0,                            /* xRollbackTo */
9021     0,                            /* xShadowName */
9022   };
9023
9024   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
9025 }
9026 /*
9027 ** End of virtual table implementation.
9028 *************************************************************************/
9029 /*
9030 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
9031 ** is called, set it to the return value of sqlite3_finalize() before
9032 ** returning. Otherwise, discard the sqlite3_finalize() return value.
9033 */
9034 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
9035   int rc = sqlite3_finalize(pStmt);
9036   if( *pRc==SQLITE_OK ) *pRc = rc;
9037 }
9038
9039 /*
9040 ** Attempt to allocate an IdxTable structure corresponding to table zTab
9041 ** in the main database of connection db. If successful, set (*ppOut) to
9042 ** point to the new object and return SQLITE_OK. Otherwise, return an
9043 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
9044 ** set to point to an error string.
9045 **
9046 ** It is the responsibility of the caller to eventually free either the
9047 ** IdxTable object or error message using sqlite3_free().
9048 */
9049 static int idxGetTableInfo(
9050   sqlite3 *db,                    /* Database connection to read details from */
9051   const char *zTab,               /* Table name */
9052   IdxTable **ppOut,               /* OUT: New object (if successful) */
9053   char **pzErrmsg                 /* OUT: Error message (if not) */
9054 ){
9055   sqlite3_stmt *p1 = 0;
9056   int nCol = 0;
9057   int nTab = STRLEN(zTab);
9058   int nByte = sizeof(IdxTable) + nTab + 1;
9059   IdxTable *pNew = 0;
9060   int rc, rc2;
9061   char *pCsr = 0;
9062   int nPk = 0;
9063
9064   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
9065   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
9066     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
9067     nByte += 1 + STRLEN(zCol);
9068     rc = sqlite3_table_column_metadata(
9069         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
9070     );
9071     nByte += 1 + STRLEN(zCol);
9072     nCol++;
9073     nPk += (sqlite3_column_int(p1, 5)>0);
9074   }
9075   rc2 = sqlite3_reset(p1);
9076   if( rc==SQLITE_OK ) rc = rc2;
9077
9078   nByte += sizeof(IdxColumn) * nCol;
9079   if( rc==SQLITE_OK ){
9080     pNew = idxMalloc(&rc, nByte);
9081   }
9082   if( rc==SQLITE_OK ){
9083     pNew->aCol = (IdxColumn*)&pNew[1];
9084     pNew->nCol = nCol;
9085     pCsr = (char*)&pNew->aCol[nCol];
9086   }
9087
9088   nCol = 0;
9089   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
9090     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
9091     int nCopy = STRLEN(zCol) + 1;
9092     pNew->aCol[nCol].zName = pCsr;
9093     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
9094     memcpy(pCsr, zCol, nCopy);
9095     pCsr += nCopy;
9096
9097     rc = sqlite3_table_column_metadata(
9098         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
9099     );
9100     if( rc==SQLITE_OK ){
9101       nCopy = STRLEN(zCol) + 1;
9102       pNew->aCol[nCol].zColl = pCsr;
9103       memcpy(pCsr, zCol, nCopy);
9104       pCsr += nCopy;
9105     }
9106
9107     nCol++;
9108   }
9109   idxFinalize(&rc, p1);
9110
9111   if( rc!=SQLITE_OK ){
9112     sqlite3_free(pNew);
9113     pNew = 0;
9114   }else{
9115     pNew->zName = pCsr;
9116     memcpy(pNew->zName, zTab, nTab+1);
9117   }
9118
9119   *ppOut = pNew;
9120   return rc;
9121 }
9122
9123 /*
9124 ** This function is a no-op if *pRc is set to anything other than 
9125 ** SQLITE_OK when it is called.
9126 **
9127 ** If *pRc is initially set to SQLITE_OK, then the text specified by
9128 ** the printf() style arguments is appended to zIn and the result returned
9129 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
9130 ** zIn before returning.
9131 */
9132 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
9133   va_list ap;
9134   char *zAppend = 0;
9135   char *zRet = 0;
9136   int nIn = zIn ? STRLEN(zIn) : 0;
9137   int nAppend = 0;
9138   va_start(ap, zFmt);
9139   if( *pRc==SQLITE_OK ){
9140     zAppend = sqlite3_vmprintf(zFmt, ap);
9141     if( zAppend ){
9142       nAppend = STRLEN(zAppend);
9143       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
9144     }
9145     if( zAppend && zRet ){
9146       if( nIn ) memcpy(zRet, zIn, nIn);
9147       memcpy(&zRet[nIn], zAppend, nAppend+1);
9148     }else{
9149       sqlite3_free(zRet);
9150       zRet = 0;
9151       *pRc = SQLITE_NOMEM;
9152     }
9153     sqlite3_free(zAppend);
9154     sqlite3_free(zIn);
9155   }
9156   va_end(ap);
9157   return zRet;
9158 }
9159
9160 /*
9161 ** Return true if zId must be quoted in order to use it as an SQL
9162 ** identifier, or false otherwise.
9163 */
9164 static int idxIdentifierRequiresQuotes(const char *zId){
9165   int i;
9166   for(i=0; zId[i]; i++){
9167     if( !(zId[i]=='_')
9168      && !(zId[i]>='0' && zId[i]<='9')
9169      && !(zId[i]>='a' && zId[i]<='z')
9170      && !(zId[i]>='A' && zId[i]<='Z')
9171     ){
9172       return 1;
9173     }
9174   }
9175   return 0;
9176 }
9177
9178 /*
9179 ** This function appends an index column definition suitable for constraint
9180 ** pCons to the string passed as zIn and returns the result.
9181 */
9182 static char *idxAppendColDefn(
9183   int *pRc,                       /* IN/OUT: Error code */
9184   char *zIn,                      /* Column defn accumulated so far */
9185   IdxTable *pTab,                 /* Table index will be created on */
9186   IdxConstraint *pCons
9187 ){
9188   char *zRet = zIn;
9189   IdxColumn *p = &pTab->aCol[pCons->iCol];
9190   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
9191
9192   if( idxIdentifierRequiresQuotes(p->zName) ){
9193     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
9194   }else{
9195     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
9196   }
9197
9198   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
9199     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
9200       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
9201     }else{
9202       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
9203     }
9204   }
9205
9206   if( pCons->bDesc ){
9207     zRet = idxAppendText(pRc, zRet, " DESC");
9208   }
9209   return zRet;
9210 }
9211
9212 /*
9213 ** Search database dbm for an index compatible with the one idxCreateFromCons()
9214 ** would create from arguments pScan, pEq and pTail. If no error occurs and 
9215 ** such an index is found, return non-zero. Or, if no such index is found,
9216 ** return zero.
9217 **
9218 ** If an error occurs, set *pRc to an SQLite error code and return zero.
9219 */
9220 static int idxFindCompatible(
9221   int *pRc,                       /* OUT: Error code */
9222   sqlite3* dbm,                   /* Database to search */
9223   IdxScan *pScan,                 /* Scan for table to search for index on */
9224   IdxConstraint *pEq,             /* List of == constraints */
9225   IdxConstraint *pTail            /* List of range constraints */
9226 ){
9227   const char *zTbl = pScan->pTab->zName;
9228   sqlite3_stmt *pIdxList = 0;
9229   IdxConstraint *pIter;
9230   int nEq = 0;                    /* Number of elements in pEq */
9231   int rc;
9232
9233   /* Count the elements in list pEq */
9234   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
9235
9236   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
9237   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
9238     int bMatch = 1;
9239     IdxConstraint *pT = pTail;
9240     sqlite3_stmt *pInfo = 0;
9241     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
9242
9243     /* Zero the IdxConstraint.bFlag values in the pEq list */
9244     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
9245
9246     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
9247     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
9248       int iIdx = sqlite3_column_int(pInfo, 0);
9249       int iCol = sqlite3_column_int(pInfo, 1);
9250       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
9251
9252       if( iIdx<nEq ){
9253         for(pIter=pEq; pIter; pIter=pIter->pLink){
9254           if( pIter->bFlag ) continue;
9255           if( pIter->iCol!=iCol ) continue;
9256           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
9257           pIter->bFlag = 1;
9258           break;
9259         }
9260         if( pIter==0 ){
9261           bMatch = 0;
9262           break;
9263         }
9264       }else{
9265         if( pT ){
9266           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
9267             bMatch = 0;
9268             break;
9269           }
9270           pT = pT->pLink;
9271         }
9272       }
9273     }
9274     idxFinalize(&rc, pInfo);
9275
9276     if( rc==SQLITE_OK && bMatch ){
9277       sqlite3_finalize(pIdxList);
9278       return 1;
9279     }
9280   }
9281   idxFinalize(&rc, pIdxList);
9282
9283   *pRc = rc;
9284   return 0;
9285 }
9286
9287 static int idxCreateFromCons(
9288   sqlite3expert *p,
9289   IdxScan *pScan,
9290   IdxConstraint *pEq, 
9291   IdxConstraint *pTail
9292 ){
9293   sqlite3 *dbm = p->dbm;
9294   int rc = SQLITE_OK;
9295   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
9296     IdxTable *pTab = pScan->pTab;
9297     char *zCols = 0;
9298     char *zIdx = 0;
9299     IdxConstraint *pCons;
9300     unsigned int h = 0;
9301     const char *zFmt;
9302
9303     for(pCons=pEq; pCons; pCons=pCons->pLink){
9304       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
9305     }
9306     for(pCons=pTail; pCons; pCons=pCons->pLink){
9307       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
9308     }
9309
9310     if( rc==SQLITE_OK ){
9311       /* Hash the list of columns to come up with a name for the index */
9312       const char *zTable = pScan->pTab->zName;
9313       char *zName;                /* Index name */
9314       int i;
9315       for(i=0; zCols[i]; i++){
9316         h += ((h<<3) + zCols[i]);
9317       }
9318       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
9319       if( zName==0 ){ 
9320         rc = SQLITE_NOMEM;
9321       }else{
9322         if( idxIdentifierRequiresQuotes(zTable) ){
9323           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
9324         }else{
9325           zFmt = "CREATE INDEX %s ON %s(%s)";
9326         }
9327         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
9328         if( !zIdx ){
9329           rc = SQLITE_NOMEM;
9330         }else{
9331           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
9332           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
9333         }
9334         sqlite3_free(zName);
9335         sqlite3_free(zIdx);
9336       }
9337     }
9338
9339     sqlite3_free(zCols);
9340   }
9341   return rc;
9342 }
9343
9344 /*
9345 ** Return true if list pList (linked by IdxConstraint.pLink) contains
9346 ** a constraint compatible with *p. Otherwise return false.
9347 */
9348 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
9349   IdxConstraint *pCmp;
9350   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
9351     if( p->iCol==pCmp->iCol ) return 1;
9352   }
9353   return 0;
9354 }
9355
9356 static int idxCreateFromWhere(
9357   sqlite3expert *p, 
9358   IdxScan *pScan,                 /* Create indexes for this scan */
9359   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
9360 ){
9361   IdxConstraint *p1 = 0;
9362   IdxConstraint *pCon;
9363   int rc;
9364
9365   /* Gather up all the == constraints. */
9366   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
9367     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
9368       pCon->pLink = p1;
9369       p1 = pCon;
9370     }
9371   }
9372
9373   /* Create an index using the == constraints collected above. And the
9374   ** range constraint/ORDER BY terms passed in by the caller, if any. */
9375   rc = idxCreateFromCons(p, pScan, p1, pTail);
9376
9377   /* If no range/ORDER BY passed by the caller, create a version of the
9378   ** index for each range constraint.  */
9379   if( pTail==0 ){
9380     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
9381       assert( pCon->pLink==0 );
9382       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
9383         rc = idxCreateFromCons(p, pScan, p1, pCon);
9384       }
9385     }
9386   }
9387
9388   return rc;
9389 }
9390
9391 /*
9392 ** Create candidate indexes in database [dbm] based on the data in 
9393 ** linked-list pScan.
9394 */
9395 static int idxCreateCandidates(sqlite3expert *p){
9396   int rc = SQLITE_OK;
9397   IdxScan *pIter;
9398
9399   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
9400     rc = idxCreateFromWhere(p, pIter, 0);
9401     if( rc==SQLITE_OK && pIter->pOrder ){
9402       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
9403     }
9404   }
9405
9406   return rc;
9407 }
9408
9409 /*
9410 ** Free all elements of the linked list starting at pConstraint.
9411 */
9412 static void idxConstraintFree(IdxConstraint *pConstraint){
9413   IdxConstraint *pNext;
9414   IdxConstraint *p;
9415
9416   for(p=pConstraint; p; p=pNext){
9417     pNext = p->pNext;
9418     sqlite3_free(p);
9419   }
9420 }
9421
9422 /*
9423 ** Free all elements of the linked list starting from pScan up until pLast
9424 ** (pLast is not freed).
9425 */
9426 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
9427   IdxScan *p;
9428   IdxScan *pNext;
9429   for(p=pScan; p!=pLast; p=pNext){
9430     pNext = p->pNextScan;
9431     idxConstraintFree(p->pOrder);
9432     idxConstraintFree(p->pEq);
9433     idxConstraintFree(p->pRange);
9434     sqlite3_free(p);
9435   }
9436 }
9437
9438 /*
9439 ** Free all elements of the linked list starting from pStatement up 
9440 ** until pLast (pLast is not freed).
9441 */
9442 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
9443   IdxStatement *p;
9444   IdxStatement *pNext;
9445   for(p=pStatement; p!=pLast; p=pNext){
9446     pNext = p->pNext;
9447     sqlite3_free(p->zEQP);
9448     sqlite3_free(p->zIdx);
9449     sqlite3_free(p);
9450   }
9451 }
9452
9453 /*
9454 ** Free the linked list of IdxTable objects starting at pTab.
9455 */
9456 static void idxTableFree(IdxTable *pTab){
9457   IdxTable *pIter;
9458   IdxTable *pNext;
9459   for(pIter=pTab; pIter; pIter=pNext){
9460     pNext = pIter->pNext;
9461     sqlite3_free(pIter);
9462   }
9463 }
9464
9465 /*
9466 ** Free the linked list of IdxWrite objects starting at pTab.
9467 */
9468 static void idxWriteFree(IdxWrite *pTab){
9469   IdxWrite *pIter;
9470   IdxWrite *pNext;
9471   for(pIter=pTab; pIter; pIter=pNext){
9472     pNext = pIter->pNext;
9473     sqlite3_free(pIter);
9474   }
9475 }
9476
9477
9478
9479 /*
9480 ** This function is called after candidate indexes have been created. It
9481 ** runs all the queries to see which indexes they prefer, and populates
9482 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
9483 */
9484 int idxFindIndexes(
9485   sqlite3expert *p,
9486   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
9487 ){
9488   IdxStatement *pStmt;
9489   sqlite3 *dbm = p->dbm;
9490   int rc = SQLITE_OK;
9491
9492   IdxHash hIdx;
9493   idxHashInit(&hIdx);
9494
9495   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
9496     IdxHashEntry *pEntry;
9497     sqlite3_stmt *pExplain = 0;
9498     idxHashClear(&hIdx);
9499     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
9500         "EXPLAIN QUERY PLAN %s", pStmt->zSql
9501     );
9502     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
9503       /* int iId = sqlite3_column_int(pExplain, 0); */
9504       /* int iParent = sqlite3_column_int(pExplain, 1); */
9505       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
9506       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
9507       int nDetail;
9508       int i;
9509
9510       if( !zDetail ) continue;
9511       nDetail = STRLEN(zDetail);
9512
9513       for(i=0; i<nDetail; i++){
9514         const char *zIdx = 0;
9515         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
9516           zIdx = &zDetail[i+13];
9517         }else if( i+22<nDetail 
9518             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 
9519         ){
9520           zIdx = &zDetail[i+22];
9521         }
9522         if( zIdx ){
9523           const char *zSql;
9524           int nIdx = 0;
9525           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
9526             nIdx++;
9527           }
9528           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
9529           if( zSql ){
9530             idxHashAdd(&rc, &hIdx, zSql, 0);
9531             if( rc ) goto find_indexes_out;
9532           }
9533           break;
9534         }
9535       }
9536
9537       if( zDetail[0]!='-' ){
9538         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
9539       }
9540     }
9541
9542     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
9543       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
9544     }
9545
9546     idxFinalize(&rc, pExplain);
9547   }
9548
9549  find_indexes_out:
9550   idxHashClear(&hIdx);
9551   return rc;
9552 }
9553
9554 static int idxAuthCallback(
9555   void *pCtx,
9556   int eOp,
9557   const char *z3,
9558   const char *z4,
9559   const char *zDb,
9560   const char *zTrigger
9561 ){
9562   int rc = SQLITE_OK;
9563   (void)z4;
9564   (void)zTrigger;
9565   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
9566     if( sqlite3_stricmp(zDb, "main")==0 ){
9567       sqlite3expert *p = (sqlite3expert*)pCtx;
9568       IdxTable *pTab;
9569       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
9570         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
9571       }
9572       if( pTab ){
9573         IdxWrite *pWrite;
9574         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
9575           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
9576         }
9577         if( pWrite==0 ){
9578           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
9579           if( rc==SQLITE_OK ){
9580             pWrite->pTab = pTab;
9581             pWrite->eOp = eOp;
9582             pWrite->pNext = p->pWrite;
9583             p->pWrite = pWrite;
9584           }
9585         }
9586       }
9587     }
9588   }
9589   return rc;
9590 }
9591
9592 static int idxProcessOneTrigger(
9593   sqlite3expert *p, 
9594   IdxWrite *pWrite, 
9595   char **pzErr
9596 ){
9597   static const char *zInt = UNIQUE_TABLE_NAME;
9598   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
9599   IdxTable *pTab = pWrite->pTab;
9600   const char *zTab = pTab->zName;
9601   const char *zSql = 
9602     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
9603     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
9604     "ORDER BY type;";
9605   sqlite3_stmt *pSelect = 0;
9606   int rc = SQLITE_OK;
9607   char *zWrite = 0;
9608
9609   /* Create the table and its triggers in the temp schema */
9610   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
9611   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
9612     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
9613     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
9614   }
9615   idxFinalize(&rc, pSelect);
9616
9617   /* Rename the table in the temp schema to zInt */
9618   if( rc==SQLITE_OK ){
9619     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
9620     if( z==0 ){
9621       rc = SQLITE_NOMEM;
9622     }else{
9623       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
9624       sqlite3_free(z);
9625     }
9626   }
9627
9628   switch( pWrite->eOp ){
9629     case SQLITE_INSERT: {
9630       int i;
9631       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
9632       for(i=0; i<pTab->nCol; i++){
9633         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
9634       }
9635       zWrite = idxAppendText(&rc, zWrite, ")");
9636       break;
9637     }
9638     case SQLITE_UPDATE: {
9639       int i;
9640       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
9641       for(i=0; i<pTab->nCol; i++){
9642         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", 
9643             pTab->aCol[i].zName
9644         );
9645       }
9646       break;
9647     }
9648     default: {
9649       assert( pWrite->eOp==SQLITE_DELETE );
9650       if( rc==SQLITE_OK ){
9651         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
9652         if( zWrite==0 ) rc = SQLITE_NOMEM;
9653       }
9654     }
9655   }
9656
9657   if( rc==SQLITE_OK ){
9658     sqlite3_stmt *pX = 0;
9659     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
9660     idxFinalize(&rc, pX);
9661     if( rc!=SQLITE_OK ){
9662       idxDatabaseError(p->dbv, pzErr);
9663     }
9664   }
9665   sqlite3_free(zWrite);
9666
9667   if( rc==SQLITE_OK ){
9668     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
9669   }
9670
9671   return rc;
9672 }
9673
9674 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
9675   int rc = SQLITE_OK;
9676   IdxWrite *pEnd = 0;
9677   IdxWrite *pFirst = p->pWrite;
9678
9679   while( rc==SQLITE_OK && pFirst!=pEnd ){
9680     IdxWrite *pIter;
9681     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
9682       rc = idxProcessOneTrigger(p, pIter, pzErr);
9683     }
9684     pEnd = pFirst;
9685     pFirst = p->pWrite;
9686   }
9687
9688   return rc;
9689 }
9690
9691
9692 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
9693   int rc = idxRegisterVtab(p);
9694   sqlite3_stmt *pSchema = 0;
9695
9696   /* For each table in the main db schema:
9697   **
9698   **   1) Add an entry to the p->pTable list, and
9699   **   2) Create the equivalent virtual table in dbv.
9700   */
9701   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
9702       "SELECT type, name, sql, 1 FROM sqlite_schema "
9703       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
9704       " UNION ALL "
9705       "SELECT type, name, sql, 2 FROM sqlite_schema "
9706       "WHERE type = 'trigger'"
9707       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
9708       "ORDER BY 4, 1"
9709   );
9710   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
9711     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
9712     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
9713     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
9714
9715     if( zType[0]=='v' || zType[1]=='r' ){
9716       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
9717     }else{
9718       IdxTable *pTab;
9719       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
9720       if( rc==SQLITE_OK ){
9721         int i;
9722         char *zInner = 0;
9723         char *zOuter = 0;
9724         pTab->pNext = p->pTable;
9725         p->pTable = pTab;
9726
9727         /* The statement the vtab will pass to sqlite3_declare_vtab() */
9728         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
9729         for(i=0; i<pTab->nCol; i++){
9730           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", 
9731               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
9732           );
9733         }
9734         zInner = idxAppendText(&rc, zInner, ")");
9735
9736         /* The CVT statement to create the vtab */
9737         zOuter = idxAppendText(&rc, 0, 
9738             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
9739         );
9740         if( rc==SQLITE_OK ){
9741           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
9742         }
9743         sqlite3_free(zInner);
9744         sqlite3_free(zOuter);
9745       }
9746     }
9747   }
9748   idxFinalize(&rc, pSchema);
9749   return rc;
9750 }
9751
9752 struct IdxSampleCtx {
9753   int iTarget;
9754   double target;                  /* Target nRet/nRow value */
9755   double nRow;                    /* Number of rows seen */
9756   double nRet;                    /* Number of rows returned */
9757 };
9758
9759 static void idxSampleFunc(
9760   sqlite3_context *pCtx,
9761   int argc,
9762   sqlite3_value **argv
9763 ){
9764   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
9765   int bRet;
9766
9767   (void)argv;
9768   assert( argc==0 );
9769   if( p->nRow==0.0 ){
9770     bRet = 1;
9771   }else{
9772     bRet = (p->nRet / p->nRow) <= p->target;
9773     if( bRet==0 ){
9774       unsigned short rnd;
9775       sqlite3_randomness(2, (void*)&rnd);
9776       bRet = ((int)rnd % 100) <= p->iTarget;
9777     }
9778   }
9779
9780   sqlite3_result_int(pCtx, bRet);
9781   p->nRow += 1.0;
9782   p->nRet += (double)bRet;
9783 }
9784
9785 struct IdxRemCtx {
9786   int nSlot;
9787   struct IdxRemSlot {
9788     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
9789     i64 iVal;                     /* SQLITE_INTEGER value */
9790     double rVal;                  /* SQLITE_FLOAT value */
9791     int nByte;                    /* Bytes of space allocated at z */
9792     int n;                        /* Size of buffer z */
9793     char *z;                      /* SQLITE_TEXT/BLOB value */
9794   } aSlot[1];
9795 };
9796
9797 /*
9798 ** Implementation of scalar function rem().
9799 */
9800 static void idxRemFunc(
9801   sqlite3_context *pCtx,
9802   int argc,
9803   sqlite3_value **argv
9804 ){
9805   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
9806   struct IdxRemSlot *pSlot;
9807   int iSlot;
9808   assert( argc==2 );
9809
9810   iSlot = sqlite3_value_int(argv[0]);
9811   assert( iSlot<=p->nSlot );
9812   pSlot = &p->aSlot[iSlot];
9813
9814   switch( pSlot->eType ){
9815     case SQLITE_NULL:
9816       /* no-op */
9817       break;
9818
9819     case SQLITE_INTEGER:
9820       sqlite3_result_int64(pCtx, pSlot->iVal);
9821       break;
9822
9823     case SQLITE_FLOAT:
9824       sqlite3_result_double(pCtx, pSlot->rVal);
9825       break;
9826
9827     case SQLITE_BLOB:
9828       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
9829       break;
9830
9831     case SQLITE_TEXT:
9832       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
9833       break;
9834   }
9835
9836   pSlot->eType = sqlite3_value_type(argv[1]);
9837   switch( pSlot->eType ){
9838     case SQLITE_NULL:
9839       /* no-op */
9840       break;
9841
9842     case SQLITE_INTEGER:
9843       pSlot->iVal = sqlite3_value_int64(argv[1]);
9844       break;
9845
9846     case SQLITE_FLOAT:
9847       pSlot->rVal = sqlite3_value_double(argv[1]);
9848       break;
9849
9850     case SQLITE_BLOB:
9851     case SQLITE_TEXT: {
9852       int nByte = sqlite3_value_bytes(argv[1]);
9853       if( nByte>pSlot->nByte ){
9854         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
9855         if( zNew==0 ){
9856           sqlite3_result_error_nomem(pCtx);
9857           return;
9858         }
9859         pSlot->nByte = nByte*2;
9860         pSlot->z = zNew;
9861       }
9862       pSlot->n = nByte;
9863       if( pSlot->eType==SQLITE_BLOB ){
9864         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
9865       }else{
9866         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
9867       }
9868       break;
9869     }
9870   }
9871 }
9872
9873 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
9874   int rc = SQLITE_OK;
9875   const char *zMax = 
9876     "SELECT max(i.seqno) FROM "
9877     "  sqlite_schema AS s, "
9878     "  pragma_index_list(s.name) AS l, "
9879     "  pragma_index_info(l.name) AS i "
9880     "WHERE s.type = 'table'";
9881   sqlite3_stmt *pMax = 0;
9882
9883   *pnMax = 0;
9884   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
9885   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
9886     *pnMax = sqlite3_column_int(pMax, 0) + 1;
9887   }
9888   idxFinalize(&rc, pMax);
9889
9890   return rc;
9891 }
9892
9893 static int idxPopulateOneStat1(
9894   sqlite3expert *p,
9895   sqlite3_stmt *pIndexXInfo,
9896   sqlite3_stmt *pWriteStat,
9897   const char *zTab,
9898   const char *zIdx,
9899   char **pzErr
9900 ){
9901   char *zCols = 0;
9902   char *zOrder = 0;
9903   char *zQuery = 0;
9904   int nCol = 0;
9905   int i;
9906   sqlite3_stmt *pQuery = 0;
9907   int *aStat = 0;
9908   int rc = SQLITE_OK;
9909
9910   assert( p->iSample>0 );
9911
9912   /* Formulate the query text */
9913   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
9914   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
9915     const char *zComma = zCols==0 ? "" : ", ";
9916     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
9917     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
9918     zCols = idxAppendText(&rc, zCols, 
9919         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
9920     );
9921     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
9922   }
9923   sqlite3_reset(pIndexXInfo);
9924   if( rc==SQLITE_OK ){
9925     if( p->iSample==100 ){
9926       zQuery = sqlite3_mprintf(
9927           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
9928       );
9929     }else{
9930       zQuery = sqlite3_mprintf(
9931           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
9932       );
9933     }
9934   }
9935   sqlite3_free(zCols);
9936   sqlite3_free(zOrder);
9937
9938   /* Formulate the query text */
9939   if( rc==SQLITE_OK ){
9940     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
9941     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
9942   }
9943   sqlite3_free(zQuery);
9944
9945   if( rc==SQLITE_OK ){
9946     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
9947   }
9948   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
9949     IdxHashEntry *pEntry;
9950     char *zStat = 0;
9951     for(i=0; i<=nCol; i++) aStat[i] = 1;
9952     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
9953       aStat[0]++;
9954       for(i=0; i<nCol; i++){
9955         if( sqlite3_column_int(pQuery, i)==0 ) break;
9956       }
9957       for(/*no-op*/; i<nCol; i++){
9958         aStat[i+1]++;
9959       }
9960     }
9961
9962     if( rc==SQLITE_OK ){
9963       int s0 = aStat[0];
9964       zStat = sqlite3_mprintf("%d", s0);
9965       if( zStat==0 ) rc = SQLITE_NOMEM;
9966       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
9967         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
9968       }
9969     }
9970
9971     if( rc==SQLITE_OK ){
9972       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
9973       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
9974       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
9975       sqlite3_step(pWriteStat);
9976       rc = sqlite3_reset(pWriteStat);
9977     }
9978
9979     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
9980     if( pEntry ){
9981       assert( pEntry->zVal2==0 );
9982       pEntry->zVal2 = zStat;
9983     }else{
9984       sqlite3_free(zStat);
9985     }
9986   }
9987   sqlite3_free(aStat);
9988   idxFinalize(&rc, pQuery);
9989
9990   return rc;
9991 }
9992
9993 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
9994   int rc;
9995   char *zSql;
9996
9997   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
9998   if( rc!=SQLITE_OK ) return rc;
9999
10000   zSql = sqlite3_mprintf(
10001       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
10002   );
10003   if( zSql==0 ) return SQLITE_NOMEM;
10004   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
10005   sqlite3_free(zSql);
10006
10007   return rc;
10008 }
10009
10010 /*
10011 ** This function is called as part of sqlite3_expert_analyze(). Candidate
10012 ** indexes have already been created in database sqlite3expert.dbm, this
10013 ** function populates sqlite_stat1 table in the same database.
10014 **
10015 ** The stat1 data is generated by querying the 
10016 */
10017 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
10018   int rc = SQLITE_OK;
10019   int nMax =0;
10020   struct IdxRemCtx *pCtx = 0;
10021   struct IdxSampleCtx samplectx; 
10022   int i;
10023   i64 iPrev = -100000;
10024   sqlite3_stmt *pAllIndex = 0;
10025   sqlite3_stmt *pIndexXInfo = 0;
10026   sqlite3_stmt *pWrite = 0;
10027
10028   const char *zAllIndex =
10029     "SELECT s.rowid, s.name, l.name FROM "
10030     "  sqlite_schema AS s, "
10031     "  pragma_index_list(s.name) AS l "
10032     "WHERE s.type = 'table'";
10033   const char *zIndexXInfo = 
10034     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
10035   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
10036
10037   /* If iSample==0, no sqlite_stat1 data is required. */
10038   if( p->iSample==0 ) return SQLITE_OK;
10039
10040   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
10041   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
10042
10043   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
10044
10045   if( rc==SQLITE_OK ){
10046     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
10047     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
10048   }
10049
10050   if( rc==SQLITE_OK ){
10051     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
10052     rc = sqlite3_create_function(
10053         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
10054     );
10055   }
10056   if( rc==SQLITE_OK ){
10057     rc = sqlite3_create_function(
10058         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
10059     );
10060   }
10061
10062   if( rc==SQLITE_OK ){
10063     pCtx->nSlot = nMax+1;
10064     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
10065   }
10066   if( rc==SQLITE_OK ){
10067     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
10068   }
10069   if( rc==SQLITE_OK ){
10070     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
10071   }
10072
10073   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
10074     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
10075     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
10076     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
10077     if( p->iSample<100 && iPrev!=iRowid ){
10078       samplectx.target = (double)p->iSample / 100.0;
10079       samplectx.iTarget = p->iSample;
10080       samplectx.nRow = 0.0;
10081       samplectx.nRet = 0.0;
10082       rc = idxBuildSampleTable(p, zTab);
10083       if( rc!=SQLITE_OK ) break;
10084     }
10085     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
10086     iPrev = iRowid;
10087   }
10088   if( rc==SQLITE_OK && p->iSample<100 ){
10089     rc = sqlite3_exec(p->dbv, 
10090         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
10091     );
10092   }
10093
10094   idxFinalize(&rc, pAllIndex);
10095   idxFinalize(&rc, pIndexXInfo);
10096   idxFinalize(&rc, pWrite);
10097
10098   if( pCtx ){
10099     for(i=0; i<pCtx->nSlot; i++){
10100       sqlite3_free(pCtx->aSlot[i].z);
10101     }
10102     sqlite3_free(pCtx);
10103   }
10104
10105   if( rc==SQLITE_OK ){
10106     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
10107   }
10108
10109   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
10110   return rc;
10111 }
10112
10113 /*
10114 ** Allocate a new sqlite3expert object.
10115 */
10116 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
10117   int rc = SQLITE_OK;
10118   sqlite3expert *pNew;
10119
10120   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
10121
10122   /* Open two in-memory databases to work with. The "vtab database" (dbv)
10123   ** will contain a virtual table corresponding to each real table in
10124   ** the user database schema, and a copy of each view. It is used to
10125   ** collect information regarding the WHERE, ORDER BY and other clauses
10126   ** of the user's query.
10127   */
10128   if( rc==SQLITE_OK ){
10129     pNew->db = db;
10130     pNew->iSample = 100;
10131     rc = sqlite3_open(":memory:", &pNew->dbv);
10132   }
10133   if( rc==SQLITE_OK ){
10134     rc = sqlite3_open(":memory:", &pNew->dbm);
10135     if( rc==SQLITE_OK ){
10136       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
10137     }
10138   }
10139   
10140
10141   /* Copy the entire schema of database [db] into [dbm]. */
10142   if( rc==SQLITE_OK ){
10143     sqlite3_stmt *pSql;
10144     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, 
10145         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
10146         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
10147     );
10148     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
10149       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
10150       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
10151     }
10152     idxFinalize(&rc, pSql);
10153   }
10154
10155   /* Create the vtab schema */
10156   if( rc==SQLITE_OK ){
10157     rc = idxCreateVtabSchema(pNew, pzErrmsg);
10158   }
10159
10160   /* Register the auth callback with dbv */
10161   if( rc==SQLITE_OK ){
10162     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
10163   }
10164
10165   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
10166   ** return the new sqlite3expert handle.  */
10167   if( rc!=SQLITE_OK ){
10168     sqlite3_expert_destroy(pNew);
10169     pNew = 0;
10170   }
10171   return pNew;
10172 }
10173
10174 /*
10175 ** Configure an sqlite3expert object.
10176 */
10177 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
10178   int rc = SQLITE_OK;
10179   va_list ap;
10180   va_start(ap, op);
10181   switch( op ){
10182     case EXPERT_CONFIG_SAMPLE: {
10183       int iVal = va_arg(ap, int);
10184       if( iVal<0 ) iVal = 0;
10185       if( iVal>100 ) iVal = 100;
10186       p->iSample = iVal;
10187       break;
10188     }
10189     default:
10190       rc = SQLITE_NOTFOUND;
10191       break;
10192   }
10193
10194   va_end(ap);
10195   return rc;
10196 }
10197
10198 /*
10199 ** Add an SQL statement to the analysis.
10200 */
10201 int sqlite3_expert_sql(
10202   sqlite3expert *p,               /* From sqlite3_expert_new() */
10203   const char *zSql,               /* SQL statement to add */
10204   char **pzErr                    /* OUT: Error message (if any) */
10205 ){
10206   IdxScan *pScanOrig = p->pScan;
10207   IdxStatement *pStmtOrig = p->pStatement;
10208   int rc = SQLITE_OK;
10209   const char *zStmt = zSql;
10210
10211   if( p->bRun ) return SQLITE_MISUSE;
10212
10213   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
10214     sqlite3_stmt *pStmt = 0;
10215     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
10216     if( rc==SQLITE_OK ){
10217       if( pStmt ){
10218         IdxStatement *pNew;
10219         const char *z = sqlite3_sql(pStmt);
10220         int n = STRLEN(z);
10221         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
10222         if( rc==SQLITE_OK ){
10223           pNew->zSql = (char*)&pNew[1];
10224           memcpy(pNew->zSql, z, n+1);
10225           pNew->pNext = p->pStatement;
10226           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
10227           p->pStatement = pNew;
10228         }
10229         sqlite3_finalize(pStmt);
10230       }
10231     }else{
10232       idxDatabaseError(p->dbv, pzErr);
10233     }
10234   }
10235
10236   if( rc!=SQLITE_OK ){
10237     idxScanFree(p->pScan, pScanOrig);
10238     idxStatementFree(p->pStatement, pStmtOrig);
10239     p->pScan = pScanOrig;
10240     p->pStatement = pStmtOrig;
10241   }
10242
10243   return rc;
10244 }
10245
10246 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
10247   int rc;
10248   IdxHashEntry *pEntry;
10249
10250   /* Do trigger processing to collect any extra IdxScan structures */
10251   rc = idxProcessTriggers(p, pzErr);
10252
10253   /* Create candidate indexes within the in-memory database file */
10254   if( rc==SQLITE_OK ){
10255     rc = idxCreateCandidates(p);
10256   }
10257
10258   /* Generate the stat1 data */
10259   if( rc==SQLITE_OK ){
10260     rc = idxPopulateStat1(p, pzErr);
10261   }
10262
10263   /* Formulate the EXPERT_REPORT_CANDIDATES text */
10264   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
10265     p->zCandidates = idxAppendText(&rc, p->zCandidates, 
10266         "%s;%s%s\n", pEntry->zVal, 
10267         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
10268     );
10269   }
10270
10271   /* Figure out which of the candidate indexes are preferred by the query
10272   ** planner and report the results to the user.  */
10273   if( rc==SQLITE_OK ){
10274     rc = idxFindIndexes(p, pzErr);
10275   }
10276
10277   if( rc==SQLITE_OK ){
10278     p->bRun = 1;
10279   }
10280   return rc;
10281 }
10282
10283 /*
10284 ** Return the total number of statements that have been added to this
10285 ** sqlite3expert using sqlite3_expert_sql().
10286 */
10287 int sqlite3_expert_count(sqlite3expert *p){
10288   int nRet = 0;
10289   if( p->pStatement ) nRet = p->pStatement->iId+1;
10290   return nRet;
10291 }
10292
10293 /*
10294 ** Return a component of the report.
10295 */
10296 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
10297   const char *zRet = 0;
10298   IdxStatement *pStmt;
10299
10300   if( p->bRun==0 ) return 0;
10301   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
10302   switch( eReport ){
10303     case EXPERT_REPORT_SQL:
10304       if( pStmt ) zRet = pStmt->zSql;
10305       break;
10306     case EXPERT_REPORT_INDEXES:
10307       if( pStmt ) zRet = pStmt->zIdx;
10308       break;
10309     case EXPERT_REPORT_PLAN:
10310       if( pStmt ) zRet = pStmt->zEQP;
10311       break;
10312     case EXPERT_REPORT_CANDIDATES:
10313       zRet = p->zCandidates;
10314       break;
10315   }
10316   return zRet;
10317 }
10318
10319 /*
10320 ** Free an sqlite3expert object.
10321 */
10322 void sqlite3_expert_destroy(sqlite3expert *p){
10323   if( p ){
10324     sqlite3_close(p->dbm);
10325     sqlite3_close(p->dbv);
10326     idxScanFree(p->pScan, 0);
10327     idxStatementFree(p->pStatement, 0);
10328     idxTableFree(p->pTable);
10329     idxWriteFree(p->pWrite);
10330     idxHashClear(&p->hIdx);
10331     sqlite3_free(p->zCandidates);
10332     sqlite3_free(p);
10333   }
10334 }
10335
10336 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
10337
10338 /************************* End ../ext/expert/sqlite3expert.c ********************/
10339
10340 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
10341 /************************* Begin ../ext/misc/dbdata.c ******************/
10342 /*
10343 ** 2019-04-17
10344 **
10345 ** The author disclaims copyright to this source code.  In place of
10346 ** a legal notice, here is a blessing:
10347 **
10348 **    May you do good and not evil.
10349 **    May you find forgiveness for yourself and forgive others.
10350 **    May you share freely, never taking more than you give.
10351 **
10352 ******************************************************************************
10353 **
10354 ** This file contains an implementation of two eponymous virtual tables,
10355 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
10356 ** "sqlite_dbpage" eponymous virtual table be available.
10357 **
10358 ** SQLITE_DBDATA:
10359 **   sqlite_dbdata is used to extract data directly from a database b-tree
10360 **   page and its associated overflow pages, bypassing the b-tree layer.
10361 **   The table schema is equivalent to:
10362 **
10363 **     CREATE TABLE sqlite_dbdata(
10364 **       pgno INTEGER,
10365 **       cell INTEGER,
10366 **       field INTEGER,
10367 **       value ANY,
10368 **       schema TEXT HIDDEN
10369 **     );
10370 **
10371 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
10372 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
10373 **   "schema".
10374 **
10375 **   Each page of the database is inspected. If it cannot be interpreted as
10376 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
10377 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
10378 **   table contains one row for each field in the record associated with
10379 **   each cell on the page. For intkey b-trees, the key value is stored in
10380 **   field -1.
10381 **
10382 **   For example, for the database:
10383 **
10384 **     CREATE TABLE t1(a, b);     -- root page is page 2
10385 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
10386 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
10387 **
10388 **   the sqlite_dbdata table contains, as well as from entries related to 
10389 **   page 1, content equivalent to:
10390 **
10391 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
10392 **         (2, 0, -1, 5     ),
10393 **         (2, 0,  0, 'v'   ),
10394 **         (2, 0,  1, 'five'),
10395 **         (2, 1, -1, 10    ),
10396 **         (2, 1,  0, 'x'   ),
10397 **         (2, 1,  1, 'ten' );
10398 **
10399 **   If database corruption is encountered, this module does not report an
10400 **   error. Instead, it attempts to extract as much data as possible and
10401 **   ignores the corruption.
10402 **
10403 ** SQLITE_DBPTR:
10404 **   The sqlite_dbptr table has the following schema:
10405 **
10406 **     CREATE TABLE sqlite_dbptr(
10407 **       pgno INTEGER,
10408 **       child INTEGER,
10409 **       schema TEXT HIDDEN
10410 **     );
10411 **
10412 **   It contains one entry for each b-tree pointer between a parent and
10413 **   child page in the database.
10414 */
10415 #if !defined(SQLITEINT_H) 
10416 /* #include "sqlite3ext.h" */
10417
10418 /* typedef unsigned char u8; */
10419
10420 #endif
10421 SQLITE_EXTENSION_INIT1
10422 #include <string.h>
10423 #include <assert.h>
10424
10425 #define DBDATA_PADDING_BYTES 100 
10426
10427 typedef struct DbdataTable DbdataTable;
10428 typedef struct DbdataCursor DbdataCursor;
10429
10430 /* Cursor object */
10431 struct DbdataCursor {
10432   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
10433   sqlite3_stmt *pStmt;            /* For fetching database pages */
10434
10435   int iPgno;                      /* Current page number */
10436   u8 *aPage;                      /* Buffer containing page */
10437   int nPage;                      /* Size of aPage[] in bytes */
10438   int nCell;                      /* Number of cells on aPage[] */
10439   int iCell;                      /* Current cell number */
10440   int bOnePage;                   /* True to stop after one page */
10441   int szDb;
10442   sqlite3_int64 iRowid;
10443
10444   /* Only for the sqlite_dbdata table */
10445   u8 *pRec;                       /* Buffer containing current record */
10446   int nRec;                       /* Size of pRec[] in bytes */
10447   int nHdr;                       /* Size of header in bytes */
10448   int iField;                     /* Current field number */
10449   u8 *pHdrPtr;
10450   u8 *pPtr;
10451   
10452   sqlite3_int64 iIntkey;          /* Integer key value */
10453 };
10454
10455 /* Table object */
10456 struct DbdataTable {
10457   sqlite3_vtab base;              /* Base class.  Must be first */
10458   sqlite3 *db;                    /* The database connection */
10459   sqlite3_stmt *pStmt;            /* For fetching database pages */
10460   int bPtr;                       /* True for sqlite3_dbptr table */
10461 };
10462
10463 /* Column and schema definitions for sqlite_dbdata */
10464 #define DBDATA_COLUMN_PGNO        0
10465 #define DBDATA_COLUMN_CELL        1
10466 #define DBDATA_COLUMN_FIELD       2
10467 #define DBDATA_COLUMN_VALUE       3
10468 #define DBDATA_COLUMN_SCHEMA      4
10469 #define DBDATA_SCHEMA             \
10470       "CREATE TABLE x("           \
10471       "  pgno INTEGER,"           \
10472       "  cell INTEGER,"           \
10473       "  field INTEGER,"          \
10474       "  value ANY,"              \
10475       "  schema TEXT HIDDEN"      \
10476       ")"
10477
10478 /* Column and schema definitions for sqlite_dbptr */
10479 #define DBPTR_COLUMN_PGNO         0
10480 #define DBPTR_COLUMN_CHILD        1
10481 #define DBPTR_COLUMN_SCHEMA       2
10482 #define DBPTR_SCHEMA              \
10483       "CREATE TABLE x("           \
10484       "  pgno INTEGER,"           \
10485       "  child INTEGER,"          \
10486       "  schema TEXT HIDDEN"      \
10487       ")"
10488
10489 /*
10490 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual 
10491 ** table.
10492 */
10493 static int dbdataConnect(
10494   sqlite3 *db,
10495   void *pAux,
10496   int argc, const char *const*argv,
10497   sqlite3_vtab **ppVtab,
10498   char **pzErr
10499 ){
10500   DbdataTable *pTab = 0;
10501   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
10502
10503   if( rc==SQLITE_OK ){
10504     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
10505     if( pTab==0 ){
10506       rc = SQLITE_NOMEM;
10507     }else{
10508       memset(pTab, 0, sizeof(DbdataTable));
10509       pTab->db = db;
10510       pTab->bPtr = (pAux!=0);
10511     }
10512   }
10513
10514   *ppVtab = (sqlite3_vtab*)pTab;
10515   return rc;
10516 }
10517
10518 /*
10519 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
10520 */
10521 static int dbdataDisconnect(sqlite3_vtab *pVtab){
10522   DbdataTable *pTab = (DbdataTable*)pVtab;
10523   if( pTab ){
10524     sqlite3_finalize(pTab->pStmt);
10525     sqlite3_free(pVtab);
10526   }
10527   return SQLITE_OK;
10528 }
10529
10530 /*
10531 ** This function interprets two types of constraints:
10532 **
10533 **       schema=?
10534 **       pgno=?
10535 **
10536 ** If neither are present, idxNum is set to 0. If schema=? is present,
10537 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
10538 ** in idxNum is set.
10539 **
10540 ** If both parameters are present, schema is in position 0 and pgno in
10541 ** position 1.
10542 */
10543 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
10544   DbdataTable *pTab = (DbdataTable*)tab;
10545   int i;
10546   int iSchema = -1;
10547   int iPgno = -1;
10548   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
10549
10550   for(i=0; i<pIdx->nConstraint; i++){
10551     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
10552     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10553       if( p->iColumn==colSchema ){
10554         if( p->usable==0 ) return SQLITE_CONSTRAINT;
10555         iSchema = i;
10556       }
10557       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
10558         iPgno = i;
10559       }
10560     }
10561   }
10562
10563   if( iSchema>=0 ){
10564     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
10565     pIdx->aConstraintUsage[iSchema].omit = 1;
10566   }
10567   if( iPgno>=0 ){
10568     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
10569     pIdx->aConstraintUsage[iPgno].omit = 1;
10570     pIdx->estimatedCost = 100;
10571     pIdx->estimatedRows =  50;
10572
10573     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
10574       int iCol = pIdx->aOrderBy[0].iColumn;
10575       if( pIdx->nOrderBy==1 ){
10576         pIdx->orderByConsumed = (iCol==0 || iCol==1);
10577       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
10578         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
10579       }
10580     }
10581
10582   }else{
10583     pIdx->estimatedCost = 100000000;
10584     pIdx->estimatedRows = 1000000000;
10585   }
10586   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
10587   return SQLITE_OK;
10588 }
10589
10590 /*
10591 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
10592 */
10593 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
10594   DbdataCursor *pCsr;
10595
10596   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
10597   if( pCsr==0 ){
10598     return SQLITE_NOMEM;
10599   }else{
10600     memset(pCsr, 0, sizeof(DbdataCursor));
10601     pCsr->base.pVtab = pVTab;
10602   }
10603
10604   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
10605   return SQLITE_OK;
10606 }
10607
10608 /*
10609 ** Restore a cursor object to the state it was in when first allocated 
10610 ** by dbdataOpen().
10611 */
10612 static void dbdataResetCursor(DbdataCursor *pCsr){
10613   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
10614   if( pTab->pStmt==0 ){
10615     pTab->pStmt = pCsr->pStmt;
10616   }else{
10617     sqlite3_finalize(pCsr->pStmt);
10618   }
10619   pCsr->pStmt = 0;
10620   pCsr->iPgno = 1;
10621   pCsr->iCell = 0;
10622   pCsr->iField = 0;
10623   pCsr->bOnePage = 0;
10624   sqlite3_free(pCsr->aPage);
10625   sqlite3_free(pCsr->pRec);
10626   pCsr->pRec = 0;
10627   pCsr->aPage = 0;
10628 }
10629
10630 /*
10631 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
10632 */
10633 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
10634   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10635   dbdataResetCursor(pCsr);
10636   sqlite3_free(pCsr);
10637   return SQLITE_OK;
10638 }
10639
10640 /* 
10641 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers. 
10642 */
10643 static unsigned int get_uint16(unsigned char *a){
10644   return (a[0]<<8)|a[1];
10645 }
10646 static unsigned int get_uint32(unsigned char *a){
10647   return ((unsigned int)a[0]<<24)
10648        | ((unsigned int)a[1]<<16)
10649        | ((unsigned int)a[2]<<8)
10650        | ((unsigned int)a[3]);
10651 }
10652
10653 /*
10654 ** Load page pgno from the database via the sqlite_dbpage virtual table.
10655 ** If successful, set (*ppPage) to point to a buffer containing the page
10656 ** data, (*pnPage) to the size of that buffer in bytes and return
10657 ** SQLITE_OK. In this case it is the responsibility of the caller to
10658 ** eventually free the buffer using sqlite3_free().
10659 **
10660 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
10661 ** return an SQLite error code.
10662 */
10663 static int dbdataLoadPage(
10664   DbdataCursor *pCsr,             /* Cursor object */
10665   unsigned int pgno,              /* Page number of page to load */
10666   u8 **ppPage,                    /* OUT: pointer to page buffer */
10667   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
10668 ){
10669   int rc2;
10670   int rc = SQLITE_OK;
10671   sqlite3_stmt *pStmt = pCsr->pStmt;
10672
10673   *ppPage = 0;
10674   *pnPage = 0;
10675   sqlite3_bind_int64(pStmt, 2, pgno);
10676   if( SQLITE_ROW==sqlite3_step(pStmt) ){
10677     int nCopy = sqlite3_column_bytes(pStmt, 0);
10678     if( nCopy>0 ){
10679       u8 *pPage;
10680       pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
10681       if( pPage==0 ){
10682         rc = SQLITE_NOMEM;
10683       }else{
10684         const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
10685         memcpy(pPage, pCopy, nCopy);
10686         memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
10687       }
10688       *ppPage = pPage;
10689       *pnPage = nCopy;
10690     }
10691   }
10692   rc2 = sqlite3_reset(pStmt);
10693   if( rc==SQLITE_OK ) rc = rc2;
10694
10695   return rc;
10696 }
10697
10698 /*
10699 ** Read a varint.  Put the value in *pVal and return the number of bytes.
10700 */
10701 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
10702   sqlite3_int64 v = 0;
10703   int i;
10704   for(i=0; i<8; i++){
10705     v = (v<<7) + (z[i]&0x7f);
10706     if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
10707   }
10708   v = (v<<8) + (z[i]&0xff);
10709   *pVal = v;
10710   return 9;
10711 }
10712
10713 /*
10714 ** Return the number of bytes of space used by an SQLite value of type
10715 ** eType.
10716 */
10717 static int dbdataValueBytes(int eType){
10718   switch( eType ){
10719     case 0: case 8: case 9:
10720     case 10: case 11:
10721       return 0;
10722     case 1:
10723       return 1;
10724     case 2:
10725       return 2;
10726     case 3:
10727       return 3;
10728     case 4:
10729       return 4;
10730     case 5:
10731       return 6;
10732     case 6:
10733     case 7:
10734       return 8;
10735     default:
10736       if( eType>0 ){
10737         return ((eType-12) / 2);
10738       }
10739       return 0;
10740   }
10741 }
10742
10743 /*
10744 ** Load a value of type eType from buffer pData and use it to set the
10745 ** result of context object pCtx.
10746 */
10747 static void dbdataValue(
10748   sqlite3_context *pCtx, 
10749   int eType, 
10750   u8 *pData,
10751   int nData
10752 ){
10753   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
10754     switch( eType ){
10755       case 0: 
10756       case 10: 
10757       case 11: 
10758         sqlite3_result_null(pCtx);
10759         break;
10760       
10761       case 8: 
10762         sqlite3_result_int(pCtx, 0);
10763         break;
10764       case 9:
10765         sqlite3_result_int(pCtx, 1);
10766         break;
10767   
10768       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
10769         sqlite3_uint64 v = (signed char)pData[0];
10770         pData++;
10771         switch( eType ){
10772           case 7:
10773           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
10774           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
10775           case 4:  v = (v<<8) + pData[0];  pData++;
10776           case 3:  v = (v<<8) + pData[0];  pData++;
10777           case 2:  v = (v<<8) + pData[0];  pData++;
10778         }
10779   
10780         if( eType==7 ){
10781           double r;
10782           memcpy(&r, &v, sizeof(r));
10783           sqlite3_result_double(pCtx, r);
10784         }else{
10785           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
10786         }
10787         break;
10788       }
10789   
10790       default: {
10791         int n = ((eType-12) / 2);
10792         if( eType % 2 ){
10793           sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
10794         }else{
10795           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
10796         }
10797       }
10798     }
10799   }
10800 }
10801
10802 /*
10803 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
10804 */
10805 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
10806   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10807   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
10808
10809   pCsr->iRowid++;
10810   while( 1 ){
10811     int rc;
10812     int iOff = (pCsr->iPgno==1 ? 100 : 0);
10813     int bNextPage = 0;
10814
10815     if( pCsr->aPage==0 ){
10816       while( 1 ){
10817         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
10818         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
10819         if( rc!=SQLITE_OK ) return rc;
10820         if( pCsr->aPage ) break;
10821         pCsr->iPgno++;
10822       }
10823       pCsr->iCell = pTab->bPtr ? -2 : 0;
10824       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
10825     }
10826
10827     if( pTab->bPtr ){
10828       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
10829         pCsr->iCell = pCsr->nCell;
10830       }
10831       pCsr->iCell++;
10832       if( pCsr->iCell>=pCsr->nCell ){
10833         sqlite3_free(pCsr->aPage);
10834         pCsr->aPage = 0;
10835         if( pCsr->bOnePage ) return SQLITE_OK;
10836         pCsr->iPgno++;
10837       }else{
10838         return SQLITE_OK;
10839       }
10840     }else{
10841       /* If there is no record loaded, load it now. */
10842       if( pCsr->pRec==0 ){
10843         int bHasRowid = 0;
10844         int nPointer = 0;
10845         sqlite3_int64 nPayload = 0;
10846         sqlite3_int64 nHdr = 0;
10847         int iHdr;
10848         int U, X;
10849         int nLocal;
10850   
10851         switch( pCsr->aPage[iOff] ){
10852           case 0x02:
10853             nPointer = 4;
10854             break;
10855           case 0x0a:
10856             break;
10857           case 0x0d:
10858             bHasRowid = 1;
10859             break;
10860           default:
10861             /* This is not a b-tree page with records on it. Continue. */
10862             pCsr->iCell = pCsr->nCell;
10863             break;
10864         }
10865
10866         if( pCsr->iCell>=pCsr->nCell ){
10867           bNextPage = 1;
10868         }else{
10869   
10870           iOff += 8 + nPointer + pCsr->iCell*2;
10871           if( iOff>pCsr->nPage ){
10872             bNextPage = 1;
10873           }else{
10874             iOff = get_uint16(&pCsr->aPage[iOff]);
10875           }
10876     
10877           /* For an interior node cell, skip past the child-page number */
10878           iOff += nPointer;
10879     
10880           /* Load the "byte of payload including overflow" field */
10881           if( bNextPage || iOff>pCsr->nPage ){
10882             bNextPage = 1;
10883           }else{
10884             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
10885           }
10886     
10887           /* If this is a leaf intkey cell, load the rowid */
10888           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
10889             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
10890           }
10891     
10892           /* Figure out how much data to read from the local page */
10893           U = pCsr->nPage;
10894           if( bHasRowid ){
10895             X = U-35;
10896           }else{
10897             X = ((U-12)*64/255)-23;
10898           }
10899           if( nPayload<=X ){
10900             nLocal = nPayload;
10901           }else{
10902             int M, K;
10903             M = ((U-12)*32/255)-23;
10904             K = M+((nPayload-M)%(U-4));
10905             if( K<=X ){
10906               nLocal = K;
10907             }else{
10908               nLocal = M;
10909             }
10910           }
10911
10912           if( bNextPage || nLocal+iOff>pCsr->nPage ){
10913             bNextPage = 1;
10914           }else{
10915
10916             /* Allocate space for payload. And a bit more to catch small buffer
10917             ** overruns caused by attempting to read a varint or similar from 
10918             ** near the end of a corrupt record.  */
10919             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
10920             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
10921             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
10922             pCsr->nRec = nPayload;
10923
10924             /* Load the nLocal bytes of payload */
10925             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
10926             iOff += nLocal;
10927
10928             /* Load content from overflow pages */
10929             if( nPayload>nLocal ){
10930               sqlite3_int64 nRem = nPayload - nLocal;
10931               unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
10932               while( nRem>0 ){
10933                 u8 *aOvfl = 0;
10934                 int nOvfl = 0;
10935                 int nCopy;
10936                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
10937                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
10938                 if( rc!=SQLITE_OK ) return rc;
10939                 if( aOvfl==0 ) break;
10940
10941                 nCopy = U-4;
10942                 if( nCopy>nRem ) nCopy = nRem;
10943                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
10944                 nRem -= nCopy;
10945
10946                 pgnoOvfl = get_uint32(aOvfl);
10947                 sqlite3_free(aOvfl);
10948               }
10949             }
10950     
10951             iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
10952             pCsr->nHdr = nHdr;
10953             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
10954             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
10955             pCsr->iField = (bHasRowid ? -1 : 0);
10956           }
10957         }
10958       }else{
10959         pCsr->iField++;
10960         if( pCsr->iField>0 ){
10961           sqlite3_int64 iType;
10962           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
10963             bNextPage = 1;
10964           }else{
10965             pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
10966             pCsr->pPtr += dbdataValueBytes(iType);
10967           }
10968         }
10969       }
10970
10971       if( bNextPage ){
10972         sqlite3_free(pCsr->aPage);
10973         sqlite3_free(pCsr->pRec);
10974         pCsr->aPage = 0;
10975         pCsr->pRec = 0;
10976         if( pCsr->bOnePage ) return SQLITE_OK;
10977         pCsr->iPgno++;
10978       }else{
10979         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
10980           return SQLITE_OK;
10981         }
10982
10983         /* Advance to the next cell. The next iteration of the loop will load
10984         ** the record and so on. */
10985         sqlite3_free(pCsr->pRec);
10986         pCsr->pRec = 0;
10987         pCsr->iCell++;
10988       }
10989     }
10990   }
10991
10992   assert( !"can't get here" );
10993   return SQLITE_OK;
10994 }
10995
10996 /* 
10997 ** Return true if the cursor is at EOF.
10998 */
10999 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
11000   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11001   return pCsr->aPage==0;
11002 }
11003
11004 /* 
11005 ** Determine the size in pages of database zSchema (where zSchema is
11006 ** "main", "temp" or the name of an attached database) and set 
11007 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
11008 ** an SQLite error code.
11009 */
11010 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
11011   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
11012   char *zSql = 0;
11013   int rc, rc2;
11014   sqlite3_stmt *pStmt = 0;
11015
11016   zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
11017   if( zSql==0 ) return SQLITE_NOMEM;
11018   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
11019   sqlite3_free(zSql);
11020   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
11021     pCsr->szDb = sqlite3_column_int(pStmt, 0);
11022   }
11023   rc2 = sqlite3_finalize(pStmt);
11024   if( rc==SQLITE_OK ) rc = rc2;
11025   return rc;
11026 }
11027
11028 /* 
11029 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
11030 */
11031 static int dbdataFilter(
11032   sqlite3_vtab_cursor *pCursor, 
11033   int idxNum, const char *idxStr,
11034   int argc, sqlite3_value **argv
11035 ){
11036   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11037   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11038   int rc = SQLITE_OK;
11039   const char *zSchema = "main";
11040
11041   dbdataResetCursor(pCsr);
11042   assert( pCsr->iPgno==1 );
11043   if( idxNum & 0x01 ){
11044     zSchema = (const char*)sqlite3_value_text(argv[0]);
11045   }
11046   if( idxNum & 0x02 ){
11047     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
11048     pCsr->bOnePage = 1;
11049   }else{
11050     pCsr->nPage = dbdataDbsize(pCsr, zSchema);
11051     rc = dbdataDbsize(pCsr, zSchema);
11052   }
11053
11054   if( rc==SQLITE_OK ){
11055     if( pTab->pStmt ){
11056       pCsr->pStmt = pTab->pStmt;
11057       pTab->pStmt = 0;
11058     }else{
11059       rc = sqlite3_prepare_v2(pTab->db, 
11060           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
11061           &pCsr->pStmt, 0
11062       );
11063     }
11064   }
11065   if( rc==SQLITE_OK ){
11066     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
11067   }else{
11068     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
11069   }
11070   if( rc==SQLITE_OK ){
11071     rc = dbdataNext(pCursor);
11072   }
11073   return rc;
11074 }
11075
11076 /* 
11077 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
11078 */
11079 static int dbdataColumn(
11080   sqlite3_vtab_cursor *pCursor, 
11081   sqlite3_context *ctx, 
11082   int i
11083 ){
11084   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11085   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11086   if( pTab->bPtr ){
11087     switch( i ){
11088       case DBPTR_COLUMN_PGNO:
11089         sqlite3_result_int64(ctx, pCsr->iPgno);
11090         break;
11091       case DBPTR_COLUMN_CHILD: {
11092         int iOff = pCsr->iPgno==1 ? 100 : 0;
11093         if( pCsr->iCell<0 ){
11094           iOff += 8;
11095         }else{
11096           iOff += 12 + pCsr->iCell*2;
11097           if( iOff>pCsr->nPage ) return SQLITE_OK;
11098           iOff = get_uint16(&pCsr->aPage[iOff]);
11099         }
11100         if( iOff<=pCsr->nPage ){
11101           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
11102         }
11103         break;
11104       }
11105     }
11106   }else{
11107     switch( i ){
11108       case DBDATA_COLUMN_PGNO:
11109         sqlite3_result_int64(ctx, pCsr->iPgno);
11110         break;
11111       case DBDATA_COLUMN_CELL:
11112         sqlite3_result_int(ctx, pCsr->iCell);
11113         break;
11114       case DBDATA_COLUMN_FIELD:
11115         sqlite3_result_int(ctx, pCsr->iField);
11116         break;
11117       case DBDATA_COLUMN_VALUE: {
11118         if( pCsr->iField<0 ){
11119           sqlite3_result_int64(ctx, pCsr->iIntkey);
11120         }else{
11121           sqlite3_int64 iType;
11122           dbdataGetVarint(pCsr->pHdrPtr, &iType);
11123           dbdataValue(
11124               ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
11125           );
11126         }
11127         break;
11128       }
11129     }
11130   }
11131   return SQLITE_OK;
11132 }
11133
11134 /* 
11135 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
11136 */
11137 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
11138   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11139   *pRowid = pCsr->iRowid;
11140   return SQLITE_OK;
11141 }
11142
11143
11144 /*
11145 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
11146 */
11147 static int sqlite3DbdataRegister(sqlite3 *db){
11148   static sqlite3_module dbdata_module = {
11149     0,                            /* iVersion */
11150     0,                            /* xCreate */
11151     dbdataConnect,                /* xConnect */
11152     dbdataBestIndex,              /* xBestIndex */
11153     dbdataDisconnect,             /* xDisconnect */
11154     0,                            /* xDestroy */
11155     dbdataOpen,                   /* xOpen - open a cursor */
11156     dbdataClose,                  /* xClose - close a cursor */
11157     dbdataFilter,                 /* xFilter - configure scan constraints */
11158     dbdataNext,                   /* xNext - advance a cursor */
11159     dbdataEof,                    /* xEof - check for end of scan */
11160     dbdataColumn,                 /* xColumn - read data */
11161     dbdataRowid,                  /* xRowid - read data */
11162     0,                            /* xUpdate */
11163     0,                            /* xBegin */
11164     0,                            /* xSync */
11165     0,                            /* xCommit */
11166     0,                            /* xRollback */
11167     0,                            /* xFindMethod */
11168     0,                            /* xRename */
11169     0,                            /* xSavepoint */
11170     0,                            /* xRelease */
11171     0,                            /* xRollbackTo */
11172     0                             /* xShadowName */
11173   };
11174
11175   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
11176   if( rc==SQLITE_OK ){
11177     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
11178   }
11179   return rc;
11180 }
11181
11182 #ifdef _WIN32
11183
11184 #endif
11185 int sqlite3_dbdata_init(
11186   sqlite3 *db, 
11187   char **pzErrMsg, 
11188   const sqlite3_api_routines *pApi
11189 ){
11190   SQLITE_EXTENSION_INIT2(pApi);
11191   return sqlite3DbdataRegister(db);
11192 }
11193
11194 /************************* End ../ext/misc/dbdata.c ********************/
11195 #endif
11196
11197 #if defined(SQLITE_ENABLE_SESSION)
11198 /*
11199 ** State information for a single open session
11200 */
11201 typedef struct OpenSession OpenSession;
11202 struct OpenSession {
11203   char *zName;             /* Symbolic name for this session */
11204   int nFilter;             /* Number of xFilter rejection GLOB patterns */
11205   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
11206   sqlite3_session *p;      /* The open session */
11207 };
11208 #endif
11209
11210 typedef struct ExpertInfo ExpertInfo;
11211 struct ExpertInfo {
11212   sqlite3expert *pExpert;
11213   int bVerbose;
11214 };
11215
11216 /* A single line in the EQP output */
11217 typedef struct EQPGraphRow EQPGraphRow;
11218 struct EQPGraphRow {
11219   int iEqpId;           /* ID for this row */
11220   int iParentId;        /* ID of the parent row */
11221   EQPGraphRow *pNext;   /* Next row in sequence */
11222   char zText[1];        /* Text to display for this row */
11223 };
11224
11225 /* All EQP output is collected into an instance of the following */
11226 typedef struct EQPGraph EQPGraph;
11227 struct EQPGraph {
11228   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
11229   EQPGraphRow *pLast;   /* Last element of the pRow list */
11230   char zPrefix[100];    /* Graph prefix */
11231 };
11232
11233 /*
11234 ** State information about the database connection is contained in an
11235 ** instance of the following structure.
11236 */
11237 typedef struct ShellState ShellState;
11238 struct ShellState {
11239   sqlite3 *db;           /* The database */
11240   u8 autoExplain;        /* Automatically turn on .explain mode */
11241   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
11242   u8 autoEQPtest;        /* autoEQP is in test mode */
11243   u8 autoEQPtrace;       /* autoEQP is in trace mode */
11244   u8 scanstatsOn;        /* True to display scan stats before each finalize */
11245   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
11246   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
11247   u8 nEqpLevel;          /* Depth of the EQP output graph */
11248   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
11249   unsigned statsOn;      /* True to display memory stats before each finalize */
11250   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
11251   int outCount;          /* Revert to stdout when reaching zero */
11252   int cnt;               /* Number of records displayed so far */
11253   int lineno;            /* Line number of last line read from in */
11254   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
11255   FILE *in;              /* Read commands from this stream */
11256   FILE *out;             /* Write results here */
11257   FILE *traceOut;        /* Output for sqlite3_trace() */
11258   int nErr;              /* Number of errors seen */
11259   int mode;              /* An output mode setting */
11260   int modePrior;         /* Saved mode */
11261   int cMode;             /* temporary output mode for the current query */
11262   int normalMode;        /* Output mode before ".explain on" */
11263   int writableSchema;    /* True if PRAGMA writable_schema=ON */
11264   int showHeader;        /* True to show column names in List or Column mode */
11265   int nCheck;            /* Number of ".check" commands run */
11266   unsigned nProgress;    /* Number of progress callbacks encountered */
11267   unsigned mxProgress;   /* Maximum progress callbacks before failing */
11268   unsigned flgProgress;  /* Flags for the progress callback */
11269   unsigned shellFlgs;    /* Various flags */
11270   unsigned priorShFlgs;  /* Saved copy of flags */
11271   sqlite3_int64 szMax;   /* --maxsize argument to .open */
11272   char *zDestTable;      /* Name of destination table when MODE_Insert */
11273   char *zTempFile;       /* Temporary file that might need deleting */
11274   char zTestcase[30];    /* Name of current test case */
11275   char colSeparator[20]; /* Column separator character for several modes */
11276   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
11277   char colSepPrior[20];  /* Saved column separator */
11278   char rowSepPrior[20];  /* Saved row separator */
11279   int *colWidth;         /* Requested width of each column in columnar modes */
11280   int *actualWidth;      /* Actual width of each column */
11281   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
11282   char nullValue[20];    /* The text to print when a NULL comes back from
11283                          ** the database */
11284   char outfile[FILENAME_MAX]; /* Filename for *out */
11285   const char *zDbFilename;    /* name of the database file */
11286   char *zFreeOnClose;         /* Filename to free when closing */
11287   const char *zVfs;           /* Name of VFS to use */
11288   sqlite3_stmt *pStmt;   /* Current statement if any. */
11289   FILE *pLog;            /* Write log output here */
11290   int *aiIndent;         /* Array of indents used in MODE_Explain */
11291   int nIndent;           /* Size of array aiIndent[] */
11292   int iIndent;           /* Index of current op in aiIndent[] */
11293   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
11294 #if defined(SQLITE_ENABLE_SESSION)
11295   int nSession;             /* Number of active sessions */
11296   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
11297 #endif
11298   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
11299 };
11300
11301
11302 /* Allowed values for ShellState.autoEQP
11303 */
11304 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
11305 #define AUTOEQP_on       1           /* Automatic EQP is on */
11306 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
11307 #define AUTOEQP_full     3           /* Show full EXPLAIN */
11308
11309 /* Allowed values for ShellState.openMode
11310 */
11311 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
11312 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
11313 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
11314 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
11315 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
11316 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
11317 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
11318
11319 /* Allowed values for ShellState.eTraceType
11320 */
11321 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
11322 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
11323 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
11324
11325 /* Bits in the ShellState.flgProgress variable */
11326 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
11327 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
11328                                    ** callback limit is reached, and for each
11329                                    ** top-level SQL statement */
11330 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
11331
11332 /*
11333 ** These are the allowed shellFlgs values
11334 */
11335 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
11336 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
11337 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
11338 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
11339 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
11340 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
11341 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
11342 #define SHFLG_HeaderSet      0x00000080 /* .header has been used */
11343 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
11344 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
11345
11346 /*
11347 ** Macros for testing and setting shellFlgs
11348 */
11349 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
11350 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
11351 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
11352
11353 /*
11354 ** These are the allowed modes.
11355 */
11356 #define MODE_Line     0  /* One column per line.  Blank line between records */
11357 #define MODE_Column   1  /* One record per line in neat columns */
11358 #define MODE_List     2  /* One record per line with a separator */
11359 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
11360 #define MODE_Html     4  /* Generate an XHTML table */
11361 #define MODE_Insert   5  /* Generate SQL "insert" statements */
11362 #define MODE_Quote    6  /* Quote values as for SQL */
11363 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
11364 #define MODE_Csv      8  /* Quote strings, numbers are plain */
11365 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
11366 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
11367 #define MODE_Pretty  11  /* Pretty-print schemas */
11368 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
11369 #define MODE_Json    13  /* Output JSON */
11370 #define MODE_Markdown 14 /* Markdown formatting */
11371 #define MODE_Table   15  /* MySQL-style table formatting */
11372 #define MODE_Box     16  /* Unicode box-drawing characters */
11373
11374 static const char *modeDescr[] = {
11375   "line",
11376   "column",
11377   "list",
11378   "semi",
11379   "html",
11380   "insert",
11381   "quote",
11382   "tcl",
11383   "csv",
11384   "explain",
11385   "ascii",
11386   "prettyprint",
11387   "eqp",
11388   "json",
11389   "markdown",
11390   "table",
11391   "box"
11392 };
11393
11394 /*
11395 ** These are the column/row/line separators used by the various
11396 ** import/export modes.
11397 */
11398 #define SEP_Column    "|"
11399 #define SEP_Row       "\n"
11400 #define SEP_Tab       "\t"
11401 #define SEP_Space     " "
11402 #define SEP_Comma     ","
11403 #define SEP_CrLf      "\r\n"
11404 #define SEP_Unit      "\x1F"
11405 #define SEP_Record    "\x1E"
11406
11407 /*
11408 ** A callback for the sqlite3_log() interface.
11409 */
11410 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
11411   ShellState *p = (ShellState*)pArg;
11412   if( p->pLog==0 ) return;
11413   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
11414   fflush(p->pLog);
11415 }
11416
11417 /*
11418 ** SQL function:  shell_putsnl(X)
11419 **
11420 ** Write the text X to the screen (or whatever output is being directed)
11421 ** adding a newline at the end, and then return X.
11422 */
11423 static void shellPutsFunc(
11424   sqlite3_context *pCtx,
11425   int nVal,
11426   sqlite3_value **apVal
11427 ){
11428   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
11429   (void)nVal;
11430   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
11431   sqlite3_result_value(pCtx, apVal[0]);
11432 }
11433
11434 /*
11435 ** SQL function:   edit(VALUE)
11436 **                 edit(VALUE,EDITOR)
11437 **
11438 ** These steps:
11439 **
11440 **     (1) Write VALUE into a temporary file.
11441 **     (2) Run program EDITOR on that temporary file.
11442 **     (3) Read the temporary file back and return its content as the result.
11443 **     (4) Delete the temporary file
11444 **
11445 ** If the EDITOR argument is omitted, use the value in the VISUAL
11446 ** environment variable.  If still there is no EDITOR, through an error.
11447 **
11448 ** Also throw an error if the EDITOR program returns a non-zero exit code.
11449 */
11450 #ifndef SQLITE_NOHAVE_SYSTEM
11451 static void editFunc(
11452   sqlite3_context *context,
11453   int argc,
11454   sqlite3_value **argv
11455 ){
11456   const char *zEditor;
11457   char *zTempFile = 0;
11458   sqlite3 *db;
11459   char *zCmd = 0;
11460   int bBin;
11461   int rc;
11462   int hasCRNL = 0;
11463   FILE *f = 0;
11464   sqlite3_int64 sz;
11465   sqlite3_int64 x;
11466   unsigned char *p = 0;
11467
11468   if( argc==2 ){
11469     zEditor = (const char*)sqlite3_value_text(argv[1]);
11470   }else{
11471     zEditor = getenv("VISUAL");
11472   }
11473   if( zEditor==0 ){
11474     sqlite3_result_error(context, "no editor for edit()", -1);
11475     return;
11476   }
11477   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
11478     sqlite3_result_error(context, "NULL input to edit()", -1);
11479     return;
11480   }
11481   db = sqlite3_context_db_handle(context);
11482   zTempFile = 0;
11483   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
11484   if( zTempFile==0 ){
11485     sqlite3_uint64 r = 0;
11486     sqlite3_randomness(sizeof(r), &r);
11487     zTempFile = sqlite3_mprintf("temp%llx", r);
11488     if( zTempFile==0 ){
11489       sqlite3_result_error_nomem(context);
11490       return;
11491     }
11492   }
11493   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
11494   /* When writing the file to be edited, do \n to \r\n conversions on systems
11495   ** that want \r\n line endings */
11496   f = fopen(zTempFile, bBin ? "wb" : "w");
11497   if( f==0 ){
11498     sqlite3_result_error(context, "edit() cannot open temp file", -1);
11499     goto edit_func_end;
11500   }
11501   sz = sqlite3_value_bytes(argv[0]);
11502   if( bBin ){
11503     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
11504   }else{
11505     const char *z = (const char*)sqlite3_value_text(argv[0]);
11506     /* Remember whether or not the value originally contained \r\n */
11507     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
11508     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
11509   }
11510   fclose(f);
11511   f = 0;
11512   if( x!=sz ){
11513     sqlite3_result_error(context, "edit() could not write the whole file", -1);
11514     goto edit_func_end;
11515   }
11516   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
11517   if( zCmd==0 ){
11518     sqlite3_result_error_nomem(context);
11519     goto edit_func_end;
11520   }
11521   rc = system(zCmd);
11522   sqlite3_free(zCmd);
11523   if( rc ){
11524     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
11525     goto edit_func_end;
11526   }
11527   f = fopen(zTempFile, "rb");
11528   if( f==0 ){
11529     sqlite3_result_error(context,
11530       "edit() cannot reopen temp file after edit", -1);
11531     goto edit_func_end;
11532   }
11533   fseek(f, 0, SEEK_END);
11534   sz = ftell(f);
11535   rewind(f);
11536   p = sqlite3_malloc64( sz+1 );
11537   if( p==0 ){
11538     sqlite3_result_error_nomem(context);
11539     goto edit_func_end;
11540   }
11541   x = fread(p, 1, (size_t)sz, f);
11542   fclose(f);
11543   f = 0;
11544   if( x!=sz ){
11545     sqlite3_result_error(context, "could not read back the whole file", -1);
11546     goto edit_func_end;
11547   }
11548   if( bBin ){
11549     sqlite3_result_blob64(context, p, sz, sqlite3_free);
11550   }else{
11551     sqlite3_int64 i, j;
11552     if( hasCRNL ){
11553       /* If the original contains \r\n then do no conversions back to \n */
11554       j = sz;
11555     }else{
11556       /* If the file did not originally contain \r\n then convert any new
11557       ** \r\n back into \n */
11558       for(i=j=0; i<sz; i++){
11559         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
11560         p[j++] = p[i];
11561       }
11562       sz = j;
11563       p[sz] = 0;
11564     } 
11565     sqlite3_result_text64(context, (const char*)p, sz,
11566                           sqlite3_free, SQLITE_UTF8);
11567   }
11568   p = 0;
11569
11570 edit_func_end:
11571   if( f ) fclose(f);
11572   unlink(zTempFile);
11573   sqlite3_free(zTempFile);
11574   sqlite3_free(p);
11575 }
11576 #endif /* SQLITE_NOHAVE_SYSTEM */
11577
11578 /*
11579 ** Save or restore the current output mode
11580 */
11581 static void outputModePush(ShellState *p){
11582   p->modePrior = p->mode;
11583   p->priorShFlgs = p->shellFlgs;
11584   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
11585   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
11586 }
11587 static void outputModePop(ShellState *p){
11588   p->mode = p->modePrior;
11589   p->shellFlgs = p->priorShFlgs;
11590   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
11591   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
11592 }
11593
11594 /*
11595 ** Output the given string as a hex-encoded blob (eg. X'1234' )
11596 */
11597 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
11598   int i;
11599   char *zBlob = (char *)pBlob;
11600   raw_printf(out,"X'");
11601   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
11602   raw_printf(out,"'");
11603 }
11604
11605 /*
11606 ** Find a string that is not found anywhere in z[].  Return a pointer
11607 ** to that string.
11608 **
11609 ** Try to use zA and zB first.  If both of those are already found in z[]
11610 ** then make up some string and store it in the buffer zBuf.
11611 */
11612 static const char *unused_string(
11613   const char *z,                    /* Result must not appear anywhere in z */
11614   const char *zA, const char *zB,   /* Try these first */
11615   char *zBuf                        /* Space to store a generated string */
11616 ){
11617   unsigned i = 0;
11618   if( strstr(z, zA)==0 ) return zA;
11619   if( strstr(z, zB)==0 ) return zB;
11620   do{
11621     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
11622   }while( strstr(z,zBuf)!=0 );
11623   return zBuf;
11624 }
11625
11626 /*
11627 ** Output the given string as a quoted string using SQL quoting conventions.
11628 **
11629 ** See also: output_quoted_escaped_string()
11630 */
11631 static void output_quoted_string(FILE *out, const char *z){
11632   int i;
11633   char c;
11634   setBinaryMode(out, 1);
11635   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
11636   if( c==0 ){
11637     utf8_printf(out,"'%s'",z);
11638   }else{
11639     raw_printf(out, "'");
11640     while( *z ){
11641       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
11642       if( c=='\'' ) i++;
11643       if( i ){
11644         utf8_printf(out, "%.*s", i, z);
11645         z += i;
11646       }
11647       if( c=='\'' ){
11648         raw_printf(out, "'");
11649         continue;
11650       }
11651       if( c==0 ){
11652         break;
11653       }
11654       z++;
11655     }
11656     raw_printf(out, "'");
11657   }
11658   setTextMode(out, 1);
11659 }
11660
11661 /*
11662 ** Output the given string as a quoted string using SQL quoting conventions.
11663 ** Additionallly , escape the "\n" and "\r" characters so that they do not
11664 ** get corrupted by end-of-line translation facilities in some operating
11665 ** systems.
11666 **
11667 ** This is like output_quoted_string() but with the addition of the \r\n
11668 ** escape mechanism.
11669 */
11670 static void output_quoted_escaped_string(FILE *out, const char *z){
11671   int i;
11672   char c;
11673   setBinaryMode(out, 1);
11674   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
11675   if( c==0 ){
11676     utf8_printf(out,"'%s'",z);
11677   }else{
11678     const char *zNL = 0;
11679     const char *zCR = 0;
11680     int nNL = 0;
11681     int nCR = 0;
11682     char zBuf1[20], zBuf2[20];
11683     for(i=0; z[i]; i++){
11684       if( z[i]=='\n' ) nNL++;
11685       if( z[i]=='\r' ) nCR++;
11686     }
11687     if( nNL ){
11688       raw_printf(out, "replace(");
11689       zNL = unused_string(z, "\\n", "\\012", zBuf1);
11690     }
11691     if( nCR ){
11692       raw_printf(out, "replace(");
11693       zCR = unused_string(z, "\\r", "\\015", zBuf2);
11694     }
11695     raw_printf(out, "'");
11696     while( *z ){
11697       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
11698       if( c=='\'' ) i++;
11699       if( i ){
11700         utf8_printf(out, "%.*s", i, z);
11701         z += i;
11702       }
11703       if( c=='\'' ){
11704         raw_printf(out, "'");
11705         continue;
11706       }
11707       if( c==0 ){
11708         break;
11709       }
11710       z++;
11711       if( c=='\n' ){
11712         raw_printf(out, "%s", zNL);
11713         continue;
11714       }
11715       raw_printf(out, "%s", zCR);
11716     }
11717     raw_printf(out, "'");
11718     if( nCR ){
11719       raw_printf(out, ",'%s',char(13))", zCR);
11720     }
11721     if( nNL ){
11722       raw_printf(out, ",'%s',char(10))", zNL);
11723     }
11724   }
11725   setTextMode(out, 1);
11726 }
11727
11728 /*
11729 ** Output the given string as a quoted according to C or TCL quoting rules.
11730 */
11731 static void output_c_string(FILE *out, const char *z){
11732   unsigned int c;
11733   fputc('"', out);
11734   while( (c = *(z++))!=0 ){
11735     if( c=='\\' ){
11736       fputc(c, out);
11737       fputc(c, out);
11738     }else if( c=='"' ){
11739       fputc('\\', out);
11740       fputc('"', out);
11741     }else if( c=='\t' ){
11742       fputc('\\', out);
11743       fputc('t', out);
11744     }else if( c=='\n' ){
11745       fputc('\\', out);
11746       fputc('n', out);
11747     }else if( c=='\r' ){
11748       fputc('\\', out);
11749       fputc('r', out);
11750     }else if( !isprint(c&0xff) ){
11751       raw_printf(out, "\\%03o", c&0xff);
11752     }else{
11753       fputc(c, out);
11754     }
11755   }
11756   fputc('"', out);
11757 }
11758
11759 /*
11760 ** Output the given string as a quoted according to JSON quoting rules.
11761 */
11762 static void output_json_string(FILE *out, const char *z, int n){
11763   unsigned int c;
11764   if( n<0 ) n = (int)strlen(z);
11765   fputc('"', out);
11766   while( n-- ){
11767     c = *(z++);
11768     if( c=='\\' || c=='"' ){
11769       fputc('\\', out);
11770       fputc(c, out);
11771     }else if( c<=0x1f ){
11772       fputc('\\', out);
11773       if( c=='\b' ){
11774         fputc('b', out);
11775       }else if( c=='\f' ){
11776         fputc('f', out);
11777       }else if( c=='\n' ){
11778         fputc('n', out);
11779       }else if( c=='\r' ){
11780         fputc('r', out);
11781       }else if( c=='\t' ){
11782         fputc('t', out);
11783       }else{
11784          raw_printf(out, "u%04x",c);
11785       }
11786     }else{
11787       fputc(c, out);
11788     }
11789   }
11790   fputc('"', out);
11791 }
11792
11793 /*
11794 ** Output the given string with characters that are special to
11795 ** HTML escaped.
11796 */
11797 static void output_html_string(FILE *out, const char *z){
11798   int i;
11799   if( z==0 ) z = "";
11800   while( *z ){
11801     for(i=0;   z[i]
11802             && z[i]!='<'
11803             && z[i]!='&'
11804             && z[i]!='>'
11805             && z[i]!='\"'
11806             && z[i]!='\'';
11807         i++){}
11808     if( i>0 ){
11809       utf8_printf(out,"%.*s",i,z);
11810     }
11811     if( z[i]=='<' ){
11812       raw_printf(out,"&lt;");
11813     }else if( z[i]=='&' ){
11814       raw_printf(out,"&amp;");
11815     }else if( z[i]=='>' ){
11816       raw_printf(out,"&gt;");
11817     }else if( z[i]=='\"' ){
11818       raw_printf(out,"&quot;");
11819     }else if( z[i]=='\'' ){
11820       raw_printf(out,"&#39;");
11821     }else{
11822       break;
11823     }
11824     z += i + 1;
11825   }
11826 }
11827
11828 /*
11829 ** If a field contains any character identified by a 1 in the following
11830 ** array, then the string must be quoted for CSV.
11831 */
11832 static const char needCsvQuote[] = {
11833   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11834   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11835   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
11836   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11837   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11838   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11839   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11840   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
11841   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11842   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11843   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11844   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11845   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11846   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11847   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11848   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11849 };
11850
11851 /*
11852 ** Output a single term of CSV.  Actually, p->colSeparator is used for
11853 ** the separator, which may or may not be a comma.  p->nullValue is
11854 ** the null value.  Strings are quoted if necessary.  The separator
11855 ** is only issued if bSep is true.
11856 */
11857 static void output_csv(ShellState *p, const char *z, int bSep){
11858   FILE *out = p->out;
11859   if( z==0 ){
11860     utf8_printf(out,"%s",p->nullValue);
11861   }else{
11862     int i;
11863     int nSep = strlen30(p->colSeparator);
11864     for(i=0; z[i]; i++){
11865       if( needCsvQuote[((unsigned char*)z)[i]]
11866          || (z[i]==p->colSeparator[0] &&
11867              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
11868         i = 0;
11869         break;
11870       }
11871     }
11872     if( i==0 ){
11873       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
11874       utf8_printf(out, "%s", zQuoted);
11875       sqlite3_free(zQuoted);
11876     }else{
11877       utf8_printf(out, "%s", z);
11878     }
11879   }
11880   if( bSep ){
11881     utf8_printf(p->out, "%s", p->colSeparator);
11882   }
11883 }
11884
11885 /*
11886 ** This routine runs when the user presses Ctrl-C
11887 */
11888 static void interrupt_handler(int NotUsed){
11889   UNUSED_PARAMETER(NotUsed);
11890   seenInterrupt++;
11891   if( seenInterrupt>2 ) exit(1);
11892   if( globalDb ) sqlite3_interrupt(globalDb);
11893 }
11894
11895 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11896 /*
11897 ** This routine runs for console events (e.g. Ctrl-C) on Win32
11898 */
11899 static BOOL WINAPI ConsoleCtrlHandler(
11900   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
11901 ){
11902   if( dwCtrlType==CTRL_C_EVENT ){
11903     interrupt_handler(0);
11904     return TRUE;
11905   }
11906   return FALSE;
11907 }
11908 #endif
11909
11910 #ifndef SQLITE_OMIT_AUTHORIZATION
11911 /*
11912 ** When the ".auth ON" is set, the following authorizer callback is
11913 ** invoked.  It always returns SQLITE_OK.
11914 */
11915 static int shellAuth(
11916   void *pClientData,
11917   int op,
11918   const char *zA1,
11919   const char *zA2,
11920   const char *zA3,
11921   const char *zA4
11922 ){
11923   ShellState *p = (ShellState*)pClientData;
11924   static const char *azAction[] = { 0,
11925      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
11926      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
11927      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
11928      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
11929      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
11930      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
11931      "PRAGMA",               "READ",                 "SELECT",
11932      "TRANSACTION",          "UPDATE",               "ATTACH",
11933      "DETACH",               "ALTER_TABLE",          "REINDEX",
11934      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
11935      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
11936   };
11937   int i;
11938   const char *az[4];
11939   az[0] = zA1;
11940   az[1] = zA2;
11941   az[2] = zA3;
11942   az[3] = zA4;
11943   utf8_printf(p->out, "authorizer: %s", azAction[op]);
11944   for(i=0; i<4; i++){
11945     raw_printf(p->out, " ");
11946     if( az[i] ){
11947       output_c_string(p->out, az[i]);
11948     }else{
11949       raw_printf(p->out, "NULL");
11950     }
11951   }
11952   raw_printf(p->out, "\n");
11953   return SQLITE_OK;
11954 }
11955 #endif
11956
11957 /*
11958 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
11959 **
11960 ** This routine converts some CREATE TABLE statements for shadow tables
11961 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
11962 */
11963 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
11964   if( z==0 ) return;
11965   if( zTail==0 ) return;
11966   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
11967     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
11968   }else{
11969     utf8_printf(out, "%s%s", z, zTail);
11970   }
11971 }
11972 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
11973   char c = z[n];
11974   z[n] = 0;
11975   printSchemaLine(out, z, zTail);
11976   z[n] = c;
11977 }
11978
11979 /*
11980 ** Return true if string z[] has nothing but whitespace and comments to the
11981 ** end of the first line.
11982 */
11983 static int wsToEol(const char *z){
11984   int i;
11985   for(i=0; z[i]; i++){
11986     if( z[i]=='\n' ) return 1;
11987     if( IsSpace(z[i]) ) continue;
11988     if( z[i]=='-' && z[i+1]=='-' ) return 1;
11989     return 0;
11990   }
11991   return 1;
11992 }
11993
11994 /*
11995 ** Add a new entry to the EXPLAIN QUERY PLAN data
11996 */
11997 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
11998   EQPGraphRow *pNew;
11999   int nText = strlen30(zText);
12000   if( p->autoEQPtest ){
12001     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
12002   }
12003   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
12004   if( pNew==0 ) shell_out_of_memory();
12005   pNew->iEqpId = iEqpId;
12006   pNew->iParentId = p2;
12007   memcpy(pNew->zText, zText, nText+1);
12008   pNew->pNext = 0;
12009   if( p->sGraph.pLast ){
12010     p->sGraph.pLast->pNext = pNew;
12011   }else{
12012     p->sGraph.pRow = pNew;
12013   }
12014   p->sGraph.pLast = pNew;
12015 }
12016
12017 /*
12018 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
12019 ** in p->sGraph.
12020 */
12021 static void eqp_reset(ShellState *p){
12022   EQPGraphRow *pRow, *pNext;
12023   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
12024     pNext = pRow->pNext;
12025     sqlite3_free(pRow);
12026   }
12027   memset(&p->sGraph, 0, sizeof(p->sGraph));
12028 }
12029
12030 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
12031 ** pOld, or return the first such line if pOld is NULL
12032 */
12033 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
12034   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
12035   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
12036   return pRow;
12037 }
12038
12039 /* Render a single level of the graph that has iEqpId as its parent.  Called
12040 ** recursively to render sublevels.
12041 */
12042 static void eqp_render_level(ShellState *p, int iEqpId){
12043   EQPGraphRow *pRow, *pNext;
12044   int n = strlen30(p->sGraph.zPrefix);
12045   char *z;
12046   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
12047     pNext = eqp_next_row(p, iEqpId, pRow);
12048     z = pRow->zText;
12049     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
12050                 pNext ? "|--" : "`--", z);
12051     if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
12052       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
12053       eqp_render_level(p, pRow->iEqpId);
12054       p->sGraph.zPrefix[n] = 0;
12055     }
12056   }
12057 }
12058
12059 /*
12060 ** Display and reset the EXPLAIN QUERY PLAN data
12061 */
12062 static void eqp_render(ShellState *p){
12063   EQPGraphRow *pRow = p->sGraph.pRow;
12064   if( pRow ){
12065     if( pRow->zText[0]=='-' ){
12066       if( pRow->pNext==0 ){
12067         eqp_reset(p);
12068         return;
12069       }
12070       utf8_printf(p->out, "%s\n", pRow->zText+3);
12071       p->sGraph.pRow = pRow->pNext;
12072       sqlite3_free(pRow);
12073     }else{
12074       utf8_printf(p->out, "QUERY PLAN\n");
12075     }
12076     p->sGraph.zPrefix[0] = 0;
12077     eqp_render_level(p, 0);
12078     eqp_reset(p);
12079   }
12080 }
12081
12082 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
12083 /*
12084 ** Progress handler callback.
12085 */
12086 static int progress_handler(void *pClientData) {
12087   ShellState *p = (ShellState*)pClientData;
12088   p->nProgress++;
12089   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
12090     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
12091     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
12092     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
12093     return 1;
12094   }
12095   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
12096     raw_printf(p->out, "Progress %u\n", p->nProgress);
12097   }
12098   return 0;
12099 }
12100 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
12101
12102 /*
12103 ** Print N dashes
12104 */
12105 static void print_dashes(FILE *out, int N){
12106   const char zDash[] = "--------------------------------------------------";
12107   const int nDash = sizeof(zDash) - 1;
12108   while( N>nDash ){
12109     fputs(zDash, out);
12110     N -= nDash;
12111   }
12112   raw_printf(out, "%.*s", N, zDash);
12113 }
12114
12115 /*
12116 ** Print a markdown or table-style row separator using ascii-art
12117 */
12118 static void print_row_separator(
12119   ShellState *p,
12120   int nArg,
12121   const char *zSep
12122 ){
12123   int i;
12124   if( nArg>0 ){
12125     fputs(zSep, p->out);
12126     print_dashes(p->out, p->actualWidth[0]+2);
12127     for(i=1; i<nArg; i++){
12128       fputs(zSep, p->out);
12129       print_dashes(p->out, p->actualWidth[i]+2);
12130     }
12131     fputs(zSep, p->out);
12132   }
12133   fputs("\n", p->out);
12134 }
12135
12136 /*
12137 ** This is the callback routine that the shell
12138 ** invokes for each row of a query result.
12139 */
12140 static int shell_callback(
12141   void *pArg,
12142   int nArg,        /* Number of result columns */
12143   char **azArg,    /* Text of each result column */
12144   char **azCol,    /* Column names */
12145   int *aiType      /* Column types.  Might be NULL */
12146 ){
12147   int i;
12148   ShellState *p = (ShellState*)pArg;
12149
12150   if( azArg==0 ) return 0;
12151   switch( p->cMode ){
12152     case MODE_Line: {
12153       int w = 5;
12154       if( azArg==0 ) break;
12155       for(i=0; i<nArg; i++){
12156         int len = strlen30(azCol[i] ? azCol[i] : "");
12157         if( len>w ) w = len;
12158       }
12159       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
12160       for(i=0; i<nArg; i++){
12161         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
12162                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
12163       }
12164       break;
12165     }
12166     case MODE_Explain: {
12167       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
12168       if( nArg>ArraySize(aExplainWidth) ){
12169         nArg = ArraySize(aExplainWidth);
12170       }
12171       if( p->cnt++==0 ){
12172         for(i=0; i<nArg; i++){
12173           int w = aExplainWidth[i];
12174           utf8_width_print(p->out, w, azCol[i]);
12175           fputs(i==nArg-1 ? "\n" : "  ", p->out);
12176         }
12177         for(i=0; i<nArg; i++){
12178           int w = aExplainWidth[i];
12179           print_dashes(p->out, w);
12180           fputs(i==nArg-1 ? "\n" : "  ", p->out);
12181         }
12182       }
12183       if( azArg==0 ) break;
12184       for(i=0; i<nArg; i++){
12185         int w = aExplainWidth[i];
12186         if( i==nArg-1 ) w = 0;
12187         if( azArg[i] && strlenChar(azArg[i])>w ){
12188           w = strlenChar(azArg[i]);
12189         }
12190         if( i==1 && p->aiIndent && p->pStmt ){
12191           if( p->iIndent<p->nIndent ){
12192             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
12193           }
12194           p->iIndent++;
12195         }
12196         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
12197         fputs(i==nArg-1 ? "\n" : "  ", p->out);
12198       }
12199       break;
12200     }
12201     case MODE_Semi: {   /* .schema and .fullschema output */
12202       printSchemaLine(p->out, azArg[0], ";\n");
12203       break;
12204     }
12205     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
12206       char *z;
12207       int j;
12208       int nParen = 0;
12209       char cEnd = 0;
12210       char c;
12211       int nLine = 0;
12212       assert( nArg==1 );
12213       if( azArg[0]==0 ) break;
12214       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
12215        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
12216       ){
12217         utf8_printf(p->out, "%s;\n", azArg[0]);
12218         break;
12219       }
12220       z = sqlite3_mprintf("%s", azArg[0]);
12221       j = 0;
12222       for(i=0; IsSpace(z[i]); i++){}
12223       for(; (c = z[i])!=0; i++){
12224         if( IsSpace(c) ){
12225           if( z[j-1]=='\r' ) z[j-1] = '\n';
12226           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
12227         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
12228           j--;
12229         }
12230         z[j++] = c;
12231       }
12232       while( j>0 && IsSpace(z[j-1]) ){ j--; }
12233       z[j] = 0;
12234       if( strlen30(z)>=79 ){
12235         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
12236           if( c==cEnd ){
12237             cEnd = 0;
12238           }else if( c=='"' || c=='\'' || c=='`' ){
12239             cEnd = c;
12240           }else if( c=='[' ){
12241             cEnd = ']';
12242           }else if( c=='-' && z[i+1]=='-' ){
12243             cEnd = '\n';
12244           }else if( c=='(' ){
12245             nParen++;
12246           }else if( c==')' ){
12247             nParen--;
12248             if( nLine>0 && nParen==0 && j>0 ){
12249               printSchemaLineN(p->out, z, j, "\n");
12250               j = 0;
12251             }
12252           }
12253           z[j++] = c;
12254           if( nParen==1 && cEnd==0
12255            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
12256           ){
12257             if( c=='\n' ) j--;
12258             printSchemaLineN(p->out, z, j, "\n  ");
12259             j = 0;
12260             nLine++;
12261             while( IsSpace(z[i+1]) ){ i++; }
12262           }
12263         }
12264         z[j] = 0;
12265       }
12266       printSchemaLine(p->out, z, ";\n");
12267       sqlite3_free(z);
12268       break;
12269     }
12270     case MODE_List: {
12271       if( p->cnt++==0 && p->showHeader ){
12272         for(i=0; i<nArg; i++){
12273           utf8_printf(p->out,"%s%s",azCol[i],
12274                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
12275         }
12276       }
12277       if( azArg==0 ) break;
12278       for(i=0; i<nArg; i++){
12279         char *z = azArg[i];
12280         if( z==0 ) z = p->nullValue;
12281         utf8_printf(p->out, "%s", z);
12282         if( i<nArg-1 ){
12283           utf8_printf(p->out, "%s", p->colSeparator);
12284         }else{
12285           utf8_printf(p->out, "%s", p->rowSeparator);
12286         }
12287       }
12288       break;
12289     }
12290     case MODE_Html: {
12291       if( p->cnt++==0 && p->showHeader ){
12292         raw_printf(p->out,"<TR>");
12293         for(i=0; i<nArg; i++){
12294           raw_printf(p->out,"<TH>");
12295           output_html_string(p->out, azCol[i]);
12296           raw_printf(p->out,"</TH>\n");
12297         }
12298         raw_printf(p->out,"</TR>\n");
12299       }
12300       if( azArg==0 ) break;
12301       raw_printf(p->out,"<TR>");
12302       for(i=0; i<nArg; i++){
12303         raw_printf(p->out,"<TD>");
12304         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
12305         raw_printf(p->out,"</TD>\n");
12306       }
12307       raw_printf(p->out,"</TR>\n");
12308       break;
12309     }
12310     case MODE_Tcl: {
12311       if( p->cnt++==0 && p->showHeader ){
12312         for(i=0; i<nArg; i++){
12313           output_c_string(p->out,azCol[i] ? azCol[i] : "");
12314           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
12315         }
12316         utf8_printf(p->out, "%s", p->rowSeparator);
12317       }
12318       if( azArg==0 ) break;
12319       for(i=0; i<nArg; i++){
12320         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
12321         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
12322       }
12323       utf8_printf(p->out, "%s", p->rowSeparator);
12324       break;
12325     }
12326     case MODE_Csv: {
12327       setBinaryMode(p->out, 1);
12328       if( p->cnt++==0 && p->showHeader ){
12329         for(i=0; i<nArg; i++){
12330           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
12331         }
12332         utf8_printf(p->out, "%s", p->rowSeparator);
12333       }
12334       if( nArg>0 ){
12335         for(i=0; i<nArg; i++){
12336           output_csv(p, azArg[i], i<nArg-1);
12337         }
12338         utf8_printf(p->out, "%s", p->rowSeparator);
12339       }
12340       setTextMode(p->out, 1);
12341       break;
12342     }
12343     case MODE_Insert: {
12344       if( azArg==0 ) break;
12345       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
12346       if( p->showHeader ){
12347         raw_printf(p->out,"(");
12348         for(i=0; i<nArg; i++){
12349           if( i>0 ) raw_printf(p->out, ",");
12350           if( quoteChar(azCol[i]) ){
12351             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
12352             utf8_printf(p->out, "%s", z);
12353             sqlite3_free(z);
12354           }else{
12355             raw_printf(p->out, "%s", azCol[i]);
12356           }
12357         }
12358         raw_printf(p->out,")");
12359       }
12360       p->cnt++;
12361       for(i=0; i<nArg; i++){
12362         raw_printf(p->out, i>0 ? "," : " VALUES(");
12363         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
12364           utf8_printf(p->out,"NULL");
12365         }else if( aiType && aiType[i]==SQLITE_TEXT ){
12366           if( ShellHasFlag(p, SHFLG_Newlines) ){
12367             output_quoted_string(p->out, azArg[i]);
12368           }else{
12369             output_quoted_escaped_string(p->out, azArg[i]);
12370           }
12371         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
12372           utf8_printf(p->out,"%s", azArg[i]);
12373         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
12374           char z[50];
12375           double r = sqlite3_column_double(p->pStmt, i);
12376           sqlite3_uint64 ur;
12377           memcpy(&ur,&r,sizeof(r));
12378           if( ur==0x7ff0000000000000LL ){
12379             raw_printf(p->out, "1e999");
12380           }else if( ur==0xfff0000000000000LL ){
12381             raw_printf(p->out, "-1e999");
12382           }else{
12383             sqlite3_snprintf(50,z,"%!.20g", r);
12384             raw_printf(p->out, "%s", z);
12385           }
12386         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
12387           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
12388           int nBlob = sqlite3_column_bytes(p->pStmt, i);
12389           output_hex_blob(p->out, pBlob, nBlob);
12390         }else if( isNumber(azArg[i], 0) ){
12391           utf8_printf(p->out,"%s", azArg[i]);
12392         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
12393           output_quoted_string(p->out, azArg[i]);
12394         }else{
12395           output_quoted_escaped_string(p->out, azArg[i]);
12396         }
12397       }
12398       raw_printf(p->out,");\n");
12399       break;
12400     }
12401     case MODE_Json: {
12402       if( azArg==0 ) break;
12403       if( p->cnt==0 ){
12404         fputs("[{", p->out);
12405       }else{
12406         fputs(",\n{", p->out);
12407       }
12408       p->cnt++;
12409       for(i=0; i<nArg; i++){
12410         output_json_string(p->out, azCol[i], -1);
12411         putc(':', p->out);
12412         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
12413           fputs("null",p->out);
12414         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
12415           char z[50];
12416           double r = sqlite3_column_double(p->pStmt, i);
12417           sqlite3_uint64 ur;
12418           memcpy(&ur,&r,sizeof(r));
12419           if( ur==0x7ff0000000000000LL ){
12420             raw_printf(p->out, "1e999");
12421           }else if( ur==0xfff0000000000000LL ){
12422             raw_printf(p->out, "-1e999");
12423           }else{
12424             sqlite3_snprintf(50,z,"%!.20g", r);
12425             raw_printf(p->out, "%s", z);
12426           }
12427         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
12428           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
12429           int nBlob = sqlite3_column_bytes(p->pStmt, i);
12430           output_json_string(p->out, pBlob, nBlob);
12431         }else if( aiType && aiType[i]==SQLITE_TEXT ){
12432           output_json_string(p->out, azArg[i], -1);
12433         }else{
12434           utf8_printf(p->out,"%s", azArg[i]);
12435         }
12436         if( i<nArg-1 ){
12437           putc(',', p->out);
12438         }
12439       }
12440       putc('}', p->out);
12441       break;
12442     }
12443     case MODE_Quote: {
12444       if( azArg==0 ) break;
12445       if( p->cnt==0 && p->showHeader ){
12446         for(i=0; i<nArg; i++){
12447           if( i>0 ) fputs(p->colSeparator, p->out);
12448           output_quoted_string(p->out, azCol[i]);
12449         }
12450         fputs(p->rowSeparator, p->out);
12451       }
12452       p->cnt++;
12453       for(i=0; i<nArg; i++){
12454         if( i>0 ) fputs(p->colSeparator, p->out);
12455         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
12456           utf8_printf(p->out,"NULL");
12457         }else if( aiType && aiType[i]==SQLITE_TEXT ){
12458           output_quoted_string(p->out, azArg[i]);
12459         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
12460           utf8_printf(p->out,"%s", azArg[i]);
12461         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
12462           char z[50];
12463           double r = sqlite3_column_double(p->pStmt, i);
12464           sqlite3_snprintf(50,z,"%!.20g", r);
12465           raw_printf(p->out, "%s", z);
12466         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
12467           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
12468           int nBlob = sqlite3_column_bytes(p->pStmt, i);
12469           output_hex_blob(p->out, pBlob, nBlob);
12470         }else if( isNumber(azArg[i], 0) ){
12471           utf8_printf(p->out,"%s", azArg[i]);
12472         }else{
12473           output_quoted_string(p->out, azArg[i]);
12474         }
12475       }
12476       fputs(p->rowSeparator, p->out);
12477       break;
12478     }
12479     case MODE_Ascii: {
12480       if( p->cnt++==0 && p->showHeader ){
12481         for(i=0; i<nArg; i++){
12482           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
12483           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
12484         }
12485         utf8_printf(p->out, "%s", p->rowSeparator);
12486       }
12487       if( azArg==0 ) break;
12488       for(i=0; i<nArg; i++){
12489         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
12490         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
12491       }
12492       utf8_printf(p->out, "%s", p->rowSeparator);
12493       break;
12494     }
12495     case MODE_EQP: {
12496       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
12497       break;
12498     }
12499   }
12500   return 0;
12501 }
12502
12503 /*
12504 ** This is the callback routine that the SQLite library
12505 ** invokes for each row of a query result.
12506 */
12507 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
12508   /* since we don't have type info, call the shell_callback with a NULL value */
12509   return shell_callback(pArg, nArg, azArg, azCol, NULL);
12510 }
12511
12512 /*
12513 ** This is the callback routine from sqlite3_exec() that appends all
12514 ** output onto the end of a ShellText object.
12515 */
12516 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
12517   ShellText *p = (ShellText*)pArg;
12518   int i;
12519   UNUSED_PARAMETER(az);
12520   if( azArg==0 ) return 0;
12521   if( p->n ) appendText(p, "|", 0);
12522   for(i=0; i<nArg; i++){
12523     if( i ) appendText(p, ",", 0);
12524     if( azArg[i] ) appendText(p, azArg[i], 0);
12525   }
12526   return 0;
12527 }
12528
12529 /*
12530 ** Generate an appropriate SELFTEST table in the main database.
12531 */
12532 static void createSelftestTable(ShellState *p){
12533   char *zErrMsg = 0;
12534   sqlite3_exec(p->db,
12535     "SAVEPOINT selftest_init;\n"
12536     "CREATE TABLE IF NOT EXISTS selftest(\n"
12537     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
12538     "  op TEXT,\n"                   /* Operator:  memo run */
12539     "  cmd TEXT,\n"                  /* Command text */
12540     "  ans TEXT\n"                   /* Desired answer */
12541     ");"
12542     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
12543     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
12544     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
12545     "         'memo','Tests generated by --init');\n"
12546     "INSERT INTO [_shell$self]\n"
12547     "  SELECT 'run',\n"
12548     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
12549                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
12550     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
12551                           "FROM sqlite_schema ORDER BY 2',224));\n"
12552     "INSERT INTO [_shell$self]\n"
12553     "  SELECT 'run',"
12554     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
12555     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
12556     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
12557     "  FROM (\n"
12558     "    SELECT name FROM sqlite_schema\n"
12559     "     WHERE type='table'\n"
12560     "       AND name<>'selftest'\n"
12561     "       AND coalesce(rootpage,0)>0\n"
12562     "  )\n"
12563     " ORDER BY name;\n"
12564     "INSERT INTO [_shell$self]\n"
12565     "  VALUES('run','PRAGMA integrity_check','ok');\n"
12566     "INSERT INTO selftest(tno,op,cmd,ans)"
12567     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
12568     "DROP TABLE [_shell$self];"
12569     ,0,0,&zErrMsg);
12570   if( zErrMsg ){
12571     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
12572     sqlite3_free(zErrMsg);
12573   }
12574   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
12575 }
12576
12577
12578 /*
12579 ** Set the destination table field of the ShellState structure to
12580 ** the name of the table given.  Escape any quote characters in the
12581 ** table name.
12582 */
12583 static void set_table_name(ShellState *p, const char *zName){
12584   int i, n;
12585   char cQuote;
12586   char *z;
12587
12588   if( p->zDestTable ){
12589     free(p->zDestTable);
12590     p->zDestTable = 0;
12591   }
12592   if( zName==0 ) return;
12593   cQuote = quoteChar(zName);
12594   n = strlen30(zName);
12595   if( cQuote ) n += n+2;
12596   z = p->zDestTable = malloc( n+1 );
12597   if( z==0 ) shell_out_of_memory();
12598   n = 0;
12599   if( cQuote ) z[n++] = cQuote;
12600   for(i=0; zName[i]; i++){
12601     z[n++] = zName[i];
12602     if( zName[i]==cQuote ) z[n++] = cQuote;
12603   }
12604   if( cQuote ) z[n++] = cQuote;
12605   z[n] = 0;
12606 }
12607
12608
12609 /*
12610 ** Execute a query statement that will generate SQL output.  Print
12611 ** the result columns, comma-separated, on a line and then add a
12612 ** semicolon terminator to the end of that line.
12613 **
12614 ** If the number of columns is 1 and that column contains text "--"
12615 ** then write the semicolon on a separate line.  That way, if a
12616 ** "--" comment occurs at the end of the statement, the comment
12617 ** won't consume the semicolon terminator.
12618 */
12619 static int run_table_dump_query(
12620   ShellState *p,           /* Query context */
12621   const char *zSelect      /* SELECT statement to extract content */
12622 ){
12623   sqlite3_stmt *pSelect;
12624   int rc;
12625   int nResult;
12626   int i;
12627   const char *z;
12628   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
12629   if( rc!=SQLITE_OK || !pSelect ){
12630     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
12631                 sqlite3_errmsg(p->db));
12632     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
12633     return rc;
12634   }
12635   rc = sqlite3_step(pSelect);
12636   nResult = sqlite3_column_count(pSelect);
12637   while( rc==SQLITE_ROW ){
12638     z = (const char*)sqlite3_column_text(pSelect, 0);
12639     utf8_printf(p->out, "%s", z);
12640     for(i=1; i<nResult; i++){
12641       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
12642     }
12643     if( z==0 ) z = "";
12644     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
12645     if( z[0] ){
12646       raw_printf(p->out, "\n;\n");
12647     }else{
12648       raw_printf(p->out, ";\n");
12649     }
12650     rc = sqlite3_step(pSelect);
12651   }
12652   rc = sqlite3_finalize(pSelect);
12653   if( rc!=SQLITE_OK ){
12654     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
12655                 sqlite3_errmsg(p->db));
12656     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
12657   }
12658   return rc;
12659 }
12660
12661 /*
12662 ** Allocate space and save off current error string.
12663 */
12664 static char *save_err_msg(
12665   sqlite3 *db            /* Database to query */
12666 ){
12667   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
12668   char *zErrMsg = sqlite3_malloc64(nErrMsg);
12669   if( zErrMsg ){
12670     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
12671   }
12672   return zErrMsg;
12673 }
12674
12675 #ifdef __linux__
12676 /*
12677 ** Attempt to display I/O stats on Linux using /proc/PID/io
12678 */
12679 static void displayLinuxIoStats(FILE *out){
12680   FILE *in;
12681   char z[200];
12682   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
12683   in = fopen(z, "rb");
12684   if( in==0 ) return;
12685   while( fgets(z, sizeof(z), in)!=0 ){
12686     static const struct {
12687       const char *zPattern;
12688       const char *zDesc;
12689     } aTrans[] = {
12690       { "rchar: ",                  "Bytes received by read():" },
12691       { "wchar: ",                  "Bytes sent to write():"    },
12692       { "syscr: ",                  "Read() system calls:"      },
12693       { "syscw: ",                  "Write() system calls:"     },
12694       { "read_bytes: ",             "Bytes read from storage:"  },
12695       { "write_bytes: ",            "Bytes written to storage:" },
12696       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
12697     };
12698     int i;
12699     for(i=0; i<ArraySize(aTrans); i++){
12700       int n = strlen30(aTrans[i].zPattern);
12701       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
12702         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
12703         break;
12704       }
12705     }
12706   }
12707   fclose(in);
12708 }
12709 #endif
12710
12711 /*
12712 ** Display a single line of status using 64-bit values.
12713 */
12714 static void displayStatLine(
12715   ShellState *p,            /* The shell context */
12716   char *zLabel,             /* Label for this one line */
12717   char *zFormat,            /* Format for the result */
12718   int iStatusCtrl,          /* Which status to display */
12719   int bReset                /* True to reset the stats */
12720 ){
12721   sqlite3_int64 iCur = -1;
12722   sqlite3_int64 iHiwtr = -1;
12723   int i, nPercent;
12724   char zLine[200];
12725   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
12726   for(i=0, nPercent=0; zFormat[i]; i++){
12727     if( zFormat[i]=='%' ) nPercent++;
12728   }
12729   if( nPercent>1 ){
12730     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
12731   }else{
12732     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
12733   }
12734   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
12735 }
12736
12737 /*
12738 ** Display memory stats.
12739 */
12740 static int display_stats(
12741   sqlite3 *db,                /* Database to query */
12742   ShellState *pArg,           /* Pointer to ShellState */
12743   int bReset                  /* True to reset the stats */
12744 ){
12745   int iCur;
12746   int iHiwtr;
12747   FILE *out;
12748   if( pArg==0 || pArg->out==0 ) return 0;
12749   out = pArg->out;
12750
12751   if( pArg->pStmt && pArg->statsOn==2 ){
12752     int nCol, i, x;
12753     sqlite3_stmt *pStmt = pArg->pStmt;
12754     char z[100];
12755     nCol = sqlite3_column_count(pStmt);
12756     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
12757     for(i=0; i<nCol; i++){
12758       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
12759       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
12760 #ifndef SQLITE_OMIT_DECLTYPE
12761       sqlite3_snprintf(30, z+x, "declared type:");
12762       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
12763 #endif
12764 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12765       sqlite3_snprintf(30, z+x, "database name:");
12766       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
12767       sqlite3_snprintf(30, z+x, "table name:");
12768       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
12769       sqlite3_snprintf(30, z+x, "origin name:");
12770       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
12771 #endif
12772     }
12773   }
12774
12775   if( pArg->statsOn==3 ){
12776     if( pArg->pStmt ){
12777       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
12778       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
12779     }
12780     return 0;
12781   }
12782
12783   displayStatLine(pArg, "Memory Used:",
12784      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
12785   displayStatLine(pArg, "Number of Outstanding Allocations:",
12786      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
12787   if( pArg->shellFlgs & SHFLG_Pagecache ){
12788     displayStatLine(pArg, "Number of Pcache Pages Used:",
12789        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
12790   }
12791   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
12792      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
12793   displayStatLine(pArg, "Largest Allocation:",
12794      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
12795   displayStatLine(pArg, "Largest Pcache Allocation:",
12796      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
12797 #ifdef YYTRACKMAXSTACKDEPTH
12798   displayStatLine(pArg, "Deepest Parser Stack:",
12799      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
12800 #endif
12801
12802   if( db ){
12803     if( pArg->shellFlgs & SHFLG_Lookaside ){
12804       iHiwtr = iCur = -1;
12805       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
12806                         &iCur, &iHiwtr, bReset);
12807       raw_printf(pArg->out,
12808               "Lookaside Slots Used:                %d (max %d)\n",
12809               iCur, iHiwtr);
12810       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
12811                         &iCur, &iHiwtr, bReset);
12812       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
12813               iHiwtr);
12814       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
12815                         &iCur, &iHiwtr, bReset);
12816       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
12817               iHiwtr);
12818       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
12819                         &iCur, &iHiwtr, bReset);
12820       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
12821               iHiwtr);
12822     }
12823     iHiwtr = iCur = -1;
12824     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
12825     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
12826             iCur);
12827     iHiwtr = iCur = -1;
12828     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
12829     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
12830     iHiwtr = iCur = -1;
12831     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
12832     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
12833     iHiwtr = iCur = -1;
12834     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
12835     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
12836     iHiwtr = iCur = -1;
12837     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
12838     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
12839     iHiwtr = iCur = -1;
12840     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
12841     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
12842             iCur);
12843     iHiwtr = iCur = -1;
12844     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
12845     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
12846             iCur);
12847   }
12848
12849   if( pArg->pStmt ){
12850     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
12851                                bReset);
12852     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
12853     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
12854     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
12855     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
12856     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
12857     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
12858     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
12859     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
12860     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
12861     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
12862     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
12863     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
12864     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
12865   }
12866
12867 #ifdef __linux__
12868   displayLinuxIoStats(pArg->out);
12869 #endif
12870
12871   /* Do not remove this machine readable comment: extra-stats-output-here */
12872
12873   return 0;
12874 }
12875
12876 /*
12877 ** Display scan stats.
12878 */
12879 static void display_scanstats(
12880   sqlite3 *db,                    /* Database to query */
12881   ShellState *pArg                /* Pointer to ShellState */
12882 ){
12883 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
12884   UNUSED_PARAMETER(db);
12885   UNUSED_PARAMETER(pArg);
12886 #else
12887   int i, k, n, mx;
12888   raw_printf(pArg->out, "-------- scanstats --------\n");
12889   mx = 0;
12890   for(k=0; k<=mx; k++){
12891     double rEstLoop = 1.0;
12892     for(i=n=0; 1; i++){
12893       sqlite3_stmt *p = pArg->pStmt;
12894       sqlite3_int64 nLoop, nVisit;
12895       double rEst;
12896       int iSid;
12897       const char *zExplain;
12898       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
12899         break;
12900       }
12901       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
12902       if( iSid>mx ) mx = iSid;
12903       if( iSid!=k ) continue;
12904       if( n==0 ){
12905         rEstLoop = (double)nLoop;
12906         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
12907       }
12908       n++;
12909       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
12910       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
12911       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
12912       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
12913       rEstLoop *= rEst;
12914       raw_printf(pArg->out,
12915           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
12916           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
12917       );
12918     }
12919   }
12920   raw_printf(pArg->out, "---------------------------\n");
12921 #endif
12922 }
12923
12924 /*
12925 ** Parameter azArray points to a zero-terminated array of strings. zStr
12926 ** points to a single nul-terminated string. Return non-zero if zStr
12927 ** is equal, according to strcmp(), to any of the strings in the array.
12928 ** Otherwise, return zero.
12929 */
12930 static int str_in_array(const char *zStr, const char **azArray){
12931   int i;
12932   for(i=0; azArray[i]; i++){
12933     if( 0==strcmp(zStr, azArray[i]) ) return 1;
12934   }
12935   return 0;
12936 }
12937
12938 /*
12939 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
12940 ** and populate the ShellState.aiIndent[] array with the number of
12941 ** spaces each opcode should be indented before it is output.
12942 **
12943 ** The indenting rules are:
12944 **
12945 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
12946 **       all opcodes that occur between the p2 jump destination and the opcode
12947 **       itself by 2 spaces.
12948 **
12949 **     * For each "Goto", if the jump destination is earlier in the program
12950 **       and ends on one of:
12951 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
12952 **       or if the P1 parameter is one instead of zero,
12953 **       then indent all opcodes between the earlier instruction
12954 **       and "Goto" by 2 spaces.
12955 */
12956 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
12957   const char *zSql;               /* The text of the SQL statement */
12958   const char *z;                  /* Used to check if this is an EXPLAIN */
12959   int *abYield = 0;               /* True if op is an OP_Yield */
12960   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
12961   int iOp;                        /* Index of operation in p->aiIndent[] */
12962
12963   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
12964   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
12965                             "Rewind", 0 };
12966   const char *azGoto[] = { "Goto", 0 };
12967
12968   /* Try to figure out if this is really an EXPLAIN statement. If this
12969   ** cannot be verified, return early.  */
12970   if( sqlite3_column_count(pSql)!=8 ){
12971     p->cMode = p->mode;
12972     return;
12973   }
12974   zSql = sqlite3_sql(pSql);
12975   if( zSql==0 ) return;
12976   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
12977   if( sqlite3_strnicmp(z, "explain", 7) ){
12978     p->cMode = p->mode;
12979     return;
12980   }
12981
12982   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
12983     int i;
12984     int iAddr = sqlite3_column_int(pSql, 0);
12985     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
12986
12987     /* Set p2 to the P2 field of the current opcode. Then, assuming that
12988     ** p2 is an instruction address, set variable p2op to the index of that
12989     ** instruction in the aiIndent[] array. p2 and p2op may be different if
12990     ** the current instruction is part of a sub-program generated by an
12991     ** SQL trigger or foreign key.  */
12992     int p2 = sqlite3_column_int(pSql, 3);
12993     int p2op = (p2 + (iOp-iAddr));
12994
12995     /* Grow the p->aiIndent array as required */
12996     if( iOp>=nAlloc ){
12997       if( iOp==0 ){
12998         /* Do further verfication that this is explain output.  Abort if
12999         ** it is not */
13000         static const char *explainCols[] = {
13001            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
13002         int jj;
13003         for(jj=0; jj<ArraySize(explainCols); jj++){
13004           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
13005             p->cMode = p->mode;
13006             sqlite3_reset(pSql);
13007             return;
13008           }
13009         }
13010       }
13011       nAlloc += 100;
13012       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
13013       if( p->aiIndent==0 ) shell_out_of_memory();
13014       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
13015       if( abYield==0 ) shell_out_of_memory();
13016     }
13017     abYield[iOp] = str_in_array(zOp, azYield);
13018     p->aiIndent[iOp] = 0;
13019     p->nIndent = iOp+1;
13020
13021     if( str_in_array(zOp, azNext) ){
13022       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
13023     }
13024     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
13025      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
13026     ){
13027       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
13028     }
13029   }
13030
13031   p->iIndent = 0;
13032   sqlite3_free(abYield);
13033   sqlite3_reset(pSql);
13034 }
13035
13036 /*
13037 ** Free the array allocated by explain_data_prepare().
13038 */
13039 static void explain_data_delete(ShellState *p){
13040   sqlite3_free(p->aiIndent);
13041   p->aiIndent = 0;
13042   p->nIndent = 0;
13043   p->iIndent = 0;
13044 }
13045
13046 /*
13047 ** Disable and restore .wheretrace and .selecttrace settings.
13048 */
13049 static unsigned int savedSelectTrace;
13050 static unsigned int savedWhereTrace;
13051 static void disable_debug_trace_modes(void){
13052   unsigned int zero = 0;
13053   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
13054   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
13055   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
13056   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
13057 }
13058 static void restore_debug_trace_modes(void){
13059   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
13060   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
13061 }
13062
13063 /* Create the TEMP table used to store parameter bindings */
13064 static void bind_table_init(ShellState *p){
13065   int wrSchema = 0;
13066   int defensiveMode = 0;
13067   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
13068   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
13069   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
13070   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
13071   sqlite3_exec(p->db,
13072     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
13073     "  key TEXT PRIMARY KEY,\n"
13074     "  value ANY\n"
13075     ") WITHOUT ROWID;",
13076     0, 0, 0);
13077   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
13078   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
13079 }
13080
13081 /*
13082 ** Bind parameters on a prepared statement.
13083 **
13084 ** Parameter bindings are taken from a TEMP table of the form:
13085 **
13086 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
13087 **    WITHOUT ROWID;
13088 **
13089 ** No bindings occur if this table does not exist.  The name of the table
13090 ** begins with "sqlite_" so that it will not collide with ordinary application
13091 ** tables.  The table must be in the TEMP schema.
13092 */
13093 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
13094   int nVar;
13095   int i;
13096   int rc;
13097   sqlite3_stmt *pQ = 0;
13098
13099   nVar = sqlite3_bind_parameter_count(pStmt);
13100   if( nVar==0 ) return;  /* Nothing to do */
13101   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
13102                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
13103     return; /* Parameter table does not exist */
13104   }
13105   rc = sqlite3_prepare_v2(pArg->db,
13106           "SELECT value FROM temp.sqlite_parameters"
13107           " WHERE key=?1", -1, &pQ, 0);
13108   if( rc || pQ==0 ) return;
13109   for(i=1; i<=nVar; i++){
13110     char zNum[30];
13111     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
13112     if( zVar==0 ){
13113       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
13114       zVar = zNum;
13115     }
13116     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
13117     if( sqlite3_step(pQ)==SQLITE_ROW ){
13118       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
13119     }else{
13120       sqlite3_bind_null(pStmt, i);
13121     }
13122     sqlite3_reset(pQ);
13123   }
13124   sqlite3_finalize(pQ);
13125 }
13126
13127 /*
13128 ** UTF8 box-drawing characters.  Imagine box lines like this:
13129 **
13130 **           1
13131 **           |
13132 **       4 --+-- 2
13133 **           |
13134 **           3
13135 **
13136 ** Each box characters has between 2 and 4 of the lines leading from
13137 ** the center.  The characters are here identified by the numbers of
13138 ** their corresponding lines.
13139 */
13140 #define BOX_24   "\342\224\200"  /* U+2500 --- */
13141 #define BOX_13   "\342\224\202"  /* U+2502  |  */
13142 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
13143 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
13144 #define BOX_12   "\342\224\224"  /* U+2514  '- */
13145 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
13146 #define BOX_123  "\342\224\234"  /* U+251c  |- */
13147 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
13148 #define BOX_234  "\342\224\254"  /* U+252c -,- */
13149 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
13150 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
13151
13152 /* Draw horizontal line N characters long using unicode box
13153 ** characters
13154 */
13155 static void print_box_line(FILE *out, int N){
13156   const char zDash[] = 
13157       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
13158       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
13159   const int nDash = sizeof(zDash) - 1;
13160   N *= 3;
13161   while( N>nDash ){
13162     utf8_printf(out, zDash);
13163     N -= nDash;
13164   }
13165   utf8_printf(out, "%.*s", N, zDash);
13166 }
13167
13168 /*
13169 ** Draw a horizontal separator for a MODE_Box table.
13170 */
13171 static void print_box_row_separator(
13172   ShellState *p,
13173   int nArg,
13174   const char *zSep1,
13175   const char *zSep2,
13176   const char *zSep3
13177 ){
13178   int i;
13179   if( nArg>0 ){
13180     utf8_printf(p->out, "%s", zSep1);
13181     print_box_line(p->out, p->actualWidth[0]+2);
13182     for(i=1; i<nArg; i++){
13183       utf8_printf(p->out, "%s", zSep2);
13184       print_box_line(p->out, p->actualWidth[i]+2);
13185     }
13186     utf8_printf(p->out, "%s", zSep3);
13187   }
13188   fputs("\n", p->out);
13189 }
13190
13191
13192
13193 /*
13194 ** Run a prepared statement and output the result in one of the
13195 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
13196 ** or MODE_Box.
13197 **
13198 ** This is different from ordinary exec_prepared_stmt() in that
13199 ** it has to run the entire query and gather the results into memory
13200 ** first, in order to determine column widths, before providing
13201 ** any output.
13202 */
13203 static void exec_prepared_stmt_columnar(
13204   ShellState *p,                        /* Pointer to ShellState */
13205   sqlite3_stmt *pStmt                   /* Statment to run */
13206 ){
13207   sqlite3_int64 nRow = 0;
13208   int nColumn = 0;
13209   char **azData = 0;
13210   sqlite3_int64 nAlloc = 0;
13211   const char *z;
13212   int rc;
13213   sqlite3_int64 i, nData;
13214   int j, nTotal, w, n;
13215   const char *colSep = 0;
13216   const char *rowSep = 0;
13217
13218   rc = sqlite3_step(pStmt);
13219   if( rc!=SQLITE_ROW ) return;
13220   nColumn = sqlite3_column_count(pStmt);
13221   nAlloc = nColumn*4;
13222   if( nAlloc<=0 ) nAlloc = 1;
13223   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
13224   if( azData==0 ) shell_out_of_memory();
13225   for(i=0; i<nColumn; i++){
13226     azData[i] = strdup(sqlite3_column_name(pStmt,i));
13227   }
13228   do{
13229     if( (nRow+2)*nColumn >= nAlloc ){
13230       nAlloc *= 2;
13231       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
13232       if( azData==0 ) shell_out_of_memory();
13233     }
13234     nRow++;
13235     for(i=0; i<nColumn; i++){
13236       z = (const char*)sqlite3_column_text(pStmt,i);
13237       azData[nRow*nColumn + i] = z ? strdup(z) : 0;
13238     }
13239   }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
13240   if( nColumn>p->nWidth ){
13241     p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
13242     if( p->colWidth==0 ) shell_out_of_memory();
13243     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
13244     p->nWidth = nColumn;
13245     p->actualWidth = &p->colWidth[nColumn];
13246   }
13247   memset(p->actualWidth, 0, nColumn*sizeof(int));
13248   for(i=0; i<nColumn; i++){
13249     w = p->colWidth[i];
13250     if( w<0 ) w = -w;
13251     p->actualWidth[i] = w;
13252   }
13253   nTotal = nColumn*(nRow+1);
13254   for(i=0; i<nTotal; i++){
13255     z = azData[i];
13256     if( z==0 ) z = p->nullValue;
13257     n = strlenChar(z);
13258     j = i%nColumn;
13259     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
13260   }
13261   if( seenInterrupt ) goto columnar_end;
13262   if( nColumn==0 ) goto columnar_end;
13263   switch( p->cMode ){
13264     case MODE_Column: {
13265       colSep = "  ";
13266       rowSep = "\n";
13267       if( p->showHeader ){
13268         for(i=0; i<nColumn; i++){
13269           w = p->actualWidth[i];
13270           if( p->colWidth[i]<0 ) w = -w;
13271           utf8_width_print(p->out, w, azData[i]);
13272           fputs(i==nColumn-1?"\n":"  ", p->out);
13273         }
13274         for(i=0; i<nColumn; i++){
13275           print_dashes(p->out, p->actualWidth[i]);
13276           fputs(i==nColumn-1?"\n":"  ", p->out);
13277         }
13278       }
13279       break;
13280     }
13281     case MODE_Table: {
13282       colSep = " | ";
13283       rowSep = " |\n";
13284       print_row_separator(p, nColumn, "+");
13285       fputs("| ", p->out);
13286       for(i=0; i<nColumn; i++){
13287         w = p->actualWidth[i];
13288         n = strlenChar(azData[i]);
13289         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
13290         fputs(i==nColumn-1?" |\n":" | ", p->out);
13291       }
13292       print_row_separator(p, nColumn, "+");
13293       break;
13294     }
13295     case MODE_Markdown: {
13296       colSep = " | ";
13297       rowSep = " |\n";
13298       fputs("| ", p->out);
13299       for(i=0; i<nColumn; i++){
13300         w = p->actualWidth[i];
13301         n = strlenChar(azData[i]);
13302         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
13303         fputs(i==nColumn-1?" |\n":" | ", p->out);
13304       }
13305       print_row_separator(p, nColumn, "|");
13306       break;
13307     }
13308     case MODE_Box: {
13309       colSep = " " BOX_13 " ";
13310       rowSep = " " BOX_13 "\n";
13311       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
13312       utf8_printf(p->out, BOX_13 " ");
13313       for(i=0; i<nColumn; i++){
13314         w = p->actualWidth[i];
13315         n = strlenChar(azData[i]);
13316         utf8_printf(p->out, "%*s%s%*s%s",
13317             (w-n)/2, "", azData[i], (w-n+1)/2, "",
13318             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
13319       }
13320       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
13321       break;
13322     }
13323   }
13324   for(i=nColumn, j=0; i<nTotal; i++, j++){
13325     if( j==0 && p->cMode!=MODE_Column ){
13326       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
13327     }
13328     z = azData[i];
13329     if( z==0 ) z = p->nullValue;
13330     w = p->actualWidth[j];
13331     if( p->colWidth[j]<0 ) w = -w;
13332     utf8_width_print(p->out, w, z);
13333     if( j==nColumn-1 ){
13334       utf8_printf(p->out, "%s", rowSep);
13335       j = -1;
13336       if( seenInterrupt ) goto columnar_end;
13337     }else{
13338       utf8_printf(p->out, "%s", colSep);
13339     }
13340   }
13341   if( p->cMode==MODE_Table ){
13342     print_row_separator(p, nColumn, "+");
13343   }else if( p->cMode==MODE_Box ){
13344     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
13345   }
13346 columnar_end:
13347   if( seenInterrupt ){
13348     utf8_printf(p->out, "Interrupt\n");
13349   }
13350   nData = (nRow+1)*nColumn;
13351   for(i=0; i<nData; i++) free(azData[i]);
13352   sqlite3_free(azData);
13353 }
13354
13355 /*
13356 ** Run a prepared statement
13357 */
13358 static void exec_prepared_stmt(
13359   ShellState *pArg,                                /* Pointer to ShellState */
13360   sqlite3_stmt *pStmt                              /* Statment to run */
13361 ){
13362   int rc;
13363
13364   if( pArg->cMode==MODE_Column
13365    || pArg->cMode==MODE_Table
13366    || pArg->cMode==MODE_Box
13367    || pArg->cMode==MODE_Markdown
13368   ){
13369     exec_prepared_stmt_columnar(pArg, pStmt);
13370     return;
13371   }
13372
13373   /* perform the first step.  this will tell us if we
13374   ** have a result set or not and how wide it is.
13375   */
13376   rc = sqlite3_step(pStmt);
13377   /* if we have a result set... */
13378   if( SQLITE_ROW == rc ){
13379     /* allocate space for col name ptr, value ptr, and type */
13380     int nCol = sqlite3_column_count(pStmt);
13381     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
13382     if( !pData ){
13383       rc = SQLITE_NOMEM;
13384     }else{
13385       char **azCols = (char **)pData;      /* Names of result columns */
13386       char **azVals = &azCols[nCol];       /* Results */
13387       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
13388       int i, x;
13389       assert(sizeof(int) <= sizeof(char *));
13390       /* save off ptrs to column names */
13391       for(i=0; i<nCol; i++){
13392         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
13393       }
13394       do{
13395         /* extract the data and data types */
13396         for(i=0; i<nCol; i++){
13397           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
13398           if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
13399             azVals[i] = "";
13400           }else{
13401             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
13402           }
13403           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
13404             rc = SQLITE_NOMEM;
13405             break; /* from for */
13406           }
13407         } /* end for */
13408
13409         /* if data and types extracted successfully... */
13410         if( SQLITE_ROW == rc ){
13411           /* call the supplied callback with the result row data */
13412           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
13413             rc = SQLITE_ABORT;
13414           }else{
13415             rc = sqlite3_step(pStmt);
13416           }
13417         }
13418       } while( SQLITE_ROW == rc );
13419       sqlite3_free(pData);
13420       if( pArg->cMode==MODE_Json ){
13421         fputs("]\n", pArg->out);
13422       }
13423     }
13424   }
13425 }
13426
13427 #ifndef SQLITE_OMIT_VIRTUALTABLE
13428 /*
13429 ** This function is called to process SQL if the previous shell command
13430 ** was ".expert". It passes the SQL in the second argument directly to
13431 ** the sqlite3expert object.
13432 **
13433 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
13434 ** code. In this case, (*pzErr) may be set to point to a buffer containing
13435 ** an English language error message. It is the responsibility of the
13436 ** caller to eventually free this buffer using sqlite3_free().
13437 */
13438 static int expertHandleSQL(
13439   ShellState *pState, 
13440   const char *zSql, 
13441   char **pzErr
13442 ){
13443   assert( pState->expert.pExpert );
13444   assert( pzErr==0 || *pzErr==0 );
13445   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
13446 }
13447
13448 /*
13449 ** This function is called either to silently clean up the object
13450 ** created by the ".expert" command (if bCancel==1), or to generate a 
13451 ** report from it and then clean it up (if bCancel==0).
13452 **
13453 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
13454 ** code. In this case, (*pzErr) may be set to point to a buffer containing
13455 ** an English language error message. It is the responsibility of the
13456 ** caller to eventually free this buffer using sqlite3_free().
13457 */
13458 static int expertFinish(
13459   ShellState *pState,
13460   int bCancel,
13461   char **pzErr
13462 ){
13463   int rc = SQLITE_OK;
13464   sqlite3expert *p = pState->expert.pExpert;
13465   assert( p );
13466   assert( bCancel || pzErr==0 || *pzErr==0 );
13467   if( bCancel==0 ){
13468     FILE *out = pState->out;
13469     int bVerbose = pState->expert.bVerbose;
13470
13471     rc = sqlite3_expert_analyze(p, pzErr);
13472     if( rc==SQLITE_OK ){
13473       int nQuery = sqlite3_expert_count(p);
13474       int i;
13475
13476       if( bVerbose ){
13477         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
13478         raw_printf(out, "-- Candidates -----------------------------\n");
13479         raw_printf(out, "%s\n", zCand);
13480       }
13481       for(i=0; i<nQuery; i++){
13482         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
13483         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
13484         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
13485         if( zIdx==0 ) zIdx = "(no new indexes)\n";
13486         if( bVerbose ){
13487           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
13488           raw_printf(out, "%s\n\n", zSql);
13489         }
13490         raw_printf(out, "%s\n", zIdx);
13491         raw_printf(out, "%s\n", zEQP);
13492       }
13493     }
13494   }
13495   sqlite3_expert_destroy(p);
13496   pState->expert.pExpert = 0;
13497   return rc;
13498 }
13499
13500 /*
13501 ** Implementation of ".expert" dot command.
13502 */
13503 static int expertDotCommand(
13504   ShellState *pState,             /* Current shell tool state */
13505   char **azArg,                   /* Array of arguments passed to dot command */
13506   int nArg                        /* Number of entries in azArg[] */
13507 ){
13508   int rc = SQLITE_OK;
13509   char *zErr = 0;
13510   int i;
13511   int iSample = 0;
13512
13513   assert( pState->expert.pExpert==0 );
13514   memset(&pState->expert, 0, sizeof(ExpertInfo));
13515
13516   for(i=1; rc==SQLITE_OK && i<nArg; i++){
13517     char *z = azArg[i];
13518     int n;
13519     if( z[0]=='-' && z[1]=='-' ) z++;
13520     n = strlen30(z);
13521     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
13522       pState->expert.bVerbose = 1;
13523     }
13524     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
13525       if( i==(nArg-1) ){
13526         raw_printf(stderr, "option requires an argument: %s\n", z);
13527         rc = SQLITE_ERROR;
13528       }else{
13529         iSample = (int)integerValue(azArg[++i]);
13530         if( iSample<0 || iSample>100 ){
13531           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
13532           rc = SQLITE_ERROR;
13533         }
13534       }
13535     }
13536     else{
13537       raw_printf(stderr, "unknown option: %s\n", z);
13538       rc = SQLITE_ERROR;
13539     }
13540   }
13541
13542   if( rc==SQLITE_OK ){
13543     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
13544     if( pState->expert.pExpert==0 ){
13545       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
13546       rc = SQLITE_ERROR;
13547     }else{
13548       sqlite3_expert_config(
13549           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
13550       );
13551     }
13552   }
13553
13554   return rc;
13555 }
13556 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13557
13558 /*
13559 ** Execute a statement or set of statements.  Print
13560 ** any result rows/columns depending on the current mode
13561 ** set via the supplied callback.
13562 **
13563 ** This is very similar to SQLite's built-in sqlite3_exec()
13564 ** function except it takes a slightly different callback
13565 ** and callback data argument.
13566 */
13567 static int shell_exec(
13568   ShellState *pArg,                         /* Pointer to ShellState */
13569   const char *zSql,                         /* SQL to be evaluated */
13570   char **pzErrMsg                           /* Error msg written here */
13571 ){
13572   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
13573   int rc = SQLITE_OK;             /* Return Code */
13574   int rc2;
13575   const char *zLeftover;          /* Tail of unprocessed SQL */
13576   sqlite3 *db = pArg->db;
13577
13578   if( pzErrMsg ){
13579     *pzErrMsg = NULL;
13580   }
13581
13582 #ifndef SQLITE_OMIT_VIRTUALTABLE
13583   if( pArg->expert.pExpert ){
13584     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
13585     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
13586   }
13587 #endif
13588
13589   while( zSql[0] && (SQLITE_OK == rc) ){
13590     static const char *zStmtSql;
13591     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
13592     if( SQLITE_OK != rc ){
13593       if( pzErrMsg ){
13594         *pzErrMsg = save_err_msg(db);
13595       }
13596     }else{
13597       if( !pStmt ){
13598         /* this happens for a comment or white-space */
13599         zSql = zLeftover;
13600         while( IsSpace(zSql[0]) ) zSql++;
13601         continue;
13602       }
13603       zStmtSql = sqlite3_sql(pStmt);
13604       if( zStmtSql==0 ) zStmtSql = "";
13605       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
13606
13607       /* save off the prepared statment handle and reset row count */
13608       if( pArg ){
13609         pArg->pStmt = pStmt;
13610         pArg->cnt = 0;
13611       }
13612
13613       /* echo the sql statement if echo on */
13614       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
13615         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
13616       }
13617
13618       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
13619       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
13620         sqlite3_stmt *pExplain;
13621         char *zEQP;
13622         int triggerEQP = 0;
13623         disable_debug_trace_modes();
13624         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
13625         if( pArg->autoEQP>=AUTOEQP_trigger ){
13626           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
13627         }
13628         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
13629         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
13630         if( rc==SQLITE_OK ){
13631           while( sqlite3_step(pExplain)==SQLITE_ROW ){
13632             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
13633             int iEqpId = sqlite3_column_int(pExplain, 0);
13634             int iParentId = sqlite3_column_int(pExplain, 1);
13635             if( zEQPLine==0 ) zEQPLine = "";
13636             if( zEQPLine[0]=='-' ) eqp_render(pArg);
13637             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
13638           }
13639           eqp_render(pArg);
13640         }
13641         sqlite3_finalize(pExplain);
13642         sqlite3_free(zEQP);
13643         if( pArg->autoEQP>=AUTOEQP_full ){
13644           /* Also do an EXPLAIN for ".eqp full" mode */
13645           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
13646           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
13647           if( rc==SQLITE_OK ){
13648             pArg->cMode = MODE_Explain;
13649             explain_data_prepare(pArg, pExplain);
13650             exec_prepared_stmt(pArg, pExplain);
13651             explain_data_delete(pArg);
13652           }
13653           sqlite3_finalize(pExplain);
13654           sqlite3_free(zEQP);
13655         }
13656         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
13657           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
13658           /* Reprepare pStmt before reactiving trace modes */
13659           sqlite3_finalize(pStmt);
13660           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
13661           if( pArg ) pArg->pStmt = pStmt;
13662         }
13663         restore_debug_trace_modes();
13664       }
13665
13666       if( pArg ){
13667         pArg->cMode = pArg->mode;
13668         if( pArg->autoExplain ){
13669           if( sqlite3_stmt_isexplain(pStmt)==1 ){
13670             pArg->cMode = MODE_Explain;
13671           }
13672           if( sqlite3_stmt_isexplain(pStmt)==2 ){
13673             pArg->cMode = MODE_EQP;
13674           }
13675         }
13676
13677         /* If the shell is currently in ".explain" mode, gather the extra
13678         ** data required to add indents to the output.*/
13679         if( pArg->cMode==MODE_Explain ){
13680           explain_data_prepare(pArg, pStmt);
13681         }
13682       }
13683
13684       bind_prepared_stmt(pArg, pStmt);
13685       exec_prepared_stmt(pArg, pStmt);
13686       explain_data_delete(pArg);
13687       eqp_render(pArg);
13688
13689       /* print usage stats if stats on */
13690       if( pArg && pArg->statsOn ){
13691         display_stats(db, pArg, 0);
13692       }
13693
13694       /* print loop-counters if required */
13695       if( pArg && pArg->scanstatsOn ){
13696         display_scanstats(db, pArg);
13697       }
13698
13699       /* Finalize the statement just executed. If this fails, save a
13700       ** copy of the error message. Otherwise, set zSql to point to the
13701       ** next statement to execute. */
13702       rc2 = sqlite3_finalize(pStmt);
13703       if( rc!=SQLITE_NOMEM ) rc = rc2;
13704       if( rc==SQLITE_OK ){
13705         zSql = zLeftover;
13706         while( IsSpace(zSql[0]) ) zSql++;
13707       }else if( pzErrMsg ){
13708         *pzErrMsg = save_err_msg(db);
13709       }
13710
13711       /* clear saved stmt handle */
13712       if( pArg ){
13713         pArg->pStmt = NULL;
13714       }
13715     }
13716   } /* end while */
13717
13718   return rc;
13719 }
13720
13721 /*
13722 ** Release memory previously allocated by tableColumnList().
13723 */
13724 static void freeColumnList(char **azCol){
13725   int i;
13726   for(i=1; azCol[i]; i++){
13727     sqlite3_free(azCol[i]);
13728   }
13729   /* azCol[0] is a static string */
13730   sqlite3_free(azCol);
13731 }
13732
13733 /*
13734 ** Return a list of pointers to strings which are the names of all
13735 ** columns in table zTab.   The memory to hold the names is dynamically
13736 ** allocated and must be released by the caller using a subsequent call
13737 ** to freeColumnList().
13738 **
13739 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
13740 ** value that needs to be preserved, then azCol[0] is filled in with the
13741 ** name of the rowid column.
13742 **
13743 ** The first regular column in the table is azCol[1].  The list is terminated
13744 ** by an entry with azCol[i]==0.
13745 */
13746 static char **tableColumnList(ShellState *p, const char *zTab){
13747   char **azCol = 0;
13748   sqlite3_stmt *pStmt;
13749   char *zSql;
13750   int nCol = 0;
13751   int nAlloc = 0;
13752   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
13753   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
13754   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
13755   int rc;
13756
13757   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
13758   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13759   sqlite3_free(zSql);
13760   if( rc ) return 0;
13761   while( sqlite3_step(pStmt)==SQLITE_ROW ){
13762     if( nCol>=nAlloc-2 ){
13763       nAlloc = nAlloc*2 + nCol + 10;
13764       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
13765       if( azCol==0 ) shell_out_of_memory();
13766     }
13767     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
13768     if( sqlite3_column_int(pStmt, 5) ){
13769       nPK++;
13770       if( nPK==1
13771        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
13772                           "INTEGER")==0
13773       ){
13774         isIPK = 1;
13775       }else{
13776         isIPK = 0;
13777       }
13778     }
13779   }
13780   sqlite3_finalize(pStmt);
13781   if( azCol==0 ) return 0;
13782   azCol[0] = 0;
13783   azCol[nCol+1] = 0;
13784
13785   /* The decision of whether or not a rowid really needs to be preserved
13786   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
13787   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
13788   ** rowids on tables where the rowid is inaccessible because there are other
13789   ** columns in the table named "rowid", "_rowid_", and "oid".
13790   */
13791   if( preserveRowid && isIPK ){
13792     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
13793     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
13794     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
13795     ** ROWID aliases.  To distinguish these cases, check to see if
13796     ** there is a "pk" entry in "PRAGMA index_list".  There will be
13797     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
13798     */
13799     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
13800                            " WHERE origin='pk'", zTab);
13801     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13802     sqlite3_free(zSql);
13803     if( rc ){
13804       freeColumnList(azCol);
13805       return 0;
13806     }
13807     rc = sqlite3_step(pStmt);
13808     sqlite3_finalize(pStmt);
13809     preserveRowid = rc==SQLITE_ROW;
13810   }
13811   if( preserveRowid ){
13812     /* Only preserve the rowid if we can find a name to use for the
13813     ** rowid */
13814     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
13815     int i, j;
13816     for(j=0; j<3; j++){
13817       for(i=1; i<=nCol; i++){
13818         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
13819       }
13820       if( i>nCol ){
13821         /* At this point, we know that azRowid[j] is not the name of any
13822         ** ordinary column in the table.  Verify that azRowid[j] is a valid
13823         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
13824         ** tables will fail this last check */
13825         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
13826         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
13827         break;
13828       }
13829     }
13830   }
13831   return azCol;
13832 }
13833
13834 /*
13835 ** Toggle the reverse_unordered_selects setting.
13836 */
13837 static void toggleSelectOrder(sqlite3 *db){
13838   sqlite3_stmt *pStmt = 0;
13839   int iSetting = 0;
13840   char zStmt[100];
13841   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
13842   if( sqlite3_step(pStmt)==SQLITE_ROW ){
13843     iSetting = sqlite3_column_int(pStmt, 0);
13844   }
13845   sqlite3_finalize(pStmt);
13846   sqlite3_snprintf(sizeof(zStmt), zStmt,
13847        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
13848   sqlite3_exec(db, zStmt, 0, 0, 0);
13849 }
13850
13851 /*
13852 ** This is a different callback routine used for dumping the database.
13853 ** Each row received by this callback consists of a table name,
13854 ** the table type ("index" or "table") and SQL to create the table.
13855 ** This routine should print text sufficient to recreate the table.
13856 */
13857 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
13858   int rc;
13859   const char *zTable;
13860   const char *zType;
13861   const char *zSql;
13862   ShellState *p = (ShellState *)pArg;
13863   int dataOnly;
13864   int noSys;
13865
13866   UNUSED_PARAMETER(azNotUsed);
13867   if( nArg!=3 || azArg==0 ) return 0;
13868   zTable = azArg[0];
13869   zType = azArg[1];
13870   zSql = azArg[2];
13871   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
13872   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
13873
13874   if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
13875     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
13876   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
13877     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
13878   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
13879     return 0;
13880   }else if( dataOnly ){
13881     /* no-op */
13882   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
13883     char *zIns;
13884     if( !p->writableSchema ){
13885       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
13886       p->writableSchema = 1;
13887     }
13888     zIns = sqlite3_mprintf(
13889        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
13890        "VALUES('table','%q','%q',0,'%q');",
13891        zTable, zTable, zSql);
13892     utf8_printf(p->out, "%s\n", zIns);
13893     sqlite3_free(zIns);
13894     return 0;
13895   }else{
13896     printSchemaLine(p->out, zSql, ";\n");
13897   }
13898
13899   if( strcmp(zType, "table")==0 ){
13900     ShellText sSelect;
13901     ShellText sTable;
13902     char **azCol;
13903     int i;
13904     char *savedDestTable;
13905     int savedMode;
13906
13907     azCol = tableColumnList(p, zTable);
13908     if( azCol==0 ){
13909       p->nErr++;
13910       return 0;
13911     }
13912
13913     /* Always quote the table name, even if it appears to be pure ascii,
13914     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
13915     initText(&sTable);
13916     appendText(&sTable, zTable, quoteChar(zTable));
13917     /* If preserving the rowid, add a column list after the table name.
13918     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
13919     ** instead of the usual "INSERT INTO tab VALUES(...)".
13920     */
13921     if( azCol[0] ){
13922       appendText(&sTable, "(", 0);
13923       appendText(&sTable, azCol[0], 0);
13924       for(i=1; azCol[i]; i++){
13925         appendText(&sTable, ",", 0);
13926         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
13927       }
13928       appendText(&sTable, ")", 0);
13929     }
13930
13931     /* Build an appropriate SELECT statement */
13932     initText(&sSelect);
13933     appendText(&sSelect, "SELECT ", 0);
13934     if( azCol[0] ){
13935       appendText(&sSelect, azCol[0], 0);
13936       appendText(&sSelect, ",", 0);
13937     }
13938     for(i=1; azCol[i]; i++){
13939       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
13940       if( azCol[i+1] ){
13941         appendText(&sSelect, ",", 0);
13942       }
13943     }
13944     freeColumnList(azCol);
13945     appendText(&sSelect, " FROM ", 0);
13946     appendText(&sSelect, zTable, quoteChar(zTable));
13947
13948     savedDestTable = p->zDestTable;
13949     savedMode = p->mode;
13950     p->zDestTable = sTable.z;
13951     p->mode = p->cMode = MODE_Insert;
13952     rc = shell_exec(p, sSelect.z, 0);
13953     if( (rc&0xff)==SQLITE_CORRUPT ){
13954       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
13955       toggleSelectOrder(p->db);
13956       shell_exec(p, sSelect.z, 0);
13957       toggleSelectOrder(p->db);
13958     }
13959     p->zDestTable = savedDestTable;
13960     p->mode = savedMode;
13961     freeText(&sTable);
13962     freeText(&sSelect);
13963     if( rc ) p->nErr++;
13964   }
13965   return 0;
13966 }
13967
13968 /*
13969 ** Run zQuery.  Use dump_callback() as the callback routine so that
13970 ** the contents of the query are output as SQL statements.
13971 **
13972 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
13973 ** "ORDER BY rowid DESC" to the end.
13974 */
13975 static int run_schema_dump_query(
13976   ShellState *p,
13977   const char *zQuery
13978 ){
13979   int rc;
13980   char *zErr = 0;
13981   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
13982   if( rc==SQLITE_CORRUPT ){
13983     char *zQ2;
13984     int len = strlen30(zQuery);
13985     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
13986     if( zErr ){
13987       utf8_printf(p->out, "/****** %s ******/\n", zErr);
13988       sqlite3_free(zErr);
13989       zErr = 0;
13990     }
13991     zQ2 = malloc( len+100 );
13992     if( zQ2==0 ) return rc;
13993     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
13994     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
13995     if( rc ){
13996       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
13997     }else{
13998       rc = SQLITE_CORRUPT;
13999     }
14000     sqlite3_free(zErr);
14001     free(zQ2);
14002   }
14003   return rc;
14004 }
14005
14006 /*
14007 ** Text of help messages.
14008 **
14009 ** The help text for each individual command begins with a line that starts
14010 ** with ".".  Subsequent lines are supplimental information.
14011 **
14012 ** There must be two or more spaces between the end of the command and the
14013 ** start of the description of what that command does.
14014 */
14015 static const char *(azHelp[]) = {
14016 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
14017   ".archive ...             Manage SQL archives",
14018   "   Each command must have exactly one of the following options:",
14019   "     -c, --create               Create a new archive",
14020   "     -u, --update               Add or update files with changed mtime",
14021   "     -i, --insert               Like -u but always add even if unchanged",
14022   "     -t, --list                 List contents of archive",
14023   "     -x, --extract              Extract files from archive",
14024   "   Optional arguments:",
14025   "     -v, --verbose              Print each filename as it is processed",
14026   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
14027   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
14028   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
14029   "     -n, --dryrun               Show the SQL that would have occurred",
14030   "   Examples:",
14031   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
14032   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
14033   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
14034   "   See also:",
14035   "      http://sqlite.org/cli.html#sqlar_archive_support",
14036 #endif
14037 #ifndef SQLITE_OMIT_AUTHORIZATION
14038   ".auth ON|OFF             Show authorizer callbacks",
14039 #endif
14040   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
14041   "       --append            Use the appendvfs",
14042   "       --async             Write to FILE without journal and fsync()",
14043   ".bail on|off             Stop after hitting an error.  Default OFF",
14044   ".binary on|off           Turn binary output on or off.  Default OFF",
14045   ".cd DIRECTORY            Change the working directory to DIRECTORY",
14046   ".changes on|off          Show number of rows changed by SQL",
14047   ".check GLOB              Fail if output since .testcase does not match",
14048   ".clone NEWDB             Clone data into NEWDB from the existing database",
14049   ".databases               List names and files of attached databases",
14050   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
14051   ".dbinfo ?DB?             Show status information about the database",
14052   ".dump ?OBJECTS?          Render database content as SQL",
14053   "   Options:",
14054   "     --data-only            Output only INSERT statements",
14055   "     --newlines             Allow unescaped newline characters in output",
14056   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
14057   "     --preserve-rowids      Include ROWID values in the output",
14058   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
14059   "   Additional LIKE patterns can be given in subsequent arguments",
14060   ".echo on|off             Turn command echo on or off",
14061   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
14062   "   Other Modes:",
14063 #ifdef SQLITE_DEBUG
14064   "      test                  Show raw EXPLAIN QUERY PLAN output",
14065   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
14066 #endif
14067   "      trigger               Like \"full\" but also show trigger bytecode",
14068   ".excel                   Display the output of next command in spreadsheet",
14069   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
14070   ".exit ?CODE?             Exit this program with return-code CODE",
14071   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
14072   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
14073   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
14074   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
14075   "   --help                  Show CMD details",
14076   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
14077   ".headers on|off          Turn display of headers on or off",
14078   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
14079   ".import FILE TABLE       Import data from FILE into TABLE",
14080   "   Options:",
14081   "     --ascii               Use \\037 and \\036 as column and row separators",
14082   "     --csv                 Use , and \\n as column and row separators",
14083   "     --skip N              Skip the first N rows of input",
14084   "     -v                    \"Verbose\" - increase auxiliary output",
14085   "   Notes:",
14086   "     *  If TABLE does not exist, it is created.  The first row of input",
14087   "        determines the column names.",
14088   "     *  If neither --csv or --ascii are used, the input mode is derived",
14089   "        from the \".mode\" output mode",
14090   "     *  If FILE begins with \"|\" then it is a command that generates the",
14091   "        input text.",
14092 #ifndef SQLITE_OMIT_TEST_CONTROL
14093   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
14094 #endif
14095   ".indexes ?TABLE?         Show names of indexes",
14096   "                           If TABLE is specified, only show indexes for",
14097   "                           tables matching TABLE using the LIKE operator.",
14098 #ifdef SQLITE_ENABLE_IOTRACE
14099   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
14100 #endif
14101   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
14102   ".lint OPTIONS            Report potential schema issues.",
14103   "     Options:",
14104   "        fkey-indexes     Find missing foreign key indexes",
14105 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14106   ".load FILE ?ENTRY?       Load an extension library",
14107 #endif
14108   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
14109   ".mode MODE ?TABLE?       Set output mode",
14110   "   MODE is one of:",
14111   "     ascii     Columns/rows delimited by 0x1F and 0x1E",
14112   "     box       Tables using unicode box-drawing characters",
14113   "     csv       Comma-separated values",
14114   "     column    Output in columns.  (See .width)",
14115   "     html      HTML <table> code",
14116   "     insert    SQL insert statements for TABLE",
14117   "     json      Results in a JSON array",
14118   "     line      One value per line",
14119   "     list      Values delimited by \"|\"",
14120   "     markdown  Markdown table format",
14121   "     quote     Escape answers as for SQL",
14122   "     table     ASCII-art table",
14123   "     tabs      Tab-separated values",
14124   "     tcl       TCL list elements",
14125   ".nullvalue STRING        Use STRING in place of NULL values",
14126   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
14127   "     If FILE begins with '|' then open as a pipe",
14128   "       --bom  Put a UTF8 byte-order mark at the beginning",
14129   "       -e     Send output to the system text editor",
14130   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
14131 #ifdef SQLITE_DEBUG
14132   ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
14133 #endif 
14134   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
14135   "     Options:",
14136   "        --append        Use appendvfs to append database to the end of FILE",
14137 #ifdef SQLITE_ENABLE_DESERIALIZE
14138   "        --deserialize   Load into memory useing sqlite3_deserialize()",
14139   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
14140   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
14141 #endif
14142   "        --new           Initialize FILE to an empty database",
14143   "        --nofollow      Do not follow symbolic links",
14144   "        --readonly      Open FILE readonly",
14145   "        --zip           FILE is a ZIP archive",
14146   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
14147   "   If FILE begins with '|' then open it as a pipe.",
14148   "   Options:",
14149   "     --bom                 Prefix output with a UTF8 byte-order mark",
14150   "     -e                    Send output to the system text editor",
14151   "     -x                    Send output as CSV to a spreadsheet",
14152   ".parameter CMD ...       Manage SQL parameter bindings",
14153   "   clear                   Erase all bindings",
14154   "   init                    Initialize the TEMP table that holds bindings",
14155   "   list                    List the current parameter bindings",
14156   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
14157   "                           PARAMETER should start with one of: $ : @ ?",
14158   "   unset PARAMETER         Remove PARAMETER from the binding table",
14159   ".print STRING...         Print literal STRING",
14160 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
14161   ".progress N              Invoke progress handler after every N opcodes",
14162   "   --limit N                 Interrupt after N progress callbacks",
14163   "   --once                    Do no more than one progress interrupt",
14164   "   --quiet|-q                No output except at interrupts",
14165   "   --reset                   Reset the count for each input and interrupt",
14166 #endif
14167   ".prompt MAIN CONTINUE    Replace the standard prompts",
14168   ".quit                    Exit this program",
14169   ".read FILE               Read input from FILE",
14170 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
14171   ".recover                 Recover as much data as possible from corrupt db.",
14172   "   --freelist-corrupt       Assume the freelist is corrupt",
14173   "   --recovery-db NAME       Store recovery metadata in database file NAME",
14174   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
14175   "   --no-rowids              Do not attempt to recover rowid values",
14176   "                            that are not also INTEGER PRIMARY KEYs",
14177 #endif
14178   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
14179   ".save FILE               Write in-memory database into FILE",
14180   ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
14181   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
14182   "   Options:",
14183   "      --indent             Try to pretty-print the schema",
14184   "      --nosys              Omit objects whose names start with \"sqlite_\"",
14185   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
14186   "    Options:",
14187   "       --init               Create a new SELFTEST table",
14188   "       -v                   Verbose output",
14189   ".separator COL ?ROW?     Change the column and row separators",
14190 #if defined(SQLITE_ENABLE_SESSION)
14191   ".session ?NAME? CMD ...  Create or control sessions",
14192   "   Subcommands:",
14193   "     attach TABLE             Attach TABLE",
14194   "     changeset FILE           Write a changeset into FILE",
14195   "     close                    Close one session",
14196   "     enable ?BOOLEAN?         Set or query the enable bit",
14197   "     filter GLOB...           Reject tables matching GLOBs",
14198   "     indirect ?BOOLEAN?       Mark or query the indirect status",
14199   "     isempty                  Query whether the session is empty",
14200   "     list                     List currently open session names",
14201   "     open DB NAME             Open a new session on DB",
14202   "     patchset FILE            Write a patchset into FILE",
14203   "   If ?NAME? is omitted, the first defined session is used.",
14204 #endif
14205   ".sha3sum ...             Compute a SHA3 hash of database content",
14206   "    Options:",
14207   "      --schema              Also hash the sqlite_schema table",
14208   "      --sha3-224            Use the sha3-224 algorithm",
14209   "      --sha3-256            Use the sha3-256 algorithm (default)",
14210   "      --sha3-384            Use the sha3-384 algorithm",
14211   "      --sha3-512            Use the sha3-512 algorithm",
14212   "    Any other argument is a LIKE pattern for tables to hash",
14213 #ifndef SQLITE_NOHAVE_SYSTEM
14214   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
14215 #endif
14216   ".show                    Show the current values for various settings",
14217   ".stats ?ARG?             Show stats or turn stats on or off",
14218   "   off                      Turn off automatic stat display",
14219   "   on                       Turn on automatic stat display",
14220   "   stmt                     Show statement stats",
14221   "   vmstep                   Show the virtual machine step count only",
14222 #ifndef SQLITE_NOHAVE_SYSTEM
14223   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
14224 #endif
14225   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
14226   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
14227   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
14228   "                           Run \".testctrl\" with no arguments for details",
14229   ".timeout MS              Try opening locked tables for MS milliseconds",
14230   ".timer on|off            Turn SQL timer on or off",
14231 #ifndef SQLITE_OMIT_TRACE
14232   ".trace ?OPTIONS?         Output each SQL statement as it is run",
14233   "    FILE                    Send output to FILE",
14234   "    stdout                  Send output to stdout",
14235   "    stderr                  Send output to stderr",
14236   "    off                     Disable tracing",
14237   "    --expanded              Expand query parameters",
14238 #ifdef SQLITE_ENABLE_NORMALIZE
14239   "    --normalized            Normal the SQL statements",
14240 #endif
14241   "    --plain                 Show SQL as it is input",
14242   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
14243   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
14244   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
14245   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
14246 #endif /* SQLITE_OMIT_TRACE */
14247 #ifdef SQLITE_DEBUG
14248   ".unmodule NAME ...       Unregister virtual table modules",
14249   "    --allexcept             Unregister everything except those named",
14250 #endif
14251   ".vfsinfo ?AUX?           Information about the top-level VFS",
14252   ".vfslist                 List all available VFSes",
14253   ".vfsname ?AUX?           Print the name of the VFS stack",
14254   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
14255   "     Negative values right-justify",
14256 };
14257
14258 /*
14259 ** Output help text.
14260 **
14261 ** zPattern describes the set of commands for which help text is provided.
14262 ** If zPattern is NULL, then show all commands, but only give a one-line
14263 ** description of each.
14264 **
14265 ** Return the number of matches.
14266 */
14267 static int showHelp(FILE *out, const char *zPattern){
14268   int i = 0;
14269   int j = 0;
14270   int n = 0;
14271   char *zPat;
14272   if( zPattern==0
14273    || zPattern[0]=='0'
14274    || strcmp(zPattern,"-a")==0
14275    || strcmp(zPattern,"-all")==0
14276    || strcmp(zPattern,"--all")==0
14277   ){
14278     /* Show all commands, but only one line per command */
14279     if( zPattern==0 ) zPattern = "";
14280     for(i=0; i<ArraySize(azHelp); i++){
14281       if( azHelp[i][0]=='.' || zPattern[0] ){
14282         utf8_printf(out, "%s\n", azHelp[i]);
14283         n++;
14284       }
14285     }
14286   }else{
14287     /* Look for commands that for which zPattern is an exact prefix */
14288     zPat = sqlite3_mprintf(".%s*", zPattern);
14289     for(i=0; i<ArraySize(azHelp); i++){
14290       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
14291         utf8_printf(out, "%s\n", azHelp[i]);
14292         j = i+1;
14293         n++;
14294       }
14295     }
14296     sqlite3_free(zPat);
14297     if( n ){
14298       if( n==1 ){
14299         /* when zPattern is a prefix of exactly one command, then include the
14300         ** details of that command, which should begin at offset j */
14301         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
14302           utf8_printf(out, "%s\n", azHelp[j]);
14303           j++;
14304         }
14305       }
14306       return n;
14307     }
14308     /* Look for commands that contain zPattern anywhere.  Show the complete
14309     ** text of all commands that match. */
14310     zPat = sqlite3_mprintf("%%%s%%", zPattern);
14311     for(i=0; i<ArraySize(azHelp); i++){
14312       if( azHelp[i][0]=='.' ) j = i;
14313       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
14314         utf8_printf(out, "%s\n", azHelp[j]);
14315         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
14316           j++;
14317           utf8_printf(out, "%s\n", azHelp[j]);
14318         }
14319         i = j;
14320         n++;
14321       }
14322     }
14323     sqlite3_free(zPat);
14324   }
14325   return n;
14326 }
14327
14328 /* Forward reference */
14329 static int process_input(ShellState *p);
14330
14331 /*
14332 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
14333 ** and return a pointer to the buffer. The caller is responsible for freeing
14334 ** the memory.
14335 **
14336 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
14337 ** read.
14338 **
14339 ** For convenience, a nul-terminator byte is always appended to the data read
14340 ** from the file before the buffer is returned. This byte is not included in
14341 ** the final value of (*pnByte), if applicable.
14342 **
14343 ** NULL is returned if any error is encountered. The final value of *pnByte
14344 ** is undefined in this case.
14345 */
14346 static char *readFile(const char *zName, int *pnByte){
14347   FILE *in = fopen(zName, "rb");
14348   long nIn;
14349   size_t nRead;
14350   char *pBuf;
14351   if( in==0 ) return 0;
14352   fseek(in, 0, SEEK_END);
14353   nIn = ftell(in);
14354   rewind(in);
14355   pBuf = sqlite3_malloc64( nIn+1 );
14356   if( pBuf==0 ){ fclose(in); return 0; }
14357   nRead = fread(pBuf, nIn, 1, in);
14358   fclose(in);
14359   if( nRead!=1 ){
14360     sqlite3_free(pBuf);
14361     return 0;
14362   }
14363   pBuf[nIn] = 0;
14364   if( pnByte ) *pnByte = nIn;
14365   return pBuf;
14366 }
14367
14368 #if defined(SQLITE_ENABLE_SESSION)
14369 /*
14370 ** Close a single OpenSession object and release all of its associated
14371 ** resources.
14372 */
14373 static void session_close(OpenSession *pSession){
14374   int i;
14375   sqlite3session_delete(pSession->p);
14376   sqlite3_free(pSession->zName);
14377   for(i=0; i<pSession->nFilter; i++){
14378     sqlite3_free(pSession->azFilter[i]);
14379   }
14380   sqlite3_free(pSession->azFilter);
14381   memset(pSession, 0, sizeof(OpenSession));
14382 }
14383 #endif
14384
14385 /*
14386 ** Close all OpenSession objects and release all associated resources.
14387 */
14388 #if defined(SQLITE_ENABLE_SESSION)
14389 static void session_close_all(ShellState *p){
14390   int i;
14391   for(i=0; i<p->nSession; i++){
14392     session_close(&p->aSession[i]);
14393   }
14394   p->nSession = 0;
14395 }
14396 #else
14397 # define session_close_all(X)
14398 #endif
14399
14400 /*
14401 ** Implementation of the xFilter function for an open session.  Omit
14402 ** any tables named by ".session filter" but let all other table through.
14403 */
14404 #if defined(SQLITE_ENABLE_SESSION)
14405 static int session_filter(void *pCtx, const char *zTab){
14406   OpenSession *pSession = (OpenSession*)pCtx;
14407   int i;
14408   for(i=0; i<pSession->nFilter; i++){
14409     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
14410   }
14411   return 1;
14412 }
14413 #endif
14414
14415 /*
14416 ** Try to deduce the type of file for zName based on its content.  Return
14417 ** one of the SHELL_OPEN_* constants.
14418 **
14419 ** If the file does not exist or is empty but its name looks like a ZIP
14420 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
14421 ** Otherwise, assume an ordinary database regardless of the filename if
14422 ** the type cannot be determined from content.
14423 */
14424 int deduceDatabaseType(const char *zName, int dfltZip){
14425   FILE *f = fopen(zName, "rb");
14426   size_t n;
14427   int rc = SHELL_OPEN_UNSPEC;
14428   char zBuf[100];
14429   if( f==0 ){
14430     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
14431        return SHELL_OPEN_ZIPFILE;
14432     }else{
14433        return SHELL_OPEN_NORMAL;
14434     }
14435   }
14436   n = fread(zBuf, 16, 1, f);
14437   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
14438     fclose(f);
14439     return SHELL_OPEN_NORMAL;
14440   }
14441   fseek(f, -25, SEEK_END);
14442   n = fread(zBuf, 25, 1, f);
14443   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
14444     rc = SHELL_OPEN_APPENDVFS;
14445   }else{
14446     fseek(f, -22, SEEK_END);
14447     n = fread(zBuf, 22, 1, f);
14448     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
14449        && zBuf[3]==0x06 ){
14450       rc = SHELL_OPEN_ZIPFILE;
14451     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
14452       rc = SHELL_OPEN_ZIPFILE;
14453     }
14454   }
14455   fclose(f);
14456   return rc;  
14457 }
14458
14459 #ifdef SQLITE_ENABLE_DESERIALIZE
14460 /*
14461 ** Reconstruct an in-memory database using the output from the "dbtotxt"
14462 ** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
14463 ** is 0, then read from standard input.
14464 */
14465 static unsigned char *readHexDb(ShellState *p, int *pnData){
14466   unsigned char *a = 0;
14467   int nLine;
14468   int n = 0;
14469   int pgsz = 0;
14470   int iOffset = 0;
14471   int j, k;
14472   int rc;
14473   FILE *in;
14474   unsigned int x[16];
14475   char zLine[1000];
14476   if( p->zDbFilename ){
14477     in = fopen(p->zDbFilename, "r");
14478     if( in==0 ){
14479       utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
14480       return 0;
14481     }
14482     nLine = 0;
14483   }else{
14484     in = p->in;
14485     nLine = p->lineno;
14486     if( in==0 ) in = stdin;
14487   }
14488   *pnData = 0;
14489   nLine++;
14490   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
14491   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
14492   if( rc!=2 ) goto readHexDb_error;
14493   if( n<0 ) goto readHexDb_error;
14494   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
14495   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
14496   a = sqlite3_malloc( n ? n : 1 );
14497   if( a==0 ){
14498     utf8_printf(stderr, "Out of memory!\n");
14499     goto readHexDb_error;
14500   }
14501   memset(a, 0, n);
14502   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
14503     utf8_printf(stderr, "invalid pagesize\n");
14504     goto readHexDb_error;
14505   }
14506   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
14507     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
14508     if( rc==2 ){
14509       iOffset = k;
14510       continue;
14511     }
14512     if( strncmp(zLine, "| end ", 6)==0 ){
14513       break;
14514     }
14515     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
14516                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
14517                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
14518     if( rc==17 ){
14519       k = iOffset+j;
14520       if( k+16<=n ){
14521         int ii;
14522         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
14523       }
14524     }
14525   }
14526   *pnData = n;
14527   if( in!=p->in ){
14528     fclose(in);
14529   }else{
14530     p->lineno = nLine;
14531   }
14532   return a;
14533
14534 readHexDb_error:
14535   if( in!=p->in ){
14536     fclose(in);
14537   }else{
14538     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
14539       nLine++;
14540       if(strncmp(zLine, "| end ", 6)==0 ) break;
14541     }
14542     p->lineno = nLine;
14543   }
14544   sqlite3_free(a);
14545   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
14546   return 0;
14547 }
14548 #endif /* SQLITE_ENABLE_DESERIALIZE */
14549
14550 /*
14551 ** Scalar function "shell_int32". The first argument to this function
14552 ** must be a blob. The second a non-negative integer. This function
14553 ** reads and returns a 32-bit big-endian integer from byte
14554 ** offset (4*<arg2>) of the blob.
14555 */
14556 static void shellInt32(
14557   sqlite3_context *context, 
14558   int argc, 
14559   sqlite3_value **argv
14560 ){
14561   const unsigned char *pBlob;
14562   int nBlob;
14563   int iInt;
14564
14565   UNUSED_PARAMETER(argc);
14566   nBlob = sqlite3_value_bytes(argv[0]);
14567   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
14568   iInt = sqlite3_value_int(argv[1]);
14569
14570   if( iInt>=0 && (iInt+1)*4<=nBlob ){
14571     const unsigned char *a = &pBlob[iInt*4];
14572     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
14573                        + ((sqlite3_int64)a[1]<<16)
14574                        + ((sqlite3_int64)a[2]<< 8)
14575                        + ((sqlite3_int64)a[3]<< 0);
14576     sqlite3_result_int64(context, iVal);
14577   }
14578 }
14579
14580 /*
14581 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
14582 ** using "..." with internal double-quote characters doubled.
14583 */
14584 static void shellIdQuote(
14585   sqlite3_context *context, 
14586   int argc, 
14587   sqlite3_value **argv
14588 ){
14589   const char *zName = (const char*)sqlite3_value_text(argv[0]);
14590   UNUSED_PARAMETER(argc);
14591   if( zName ){
14592     char *z = sqlite3_mprintf("\"%w\"", zName);
14593     sqlite3_result_text(context, z, -1, sqlite3_free);
14594   }
14595 }
14596
14597 /*
14598 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
14599 */
14600 static void shellUSleepFunc(
14601   sqlite3_context *context, 
14602   int argcUnused, 
14603   sqlite3_value **argv
14604 ){
14605   int sleep = sqlite3_value_int(argv[0]);
14606   (void)argcUnused;
14607   sqlite3_sleep(sleep/1000);
14608   sqlite3_result_int(context, sleep);
14609 }
14610
14611 /*
14612 ** Scalar function "shell_escape_crnl" used by the .recover command.
14613 ** The argument passed to this function is the output of built-in
14614 ** function quote(). If the first character of the input is "'", 
14615 ** indicating that the value passed to quote() was a text value,
14616 ** then this function searches the input for "\n" and "\r" characters
14617 ** and adds a wrapper similar to the following:
14618 **
14619 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
14620 **
14621 ** Or, if the first character of the input is not "'", then a copy
14622 ** of the input is returned.
14623 */
14624 static void shellEscapeCrnl(
14625   sqlite3_context *context, 
14626   int argc, 
14627   sqlite3_value **argv
14628 ){
14629   const char *zText = (const char*)sqlite3_value_text(argv[0]);
14630   UNUSED_PARAMETER(argc);
14631   if( zText[0]=='\'' ){
14632     int nText = sqlite3_value_bytes(argv[0]);
14633     int i;
14634     char zBuf1[20];
14635     char zBuf2[20];
14636     const char *zNL = 0;
14637     const char *zCR = 0;
14638     int nCR = 0;
14639     int nNL = 0;
14640
14641     for(i=0; zText[i]; i++){
14642       if( zNL==0 && zText[i]=='\n' ){
14643         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
14644         nNL = (int)strlen(zNL);
14645       }
14646       if( zCR==0 && zText[i]=='\r' ){
14647         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
14648         nCR = (int)strlen(zCR);
14649       }
14650     }
14651
14652     if( zNL || zCR ){
14653       int iOut = 0;
14654       i64 nMax = (nNL > nCR) ? nNL : nCR;
14655       i64 nAlloc = nMax * nText + (nMax+64)*2;
14656       char *zOut = (char*)sqlite3_malloc64(nAlloc);
14657       if( zOut==0 ){
14658         sqlite3_result_error_nomem(context);
14659         return;
14660       }
14661
14662       if( zNL && zCR ){
14663         memcpy(&zOut[iOut], "replace(replace(", 16);
14664         iOut += 16;
14665       }else{
14666         memcpy(&zOut[iOut], "replace(", 8);
14667         iOut += 8;
14668       }
14669       for(i=0; zText[i]; i++){
14670         if( zText[i]=='\n' ){
14671           memcpy(&zOut[iOut], zNL, nNL);
14672           iOut += nNL;
14673         }else if( zText[i]=='\r' ){
14674           memcpy(&zOut[iOut], zCR, nCR);
14675           iOut += nCR;
14676         }else{
14677           zOut[iOut] = zText[i];
14678           iOut++;
14679         }
14680       }
14681
14682       if( zNL ){
14683         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14684         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
14685         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
14686       }
14687       if( zCR ){
14688         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14689         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
14690         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
14691       }
14692
14693       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
14694       sqlite3_free(zOut);
14695       return;
14696     }
14697   }
14698
14699   sqlite3_result_value(context, argv[0]);
14700 }
14701
14702 /* Flags for open_db().
14703 **
14704 ** The default behavior of open_db() is to exit(1) if the database fails to
14705 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
14706 ** but still returns without calling exit.
14707 **
14708 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
14709 ** ZIP archive if the file does not exist or is empty and its name matches
14710 ** the *.zip pattern.
14711 */
14712 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
14713 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
14714
14715 /*
14716 ** Make sure the database is open.  If it is not, then open it.  If
14717 ** the database fails to open, print an error message and exit.
14718 */
14719 static void open_db(ShellState *p, int openFlags){
14720   if( p->db==0 ){
14721     if( p->openMode==SHELL_OPEN_UNSPEC ){
14722       if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
14723         p->openMode = SHELL_OPEN_NORMAL;
14724       }else{
14725         p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 
14726                              (openFlags & OPEN_DB_ZIPFILE)!=0);
14727       }
14728     }
14729     switch( p->openMode ){
14730       case SHELL_OPEN_APPENDVFS: {
14731         sqlite3_open_v2(p->zDbFilename, &p->db, 
14732            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
14733         break;
14734       }
14735       case SHELL_OPEN_HEXDB:
14736       case SHELL_OPEN_DESERIALIZE: {
14737         sqlite3_open(0, &p->db);
14738         break;
14739       }
14740       case SHELL_OPEN_ZIPFILE: {
14741         sqlite3_open(":memory:", &p->db);
14742         break;
14743       }
14744       case SHELL_OPEN_READONLY: {
14745         sqlite3_open_v2(p->zDbFilename, &p->db,
14746             SQLITE_OPEN_READONLY|p->openFlags, 0);
14747         break;
14748       }
14749       case SHELL_OPEN_UNSPEC:
14750       case SHELL_OPEN_NORMAL: {
14751         sqlite3_open_v2(p->zDbFilename, &p->db,
14752            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
14753         break;
14754       }
14755     }
14756     globalDb = p->db;
14757     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
14758       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
14759           p->zDbFilename, sqlite3_errmsg(p->db));
14760       if( openFlags & OPEN_DB_KEEPALIVE ){
14761         sqlite3_open(":memory:", &p->db);
14762         return;
14763       }
14764       exit(1);
14765     }
14766 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14767     sqlite3_enable_load_extension(p->db, 1);
14768 #endif
14769     sqlite3_fileio_init(p->db, 0, 0);
14770     sqlite3_shathree_init(p->db, 0, 0);
14771     sqlite3_completion_init(p->db, 0, 0);
14772     sqlite3_uint_init(p->db, 0, 0);
14773     sqlite3_decimal_init(p->db, 0, 0);
14774     sqlite3_ieee_init(p->db, 0, 0);
14775     sqlite3_series_init(p->db, 0, 0);
14776 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
14777     sqlite3_dbdata_init(p->db, 0, 0);
14778 #endif
14779 #ifdef SQLITE_HAVE_ZLIB
14780     sqlite3_zipfile_init(p->db, 0, 0);
14781     sqlite3_sqlar_init(p->db, 0, 0);
14782 #endif
14783     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
14784                             shellAddSchemaName, 0, 0);
14785     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
14786                             shellModuleSchema, 0, 0);
14787     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
14788                             shellPutsFunc, 0, 0);
14789     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
14790                             shellEscapeCrnl, 0, 0);
14791     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
14792                             shellInt32, 0, 0);
14793     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
14794                             shellIdQuote, 0, 0);
14795     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
14796                             shellUSleepFunc, 0, 0);
14797 #ifndef SQLITE_NOHAVE_SYSTEM
14798     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
14799                             editFunc, 0, 0);
14800     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
14801                             editFunc, 0, 0);
14802 #endif
14803     if( p->openMode==SHELL_OPEN_ZIPFILE ){
14804       char *zSql = sqlite3_mprintf(
14805          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
14806       sqlite3_exec(p->db, zSql, 0, 0, 0);
14807       sqlite3_free(zSql);
14808     }
14809 #ifdef SQLITE_ENABLE_DESERIALIZE
14810     else
14811     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
14812       int rc;
14813       int nData = 0;
14814       unsigned char *aData;
14815       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
14816         aData = (unsigned char*)readFile(p->zDbFilename, &nData);
14817       }else{
14818         aData = readHexDb(p, &nData);
14819         if( aData==0 ){
14820           return;
14821         }
14822       }
14823       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
14824                    SQLITE_DESERIALIZE_RESIZEABLE |
14825                    SQLITE_DESERIALIZE_FREEONCLOSE);
14826       if( rc ){
14827         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
14828       }
14829       if( p->szMax>0 ){
14830         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
14831       }
14832     }
14833 #endif
14834   }
14835 }
14836
14837 /*
14838 ** Attempt to close the databaes connection.  Report errors.
14839 */
14840 void close_db(sqlite3 *db){
14841   int rc = sqlite3_close(db);
14842   if( rc ){
14843     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
14844         rc, sqlite3_errmsg(db));
14845   } 
14846 }
14847
14848 #if HAVE_READLINE || HAVE_EDITLINE
14849 /*
14850 ** Readline completion callbacks
14851 */
14852 static char *readline_completion_generator(const char *text, int state){
14853   static sqlite3_stmt *pStmt = 0;
14854   char *zRet;
14855   if( state==0 ){
14856     char *zSql;
14857     sqlite3_finalize(pStmt);
14858     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
14859                            "  FROM completion(%Q) ORDER BY 1", text);
14860     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
14861     sqlite3_free(zSql);
14862   }
14863   if( sqlite3_step(pStmt)==SQLITE_ROW ){
14864     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
14865   }else{
14866     sqlite3_finalize(pStmt);
14867     pStmt = 0;
14868     zRet = 0;
14869   }
14870   return zRet;
14871 }
14872 static char **readline_completion(const char *zText, int iStart, int iEnd){
14873   rl_attempted_completion_over = 1;
14874   return rl_completion_matches(zText, readline_completion_generator);
14875 }
14876
14877 #elif HAVE_LINENOISE
14878 /*
14879 ** Linenoise completion callback
14880 */
14881 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
14882   int nLine = strlen30(zLine);
14883   int i, iStart;
14884   sqlite3_stmt *pStmt = 0;
14885   char *zSql;
14886   char zBuf[1000];
14887
14888   if( nLine>sizeof(zBuf)-30 ) return;
14889   if( zLine[0]=='.' || zLine[0]=='#') return;
14890   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
14891   if( i==nLine-1 ) return;
14892   iStart = i+1;
14893   memcpy(zBuf, zLine, iStart);
14894   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
14895                          "  FROM completion(%Q,%Q) ORDER BY 1",
14896                          &zLine[iStart], zLine);
14897   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
14898   sqlite3_free(zSql);
14899   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
14900   while( sqlite3_step(pStmt)==SQLITE_ROW ){
14901     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
14902     int nCompletion = sqlite3_column_bytes(pStmt, 0);
14903     if( iStart+nCompletion < sizeof(zBuf)-1 ){
14904       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
14905       linenoiseAddCompletion(lc, zBuf);
14906     }
14907   }
14908   sqlite3_finalize(pStmt);
14909 }
14910 #endif
14911
14912 /*
14913 ** Do C-language style dequoting.
14914 **
14915 **    \a    -> alarm
14916 **    \b    -> backspace
14917 **    \t    -> tab
14918 **    \n    -> newline
14919 **    \v    -> vertical tab
14920 **    \f    -> form feed
14921 **    \r    -> carriage return
14922 **    \s    -> space
14923 **    \"    -> "
14924 **    \'    -> '
14925 **    \\    -> backslash
14926 **    \NNN  -> ascii character NNN in octal
14927 */
14928 static void resolve_backslashes(char *z){
14929   int i, j;
14930   char c;
14931   while( *z && *z!='\\' ) z++;
14932   for(i=j=0; (c = z[i])!=0; i++, j++){
14933     if( c=='\\' && z[i+1]!=0 ){
14934       c = z[++i];
14935       if( c=='a' ){
14936         c = '\a';
14937       }else if( c=='b' ){
14938         c = '\b';
14939       }else if( c=='t' ){
14940         c = '\t';
14941       }else if( c=='n' ){
14942         c = '\n';
14943       }else if( c=='v' ){
14944         c = '\v';
14945       }else if( c=='f' ){
14946         c = '\f';
14947       }else if( c=='r' ){
14948         c = '\r';
14949       }else if( c=='"' ){
14950         c = '"';
14951       }else if( c=='\'' ){
14952         c = '\'';
14953       }else if( c=='\\' ){
14954         c = '\\';
14955       }else if( c>='0' && c<='7' ){
14956         c -= '0';
14957         if( z[i+1]>='0' && z[i+1]<='7' ){
14958           i++;
14959           c = (c<<3) + z[i] - '0';
14960           if( z[i+1]>='0' && z[i+1]<='7' ){
14961             i++;
14962             c = (c<<3) + z[i] - '0';
14963           }
14964         }
14965       }
14966     }
14967     z[j] = c;
14968   }
14969   if( j<i ) z[j] = 0;
14970 }
14971
14972 /*
14973 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
14974 ** for TRUE and FALSE.  Return the integer value if appropriate.
14975 */
14976 static int booleanValue(const char *zArg){
14977   int i;
14978   if( zArg[0]=='0' && zArg[1]=='x' ){
14979     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
14980   }else{
14981     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
14982   }
14983   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
14984   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
14985     return 1;
14986   }
14987   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
14988     return 0;
14989   }
14990   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
14991           zArg);
14992   return 0;
14993 }
14994
14995 /*
14996 ** Set or clear a shell flag according to a boolean value.
14997 */
14998 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
14999   if( booleanValue(zArg) ){
15000     ShellSetFlag(p, mFlag);
15001   }else{
15002     ShellClearFlag(p, mFlag);
15003   }
15004 }
15005
15006 /*
15007 ** Close an output file, assuming it is not stderr or stdout
15008 */
15009 static void output_file_close(FILE *f){
15010   if( f && f!=stdout && f!=stderr ) fclose(f);
15011 }
15012
15013 /*
15014 ** Try to open an output file.   The names "stdout" and "stderr" are
15015 ** recognized and do the right thing.  NULL is returned if the output
15016 ** filename is "off".
15017 */
15018 static FILE *output_file_open(const char *zFile, int bTextMode){
15019   FILE *f;
15020   if( strcmp(zFile,"stdout")==0 ){
15021     f = stdout;
15022   }else if( strcmp(zFile, "stderr")==0 ){
15023     f = stderr;
15024   }else if( strcmp(zFile, "off")==0 ){
15025     f = 0;
15026   }else{
15027     f = fopen(zFile, bTextMode ? "w" : "wb");
15028     if( f==0 ){
15029       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
15030     }
15031   }
15032   return f;
15033 }
15034
15035 #ifndef SQLITE_OMIT_TRACE
15036 /*
15037 ** A routine for handling output from sqlite3_trace().
15038 */
15039 static int sql_trace_callback(
15040   unsigned mType,         /* The trace type */
15041   void *pArg,             /* The ShellState pointer */
15042   void *pP,               /* Usually a pointer to sqlite_stmt */
15043   void *pX                /* Auxiliary output */
15044 ){
15045   ShellState *p = (ShellState*)pArg;
15046   sqlite3_stmt *pStmt;
15047   const char *zSql;
15048   int nSql;
15049   if( p->traceOut==0 ) return 0;
15050   if( mType==SQLITE_TRACE_CLOSE ){
15051     utf8_printf(p->traceOut, "-- closing database connection\n");
15052     return 0;
15053   }
15054   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
15055     zSql = (const char*)pX;
15056   }else{
15057     pStmt = (sqlite3_stmt*)pP;
15058     switch( p->eTraceType ){
15059       case SHELL_TRACE_EXPANDED: {
15060         zSql = sqlite3_expanded_sql(pStmt);
15061         break;
15062       }
15063 #ifdef SQLITE_ENABLE_NORMALIZE
15064       case SHELL_TRACE_NORMALIZED: {
15065         zSql = sqlite3_normalized_sql(pStmt);
15066         break;
15067       }
15068 #endif
15069       default: {
15070         zSql = sqlite3_sql(pStmt);
15071         break;
15072       }
15073     }
15074   }
15075   if( zSql==0 ) return 0;
15076   nSql = strlen30(zSql);
15077   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
15078   switch( mType ){
15079     case SQLITE_TRACE_ROW:
15080     case SQLITE_TRACE_STMT: {
15081       utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
15082       break;
15083     }
15084     case SQLITE_TRACE_PROFILE: {
15085       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
15086       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
15087       break;
15088     }
15089   }
15090   return 0;
15091 }
15092 #endif
15093
15094 /*
15095 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
15096 ** a useful spot to set a debugger breakpoint.
15097 */
15098 static void test_breakpoint(void){
15099   static int nCall = 0;
15100   nCall++;
15101 }
15102
15103 /*
15104 ** An object used to read a CSV and other files for import.
15105 */
15106 typedef struct ImportCtx ImportCtx;
15107 struct ImportCtx {
15108   const char *zFile;  /* Name of the input file */
15109   FILE *in;           /* Read the CSV text from this input stream */
15110   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
15111   char *z;            /* Accumulated text for a field */
15112   int n;              /* Number of bytes in z */
15113   int nAlloc;         /* Space allocated for z[] */
15114   int nLine;          /* Current line number */
15115   int nRow;           /* Number of rows imported */
15116   int nErr;           /* Number of errors encountered */
15117   int bNotFirst;      /* True if one or more bytes already read */
15118   int cTerm;          /* Character that terminated the most recent field */
15119   int cColSep;        /* The column separator character.  (Usually ",") */
15120   int cRowSep;        /* The row separator character.  (Usually "\n") */
15121 };
15122
15123 /* Clean up resourced used by an ImportCtx */
15124 static void import_cleanup(ImportCtx *p){
15125   if( p->in!=0 && p->xCloser!=0 ){
15126     p->xCloser(p->in);
15127     p->in = 0;
15128   }
15129   sqlite3_free(p->z);
15130   p->z = 0;
15131 }
15132
15133 /* Append a single byte to z[] */
15134 static void import_append_char(ImportCtx *p, int c){
15135   if( p->n+1>=p->nAlloc ){
15136     p->nAlloc += p->nAlloc + 100;
15137     p->z = sqlite3_realloc64(p->z, p->nAlloc);
15138     if( p->z==0 ) shell_out_of_memory();
15139   }
15140   p->z[p->n++] = (char)c;
15141 }
15142
15143 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
15144 ** with the option of having a separator other than ",".
15145 **
15146 **   +  Input comes from p->in.
15147 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
15148 **      from sqlite3_malloc64().
15149 **   +  Use p->cSep as the column separator.  The default is ",".
15150 **   +  Use p->rSep as the row separator.  The default is "\n".
15151 **   +  Keep track of the line number in p->nLine.
15152 **   +  Store the character that terminates the field in p->cTerm.  Store
15153 **      EOF on end-of-file.
15154 **   +  Report syntax errors on stderr
15155 */
15156 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
15157   int c;
15158   int cSep = p->cColSep;
15159   int rSep = p->cRowSep;
15160   p->n = 0;
15161   c = fgetc(p->in);
15162   if( c==EOF || seenInterrupt ){
15163     p->cTerm = EOF;
15164     return 0;
15165   }
15166   if( c=='"' ){
15167     int pc, ppc;
15168     int startLine = p->nLine;
15169     int cQuote = c;
15170     pc = ppc = 0;
15171     while( 1 ){
15172       c = fgetc(p->in);
15173       if( c==rSep ) p->nLine++;
15174       if( c==cQuote ){
15175         if( pc==cQuote ){
15176           pc = 0;
15177           continue;
15178         }
15179       }
15180       if( (c==cSep && pc==cQuote)
15181        || (c==rSep && pc==cQuote)
15182        || (c==rSep && pc=='\r' && ppc==cQuote)
15183        || (c==EOF && pc==cQuote)
15184       ){
15185         do{ p->n--; }while( p->z[p->n]!=cQuote );
15186         p->cTerm = c;
15187         break;
15188       }
15189       if( pc==cQuote && c!='\r' ){
15190         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
15191                 p->zFile, p->nLine, cQuote);
15192       }
15193       if( c==EOF ){
15194         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
15195                 p->zFile, startLine, cQuote);
15196         p->cTerm = c;
15197         break;
15198       }
15199       import_append_char(p, c);
15200       ppc = pc;
15201       pc = c;
15202     }
15203   }else{
15204     /* If this is the first field being parsed and it begins with the
15205     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
15206     if( (c&0xff)==0xef && p->bNotFirst==0 ){
15207       import_append_char(p, c);
15208       c = fgetc(p->in);
15209       if( (c&0xff)==0xbb ){
15210         import_append_char(p, c);
15211         c = fgetc(p->in);
15212         if( (c&0xff)==0xbf ){
15213           p->bNotFirst = 1;
15214           p->n = 0;
15215           return csv_read_one_field(p);
15216         }
15217       }
15218     }
15219     while( c!=EOF && c!=cSep && c!=rSep ){
15220       import_append_char(p, c);
15221       c = fgetc(p->in);
15222     }
15223     if( c==rSep ){
15224       p->nLine++;
15225       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
15226     }
15227     p->cTerm = c;
15228   }
15229   if( p->z ) p->z[p->n] = 0;
15230   p->bNotFirst = 1;
15231   return p->z;
15232 }
15233
15234 /* Read a single field of ASCII delimited text.
15235 **
15236 **   +  Input comes from p->in.
15237 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
15238 **      from sqlite3_malloc64().
15239 **   +  Use p->cSep as the column separator.  The default is "\x1F".
15240 **   +  Use p->rSep as the row separator.  The default is "\x1E".
15241 **   +  Keep track of the row number in p->nLine.
15242 **   +  Store the character that terminates the field in p->cTerm.  Store
15243 **      EOF on end-of-file.
15244 **   +  Report syntax errors on stderr
15245 */
15246 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
15247   int c;
15248   int cSep = p->cColSep;
15249   int rSep = p->cRowSep;
15250   p->n = 0;
15251   c = fgetc(p->in);
15252   if( c==EOF || seenInterrupt ){
15253     p->cTerm = EOF;
15254     return 0;
15255   }
15256   while( c!=EOF && c!=cSep && c!=rSep ){
15257     import_append_char(p, c);
15258     c = fgetc(p->in);
15259   }
15260   if( c==rSep ){
15261     p->nLine++;
15262   }
15263   p->cTerm = c;
15264   if( p->z ) p->z[p->n] = 0;
15265   return p->z;
15266 }
15267
15268 /*
15269 ** Try to transfer data for table zTable.  If an error is seen while
15270 ** moving forward, try to go backwards.  The backwards movement won't
15271 ** work for WITHOUT ROWID tables.
15272 */
15273 static void tryToCloneData(
15274   ShellState *p,
15275   sqlite3 *newDb,
15276   const char *zTable
15277 ){
15278   sqlite3_stmt *pQuery = 0;
15279   sqlite3_stmt *pInsert = 0;
15280   char *zQuery = 0;
15281   char *zInsert = 0;
15282   int rc;
15283   int i, j, n;
15284   int nTable = strlen30(zTable);
15285   int k = 0;
15286   int cnt = 0;
15287   const int spinRate = 10000;
15288
15289   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
15290   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15291   if( rc ){
15292     utf8_printf(stderr, "Error %d: %s on [%s]\n",
15293             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
15294             zQuery);
15295     goto end_data_xfer;
15296   }
15297   n = sqlite3_column_count(pQuery);
15298   zInsert = sqlite3_malloc64(200 + nTable + n*3);
15299   if( zInsert==0 ) shell_out_of_memory();
15300   sqlite3_snprintf(200+nTable,zInsert,
15301                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
15302   i = strlen30(zInsert);
15303   for(j=1; j<n; j++){
15304     memcpy(zInsert+i, ",?", 2);
15305     i += 2;
15306   }
15307   memcpy(zInsert+i, ");", 3);
15308   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
15309   if( rc ){
15310     utf8_printf(stderr, "Error %d: %s on [%s]\n",
15311             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
15312             zQuery);
15313     goto end_data_xfer;
15314   }
15315   for(k=0; k<2; k++){
15316     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
15317       for(i=0; i<n; i++){
15318         switch( sqlite3_column_type(pQuery, i) ){
15319           case SQLITE_NULL: {
15320             sqlite3_bind_null(pInsert, i+1);
15321             break;
15322           }
15323           case SQLITE_INTEGER: {
15324             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
15325             break;
15326           }
15327           case SQLITE_FLOAT: {
15328             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
15329             break;
15330           }
15331           case SQLITE_TEXT: {
15332             sqlite3_bind_text(pInsert, i+1,
15333                              (const char*)sqlite3_column_text(pQuery,i),
15334                              -1, SQLITE_STATIC);
15335             break;
15336           }
15337           case SQLITE_BLOB: {
15338             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
15339                                             sqlite3_column_bytes(pQuery,i),
15340                                             SQLITE_STATIC);
15341             break;
15342           }
15343         }
15344       } /* End for */
15345       rc = sqlite3_step(pInsert);
15346       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
15347         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
15348                         sqlite3_errmsg(newDb));
15349       }
15350       sqlite3_reset(pInsert);
15351       cnt++;
15352       if( (cnt%spinRate)==0 ){
15353         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
15354         fflush(stdout);
15355       }
15356     } /* End while */
15357     if( rc==SQLITE_DONE ) break;
15358     sqlite3_finalize(pQuery);
15359     sqlite3_free(zQuery);
15360     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
15361                              zTable);
15362     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15363     if( rc ){
15364       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
15365       break;
15366     }
15367   } /* End for(k=0...) */
15368
15369 end_data_xfer:
15370   sqlite3_finalize(pQuery);
15371   sqlite3_finalize(pInsert);
15372   sqlite3_free(zQuery);
15373   sqlite3_free(zInsert);
15374 }
15375
15376
15377 /*
15378 ** Try to transfer all rows of the schema that match zWhere.  For
15379 ** each row, invoke xForEach() on the object defined by that row.
15380 ** If an error is encountered while moving forward through the
15381 ** sqlite_schema table, try again moving backwards.
15382 */
15383 static void tryToCloneSchema(
15384   ShellState *p,
15385   sqlite3 *newDb,
15386   const char *zWhere,
15387   void (*xForEach)(ShellState*,sqlite3*,const char*)
15388 ){
15389   sqlite3_stmt *pQuery = 0;
15390   char *zQuery = 0;
15391   int rc;
15392   const unsigned char *zName;
15393   const unsigned char *zSql;
15394   char *zErrMsg = 0;
15395
15396   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
15397                            " WHERE %s", zWhere);
15398   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15399   if( rc ){
15400     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
15401                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
15402                     zQuery);
15403     goto end_schema_xfer;
15404   }
15405   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
15406     zName = sqlite3_column_text(pQuery, 0);
15407     zSql = sqlite3_column_text(pQuery, 1);
15408     printf("%s... ", zName); fflush(stdout);
15409     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
15410     if( zErrMsg ){
15411       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
15412       sqlite3_free(zErrMsg);
15413       zErrMsg = 0;
15414     }
15415     if( xForEach ){
15416       xForEach(p, newDb, (const char*)zName);
15417     }
15418     printf("done\n");
15419   }
15420   if( rc!=SQLITE_DONE ){
15421     sqlite3_finalize(pQuery);
15422     sqlite3_free(zQuery);
15423     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
15424                              " WHERE %s ORDER BY rowid DESC", zWhere);
15425     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15426     if( rc ){
15427       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
15428                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
15429                       zQuery);
15430       goto end_schema_xfer;
15431     }
15432     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
15433       zName = sqlite3_column_text(pQuery, 0);
15434       zSql = sqlite3_column_text(pQuery, 1);
15435       printf("%s... ", zName); fflush(stdout);
15436       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
15437       if( zErrMsg ){
15438         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
15439         sqlite3_free(zErrMsg);
15440         zErrMsg = 0;
15441       }
15442       if( xForEach ){
15443         xForEach(p, newDb, (const char*)zName);
15444       }
15445       printf("done\n");
15446     }
15447   }
15448 end_schema_xfer:
15449   sqlite3_finalize(pQuery);
15450   sqlite3_free(zQuery);
15451 }
15452
15453 /*
15454 ** Open a new database file named "zNewDb".  Try to recover as much information
15455 ** as possible out of the main database (which might be corrupt) and write it
15456 ** into zNewDb.
15457 */
15458 static void tryToClone(ShellState *p, const char *zNewDb){
15459   int rc;
15460   sqlite3 *newDb = 0;
15461   if( access(zNewDb,0)==0 ){
15462     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
15463     return;
15464   }
15465   rc = sqlite3_open(zNewDb, &newDb);
15466   if( rc ){
15467     utf8_printf(stderr, "Cannot create output database: %s\n",
15468             sqlite3_errmsg(newDb));
15469   }else{
15470     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
15471     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
15472     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
15473     tryToCloneSchema(p, newDb, "type!='table'", 0);
15474     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
15475     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
15476   }
15477   close_db(newDb);
15478 }
15479
15480 /*
15481 ** Change the output file back to stdout.
15482 **
15483 ** If the p->doXdgOpen flag is set, that means the output was being
15484 ** redirected to a temporary file named by p->zTempFile.  In that case,
15485 ** launch start/open/xdg-open on that temporary file.
15486 */
15487 static void output_reset(ShellState *p){
15488   if( p->outfile[0]=='|' ){
15489 #ifndef SQLITE_OMIT_POPEN
15490     pclose(p->out);
15491 #endif
15492   }else{
15493     output_file_close(p->out);
15494 #ifndef SQLITE_NOHAVE_SYSTEM
15495     if( p->doXdgOpen ){
15496       const char *zXdgOpenCmd =
15497 #if defined(_WIN32)
15498       "start";
15499 #elif defined(__APPLE__)
15500       "open";
15501 #else
15502       "xdg-open";
15503 #endif
15504       char *zCmd;
15505       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
15506       if( system(zCmd) ){
15507         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
15508       }else{
15509         /* Give the start/open/xdg-open command some time to get
15510         ** going before we continue, and potential delete the
15511         ** p->zTempFile data file out from under it */
15512         sqlite3_sleep(2000);
15513       }
15514       sqlite3_free(zCmd);
15515       outputModePop(p);
15516       p->doXdgOpen = 0;
15517     }
15518 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
15519   }
15520   p->outfile[0] = 0;
15521   p->out = stdout;
15522 }
15523
15524 /*
15525 ** Run an SQL command and return the single integer result.
15526 */
15527 static int db_int(ShellState *p, const char *zSql){
15528   sqlite3_stmt *pStmt;
15529   int res = 0;
15530   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
15531   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
15532     res = sqlite3_column_int(pStmt,0);
15533   }
15534   sqlite3_finalize(pStmt);
15535   return res;
15536 }
15537
15538 /*
15539 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
15540 */
15541 static unsigned int get2byteInt(unsigned char *a){
15542   return (a[0]<<8) + a[1];
15543 }
15544 static unsigned int get4byteInt(unsigned char *a){
15545   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
15546 }
15547
15548 /*
15549 ** Implementation of the ".dbinfo" command.
15550 **
15551 ** Return 1 on error, 2 to exit, and 0 otherwise.
15552 */
15553 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
15554   static const struct { const char *zName; int ofst; } aField[] = {
15555      { "file change counter:",  24  },
15556      { "database page count:",  28  },
15557      { "freelist page count:",  36  },
15558      { "schema cookie:",        40  },
15559      { "schema format:",        44  },
15560      { "default cache size:",   48  },
15561      { "autovacuum top root:",  52  },
15562      { "incremental vacuum:",   64  },
15563      { "text encoding:",        56  },
15564      { "user version:",         60  },
15565      { "application id:",       68  },
15566      { "software version:",     96  },
15567   };
15568   static const struct { const char *zName; const char *zSql; } aQuery[] = {
15569      { "number of tables:",
15570        "SELECT count(*) FROM %s WHERE type='table'" },
15571      { "number of indexes:",
15572        "SELECT count(*) FROM %s WHERE type='index'" },
15573      { "number of triggers:",
15574        "SELECT count(*) FROM %s WHERE type='trigger'" },
15575      { "number of views:",
15576        "SELECT count(*) FROM %s WHERE type='view'" },
15577      { "schema size:",
15578        "SELECT total(length(sql)) FROM %s" },
15579   };
15580   int i, rc;
15581   unsigned iDataVersion;
15582   char *zSchemaTab;
15583   char *zDb = nArg>=2 ? azArg[1] : "main";
15584   sqlite3_stmt *pStmt = 0;
15585   unsigned char aHdr[100];
15586   open_db(p, 0);
15587   if( p->db==0 ) return 1;
15588   rc = sqlite3_prepare_v2(p->db,
15589              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
15590              -1, &pStmt, 0);
15591   if( rc ){
15592     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
15593     sqlite3_finalize(pStmt);
15594     return 1;
15595   }
15596   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
15597   if( sqlite3_step(pStmt)==SQLITE_ROW
15598    && sqlite3_column_bytes(pStmt,0)>100
15599   ){
15600     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
15601     sqlite3_finalize(pStmt);
15602   }else{
15603     raw_printf(stderr, "unable to read database header\n");
15604     sqlite3_finalize(pStmt);
15605     return 1;
15606   }
15607   i = get2byteInt(aHdr+16);
15608   if( i==1 ) i = 65536;
15609   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
15610   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
15611   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
15612   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
15613   for(i=0; i<ArraySize(aField); i++){
15614     int ofst = aField[i].ofst;
15615     unsigned int val = get4byteInt(aHdr + ofst);
15616     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
15617     switch( ofst ){
15618       case 56: {
15619         if( val==1 ) raw_printf(p->out, " (utf8)");
15620         if( val==2 ) raw_printf(p->out, " (utf16le)");
15621         if( val==3 ) raw_printf(p->out, " (utf16be)");
15622       }
15623     }
15624     raw_printf(p->out, "\n");
15625   }
15626   if( zDb==0 ){
15627     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
15628   }else if( strcmp(zDb,"temp")==0 ){
15629     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
15630   }else{
15631     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
15632   }
15633   for(i=0; i<ArraySize(aQuery); i++){
15634     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
15635     int val = db_int(p, zSql);
15636     sqlite3_free(zSql);
15637     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
15638   }
15639   sqlite3_free(zSchemaTab);
15640   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
15641   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
15642   return 0;
15643 }
15644
15645 /*
15646 ** Print the current sqlite3_errmsg() value to stderr and return 1.
15647 */
15648 static int shellDatabaseError(sqlite3 *db){
15649   const char *zErr = sqlite3_errmsg(db);
15650   utf8_printf(stderr, "Error: %s\n", zErr);
15651   return 1;
15652 }
15653
15654 /*
15655 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
15656 ** if they match and FALSE (0) if they do not match.
15657 **
15658 ** Globbing rules:
15659 **
15660 **      '*'       Matches any sequence of zero or more characters.
15661 **
15662 **      '?'       Matches exactly one character.
15663 **
15664 **     [...]      Matches one character from the enclosed list of
15665 **                characters.
15666 **
15667 **     [^...]     Matches one character not in the enclosed list.
15668 **
15669 **      '#'       Matches any sequence of one or more digits with an
15670 **                optional + or - sign in front
15671 **
15672 **      ' '       Any span of whitespace matches any other span of
15673 **                whitespace.
15674 **
15675 ** Extra whitespace at the end of z[] is ignored.
15676 */
15677 static int testcase_glob(const char *zGlob, const char *z){
15678   int c, c2;
15679   int invert;
15680   int seen;
15681
15682   while( (c = (*(zGlob++)))!=0 ){
15683     if( IsSpace(c) ){
15684       if( !IsSpace(*z) ) return 0;
15685       while( IsSpace(*zGlob) ) zGlob++;
15686       while( IsSpace(*z) ) z++;
15687     }else if( c=='*' ){
15688       while( (c=(*(zGlob++))) == '*' || c=='?' ){
15689         if( c=='?' && (*(z++))==0 ) return 0;
15690       }
15691       if( c==0 ){
15692         return 1;
15693       }else if( c=='[' ){
15694         while( *z && testcase_glob(zGlob-1,z)==0 ){
15695           z++;
15696         }
15697         return (*z)!=0;
15698       }
15699       while( (c2 = (*(z++)))!=0 ){
15700         while( c2!=c ){
15701           c2 = *(z++);
15702           if( c2==0 ) return 0;
15703         }
15704         if( testcase_glob(zGlob,z) ) return 1;
15705       }
15706       return 0;
15707     }else if( c=='?' ){
15708       if( (*(z++))==0 ) return 0;
15709     }else if( c=='[' ){
15710       int prior_c = 0;
15711       seen = 0;
15712       invert = 0;
15713       c = *(z++);
15714       if( c==0 ) return 0;
15715       c2 = *(zGlob++);
15716       if( c2=='^' ){
15717         invert = 1;
15718         c2 = *(zGlob++);
15719       }
15720       if( c2==']' ){
15721         if( c==']' ) seen = 1;
15722         c2 = *(zGlob++);
15723       }
15724       while( c2 && c2!=']' ){
15725         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
15726           c2 = *(zGlob++);
15727           if( c>=prior_c && c<=c2 ) seen = 1;
15728           prior_c = 0;
15729         }else{
15730           if( c==c2 ){
15731             seen = 1;
15732           }
15733           prior_c = c2;
15734         }
15735         c2 = *(zGlob++);
15736       }
15737       if( c2==0 || (seen ^ invert)==0 ) return 0;
15738     }else if( c=='#' ){
15739       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
15740       if( !IsDigit(z[0]) ) return 0;
15741       z++;
15742       while( IsDigit(z[0]) ){ z++; }
15743     }else{
15744       if( c!=(*(z++)) ) return 0;
15745     }
15746   }
15747   while( IsSpace(*z) ){ z++; }
15748   return *z==0;
15749 }
15750
15751
15752 /*
15753 ** Compare the string as a command-line option with either one or two
15754 ** initial "-" characters.
15755 */
15756 static int optionMatch(const char *zStr, const char *zOpt){
15757   if( zStr[0]!='-' ) return 0;
15758   zStr++;
15759   if( zStr[0]=='-' ) zStr++;
15760   return strcmp(zStr, zOpt)==0;
15761 }
15762
15763 /*
15764 ** Delete a file.
15765 */
15766 int shellDeleteFile(const char *zFilename){
15767   int rc;
15768 #ifdef _WIN32
15769   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
15770   rc = _wunlink(z);
15771   sqlite3_free(z);
15772 #else
15773   rc = unlink(zFilename);
15774 #endif
15775   return rc;
15776 }
15777
15778 /*
15779 ** Try to delete the temporary file (if there is one) and free the
15780 ** memory used to hold the name of the temp file.
15781 */
15782 static void clearTempFile(ShellState *p){
15783   if( p->zTempFile==0 ) return;
15784   if( p->doXdgOpen ) return;
15785   if( shellDeleteFile(p->zTempFile) ) return;
15786   sqlite3_free(p->zTempFile);
15787   p->zTempFile = 0;
15788 }
15789
15790 /*
15791 ** Create a new temp file name with the given suffix.
15792 */
15793 static void newTempFile(ShellState *p, const char *zSuffix){
15794   clearTempFile(p);
15795   sqlite3_free(p->zTempFile);
15796   p->zTempFile = 0;
15797   if( p->db ){
15798     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
15799   }
15800   if( p->zTempFile==0 ){
15801     /* If p->db is an in-memory database then the TEMPFILENAME file-control
15802     ** will not work and we will need to fallback to guessing */
15803     char *zTemp;
15804     sqlite3_uint64 r;
15805     sqlite3_randomness(sizeof(r), &r);
15806     zTemp = getenv("TEMP");
15807     if( zTemp==0 ) zTemp = getenv("TMP");
15808     if( zTemp==0 ){
15809 #ifdef _WIN32
15810       zTemp = "\\tmp";
15811 #else
15812       zTemp = "/tmp";
15813 #endif
15814     }
15815     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
15816   }else{
15817     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
15818   }
15819   if( p->zTempFile==0 ){
15820     raw_printf(stderr, "out of memory\n");
15821     exit(1);
15822   }
15823 }
15824
15825
15826 /*
15827 ** The implementation of SQL scalar function fkey_collate_clause(), used
15828 ** by the ".lint fkey-indexes" command. This scalar function is always
15829 ** called with four arguments - the parent table name, the parent column name,
15830 ** the child table name and the child column name.
15831 **
15832 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
15833 **
15834 ** If either of the named tables or columns do not exist, this function
15835 ** returns an empty string. An empty string is also returned if both tables
15836 ** and columns exist but have the same default collation sequence. Or,
15837 ** if both exist but the default collation sequences are different, this
15838 ** function returns the string " COLLATE <parent-collation>", where
15839 ** <parent-collation> is the default collation sequence of the parent column.
15840 */
15841 static void shellFkeyCollateClause(
15842   sqlite3_context *pCtx,
15843   int nVal,
15844   sqlite3_value **apVal
15845 ){
15846   sqlite3 *db = sqlite3_context_db_handle(pCtx);
15847   const char *zParent;
15848   const char *zParentCol;
15849   const char *zParentSeq;
15850   const char *zChild;
15851   const char *zChildCol;
15852   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
15853   int rc;
15854
15855   assert( nVal==4 );
15856   zParent = (const char*)sqlite3_value_text(apVal[0]);
15857   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
15858   zChild = (const char*)sqlite3_value_text(apVal[2]);
15859   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
15860
15861   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
15862   rc = sqlite3_table_column_metadata(
15863       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
15864   );
15865   if( rc==SQLITE_OK ){
15866     rc = sqlite3_table_column_metadata(
15867         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
15868     );
15869   }
15870
15871   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
15872     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
15873     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
15874     sqlite3_free(z);
15875   }
15876 }
15877
15878
15879 /*
15880 ** The implementation of dot-command ".lint fkey-indexes".
15881 */
15882 static int lintFkeyIndexes(
15883   ShellState *pState,             /* Current shell tool state */
15884   char **azArg,                   /* Array of arguments passed to dot command */
15885   int nArg                        /* Number of entries in azArg[] */
15886 ){
15887   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
15888   FILE *out = pState->out;        /* Stream to write non-error output to */
15889   int bVerbose = 0;               /* If -verbose is present */
15890   int bGroupByParent = 0;         /* If -groupbyparent is present */
15891   int i;                          /* To iterate through azArg[] */
15892   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
15893   int rc;                         /* Return code */
15894   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
15895
15896   /*
15897   ** This SELECT statement returns one row for each foreign key constraint
15898   ** in the schema of the main database. The column values are:
15899   **
15900   ** 0. The text of an SQL statement similar to:
15901   **
15902   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
15903   **
15904   **    This SELECT is similar to the one that the foreign keys implementation
15905   **    needs to run internally on child tables. If there is an index that can
15906   **    be used to optimize this query, then it can also be used by the FK
15907   **    implementation to optimize DELETE or UPDATE statements on the parent
15908   **    table.
15909   **
15910   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
15911   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
15912   **    contains an index that can be used to optimize the query.
15913   **
15914   ** 2. Human readable text that describes the child table and columns. e.g.
15915   **
15916   **       "child_table(child_key1, child_key2)"
15917   **
15918   ** 3. Human readable text that describes the parent table and columns. e.g.
15919   **
15920   **       "parent_table(parent_key1, parent_key2)"
15921   **
15922   ** 4. A full CREATE INDEX statement for an index that could be used to
15923   **    optimize DELETE or UPDATE statements on the parent table. e.g.
15924   **
15925   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
15926   **
15927   ** 5. The name of the parent table.
15928   **
15929   ** These six values are used by the C logic below to generate the report.
15930   */
15931   const char *zSql =
15932   "SELECT "
15933     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
15934     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
15935     "  || fkey_collate_clause("
15936     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
15937     ", "
15938     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
15939     "  || group_concat('*=?', ' AND ') || ')'"
15940     ", "
15941     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
15942     ", "
15943     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
15944     ", "
15945     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
15946     "  || ' ON ' || quote(s.name) || '('"
15947     "  || group_concat(quote(f.[from]) ||"
15948     "        fkey_collate_clause("
15949     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
15950     "  || ');'"
15951     ", "
15952     "     f.[table] "
15953     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
15954     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
15955     "GROUP BY s.name, f.id "
15956     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
15957   ;
15958   const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
15959
15960   for(i=2; i<nArg; i++){
15961     int n = strlen30(azArg[i]);
15962     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
15963       bVerbose = 1;
15964     }
15965     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
15966       bGroupByParent = 1;
15967       zIndent = "    ";
15968     }
15969     else{
15970       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
15971           azArg[0], azArg[1]
15972       );
15973       return SQLITE_ERROR;
15974     }
15975   }
15976
15977   /* Register the fkey_collate_clause() SQL function */
15978   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
15979       0, shellFkeyCollateClause, 0, 0
15980   );
15981
15982
15983   if( rc==SQLITE_OK ){
15984     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
15985   }
15986   if( rc==SQLITE_OK ){
15987     sqlite3_bind_int(pSql, 1, bGroupByParent);
15988   }
15989
15990   if( rc==SQLITE_OK ){
15991     int rc2;
15992     char *zPrev = 0;
15993     while( SQLITE_ROW==sqlite3_step(pSql) ){
15994       int res = -1;
15995       sqlite3_stmt *pExplain = 0;
15996       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
15997       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
15998       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
15999       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
16000       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
16001       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
16002
16003       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
16004       if( rc!=SQLITE_OK ) break;
16005       if( SQLITE_ROW==sqlite3_step(pExplain) ){
16006         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
16007         res = (
16008               0==sqlite3_strglob(zGlob, zPlan)
16009            || 0==sqlite3_strglob(zGlobIPK, zPlan)
16010         );
16011       }
16012       rc = sqlite3_finalize(pExplain);
16013       if( rc!=SQLITE_OK ) break;
16014
16015       if( res<0 ){
16016         raw_printf(stderr, "Error: internal error");
16017         break;
16018       }else{
16019         if( bGroupByParent
16020         && (bVerbose || res==0)
16021         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
16022         ){
16023           raw_printf(out, "-- Parent table %s\n", zParent);
16024           sqlite3_free(zPrev);
16025           zPrev = sqlite3_mprintf("%s", zParent);
16026         }
16027
16028         if( res==0 ){
16029           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
16030         }else if( bVerbose ){
16031           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
16032               zIndent, zFrom, zTarget
16033           );
16034         }
16035       }
16036     }
16037     sqlite3_free(zPrev);
16038
16039     if( rc!=SQLITE_OK ){
16040       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
16041     }
16042
16043     rc2 = sqlite3_finalize(pSql);
16044     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
16045       rc = rc2;
16046       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
16047     }
16048   }else{
16049     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
16050   }
16051
16052   return rc;
16053 }
16054
16055 /*
16056 ** Implementation of ".lint" dot command.
16057 */
16058 static int lintDotCommand(
16059   ShellState *pState,             /* Current shell tool state */
16060   char **azArg,                   /* Array of arguments passed to dot command */
16061   int nArg                        /* Number of entries in azArg[] */
16062 ){
16063   int n;
16064   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
16065   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
16066   return lintFkeyIndexes(pState, azArg, nArg);
16067
16068  usage:
16069   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
16070   raw_printf(stderr, "Where sub-commands are:\n");
16071   raw_printf(stderr, "    fkey-indexes\n");
16072   return SQLITE_ERROR;
16073 }
16074
16075 #if !defined SQLITE_OMIT_VIRTUALTABLE
16076 static void shellPrepare(
16077   sqlite3 *db, 
16078   int *pRc, 
16079   const char *zSql, 
16080   sqlite3_stmt **ppStmt
16081 ){
16082   *ppStmt = 0;
16083   if( *pRc==SQLITE_OK ){
16084     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
16085     if( rc!=SQLITE_OK ){
16086       raw_printf(stderr, "sql error: %s (%d)\n", 
16087           sqlite3_errmsg(db), sqlite3_errcode(db)
16088       );
16089       *pRc = rc;
16090     }
16091   }
16092 }
16093
16094 /*
16095 ** Create a prepared statement using printf-style arguments for the SQL.
16096 **
16097 ** This routine is could be marked "static".  But it is not always used,
16098 ** depending on compile-time options.  By omitting the "static", we avoid
16099 ** nuisance compiler warnings about "defined but not used".
16100 */
16101 void shellPreparePrintf(
16102   sqlite3 *db, 
16103   int *pRc, 
16104   sqlite3_stmt **ppStmt,
16105   const char *zFmt, 
16106   ...
16107 ){
16108   *ppStmt = 0;
16109   if( *pRc==SQLITE_OK ){
16110     va_list ap;
16111     char *z;
16112     va_start(ap, zFmt);
16113     z = sqlite3_vmprintf(zFmt, ap);
16114     va_end(ap);
16115     if( z==0 ){
16116       *pRc = SQLITE_NOMEM;
16117     }else{
16118       shellPrepare(db, pRc, z, ppStmt);
16119       sqlite3_free(z);
16120     }
16121   }
16122 }
16123
16124 /* Finalize the prepared statement created using shellPreparePrintf().
16125 **
16126 ** This routine is could be marked "static".  But it is not always used,
16127 ** depending on compile-time options.  By omitting the "static", we avoid
16128 ** nuisance compiler warnings about "defined but not used".
16129 */
16130 void shellFinalize(
16131   int *pRc, 
16132   sqlite3_stmt *pStmt
16133 ){
16134   if( pStmt ){
16135     sqlite3 *db = sqlite3_db_handle(pStmt);
16136     int rc = sqlite3_finalize(pStmt);
16137     if( *pRc==SQLITE_OK ){
16138       if( rc!=SQLITE_OK ){
16139         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
16140       }
16141       *pRc = rc;
16142     }
16143   }
16144 }
16145
16146 /* Reset the prepared statement created using shellPreparePrintf().
16147 **
16148 ** This routine is could be marked "static".  But it is not always used,
16149 ** depending on compile-time options.  By omitting the "static", we avoid
16150 ** nuisance compiler warnings about "defined but not used".
16151 */
16152 void shellReset(
16153   int *pRc, 
16154   sqlite3_stmt *pStmt
16155 ){
16156   int rc = sqlite3_reset(pStmt);
16157   if( *pRc==SQLITE_OK ){
16158     if( rc!=SQLITE_OK ){
16159       sqlite3 *db = sqlite3_db_handle(pStmt);
16160       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
16161     }
16162     *pRc = rc;
16163   }
16164 }
16165 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
16166
16167 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16168 /******************************************************************************
16169 ** The ".archive" or ".ar" command.
16170 */
16171 /*
16172 ** Structure representing a single ".ar" command.
16173 */
16174 typedef struct ArCommand ArCommand;
16175 struct ArCommand {
16176   u8 eCmd;                        /* An AR_CMD_* value */
16177   u8 bVerbose;                    /* True if --verbose */
16178   u8 bZip;                        /* True if the archive is a ZIP */
16179   u8 bDryRun;                     /* True if --dry-run */
16180   u8 bAppend;                     /* True if --append */
16181   u8 fromCmdLine;                 /* Run from -A instead of .archive */
16182   int nArg;                       /* Number of command arguments */
16183   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
16184   const char *zFile;              /* --file argument, or NULL */
16185   const char *zDir;               /* --directory argument, or NULL */
16186   char **azArg;                   /* Array of command arguments */
16187   ShellState *p;                  /* Shell state */
16188   sqlite3 *db;                    /* Database containing the archive */
16189 };
16190
16191 /*
16192 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
16193 */
16194 static int arUsage(FILE *f){
16195   showHelp(f,"archive");
16196   return SQLITE_ERROR;
16197 }
16198
16199 /*
16200 ** Print an error message for the .ar command to stderr and return 
16201 ** SQLITE_ERROR.
16202 */
16203 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
16204   va_list ap;
16205   char *z;
16206   va_start(ap, zFmt);
16207   z = sqlite3_vmprintf(zFmt, ap);
16208   va_end(ap);
16209   utf8_printf(stderr, "Error: %s\n", z);
16210   if( pAr->fromCmdLine ){
16211     utf8_printf(stderr, "Use \"-A\" for more help\n");
16212   }else{
16213     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
16214   }
16215   sqlite3_free(z);
16216   return SQLITE_ERROR;
16217 }
16218
16219 /*
16220 ** Values for ArCommand.eCmd.
16221 */
16222 #define AR_CMD_CREATE       1
16223 #define AR_CMD_UPDATE       2
16224 #define AR_CMD_INSERT       3
16225 #define AR_CMD_EXTRACT      4
16226 #define AR_CMD_LIST         5
16227 #define AR_CMD_HELP         6
16228
16229 /*
16230 ** Other (non-command) switches.
16231 */
16232 #define AR_SWITCH_VERBOSE     7
16233 #define AR_SWITCH_FILE        8
16234 #define AR_SWITCH_DIRECTORY   9
16235 #define AR_SWITCH_APPEND     10
16236 #define AR_SWITCH_DRYRUN     11
16237
16238 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
16239   switch( eSwitch ){
16240     case AR_CMD_CREATE:
16241     case AR_CMD_EXTRACT:
16242     case AR_CMD_LIST:
16243     case AR_CMD_UPDATE:
16244     case AR_CMD_INSERT:
16245     case AR_CMD_HELP:
16246       if( pAr->eCmd ){
16247         return arErrorMsg(pAr, "multiple command options");
16248       }
16249       pAr->eCmd = eSwitch;
16250       break;
16251
16252     case AR_SWITCH_DRYRUN:
16253       pAr->bDryRun = 1;
16254       break;
16255     case AR_SWITCH_VERBOSE:
16256       pAr->bVerbose = 1;
16257       break;
16258     case AR_SWITCH_APPEND:
16259       pAr->bAppend = 1;
16260       /* Fall thru into --file */
16261     case AR_SWITCH_FILE:
16262       pAr->zFile = zArg;
16263       break;
16264     case AR_SWITCH_DIRECTORY:
16265       pAr->zDir = zArg;
16266       break;
16267   }
16268
16269   return SQLITE_OK;
16270 }
16271
16272 /*
16273 ** Parse the command line for an ".ar" command. The results are written into
16274 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
16275 ** successfully, otherwise an error message is written to stderr and 
16276 ** SQLITE_ERROR returned.
16277 */
16278 static int arParseCommand(
16279   char **azArg,                   /* Array of arguments passed to dot command */
16280   int nArg,                       /* Number of entries in azArg[] */
16281   ArCommand *pAr                  /* Populate this object */
16282 ){
16283   struct ArSwitch {
16284     const char *zLong;
16285     char cShort;
16286     u8 eSwitch;
16287     u8 bArg;
16288   } aSwitch[] = {
16289     { "create",    'c', AR_CMD_CREATE,       0 },
16290     { "extract",   'x', AR_CMD_EXTRACT,      0 },
16291     { "insert",    'i', AR_CMD_INSERT,       0 },
16292     { "list",      't', AR_CMD_LIST,         0 },
16293     { "update",    'u', AR_CMD_UPDATE,       0 },
16294     { "help",      'h', AR_CMD_HELP,         0 },
16295     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
16296     { "file",      'f', AR_SWITCH_FILE,      1 },
16297     { "append",    'a', AR_SWITCH_APPEND,    1 },
16298     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
16299     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
16300   };
16301   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
16302   struct ArSwitch *pEnd = &aSwitch[nSwitch];
16303
16304   if( nArg<=1 ){
16305     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
16306     return arUsage(stderr);
16307   }else{
16308     char *z = azArg[1];
16309     if( z[0]!='-' ){
16310       /* Traditional style [tar] invocation */
16311       int i;
16312       int iArg = 2;
16313       for(i=0; z[i]; i++){
16314         const char *zArg = 0;
16315         struct ArSwitch *pOpt;
16316         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
16317           if( z[i]==pOpt->cShort ) break;
16318         }
16319         if( pOpt==pEnd ){
16320           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
16321         }
16322         if( pOpt->bArg ){
16323           if( iArg>=nArg ){
16324             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
16325           }
16326           zArg = azArg[iArg++];
16327         }
16328         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
16329       }
16330       pAr->nArg = nArg-iArg;
16331       if( pAr->nArg>0 ){
16332         pAr->azArg = &azArg[iArg];
16333       }
16334     }else{
16335       /* Non-traditional invocation */
16336       int iArg;
16337       for(iArg=1; iArg<nArg; iArg++){
16338         int n;
16339         z = azArg[iArg];
16340         if( z[0]!='-' ){
16341           /* All remaining command line words are command arguments. */
16342           pAr->azArg = &azArg[iArg];
16343           pAr->nArg = nArg-iArg;
16344           break;
16345         }
16346         n = strlen30(z);
16347
16348         if( z[1]!='-' ){
16349           int i;
16350           /* One or more short options */
16351           for(i=1; i<n; i++){
16352             const char *zArg = 0;
16353             struct ArSwitch *pOpt;
16354             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
16355               if( z[i]==pOpt->cShort ) break;
16356             }
16357             if( pOpt==pEnd ){
16358               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
16359             }
16360             if( pOpt->bArg ){
16361               if( i<(n-1) ){
16362                 zArg = &z[i+1];
16363                 i = n;
16364               }else{
16365                 if( iArg>=(nArg-1) ){
16366                   return arErrorMsg(pAr, "option requires an argument: %c",
16367                                     z[i]);
16368                 }
16369                 zArg = azArg[++iArg];
16370               }
16371             }
16372             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
16373           }
16374         }else if( z[2]=='\0' ){
16375           /* A -- option, indicating that all remaining command line words
16376           ** are command arguments.  */
16377           pAr->azArg = &azArg[iArg+1];
16378           pAr->nArg = nArg-iArg-1;
16379           break;
16380         }else{
16381           /* A long option */
16382           const char *zArg = 0;             /* Argument for option, if any */
16383           struct ArSwitch *pMatch = 0;      /* Matching option */
16384           struct ArSwitch *pOpt;            /* Iterator */
16385           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
16386             const char *zLong = pOpt->zLong;
16387             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
16388               if( pMatch ){
16389                 return arErrorMsg(pAr, "ambiguous option: %s",z);
16390               }else{
16391                 pMatch = pOpt;
16392               }
16393             }
16394           }
16395
16396           if( pMatch==0 ){
16397             return arErrorMsg(pAr, "unrecognized option: %s", z);
16398           }
16399           if( pMatch->bArg ){
16400             if( iArg>=(nArg-1) ){
16401               return arErrorMsg(pAr, "option requires an argument: %s", z);
16402             }
16403             zArg = azArg[++iArg];
16404           }
16405           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
16406         }
16407       }
16408     }
16409   }
16410
16411   return SQLITE_OK;
16412 }
16413
16414 /*
16415 ** This function assumes that all arguments within the ArCommand.azArg[]
16416 ** array refer to archive members, as for the --extract or --list commands. 
16417 ** It checks that each of them are present. If any specified file is not
16418 ** present in the archive, an error is printed to stderr and an error
16419 ** code returned. Otherwise, if all specified arguments are present in
16420 ** the archive, SQLITE_OK is returned.
16421 **
16422 ** This function strips any trailing '/' characters from each argument.
16423 ** This is consistent with the way the [tar] command seems to work on
16424 ** Linux.
16425 */
16426 static int arCheckEntries(ArCommand *pAr){
16427   int rc = SQLITE_OK;
16428   if( pAr->nArg ){
16429     int i, j;
16430     sqlite3_stmt *pTest = 0;
16431
16432     shellPreparePrintf(pAr->db, &rc, &pTest,
16433         "SELECT name FROM %s WHERE name=$name", 
16434         pAr->zSrcTable
16435     );
16436     j = sqlite3_bind_parameter_index(pTest, "$name");
16437     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
16438       char *z = pAr->azArg[i];
16439       int n = strlen30(z);
16440       int bOk = 0;
16441       while( n>0 && z[n-1]=='/' ) n--;
16442       z[n] = '\0';
16443       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
16444       if( SQLITE_ROW==sqlite3_step(pTest) ){
16445         bOk = 1;
16446       }
16447       shellReset(&rc, pTest);
16448       if( rc==SQLITE_OK && bOk==0 ){
16449         utf8_printf(stderr, "not found in archive: %s\n", z);
16450         rc = SQLITE_ERROR;
16451       }
16452     }
16453     shellFinalize(&rc, pTest);
16454   }
16455   return rc;
16456 }
16457
16458 /*
16459 ** Format a WHERE clause that can be used against the "sqlar" table to
16460 ** identify all archive members that match the command arguments held
16461 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
16462 ** The caller is responsible for eventually calling sqlite3_free() on
16463 ** any non-NULL (*pzWhere) value.
16464 */
16465 static void arWhereClause(
16466   int *pRc, 
16467   ArCommand *pAr, 
16468   char **pzWhere                  /* OUT: New WHERE clause */
16469 ){
16470   char *zWhere = 0;
16471   if( *pRc==SQLITE_OK ){
16472     if( pAr->nArg==0 ){
16473       zWhere = sqlite3_mprintf("1");
16474     }else{
16475       int i;
16476       const char *zSep = "";
16477       for(i=0; i<pAr->nArg; i++){
16478         const char *z = pAr->azArg[i];
16479         zWhere = sqlite3_mprintf(
16480           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 
16481           zWhere, zSep, z, strlen30(z)+1, z
16482         );
16483         if( zWhere==0 ){
16484           *pRc = SQLITE_NOMEM;
16485           break;
16486         }
16487         zSep = " OR ";
16488       }
16489     }
16490   }
16491   *pzWhere = zWhere;
16492 }
16493
16494 /*
16495 ** Implementation of .ar "lisT" command. 
16496 */
16497 static int arListCommand(ArCommand *pAr){
16498   const char *zSql = "SELECT %s FROM %s WHERE %s"; 
16499   const char *azCols[] = {
16500     "name",
16501     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
16502   };
16503
16504   char *zWhere = 0;
16505   sqlite3_stmt *pSql = 0;
16506   int rc;
16507
16508   rc = arCheckEntries(pAr);
16509   arWhereClause(&rc, pAr, &zWhere);
16510
16511   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
16512                      pAr->zSrcTable, zWhere);
16513   if( pAr->bDryRun ){
16514     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
16515   }else{
16516     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
16517       if( pAr->bVerbose ){
16518         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
16519             sqlite3_column_text(pSql, 0),
16520             sqlite3_column_int(pSql, 1), 
16521             sqlite3_column_text(pSql, 2),
16522             sqlite3_column_text(pSql, 3)
16523         );
16524       }else{
16525         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
16526       }
16527     }
16528   }
16529   shellFinalize(&rc, pSql);
16530   sqlite3_free(zWhere);
16531   return rc;
16532 }
16533
16534
16535 /*
16536 ** Implementation of .ar "eXtract" command. 
16537 */
16538 static int arExtractCommand(ArCommand *pAr){
16539   const char *zSql1 = 
16540     "SELECT "
16541     " ($dir || name),"
16542     " writefile(($dir || name), %s, mode, mtime) "
16543     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
16544     " AND name NOT GLOB '*..[/\\]*'";
16545
16546   const char *azExtraArg[] = { 
16547     "sqlar_uncompress(data, sz)",
16548     "data"
16549   };
16550
16551   sqlite3_stmt *pSql = 0;
16552   int rc = SQLITE_OK;
16553   char *zDir = 0;
16554   char *zWhere = 0;
16555   int i, j;
16556
16557   /* If arguments are specified, check that they actually exist within
16558   ** the archive before proceeding. And formulate a WHERE clause to
16559   ** match them.  */
16560   rc = arCheckEntries(pAr);
16561   arWhereClause(&rc, pAr, &zWhere);
16562
16563   if( rc==SQLITE_OK ){
16564     if( pAr->zDir ){
16565       zDir = sqlite3_mprintf("%s/", pAr->zDir);
16566     }else{
16567       zDir = sqlite3_mprintf("");
16568     }
16569     if( zDir==0 ) rc = SQLITE_NOMEM;
16570   }
16571
16572   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 
16573       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
16574   );
16575
16576   if( rc==SQLITE_OK ){
16577     j = sqlite3_bind_parameter_index(pSql, "$dir");
16578     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
16579
16580     /* Run the SELECT statement twice. The first time, writefile() is called
16581     ** for all archive members that should be extracted. The second time,
16582     ** only for the directories. This is because the timestamps for
16583     ** extracted directories must be reset after they are populated (as
16584     ** populating them changes the timestamp).  */
16585     for(i=0; i<2; i++){
16586       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
16587       sqlite3_bind_int(pSql, j, i);
16588       if( pAr->bDryRun ){
16589         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
16590       }else{
16591         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
16592           if( i==0 && pAr->bVerbose ){
16593             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
16594           }
16595         }
16596       }
16597       shellReset(&rc, pSql);
16598     }
16599     shellFinalize(&rc, pSql);
16600   }
16601
16602   sqlite3_free(zDir);
16603   sqlite3_free(zWhere);
16604   return rc;
16605 }
16606
16607 /*
16608 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
16609 */
16610 static int arExecSql(ArCommand *pAr, const char *zSql){
16611   int rc;
16612   if( pAr->bDryRun ){
16613     utf8_printf(pAr->p->out, "%s\n", zSql);
16614     rc = SQLITE_OK;
16615   }else{
16616     char *zErr = 0;
16617     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
16618     if( zErr ){
16619       utf8_printf(stdout, "ERROR: %s\n", zErr);
16620       sqlite3_free(zErr);
16621     }
16622   }
16623   return rc;
16624 }
16625
16626
16627 /*
16628 ** Implementation of .ar "create", "insert", and "update" commands.
16629 **
16630 **     create    ->     Create a new SQL archive
16631 **     insert    ->     Insert or reinsert all files listed
16632 **     update    ->     Insert files that have changed or that were not
16633 **                      previously in the archive
16634 **
16635 ** Create the "sqlar" table in the database if it does not already exist.
16636 ** Then add each file in the azFile[] array to the archive. Directories
16637 ** are added recursively. If argument bVerbose is non-zero, a message is
16638 ** printed on stdout for each file archived.
16639 **
16640 ** The create command is the same as update, except that it drops
16641 ** any existing "sqlar" table before beginning.  The "insert" command
16642 ** always overwrites every file named on the command-line, where as
16643 ** "update" only overwrites if the size or mtime or mode has changed.
16644 */
16645 static int arCreateOrUpdateCommand(
16646   ArCommand *pAr,                 /* Command arguments and options */
16647   int bUpdate,                    /* true for a --create. */
16648   int bOnlyIfChanged              /* Only update if file has changed */
16649 ){
16650   const char *zCreate = 
16651       "CREATE TABLE IF NOT EXISTS sqlar(\n"
16652       "  name TEXT PRIMARY KEY,  -- name of the file\n"
16653       "  mode INT,               -- access permissions\n"
16654       "  mtime INT,              -- last modification time\n"
16655       "  sz INT,                 -- original file size\n"
16656       "  data BLOB               -- compressed content\n"
16657       ")";
16658   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
16659   const char *zInsertFmt[2] = {
16660      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
16661      "  SELECT\n"
16662      "    %s,\n"
16663      "    mode,\n"
16664      "    mtime,\n"
16665      "    CASE substr(lsmode(mode),1,1)\n"
16666      "      WHEN '-' THEN length(data)\n"
16667      "      WHEN 'd' THEN 0\n"
16668      "      ELSE -1 END,\n"
16669      "    sqlar_compress(data)\n"
16670      "  FROM fsdir(%Q,%Q) AS disk\n"
16671      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
16672      ,
16673      "REPLACE INTO %s(name,mode,mtime,data)\n"
16674      "  SELECT\n"
16675      "    %s,\n"
16676      "    mode,\n"
16677      "    mtime,\n"
16678      "    data\n"
16679      "  FROM fsdir(%Q,%Q) AS disk\n"
16680      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
16681   };
16682   int i;                          /* For iterating through azFile[] */
16683   int rc;                         /* Return code */
16684   const char *zTab = 0;           /* SQL table into which to insert */
16685   char *zSql;
16686   char zTemp[50];
16687   char *zExists = 0;
16688
16689   arExecSql(pAr, "PRAGMA page_size=512");
16690   rc = arExecSql(pAr, "SAVEPOINT ar;");
16691   if( rc!=SQLITE_OK ) return rc;
16692   zTemp[0] = 0; 
16693   if( pAr->bZip ){
16694     /* Initialize the zipfile virtual table, if necessary */
16695     if( pAr->zFile ){
16696       sqlite3_uint64 r;
16697       sqlite3_randomness(sizeof(r),&r);
16698       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
16699       zTab = zTemp;
16700       zSql = sqlite3_mprintf(
16701          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
16702          zTab, pAr->zFile
16703       );
16704       rc = arExecSql(pAr, zSql);
16705       sqlite3_free(zSql);
16706     }else{
16707       zTab = "zip";
16708     }
16709   }else{
16710     /* Initialize the table for an SQLAR */
16711     zTab = "sqlar";
16712     if( bUpdate==0 ){
16713       rc = arExecSql(pAr, zDrop);
16714       if( rc!=SQLITE_OK ) goto end_ar_transaction;
16715     }
16716     rc = arExecSql(pAr, zCreate);
16717   }
16718   if( bOnlyIfChanged ){
16719     zExists = sqlite3_mprintf(
16720       " AND NOT EXISTS("
16721           "SELECT 1 FROM %s AS mem"
16722           " WHERE mem.name=disk.name"
16723           " AND mem.mtime=disk.mtime"
16724           " AND mem.mode=disk.mode)", zTab);
16725   }else{
16726     zExists = sqlite3_mprintf("");
16727   }
16728   if( zExists==0 ) rc = SQLITE_NOMEM;
16729   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
16730     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
16731         pAr->bVerbose ? "shell_putsnl(name)" : "name",
16732         pAr->azArg[i], pAr->zDir, zExists);
16733     rc = arExecSql(pAr, zSql2);
16734     sqlite3_free(zSql2);
16735   }
16736 end_ar_transaction:
16737   if( rc!=SQLITE_OK ){
16738     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
16739   }else{
16740     rc = arExecSql(pAr, "RELEASE ar;");
16741     if( pAr->bZip && pAr->zFile ){
16742       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
16743       arExecSql(pAr, zSql);
16744       sqlite3_free(zSql);
16745     }
16746   }
16747   sqlite3_free(zExists);
16748   return rc;
16749 }
16750
16751 /*
16752 ** Implementation of ".ar" dot command.
16753 */
16754 static int arDotCommand(
16755   ShellState *pState,          /* Current shell tool state */
16756   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
16757   char **azArg,                /* Array of arguments passed to dot command */
16758   int nArg                     /* Number of entries in azArg[] */
16759 ){
16760   ArCommand cmd;
16761   int rc;
16762   memset(&cmd, 0, sizeof(cmd));
16763   cmd.fromCmdLine = fromCmdLine;
16764   rc = arParseCommand(azArg, nArg, &cmd);
16765   if( rc==SQLITE_OK ){
16766     int eDbType = SHELL_OPEN_UNSPEC;
16767     cmd.p = pState;
16768     cmd.db = pState->db;
16769     if( cmd.zFile ){
16770       eDbType = deduceDatabaseType(cmd.zFile, 1);
16771     }else{
16772       eDbType = pState->openMode;
16773     }
16774     if( eDbType==SHELL_OPEN_ZIPFILE ){
16775       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
16776         if( cmd.zFile==0 ){
16777           cmd.zSrcTable = sqlite3_mprintf("zip");
16778         }else{
16779           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
16780         }
16781       }
16782       cmd.bZip = 1;
16783     }else if( cmd.zFile ){
16784       int flags;
16785       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
16786       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 
16787            || cmd.eCmd==AR_CMD_UPDATE ){
16788         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
16789       }else{
16790         flags = SQLITE_OPEN_READONLY;
16791       }
16792       cmd.db = 0;
16793       if( cmd.bDryRun ){
16794         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
16795              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
16796       }
16797       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 
16798              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
16799       if( rc!=SQLITE_OK ){
16800         utf8_printf(stderr, "cannot open file: %s (%s)\n", 
16801             cmd.zFile, sqlite3_errmsg(cmd.db)
16802         );
16803         goto end_ar_command;
16804       }
16805       sqlite3_fileio_init(cmd.db, 0, 0);
16806       sqlite3_sqlar_init(cmd.db, 0, 0);
16807       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
16808                               shellPutsFunc, 0, 0);
16809
16810     }
16811     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
16812       if( cmd.eCmd!=AR_CMD_CREATE
16813        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
16814       ){
16815         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
16816         rc = SQLITE_ERROR;
16817         goto end_ar_command;
16818       }
16819       cmd.zSrcTable = sqlite3_mprintf("sqlar");
16820     }
16821
16822     switch( cmd.eCmd ){
16823       case AR_CMD_CREATE:
16824         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
16825         break;
16826
16827       case AR_CMD_EXTRACT:
16828         rc = arExtractCommand(&cmd);
16829         break;
16830
16831       case AR_CMD_LIST:
16832         rc = arListCommand(&cmd);
16833         break;
16834
16835       case AR_CMD_HELP:
16836         arUsage(pState->out);
16837         break;
16838
16839       case AR_CMD_INSERT:
16840         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
16841         break;
16842
16843       default:
16844         assert( cmd.eCmd==AR_CMD_UPDATE );
16845         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
16846         break;
16847     }
16848   }
16849 end_ar_command:
16850   if( cmd.db!=pState->db ){
16851     close_db(cmd.db);
16852   }
16853   sqlite3_free(cmd.zSrcTable);
16854
16855   return rc;
16856 }
16857 /* End of the ".archive" or ".ar" command logic
16858 *******************************************************************************/
16859 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
16860
16861 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
16862 /*
16863 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
16864 ** Otherwise, the SQL statement or statements in zSql are executed using
16865 ** database connection db and the error code written to *pRc before
16866 ** this function returns.
16867 */
16868 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
16869   int rc = *pRc;
16870   if( rc==SQLITE_OK ){
16871     char *zErr = 0;
16872     rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
16873     if( rc!=SQLITE_OK ){
16874       raw_printf(stderr, "SQL error: %s\n", zErr);
16875     }
16876     *pRc = rc;
16877   }
16878 }
16879
16880 /*
16881 ** Like shellExec(), except that zFmt is a printf() style format string.
16882 */
16883 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
16884   char *z = 0;
16885   if( *pRc==SQLITE_OK ){
16886     va_list ap;
16887     va_start(ap, zFmt);
16888     z = sqlite3_vmprintf(zFmt, ap);
16889     va_end(ap);
16890     if( z==0 ){
16891       *pRc = SQLITE_NOMEM;
16892     }else{
16893       shellExec(db, pRc, z);
16894     }
16895     sqlite3_free(z);
16896   }
16897 }
16898
16899 /*
16900 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
16901 ** Otherwise, an attempt is made to allocate, zero and return a pointer
16902 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
16903 ** to SQLITE_NOMEM and NULL returned.
16904 */
16905 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
16906   void *pRet = 0;
16907   if( *pRc==SQLITE_OK ){
16908     pRet = sqlite3_malloc64(nByte);
16909     if( pRet==0 ){
16910       *pRc = SQLITE_NOMEM;
16911     }else{
16912       memset(pRet, 0, nByte);
16913     }
16914   }
16915   return pRet;
16916 }
16917
16918 /*
16919 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
16920 ** Otherwise, zFmt is treated as a printf() style string. The result of
16921 ** formatting it along with any trailing arguments is written into a 
16922 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
16923 ** It is the responsibility of the caller to eventually free this buffer
16924 ** using a call to sqlite3_free().
16925 ** 
16926 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 
16927 ** pointer returned.
16928 */
16929 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
16930   char *z = 0;
16931   if( *pRc==SQLITE_OK ){
16932     va_list ap;
16933     va_start(ap, zFmt);
16934     z = sqlite3_vmprintf(zFmt, ap);
16935     va_end(ap);
16936     if( z==0 ){
16937       *pRc = SQLITE_NOMEM;
16938     }
16939   }
16940   return z;
16941 }
16942
16943 /*
16944 ** When running the ".recover" command, each output table, and the special
16945 ** orphaned row table if it is required, is represented by an instance
16946 ** of the following struct.
16947 */
16948 typedef struct RecoverTable RecoverTable;
16949 struct RecoverTable {
16950   char *zQuoted;                  /* Quoted version of table name */
16951   int nCol;                       /* Number of columns in table */
16952   char **azlCol;                  /* Array of column lists */
16953   int iPk;                        /* Index of IPK column */
16954 };
16955
16956 /*
16957 ** Free a RecoverTable object allocated by recoverFindTable() or
16958 ** recoverOrphanTable().
16959 */
16960 static void recoverFreeTable(RecoverTable *pTab){
16961   if( pTab ){
16962     sqlite3_free(pTab->zQuoted);
16963     if( pTab->azlCol ){
16964       int i;
16965       for(i=0; i<=pTab->nCol; i++){
16966         sqlite3_free(pTab->azlCol[i]);
16967       }
16968       sqlite3_free(pTab->azlCol);
16969     }
16970     sqlite3_free(pTab);
16971   }
16972 }
16973
16974 /*
16975 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
16976 ** Otherwise, it allocates and returns a RecoverTable object based on the
16977 ** final four arguments passed to this function. It is the responsibility
16978 ** of the caller to eventually free the returned object using
16979 ** recoverFreeTable().
16980 */
16981 static RecoverTable *recoverNewTable(
16982   int *pRc,                       /* IN/OUT: Error code */
16983   const char *zName,              /* Name of table */
16984   const char *zSql,               /* CREATE TABLE statement */
16985   int bIntkey, 
16986   int nCol
16987 ){
16988   sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
16989   int rc = *pRc;
16990   RecoverTable *pTab = 0;
16991
16992   pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
16993   if( rc==SQLITE_OK ){
16994     int nSqlCol = 0;
16995     int bSqlIntkey = 0;
16996     sqlite3_stmt *pStmt = 0;
16997     
16998     rc = sqlite3_open("", &dbtmp);
16999     if( rc==SQLITE_OK ){
17000       sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
17001                               shellIdQuote, 0, 0);
17002     }
17003     if( rc==SQLITE_OK ){
17004       rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
17005     }
17006     if( rc==SQLITE_OK ){
17007       rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
17008       if( rc==SQLITE_ERROR ){
17009         rc = SQLITE_OK;
17010         goto finished;
17011       }
17012     }
17013     shellPreparePrintf(dbtmp, &rc, &pStmt, 
17014         "SELECT count(*) FROM pragma_table_info(%Q)", zName
17015     );
17016     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17017       nSqlCol = sqlite3_column_int(pStmt, 0);
17018     }
17019     shellFinalize(&rc, pStmt);
17020
17021     if( rc!=SQLITE_OK || nSqlCol<nCol ){
17022       goto finished;
17023     }
17024
17025     shellPreparePrintf(dbtmp, &rc, &pStmt, 
17026       "SELECT ("
17027       "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
17028       ") FROM sqlite_schema WHERE name = %Q", zName
17029     );
17030     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17031       bSqlIntkey = sqlite3_column_int(pStmt, 0);
17032     }
17033     shellFinalize(&rc, pStmt);
17034
17035     if( bIntkey==bSqlIntkey ){
17036       int i;
17037       const char *zPk = "_rowid_";
17038       sqlite3_stmt *pPkFinder = 0;
17039
17040       /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
17041       ** set zPk to the name of the PK column, and pTab->iPk to the index
17042       ** of the column, where columns are 0-numbered from left to right.
17043       ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
17044       ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
17045       pTab->iPk = -2;
17046       if( bIntkey ){
17047         shellPreparePrintf(dbtmp, &rc, &pPkFinder, 
17048           "SELECT cid, name FROM pragma_table_info(%Q) "
17049           "  WHERE pk=1 AND type='integer' COLLATE nocase"
17050           "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
17051           , zName, zName
17052         );
17053         if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
17054           pTab->iPk = sqlite3_column_int(pPkFinder, 0);
17055           zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
17056         }
17057       }
17058
17059       pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
17060       pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
17061       pTab->nCol = nSqlCol;
17062
17063       if( bIntkey ){
17064         pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
17065       }else{
17066         pTab->azlCol[0] = shellMPrintf(&rc, "");
17067       }
17068       i = 1;
17069       shellPreparePrintf(dbtmp, &rc, &pStmt, 
17070           "SELECT %Q || group_concat(shell_idquote(name), ', ') "
17071           "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
17072           "FROM pragma_table_info(%Q)", 
17073           bIntkey ? ", " : "", pTab->iPk, 
17074           bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
17075           zName
17076       );
17077       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17078         const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
17079         pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
17080         i++;
17081       }
17082       shellFinalize(&rc, pStmt);
17083
17084       shellFinalize(&rc, pPkFinder);
17085     }
17086   }
17087
17088  finished:
17089   sqlite3_close(dbtmp);
17090   *pRc = rc;
17091   if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
17092     recoverFreeTable(pTab);
17093     pTab = 0;
17094   }
17095   return pTab;
17096 }
17097
17098 /*
17099 ** This function is called to search the schema recovered from the
17100 ** sqlite_schema table of the (possibly) corrupt database as part
17101 ** of a ".recover" command. Specifically, for a table with root page
17102 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
17103 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
17104 ** those.
17105 **
17106 ** If a table is found, a (RecoverTable*) object is returned. Or, if
17107 ** no such table is found, but bIntkey is false and iRoot is the 
17108 ** root page of an index in the recovered schema, then (*pbNoop) is
17109 ** set to true and NULL returned. Or, if there is no such table or
17110 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
17111 ** the caller should write data to the orphans table.
17112 */
17113 static RecoverTable *recoverFindTable(
17114   ShellState *pState,             /* Shell state object */
17115   int *pRc,                       /* IN/OUT: Error code */
17116   int iRoot,                      /* Root page of table */
17117   int bIntkey,                    /* True for an intkey table */
17118   int nCol,                       /* Number of columns in table */
17119   int *pbNoop                     /* OUT: True if iRoot is root of index */
17120 ){
17121   sqlite3_stmt *pStmt = 0;
17122   RecoverTable *pRet = 0;
17123   int bNoop = 0;
17124   const char *zSql = 0;
17125   const char *zName = 0;
17126
17127   /* Search the recovered schema for an object with root page iRoot. */
17128   shellPreparePrintf(pState->db, pRc, &pStmt,
17129       "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
17130   );
17131   while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17132     const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
17133     if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
17134       bNoop = 1;
17135       break;
17136     }
17137     if( sqlite3_stricmp(zType, "table")==0 ){
17138       zName = (const char*)sqlite3_column_text(pStmt, 1);
17139       zSql = (const char*)sqlite3_column_text(pStmt, 2);
17140       pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
17141       break;
17142     }
17143   }
17144
17145   shellFinalize(pRc, pStmt);
17146   *pbNoop = bNoop;
17147   return pRet;
17148 }
17149
17150 /*
17151 ** Return a RecoverTable object representing the orphans table.
17152 */
17153 static RecoverTable *recoverOrphanTable(
17154   ShellState *pState,             /* Shell state object */
17155   int *pRc,                       /* IN/OUT: Error code */
17156   const char *zLostAndFound,      /* Base name for orphans table */
17157   int nCol                        /* Number of user data columns */
17158 ){
17159   RecoverTable *pTab = 0;
17160   if( nCol>=0 && *pRc==SQLITE_OK ){
17161     int i;
17162
17163     /* This block determines the name of the orphan table. The prefered
17164     ** name is zLostAndFound. But if that clashes with another name
17165     ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
17166     ** and so on until a non-clashing name is found.  */
17167     int iTab = 0;
17168     char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
17169     sqlite3_stmt *pTest = 0;
17170     shellPrepare(pState->db, pRc,
17171         "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
17172     );
17173     if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
17174     while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
17175       shellReset(pRc, pTest);
17176       sqlite3_free(zTab);
17177       zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
17178       sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
17179     }
17180     shellFinalize(pRc, pTest);
17181
17182     pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
17183     if( pTab ){
17184       pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
17185       pTab->nCol = nCol;
17186       pTab->iPk = -2;
17187       if( nCol>0 ){
17188         pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
17189         if( pTab->azlCol ){
17190           pTab->azlCol[nCol] = shellMPrintf(pRc, "");
17191           for(i=nCol-1; i>=0; i--){
17192             pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
17193           }
17194         }
17195       }
17196
17197       if( *pRc!=SQLITE_OK ){
17198         recoverFreeTable(pTab);
17199         pTab = 0;
17200       }else{
17201         raw_printf(pState->out, 
17202             "CREATE TABLE %s(rootpgno INTEGER, "
17203             "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
17204         );
17205         for(i=0; i<nCol; i++){
17206           raw_printf(pState->out, ", c%d", i);
17207         }
17208         raw_printf(pState->out, ");\n");
17209       }
17210     }
17211     sqlite3_free(zTab);
17212   }
17213   return pTab;
17214 }
17215
17216 /*
17217 ** This function is called to recover data from the database. A script
17218 ** to construct a new database containing all recovered data is output
17219 ** on stream pState->out.
17220 */
17221 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
17222   int rc = SQLITE_OK;
17223   sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
17224   sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
17225   sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
17226   const char *zRecoveryDb = "";   /* Name of "recovery" database */
17227   const char *zLostAndFound = "lost_and_found";
17228   int i;
17229   int nOrphan = -1;
17230   RecoverTable *pOrphan = 0;
17231
17232   int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
17233   int bRowids = 1;                /* 0 if --no-rowids */
17234   for(i=1; i<nArg; i++){
17235     char *z = azArg[i];
17236     int n;
17237     if( z[0]=='-' && z[1]=='-' ) z++;
17238     n = strlen30(z);
17239     if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
17240       bFreelist = 0;
17241     }else
17242     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
17243       i++;
17244       zRecoveryDb = azArg[i];
17245     }else
17246     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
17247       i++;
17248       zLostAndFound = azArg[i];
17249     }else
17250     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
17251       bRowids = 0;
17252     }
17253     else{
17254       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 
17255       showHelp(pState->out, azArg[0]);
17256       return 1;
17257     }
17258   }
17259
17260   shellExecPrintf(pState->db, &rc,
17261     /* Attach an in-memory database named 'recovery'. Create an indexed 
17262     ** cache of the sqlite_dbptr virtual table. */
17263     "PRAGMA writable_schema = on;"
17264     "ATTACH %Q AS recovery;"
17265     "DROP TABLE IF EXISTS recovery.dbptr;"
17266     "DROP TABLE IF EXISTS recovery.freelist;"
17267     "DROP TABLE IF EXISTS recovery.map;"
17268     "DROP TABLE IF EXISTS recovery.schema;"
17269     "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
17270   );
17271
17272   if( bFreelist ){
17273     shellExec(pState->db, &rc,
17274       "WITH trunk(pgno) AS ("
17275       "  SELECT shell_int32("
17276       "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
17277       "      WHERE x>0"
17278       "    UNION"
17279       "  SELECT shell_int32("
17280       "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
17281       "      FROM trunk WHERE x>0"
17282       "),"
17283       "freelist(data, n, freepgno) AS ("
17284       "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
17285       "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
17286       "    UNION ALL"
17287       "  SELECT data, n-1, shell_int32(data, 2+n) "
17288       "      FROM freelist WHERE n>=0"
17289       ")"
17290       "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
17291     );
17292   }
17293
17294   /* If this is an auto-vacuum database, add all pointer-map pages to
17295   ** the freelist table. Do this regardless of whether or not 
17296   ** --freelist-corrupt was specified.  */
17297   shellExec(pState->db, &rc, 
17298     "WITH ptrmap(pgno) AS ("
17299     "  SELECT 2 WHERE shell_int32("
17300     "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
17301     "  )"
17302     "    UNION ALL "
17303     "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
17304     "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
17305     ")"
17306     "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
17307   );
17308
17309   shellExec(pState->db, &rc, 
17310     "CREATE TABLE recovery.dbptr("
17311     "      pgno, child, PRIMARY KEY(child, pgno)"
17312     ") WITHOUT ROWID;"
17313     "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
17314     "    SELECT * FROM sqlite_dbptr"
17315     "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
17316
17317     /* Delete any pointer to page 1. This ensures that page 1 is considered
17318     ** a root page, regardless of how corrupt the db is. */
17319     "DELETE FROM recovery.dbptr WHERE child = 1;"
17320
17321     /* Delete all pointers to any pages that have more than one pointer
17322     ** to them. Such pages will be treated as root pages when recovering
17323     ** data.  */
17324     "DELETE FROM recovery.dbptr WHERE child IN ("
17325     "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
17326     ");"
17327
17328     /* Create the "map" table that will (eventually) contain instructions
17329     ** for dealing with each page in the db that contains one or more 
17330     ** records. */
17331     "CREATE TABLE recovery.map("
17332       "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
17333     ");"
17334
17335     /* Populate table [map]. If there are circular loops of pages in the
17336     ** database, the following adds all pages in such a loop to the map
17337     ** as individual root pages. This could be handled better.  */
17338     "WITH pages(i, maxlen) AS ("
17339     "  SELECT page_count, ("
17340     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
17341     "  ) FROM pragma_page_count WHERE page_count>0"
17342     "    UNION ALL"
17343     "  SELECT i-1, ("
17344     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
17345     "  ) FROM pages WHERE i>=2"
17346     ")"
17347     "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
17348     "  SELECT i, maxlen, NULL, ("
17349     "    WITH p(orig, pgno, parent) AS ("
17350     "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
17351     "        UNION "
17352     "      SELECT i, p.parent, "
17353     "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
17354     "    )"
17355     "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
17356     ") "
17357     "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
17358     "UPDATE recovery.map AS o SET intkey = ("
17359     "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
17360     ");"
17361
17362     /* Extract data from page 1 and any linked pages into table
17363     ** recovery.schema. With the same schema as an sqlite_schema table.  */
17364     "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
17365     "INSERT INTO recovery.schema SELECT "
17366     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
17367     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
17368     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
17369     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
17370     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
17371     "FROM sqlite_dbdata WHERE pgno IN ("
17372     "  SELECT pgno FROM recovery.map WHERE root=1"
17373     ")"
17374     "GROUP BY pgno, cell;"
17375     "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
17376   );
17377
17378   /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 
17379   ** CREATE TABLE statements that extracted from the existing schema.  */
17380   if( rc==SQLITE_OK ){
17381     sqlite3_stmt *pStmt = 0;
17382     /* ".recover" might output content in an order which causes immediate
17383     ** foreign key constraints to be violated. So disable foreign-key
17384     ** constraint enforcement to prevent problems when running the output
17385     ** script. */
17386     raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
17387     raw_printf(pState->out, "BEGIN;\n");
17388     raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
17389     shellPrepare(pState->db, &rc,
17390         "SELECT sql FROM recovery.schema "
17391         "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
17392     );
17393     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17394       const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
17395       raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 
17396           &zCreateTable[12]
17397       );
17398     }
17399     shellFinalize(&rc, pStmt);
17400   }
17401
17402   /* Figure out if an orphan table will be required. And if so, how many
17403   ** user columns it should contain */
17404   shellPrepare(pState->db, &rc, 
17405       "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
17406       , &pLoop
17407   );
17408   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
17409     nOrphan = sqlite3_column_int(pLoop, 0);
17410   }
17411   shellFinalize(&rc, pLoop);
17412   pLoop = 0;
17413
17414   shellPrepare(pState->db, &rc,
17415       "SELECT pgno FROM recovery.map WHERE root=?", &pPages
17416   );
17417
17418   shellPrepare(pState->db, &rc,
17419       "SELECT max(field), group_concat(shell_escape_crnl(quote"
17420       "(case when (? AND field<0) then NULL else value end)"
17421       "), ', ')"
17422       ", min(field) "
17423       "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
17424       "GROUP BY cell", &pCells
17425   );
17426
17427   /* Loop through each root page. */
17428   shellPrepare(pState->db, &rc, 
17429       "SELECT root, intkey, max(maxlen) FROM recovery.map" 
17430       " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
17431       "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
17432       ")", &pLoop
17433   );
17434   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
17435     int iRoot = sqlite3_column_int(pLoop, 0);
17436     int bIntkey = sqlite3_column_int(pLoop, 1);
17437     int nCol = sqlite3_column_int(pLoop, 2);
17438     int bNoop = 0;
17439     RecoverTable *pTab;
17440
17441     assert( bIntkey==0 || bIntkey==1 );
17442     pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
17443     if( bNoop || rc ) continue;
17444     if( pTab==0 ){
17445       if( pOrphan==0 ){
17446         pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
17447       }
17448       pTab = pOrphan;
17449       if( pTab==0 ) break;
17450     }
17451
17452     if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
17453       raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
17454     }
17455     sqlite3_bind_int(pPages, 1, iRoot);
17456     if( bRowids==0 && pTab->iPk<0 ){
17457       sqlite3_bind_int(pCells, 1, 1);
17458     }else{
17459       sqlite3_bind_int(pCells, 1, 0);
17460     }
17461     sqlite3_bind_int(pCells, 3, pTab->iPk);
17462
17463     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
17464       int iPgno = sqlite3_column_int(pPages, 0);
17465       sqlite3_bind_int(pCells, 2, iPgno);
17466       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
17467         int nField = sqlite3_column_int(pCells, 0);
17468         int iMin = sqlite3_column_int(pCells, 2);
17469         const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
17470
17471         RecoverTable *pTab2 = pTab;
17472         if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
17473           if( pOrphan==0 ){
17474             pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
17475           }
17476           pTab2 = pOrphan;
17477           if( pTab2==0 ) break;
17478         }
17479
17480         nField = nField+1;
17481         if( pTab2==pOrphan ){
17482           raw_printf(pState->out, 
17483               "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
17484               pTab2->zQuoted, iRoot, iPgno, nField,
17485               iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
17486           );
17487         }else{
17488           raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 
17489               pTab2->zQuoted, pTab2->azlCol[nField], zVal
17490           );
17491         }
17492       }
17493       shellReset(&rc, pCells);
17494     }
17495     shellReset(&rc, pPages);
17496     if( pTab!=pOrphan ) recoverFreeTable(pTab);
17497   }
17498   shellFinalize(&rc, pLoop);
17499   shellFinalize(&rc, pPages);
17500   shellFinalize(&rc, pCells);
17501   recoverFreeTable(pOrphan);
17502
17503   /* The rest of the schema */
17504   if( rc==SQLITE_OK ){
17505     sqlite3_stmt *pStmt = 0;
17506     shellPrepare(pState->db, &rc, 
17507         "SELECT sql, name FROM recovery.schema "
17508         "WHERE sql NOT LIKE 'create table%'", &pStmt
17509     );
17510     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17511       const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
17512       if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
17513         const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
17514         char *zPrint = shellMPrintf(&rc, 
17515           "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
17516           zName, zName, zSql
17517         );
17518         raw_printf(pState->out, "%s;\n", zPrint);
17519         sqlite3_free(zPrint);
17520       }else{
17521         raw_printf(pState->out, "%s;\n", zSql);
17522       }
17523     }
17524     shellFinalize(&rc, pStmt);
17525   }
17526
17527   if( rc==SQLITE_OK ){
17528     raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
17529     raw_printf(pState->out, "COMMIT;\n");
17530   }
17531   sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
17532   return rc;
17533 }
17534 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
17535
17536
17537 /*
17538 ** If an input line begins with "." then invoke this routine to
17539 ** process that line.
17540 **
17541 ** Return 1 on error, 2 to exit, and 0 otherwise.
17542 */
17543 static int do_meta_command(char *zLine, ShellState *p){
17544   int h = 1;
17545   int nArg = 0;
17546   int n, c;
17547   int rc = 0;
17548   char *azArg[52];
17549
17550 #ifndef SQLITE_OMIT_VIRTUALTABLE
17551   if( p->expert.pExpert ){
17552     expertFinish(p, 1, 0);
17553   }
17554 #endif
17555
17556   /* Parse the input line into tokens.
17557   */
17558   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
17559     while( IsSpace(zLine[h]) ){ h++; }
17560     if( zLine[h]==0 ) break;
17561     if( zLine[h]=='\'' || zLine[h]=='"' ){
17562       int delim = zLine[h++];
17563       azArg[nArg++] = &zLine[h];
17564       while( zLine[h] && zLine[h]!=delim ){
17565         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
17566         h++;
17567       }
17568       if( zLine[h]==delim ){
17569         zLine[h++] = 0;
17570       }
17571       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
17572     }else{
17573       azArg[nArg++] = &zLine[h];
17574       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
17575       if( zLine[h] ) zLine[h++] = 0;
17576       resolve_backslashes(azArg[nArg-1]);
17577     }
17578   }
17579   azArg[nArg] = 0;
17580
17581   /* Process the input line.
17582   */
17583   if( nArg==0 ) return 0; /* no tokens, no error */
17584   n = strlen30(azArg[0]);
17585   c = azArg[0][0];
17586   clearTempFile(p);
17587
17588 #ifndef SQLITE_OMIT_AUTHORIZATION
17589   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
17590     if( nArg!=2 ){
17591       raw_printf(stderr, "Usage: .auth ON|OFF\n");
17592       rc = 1;
17593       goto meta_command_exit;
17594     }
17595     open_db(p, 0);
17596     if( booleanValue(azArg[1]) ){
17597       sqlite3_set_authorizer(p->db, shellAuth, p);
17598     }else{
17599       sqlite3_set_authorizer(p->db, 0, 0);
17600     }
17601   }else
17602 #endif
17603
17604 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
17605   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
17606     open_db(p, 0);
17607     rc = arDotCommand(p, 0, azArg, nArg);
17608   }else
17609 #endif
17610
17611   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
17612    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
17613   ){
17614     const char *zDestFile = 0;
17615     const char *zDb = 0;
17616     sqlite3 *pDest;
17617     sqlite3_backup *pBackup;
17618     int j;
17619     int bAsync = 0;
17620     const char *zVfs = 0;
17621     for(j=1; j<nArg; j++){
17622       const char *z = azArg[j];
17623       if( z[0]=='-' ){
17624         if( z[1]=='-' ) z++;
17625         if( strcmp(z, "-append")==0 ){
17626           zVfs = "apndvfs";
17627         }else
17628         if( strcmp(z, "-async")==0 ){
17629           bAsync = 1;
17630         }else
17631         {
17632           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
17633           return 1;
17634         }
17635       }else if( zDestFile==0 ){
17636         zDestFile = azArg[j];
17637       }else if( zDb==0 ){
17638         zDb = zDestFile;
17639         zDestFile = azArg[j];
17640       }else{
17641         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
17642         return 1;
17643       }
17644     }
17645     if( zDestFile==0 ){
17646       raw_printf(stderr, "missing FILENAME argument on .backup\n");
17647       return 1;
17648     }
17649     if( zDb==0 ) zDb = "main";
17650     rc = sqlite3_open_v2(zDestFile, &pDest, 
17651                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
17652     if( rc!=SQLITE_OK ){
17653       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
17654       close_db(pDest);
17655       return 1;
17656     }
17657     if( bAsync ){
17658       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
17659                    0, 0, 0);
17660     }
17661     open_db(p, 0);
17662     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
17663     if( pBackup==0 ){
17664       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
17665       close_db(pDest);
17666       return 1;
17667     }
17668     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
17669     sqlite3_backup_finish(pBackup);
17670     if( rc==SQLITE_DONE ){
17671       rc = 0;
17672     }else{
17673       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
17674       rc = 1;
17675     }
17676     close_db(pDest);
17677   }else
17678
17679   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
17680     if( nArg==2 ){
17681       bail_on_error = booleanValue(azArg[1]);
17682     }else{
17683       raw_printf(stderr, "Usage: .bail on|off\n");
17684       rc = 1;
17685     }
17686   }else
17687
17688   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
17689     if( nArg==2 ){
17690       if( booleanValue(azArg[1]) ){
17691         setBinaryMode(p->out, 1);
17692       }else{
17693         setTextMode(p->out, 1);
17694       }
17695     }else{
17696       raw_printf(stderr, "Usage: .binary on|off\n");
17697       rc = 1;
17698     }
17699   }else
17700
17701   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
17702     if( nArg==2 ){
17703 #if defined(_WIN32) || defined(WIN32)
17704       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
17705       rc = !SetCurrentDirectoryW(z);
17706       sqlite3_free(z);
17707 #else
17708       rc = chdir(azArg[1]);
17709 #endif
17710       if( rc ){
17711         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
17712         rc = 1;
17713       }
17714     }else{
17715       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
17716       rc = 1;
17717     }
17718   }else
17719
17720   /* The undocumented ".breakpoint" command causes a call to the no-op
17721   ** routine named test_breakpoint().
17722   */
17723   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
17724     test_breakpoint();
17725   }else
17726
17727   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
17728     if( nArg==2 ){
17729       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
17730     }else{
17731       raw_printf(stderr, "Usage: .changes on|off\n");
17732       rc = 1;
17733     }
17734   }else
17735
17736   /* Cancel output redirection, if it is currently set (by .testcase)
17737   ** Then read the content of the testcase-out.txt file and compare against
17738   ** azArg[1].  If there are differences, report an error and exit.
17739   */
17740   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
17741     char *zRes = 0;
17742     output_reset(p);
17743     if( nArg!=2 ){
17744       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
17745       rc = 2;
17746     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
17747       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
17748       rc = 2;
17749     }else if( testcase_glob(azArg[1],zRes)==0 ){
17750       utf8_printf(stderr,
17751                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
17752                  p->zTestcase, azArg[1], zRes);
17753       rc = 1;
17754     }else{
17755       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
17756       p->nCheck++;
17757     }
17758     sqlite3_free(zRes);
17759   }else
17760
17761   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
17762     if( nArg==2 ){
17763       tryToClone(p, azArg[1]);
17764     }else{
17765       raw_printf(stderr, "Usage: .clone FILENAME\n");
17766       rc = 1;
17767     }
17768   }else
17769
17770   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
17771     char **azName = 0;
17772     int nName = 0;
17773     sqlite3_stmt *pStmt;
17774     int i;
17775     open_db(p, 0);
17776     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
17777     if( rc ){
17778       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
17779       rc = 1;
17780     }else{
17781       while( sqlite3_step(pStmt)==SQLITE_ROW ){
17782         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
17783         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
17784         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
17785         if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
17786         azName[nName*2] = strdup(zSchema);
17787         azName[nName*2+1] = strdup(zFile);
17788         nName++;
17789       }
17790     }
17791     sqlite3_finalize(pStmt);
17792     for(i=0; i<nName; i++){
17793       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
17794       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
17795       const char *z = azName[i*2+1];
17796       utf8_printf(p->out, "%s: %s %s%s\n",
17797          azName[i*2],
17798          z && z[0] ? z : "\"\"",
17799          bRdonly ? "r/o" : "r/w",
17800          eTxn==SQLITE_TXN_NONE ? "" :
17801             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
17802       free(azName[i*2]);
17803       free(azName[i*2+1]);
17804     }
17805     sqlite3_free(azName);
17806   }else
17807
17808   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
17809     static const struct DbConfigChoices {
17810       const char *zName;
17811       int op;
17812     } aDbConfig[] = {
17813         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
17814         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
17815         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
17816         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
17817         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
17818         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
17819         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
17820         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
17821         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
17822         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
17823         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
17824         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
17825         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
17826         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
17827         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
17828         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
17829     };
17830     int ii, v;
17831     open_db(p, 0);
17832     for(ii=0; ii<ArraySize(aDbConfig); ii++){
17833       if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
17834       if( nArg>=3 ){
17835         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
17836       }
17837       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
17838       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
17839       if( nArg>1 ) break;
17840     }
17841     if( nArg>1 && ii==ArraySize(aDbConfig) ){
17842       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
17843       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
17844     }   
17845   }else
17846
17847   if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
17848     rc = shell_dbinfo_command(p, nArg, azArg);
17849   }else
17850
17851 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
17852   if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
17853     open_db(p, 0);
17854     rc = recoverDatabaseCmd(p, nArg, azArg);
17855   }else
17856 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
17857
17858   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
17859     char *zLike = 0;
17860     char *zSql;
17861     int i;
17862     int savedShowHeader = p->showHeader;
17863     int savedShellFlags = p->shellFlgs;
17864     ShellClearFlag(p, 
17865        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
17866        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
17867     for(i=1; i<nArg; i++){
17868       if( azArg[i][0]=='-' ){
17869         const char *z = azArg[i]+1;
17870         if( z[0]=='-' ) z++;
17871         if( strcmp(z,"preserve-rowids")==0 ){
17872 #ifdef SQLITE_OMIT_VIRTUALTABLE
17873           raw_printf(stderr, "The --preserve-rowids option is not compatible"
17874                              " with SQLITE_OMIT_VIRTUALTABLE\n");
17875           rc = 1;
17876           sqlite3_free(zLike);
17877           goto meta_command_exit;
17878 #else
17879           ShellSetFlag(p, SHFLG_PreserveRowid);
17880 #endif
17881         }else
17882         if( strcmp(z,"newlines")==0 ){
17883           ShellSetFlag(p, SHFLG_Newlines);
17884         }else
17885         if( strcmp(z,"data-only")==0 ){
17886           ShellSetFlag(p, SHFLG_DumpDataOnly);
17887         }else
17888         if( strcmp(z,"nosys")==0 ){
17889           ShellSetFlag(p, SHFLG_DumpNoSys);
17890         }else
17891         {
17892           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
17893           rc = 1;
17894           sqlite3_free(zLike);
17895           goto meta_command_exit;
17896         }
17897       }else if( zLike ){
17898         zLike = sqlite3_mprintf("%z OR name LIKE %Q ESCAPE '\\'",
17899                 zLike, azArg[i]);
17900       }else{
17901         zLike = sqlite3_mprintf("name LIKE %Q ESCAPE '\\'", azArg[i]);
17902       }
17903     }
17904
17905     open_db(p, 0);
17906
17907     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
17908       /* When playing back a "dump", the content might appear in an order
17909       ** which causes immediate foreign key constraints to be violated.
17910       ** So disable foreign-key constraint enforcement to prevent problems. */
17911       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
17912       raw_printf(p->out, "BEGIN TRANSACTION;\n");
17913     }
17914     p->writableSchema = 0;
17915     p->showHeader = 0;
17916     /* Set writable_schema=ON since doing so forces SQLite to initialize
17917     ** as much of the schema as it can even if the sqlite_schema table is
17918     ** corrupt. */
17919     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
17920     p->nErr = 0;
17921     if( zLike==0 ) zLike = sqlite3_mprintf("true");
17922     zSql = sqlite3_mprintf(
17923       "SELECT name, type, sql FROM sqlite_schema "
17924       "WHERE (%s) AND type=='table'"
17925       "  AND sql NOT NULL"
17926       " ORDER BY tbl_name='sqlite_sequence', rowid",
17927       zLike
17928     );
17929     run_schema_dump_query(p,zSql);
17930     sqlite3_free(zSql);
17931     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
17932       zSql = sqlite3_mprintf(
17933         "SELECT sql FROM sqlite_schema "
17934         "WHERE (%s) AND sql NOT NULL"
17935         "  AND type IN ('index','trigger','view')",
17936         zLike
17937       );
17938       run_table_dump_query(p, zSql);
17939       sqlite3_free(zSql);
17940     }
17941     sqlite3_free(zLike);
17942     if( p->writableSchema ){
17943       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
17944       p->writableSchema = 0;
17945     }
17946     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
17947     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
17948     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
17949       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
17950     }
17951     p->showHeader = savedShowHeader;
17952     p->shellFlgs = savedShellFlags;
17953   }else
17954
17955   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
17956     if( nArg==2 ){
17957       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
17958     }else{
17959       raw_printf(stderr, "Usage: .echo on|off\n");
17960       rc = 1;
17961     }
17962   }else
17963
17964   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
17965     if( nArg==2 ){
17966       p->autoEQPtest = 0;
17967       if( p->autoEQPtrace ){
17968         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
17969         p->autoEQPtrace = 0;
17970       }
17971       if( strcmp(azArg[1],"full")==0 ){
17972         p->autoEQP = AUTOEQP_full;
17973       }else if( strcmp(azArg[1],"trigger")==0 ){
17974         p->autoEQP = AUTOEQP_trigger;
17975 #ifdef SQLITE_DEBUG
17976       }else if( strcmp(azArg[1],"test")==0 ){
17977         p->autoEQP = AUTOEQP_on;
17978         p->autoEQPtest = 1;
17979       }else if( strcmp(azArg[1],"trace")==0 ){
17980         p->autoEQP = AUTOEQP_full;
17981         p->autoEQPtrace = 1;
17982         open_db(p, 0);
17983         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
17984         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
17985 #endif
17986       }else{
17987         p->autoEQP = (u8)booleanValue(azArg[1]);
17988       }
17989     }else{
17990       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
17991       rc = 1;
17992     }
17993   }else
17994
17995   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
17996     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
17997     rc = 2;
17998   }else
17999
18000   /* The ".explain" command is automatic now.  It is largely pointless.  It
18001   ** retained purely for backwards compatibility */
18002   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
18003     int val = 1;
18004     if( nArg>=2 ){
18005       if( strcmp(azArg[1],"auto")==0 ){
18006         val = 99;
18007       }else{
18008         val =  booleanValue(azArg[1]);
18009       }
18010     }
18011     if( val==1 && p->mode!=MODE_Explain ){
18012       p->normalMode = p->mode;
18013       p->mode = MODE_Explain;
18014       p->autoExplain = 0;
18015     }else if( val==0 ){
18016       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
18017       p->autoExplain = 0;
18018     }else if( val==99 ){
18019       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
18020       p->autoExplain = 1;
18021     }
18022   }else
18023
18024 #ifndef SQLITE_OMIT_VIRTUALTABLE
18025   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
18026     open_db(p, 0);
18027     expertDotCommand(p, azArg, nArg);
18028   }else
18029 #endif
18030
18031   if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
18032     static const struct {
18033        const char *zCtrlName;   /* Name of a test-control option */
18034        int ctrlCode;            /* Integer code for that option */
18035        const char *zUsage;      /* Usage notes */
18036     } aCtrl[] = {
18037       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
18038       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
18039       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
18040       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
18041       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
18042    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
18043       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
18044       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
18045       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
18046       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
18047    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
18048     };
18049     int filectrl = -1;
18050     int iCtrl = -1;
18051     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
18052     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
18053     int n2, i;
18054     const char *zCmd = 0;
18055     const char *zSchema = 0;
18056
18057     open_db(p, 0);
18058     zCmd = nArg>=2 ? azArg[1] : "help";
18059
18060     if( zCmd[0]=='-' 
18061      && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
18062      && nArg>=4
18063     ){
18064       zSchema = azArg[2];
18065       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
18066       nArg -= 2;
18067       zCmd = azArg[1];
18068     }
18069
18070     /* The argument can optionally begin with "-" or "--" */
18071     if( zCmd[0]=='-' && zCmd[1] ){
18072       zCmd++;
18073       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
18074     }
18075
18076     /* --help lists all file-controls */
18077     if( strcmp(zCmd,"help")==0 ){
18078       utf8_printf(p->out, "Available file-controls:\n");
18079       for(i=0; i<ArraySize(aCtrl); i++){
18080         utf8_printf(p->out, "  .filectrl %s %s\n",
18081                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
18082       }
18083       rc = 1;
18084       goto meta_command_exit;
18085     }
18086
18087     /* convert filectrl text option to value. allow any unique prefix
18088     ** of the option name, or a numerical value. */
18089     n2 = strlen30(zCmd);
18090     for(i=0; i<ArraySize(aCtrl); i++){
18091       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
18092         if( filectrl<0 ){
18093           filectrl = aCtrl[i].ctrlCode;
18094           iCtrl = i;
18095         }else{
18096           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
18097                               "Use \".filectrl --help\" for help\n", zCmd);
18098           rc = 1;
18099           goto meta_command_exit;
18100         }
18101       }
18102     }
18103     if( filectrl<0 ){
18104       utf8_printf(stderr,"Error: unknown file-control: %s\n"
18105                          "Use \".filectrl --help\" for help\n", zCmd);
18106     }else{
18107       switch(filectrl){
18108         case SQLITE_FCNTL_SIZE_LIMIT: {
18109           if( nArg!=2 && nArg!=3 ) break;
18110           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
18111           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
18112           isOk = 1;
18113           break;
18114         }
18115         case SQLITE_FCNTL_LOCK_TIMEOUT:
18116         case SQLITE_FCNTL_CHUNK_SIZE: {
18117           int x;
18118           if( nArg!=3 ) break;
18119           x = (int)integerValue(azArg[2]);
18120           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18121           isOk = 2;
18122           break;
18123         }
18124         case SQLITE_FCNTL_PERSIST_WAL:
18125         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
18126           int x;
18127           if( nArg!=2 && nArg!=3 ) break;
18128           x = nArg==3 ? booleanValue(azArg[2]) : -1;
18129           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18130           iRes = x;
18131           isOk = 1;
18132           break;
18133         }
18134         case SQLITE_FCNTL_DATA_VERSION:
18135         case SQLITE_FCNTL_HAS_MOVED: {
18136           int x;
18137           if( nArg!=2 ) break;
18138           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18139           iRes = x;
18140           isOk = 1;
18141           break;
18142         }
18143         case SQLITE_FCNTL_TEMPFILENAME: {
18144           char *z = 0;
18145           if( nArg!=2 ) break;
18146           sqlite3_file_control(p->db, zSchema, filectrl, &z);
18147           if( z ){
18148             utf8_printf(p->out, "%s\n", z);
18149             sqlite3_free(z);
18150           }
18151           isOk = 2;
18152           break;
18153         }
18154         case SQLITE_FCNTL_RESERVE_BYTES: {
18155           int x;
18156           if( nArg>=3 ){
18157             x = atoi(azArg[2]);
18158             sqlite3_file_control(p->db, zSchema, filectrl, &x);
18159           }
18160           x = -1;
18161           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18162           utf8_printf(p->out,"%d\n", x);
18163           isOk = 2;
18164           break;
18165         }
18166       }
18167     }
18168     if( isOk==0 && iCtrl>=0 ){
18169       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
18170       rc = 1;
18171     }else if( isOk==1 ){
18172       char zBuf[100];
18173       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
18174       raw_printf(p->out, "%s\n", zBuf);
18175     }
18176   }else
18177
18178   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
18179     ShellState data;
18180     char *zErrMsg = 0;
18181     int doStats = 0;
18182     memcpy(&data, p, sizeof(data));
18183     data.showHeader = 0;
18184     data.cMode = data.mode = MODE_Semi;
18185     if( nArg==2 && optionMatch(azArg[1], "indent") ){
18186       data.cMode = data.mode = MODE_Pretty;
18187       nArg = 1;
18188     }
18189     if( nArg!=1 ){
18190       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
18191       rc = 1;
18192       goto meta_command_exit;
18193     }
18194     open_db(p, 0);
18195     rc = sqlite3_exec(p->db,
18196        "SELECT sql FROM"
18197        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
18198        "     FROM sqlite_schema UNION ALL"
18199        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
18200        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
18201        "ORDER BY rowid",
18202        callback, &data, &zErrMsg
18203     );
18204     if( rc==SQLITE_OK ){
18205       sqlite3_stmt *pStmt;
18206       rc = sqlite3_prepare_v2(p->db,
18207                "SELECT rowid FROM sqlite_schema"
18208                " WHERE name GLOB 'sqlite_stat[134]'",
18209                -1, &pStmt, 0);
18210       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
18211       sqlite3_finalize(pStmt);
18212     }
18213     if( doStats==0 ){
18214       raw_printf(p->out, "/* No STAT tables available */\n");
18215     }else{
18216       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
18217       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
18218                    callback, &data, &zErrMsg);
18219       data.cMode = data.mode = MODE_Insert;
18220       data.zDestTable = "sqlite_stat1";
18221       shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
18222       data.zDestTable = "sqlite_stat4";
18223       shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
18224       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
18225     }
18226   }else
18227
18228   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
18229     if( nArg==2 ){
18230       p->showHeader = booleanValue(azArg[1]);
18231       p->shellFlgs |= SHFLG_HeaderSet;
18232     }else{
18233       raw_printf(stderr, "Usage: .headers on|off\n");
18234       rc = 1;
18235     }
18236   }else
18237
18238   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
18239     if( nArg>=2 ){
18240       n = showHelp(p->out, azArg[1]);
18241       if( n==0 ){
18242         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
18243       }
18244     }else{
18245       showHelp(p->out, 0);
18246     }
18247   }else
18248
18249   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
18250     char *zTable = 0;           /* Insert data into this table */
18251     char *zFile = 0;            /* Name of file to extra content from */
18252     sqlite3_stmt *pStmt = NULL; /* A statement */
18253     int nCol;                   /* Number of columns in the table */
18254     int nByte;                  /* Number of bytes in an SQL string */
18255     int i, j;                   /* Loop counters */
18256     int needCommit;             /* True to COMMIT or ROLLBACK at end */
18257     int nSep;                   /* Number of bytes in p->colSeparator[] */
18258     char *zSql;                 /* An SQL statement */
18259     ImportCtx sCtx;             /* Reader context */
18260     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
18261     int eVerbose = 0;           /* Larger for more console output */
18262     int nSkip = 0;              /* Initial lines to skip */
18263     int useOutputMode = 1;      /* Use output mode to determine separators */
18264
18265     memset(&sCtx, 0, sizeof(sCtx));
18266     if( p->mode==MODE_Ascii ){
18267       xRead = ascii_read_one_field;
18268     }else{
18269       xRead = csv_read_one_field;
18270     }
18271     for(i=1; i<nArg; i++){
18272       char *z = azArg[i];
18273       if( z[0]=='-' && z[1]=='-' ) z++;
18274       if( z[0]!='-' ){
18275         if( zFile==0 ){
18276           zFile = z;
18277         }else if( zTable==0 ){
18278           zTable = z;
18279         }else{
18280           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
18281           showHelp(p->out, "import");
18282           rc = 1;
18283           goto meta_command_exit;
18284         }
18285       }else if( strcmp(z,"-v")==0 ){
18286         eVerbose++;
18287       }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
18288         nSkip = integerValue(azArg[++i]);
18289       }else if( strcmp(z,"-ascii")==0 ){
18290         sCtx.cColSep = SEP_Unit[0];
18291         sCtx.cRowSep = SEP_Record[0];
18292         xRead = ascii_read_one_field;
18293         useOutputMode = 0;
18294       }else if( strcmp(z,"-csv")==0 ){
18295         sCtx.cColSep = ',';
18296         sCtx.cRowSep = '\n';
18297         xRead = csv_read_one_field;
18298         useOutputMode = 0;
18299       }else{
18300         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
18301         showHelp(p->out, "import");
18302         rc = 1;
18303         goto meta_command_exit;
18304       }
18305     }
18306     if( zTable==0 ){
18307       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
18308                   zFile==0 ? "FILE" : "TABLE");
18309       showHelp(p->out, "import");
18310       rc = 1;
18311       goto meta_command_exit;
18312     }
18313     seenInterrupt = 0;
18314     open_db(p, 0);
18315     if( useOutputMode ){
18316       /* If neither the --csv or --ascii options are specified, then set
18317       ** the column and row separator characters from the output mode. */
18318       nSep = strlen30(p->colSeparator);
18319       if( nSep==0 ){
18320         raw_printf(stderr,
18321                    "Error: non-null column separator required for import\n");
18322         rc = 1;
18323         goto meta_command_exit;
18324       }
18325       if( nSep>1 ){
18326         raw_printf(stderr, 
18327               "Error: multi-character column separators not allowed"
18328               " for import\n");
18329         rc = 1;
18330         goto meta_command_exit;
18331       }
18332       nSep = strlen30(p->rowSeparator);
18333       if( nSep==0 ){
18334         raw_printf(stderr,
18335             "Error: non-null row separator required for import\n");
18336         rc = 1;
18337         goto meta_command_exit;
18338       }
18339       if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
18340         /* When importing CSV (only), if the row separator is set to the
18341         ** default output row separator, change it to the default input
18342         ** row separator.  This avoids having to maintain different input
18343         ** and output row separators. */
18344         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18345         nSep = strlen30(p->rowSeparator);
18346       }
18347       if( nSep>1 ){
18348         raw_printf(stderr, "Error: multi-character row separators not allowed"
18349                            " for import\n");
18350         rc = 1;
18351         goto meta_command_exit;
18352       }
18353       sCtx.cColSep = p->colSeparator[0];
18354       sCtx.cRowSep = p->rowSeparator[0];
18355     }
18356     sCtx.zFile = zFile;
18357     sCtx.nLine = 1;
18358     if( sCtx.zFile[0]=='|' ){
18359 #ifdef SQLITE_OMIT_POPEN
18360       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
18361       rc = 1;
18362       goto meta_command_exit;
18363 #else
18364       sCtx.in = popen(sCtx.zFile+1, "r");
18365       sCtx.zFile = "<pipe>";
18366       sCtx.xCloser = pclose;
18367 #endif
18368     }else{
18369       sCtx.in = fopen(sCtx.zFile, "rb");
18370       sCtx.xCloser = fclose;
18371     }
18372     if( sCtx.in==0 ){
18373       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
18374       rc = 1;
18375       goto meta_command_exit;
18376     }
18377     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
18378       char zSep[2];
18379       zSep[1] = 0;
18380       zSep[0] = sCtx.cColSep;
18381       utf8_printf(p->out, "Column separator ");
18382       output_c_string(p->out, zSep);
18383       utf8_printf(p->out, ", row separator ");
18384       zSep[0] = sCtx.cRowSep;
18385       output_c_string(p->out, zSep);
18386       utf8_printf(p->out, "\n");
18387     }
18388     while( (nSkip--)>0 ){
18389       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
18390     }
18391     zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
18392     if( zSql==0 ){
18393       import_cleanup(&sCtx);
18394       shell_out_of_memory();
18395     }
18396     nByte = strlen30(zSql);
18397     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18398     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
18399     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
18400       char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
18401       char cSep = '(';
18402       while( xRead(&sCtx) ){
18403         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
18404         cSep = ',';
18405         if( sCtx.cTerm!=sCtx.cColSep ) break;
18406       }
18407       if( cSep=='(' ){
18408         sqlite3_free(zCreate);
18409         import_cleanup(&sCtx);
18410         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
18411         rc = 1;
18412         goto meta_command_exit;
18413       }
18414       zCreate = sqlite3_mprintf("%z\n)", zCreate);
18415       if( eVerbose>=1 ){
18416         utf8_printf(p->out, "%s\n", zCreate);
18417       }
18418       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
18419       sqlite3_free(zCreate);
18420       if( rc ){
18421         utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
18422                 sqlite3_errmsg(p->db));
18423         import_cleanup(&sCtx);
18424         rc = 1;
18425         goto meta_command_exit;
18426       }
18427       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18428     }
18429     sqlite3_free(zSql);
18430     if( rc ){
18431       if (pStmt) sqlite3_finalize(pStmt);
18432       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
18433       import_cleanup(&sCtx);
18434       rc = 1;
18435       goto meta_command_exit;
18436     }
18437     nCol = sqlite3_column_count(pStmt);
18438     sqlite3_finalize(pStmt);
18439     pStmt = 0;
18440     if( nCol==0 ) return 0; /* no columns, no error */
18441     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
18442     if( zSql==0 ){
18443       import_cleanup(&sCtx);
18444       shell_out_of_memory();
18445     }
18446     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
18447     j = strlen30(zSql);
18448     for(i=1; i<nCol; i++){
18449       zSql[j++] = ',';
18450       zSql[j++] = '?';
18451     }
18452     zSql[j++] = ')';
18453     zSql[j] = 0;
18454     if( eVerbose>=2 ){
18455       utf8_printf(p->out, "Insert using: %s\n", zSql);
18456     }
18457     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18458     sqlite3_free(zSql);
18459     if( rc ){
18460       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
18461       if (pStmt) sqlite3_finalize(pStmt);
18462       import_cleanup(&sCtx);
18463       rc = 1;
18464       goto meta_command_exit;
18465     }
18466     needCommit = sqlite3_get_autocommit(p->db);
18467     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
18468     do{
18469       int startLine = sCtx.nLine;
18470       for(i=0; i<nCol; i++){
18471         char *z = xRead(&sCtx);
18472         /*
18473         ** Did we reach end-of-file before finding any columns?
18474         ** If so, stop instead of NULL filling the remaining columns.
18475         */
18476         if( z==0 && i==0 ) break;
18477         /*
18478         ** Did we reach end-of-file OR end-of-line before finding any
18479         ** columns in ASCII mode?  If so, stop instead of NULL filling
18480         ** the remaining columns.
18481         */
18482         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
18483         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
18484         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
18485           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
18486                           "filling the rest with NULL\n",
18487                           sCtx.zFile, startLine, nCol, i+1);
18488           i += 2;
18489           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
18490         }
18491       }
18492       if( sCtx.cTerm==sCtx.cColSep ){
18493         do{
18494           xRead(&sCtx);
18495           i++;
18496         }while( sCtx.cTerm==sCtx.cColSep );
18497         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
18498                         "extras ignored\n",
18499                         sCtx.zFile, startLine, nCol, i);
18500       }
18501       if( i>=nCol ){
18502         sqlite3_step(pStmt);
18503         rc = sqlite3_reset(pStmt);
18504         if( rc!=SQLITE_OK ){
18505           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
18506                       startLine, sqlite3_errmsg(p->db));
18507           sCtx.nErr++;
18508         }else{
18509           sCtx.nRow++;
18510         }
18511       }
18512     }while( sCtx.cTerm!=EOF );
18513
18514     import_cleanup(&sCtx);
18515     sqlite3_finalize(pStmt);
18516     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
18517     if( eVerbose>0 ){
18518       utf8_printf(p->out,
18519           "Added %d rows with %d errors using %d lines of input\n",
18520           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
18521     }
18522   }else
18523
18524 #ifndef SQLITE_UNTESTABLE
18525   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
18526     char *zSql;
18527     char *zCollist = 0;
18528     sqlite3_stmt *pStmt;
18529     int tnum = 0;
18530     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
18531     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
18532     int i;
18533     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
18534       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
18535                           "       .imposter off\n");
18536       /* Also allowed, but not documented:
18537       **
18538       **    .imposter TABLE IMPOSTER
18539       **
18540       ** where TABLE is a WITHOUT ROWID table.  In that case, the
18541       ** imposter is another WITHOUT ROWID table with the columns in
18542       ** storage order. */
18543       rc = 1;
18544       goto meta_command_exit;
18545     }
18546     open_db(p, 0);
18547     if( nArg==2 ){
18548       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
18549       goto meta_command_exit;
18550     }
18551     zSql = sqlite3_mprintf(
18552       "SELECT rootpage, 0 FROM sqlite_schema"
18553       " WHERE name='%q' AND type='index'"
18554       "UNION ALL "
18555       "SELECT rootpage, 1 FROM sqlite_schema"
18556       " WHERE name='%q' AND type='table'"
18557       "   AND sql LIKE '%%without%%rowid%%'",
18558       azArg[1], azArg[1]
18559     );
18560     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18561     sqlite3_free(zSql);
18562     if( sqlite3_step(pStmt)==SQLITE_ROW ){
18563       tnum = sqlite3_column_int(pStmt, 0);
18564       isWO = sqlite3_column_int(pStmt, 1);
18565     }
18566     sqlite3_finalize(pStmt);
18567     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
18568     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18569     sqlite3_free(zSql);
18570     i = 0;
18571     while( sqlite3_step(pStmt)==SQLITE_ROW ){
18572       char zLabel[20];
18573       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
18574       i++;
18575       if( zCol==0 ){
18576         if( sqlite3_column_int(pStmt,1)==-1 ){
18577           zCol = "_ROWID_";
18578         }else{
18579           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
18580           zCol = zLabel;
18581         }
18582       }
18583       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
18584         lenPK = (int)strlen(zCollist);
18585       }
18586       if( zCollist==0 ){
18587         zCollist = sqlite3_mprintf("\"%w\"", zCol);
18588       }else{
18589         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
18590       }
18591     }
18592     sqlite3_finalize(pStmt);
18593     if( i==0 || tnum==0 ){
18594       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
18595       rc = 1;
18596       sqlite3_free(zCollist);
18597       goto meta_command_exit;
18598     }
18599     if( lenPK==0 ) lenPK = 100000;
18600     zSql = sqlite3_mprintf(
18601           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
18602           azArg[2], zCollist, lenPK, zCollist);
18603     sqlite3_free(zCollist);
18604     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
18605     if( rc==SQLITE_OK ){
18606       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
18607       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
18608       if( rc ){
18609         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
18610       }else{
18611         utf8_printf(stdout, "%s;\n", zSql);
18612         raw_printf(stdout,
18613           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
18614           azArg[1], isWO ? "table" : "index"
18615         );
18616       }
18617     }else{
18618       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
18619       rc = 1;
18620     }
18621     sqlite3_free(zSql);
18622   }else
18623 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
18624
18625 #ifdef SQLITE_ENABLE_IOTRACE
18626   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
18627     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
18628     if( iotrace && iotrace!=stdout ) fclose(iotrace);
18629     iotrace = 0;
18630     if( nArg<2 ){
18631       sqlite3IoTrace = 0;
18632     }else if( strcmp(azArg[1], "-")==0 ){
18633       sqlite3IoTrace = iotracePrintf;
18634       iotrace = stdout;
18635     }else{
18636       iotrace = fopen(azArg[1], "w");
18637       if( iotrace==0 ){
18638         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
18639         sqlite3IoTrace = 0;
18640         rc = 1;
18641       }else{
18642         sqlite3IoTrace = iotracePrintf;
18643       }
18644     }
18645   }else
18646 #endif
18647
18648   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
18649     static const struct {
18650        const char *zLimitName;   /* Name of a limit */
18651        int limitCode;            /* Integer code for that limit */
18652     } aLimit[] = {
18653       { "length",                SQLITE_LIMIT_LENGTH                    },
18654       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
18655       { "column",                SQLITE_LIMIT_COLUMN                    },
18656       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
18657       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
18658       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
18659       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
18660       { "attached",              SQLITE_LIMIT_ATTACHED                  },
18661       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
18662       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
18663       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
18664       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
18665     };
18666     int i, n2;
18667     open_db(p, 0);
18668     if( nArg==1 ){
18669       for(i=0; i<ArraySize(aLimit); i++){
18670         printf("%20s %d\n", aLimit[i].zLimitName,
18671                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
18672       }
18673     }else if( nArg>3 ){
18674       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
18675       rc = 1;
18676       goto meta_command_exit;
18677     }else{
18678       int iLimit = -1;
18679       n2 = strlen30(azArg[1]);
18680       for(i=0; i<ArraySize(aLimit); i++){
18681         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
18682           if( iLimit<0 ){
18683             iLimit = i;
18684           }else{
18685             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
18686             rc = 1;
18687             goto meta_command_exit;
18688           }
18689         }
18690       }
18691       if( iLimit<0 ){
18692         utf8_printf(stderr, "unknown limit: \"%s\"\n"
18693                         "enter \".limits\" with no arguments for a list.\n",
18694                          azArg[1]);
18695         rc = 1;
18696         goto meta_command_exit;
18697       }
18698       if( nArg==3 ){
18699         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
18700                       (int)integerValue(azArg[2]));
18701       }
18702       printf("%20s %d\n", aLimit[iLimit].zLimitName,
18703              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
18704     }
18705   }else
18706
18707   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
18708     open_db(p, 0);
18709     lintDotCommand(p, azArg, nArg);
18710   }else
18711
18712 #ifndef SQLITE_OMIT_LOAD_EXTENSION
18713   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
18714     const char *zFile, *zProc;
18715     char *zErrMsg = 0;
18716     if( nArg<2 ){
18717       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
18718       rc = 1;
18719       goto meta_command_exit;
18720     }
18721     zFile = azArg[1];
18722     zProc = nArg>=3 ? azArg[2] : 0;
18723     open_db(p, 0);
18724     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
18725     if( rc!=SQLITE_OK ){
18726       utf8_printf(stderr, "Error: %s\n", zErrMsg);
18727       sqlite3_free(zErrMsg);
18728       rc = 1;
18729     }
18730   }else
18731 #endif
18732
18733   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
18734     if( nArg!=2 ){
18735       raw_printf(stderr, "Usage: .log FILENAME\n");
18736       rc = 1;
18737     }else{
18738       const char *zFile = azArg[1];
18739       output_file_close(p->pLog);
18740       p->pLog = output_file_open(zFile, 0);
18741     }
18742   }else
18743
18744   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
18745     const char *zMode = nArg>=2 ? azArg[1] : "";
18746     int n2 = strlen30(zMode);
18747     int c2 = zMode[0];
18748     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
18749       p->mode = MODE_Line;
18750       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18751     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
18752       p->mode = MODE_Column;
18753       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
18754         p->showHeader = 1;
18755       }
18756       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18757     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
18758       p->mode = MODE_List;
18759       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
18760       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18761     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
18762       p->mode = MODE_Html;
18763     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
18764       p->mode = MODE_Tcl;
18765       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
18766       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18767     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
18768       p->mode = MODE_Csv;
18769       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
18770       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
18771     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
18772       p->mode = MODE_List;
18773       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
18774     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
18775       p->mode = MODE_Insert;
18776       set_table_name(p, nArg>=3 ? azArg[2] : "table");
18777     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
18778       p->mode = MODE_Quote;
18779       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
18780       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18781     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
18782       p->mode = MODE_Ascii;
18783       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
18784       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
18785     }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
18786       p->mode = MODE_Markdown;
18787     }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
18788       p->mode = MODE_Table;
18789     }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
18790       p->mode = MODE_Box;
18791     }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
18792       p->mode = MODE_Json;
18793     }else if( nArg==1 ){
18794       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
18795     }else{
18796       raw_printf(stderr, "Error: mode should be one of: "
18797          "ascii box column csv html insert json line list markdown "
18798          "quote table tabs tcl\n");
18799       rc = 1;
18800     }
18801     p->cMode = p->mode;
18802   }else
18803
18804   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
18805     if( nArg==2 ){
18806       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
18807                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
18808     }else{
18809       raw_printf(stderr, "Usage: .nullvalue STRING\n");
18810       rc = 1;
18811     }
18812   }else
18813
18814 #ifdef SQLITE_DEBUG
18815   if( c=='o' && strcmp(azArg[0],"oom")==0 ){
18816     int i;
18817     for(i=1; i<nArg; i++){
18818       const char *z = azArg[i];
18819       if( z[0]=='-' && z[1]=='-' ) z++;
18820       if( strcmp(z,"-repeat")==0 ){
18821         if( i==nArg-1 ){
18822           raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
18823           rc = 1;
18824         }else{
18825           oomRepeat = (int)integerValue(azArg[++i]);
18826         }
18827       }else if( IsDigit(z[0]) ){
18828         oomCounter = (int)integerValue(azArg[i]);
18829       }else{
18830         raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
18831         raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
18832         rc = 1;
18833       }
18834     }
18835     if( rc==0 ){
18836       raw_printf(p->out, "oomCounter = %d\n", oomCounter);
18837       raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
18838     }
18839   }else
18840 #endif /* SQLITE_DEBUG */
18841
18842   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
18843     char *zNewFilename = 0;  /* Name of the database file to open */
18844     int iName = 1;           /* Index in azArg[] of the filename */
18845     int newFlag = 0;         /* True to delete file before opening */
18846     /* Close the existing database */
18847     session_close_all(p);
18848     close_db(p->db);
18849     p->db = 0;
18850     p->zDbFilename = 0;
18851     sqlite3_free(p->zFreeOnClose);
18852     p->zFreeOnClose = 0;
18853     p->openMode = SHELL_OPEN_UNSPEC;
18854     p->openFlags = 0;
18855     p->szMax = 0;
18856     /* Check for command-line arguments */
18857     for(iName=1; iName<nArg; iName++){
18858       const char *z = azArg[iName];
18859       if( optionMatch(z,"new") ){
18860         newFlag = 1;
18861 #ifdef SQLITE_HAVE_ZLIB
18862       }else if( optionMatch(z, "zip") ){
18863         p->openMode = SHELL_OPEN_ZIPFILE;
18864 #endif
18865       }else if( optionMatch(z, "append") ){
18866         p->openMode = SHELL_OPEN_APPENDVFS;
18867       }else if( optionMatch(z, "readonly") ){
18868         p->openMode = SHELL_OPEN_READONLY;
18869       }else if( optionMatch(z, "nofollow") ){
18870         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
18871 #ifdef SQLITE_ENABLE_DESERIALIZE
18872       }else if( optionMatch(z, "deserialize") ){
18873         p->openMode = SHELL_OPEN_DESERIALIZE;
18874       }else if( optionMatch(z, "hexdb") ){
18875         p->openMode = SHELL_OPEN_HEXDB;
18876       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
18877         p->szMax = integerValue(azArg[++iName]);
18878 #endif /* SQLITE_ENABLE_DESERIALIZE */
18879       }else if( z[0]=='-' ){
18880         utf8_printf(stderr, "unknown option: %s\n", z);
18881         rc = 1;
18882         goto meta_command_exit;
18883       }else if( zNewFilename ){
18884         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
18885         rc = 1;
18886         goto meta_command_exit;
18887       }else{
18888         zNewFilename = sqlite3_mprintf("%s", z);
18889       }
18890     }
18891     /* If a filename is specified, try to open it first */
18892     if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
18893       if( newFlag ) shellDeleteFile(zNewFilename);
18894       p->zDbFilename = zNewFilename;
18895       open_db(p, OPEN_DB_KEEPALIVE);
18896       if( p->db==0 ){
18897         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
18898         sqlite3_free(zNewFilename);
18899       }else{
18900         p->zFreeOnClose = zNewFilename;
18901       }
18902     }
18903     if( p->db==0 ){
18904       /* As a fall-back open a TEMP database */
18905       p->zDbFilename = 0;
18906       open_db(p, 0);
18907     }
18908   }else
18909
18910   if( (c=='o'
18911         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
18912    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
18913   ){
18914     char *zFile = 0;
18915     int bTxtMode = 0;
18916     int i;
18917     int eMode = 0;
18918     int bBOM = 0;
18919     int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
18920
18921     if( c=='e' ){
18922       eMode = 'x';
18923       bOnce = 2;
18924     }else if( strncmp(azArg[0],"once",n)==0 ){
18925       bOnce = 1;
18926     }
18927     for(i=1; i<nArg; i++){
18928       char *z = azArg[i];
18929       if( z[0]=='-' ){
18930         if( z[1]=='-' ) z++;
18931         if( strcmp(z,"-bom")==0 ){
18932           bBOM = 1;
18933         }else if( c!='e' && strcmp(z,"-x")==0 ){
18934           eMode = 'x';  /* spreadsheet */
18935         }else if( c!='e' && strcmp(z,"-e")==0 ){
18936           eMode = 'e';  /* text editor */
18937         }else{
18938           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
18939                       azArg[i]);
18940           showHelp(p->out, azArg[0]);
18941           rc = 1;
18942           goto meta_command_exit;
18943         }
18944       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
18945         zFile = sqlite3_mprintf("%s", z);
18946         if( zFile[0]=='|' ){
18947           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
18948           break;
18949         }
18950       }else{
18951         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
18952                     azArg[i]);
18953         showHelp(p->out, azArg[0]);
18954         rc = 1;
18955         sqlite3_free(zFile);
18956         goto meta_command_exit;
18957       }
18958     }
18959     if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
18960     if( bOnce ){
18961       p->outCount = 2;
18962     }else{
18963       p->outCount = 0;
18964     }
18965     output_reset(p);
18966 #ifndef SQLITE_NOHAVE_SYSTEM
18967     if( eMode=='e' || eMode=='x' ){
18968       p->doXdgOpen = 1;
18969       outputModePush(p);
18970       if( eMode=='x' ){
18971         /* spreadsheet mode.  Output as CSV. */
18972         newTempFile(p, "csv");
18973         ShellClearFlag(p, SHFLG_Echo);
18974         p->mode = MODE_Csv;
18975         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
18976         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
18977       }else{
18978         /* text editor mode */
18979         newTempFile(p, "txt");
18980         bTxtMode = 1;
18981       }
18982       sqlite3_free(zFile);
18983       zFile = sqlite3_mprintf("%s", p->zTempFile);
18984     }
18985 #endif /* SQLITE_NOHAVE_SYSTEM */
18986     if( zFile[0]=='|' ){
18987 #ifdef SQLITE_OMIT_POPEN
18988       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
18989       rc = 1;
18990       p->out = stdout;
18991 #else
18992       p->out = popen(zFile + 1, "w");
18993       if( p->out==0 ){
18994         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
18995         p->out = stdout;
18996         rc = 1;
18997       }else{
18998         if( bBOM ) fprintf(p->out,"\357\273\277");
18999         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
19000       }
19001 #endif
19002     }else{
19003       p->out = output_file_open(zFile, bTxtMode);
19004       if( p->out==0 ){
19005         if( strcmp(zFile,"off")!=0 ){
19006           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
19007         }
19008         p->out = stdout;
19009         rc = 1;
19010       } else {
19011         if( bBOM ) fprintf(p->out,"\357\273\277");
19012         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
19013       }
19014     }
19015     sqlite3_free(zFile);
19016   }else
19017
19018   if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
19019     open_db(p,0);
19020     if( nArg<=1 ) goto parameter_syntax_error;
19021
19022     /* .parameter clear
19023     ** Clear all bind parameters by dropping the TEMP table that holds them.
19024     */
19025     if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
19026       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
19027                    0, 0, 0);
19028     }else
19029
19030     /* .parameter list
19031     ** List all bind parameters.
19032     */
19033     if( nArg==2 && strcmp(azArg[1],"list")==0 ){
19034       sqlite3_stmt *pStmt = 0;
19035       int rx;
19036       int len = 0;
19037       rx = sqlite3_prepare_v2(p->db,
19038              "SELECT max(length(key)) "
19039              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
19040       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
19041         len = sqlite3_column_int(pStmt, 0);
19042         if( len>40 ) len = 40;
19043       }
19044       sqlite3_finalize(pStmt);
19045       pStmt = 0;
19046       if( len ){
19047         rx = sqlite3_prepare_v2(p->db,
19048              "SELECT key, quote(value) "
19049              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
19050         while( sqlite3_step(pStmt)==SQLITE_ROW ){
19051           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
19052                       sqlite3_column_text(pStmt,1));
19053         }
19054         sqlite3_finalize(pStmt);
19055       }
19056     }else
19057
19058     /* .parameter init
19059     ** Make sure the TEMP table used to hold bind parameters exists.
19060     ** Create it if necessary.
19061     */
19062     if( nArg==2 && strcmp(azArg[1],"init")==0 ){
19063       bind_table_init(p);
19064     }else
19065
19066     /* .parameter set NAME VALUE
19067     ** Set or reset a bind parameter.  NAME should be the full parameter
19068     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
19069     ** VALUE can be in either SQL literal notation, or if not it will be
19070     ** understood to be a text string.
19071     */
19072     if( nArg==4 && strcmp(azArg[1],"set")==0 ){
19073       int rx;
19074       char *zSql;
19075       sqlite3_stmt *pStmt;
19076       const char *zKey = azArg[2];
19077       const char *zValue = azArg[3];
19078       bind_table_init(p);
19079       zSql = sqlite3_mprintf(
19080                   "REPLACE INTO temp.sqlite_parameters(key,value)"
19081                   "VALUES(%Q,%s);", zKey, zValue);
19082       if( zSql==0 ) shell_out_of_memory();
19083       pStmt = 0;
19084       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19085       sqlite3_free(zSql);
19086       if( rx!=SQLITE_OK ){
19087         sqlite3_finalize(pStmt);
19088         pStmt = 0;
19089         zSql = sqlite3_mprintf(
19090                    "REPLACE INTO temp.sqlite_parameters(key,value)"
19091                    "VALUES(%Q,%Q);", zKey, zValue);
19092         if( zSql==0 ) shell_out_of_memory();
19093         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19094         sqlite3_free(zSql);
19095         if( rx!=SQLITE_OK ){
19096           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
19097           sqlite3_finalize(pStmt);
19098           pStmt = 0;
19099           rc = 1;
19100         }
19101       }
19102       sqlite3_step(pStmt);
19103       sqlite3_finalize(pStmt);
19104     }else
19105
19106     /* .parameter unset NAME
19107     ** Remove the NAME binding from the parameter binding table, if it
19108     ** exists.
19109     */
19110     if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
19111       char *zSql = sqlite3_mprintf(
19112           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
19113       if( zSql==0 ) shell_out_of_memory();
19114       sqlite3_exec(p->db, zSql, 0, 0, 0);
19115       sqlite3_free(zSql);
19116     }else
19117     /* If no command name matches, show a syntax error */
19118     parameter_syntax_error:
19119     showHelp(p->out, "parameter");
19120   }else
19121
19122   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
19123     int i;
19124     for(i=1; i<nArg; i++){
19125       if( i>1 ) raw_printf(p->out, " ");
19126       utf8_printf(p->out, "%s", azArg[i]);
19127     }
19128     raw_printf(p->out, "\n");
19129   }else
19130
19131 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19132   if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
19133     int i;
19134     int nn = 0;
19135     p->flgProgress = 0;
19136     p->mxProgress = 0;
19137     p->nProgress = 0;
19138     for(i=1; i<nArg; i++){
19139       const char *z = azArg[i];
19140       if( z[0]=='-' ){
19141         z++;
19142         if( z[0]=='-' ) z++;
19143         if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
19144           p->flgProgress |= SHELL_PROGRESS_QUIET;
19145           continue;
19146         }
19147         if( strcmp(z,"reset")==0 ){
19148           p->flgProgress |= SHELL_PROGRESS_RESET;
19149           continue;
19150         }
19151         if( strcmp(z,"once")==0 ){
19152           p->flgProgress |= SHELL_PROGRESS_ONCE;
19153           continue;
19154         }
19155         if( strcmp(z,"limit")==0 ){
19156           if( i+1>=nArg ){
19157             utf8_printf(stderr, "Error: missing argument on --limit\n");
19158             rc = 1;
19159             goto meta_command_exit;
19160           }else{
19161             p->mxProgress = (int)integerValue(azArg[++i]);
19162           }
19163           continue;
19164         }
19165         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
19166         rc = 1;
19167         goto meta_command_exit;
19168       }else{
19169         nn = (int)integerValue(z);
19170       }
19171     }
19172     open_db(p, 0);
19173     sqlite3_progress_handler(p->db, nn, progress_handler, p);
19174   }else
19175 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
19176
19177   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
19178     if( nArg >= 2) {
19179       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
19180     }
19181     if( nArg >= 3) {
19182       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
19183     }
19184   }else
19185
19186   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
19187     rc = 2;
19188   }else
19189
19190   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
19191     FILE *inSaved = p->in;
19192     int savedLineno = p->lineno;
19193     if( nArg!=2 ){
19194       raw_printf(stderr, "Usage: .read FILE\n");
19195       rc = 1;
19196       goto meta_command_exit;
19197     }
19198     if( azArg[1][0]=='|' ){
19199 #ifdef SQLITE_OMIT_POPEN
19200       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
19201       rc = 1;
19202       p->out = stdout;
19203 #else
19204       p->in = popen(azArg[1]+1, "r");
19205       if( p->in==0 ){
19206         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
19207         rc = 1;
19208       }else{
19209         rc = process_input(p);
19210         pclose(p->in);
19211       }
19212 #endif
19213     }else if( notNormalFile(azArg[1]) || (p->in = fopen(azArg[1], "rb"))==0 ){
19214       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
19215       rc = 1;
19216     }else{
19217       rc = process_input(p);
19218       fclose(p->in);
19219     }
19220     p->in = inSaved;
19221     p->lineno = savedLineno;
19222   }else
19223
19224   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
19225     const char *zSrcFile;
19226     const char *zDb;
19227     sqlite3 *pSrc;
19228     sqlite3_backup *pBackup;
19229     int nTimeout = 0;
19230
19231     if( nArg==2 ){
19232       zSrcFile = azArg[1];
19233       zDb = "main";
19234     }else if( nArg==3 ){
19235       zSrcFile = azArg[2];
19236       zDb = azArg[1];
19237     }else{
19238       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
19239       rc = 1;
19240       goto meta_command_exit;
19241     }
19242     rc = sqlite3_open(zSrcFile, &pSrc);
19243     if( rc!=SQLITE_OK ){
19244       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
19245       close_db(pSrc);
19246       return 1;
19247     }
19248     open_db(p, 0);
19249     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
19250     if( pBackup==0 ){
19251       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19252       close_db(pSrc);
19253       return 1;
19254     }
19255     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
19256           || rc==SQLITE_BUSY  ){
19257       if( rc==SQLITE_BUSY ){
19258         if( nTimeout++ >= 3 ) break;
19259         sqlite3_sleep(100);
19260       }
19261     }
19262     sqlite3_backup_finish(pBackup);
19263     if( rc==SQLITE_DONE ){
19264       rc = 0;
19265     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
19266       raw_printf(stderr, "Error: source database is busy\n");
19267       rc = 1;
19268     }else{
19269       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19270       rc = 1;
19271     }
19272     close_db(pSrc);
19273   }else
19274
19275   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
19276     if( nArg==2 ){
19277       p->scanstatsOn = (u8)booleanValue(azArg[1]);
19278 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
19279       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
19280 #endif
19281     }else{
19282       raw_printf(stderr, "Usage: .scanstats on|off\n");
19283       rc = 1;
19284     }
19285   }else
19286
19287   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
19288     ShellText sSelect;
19289     ShellState data;
19290     char *zErrMsg = 0;
19291     const char *zDiv = "(";
19292     const char *zName = 0;
19293     int iSchema = 0;
19294     int bDebug = 0;
19295     int bNoSystemTabs = 0;
19296     int ii;
19297
19298     open_db(p, 0);
19299     memcpy(&data, p, sizeof(data));
19300     data.showHeader = 0;
19301     data.cMode = data.mode = MODE_Semi;
19302     initText(&sSelect);
19303     for(ii=1; ii<nArg; ii++){
19304       if( optionMatch(azArg[ii],"indent") ){
19305         data.cMode = data.mode = MODE_Pretty;
19306       }else if( optionMatch(azArg[ii],"debug") ){
19307         bDebug = 1;
19308       }else if( optionMatch(azArg[ii],"nosys") ){
19309         bNoSystemTabs = 1;
19310       }else if( azArg[ii][0]=='-' ){
19311         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
19312         rc = 1;
19313         goto meta_command_exit;
19314       }else if( zName==0 ){
19315         zName = azArg[ii];
19316       }else{
19317         raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
19318         rc = 1;
19319         goto meta_command_exit;
19320       }
19321     }
19322     if( zName!=0 ){
19323       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
19324                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
19325                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
19326                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
19327       if( isSchema ){
19328         char *new_argv[2], *new_colv[2];
19329         new_argv[0] = sqlite3_mprintf(
19330                       "CREATE TABLE %s (\n"
19331                       "  type text,\n"
19332                       "  name text,\n"
19333                       "  tbl_name text,\n"
19334                       "  rootpage integer,\n"
19335                       "  sql text\n"
19336                       ")", zName);
19337         new_argv[1] = 0;
19338         new_colv[0] = "sql";
19339         new_colv[1] = 0;
19340         callback(&data, 1, new_argv, new_colv);
19341         sqlite3_free(new_argv[0]);
19342       }
19343     }
19344     if( zDiv ){
19345       sqlite3_stmt *pStmt = 0;
19346       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
19347                               -1, &pStmt, 0);
19348       if( rc ){
19349         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19350         sqlite3_finalize(pStmt);
19351         rc = 1;
19352         goto meta_command_exit;
19353       }
19354       appendText(&sSelect, "SELECT sql FROM", 0);
19355       iSchema = 0;
19356       while( sqlite3_step(pStmt)==SQLITE_ROW ){
19357         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
19358         char zScNum[30];
19359         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
19360         appendText(&sSelect, zDiv, 0);
19361         zDiv = " UNION ALL ";
19362         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
19363         if( sqlite3_stricmp(zDb, "main")!=0 ){
19364           appendText(&sSelect, zDb, '\'');
19365         }else{
19366           appendText(&sSelect, "NULL", 0);
19367         }
19368         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
19369         appendText(&sSelect, zScNum, 0);
19370         appendText(&sSelect, " AS snum, ", 0);
19371         appendText(&sSelect, zDb, '\'');
19372         appendText(&sSelect, " AS sname FROM ", 0);
19373         appendText(&sSelect, zDb, quoteChar(zDb));
19374         appendText(&sSelect, ".sqlite_schema", 0);
19375       }
19376       sqlite3_finalize(pStmt);
19377 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
19378       if( zName ){
19379         appendText(&sSelect,
19380            " UNION ALL SELECT shell_module_schema(name),"
19381            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
19382         0);
19383       }
19384 #endif
19385       appendText(&sSelect, ") WHERE ", 0);
19386       if( zName ){
19387         char *zQarg = sqlite3_mprintf("%Q", zName);
19388         int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
19389                     strchr(zName, '[') != 0;
19390         if( strchr(zName, '.') ){
19391           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
19392         }else{
19393           appendText(&sSelect, "lower(tbl_name)", 0);
19394         }
19395         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
19396         appendText(&sSelect, zQarg, 0);
19397         if( !bGlob ){
19398           appendText(&sSelect, " ESCAPE '\\' ", 0);
19399         }
19400         appendText(&sSelect, " AND ", 0);
19401         sqlite3_free(zQarg);
19402       }
19403       if( bNoSystemTabs ){
19404         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
19405       }
19406       appendText(&sSelect, "sql IS NOT NULL"
19407                            " ORDER BY snum, rowid", 0);
19408       if( bDebug ){
19409         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
19410       }else{
19411         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
19412       }
19413       freeText(&sSelect);
19414     }
19415     if( zErrMsg ){
19416       utf8_printf(stderr,"Error: %s\n", zErrMsg);
19417       sqlite3_free(zErrMsg);
19418       rc = 1;
19419     }else if( rc != SQLITE_OK ){
19420       raw_printf(stderr,"Error: querying schema information\n");
19421       rc = 1;
19422     }else{
19423       rc = 0;
19424     }
19425   }else
19426
19427   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
19428     unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
19429     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
19430   }else
19431
19432 #if defined(SQLITE_ENABLE_SESSION)
19433   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
19434     OpenSession *pSession = &p->aSession[0];
19435     char **azCmd = &azArg[1];
19436     int iSes = 0;
19437     int nCmd = nArg - 1;
19438     int i;
19439     if( nArg<=1 ) goto session_syntax_error;
19440     open_db(p, 0);
19441     if( nArg>=3 ){
19442       for(iSes=0; iSes<p->nSession; iSes++){
19443         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
19444       }
19445       if( iSes<p->nSession ){
19446         pSession = &p->aSession[iSes];
19447         azCmd++;
19448         nCmd--;
19449       }else{
19450         pSession = &p->aSession[0];
19451         iSes = 0;
19452       }
19453     }
19454
19455     /* .session attach TABLE
19456     ** Invoke the sqlite3session_attach() interface to attach a particular
19457     ** table so that it is never filtered.
19458     */
19459     if( strcmp(azCmd[0],"attach")==0 ){
19460       if( nCmd!=2 ) goto session_syntax_error;
19461       if( pSession->p==0 ){
19462         session_not_open:
19463         raw_printf(stderr, "ERROR: No sessions are open\n");
19464       }else{
19465         rc = sqlite3session_attach(pSession->p, azCmd[1]);
19466         if( rc ){
19467           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
19468           rc = 0;
19469         }
19470       }
19471     }else
19472
19473     /* .session changeset FILE
19474     ** .session patchset FILE
19475     ** Write a changeset or patchset into a file.  The file is overwritten.
19476     */
19477     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
19478       FILE *out = 0;
19479       if( nCmd!=2 ) goto session_syntax_error;
19480       if( pSession->p==0 ) goto session_not_open;
19481       out = fopen(azCmd[1], "wb");
19482       if( out==0 ){
19483         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
19484                     azCmd[1]);
19485       }else{
19486         int szChng;
19487         void *pChng;
19488         if( azCmd[0][0]=='c' ){
19489           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
19490         }else{
19491           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
19492         }
19493         if( rc ){
19494           printf("Error: error code %d\n", rc);
19495           rc = 0;
19496         }
19497         if( pChng
19498           && fwrite(pChng, szChng, 1, out)!=1 ){
19499           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
19500                   szChng);
19501         }
19502         sqlite3_free(pChng);
19503         fclose(out);
19504       }
19505     }else
19506
19507     /* .session close
19508     ** Close the identified session
19509     */
19510     if( strcmp(azCmd[0], "close")==0 ){
19511       if( nCmd!=1 ) goto session_syntax_error;
19512       if( p->nSession ){
19513         session_close(pSession);
19514         p->aSession[iSes] = p->aSession[--p->nSession];
19515       }
19516     }else
19517
19518     /* .session enable ?BOOLEAN?
19519     ** Query or set the enable flag
19520     */
19521     if( strcmp(azCmd[0], "enable")==0 ){
19522       int ii;
19523       if( nCmd>2 ) goto session_syntax_error;
19524       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
19525       if( p->nSession ){
19526         ii = sqlite3session_enable(pSession->p, ii);
19527         utf8_printf(p->out, "session %s enable flag = %d\n",
19528                     pSession->zName, ii);
19529       }
19530     }else
19531
19532     /* .session filter GLOB ....
19533     ** Set a list of GLOB patterns of table names to be excluded.
19534     */
19535     if( strcmp(azCmd[0], "filter")==0 ){
19536       int ii, nByte;
19537       if( nCmd<2 ) goto session_syntax_error;
19538       if( p->nSession ){
19539         for(ii=0; ii<pSession->nFilter; ii++){
19540           sqlite3_free(pSession->azFilter[ii]);
19541         }
19542         sqlite3_free(pSession->azFilter);
19543         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
19544         pSession->azFilter = sqlite3_malloc( nByte );
19545         if( pSession->azFilter==0 ){
19546           raw_printf(stderr, "Error: out or memory\n");
19547           exit(1);
19548         }
19549         for(ii=1; ii<nCmd; ii++){
19550           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
19551         }
19552         pSession->nFilter = ii-1;
19553       }
19554     }else
19555
19556     /* .session indirect ?BOOLEAN?
19557     ** Query or set the indirect flag
19558     */
19559     if( strcmp(azCmd[0], "indirect")==0 ){
19560       int ii;
19561       if( nCmd>2 ) goto session_syntax_error;
19562       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
19563       if( p->nSession ){
19564         ii = sqlite3session_indirect(pSession->p, ii);
19565         utf8_printf(p->out, "session %s indirect flag = %d\n",
19566                     pSession->zName, ii);
19567       }
19568     }else
19569
19570     /* .session isempty
19571     ** Determine if the session is empty
19572     */
19573     if( strcmp(azCmd[0], "isempty")==0 ){
19574       int ii;
19575       if( nCmd!=1 ) goto session_syntax_error;
19576       if( p->nSession ){
19577         ii = sqlite3session_isempty(pSession->p);
19578         utf8_printf(p->out, "session %s isempty flag = %d\n",
19579                     pSession->zName, ii);
19580       }
19581     }else
19582
19583     /* .session list
19584     ** List all currently open sessions
19585     */
19586     if( strcmp(azCmd[0],"list")==0 ){
19587       for(i=0; i<p->nSession; i++){
19588         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
19589       }
19590     }else
19591
19592     /* .session open DB NAME
19593     ** Open a new session called NAME on the attached database DB.
19594     ** DB is normally "main".
19595     */
19596     if( strcmp(azCmd[0],"open")==0 ){
19597       char *zName;
19598       if( nCmd!=3 ) goto session_syntax_error;
19599       zName = azCmd[2];
19600       if( zName[0]==0 ) goto session_syntax_error;
19601       for(i=0; i<p->nSession; i++){
19602         if( strcmp(p->aSession[i].zName,zName)==0 ){
19603           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
19604           goto meta_command_exit;
19605         }
19606       }
19607       if( p->nSession>=ArraySize(p->aSession) ){
19608         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
19609         goto meta_command_exit;
19610       }
19611       pSession = &p->aSession[p->nSession];
19612       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
19613       if( rc ){
19614         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
19615         rc = 0;
19616         goto meta_command_exit;
19617       }
19618       pSession->nFilter = 0;
19619       sqlite3session_table_filter(pSession->p, session_filter, pSession);
19620       p->nSession++;
19621       pSession->zName = sqlite3_mprintf("%s", zName);
19622     }else
19623     /* If no command name matches, show a syntax error */
19624     session_syntax_error:
19625     showHelp(p->out, "session");
19626   }else
19627 #endif
19628
19629 #ifdef SQLITE_DEBUG
19630   /* Undocumented commands for internal testing.  Subject to change
19631   ** without notice. */
19632   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
19633     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
19634       int i, v;
19635       for(i=1; i<nArg; i++){
19636         v = booleanValue(azArg[i]);
19637         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
19638       }
19639     }
19640     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
19641       int i; sqlite3_int64 v;
19642       for(i=1; i<nArg; i++){
19643         char zBuf[200];
19644         v = integerValue(azArg[i]);
19645         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
19646         utf8_printf(p->out, "%s", zBuf);
19647       }
19648     }
19649   }else
19650 #endif
19651
19652   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
19653     int bIsInit = 0;         /* True to initialize the SELFTEST table */
19654     int bVerbose = 0;        /* Verbose output */
19655     int bSelftestExists;     /* True if SELFTEST already exists */
19656     int i, k;                /* Loop counters */
19657     int nTest = 0;           /* Number of tests runs */
19658     int nErr = 0;            /* Number of errors seen */
19659     ShellText str;           /* Answer for a query */
19660     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
19661
19662     open_db(p,0);
19663     for(i=1; i<nArg; i++){
19664       const char *z = azArg[i];
19665       if( z[0]=='-' && z[1]=='-' ) z++;
19666       if( strcmp(z,"-init")==0 ){
19667         bIsInit = 1;
19668       }else
19669       if( strcmp(z,"-v")==0 ){
19670         bVerbose++;
19671       }else
19672       {
19673         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
19674                     azArg[i], azArg[0]);
19675         raw_printf(stderr, "Should be one of: --init -v\n");
19676         rc = 1;
19677         goto meta_command_exit;
19678       }
19679     }
19680     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
19681            != SQLITE_OK ){
19682       bSelftestExists = 0;
19683     }else{
19684       bSelftestExists = 1;
19685     }
19686     if( bIsInit ){
19687       createSelftestTable(p);
19688       bSelftestExists = 1;
19689     }
19690     initText(&str);
19691     appendText(&str, "x", 0);
19692     for(k=bSelftestExists; k>=0; k--){
19693       if( k==1 ){
19694         rc = sqlite3_prepare_v2(p->db,
19695             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
19696             -1, &pStmt, 0);
19697       }else{
19698         rc = sqlite3_prepare_v2(p->db,
19699           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
19700           "      (1,'run','PRAGMA integrity_check','ok')",
19701           -1, &pStmt, 0);
19702       }
19703       if( rc ){
19704         raw_printf(stderr, "Error querying the selftest table\n");
19705         rc = 1;
19706         sqlite3_finalize(pStmt);
19707         goto meta_command_exit;
19708       }
19709       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
19710         int tno = sqlite3_column_int(pStmt, 0);
19711         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
19712         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
19713         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
19714
19715         k = 0;
19716         if( bVerbose>0 ){
19717           char *zQuote = sqlite3_mprintf("%q", zSql);
19718           printf("%d: %s %s\n", tno, zOp, zSql);
19719           sqlite3_free(zQuote);
19720         }
19721         if( strcmp(zOp,"memo")==0 ){
19722           utf8_printf(p->out, "%s\n", zSql);
19723         }else
19724         if( strcmp(zOp,"run")==0 ){
19725           char *zErrMsg = 0;
19726           str.n = 0;
19727           str.z[0] = 0;
19728           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
19729           nTest++;
19730           if( bVerbose ){
19731             utf8_printf(p->out, "Result: %s\n", str.z);
19732           }
19733           if( rc || zErrMsg ){
19734             nErr++;
19735             rc = 1;
19736             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
19737             sqlite3_free(zErrMsg);
19738           }else if( strcmp(zAns,str.z)!=0 ){
19739             nErr++;
19740             rc = 1;
19741             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
19742             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
19743           }
19744         }else
19745         {
19746           utf8_printf(stderr,
19747             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
19748           rc = 1;
19749           break;
19750         }
19751       } /* End loop over rows of content from SELFTEST */
19752       sqlite3_finalize(pStmt);
19753     } /* End loop over k */
19754     freeText(&str);
19755     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
19756   }else
19757
19758   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
19759     if( nArg<2 || nArg>3 ){
19760       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
19761       rc = 1;
19762     }
19763     if( nArg>=2 ){
19764       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
19765                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
19766     }
19767     if( nArg>=3 ){
19768       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
19769                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
19770     }
19771   }else
19772
19773   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
19774     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
19775     int i;                   /* Loop counter */
19776     int bSchema = 0;         /* Also hash the schema */
19777     int bSeparate = 0;       /* Hash each table separately */
19778     int iSize = 224;         /* Hash algorithm to use */
19779     int bDebug = 0;          /* Only show the query that would have run */
19780     sqlite3_stmt *pStmt;     /* For querying tables names */
19781     char *zSql;              /* SQL to be run */
19782     char *zSep;              /* Separator */
19783     ShellText sSql;          /* Complete SQL for the query to run the hash */
19784     ShellText sQuery;        /* Set of queries used to read all content */
19785     open_db(p, 0);
19786     for(i=1; i<nArg; i++){
19787       const char *z = azArg[i];
19788       if( z[0]=='-' ){
19789         z++;
19790         if( z[0]=='-' ) z++;
19791         if( strcmp(z,"schema")==0 ){
19792           bSchema = 1;
19793         }else
19794         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
19795          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
19796         ){
19797           iSize = atoi(&z[5]);
19798         }else
19799         if( strcmp(z,"debug")==0 ){
19800           bDebug = 1;
19801         }else
19802         {
19803           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
19804                       azArg[i], azArg[0]);
19805           showHelp(p->out, azArg[0]);
19806           rc = 1;
19807           goto meta_command_exit;
19808         }
19809       }else if( zLike ){
19810         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
19811         rc = 1;
19812         goto meta_command_exit;
19813       }else{
19814         zLike = z;
19815         bSeparate = 1;
19816         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
19817       }
19818     }
19819     if( bSchema ){
19820       zSql = "SELECT lower(name) FROM sqlite_schema"
19821              " WHERE type='table' AND coalesce(rootpage,0)>1"
19822              " UNION ALL SELECT 'sqlite_schema'"
19823              " ORDER BY 1 collate nocase";
19824     }else{
19825       zSql = "SELECT lower(name) FROM sqlite_schema"
19826              " WHERE type='table' AND coalesce(rootpage,0)>1"
19827              " AND name NOT LIKE 'sqlite_%'"
19828              " ORDER BY 1 collate nocase";
19829     }
19830     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19831     initText(&sQuery);
19832     initText(&sSql);
19833     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
19834     zSep = "VALUES(";
19835     while( SQLITE_ROW==sqlite3_step(pStmt) ){
19836       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
19837       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
19838       if( strncmp(zTab, "sqlite_",7)!=0 ){
19839         appendText(&sQuery,"SELECT * FROM ", 0);
19840         appendText(&sQuery,zTab,'"');
19841         appendText(&sQuery," NOT INDEXED;", 0);
19842       }else if( strcmp(zTab, "sqlite_schema")==0 ){
19843         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
19844                            " ORDER BY name;", 0);
19845       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
19846         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
19847                            " ORDER BY name;", 0);
19848       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
19849         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
19850                            " ORDER BY tbl,idx;", 0);
19851       }else if( strcmp(zTab, "sqlite_stat4")==0 ){
19852         appendText(&sQuery, "SELECT * FROM ", 0);
19853         appendText(&sQuery, zTab, 0);
19854         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
19855       }
19856       appendText(&sSql, zSep, 0);
19857       appendText(&sSql, sQuery.z, '\'');
19858       sQuery.n = 0;
19859       appendText(&sSql, ",", 0);
19860       appendText(&sSql, zTab, '\'');
19861       zSep = "),(";
19862     }
19863     sqlite3_finalize(pStmt);
19864     if( bSeparate ){
19865       zSql = sqlite3_mprintf(
19866           "%s))"
19867           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
19868           "   FROM [sha3sum$query]",
19869           sSql.z, iSize);
19870     }else{
19871       zSql = sqlite3_mprintf(
19872           "%s))"
19873           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
19874           "   FROM [sha3sum$query]",
19875           sSql.z, iSize);
19876     }
19877     freeText(&sQuery);
19878     freeText(&sSql);
19879     if( bDebug ){
19880       utf8_printf(p->out, "%s\n", zSql);
19881     }else{
19882       shell_exec(p, zSql, 0);
19883     }
19884     sqlite3_free(zSql);
19885   }else
19886
19887 #ifndef SQLITE_NOHAVE_SYSTEM
19888   if( c=='s'
19889    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
19890   ){
19891     char *zCmd;
19892     int i, x;
19893     if( nArg<2 ){
19894       raw_printf(stderr, "Usage: .system COMMAND\n");
19895       rc = 1;
19896       goto meta_command_exit;
19897     }
19898     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
19899     for(i=2; i<nArg; i++){
19900       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
19901                              zCmd, azArg[i]);
19902     }
19903     x = system(zCmd);
19904     sqlite3_free(zCmd);
19905     if( x ) raw_printf(stderr, "System command returns %d\n", x);
19906   }else
19907 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
19908
19909   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
19910     static const char *azBool[] = { "off", "on", "trigger", "full"};
19911     const char *zOut;
19912     int i;
19913     if( nArg!=1 ){
19914       raw_printf(stderr, "Usage: .show\n");
19915       rc = 1;
19916       goto meta_command_exit;
19917     }
19918     utf8_printf(p->out, "%12.12s: %s\n","echo",
19919                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
19920     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
19921     utf8_printf(p->out, "%12.12s: %s\n","explain",
19922          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
19923     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
19924     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
19925     utf8_printf(p->out, "%12.12s: ", "nullvalue");
19926       output_c_string(p->out, p->nullValue);
19927       raw_printf(p->out, "\n");
19928     utf8_printf(p->out,"%12.12s: %s\n","output",
19929             strlen30(p->outfile) ? p->outfile : "stdout");
19930     utf8_printf(p->out,"%12.12s: ", "colseparator");
19931       output_c_string(p->out, p->colSeparator);
19932       raw_printf(p->out, "\n");
19933     utf8_printf(p->out,"%12.12s: ", "rowseparator");
19934       output_c_string(p->out, p->rowSeparator);
19935       raw_printf(p->out, "\n");
19936     switch( p->statsOn ){
19937       case 0:  zOut = "off";     break;
19938       default: zOut = "on";      break;
19939       case 2:  zOut = "stmt";    break;
19940       case 3:  zOut = "vmstep";  break;
19941     }
19942     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
19943     utf8_printf(p->out, "%12.12s: ", "width");
19944     for (i=0;i<p->nWidth;i++) {
19945       raw_printf(p->out, "%d ", p->colWidth[i]);
19946     }
19947     raw_printf(p->out, "\n");
19948     utf8_printf(p->out, "%12.12s: %s\n", "filename",
19949                 p->zDbFilename ? p->zDbFilename : "");
19950   }else
19951
19952   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
19953     if( nArg==2 ){
19954       if( strcmp(azArg[1],"stmt")==0 ){
19955         p->statsOn = 2;
19956       }else if( strcmp(azArg[1],"vmstep")==0 ){
19957         p->statsOn = 3;
19958       }else{
19959         p->statsOn = (u8)booleanValue(azArg[1]);
19960       }
19961     }else if( nArg==1 ){
19962       display_stats(p->db, p, 0);
19963     }else{
19964       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
19965       rc = 1;
19966     }
19967   }else
19968
19969   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
19970    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
19971                  || strncmp(azArg[0], "indexes", n)==0) )
19972   ){
19973     sqlite3_stmt *pStmt;
19974     char **azResult;
19975     int nRow, nAlloc;
19976     int ii;
19977     ShellText s;
19978     initText(&s);
19979     open_db(p, 0);
19980     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
19981     if( rc ){
19982       sqlite3_finalize(pStmt);
19983       return shellDatabaseError(p->db);
19984     }
19985
19986     if( nArg>2 && c=='i' ){
19987       /* It is an historical accident that the .indexes command shows an error
19988       ** when called with the wrong number of arguments whereas the .tables
19989       ** command does not. */
19990       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
19991       rc = 1;
19992       sqlite3_finalize(pStmt);
19993       goto meta_command_exit;
19994     }
19995     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
19996       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
19997       if( zDbName==0 ) continue;
19998       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
19999       if( sqlite3_stricmp(zDbName, "main")==0 ){
20000         appendText(&s, "SELECT name FROM ", 0);
20001       }else{
20002         appendText(&s, "SELECT ", 0);
20003         appendText(&s, zDbName, '\'');
20004         appendText(&s, "||'.'||name FROM ", 0);
20005       }
20006       appendText(&s, zDbName, '"');
20007       appendText(&s, ".sqlite_schema ", 0);
20008       if( c=='t' ){
20009         appendText(&s," WHERE type IN ('table','view')"
20010                       "   AND name NOT LIKE 'sqlite_%'"
20011                       "   AND name LIKE ?1", 0);
20012       }else{
20013         appendText(&s," WHERE type='index'"
20014                       "   AND tbl_name LIKE ?1", 0);
20015       }
20016     }
20017     rc = sqlite3_finalize(pStmt);
20018     appendText(&s, " ORDER BY 1", 0);
20019     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
20020     freeText(&s);
20021     if( rc ) return shellDatabaseError(p->db);
20022
20023     /* Run the SQL statement prepared by the above block. Store the results
20024     ** as an array of nul-terminated strings in azResult[].  */
20025     nRow = nAlloc = 0;
20026     azResult = 0;
20027     if( nArg>1 ){
20028       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
20029     }else{
20030       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
20031     }
20032     while( sqlite3_step(pStmt)==SQLITE_ROW ){
20033       if( nRow>=nAlloc ){
20034         char **azNew;
20035         int n2 = nAlloc*2 + 10;
20036         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
20037         if( azNew==0 ) shell_out_of_memory();
20038         nAlloc = n2;
20039         azResult = azNew;
20040       }
20041       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
20042       if( 0==azResult[nRow] ) shell_out_of_memory();
20043       nRow++;
20044     }
20045     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
20046       rc = shellDatabaseError(p->db);
20047     }
20048
20049     /* Pretty-print the contents of array azResult[] to the output */
20050     if( rc==0 && nRow>0 ){
20051       int len, maxlen = 0;
20052       int i, j;
20053       int nPrintCol, nPrintRow;
20054       for(i=0; i<nRow; i++){
20055         len = strlen30(azResult[i]);
20056         if( len>maxlen ) maxlen = len;
20057       }
20058       nPrintCol = 80/(maxlen+2);
20059       if( nPrintCol<1 ) nPrintCol = 1;
20060       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
20061       for(i=0; i<nPrintRow; i++){
20062         for(j=i; j<nRow; j+=nPrintRow){
20063           char *zSp = j<nPrintRow ? "" : "  ";
20064           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
20065                       azResult[j] ? azResult[j]:"");
20066         }
20067         raw_printf(p->out, "\n");
20068       }
20069     }
20070
20071     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
20072     sqlite3_free(azResult);
20073   }else
20074
20075   /* Begin redirecting output to the file "testcase-out.txt" */
20076   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
20077     output_reset(p);
20078     p->out = output_file_open("testcase-out.txt", 0);
20079     if( p->out==0 ){
20080       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
20081     }
20082     if( nArg>=2 ){
20083       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
20084     }else{
20085       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
20086     }
20087   }else
20088
20089 #ifndef SQLITE_UNTESTABLE
20090   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
20091     static const struct {
20092        const char *zCtrlName;   /* Name of a test-control option */
20093        int ctrlCode;            /* Integer code for that option */
20094        const char *zUsage;      /* Usage notes */
20095     } aCtrl[] = {
20096       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
20097       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
20098     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
20099     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
20100       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
20101       { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
20102     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
20103       { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
20104       { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
20105       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
20106       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
20107       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
20108 #ifdef YYCOVERAGE
20109       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
20110 #endif
20111       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
20112       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
20113       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
20114       { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
20115       { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,    ""               },
20116     };
20117     int testctrl = -1;
20118     int iCtrl = -1;
20119     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
20120     int isOk = 0;
20121     int i, n2;
20122     const char *zCmd = 0;
20123
20124     open_db(p, 0);
20125     zCmd = nArg>=2 ? azArg[1] : "help";
20126
20127     /* The argument can optionally begin with "-" or "--" */
20128     if( zCmd[0]=='-' && zCmd[1] ){
20129       zCmd++;
20130       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
20131     }
20132
20133     /* --help lists all test-controls */
20134     if( strcmp(zCmd,"help")==0 ){
20135       utf8_printf(p->out, "Available test-controls:\n");
20136       for(i=0; i<ArraySize(aCtrl); i++){
20137         utf8_printf(p->out, "  .testctrl %s %s\n",
20138                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
20139       }
20140       rc = 1;
20141       goto meta_command_exit;
20142     }
20143
20144     /* convert testctrl text option to value. allow any unique prefix
20145     ** of the option name, or a numerical value. */
20146     n2 = strlen30(zCmd);
20147     for(i=0; i<ArraySize(aCtrl); i++){
20148       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
20149         if( testctrl<0 ){
20150           testctrl = aCtrl[i].ctrlCode;
20151           iCtrl = i;
20152         }else{
20153           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
20154                               "Use \".testctrl --help\" for help\n", zCmd);
20155           rc = 1;
20156           goto meta_command_exit;
20157         }
20158       }
20159     }
20160     if( testctrl<0 ){
20161       utf8_printf(stderr,"Error: unknown test-control: %s\n"
20162                          "Use \".testctrl --help\" for help\n", zCmd);
20163     }else{
20164       switch(testctrl){
20165
20166         /* sqlite3_test_control(int, db, int) */
20167         case SQLITE_TESTCTRL_OPTIMIZATIONS:
20168           if( nArg==3 ){
20169             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
20170             rc2 = sqlite3_test_control(testctrl, p->db, opt);
20171             isOk = 3;
20172           }
20173           break;
20174
20175         /* sqlite3_test_control(int) */
20176         case SQLITE_TESTCTRL_PRNG_SAVE:
20177         case SQLITE_TESTCTRL_PRNG_RESTORE:
20178         case SQLITE_TESTCTRL_BYTEORDER:
20179           if( nArg==2 ){
20180             rc2 = sqlite3_test_control(testctrl);
20181             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
20182           }
20183           break;
20184
20185         /* sqlite3_test_control(int, uint) */
20186         case SQLITE_TESTCTRL_PENDING_BYTE:
20187           if( nArg==3 ){
20188             unsigned int opt = (unsigned int)integerValue(azArg[2]);
20189             rc2 = sqlite3_test_control(testctrl, opt);
20190             isOk = 3;
20191           }
20192           break;
20193
20194         /* sqlite3_test_control(int, int, sqlite3*) */
20195         case SQLITE_TESTCTRL_PRNG_SEED:
20196           if( nArg==3 || nArg==4 ){
20197             int ii = (int)integerValue(azArg[2]);
20198             sqlite3 *db;
20199             if( ii==0 && strcmp(azArg[2],"random")==0 ){
20200               sqlite3_randomness(sizeof(ii),&ii);
20201               printf("-- random seed: %d\n", ii);
20202             }
20203             if( nArg==3 ){
20204               db = 0;
20205             }else{
20206               db = p->db;
20207               /* Make sure the schema has been loaded */
20208               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
20209             }
20210             rc2 = sqlite3_test_control(testctrl, ii, db);
20211             isOk = 3;
20212           }
20213           break;
20214
20215         /* sqlite3_test_control(int, int) */
20216         case SQLITE_TESTCTRL_ASSERT:
20217         case SQLITE_TESTCTRL_ALWAYS:
20218           if( nArg==3 ){
20219             int opt = booleanValue(azArg[2]);
20220             rc2 = sqlite3_test_control(testctrl, opt);
20221             isOk = 1;
20222           }
20223           break;
20224
20225         /* sqlite3_test_control(int, int) */
20226         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
20227         case SQLITE_TESTCTRL_NEVER_CORRUPT:
20228           if( nArg==3 ){
20229             int opt = booleanValue(azArg[2]);
20230             rc2 = sqlite3_test_control(testctrl, opt);
20231             isOk = 3;
20232           }
20233           break;
20234
20235         /* sqlite3_test_control(sqlite3*) */
20236         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
20237           rc2 = sqlite3_test_control(testctrl, p->db);
20238           isOk = 3;
20239           break;
20240
20241         case SQLITE_TESTCTRL_IMPOSTER:
20242           if( nArg==5 ){
20243             rc2 = sqlite3_test_control(testctrl, p->db,
20244                           azArg[2],
20245                           integerValue(azArg[3]),
20246                           integerValue(azArg[4]));
20247             isOk = 3;
20248           }
20249           break;
20250
20251         case SQLITE_TESTCTRL_SEEK_COUNT: {
20252           u64 x = 0;
20253           rc2 = sqlite3_test_control(testctrl, p->db, &x);
20254           utf8_printf(p->out, "%llu\n", x);
20255           isOk = 3;
20256           break;
20257         }
20258
20259 #ifdef YYCOVERAGE
20260         case SQLITE_TESTCTRL_PARSER_COVERAGE:
20261           if( nArg==2 ){
20262             sqlite3_test_control(testctrl, p->out);
20263             isOk = 3;
20264           }
20265 #endif
20266       }
20267     }
20268     if( isOk==0 && iCtrl>=0 ){
20269       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
20270       rc = 1;
20271     }else if( isOk==1 ){
20272       raw_printf(p->out, "%d\n", rc2);
20273     }else if( isOk==2 ){
20274       raw_printf(p->out, "0x%08x\n", rc2);
20275     }
20276   }else
20277 #endif /* !defined(SQLITE_UNTESTABLE) */
20278
20279   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
20280     open_db(p, 0);
20281     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
20282   }else
20283
20284   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
20285     if( nArg==2 ){
20286       enableTimer = booleanValue(azArg[1]);
20287       if( enableTimer && !HAS_TIMER ){
20288         raw_printf(stderr, "Error: timer not available on this system.\n");
20289         enableTimer = 0;
20290       }
20291     }else{
20292       raw_printf(stderr, "Usage: .timer on|off\n");
20293       rc = 1;
20294     }
20295   }else
20296
20297 #ifndef SQLITE_OMIT_TRACE
20298   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
20299     int mType = 0;
20300     int jj;
20301     open_db(p, 0);
20302     for(jj=1; jj<nArg; jj++){
20303       const char *z = azArg[jj];
20304       if( z[0]=='-' ){
20305         if( optionMatch(z, "expanded") ){
20306           p->eTraceType = SHELL_TRACE_EXPANDED;
20307         }
20308 #ifdef SQLITE_ENABLE_NORMALIZE
20309         else if( optionMatch(z, "normalized") ){
20310           p->eTraceType = SHELL_TRACE_NORMALIZED;
20311         }
20312 #endif
20313         else if( optionMatch(z, "plain") ){
20314           p->eTraceType = SHELL_TRACE_PLAIN;
20315         }
20316         else if( optionMatch(z, "profile") ){
20317           mType |= SQLITE_TRACE_PROFILE;
20318         }
20319         else if( optionMatch(z, "row") ){
20320           mType |= SQLITE_TRACE_ROW;
20321         }
20322         else if( optionMatch(z, "stmt") ){
20323           mType |= SQLITE_TRACE_STMT;
20324         }
20325         else if( optionMatch(z, "close") ){
20326           mType |= SQLITE_TRACE_CLOSE;
20327         }
20328         else {
20329           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
20330           rc = 1;
20331           goto meta_command_exit;
20332         }
20333       }else{
20334         output_file_close(p->traceOut);
20335         p->traceOut = output_file_open(azArg[1], 0);
20336       }
20337     }
20338     if( p->traceOut==0 ){
20339       sqlite3_trace_v2(p->db, 0, 0, 0);
20340     }else{
20341       if( mType==0 ) mType = SQLITE_TRACE_STMT;
20342       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
20343     }
20344   }else
20345 #endif /* !defined(SQLITE_OMIT_TRACE) */
20346
20347 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
20348   if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
20349     int ii;
20350     int lenOpt;
20351     char *zOpt;
20352     if( nArg<2 ){
20353       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
20354       rc = 1;
20355       goto meta_command_exit;
20356     }
20357     open_db(p, 0);
20358     zOpt = azArg[1];
20359     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
20360     lenOpt = (int)strlen(zOpt);
20361     if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
20362       assert( azArg[nArg]==0 );
20363       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
20364     }else{
20365       for(ii=1; ii<nArg; ii++){
20366         sqlite3_create_module(p->db, azArg[ii], 0, 0);
20367       }
20368     }
20369   }else
20370 #endif
20371
20372 #if SQLITE_USER_AUTHENTICATION
20373   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
20374     if( nArg<2 ){
20375       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
20376       rc = 1;
20377       goto meta_command_exit;
20378     }
20379     open_db(p, 0);
20380     if( strcmp(azArg[1],"login")==0 ){
20381       if( nArg!=4 ){
20382         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
20383         rc = 1;
20384         goto meta_command_exit;
20385       }
20386       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
20387                                      strlen30(azArg[3]));
20388       if( rc ){
20389         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
20390         rc = 1;
20391       }
20392     }else if( strcmp(azArg[1],"add")==0 ){
20393       if( nArg!=5 ){
20394         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
20395         rc = 1;
20396         goto meta_command_exit;
20397       }
20398       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
20399                             booleanValue(azArg[4]));
20400       if( rc ){
20401         raw_printf(stderr, "User-Add failed: %d\n", rc);
20402         rc = 1;
20403       }
20404     }else if( strcmp(azArg[1],"edit")==0 ){
20405       if( nArg!=5 ){
20406         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
20407         rc = 1;
20408         goto meta_command_exit;
20409       }
20410       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
20411                               booleanValue(azArg[4]));
20412       if( rc ){
20413         raw_printf(stderr, "User-Edit failed: %d\n", rc);
20414         rc = 1;
20415       }
20416     }else if( strcmp(azArg[1],"delete")==0 ){
20417       if( nArg!=3 ){
20418         raw_printf(stderr, "Usage: .user delete USER\n");
20419         rc = 1;
20420         goto meta_command_exit;
20421       }
20422       rc = sqlite3_user_delete(p->db, azArg[2]);
20423       if( rc ){
20424         raw_printf(stderr, "User-Delete failed: %d\n", rc);
20425         rc = 1;
20426       }
20427     }else{
20428       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
20429       rc = 1;
20430       goto meta_command_exit;
20431     }
20432   }else
20433 #endif /* SQLITE_USER_AUTHENTICATION */
20434
20435   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
20436     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
20437         sqlite3_libversion(), sqlite3_sourceid());
20438 #if SQLITE_HAVE_ZLIB
20439     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
20440 #endif
20441 #define CTIMEOPT_VAL_(opt) #opt
20442 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
20443 #if defined(__clang__) && defined(__clang_major__)
20444     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
20445                     CTIMEOPT_VAL(__clang_minor__) "."
20446                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
20447 #elif defined(_MSC_VER)
20448     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
20449 #elif defined(__GNUC__) && defined(__VERSION__)
20450     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
20451 #endif
20452   }else
20453
20454   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
20455     const char *zDbName = nArg==2 ? azArg[1] : "main";
20456     sqlite3_vfs *pVfs = 0;
20457     if( p->db ){
20458       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
20459       if( pVfs ){
20460         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
20461         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
20462         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
20463         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
20464       }
20465     }
20466   }else
20467
20468   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
20469     sqlite3_vfs *pVfs;
20470     sqlite3_vfs *pCurrent = 0;
20471     if( p->db ){
20472       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
20473     }
20474     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
20475       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
20476            pVfs==pCurrent ? "  <--- CURRENT" : "");
20477       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
20478       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
20479       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
20480       if( pVfs->pNext ){
20481         raw_printf(p->out, "-----------------------------------\n");
20482       }
20483     }
20484   }else
20485
20486   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
20487     const char *zDbName = nArg==2 ? azArg[1] : "main";
20488     char *zVfsName = 0;
20489     if( p->db ){
20490       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
20491       if( zVfsName ){
20492         utf8_printf(p->out, "%s\n", zVfsName);
20493         sqlite3_free(zVfsName);
20494       }
20495     }
20496   }else
20497
20498   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
20499     unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
20500     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
20501   }else
20502
20503   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
20504     int j;
20505     assert( nArg<=ArraySize(azArg) );
20506     p->nWidth = nArg-1;
20507     p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
20508     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
20509     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
20510     for(j=1; j<nArg; j++){
20511       p->colWidth[j-1] = (int)integerValue(azArg[j]);
20512     }
20513   }else
20514
20515   {
20516     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
20517       " \"%s\". Enter \".help\" for help\n", azArg[0]);
20518     rc = 1;
20519   }
20520
20521 meta_command_exit:
20522   if( p->outCount ){
20523     p->outCount--;
20524     if( p->outCount==0 ) output_reset(p);
20525   }
20526   return rc;
20527 }
20528
20529 /*
20530 ** Return TRUE if a semicolon occurs anywhere in the first N characters
20531 ** of string z[].
20532 */
20533 static int line_contains_semicolon(const char *z, int N){
20534   int i;
20535   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
20536   return 0;
20537 }
20538
20539 /*
20540 ** Test to see if a line consists entirely of whitespace.
20541 */
20542 static int _all_whitespace(const char *z){
20543   for(; *z; z++){
20544     if( IsSpace(z[0]) ) continue;
20545     if( *z=='/' && z[1]=='*' ){
20546       z += 2;
20547       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
20548       if( *z==0 ) return 0;
20549       z++;
20550       continue;
20551     }
20552     if( *z=='-' && z[1]=='-' ){
20553       z += 2;
20554       while( *z && *z!='\n' ){ z++; }
20555       if( *z==0 ) return 1;
20556       continue;
20557     }
20558     return 0;
20559   }
20560   return 1;
20561 }
20562
20563 /*
20564 ** Return TRUE if the line typed in is an SQL command terminator other
20565 ** than a semi-colon.  The SQL Server style "go" command is understood
20566 ** as is the Oracle "/".
20567 */
20568 static int line_is_command_terminator(const char *zLine){
20569   while( IsSpace(zLine[0]) ){ zLine++; };
20570   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
20571     return 1;  /* Oracle */
20572   }
20573   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
20574          && _all_whitespace(&zLine[2]) ){
20575     return 1;  /* SQL Server */
20576   }
20577   return 0;
20578 }
20579
20580 /*
20581 ** We need a default sqlite3_complete() implementation to use in case
20582 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
20583 ** any arbitrary text is a complete SQL statement.  This is not very
20584 ** user-friendly, but it does seem to work.
20585 */
20586 #ifdef SQLITE_OMIT_COMPLETE
20587 #define sqlite3_complete(x) 1
20588 #endif
20589
20590 /*
20591 ** Return true if zSql is a complete SQL statement.  Return false if it
20592 ** ends in the middle of a string literal or C-style comment.
20593 */
20594 static int line_is_complete(char *zSql, int nSql){
20595   int rc;
20596   if( zSql==0 ) return 1;
20597   zSql[nSql] = ';';
20598   zSql[nSql+1] = 0;
20599   rc = sqlite3_complete(zSql);
20600   zSql[nSql] = 0;
20601   return rc;
20602 }
20603
20604 /*
20605 ** Run a single line of SQL.  Return the number of errors.
20606 */
20607 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
20608   int rc;
20609   char *zErrMsg = 0;
20610
20611   open_db(p, 0);
20612   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
20613   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
20614   BEGIN_TIMER;
20615   rc = shell_exec(p, zSql, &zErrMsg);
20616   END_TIMER;
20617   if( rc || zErrMsg ){
20618     char zPrefix[100];
20619     if( in!=0 || !stdin_is_interactive ){
20620       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
20621                        "Error: near line %d:", startline);
20622     }else{
20623       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
20624     }
20625     if( zErrMsg!=0 ){
20626       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
20627       sqlite3_free(zErrMsg);
20628       zErrMsg = 0;
20629     }else{
20630       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
20631     }
20632     return 1;
20633   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
20634     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
20635             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
20636   }
20637   return 0;
20638 }
20639
20640
20641 /*
20642 ** Read input from *in and process it.  If *in==0 then input
20643 ** is interactive - the user is typing it it.  Otherwise, input
20644 ** is coming from a file or device.  A prompt is issued and history
20645 ** is saved only if input is interactive.  An interrupt signal will
20646 ** cause this routine to exit immediately, unless input is interactive.
20647 **
20648 ** Return the number of errors.
20649 */
20650 static int process_input(ShellState *p){
20651   char *zLine = 0;          /* A single input line */
20652   char *zSql = 0;           /* Accumulated SQL text */
20653   int nLine;                /* Length of current line */
20654   int nSql = 0;             /* Bytes of zSql[] used */
20655   int nAlloc = 0;           /* Allocated zSql[] space */
20656   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
20657   int rc;                   /* Error code */
20658   int errCnt = 0;           /* Number of errors seen */
20659   int startline = 0;        /* Line number for start of current input */
20660
20661   p->lineno = 0;
20662   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
20663     fflush(p->out);
20664     zLine = one_input_line(p->in, zLine, nSql>0);
20665     if( zLine==0 ){
20666       /* End of input */
20667       if( p->in==0 && stdin_is_interactive ) printf("\n");
20668       break;
20669     }
20670     if( seenInterrupt ){
20671       if( p->in!=0 ) break;
20672       seenInterrupt = 0;
20673     }
20674     p->lineno++;
20675     if( nSql==0 && _all_whitespace(zLine) ){
20676       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
20677       continue;
20678     }
20679     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
20680       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
20681       if( zLine[0]=='.' ){
20682         rc = do_meta_command(zLine, p);
20683         if( rc==2 ){ /* exit requested */
20684           break;
20685         }else if( rc ){
20686           errCnt++;
20687         }
20688       }
20689       continue;
20690     }
20691     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
20692       memcpy(zLine,";",2);
20693     }
20694     nLine = strlen30(zLine);
20695     if( nSql+nLine+2>=nAlloc ){
20696       nAlloc = nSql+nLine+100;
20697       zSql = realloc(zSql, nAlloc);
20698       if( zSql==0 ) shell_out_of_memory();
20699     }
20700     nSqlPrior = nSql;
20701     if( nSql==0 ){
20702       int i;
20703       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
20704       assert( nAlloc>0 && zSql!=0 );
20705       memcpy(zSql, zLine+i, nLine+1-i);
20706       startline = p->lineno;
20707       nSql = nLine-i;
20708     }else{
20709       zSql[nSql++] = '\n';
20710       memcpy(zSql+nSql, zLine, nLine+1);
20711       nSql += nLine;
20712     }
20713     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
20714                 && sqlite3_complete(zSql) ){
20715       errCnt += runOneSqlLine(p, zSql, p->in, startline);
20716       nSql = 0;
20717       if( p->outCount ){
20718         output_reset(p);
20719         p->outCount = 0;
20720       }else{
20721         clearTempFile(p);
20722       }
20723     }else if( nSql && _all_whitespace(zSql) ){
20724       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
20725       nSql = 0;
20726     }
20727   }
20728   if( nSql && !_all_whitespace(zSql) ){
20729     errCnt += runOneSqlLine(p, zSql, p->in, startline);
20730   }
20731   free(zSql);
20732   free(zLine);
20733   return errCnt>0;
20734 }
20735
20736 /*
20737 ** Return a pathname which is the user's home directory.  A
20738 ** 0 return indicates an error of some kind.
20739 */
20740 static char *find_home_dir(int clearFlag){
20741   static char *home_dir = NULL;
20742   if( clearFlag ){
20743     free(home_dir);
20744     home_dir = 0;
20745     return 0;
20746   }
20747   if( home_dir ) return home_dir;
20748
20749 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
20750      && !defined(__RTP__) && !defined(_WRS_KERNEL)
20751   {
20752     struct passwd *pwent;
20753     uid_t uid = getuid();
20754     if( (pwent=getpwuid(uid)) != NULL) {
20755       home_dir = pwent->pw_dir;
20756     }
20757   }
20758 #endif
20759
20760 #if defined(_WIN32_WCE)
20761   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
20762    */
20763   home_dir = "/";
20764 #else
20765
20766 #if defined(_WIN32) || defined(WIN32)
20767   if (!home_dir) {
20768     home_dir = getenv("USERPROFILE");
20769   }
20770 #endif
20771
20772   if (!home_dir) {
20773     home_dir = getenv("HOME");
20774   }
20775
20776 #if defined(_WIN32) || defined(WIN32)
20777   if (!home_dir) {
20778     char *zDrive, *zPath;
20779     int n;
20780     zDrive = getenv("HOMEDRIVE");
20781     zPath = getenv("HOMEPATH");
20782     if( zDrive && zPath ){
20783       n = strlen30(zDrive) + strlen30(zPath) + 1;
20784       home_dir = malloc( n );
20785       if( home_dir==0 ) return 0;
20786       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
20787       return home_dir;
20788     }
20789     home_dir = "c:\\";
20790   }
20791 #endif
20792
20793 #endif /* !_WIN32_WCE */
20794
20795   if( home_dir ){
20796     int n = strlen30(home_dir) + 1;
20797     char *z = malloc( n );
20798     if( z ) memcpy(z, home_dir, n);
20799     home_dir = z;
20800   }
20801
20802   return home_dir;
20803 }
20804
20805 /*
20806 ** Read input from the file given by sqliterc_override.  Or if that
20807 ** parameter is NULL, take input from ~/.sqliterc
20808 **
20809 ** Returns the number of errors.
20810 */
20811 static void process_sqliterc(
20812   ShellState *p,                  /* Configuration data */
20813   const char *sqliterc_override   /* Name of config file. NULL to use default */
20814 ){
20815   char *home_dir = NULL;
20816   const char *sqliterc = sqliterc_override;
20817   char *zBuf = 0;
20818   FILE *inSaved = p->in;
20819   int savedLineno = p->lineno;
20820
20821   if (sqliterc == NULL) {
20822     home_dir = find_home_dir(0);
20823     if( home_dir==0 ){
20824       raw_printf(stderr, "-- warning: cannot find home directory;"
20825                       " cannot read ~/.sqliterc\n");
20826       return;
20827     }
20828     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
20829     sqliterc = zBuf;
20830   }
20831   p->in = fopen(sqliterc,"rb");
20832   if( p->in ){
20833     if( stdin_is_interactive ){
20834       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
20835     }
20836     if( process_input(p) && bail_on_error ) exit(1);
20837     fclose(p->in);
20838   }else if( sqliterc_override!=0 ){
20839     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
20840     if( bail_on_error ) exit(1);
20841   }
20842   p->in = inSaved;
20843   p->lineno = savedLineno;
20844   sqlite3_free(zBuf);
20845 }
20846
20847 /*
20848 ** Show available command line options
20849 */
20850 static const char zOptions[] =
20851 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
20852   "   -A ARGS...           run \".archive ARGS\" and exit\n"
20853 #endif
20854   "   -append              append the database to the end of the file\n"
20855   "   -ascii               set output mode to 'ascii'\n"
20856   "   -bail                stop after hitting an error\n"
20857   "   -batch               force batch I/O\n"
20858   "   -box                 set output mode to 'box'\n"
20859   "   -column              set output mode to 'column'\n"
20860   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
20861   "   -csv                 set output mode to 'csv'\n"
20862 #if defined(SQLITE_ENABLE_DESERIALIZE)
20863   "   -deserialize         open the database using sqlite3_deserialize()\n"
20864 #endif
20865   "   -echo                print commands before execution\n"
20866   "   -init FILENAME       read/process named file\n"
20867   "   -[no]header          turn headers on or off\n"
20868 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
20869   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
20870 #endif
20871   "   -help                show this message\n"
20872   "   -html                set output mode to HTML\n"
20873   "   -interactive         force interactive I/O\n"
20874   "   -json                set output mode to 'json'\n"
20875   "   -line                set output mode to 'line'\n"
20876   "   -list                set output mode to 'list'\n"
20877   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
20878   "   -markdown            set output mode to 'markdown'\n"
20879 #if defined(SQLITE_ENABLE_DESERIALIZE)
20880   "   -maxsize N           maximum size for a --deserialize database\n"
20881 #endif
20882   "   -memtrace            trace all memory allocations and deallocations\n"
20883   "   -mmap N              default mmap size set to N\n"
20884 #ifdef SQLITE_ENABLE_MULTIPLEX
20885   "   -multiplex           enable the multiplexor VFS\n"
20886 #endif
20887   "   -newline SEP         set output row separator. Default: '\\n'\n"
20888   "   -nofollow            refuse to open symbolic links to database files\n"
20889   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
20890   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
20891   "   -quote               set output mode to 'quote'\n"
20892   "   -readonly            open the database read-only\n"
20893   "   -separator SEP       set output column separator. Default: '|'\n"
20894 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
20895   "   -sorterref SIZE      sorter references threshold size\n"
20896 #endif
20897   "   -stats               print memory stats before each finalize\n"
20898   "   -table               set output mode to 'table'\n"
20899   "   -tabs                set output mode to 'tabs'\n"
20900   "   -version             show SQLite version\n"
20901   "   -vfs NAME            use NAME as the default VFS\n"
20902 #ifdef SQLITE_ENABLE_VFSTRACE
20903   "   -vfstrace            enable tracing of all VFS calls\n"
20904 #endif
20905 #ifdef SQLITE_HAVE_ZLIB
20906   "   -zip                 open the file as a ZIP Archive\n"
20907 #endif
20908 ;
20909 static void usage(int showDetail){
20910   utf8_printf(stderr,
20911       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
20912       "FILENAME is the name of an SQLite database. A new database is created\n"
20913       "if the file does not previously exist.\n", Argv0);
20914   if( showDetail ){
20915     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
20916   }else{
20917     raw_printf(stderr, "Use the -help option for additional information\n");
20918   }
20919   exit(1);
20920 }
20921
20922 /*
20923 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
20924 ** error message if it is initialized.
20925 */
20926 static void verify_uninitialized(void){
20927   if( sqlite3_config(-1)==SQLITE_MISUSE ){
20928     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
20929                         " initialization.\n");
20930   }
20931 }
20932
20933 /*
20934 ** Initialize the state information in data
20935 */
20936 static void main_init(ShellState *data) {
20937   memset(data, 0, sizeof(*data));
20938   data->normalMode = data->cMode = data->mode = MODE_List;
20939   data->autoExplain = 1;
20940   memcpy(data->colSeparator,SEP_Column, 2);
20941   memcpy(data->rowSeparator,SEP_Row, 2);
20942   data->showHeader = 0;
20943   data->shellFlgs = SHFLG_Lookaside;
20944   verify_uninitialized();
20945   sqlite3_config(SQLITE_CONFIG_URI, 1);
20946   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
20947   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
20948   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
20949   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
20950 }
20951
20952 /*
20953 ** Output text to the console in a font that attracts extra attention.
20954 */
20955 #ifdef _WIN32
20956 static void printBold(const char *zText){
20957 #if !SQLITE_OS_WINRT
20958   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
20959   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
20960   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
20961   SetConsoleTextAttribute(out,
20962          FOREGROUND_RED|FOREGROUND_INTENSITY
20963   );
20964 #endif
20965   printf("%s", zText);
20966 #if !SQLITE_OS_WINRT
20967   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
20968 #endif
20969 }
20970 #else
20971 static void printBold(const char *zText){
20972   printf("\033[1m%s\033[0m", zText);
20973 }
20974 #endif
20975
20976 /*
20977 ** Get the argument to an --option.  Throw an error and die if no argument
20978 ** is available.
20979 */
20980 static char *cmdline_option_value(int argc, char **argv, int i){
20981   if( i==argc ){
20982     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
20983             argv[0], argv[argc-1]);
20984     exit(1);
20985   }
20986   return argv[i];
20987 }
20988
20989 #ifndef SQLITE_SHELL_IS_UTF8
20990 #  if (defined(_WIN32) || defined(WIN32)) \
20991    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
20992 #    define SQLITE_SHELL_IS_UTF8          (0)
20993 #  else
20994 #    define SQLITE_SHELL_IS_UTF8          (1)
20995 #  endif
20996 #endif
20997
20998 #if SQLITE_SHELL_IS_UTF8
20999 int SQLITE_CDECL main(int argc, char **argv){
21000 #else
21001 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
21002   char **argv;
21003 #endif
21004   char *zErrMsg = 0;
21005   ShellState data;
21006   const char *zInitFile = 0;
21007   int i;
21008   int rc = 0;
21009   int warnInmemoryDb = 0;
21010   int readStdin = 1;
21011   int nCmd = 0;
21012   char **azCmd = 0;
21013   const char *zVfs = 0;           /* Value of -vfs command-line option */
21014 #if !SQLITE_SHELL_IS_UTF8
21015   char **argvToFree = 0;
21016   int argcToFree = 0;
21017 #endif
21018
21019   setBinaryMode(stdin, 0);
21020   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
21021   stdin_is_interactive = isatty(0);
21022   stdout_is_console = isatty(1);
21023
21024 #ifdef SQLITE_DEBUG
21025   registerOomSimulator();
21026 #endif
21027
21028 #if !defined(_WIN32_WCE)
21029   if( getenv("SQLITE_DEBUG_BREAK") ){
21030     if( isatty(0) && isatty(2) ){
21031       fprintf(stderr,
21032           "attach debugger to process %d and press any key to continue.\n",
21033           GETPID());
21034       fgetc(stdin);
21035     }else{
21036 #if defined(_WIN32) || defined(WIN32)
21037 #if SQLITE_OS_WINRT
21038       __debugbreak();
21039 #else
21040       DebugBreak();
21041 #endif
21042 #elif defined(SIGTRAP)
21043       raise(SIGTRAP);
21044 #endif
21045     }
21046   }
21047 #endif
21048
21049 #if USE_SYSTEM_SQLITE+0!=1
21050   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
21051     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
21052             sqlite3_sourceid(), SQLITE_SOURCE_ID);
21053     exit(1);
21054   }
21055 #endif
21056   main_init(&data);
21057
21058   /* On Windows, we must translate command-line arguments into UTF-8.
21059   ** The SQLite memory allocator subsystem has to be enabled in order to
21060   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
21061   ** subsequent sqlite3_config() calls will work.  So copy all results into
21062   ** memory that does not come from the SQLite memory allocator.
21063   */
21064 #if !SQLITE_SHELL_IS_UTF8
21065   sqlite3_initialize();
21066   argvToFree = malloc(sizeof(argv[0])*argc*2);
21067   argcToFree = argc;
21068   argv = argvToFree + argc;
21069   if( argv==0 ) shell_out_of_memory();
21070   for(i=0; i<argc; i++){
21071     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
21072     int n;
21073     if( z==0 ) shell_out_of_memory();
21074     n = (int)strlen(z);
21075     argv[i] = malloc( n+1 );
21076     if( argv[i]==0 ) shell_out_of_memory();
21077     memcpy(argv[i], z, n+1);
21078     argvToFree[i] = argv[i];
21079     sqlite3_free(z);
21080   }
21081   sqlite3_shutdown();
21082 #endif
21083
21084   assert( argc>=1 && argv && argv[0] );
21085   Argv0 = argv[0];
21086
21087   /* Make sure we have a valid signal handler early, before anything
21088   ** else is done.
21089   */
21090 #ifdef SIGINT
21091   signal(SIGINT, interrupt_handler);
21092 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
21093   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
21094 #endif
21095
21096 #ifdef SQLITE_SHELL_DBNAME_PROC
21097   {
21098     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
21099     ** of a C-function that will provide the name of the database file.  Use
21100     ** this compile-time option to embed this shell program in larger
21101     ** applications. */
21102     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
21103     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
21104     warnInmemoryDb = 0;
21105   }
21106 #endif
21107
21108   /* Do an initial pass through the command-line argument to locate
21109   ** the name of the database file, the name of the initialization file,
21110   ** the size of the alternative malloc heap,
21111   ** and the first command to execute.
21112   */
21113   verify_uninitialized();
21114   for(i=1; i<argc; i++){
21115     char *z;
21116     z = argv[i];
21117     if( z[0]!='-' ){
21118       if( data.zDbFilename==0 ){
21119         data.zDbFilename = z;
21120       }else{
21121         /* Excesss arguments are interpreted as SQL (or dot-commands) and
21122         ** mean that nothing is read from stdin */
21123         readStdin = 0;
21124         nCmd++;
21125         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
21126         if( azCmd==0 ) shell_out_of_memory();
21127         azCmd[nCmd-1] = z;
21128       }
21129     }
21130     if( z[1]=='-' ) z++;
21131     if( strcmp(z,"-separator")==0
21132      || strcmp(z,"-nullvalue")==0
21133      || strcmp(z,"-newline")==0
21134      || strcmp(z,"-cmd")==0
21135     ){
21136       (void)cmdline_option_value(argc, argv, ++i);
21137     }else if( strcmp(z,"-init")==0 ){
21138       zInitFile = cmdline_option_value(argc, argv, ++i);
21139     }else if( strcmp(z,"-batch")==0 ){
21140       /* Need to check for batch mode here to so we can avoid printing
21141       ** informational messages (like from process_sqliterc) before
21142       ** we do the actual processing of arguments later in a second pass.
21143       */
21144       stdin_is_interactive = 0;
21145     }else if( strcmp(z,"-heap")==0 ){
21146 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
21147       const char *zSize;
21148       sqlite3_int64 szHeap;
21149
21150       zSize = cmdline_option_value(argc, argv, ++i);
21151       szHeap = integerValue(zSize);
21152       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
21153       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
21154 #else
21155       (void)cmdline_option_value(argc, argv, ++i);
21156 #endif
21157     }else if( strcmp(z,"-pagecache")==0 ){
21158       sqlite3_int64 n, sz;
21159       sz = integerValue(cmdline_option_value(argc,argv,++i));
21160       if( sz>70000 ) sz = 70000;
21161       if( sz<0 ) sz = 0;
21162       n = integerValue(cmdline_option_value(argc,argv,++i));
21163       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
21164         n = 0xffffffffffffLL/sz;
21165       }
21166       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
21167                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
21168       data.shellFlgs |= SHFLG_Pagecache;
21169     }else if( strcmp(z,"-lookaside")==0 ){
21170       int n, sz;
21171       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
21172       if( sz<0 ) sz = 0;
21173       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
21174       if( n<0 ) n = 0;
21175       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
21176       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
21177 #ifdef SQLITE_ENABLE_VFSTRACE
21178     }else if( strcmp(z,"-vfstrace")==0 ){
21179       extern int vfstrace_register(
21180          const char *zTraceName,
21181          const char *zOldVfsName,
21182          int (*xOut)(const char*,void*),
21183          void *pOutArg,
21184          int makeDefault
21185       );
21186       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
21187 #endif
21188 #ifdef SQLITE_ENABLE_MULTIPLEX
21189     }else if( strcmp(z,"-multiplex")==0 ){
21190       extern int sqlite3_multiple_initialize(const char*,int);
21191       sqlite3_multiplex_initialize(0, 1);
21192 #endif
21193     }else if( strcmp(z,"-mmap")==0 ){
21194       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
21195       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
21196 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
21197     }else if( strcmp(z,"-sorterref")==0 ){
21198       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
21199       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
21200 #endif
21201     }else if( strcmp(z,"-vfs")==0 ){
21202       zVfs = cmdline_option_value(argc, argv, ++i);
21203 #ifdef SQLITE_HAVE_ZLIB
21204     }else if( strcmp(z,"-zip")==0 ){
21205       data.openMode = SHELL_OPEN_ZIPFILE;
21206 #endif
21207     }else if( strcmp(z,"-append")==0 ){
21208       data.openMode = SHELL_OPEN_APPENDVFS;
21209 #ifdef SQLITE_ENABLE_DESERIALIZE
21210     }else if( strcmp(z,"-deserialize")==0 ){
21211       data.openMode = SHELL_OPEN_DESERIALIZE;
21212     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
21213       data.szMax = integerValue(argv[++i]);
21214 #endif
21215     }else if( strcmp(z,"-readonly")==0 ){
21216       data.openMode = SHELL_OPEN_READONLY;
21217     }else if( strcmp(z,"-nofollow")==0 ){
21218       data.openFlags = SQLITE_OPEN_NOFOLLOW;
21219 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
21220     }else if( strncmp(z, "-A",2)==0 ){
21221       /* All remaining command-line arguments are passed to the ".archive"
21222       ** command, so ignore them */
21223       break;
21224 #endif
21225     }else if( strcmp(z, "-memtrace")==0 ){
21226       sqlite3MemTraceActivate(stderr);
21227     }else if( strcmp(z,"-bail")==0 ){
21228       bail_on_error = 1;
21229     }
21230   }
21231   verify_uninitialized();
21232
21233
21234 #ifdef SQLITE_SHELL_INIT_PROC
21235   {
21236     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
21237     ** of a C-function that will perform initialization actions on SQLite that
21238     ** occur just before or after sqlite3_initialize(). Use this compile-time
21239     ** option to embed this shell program in larger applications. */
21240     extern void SQLITE_SHELL_INIT_PROC(void);
21241     SQLITE_SHELL_INIT_PROC();
21242   }
21243 #else
21244   /* All the sqlite3_config() calls have now been made. So it is safe
21245   ** to call sqlite3_initialize() and process any command line -vfs option. */
21246   sqlite3_initialize();
21247 #endif
21248
21249   if( zVfs ){
21250     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
21251     if( pVfs ){
21252       sqlite3_vfs_register(pVfs, 1);
21253     }else{
21254       utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
21255       exit(1);
21256     }
21257   }
21258
21259   if( data.zDbFilename==0 ){
21260 #ifndef SQLITE_OMIT_MEMORYDB
21261     data.zDbFilename = ":memory:";
21262     warnInmemoryDb = argc==1;
21263 #else
21264     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
21265     return 1;
21266 #endif
21267   }
21268   data.out = stdout;
21269   sqlite3_appendvfs_init(0,0,0);
21270
21271   /* Go ahead and open the database file if it already exists.  If the
21272   ** file does not exist, delay opening it.  This prevents empty database
21273   ** files from being created if a user mistypes the database name argument
21274   ** to the sqlite command-line tool.
21275   */
21276   if( access(data.zDbFilename, 0)==0 ){
21277     open_db(&data, 0);
21278   }
21279
21280   /* Process the initialization file if there is one.  If no -init option
21281   ** is given on the command line, look for a file named ~/.sqliterc and
21282   ** try to process it.
21283   */
21284   process_sqliterc(&data,zInitFile);
21285
21286   /* Make a second pass through the command-line argument and set
21287   ** options.  This second pass is delayed until after the initialization
21288   ** file is processed so that the command-line arguments will override
21289   ** settings in the initialization file.
21290   */
21291   for(i=1; i<argc; i++){
21292     char *z = argv[i];
21293     if( z[0]!='-' ) continue;
21294     if( z[1]=='-' ){ z++; }
21295     if( strcmp(z,"-init")==0 ){
21296       i++;
21297     }else if( strcmp(z,"-html")==0 ){
21298       data.mode = MODE_Html;
21299     }else if( strcmp(z,"-list")==0 ){
21300       data.mode = MODE_List;
21301     }else if( strcmp(z,"-quote")==0 ){
21302       data.mode = MODE_Quote;
21303       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
21304       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
21305     }else if( strcmp(z,"-line")==0 ){
21306       data.mode = MODE_Line;
21307     }else if( strcmp(z,"-column")==0 ){
21308       data.mode = MODE_Column;
21309     }else if( strcmp(z,"-json")==0 ){
21310       data.mode = MODE_Json;
21311     }else if( strcmp(z,"-markdown")==0 ){
21312       data.mode = MODE_Markdown;
21313     }else if( strcmp(z,"-table")==0 ){
21314       data.mode = MODE_Table;
21315     }else if( strcmp(z,"-box")==0 ){
21316       data.mode = MODE_Box;
21317     }else if( strcmp(z,"-csv")==0 ){
21318       data.mode = MODE_Csv;
21319       memcpy(data.colSeparator,",",2);
21320 #ifdef SQLITE_HAVE_ZLIB
21321     }else if( strcmp(z,"-zip")==0 ){
21322       data.openMode = SHELL_OPEN_ZIPFILE;
21323 #endif
21324     }else if( strcmp(z,"-append")==0 ){
21325       data.openMode = SHELL_OPEN_APPENDVFS;
21326 #ifdef SQLITE_ENABLE_DESERIALIZE
21327     }else if( strcmp(z,"-deserialize")==0 ){
21328       data.openMode = SHELL_OPEN_DESERIALIZE;
21329     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
21330       data.szMax = integerValue(argv[++i]);
21331 #endif
21332     }else if( strcmp(z,"-readonly")==0 ){
21333       data.openMode = SHELL_OPEN_READONLY;
21334     }else if( strcmp(z,"-nofollow")==0 ){
21335       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
21336     }else if( strcmp(z,"-ascii")==0 ){
21337       data.mode = MODE_Ascii;
21338       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
21339       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
21340     }else if( strcmp(z,"-tabs")==0 ){
21341       data.mode = MODE_List;
21342       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
21343       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
21344     }else if( strcmp(z,"-separator")==0 ){
21345       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
21346                        "%s",cmdline_option_value(argc,argv,++i));
21347     }else if( strcmp(z,"-newline")==0 ){
21348       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
21349                        "%s",cmdline_option_value(argc,argv,++i));
21350     }else if( strcmp(z,"-nullvalue")==0 ){
21351       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
21352                        "%s",cmdline_option_value(argc,argv,++i));
21353     }else if( strcmp(z,"-header")==0 ){
21354       data.showHeader = 1;
21355     }else if( strcmp(z,"-noheader")==0 ){
21356       data.showHeader = 0;
21357     }else if( strcmp(z,"-echo")==0 ){
21358       ShellSetFlag(&data, SHFLG_Echo);
21359     }else if( strcmp(z,"-eqp")==0 ){
21360       data.autoEQP = AUTOEQP_on;
21361     }else if( strcmp(z,"-eqpfull")==0 ){
21362       data.autoEQP = AUTOEQP_full;
21363     }else if( strcmp(z,"-stats")==0 ){
21364       data.statsOn = 1;
21365     }else if( strcmp(z,"-scanstats")==0 ){
21366       data.scanstatsOn = 1;
21367     }else if( strcmp(z,"-backslash")==0 ){
21368       /* Undocumented command-line option: -backslash
21369       ** Causes C-style backslash escapes to be evaluated in SQL statements
21370       ** prior to sending the SQL into SQLite.  Useful for injecting
21371       ** crazy bytes in the middle of SQL statements for testing and debugging.
21372       */
21373       ShellSetFlag(&data, SHFLG_Backslash);
21374     }else if( strcmp(z,"-bail")==0 ){
21375       /* No-op.  The bail_on_error flag should already be set. */
21376     }else if( strcmp(z,"-version")==0 ){
21377       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
21378       return 0;
21379     }else if( strcmp(z,"-interactive")==0 ){
21380       stdin_is_interactive = 1;
21381     }else if( strcmp(z,"-batch")==0 ){
21382       stdin_is_interactive = 0;
21383     }else if( strcmp(z,"-heap")==0 ){
21384       i++;
21385     }else if( strcmp(z,"-pagecache")==0 ){
21386       i+=2;
21387     }else if( strcmp(z,"-lookaside")==0 ){
21388       i+=2;
21389     }else if( strcmp(z,"-mmap")==0 ){
21390       i++;
21391     }else if( strcmp(z,"-memtrace")==0 ){
21392       i++;
21393 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
21394     }else if( strcmp(z,"-sorterref")==0 ){
21395       i++;
21396 #endif
21397     }else if( strcmp(z,"-vfs")==0 ){
21398       i++;
21399 #ifdef SQLITE_ENABLE_VFSTRACE
21400     }else if( strcmp(z,"-vfstrace")==0 ){
21401       i++;
21402 #endif
21403 #ifdef SQLITE_ENABLE_MULTIPLEX
21404     }else if( strcmp(z,"-multiplex")==0 ){
21405       i++;
21406 #endif
21407     }else if( strcmp(z,"-help")==0 ){
21408       usage(1);
21409     }else if( strcmp(z,"-cmd")==0 ){
21410       /* Run commands that follow -cmd first and separately from commands
21411       ** that simply appear on the command-line.  This seems goofy.  It would
21412       ** be better if all commands ran in the order that they appear.  But
21413       ** we retain the goofy behavior for historical compatibility. */
21414       if( i==argc-1 ) break;
21415       z = cmdline_option_value(argc,argv,++i);
21416       if( z[0]=='.' ){
21417         rc = do_meta_command(z, &data);
21418         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
21419       }else{
21420         open_db(&data, 0);
21421         rc = shell_exec(&data, z, &zErrMsg);
21422         if( zErrMsg!=0 ){
21423           utf8_printf(stderr,"Error: %s\n", zErrMsg);
21424           if( bail_on_error ) return rc!=0 ? rc : 1;
21425         }else if( rc!=0 ){
21426           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
21427           if( bail_on_error ) return rc;
21428         }
21429       }
21430 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
21431     }else if( strncmp(z, "-A", 2)==0 ){
21432       if( nCmd>0 ){
21433         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
21434                             " with \"%s\"\n", z);
21435         return 1;
21436       }
21437       open_db(&data, OPEN_DB_ZIPFILE);
21438       if( z[2] ){
21439         argv[i] = &z[2];
21440         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
21441       }else{
21442         arDotCommand(&data, 1, argv+i, argc-i);
21443       }
21444       readStdin = 0;
21445       break;
21446 #endif
21447     }else{
21448       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
21449       raw_printf(stderr,"Use -help for a list of options.\n");
21450       return 1;
21451     }
21452     data.cMode = data.mode;
21453   }
21454
21455   if( !readStdin ){
21456     /* Run all arguments that do not begin with '-' as if they were separate
21457     ** command-line inputs, except for the argToSkip argument which contains
21458     ** the database filename.
21459     */
21460     for(i=0; i<nCmd; i++){
21461       if( azCmd[i][0]=='.' ){
21462         rc = do_meta_command(azCmd[i], &data);
21463         if( rc ){
21464           free(azCmd);
21465           return rc==2 ? 0 : rc;
21466         }
21467       }else{
21468         open_db(&data, 0);
21469         rc = shell_exec(&data, azCmd[i], &zErrMsg);
21470         if( zErrMsg || rc ){
21471           if( zErrMsg!=0 ){
21472             utf8_printf(stderr,"Error: %s\n", zErrMsg);
21473           }else{
21474             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
21475           }
21476           sqlite3_free(zErrMsg);
21477           free(azCmd);
21478           return rc!=0 ? rc : 1;
21479         }
21480       }
21481     }
21482   }else{
21483     /* Run commands received from standard input
21484     */
21485     if( stdin_is_interactive ){
21486       char *zHome;
21487       char *zHistory;
21488       int nHistory;
21489       printf(
21490         "SQLite version %s %.19s\n" /*extra-version-info*/
21491         "Enter \".help\" for usage hints.\n",
21492         sqlite3_libversion(), sqlite3_sourceid()
21493       );
21494       if( warnInmemoryDb ){
21495         printf("Connected to a ");
21496         printBold("transient in-memory database");
21497         printf(".\nUse \".open FILENAME\" to reopen on a "
21498                "persistent database.\n");
21499       }
21500       zHistory = getenv("SQLITE_HISTORY");
21501       if( zHistory ){
21502         zHistory = strdup(zHistory);
21503       }else if( (zHome = find_home_dir(0))!=0 ){
21504         nHistory = strlen30(zHome) + 20;
21505         if( (zHistory = malloc(nHistory))!=0 ){
21506           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
21507         }
21508       }
21509       if( zHistory ){ shell_read_history(zHistory); }
21510 #if HAVE_READLINE || HAVE_EDITLINE
21511       rl_attempted_completion_function = readline_completion;
21512 #elif HAVE_LINENOISE
21513       linenoiseSetCompletionCallback(linenoise_completion);
21514 #endif
21515       data.in = 0;
21516       rc = process_input(&data);
21517       if( zHistory ){
21518         shell_stifle_history(2000);
21519         shell_write_history(zHistory);
21520         free(zHistory);
21521       }
21522     }else{
21523       data.in = stdin;
21524       rc = process_input(&data);
21525     }
21526   }
21527   free(azCmd);
21528   set_table_name(&data, 0);
21529   if( data.db ){
21530     session_close_all(&data);
21531     close_db(data.db);
21532   }
21533   sqlite3_free(data.zFreeOnClose);
21534   find_home_dir(1);
21535   output_reset(&data);
21536   data.doXdgOpen = 0;
21537   clearTempFile(&data);
21538 #if !SQLITE_SHELL_IS_UTF8
21539   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
21540   free(argvToFree);
21541 #endif
21542   free(data.colWidth);
21543   /* Clear the global data structure so that valgrind will detect memory
21544   ** leaks */
21545   memset(&data, 0, sizeof(data));
21546   return rc;
21547 }