]> git.lizzy.rs Git - sqlite3-cmake.git/blob - src/shell.c
c13769f5e9686d32246c481de71b51e17bcf391a
[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 /* typedef sqlite3_uint64 u64; */
1428
1429 /******************************************************************************
1430 ** The Hash Engine
1431 */
1432 /*
1433 ** Macros to determine whether the machine is big or little endian,
1434 ** and whether or not that determination is run-time or compile-time.
1435 **
1436 ** For best performance, an attempt is made to guess at the byte-order
1437 ** using C-preprocessor macros.  If that is unsuccessful, or if
1438 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1439 ** at run-time.
1440 */
1441 #ifndef SHA3_BYTEORDER
1442 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1443      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1444      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1445      defined(__arm__)
1446 #   define SHA3_BYTEORDER    1234
1447 # elif defined(sparc)    || defined(__ppc__)
1448 #   define SHA3_BYTEORDER    4321
1449 # else
1450 #   define SHA3_BYTEORDER 0
1451 # endif
1452 #endif
1453
1454
1455 /*
1456 ** State structure for a SHA3 hash in progress
1457 */
1458 typedef struct SHA3Context SHA3Context;
1459 struct SHA3Context {
1460   union {
1461     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1462     unsigned char x[1600];    /* ... or 1600 bytes */
1463   } u;
1464   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1465   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1466   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1467 };
1468
1469 /*
1470 ** A single step of the Keccak mixing function for a 1600-bit state
1471 */
1472 static void KeccakF1600Step(SHA3Context *p){
1473   int i;
1474   u64 b0, b1, b2, b3, b4;
1475   u64 c0, c1, c2, c3, c4;
1476   u64 d0, d1, d2, d3, d4;
1477   static const u64 RC[] = {
1478     0x0000000000000001ULL,  0x0000000000008082ULL,
1479     0x800000000000808aULL,  0x8000000080008000ULL,
1480     0x000000000000808bULL,  0x0000000080000001ULL,
1481     0x8000000080008081ULL,  0x8000000000008009ULL,
1482     0x000000000000008aULL,  0x0000000000000088ULL,
1483     0x0000000080008009ULL,  0x000000008000000aULL,
1484     0x000000008000808bULL,  0x800000000000008bULL,
1485     0x8000000000008089ULL,  0x8000000000008003ULL,
1486     0x8000000000008002ULL,  0x8000000000000080ULL,
1487     0x000000000000800aULL,  0x800000008000000aULL,
1488     0x8000000080008081ULL,  0x8000000000008080ULL,
1489     0x0000000080000001ULL,  0x8000000080008008ULL
1490   };
1491 # define a00 (p->u.s[0])
1492 # define a01 (p->u.s[1])
1493 # define a02 (p->u.s[2])
1494 # define a03 (p->u.s[3])
1495 # define a04 (p->u.s[4])
1496 # define a10 (p->u.s[5])
1497 # define a11 (p->u.s[6])
1498 # define a12 (p->u.s[7])
1499 # define a13 (p->u.s[8])
1500 # define a14 (p->u.s[9])
1501 # define a20 (p->u.s[10])
1502 # define a21 (p->u.s[11])
1503 # define a22 (p->u.s[12])
1504 # define a23 (p->u.s[13])
1505 # define a24 (p->u.s[14])
1506 # define a30 (p->u.s[15])
1507 # define a31 (p->u.s[16])
1508 # define a32 (p->u.s[17])
1509 # define a33 (p->u.s[18])
1510 # define a34 (p->u.s[19])
1511 # define a40 (p->u.s[20])
1512 # define a41 (p->u.s[21])
1513 # define a42 (p->u.s[22])
1514 # define a43 (p->u.s[23])
1515 # define a44 (p->u.s[24])
1516 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1517
1518   for(i=0; i<24; i+=4){
1519     c0 = a00^a10^a20^a30^a40;
1520     c1 = a01^a11^a21^a31^a41;
1521     c2 = a02^a12^a22^a32^a42;
1522     c3 = a03^a13^a23^a33^a43;
1523     c4 = a04^a14^a24^a34^a44;
1524     d0 = c4^ROL64(c1, 1);
1525     d1 = c0^ROL64(c2, 1);
1526     d2 = c1^ROL64(c3, 1);
1527     d3 = c2^ROL64(c4, 1);
1528     d4 = c3^ROL64(c0, 1);
1529
1530     b0 = (a00^d0);
1531     b1 = ROL64((a11^d1), 44);
1532     b2 = ROL64((a22^d2), 43);
1533     b3 = ROL64((a33^d3), 21);
1534     b4 = ROL64((a44^d4), 14);
1535     a00 =   b0 ^((~b1)&  b2 );
1536     a00 ^= RC[i];
1537     a11 =   b1 ^((~b2)&  b3 );
1538     a22 =   b2 ^((~b3)&  b4 );
1539     a33 =   b3 ^((~b4)&  b0 );
1540     a44 =   b4 ^((~b0)&  b1 );
1541
1542     b2 = ROL64((a20^d0), 3);
1543     b3 = ROL64((a31^d1), 45);
1544     b4 = ROL64((a42^d2), 61);
1545     b0 = ROL64((a03^d3), 28);
1546     b1 = ROL64((a14^d4), 20);
1547     a20 =   b0 ^((~b1)&  b2 );
1548     a31 =   b1 ^((~b2)&  b3 );
1549     a42 =   b2 ^((~b3)&  b4 );
1550     a03 =   b3 ^((~b4)&  b0 );
1551     a14 =   b4 ^((~b0)&  b1 );
1552
1553     b4 = ROL64((a40^d0), 18);
1554     b0 = ROL64((a01^d1), 1);
1555     b1 = ROL64((a12^d2), 6);
1556     b2 = ROL64((a23^d3), 25);
1557     b3 = ROL64((a34^d4), 8);
1558     a40 =   b0 ^((~b1)&  b2 );
1559     a01 =   b1 ^((~b2)&  b3 );
1560     a12 =   b2 ^((~b3)&  b4 );
1561     a23 =   b3 ^((~b4)&  b0 );
1562     a34 =   b4 ^((~b0)&  b1 );
1563
1564     b1 = ROL64((a10^d0), 36);
1565     b2 = ROL64((a21^d1), 10);
1566     b3 = ROL64((a32^d2), 15);
1567     b4 = ROL64((a43^d3), 56);
1568     b0 = ROL64((a04^d4), 27);
1569     a10 =   b0 ^((~b1)&  b2 );
1570     a21 =   b1 ^((~b2)&  b3 );
1571     a32 =   b2 ^((~b3)&  b4 );
1572     a43 =   b3 ^((~b4)&  b0 );
1573     a04 =   b4 ^((~b0)&  b1 );
1574
1575     b3 = ROL64((a30^d0), 41);
1576     b4 = ROL64((a41^d1), 2);
1577     b0 = ROL64((a02^d2), 62);
1578     b1 = ROL64((a13^d3), 55);
1579     b2 = ROL64((a24^d4), 39);
1580     a30 =   b0 ^((~b1)&  b2 );
1581     a41 =   b1 ^((~b2)&  b3 );
1582     a02 =   b2 ^((~b3)&  b4 );
1583     a13 =   b3 ^((~b4)&  b0 );
1584     a24 =   b4 ^((~b0)&  b1 );
1585
1586     c0 = a00^a20^a40^a10^a30;
1587     c1 = a11^a31^a01^a21^a41;
1588     c2 = a22^a42^a12^a32^a02;
1589     c3 = a33^a03^a23^a43^a13;
1590     c4 = a44^a14^a34^a04^a24;
1591     d0 = c4^ROL64(c1, 1);
1592     d1 = c0^ROL64(c2, 1);
1593     d2 = c1^ROL64(c3, 1);
1594     d3 = c2^ROL64(c4, 1);
1595     d4 = c3^ROL64(c0, 1);
1596
1597     b0 = (a00^d0);
1598     b1 = ROL64((a31^d1), 44);
1599     b2 = ROL64((a12^d2), 43);
1600     b3 = ROL64((a43^d3), 21);
1601     b4 = ROL64((a24^d4), 14);
1602     a00 =   b0 ^((~b1)&  b2 );
1603     a00 ^= RC[i+1];
1604     a31 =   b1 ^((~b2)&  b3 );
1605     a12 =   b2 ^((~b3)&  b4 );
1606     a43 =   b3 ^((~b4)&  b0 );
1607     a24 =   b4 ^((~b0)&  b1 );
1608
1609     b2 = ROL64((a40^d0), 3);
1610     b3 = ROL64((a21^d1), 45);
1611     b4 = ROL64((a02^d2), 61);
1612     b0 = ROL64((a33^d3), 28);
1613     b1 = ROL64((a14^d4), 20);
1614     a40 =   b0 ^((~b1)&  b2 );
1615     a21 =   b1 ^((~b2)&  b3 );
1616     a02 =   b2 ^((~b3)&  b4 );
1617     a33 =   b3 ^((~b4)&  b0 );
1618     a14 =   b4 ^((~b0)&  b1 );
1619
1620     b4 = ROL64((a30^d0), 18);
1621     b0 = ROL64((a11^d1), 1);
1622     b1 = ROL64((a42^d2), 6);
1623     b2 = ROL64((a23^d3), 25);
1624     b3 = ROL64((a04^d4), 8);
1625     a30 =   b0 ^((~b1)&  b2 );
1626     a11 =   b1 ^((~b2)&  b3 );
1627     a42 =   b2 ^((~b3)&  b4 );
1628     a23 =   b3 ^((~b4)&  b0 );
1629     a04 =   b4 ^((~b0)&  b1 );
1630
1631     b1 = ROL64((a20^d0), 36);
1632     b2 = ROL64((a01^d1), 10);
1633     b3 = ROL64((a32^d2), 15);
1634     b4 = ROL64((a13^d3), 56);
1635     b0 = ROL64((a44^d4), 27);
1636     a20 =   b0 ^((~b1)&  b2 );
1637     a01 =   b1 ^((~b2)&  b3 );
1638     a32 =   b2 ^((~b3)&  b4 );
1639     a13 =   b3 ^((~b4)&  b0 );
1640     a44 =   b4 ^((~b0)&  b1 );
1641
1642     b3 = ROL64((a10^d0), 41);
1643     b4 = ROL64((a41^d1), 2);
1644     b0 = ROL64((a22^d2), 62);
1645     b1 = ROL64((a03^d3), 55);
1646     b2 = ROL64((a34^d4), 39);
1647     a10 =   b0 ^((~b1)&  b2 );
1648     a41 =   b1 ^((~b2)&  b3 );
1649     a22 =   b2 ^((~b3)&  b4 );
1650     a03 =   b3 ^((~b4)&  b0 );
1651     a34 =   b4 ^((~b0)&  b1 );
1652
1653     c0 = a00^a40^a30^a20^a10;
1654     c1 = a31^a21^a11^a01^a41;
1655     c2 = a12^a02^a42^a32^a22;
1656     c3 = a43^a33^a23^a13^a03;
1657     c4 = a24^a14^a04^a44^a34;
1658     d0 = c4^ROL64(c1, 1);
1659     d1 = c0^ROL64(c2, 1);
1660     d2 = c1^ROL64(c3, 1);
1661     d3 = c2^ROL64(c4, 1);
1662     d4 = c3^ROL64(c0, 1);
1663
1664     b0 = (a00^d0);
1665     b1 = ROL64((a21^d1), 44);
1666     b2 = ROL64((a42^d2), 43);
1667     b3 = ROL64((a13^d3), 21);
1668     b4 = ROL64((a34^d4), 14);
1669     a00 =   b0 ^((~b1)&  b2 );
1670     a00 ^= RC[i+2];
1671     a21 =   b1 ^((~b2)&  b3 );
1672     a42 =   b2 ^((~b3)&  b4 );
1673     a13 =   b3 ^((~b4)&  b0 );
1674     a34 =   b4 ^((~b0)&  b1 );
1675
1676     b2 = ROL64((a30^d0), 3);
1677     b3 = ROL64((a01^d1), 45);
1678     b4 = ROL64((a22^d2), 61);
1679     b0 = ROL64((a43^d3), 28);
1680     b1 = ROL64((a14^d4), 20);
1681     a30 =   b0 ^((~b1)&  b2 );
1682     a01 =   b1 ^((~b2)&  b3 );
1683     a22 =   b2 ^((~b3)&  b4 );
1684     a43 =   b3 ^((~b4)&  b0 );
1685     a14 =   b4 ^((~b0)&  b1 );
1686
1687     b4 = ROL64((a10^d0), 18);
1688     b0 = ROL64((a31^d1), 1);
1689     b1 = ROL64((a02^d2), 6);
1690     b2 = ROL64((a23^d3), 25);
1691     b3 = ROL64((a44^d4), 8);
1692     a10 =   b0 ^((~b1)&  b2 );
1693     a31 =   b1 ^((~b2)&  b3 );
1694     a02 =   b2 ^((~b3)&  b4 );
1695     a23 =   b3 ^((~b4)&  b0 );
1696     a44 =   b4 ^((~b0)&  b1 );
1697
1698     b1 = ROL64((a40^d0), 36);
1699     b2 = ROL64((a11^d1), 10);
1700     b3 = ROL64((a32^d2), 15);
1701     b4 = ROL64((a03^d3), 56);
1702     b0 = ROL64((a24^d4), 27);
1703     a40 =   b0 ^((~b1)&  b2 );
1704     a11 =   b1 ^((~b2)&  b3 );
1705     a32 =   b2 ^((~b3)&  b4 );
1706     a03 =   b3 ^((~b4)&  b0 );
1707     a24 =   b4 ^((~b0)&  b1 );
1708
1709     b3 = ROL64((a20^d0), 41);
1710     b4 = ROL64((a41^d1), 2);
1711     b0 = ROL64((a12^d2), 62);
1712     b1 = ROL64((a33^d3), 55);
1713     b2 = ROL64((a04^d4), 39);
1714     a20 =   b0 ^((~b1)&  b2 );
1715     a41 =   b1 ^((~b2)&  b3 );
1716     a12 =   b2 ^((~b3)&  b4 );
1717     a33 =   b3 ^((~b4)&  b0 );
1718     a04 =   b4 ^((~b0)&  b1 );
1719
1720     c0 = a00^a30^a10^a40^a20;
1721     c1 = a21^a01^a31^a11^a41;
1722     c2 = a42^a22^a02^a32^a12;
1723     c3 = a13^a43^a23^a03^a33;
1724     c4 = a34^a14^a44^a24^a04;
1725     d0 = c4^ROL64(c1, 1);
1726     d1 = c0^ROL64(c2, 1);
1727     d2 = c1^ROL64(c3, 1);
1728     d3 = c2^ROL64(c4, 1);
1729     d4 = c3^ROL64(c0, 1);
1730
1731     b0 = (a00^d0);
1732     b1 = ROL64((a01^d1), 44);
1733     b2 = ROL64((a02^d2), 43);
1734     b3 = ROL64((a03^d3), 21);
1735     b4 = ROL64((a04^d4), 14);
1736     a00 =   b0 ^((~b1)&  b2 );
1737     a00 ^= RC[i+3];
1738     a01 =   b1 ^((~b2)&  b3 );
1739     a02 =   b2 ^((~b3)&  b4 );
1740     a03 =   b3 ^((~b4)&  b0 );
1741     a04 =   b4 ^((~b0)&  b1 );
1742
1743     b2 = ROL64((a10^d0), 3);
1744     b3 = ROL64((a11^d1), 45);
1745     b4 = ROL64((a12^d2), 61);
1746     b0 = ROL64((a13^d3), 28);
1747     b1 = ROL64((a14^d4), 20);
1748     a10 =   b0 ^((~b1)&  b2 );
1749     a11 =   b1 ^((~b2)&  b3 );
1750     a12 =   b2 ^((~b3)&  b4 );
1751     a13 =   b3 ^((~b4)&  b0 );
1752     a14 =   b4 ^((~b0)&  b1 );
1753
1754     b4 = ROL64((a20^d0), 18);
1755     b0 = ROL64((a21^d1), 1);
1756     b1 = ROL64((a22^d2), 6);
1757     b2 = ROL64((a23^d3), 25);
1758     b3 = ROL64((a24^d4), 8);
1759     a20 =   b0 ^((~b1)&  b2 );
1760     a21 =   b1 ^((~b2)&  b3 );
1761     a22 =   b2 ^((~b3)&  b4 );
1762     a23 =   b3 ^((~b4)&  b0 );
1763     a24 =   b4 ^((~b0)&  b1 );
1764
1765     b1 = ROL64((a30^d0), 36);
1766     b2 = ROL64((a31^d1), 10);
1767     b3 = ROL64((a32^d2), 15);
1768     b4 = ROL64((a33^d3), 56);
1769     b0 = ROL64((a34^d4), 27);
1770     a30 =   b0 ^((~b1)&  b2 );
1771     a31 =   b1 ^((~b2)&  b3 );
1772     a32 =   b2 ^((~b3)&  b4 );
1773     a33 =   b3 ^((~b4)&  b0 );
1774     a34 =   b4 ^((~b0)&  b1 );
1775
1776     b3 = ROL64((a40^d0), 41);
1777     b4 = ROL64((a41^d1), 2);
1778     b0 = ROL64((a42^d2), 62);
1779     b1 = ROL64((a43^d3), 55);
1780     b2 = ROL64((a44^d4), 39);
1781     a40 =   b0 ^((~b1)&  b2 );
1782     a41 =   b1 ^((~b2)&  b3 );
1783     a42 =   b2 ^((~b3)&  b4 );
1784     a43 =   b3 ^((~b4)&  b0 );
1785     a44 =   b4 ^((~b0)&  b1 );
1786   }
1787 }
1788
1789 /*
1790 ** Initialize a new hash.  iSize determines the size of the hash
1791 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1792 ** can be zero to use the default hash size of 256 bits.
1793 */
1794 static void SHA3Init(SHA3Context *p, int iSize){
1795   memset(p, 0, sizeof(*p));
1796   if( iSize>=128 && iSize<=512 ){
1797     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1798   }else{
1799     p->nRate = (1600 - 2*256)/8;
1800   }
1801 #if SHA3_BYTEORDER==1234
1802   /* Known to be little-endian at compile-time. No-op */
1803 #elif SHA3_BYTEORDER==4321
1804   p->ixMask = 7;  /* Big-endian */
1805 #else
1806   {
1807     static unsigned int one = 1;
1808     if( 1==*(unsigned char*)&one ){
1809       /* Little endian.  No byte swapping. */
1810       p->ixMask = 0;
1811     }else{
1812       /* Big endian.  Byte swap. */
1813       p->ixMask = 7;
1814     }
1815   }
1816 #endif
1817 }
1818
1819 /*
1820 ** Make consecutive calls to the SHA3Update function to add new content
1821 ** to the hash
1822 */
1823 static void SHA3Update(
1824   SHA3Context *p,
1825   const unsigned char *aData,
1826   unsigned int nData
1827 ){
1828   unsigned int i = 0;
1829 #if SHA3_BYTEORDER==1234
1830   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1831     for(; i+7<nData; i+=8){
1832       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1833       p->nLoaded += 8;
1834       if( p->nLoaded>=p->nRate ){
1835         KeccakF1600Step(p);
1836         p->nLoaded = 0;
1837       }
1838     }
1839   }
1840 #endif
1841   for(; i<nData; i++){
1842 #if SHA3_BYTEORDER==1234
1843     p->u.x[p->nLoaded] ^= aData[i];
1844 #elif SHA3_BYTEORDER==4321
1845     p->u.x[p->nLoaded^0x07] ^= aData[i];
1846 #else
1847     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1848 #endif
1849     p->nLoaded++;
1850     if( p->nLoaded==p->nRate ){
1851       KeccakF1600Step(p);
1852       p->nLoaded = 0;
1853     }
1854   }
1855 }
1856
1857 /*
1858 ** After all content has been added, invoke SHA3Final() to compute
1859 ** the final hash.  The function returns a pointer to the binary
1860 ** hash value.
1861 */
1862 static unsigned char *SHA3Final(SHA3Context *p){
1863   unsigned int i;
1864   if( p->nLoaded==p->nRate-1 ){
1865     const unsigned char c1 = 0x86;
1866     SHA3Update(p, &c1, 1);
1867   }else{
1868     const unsigned char c2 = 0x06;
1869     const unsigned char c3 = 0x80;
1870     SHA3Update(p, &c2, 1);
1871     p->nLoaded = p->nRate - 1;
1872     SHA3Update(p, &c3, 1);
1873   }
1874   for(i=0; i<p->nRate; i++){
1875     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1876   }
1877   return &p->u.x[p->nRate];
1878 }
1879 /* End of the hashing logic
1880 *****************************************************************************/
1881
1882 /*
1883 ** Implementation of the sha3(X,SIZE) function.
1884 **
1885 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1886 ** size is 256.  If X is a BLOB, it is hashed as is.  
1887 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1888 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1889 ** of a NULL value is NULL.
1890 */
1891 static void sha3Func(
1892   sqlite3_context *context,
1893   int argc,
1894   sqlite3_value **argv
1895 ){
1896   SHA3Context cx;
1897   int eType = sqlite3_value_type(argv[0]);
1898   int nByte = sqlite3_value_bytes(argv[0]);
1899   int iSize;
1900   if( argc==1 ){
1901     iSize = 256;
1902   }else{
1903     iSize = sqlite3_value_int(argv[1]);
1904     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1905       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1906                                     "384 512", -1);
1907       return;
1908     }
1909   }
1910   if( eType==SQLITE_NULL ) return;
1911   SHA3Init(&cx, iSize);
1912   if( eType==SQLITE_BLOB ){
1913     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1914   }else{
1915     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1916   }
1917   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1918 }
1919
1920 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1921 ** of 50 bytes and add it to the hash.
1922 */
1923 static void hash_step_vformat(
1924   SHA3Context *p,                 /* Add content to this context */
1925   const char *zFormat,
1926   ...
1927 ){
1928   va_list ap;
1929   int n;
1930   char zBuf[50];
1931   va_start(ap, zFormat);
1932   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1933   va_end(ap);
1934   n = (int)strlen(zBuf);
1935   SHA3Update(p, (unsigned char*)zBuf, n);
1936 }
1937
1938 /*
1939 ** Implementation of the sha3_query(SQL,SIZE) function.
1940 **
1941 ** This function compiles and runs the SQL statement(s) given in the
1942 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1943 ** size is 256.
1944 **
1945 ** The format of the byte stream that is hashed is summarized as follows:
1946 **
1947 **       S<n>:<sql>
1948 **       R
1949 **       N
1950 **       I<int>
1951 **       F<ieee-float>
1952 **       B<size>:<bytes>
1953 **       T<size>:<text>
1954 **
1955 ** <sql> is the original SQL text for each statement run and <n> is
1956 ** the size of that text.  The SQL text is UTF-8.  A single R character
1957 ** occurs before the start of each row.  N means a NULL value.
1958 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1959 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1960 ** B means blobs of <size> bytes.  T means text rendered as <size>
1961 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1962 ** text integers.
1963 **
1964 ** For each SQL statement in the X input, there is one S segment.  Each
1965 ** S segment is followed by zero or more R segments, one for each row in the
1966 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1967 ** one for each column in the result set.  Segments are concatentated directly
1968 ** with no delimiters of any kind.
1969 */
1970 static void sha3QueryFunc(
1971   sqlite3_context *context,
1972   int argc,
1973   sqlite3_value **argv
1974 ){
1975   sqlite3 *db = sqlite3_context_db_handle(context);
1976   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1977   sqlite3_stmt *pStmt = 0;
1978   int nCol;                   /* Number of columns in the result set */
1979   int i;                      /* Loop counter */
1980   int rc;
1981   int n;
1982   const char *z;
1983   SHA3Context cx;
1984   int iSize;
1985
1986   if( argc==1 ){
1987     iSize = 256;
1988   }else{
1989     iSize = sqlite3_value_int(argv[1]);
1990     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1991       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1992                                     "384 512", -1);
1993       return;
1994     }
1995   }
1996   if( zSql==0 ) return;
1997   SHA3Init(&cx, iSize);
1998   while( zSql[0] ){
1999     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2000     if( rc ){
2001       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2002                                    zSql, sqlite3_errmsg(db));
2003       sqlite3_finalize(pStmt);
2004       sqlite3_result_error(context, zMsg, -1);
2005       sqlite3_free(zMsg);
2006       return;
2007     }
2008     if( !sqlite3_stmt_readonly(pStmt) ){
2009       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2010       sqlite3_finalize(pStmt);
2011       sqlite3_result_error(context, zMsg, -1);
2012       sqlite3_free(zMsg);
2013       return;
2014     }
2015     nCol = sqlite3_column_count(pStmt);
2016     z = sqlite3_sql(pStmt);
2017     n = (int)strlen(z);
2018     hash_step_vformat(&cx,"S%d:",n);
2019     SHA3Update(&cx,(unsigned char*)z,n);
2020
2021     /* Compute a hash over the result of the query */
2022     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2023       SHA3Update(&cx,(const unsigned char*)"R",1);
2024       for(i=0; i<nCol; i++){
2025         switch( sqlite3_column_type(pStmt,i) ){
2026           case SQLITE_NULL: {
2027             SHA3Update(&cx, (const unsigned char*)"N",1);
2028             break;
2029           }
2030           case SQLITE_INTEGER: {
2031             sqlite3_uint64 u;
2032             int j;
2033             unsigned char x[9];
2034             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2035             memcpy(&u, &v, 8);
2036             for(j=8; j>=1; j--){
2037               x[j] = u & 0xff;
2038               u >>= 8;
2039             }
2040             x[0] = 'I';
2041             SHA3Update(&cx, x, 9);
2042             break;
2043           }
2044           case SQLITE_FLOAT: {
2045             sqlite3_uint64 u;
2046             int j;
2047             unsigned char x[9];
2048             double r = sqlite3_column_double(pStmt,i);
2049             memcpy(&u, &r, 8);
2050             for(j=8; j>=1; j--){
2051               x[j] = u & 0xff;
2052               u >>= 8;
2053             }
2054             x[0] = 'F';
2055             SHA3Update(&cx,x,9);
2056             break;
2057           }
2058           case SQLITE_TEXT: {
2059             int n2 = sqlite3_column_bytes(pStmt, i);
2060             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2061             hash_step_vformat(&cx,"T%d:",n2);
2062             SHA3Update(&cx, z2, n2);
2063             break;
2064           }
2065           case SQLITE_BLOB: {
2066             int n2 = sqlite3_column_bytes(pStmt, i);
2067             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2068             hash_step_vformat(&cx,"B%d:",n2);
2069             SHA3Update(&cx, z2, n2);
2070             break;
2071           }
2072         }
2073       }
2074     }
2075     sqlite3_finalize(pStmt);
2076   }
2077   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2078 }
2079
2080
2081 #ifdef _WIN32
2082
2083 #endif
2084 int sqlite3_shathree_init(
2085   sqlite3 *db,
2086   char **pzErrMsg,
2087   const sqlite3_api_routines *pApi
2088 ){
2089   int rc = SQLITE_OK;
2090   SQLITE_EXTENSION_INIT2(pApi);
2091   (void)pzErrMsg;  /* Unused parameter */
2092   rc = sqlite3_create_function(db, "sha3", 1,
2093                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2094                       0, sha3Func, 0, 0);
2095   if( rc==SQLITE_OK ){
2096     rc = sqlite3_create_function(db, "sha3", 2,
2097                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2098                       0, sha3Func, 0, 0);
2099   }
2100   if( rc==SQLITE_OK ){
2101     rc = sqlite3_create_function(db, "sha3_query", 1,
2102                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2103                       0, sha3QueryFunc, 0, 0);
2104   }
2105   if( rc==SQLITE_OK ){
2106     rc = sqlite3_create_function(db, "sha3_query", 2,
2107                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2108                       0, sha3QueryFunc, 0, 0);
2109   }
2110   return rc;
2111 }
2112
2113 /************************* End ../ext/misc/shathree.c ********************/
2114 /************************* Begin ../ext/misc/fileio.c ******************/
2115 /*
2116 ** 2014-06-13
2117 **
2118 ** The author disclaims copyright to this source code.  In place of
2119 ** a legal notice, here is a blessing:
2120 **
2121 **    May you do good and not evil.
2122 **    May you find forgiveness for yourself and forgive others.
2123 **    May you share freely, never taking more than you give.
2124 **
2125 ******************************************************************************
2126 **
2127 ** This SQLite extension implements SQL functions readfile() and
2128 ** writefile(), and eponymous virtual type "fsdir".
2129 **
2130 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2131 **
2132 **   If neither of the optional arguments is present, then this UDF
2133 **   function writes blob DATA to file FILE. If successful, the number
2134 **   of bytes written is returned. If an error occurs, NULL is returned.
2135 **
2136 **   If the first option argument - MODE - is present, then it must
2137 **   be passed an integer value that corresponds to a POSIX mode
2138 **   value (file type + permissions, as returned in the stat.st_mode
2139 **   field by the stat() system call). Three types of files may
2140 **   be written/created:
2141 **
2142 **     regular files:  (mode & 0170000)==0100000
2143 **     symbolic links: (mode & 0170000)==0120000
2144 **     directories:    (mode & 0170000)==0040000
2145 **
2146 **   For a directory, the DATA is ignored. For a symbolic link, it is
2147 **   interpreted as text and used as the target of the link. For a
2148 **   regular file, it is interpreted as a blob and written into the
2149 **   named file. Regardless of the type of file, its permissions are
2150 **   set to (mode & 0777) before returning.
2151 **
2152 **   If the optional MTIME argument is present, then it is interpreted
2153 **   as an integer - the number of seconds since the unix epoch. The
2154 **   modification-time of the target file is set to this value before
2155 **   returning.
2156 **
2157 **   If three or more arguments are passed to this function and an
2158 **   error is encountered, an exception is raised.
2159 **
2160 ** READFILE(FILE):
2161 **
2162 **   Read and return the contents of file FILE (type blob) from disk.
2163 **
2164 ** FSDIR:
2165 **
2166 **   Used as follows:
2167 **
2168 **     SELECT * FROM fsdir($path [, $dir]);
2169 **
2170 **   Parameter $path is an absolute or relative pathname. If the file that it
2171 **   refers to does not exist, it is an error. If the path refers to a regular
2172 **   file or symbolic link, it returns a single row. Or, if the path refers
2173 **   to a directory, it returns one row for the directory, and one row for each
2174 **   file within the hierarchy rooted at $path.
2175 **
2176 **   Each row has the following columns:
2177 **
2178 **     name:  Path to file or directory (text value).
2179 **     mode:  Value of stat.st_mode for directory entry (an integer).
2180 **     mtime: Value of stat.st_mtime for directory entry (an integer).
2181 **     data:  For a regular file, a blob containing the file data. For a
2182 **            symlink, a text value containing the text of the link. For a
2183 **            directory, NULL.
2184 **
2185 **   If a non-NULL value is specified for the optional $dir parameter and
2186 **   $path is a relative path, then $path is interpreted relative to $dir. 
2187 **   And the paths returned in the "name" column of the table are also 
2188 **   relative to directory $dir.
2189 */
2190 /* #include "sqlite3ext.h" */
2191 SQLITE_EXTENSION_INIT1
2192 #include <stdio.h>
2193 #include <string.h>
2194 #include <assert.h>
2195
2196 #include <sys/types.h>
2197 #include <sys/stat.h>
2198 #include <fcntl.h>
2199 #if !defined(_WIN32) && !defined(WIN32)
2200 #  include <unistd.h>
2201 #  include <dirent.h>
2202 #  include <utime.h>
2203 #  include <sys/time.h>
2204 #else
2205 #  include "windows.h"
2206 #  include <io.h>
2207 #  include <direct.h>
2208 /* #  include "test_windirent.h" */
2209 #  define dirent DIRENT
2210 #  ifndef chmod
2211 #    define chmod _chmod
2212 #  endif
2213 #  ifndef stat
2214 #    define stat _stat
2215 #  endif
2216 #  define mkdir(path,mode) _mkdir(path)
2217 #  define lstat(path,buf) stat(path,buf)
2218 #endif
2219 #include <time.h>
2220 #include <errno.h>
2221
2222
2223 /*
2224 ** Structure of the fsdir() table-valued function
2225 */
2226                  /*    0    1    2     3    4           5             */
2227 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2228 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
2229 #define FSDIR_COLUMN_MODE     1     /* Access mode */
2230 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
2231 #define FSDIR_COLUMN_DATA     3     /* File content */
2232 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
2233 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
2234
2235
2236 /*
2237 ** Set the result stored by context ctx to a blob containing the 
2238 ** contents of file zName.  Or, leave the result unchanged (NULL)
2239 ** if the file does not exist or is unreadable.
2240 **
2241 ** If the file exceeds the SQLite blob size limit, through an
2242 ** SQLITE_TOOBIG error.
2243 **
2244 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
2245 ** off of disk.
2246 */
2247 static void readFileContents(sqlite3_context *ctx, const char *zName){
2248   FILE *in;
2249   sqlite3_int64 nIn;
2250   void *pBuf;
2251   sqlite3 *db;
2252   int mxBlob;
2253
2254   in = fopen(zName, "rb");
2255   if( in==0 ){
2256     /* File does not exist or is unreadable. Leave the result set to NULL. */
2257     return;
2258   }
2259   fseek(in, 0, SEEK_END);
2260   nIn = ftell(in);
2261   rewind(in);
2262   db = sqlite3_context_db_handle(ctx);
2263   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
2264   if( nIn>mxBlob ){
2265     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
2266     fclose(in);
2267     return;
2268   }
2269   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
2270   if( pBuf==0 ){
2271     sqlite3_result_error_nomem(ctx);
2272     fclose(in);
2273     return;
2274   }
2275   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
2276     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
2277   }else{
2278     sqlite3_result_error_code(ctx, SQLITE_IOERR);
2279     sqlite3_free(pBuf);
2280   }
2281   fclose(in);
2282 }
2283
2284 /*
2285 ** Implementation of the "readfile(X)" SQL function.  The entire content
2286 ** of the file named X is read and returned as a BLOB.  NULL is returned
2287 ** if the file does not exist or is unreadable.
2288 */
2289 static void readfileFunc(
2290   sqlite3_context *context,
2291   int argc,
2292   sqlite3_value **argv
2293 ){
2294   const char *zName;
2295   (void)(argc);  /* Unused parameter */
2296   zName = (const char*)sqlite3_value_text(argv[0]);
2297   if( zName==0 ) return;
2298   readFileContents(context, zName);
2299 }
2300
2301 /*
2302 ** Set the error message contained in context ctx to the results of
2303 ** vprintf(zFmt, ...).
2304 */
2305 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2306   char *zMsg = 0;
2307   va_list ap;
2308   va_start(ap, zFmt);
2309   zMsg = sqlite3_vmprintf(zFmt, ap);
2310   sqlite3_result_error(ctx, zMsg, -1);
2311   sqlite3_free(zMsg);
2312   va_end(ap);
2313 }
2314
2315 #if defined(_WIN32)
2316 /*
2317 ** This function is designed to convert a Win32 FILETIME structure into the
2318 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2319 */
2320 static sqlite3_uint64 fileTimeToUnixTime(
2321   LPFILETIME pFileTime
2322 ){
2323   SYSTEMTIME epochSystemTime;
2324   ULARGE_INTEGER epochIntervals;
2325   FILETIME epochFileTime;
2326   ULARGE_INTEGER fileIntervals;
2327
2328   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2329   epochSystemTime.wYear = 1970;
2330   epochSystemTime.wMonth = 1;
2331   epochSystemTime.wDay = 1;
2332   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2333   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2334   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2335
2336   fileIntervals.LowPart = pFileTime->dwLowDateTime;
2337   fileIntervals.HighPart = pFileTime->dwHighDateTime;
2338
2339   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2340 }
2341
2342 /*
2343 ** This function attempts to normalize the time values found in the stat()
2344 ** buffer to UTC.  This is necessary on Win32, where the runtime library
2345 ** appears to return these values as local times.
2346 */
2347 static void statTimesToUtc(
2348   const char *zPath,
2349   struct stat *pStatBuf
2350 ){
2351   HANDLE hFindFile;
2352   WIN32_FIND_DATAW fd;
2353   LPWSTR zUnicodeName;
2354   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2355   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2356   if( zUnicodeName ){
2357     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
2358     hFindFile = FindFirstFileW(zUnicodeName, &fd);
2359     if( hFindFile!=NULL ){
2360       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2361       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2362       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2363       FindClose(hFindFile);
2364     }
2365     sqlite3_free(zUnicodeName);
2366   }
2367 }
2368 #endif
2369
2370 /*
2371 ** This function is used in place of stat().  On Windows, special handling
2372 ** is required in order for the included time to be returned as UTC.  On all
2373 ** other systems, this function simply calls stat().
2374 */
2375 static int fileStat(
2376   const char *zPath,
2377   struct stat *pStatBuf
2378 ){
2379 #if defined(_WIN32)
2380   int rc = stat(zPath, pStatBuf);
2381   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2382   return rc;
2383 #else
2384   return stat(zPath, pStatBuf);
2385 #endif
2386 }
2387
2388 /*
2389 ** This function is used in place of lstat().  On Windows, special handling
2390 ** is required in order for the included time to be returned as UTC.  On all
2391 ** other systems, this function simply calls lstat().
2392 */
2393 static int fileLinkStat(
2394   const char *zPath,
2395   struct stat *pStatBuf
2396 ){
2397 #if defined(_WIN32)
2398   int rc = lstat(zPath, pStatBuf);
2399   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2400   return rc;
2401 #else
2402   return lstat(zPath, pStatBuf);
2403 #endif
2404 }
2405
2406 /*
2407 ** Argument zFile is the name of a file that will be created and/or written
2408 ** by SQL function writefile(). This function ensures that the directory
2409 ** zFile will be written to exists, creating it if required. The permissions
2410 ** for any path components created by this function are set in accordance
2411 ** with the current umask.
2412 **
2413 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2414 ** SQLITE_OK is returned if the directory is successfully created, or
2415 ** SQLITE_ERROR otherwise.
2416 */
2417 static int makeDirectory(
2418   const char *zFile
2419 ){
2420   char *zCopy = sqlite3_mprintf("%s", zFile);
2421   int rc = SQLITE_OK;
2422
2423   if( zCopy==0 ){
2424     rc = SQLITE_NOMEM;
2425   }else{
2426     int nCopy = (int)strlen(zCopy);
2427     int i = 1;
2428
2429     while( rc==SQLITE_OK ){
2430       struct stat sStat;
2431       int rc2;
2432
2433       for(; zCopy[i]!='/' && i<nCopy; i++);
2434       if( i==nCopy ) break;
2435       zCopy[i] = '\0';
2436
2437       rc2 = fileStat(zCopy, &sStat);
2438       if( rc2!=0 ){
2439         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
2440       }else{
2441         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2442       }
2443       zCopy[i] = '/';
2444       i++;
2445     }
2446
2447     sqlite3_free(zCopy);
2448   }
2449
2450   return rc;
2451 }
2452
2453 /*
2454 ** This function does the work for the writefile() UDF. Refer to 
2455 ** header comments at the top of this file for details.
2456 */
2457 static int writeFile(
2458   sqlite3_context *pCtx,          /* Context to return bytes written in */
2459   const char *zFile,              /* File to write */
2460   sqlite3_value *pData,           /* Data to write */
2461   mode_t mode,                    /* MODE parameter passed to writefile() */
2462   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
2463 ){
2464 #if !defined(_WIN32) && !defined(WIN32)
2465   if( S_ISLNK(mode) ){
2466     const char *zTo = (const char*)sqlite3_value_text(pData);
2467     if( symlink(zTo, zFile)<0 ) return 1;
2468   }else
2469 #endif
2470   {
2471     if( S_ISDIR(mode) ){
2472       if( mkdir(zFile, mode) ){
2473         /* The mkdir() call to create the directory failed. This might not
2474         ** be an error though - if there is already a directory at the same
2475         ** path and either the permissions already match or can be changed
2476         ** to do so using chmod(), it is not an error.  */
2477         struct stat sStat;
2478         if( errno!=EEXIST
2479          || 0!=fileStat(zFile, &sStat)
2480          || !S_ISDIR(sStat.st_mode)
2481          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2482         ){
2483           return 1;
2484         }
2485       }
2486     }else{
2487       sqlite3_int64 nWrite = 0;
2488       const char *z;
2489       int rc = 0;
2490       FILE *out = fopen(zFile, "wb");
2491       if( out==0 ) return 1;
2492       z = (const char*)sqlite3_value_blob(pData);
2493       if( z ){
2494         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2495         nWrite = sqlite3_value_bytes(pData);
2496         if( nWrite!=n ){
2497           rc = 1;
2498         }
2499       }
2500       fclose(out);
2501       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2502         rc = 1;
2503       }
2504       if( rc ) return 2;
2505       sqlite3_result_int64(pCtx, nWrite);
2506     }
2507   }
2508
2509   if( mtime>=0 ){
2510 #if defined(_WIN32)
2511 #if !SQLITE_OS_WINRT
2512     /* Windows */
2513     FILETIME lastAccess;
2514     FILETIME lastWrite;
2515     SYSTEMTIME currentTime;
2516     LONGLONG intervals;
2517     HANDLE hFile;
2518     LPWSTR zUnicodeName;
2519     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2520
2521     GetSystemTime(&currentTime);
2522     SystemTimeToFileTime(&currentTime, &lastAccess);
2523     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2524     lastWrite.dwLowDateTime = (DWORD)intervals;
2525     lastWrite.dwHighDateTime = intervals >> 32;
2526     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2527     if( zUnicodeName==0 ){
2528       return 1;
2529     }
2530     hFile = CreateFileW(
2531       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2532       FILE_FLAG_BACKUP_SEMANTICS, NULL
2533     );
2534     sqlite3_free(zUnicodeName);
2535     if( hFile!=INVALID_HANDLE_VALUE ){
2536       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2537       CloseHandle(hFile);
2538       return !bResult;
2539     }else{
2540       return 1;
2541     }
2542 #endif
2543 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2544     /* Recent unix */
2545     struct timespec times[2];
2546     times[0].tv_nsec = times[1].tv_nsec = 0;
2547     times[0].tv_sec = time(0);
2548     times[1].tv_sec = mtime;
2549     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2550       return 1;
2551     }
2552 #else
2553     /* Legacy unix */
2554     struct timeval times[2];
2555     times[0].tv_usec = times[1].tv_usec = 0;
2556     times[0].tv_sec = time(0);
2557     times[1].tv_sec = mtime;
2558     if( utimes(zFile, times) ){
2559       return 1;
2560     }
2561 #endif
2562   }
2563
2564   return 0;
2565 }
2566
2567 /*
2568 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.  
2569 ** Refer to header comments at the top of this file for details.
2570 */
2571 static void writefileFunc(
2572   sqlite3_context *context,
2573   int argc,
2574   sqlite3_value **argv
2575 ){
2576   const char *zFile;
2577   mode_t mode = 0;
2578   int res;
2579   sqlite3_int64 mtime = -1;
2580
2581   if( argc<2 || argc>4 ){
2582     sqlite3_result_error(context, 
2583         "wrong number of arguments to function writefile()", -1
2584     );
2585     return;
2586   }
2587
2588   zFile = (const char*)sqlite3_value_text(argv[0]);
2589   if( zFile==0 ) return;
2590   if( argc>=3 ){
2591     mode = (mode_t)sqlite3_value_int(argv[2]);
2592   }
2593   if( argc==4 ){
2594     mtime = sqlite3_value_int64(argv[3]);
2595   }
2596
2597   res = writeFile(context, zFile, argv[1], mode, mtime);
2598   if( res==1 && errno==ENOENT ){
2599     if( makeDirectory(zFile)==SQLITE_OK ){
2600       res = writeFile(context, zFile, argv[1], mode, mtime);
2601     }
2602   }
2603
2604   if( argc>2 && res!=0 ){
2605     if( S_ISLNK(mode) ){
2606       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2607     }else if( S_ISDIR(mode) ){
2608       ctxErrorMsg(context, "failed to create directory: %s", zFile);
2609     }else{
2610       ctxErrorMsg(context, "failed to write file: %s", zFile);
2611     }
2612   }
2613 }
2614
2615 /*
2616 ** SQL function:   lsmode(MODE)
2617 **
2618 ** Given a numberic st_mode from stat(), convert it into a human-readable
2619 ** text string in the style of "ls -l".
2620 */
2621 static void lsModeFunc(
2622   sqlite3_context *context,
2623   int argc,
2624   sqlite3_value **argv
2625 ){
2626   int i;
2627   int iMode = sqlite3_value_int(argv[0]);
2628   char z[16];
2629   (void)argc;
2630   if( S_ISLNK(iMode) ){
2631     z[0] = 'l';
2632   }else if( S_ISREG(iMode) ){
2633     z[0] = '-';
2634   }else if( S_ISDIR(iMode) ){
2635     z[0] = 'd';
2636   }else{
2637     z[0] = '?';
2638   }
2639   for(i=0; i<3; i++){
2640     int m = (iMode >> ((2-i)*3));
2641     char *a = &z[1 + i*3];
2642     a[0] = (m & 0x4) ? 'r' : '-';
2643     a[1] = (m & 0x2) ? 'w' : '-';
2644     a[2] = (m & 0x1) ? 'x' : '-';
2645   }
2646   z[10] = '\0';
2647   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2648 }
2649
2650 #ifndef SQLITE_OMIT_VIRTUALTABLE
2651
2652 /* 
2653 ** Cursor type for recursively iterating through a directory structure.
2654 */
2655 typedef struct fsdir_cursor fsdir_cursor;
2656 typedef struct FsdirLevel FsdirLevel;
2657
2658 struct FsdirLevel {
2659   DIR *pDir;                 /* From opendir() */
2660   char *zDir;                /* Name of directory (nul-terminated) */
2661 };
2662
2663 struct fsdir_cursor {
2664   sqlite3_vtab_cursor base;  /* Base class - must be first */
2665
2666   int nLvl;                  /* Number of entries in aLvl[] array */
2667   int iLvl;                  /* Index of current entry */
2668   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
2669
2670   const char *zBase;
2671   int nBase;
2672
2673   struct stat sStat;         /* Current lstat() results */
2674   char *zPath;               /* Path to current entry */
2675   sqlite3_int64 iRowid;      /* Current rowid */
2676 };
2677
2678 typedef struct fsdir_tab fsdir_tab;
2679 struct fsdir_tab {
2680   sqlite3_vtab base;         /* Base class - must be first */
2681 };
2682
2683 /*
2684 ** Construct a new fsdir virtual table object.
2685 */
2686 static int fsdirConnect(
2687   sqlite3 *db,
2688   void *pAux,
2689   int argc, const char *const*argv,
2690   sqlite3_vtab **ppVtab,
2691   char **pzErr
2692 ){
2693   fsdir_tab *pNew = 0;
2694   int rc;
2695   (void)pAux;
2696   (void)argc;
2697   (void)argv;
2698   (void)pzErr;
2699   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2700   if( rc==SQLITE_OK ){
2701     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2702     if( pNew==0 ) return SQLITE_NOMEM;
2703     memset(pNew, 0, sizeof(*pNew));
2704     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
2705   }
2706   *ppVtab = (sqlite3_vtab*)pNew;
2707   return rc;
2708 }
2709
2710 /*
2711 ** This method is the destructor for fsdir vtab objects.
2712 */
2713 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2714   sqlite3_free(pVtab);
2715   return SQLITE_OK;
2716 }
2717
2718 /*
2719 ** Constructor for a new fsdir_cursor object.
2720 */
2721 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2722   fsdir_cursor *pCur;
2723   (void)p;
2724   pCur = sqlite3_malloc( sizeof(*pCur) );
2725   if( pCur==0 ) return SQLITE_NOMEM;
2726   memset(pCur, 0, sizeof(*pCur));
2727   pCur->iLvl = -1;
2728   *ppCursor = &pCur->base;
2729   return SQLITE_OK;
2730 }
2731
2732 /*
2733 ** Reset a cursor back to the state it was in when first returned
2734 ** by fsdirOpen().
2735 */
2736 static void fsdirResetCursor(fsdir_cursor *pCur){
2737   int i;
2738   for(i=0; i<=pCur->iLvl; i++){
2739     FsdirLevel *pLvl = &pCur->aLvl[i];
2740     if( pLvl->pDir ) closedir(pLvl->pDir);
2741     sqlite3_free(pLvl->zDir);
2742   }
2743   sqlite3_free(pCur->zPath);
2744   sqlite3_free(pCur->aLvl);
2745   pCur->aLvl = 0;
2746   pCur->zPath = 0;
2747   pCur->zBase = 0;
2748   pCur->nBase = 0;
2749   pCur->nLvl = 0;
2750   pCur->iLvl = -1;
2751   pCur->iRowid = 1;
2752 }
2753
2754 /*
2755 ** Destructor for an fsdir_cursor.
2756 */
2757 static int fsdirClose(sqlite3_vtab_cursor *cur){
2758   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2759
2760   fsdirResetCursor(pCur);
2761   sqlite3_free(pCur);
2762   return SQLITE_OK;
2763 }
2764
2765 /*
2766 ** Set the error message for the virtual table associated with cursor
2767 ** pCur to the results of vprintf(zFmt, ...).
2768 */
2769 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2770   va_list ap;
2771   va_start(ap, zFmt);
2772   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2773   va_end(ap);
2774 }
2775
2776
2777 /*
2778 ** Advance an fsdir_cursor to its next row of output.
2779 */
2780 static int fsdirNext(sqlite3_vtab_cursor *cur){
2781   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2782   mode_t m = pCur->sStat.st_mode;
2783
2784   pCur->iRowid++;
2785   if( S_ISDIR(m) ){
2786     /* Descend into this directory */
2787     int iNew = pCur->iLvl + 1;
2788     FsdirLevel *pLvl;
2789     if( iNew>=pCur->nLvl ){
2790       int nNew = iNew+1;
2791       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
2792       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
2793       if( aNew==0 ) return SQLITE_NOMEM;
2794       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2795       pCur->aLvl = aNew;
2796       pCur->nLvl = nNew;
2797     }
2798     pCur->iLvl = iNew;
2799     pLvl = &pCur->aLvl[iNew];
2800     
2801     pLvl->zDir = pCur->zPath;
2802     pCur->zPath = 0;
2803     pLvl->pDir = opendir(pLvl->zDir);
2804     if( pLvl->pDir==0 ){
2805       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2806       return SQLITE_ERROR;
2807     }
2808   }
2809
2810   while( pCur->iLvl>=0 ){
2811     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2812     struct dirent *pEntry = readdir(pLvl->pDir);
2813     if( pEntry ){
2814       if( pEntry->d_name[0]=='.' ){
2815        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2816        if( pEntry->d_name[1]=='\0' ) continue;
2817       }
2818       sqlite3_free(pCur->zPath);
2819       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2820       if( pCur->zPath==0 ) return SQLITE_NOMEM;
2821       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2822         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2823         return SQLITE_ERROR;
2824       }
2825       return SQLITE_OK;
2826     }
2827     closedir(pLvl->pDir);
2828     sqlite3_free(pLvl->zDir);
2829     pLvl->pDir = 0;
2830     pLvl->zDir = 0;
2831     pCur->iLvl--;
2832   }
2833
2834   /* EOF */
2835   sqlite3_free(pCur->zPath);
2836   pCur->zPath = 0;
2837   return SQLITE_OK;
2838 }
2839
2840 /*
2841 ** Return values of columns for the row at which the series_cursor
2842 ** is currently pointing.
2843 */
2844 static int fsdirColumn(
2845   sqlite3_vtab_cursor *cur,   /* The cursor */
2846   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2847   int i                       /* Which column to return */
2848 ){
2849   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2850   switch( i ){
2851     case FSDIR_COLUMN_NAME: {
2852       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2853       break;
2854     }
2855
2856     case FSDIR_COLUMN_MODE:
2857       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2858       break;
2859
2860     case FSDIR_COLUMN_MTIME:
2861       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2862       break;
2863
2864     case FSDIR_COLUMN_DATA: {
2865       mode_t m = pCur->sStat.st_mode;
2866       if( S_ISDIR(m) ){
2867         sqlite3_result_null(ctx);
2868 #if !defined(_WIN32) && !defined(WIN32)
2869       }else if( S_ISLNK(m) ){
2870         char aStatic[64];
2871         char *aBuf = aStatic;
2872         sqlite3_int64 nBuf = 64;
2873         int n;
2874
2875         while( 1 ){
2876           n = readlink(pCur->zPath, aBuf, nBuf);
2877           if( n<nBuf ) break;
2878           if( aBuf!=aStatic ) sqlite3_free(aBuf);
2879           nBuf = nBuf*2;
2880           aBuf = sqlite3_malloc64(nBuf);
2881           if( aBuf==0 ){
2882             sqlite3_result_error_nomem(ctx);
2883             return SQLITE_NOMEM;
2884           }
2885         }
2886
2887         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2888         if( aBuf!=aStatic ) sqlite3_free(aBuf);
2889 #endif
2890       }else{
2891         readFileContents(ctx, pCur->zPath);
2892       }
2893     }
2894     case FSDIR_COLUMN_PATH:
2895     default: {
2896       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
2897       ** always return their values as NULL */
2898       break;
2899     }
2900   }
2901   return SQLITE_OK;
2902 }
2903
2904 /*
2905 ** Return the rowid for the current row. In this implementation, the
2906 ** first row returned is assigned rowid value 1, and each subsequent
2907 ** row a value 1 more than that of the previous.
2908 */
2909 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2910   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2911   *pRowid = pCur->iRowid;
2912   return SQLITE_OK;
2913 }
2914
2915 /*
2916 ** Return TRUE if the cursor has been moved off of the last
2917 ** row of output.
2918 */
2919 static int fsdirEof(sqlite3_vtab_cursor *cur){
2920   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2921   return (pCur->zPath==0);
2922 }
2923
2924 /*
2925 ** xFilter callback.
2926 **
2927 ** idxNum==1   PATH parameter only
2928 ** idxNum==2   Both PATH and DIR supplied
2929 */
2930 static int fsdirFilter(
2931   sqlite3_vtab_cursor *cur, 
2932   int idxNum, const char *idxStr,
2933   int argc, sqlite3_value **argv
2934 ){
2935   const char *zDir = 0;
2936   fsdir_cursor *pCur = (fsdir_cursor*)cur;
2937   (void)idxStr;
2938   fsdirResetCursor(pCur);
2939
2940   if( idxNum==0 ){
2941     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2942     return SQLITE_ERROR;
2943   }
2944
2945   assert( argc==idxNum && (argc==1 || argc==2) );
2946   zDir = (const char*)sqlite3_value_text(argv[0]);
2947   if( zDir==0 ){
2948     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2949     return SQLITE_ERROR;
2950   }
2951   if( argc==2 ){
2952     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2953   }
2954   if( pCur->zBase ){
2955     pCur->nBase = (int)strlen(pCur->zBase)+1;
2956     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2957   }else{
2958     pCur->zPath = sqlite3_mprintf("%s", zDir);
2959   }
2960
2961   if( pCur->zPath==0 ){
2962     return SQLITE_NOMEM;
2963   }
2964   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2965     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2966     return SQLITE_ERROR;
2967   }
2968
2969   return SQLITE_OK;
2970 }
2971
2972 /*
2973 ** SQLite will invoke this method one or more times while planning a query
2974 ** that uses the generate_series virtual table.  This routine needs to create
2975 ** a query plan for each invocation and compute an estimated cost for that
2976 ** plan.
2977 **
2978 ** In this implementation idxNum is used to represent the
2979 ** query plan.  idxStr is unused.
2980 **
2981 ** The query plan is represented by values of idxNum:
2982 **
2983 **  (1)  The path value is supplied by argv[0]
2984 **  (2)  Path is in argv[0] and dir is in argv[1]
2985 */
2986 static int fsdirBestIndex(
2987   sqlite3_vtab *tab,
2988   sqlite3_index_info *pIdxInfo
2989 ){
2990   int i;                 /* Loop over constraints */
2991   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
2992   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
2993   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
2994   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
2995   const struct sqlite3_index_constraint *pConstraint;
2996
2997   (void)tab;
2998   pConstraint = pIdxInfo->aConstraint;
2999   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3000     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3001     switch( pConstraint->iColumn ){
3002       case FSDIR_COLUMN_PATH: {
3003         if( pConstraint->usable ){
3004           idxPath = i;
3005           seenPath = 0;
3006         }else if( idxPath<0 ){
3007           seenPath = 1;
3008         }
3009         break;
3010       }
3011       case FSDIR_COLUMN_DIR: {
3012         if( pConstraint->usable ){
3013           idxDir = i;
3014           seenDir = 0;
3015         }else if( idxDir<0 ){
3016           seenDir = 1;
3017         }
3018         break;
3019       }
3020     } 
3021   }
3022   if( seenPath || seenDir ){
3023     /* If input parameters are unusable, disallow this plan */
3024     return SQLITE_CONSTRAINT;
3025   }
3026
3027   if( idxPath<0 ){
3028     pIdxInfo->idxNum = 0;
3029     /* The pIdxInfo->estimatedCost should have been initialized to a huge
3030     ** number.  Leave it unchanged. */
3031     pIdxInfo->estimatedRows = 0x7fffffff;
3032   }else{
3033     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
3034     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
3035     if( idxDir>=0 ){
3036       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
3037       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
3038       pIdxInfo->idxNum = 2;
3039       pIdxInfo->estimatedCost = 10.0;
3040     }else{
3041       pIdxInfo->idxNum = 1;
3042       pIdxInfo->estimatedCost = 100.0;
3043     }
3044   }
3045
3046   return SQLITE_OK;
3047 }
3048
3049 /*
3050 ** Register the "fsdir" virtual table.
3051 */
3052 static int fsdirRegister(sqlite3 *db){
3053   static sqlite3_module fsdirModule = {
3054     0,                         /* iVersion */
3055     0,                         /* xCreate */
3056     fsdirConnect,              /* xConnect */
3057     fsdirBestIndex,            /* xBestIndex */
3058     fsdirDisconnect,           /* xDisconnect */
3059     0,                         /* xDestroy */
3060     fsdirOpen,                 /* xOpen - open a cursor */
3061     fsdirClose,                /* xClose - close a cursor */
3062     fsdirFilter,               /* xFilter - configure scan constraints */
3063     fsdirNext,                 /* xNext - advance a cursor */
3064     fsdirEof,                  /* xEof - check for end of scan */
3065     fsdirColumn,               /* xColumn - read data */
3066     fsdirRowid,                /* xRowid - read data */
3067     0,                         /* xUpdate */
3068     0,                         /* xBegin */
3069     0,                         /* xSync */
3070     0,                         /* xCommit */
3071     0,                         /* xRollback */
3072     0,                         /* xFindMethod */
3073     0,                         /* xRename */
3074     0,                         /* xSavepoint */
3075     0,                         /* xRelease */
3076     0,                         /* xRollbackTo */
3077     0,                         /* xShadowName */
3078   };
3079
3080   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
3081   return rc;
3082 }
3083 #else         /* SQLITE_OMIT_VIRTUALTABLE */
3084 # define fsdirRegister(x) SQLITE_OK
3085 #endif
3086
3087 #ifdef _WIN32
3088
3089 #endif
3090 int sqlite3_fileio_init(
3091   sqlite3 *db, 
3092   char **pzErrMsg, 
3093   const sqlite3_api_routines *pApi
3094 ){
3095   int rc = SQLITE_OK;
3096   SQLITE_EXTENSION_INIT2(pApi);
3097   (void)pzErrMsg;  /* Unused parameter */
3098   rc = sqlite3_create_function(db, "readfile", 1, 
3099                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3100                                readfileFunc, 0, 0);
3101   if( rc==SQLITE_OK ){
3102     rc = sqlite3_create_function(db, "writefile", -1,
3103                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
3104                                  writefileFunc, 0, 0);
3105   }
3106   if( rc==SQLITE_OK ){
3107     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
3108                                  lsModeFunc, 0, 0);
3109   }
3110   if( rc==SQLITE_OK ){
3111     rc = fsdirRegister(db);
3112   }
3113   return rc;
3114 }
3115
3116 /************************* End ../ext/misc/fileio.c ********************/
3117 /************************* Begin ../ext/misc/completion.c ******************/
3118 /*
3119 ** 2017-07-10
3120 **
3121 ** The author disclaims copyright to this source code.  In place of
3122 ** a legal notice, here is a blessing:
3123 **
3124 **    May you do good and not evil.
3125 **    May you find forgiveness for yourself and forgive others.
3126 **    May you share freely, never taking more than you give.
3127 **
3128 *************************************************************************
3129 **
3130 ** This file implements an eponymous virtual table that returns suggested
3131 ** completions for a partial SQL input.
3132 **
3133 ** Suggested usage:
3134 **
3135 **     SELECT DISTINCT candidate COLLATE nocase
3136 **       FROM completion($prefix,$wholeline)
3137 **      ORDER BY 1;
3138 **
3139 ** The two query parameters are optional.  $prefix is the text of the
3140 ** current word being typed and that is to be completed.  $wholeline is
3141 ** the complete input line, used for context.
3142 **
3143 ** The raw completion() table might return the same candidate multiple
3144 ** times, for example if the same column name is used to two or more
3145 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
3146 ** the DISTINCT and ORDER BY are recommended.
3147 **
3148 ** This virtual table operates at the speed of human typing, and so there
3149 ** is no attempt to make it fast.  Even a slow implementation will be much
3150 ** faster than any human can type.
3151 **
3152 */
3153 /* #include "sqlite3ext.h" */
3154 SQLITE_EXTENSION_INIT1
3155 #include <assert.h>
3156 #include <string.h>
3157 #include <ctype.h>
3158
3159 #ifndef SQLITE_OMIT_VIRTUALTABLE
3160
3161 /* completion_vtab is a subclass of sqlite3_vtab which will
3162 ** serve as the underlying representation of a completion virtual table
3163 */
3164 typedef struct completion_vtab completion_vtab;
3165 struct completion_vtab {
3166   sqlite3_vtab base;  /* Base class - must be first */
3167   sqlite3 *db;        /* Database connection for this completion vtab */
3168 };
3169
3170 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3171 ** serve as the underlying representation of a cursor that scans
3172 ** over rows of the result
3173 */
3174 typedef struct completion_cursor completion_cursor;
3175 struct completion_cursor {
3176   sqlite3_vtab_cursor base;  /* Base class - must be first */
3177   sqlite3 *db;               /* Database connection for this cursor */
3178   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
3179   char *zPrefix;             /* The prefix for the word we want to complete */
3180   char *zLine;               /* The whole that we want to complete */
3181   const char *zCurrentRow;   /* Current output row */
3182   int szRow;                 /* Length of the zCurrentRow string */
3183   sqlite3_stmt *pStmt;       /* Current statement */
3184   sqlite3_int64 iRowid;      /* The rowid */
3185   int ePhase;                /* Current phase */
3186   int j;                     /* inter-phase counter */
3187 };
3188
3189 /* Values for ePhase:
3190 */
3191 #define COMPLETION_FIRST_PHASE   1
3192 #define COMPLETION_KEYWORDS      1
3193 #define COMPLETION_PRAGMAS       2
3194 #define COMPLETION_FUNCTIONS     3
3195 #define COMPLETION_COLLATIONS    4
3196 #define COMPLETION_INDEXES       5
3197 #define COMPLETION_TRIGGERS      6
3198 #define COMPLETION_DATABASES     7
3199 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
3200 #define COMPLETION_COLUMNS       9
3201 #define COMPLETION_MODULES       10
3202 #define COMPLETION_EOF           11
3203
3204 /*
3205 ** The completionConnect() method is invoked to create a new
3206 ** completion_vtab that describes the completion virtual table.
3207 **
3208 ** Think of this routine as the constructor for completion_vtab objects.
3209 **
3210 ** All this routine needs to do is:
3211 **
3212 **    (1) Allocate the completion_vtab object and initialize all fields.
3213 **
3214 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3215 **        result set of queries against completion will look like.
3216 */
3217 static int completionConnect(
3218   sqlite3 *db,
3219   void *pAux,
3220   int argc, const char *const*argv,
3221   sqlite3_vtab **ppVtab,
3222   char **pzErr
3223 ){
3224   completion_vtab *pNew;
3225   int rc;
3226
3227   (void)(pAux);    /* Unused parameter */
3228   (void)(argc);    /* Unused parameter */
3229   (void)(argv);    /* Unused parameter */
3230   (void)(pzErr);   /* Unused parameter */
3231
3232 /* Column numbers */
3233 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
3234 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
3235 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
3236 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
3237
3238   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
3239   rc = sqlite3_declare_vtab(db,
3240       "CREATE TABLE x("
3241       "  candidate TEXT,"
3242       "  prefix TEXT HIDDEN,"
3243       "  wholeline TEXT HIDDEN,"
3244       "  phase INT HIDDEN"        /* Used for debugging only */
3245       ")");
3246   if( rc==SQLITE_OK ){
3247     pNew = sqlite3_malloc( sizeof(*pNew) );
3248     *ppVtab = (sqlite3_vtab*)pNew;
3249     if( pNew==0 ) return SQLITE_NOMEM;
3250     memset(pNew, 0, sizeof(*pNew));
3251     pNew->db = db;
3252   }
3253   return rc;
3254 }
3255
3256 /*
3257 ** This method is the destructor for completion_cursor objects.
3258 */
3259 static int completionDisconnect(sqlite3_vtab *pVtab){
3260   sqlite3_free(pVtab);
3261   return SQLITE_OK;
3262 }
3263
3264 /*
3265 ** Constructor for a new completion_cursor object.
3266 */
3267 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3268   completion_cursor *pCur;
3269   pCur = sqlite3_malloc( sizeof(*pCur) );
3270   if( pCur==0 ) return SQLITE_NOMEM;
3271   memset(pCur, 0, sizeof(*pCur));
3272   pCur->db = ((completion_vtab*)p)->db;
3273   *ppCursor = &pCur->base;
3274   return SQLITE_OK;
3275 }
3276
3277 /*
3278 ** Reset the completion_cursor.
3279 */
3280 static void completionCursorReset(completion_cursor *pCur){
3281   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
3282   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
3283   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3284   pCur->j = 0;
3285 }
3286
3287 /*
3288 ** Destructor for a completion_cursor.
3289 */
3290 static int completionClose(sqlite3_vtab_cursor *cur){
3291   completionCursorReset((completion_cursor*)cur);
3292   sqlite3_free(cur);
3293   return SQLITE_OK;
3294 }
3295
3296 /*
3297 ** Advance a completion_cursor to its next row of output.
3298 **
3299 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3300 ** record the current state of the scan.  This routine sets ->zCurrentRow
3301 ** to the current row of output and then returns.  If no more rows remain,
3302 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3303 ** table that has reached the end of its scan.
3304 **
3305 ** The current implementation just lists potential identifiers and
3306 ** keywords and filters them by zPrefix.  Future enhancements should
3307 ** take zLine into account to try to restrict the set of identifiers and
3308 ** keywords based on what would be legal at the current point of input.
3309 */
3310 static int completionNext(sqlite3_vtab_cursor *cur){
3311   completion_cursor *pCur = (completion_cursor*)cur;
3312   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
3313   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
3314   pCur->iRowid++;
3315   while( pCur->ePhase!=COMPLETION_EOF ){
3316     switch( pCur->ePhase ){
3317       case COMPLETION_KEYWORDS: {
3318         if( pCur->j >= sqlite3_keyword_count() ){
3319           pCur->zCurrentRow = 0;
3320           pCur->ePhase = COMPLETION_DATABASES;
3321         }else{
3322           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
3323         }
3324         iCol = -1;
3325         break;
3326       }
3327       case COMPLETION_DATABASES: {
3328         if( pCur->pStmt==0 ){
3329           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3330                              &pCur->pStmt, 0);
3331         }
3332         iCol = 1;
3333         eNextPhase = COMPLETION_TABLES;
3334         break;
3335       }
3336       case COMPLETION_TABLES: {
3337         if( pCur->pStmt==0 ){
3338           sqlite3_stmt *pS2;
3339           char *zSql = 0;
3340           const char *zSep = "";
3341           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3342           while( sqlite3_step(pS2)==SQLITE_ROW ){
3343             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3344             zSql = sqlite3_mprintf(
3345                "%z%s"
3346                "SELECT name FROM \"%w\".sqlite_schema",
3347                zSql, zSep, zDb
3348             );
3349             if( zSql==0 ) return SQLITE_NOMEM;
3350             zSep = " UNION ";
3351           }
3352           sqlite3_finalize(pS2);
3353           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3354           sqlite3_free(zSql);
3355         }
3356         iCol = 0;
3357         eNextPhase = COMPLETION_COLUMNS;
3358         break;
3359       }
3360       case COMPLETION_COLUMNS: {
3361         if( pCur->pStmt==0 ){
3362           sqlite3_stmt *pS2;
3363           char *zSql = 0;
3364           const char *zSep = "";
3365           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3366           while( sqlite3_step(pS2)==SQLITE_ROW ){
3367             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3368             zSql = sqlite3_mprintf(
3369                "%z%s"
3370                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
3371                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
3372                " WHERE sm.type='table'",
3373                zSql, zSep, zDb, zDb
3374             );
3375             if( zSql==0 ) return SQLITE_NOMEM;
3376             zSep = " UNION ";
3377           }
3378           sqlite3_finalize(pS2);
3379           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3380           sqlite3_free(zSql);
3381         }
3382         iCol = 0;
3383         eNextPhase = COMPLETION_EOF;
3384         break;
3385       }
3386     }
3387     if( iCol<0 ){
3388       /* This case is when the phase presets zCurrentRow */
3389       if( pCur->zCurrentRow==0 ) continue;
3390     }else{
3391       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3392         /* Extract the next row of content */
3393         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3394         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
3395       }else{
3396         /* When all rows are finished, advance to the next phase */
3397         sqlite3_finalize(pCur->pStmt);
3398         pCur->pStmt = 0;
3399         pCur->ePhase = eNextPhase;
3400         continue;
3401       }
3402     }
3403     if( pCur->nPrefix==0 ) break;
3404     if( pCur->nPrefix<=pCur->szRow
3405      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
3406     ){
3407       break;
3408     }
3409   }
3410
3411   return SQLITE_OK;
3412 }
3413
3414 /*
3415 ** Return values of columns for the row at which the completion_cursor
3416 ** is currently pointing.
3417 */
3418 static int completionColumn(
3419   sqlite3_vtab_cursor *cur,   /* The cursor */
3420   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3421   int i                       /* Which column to return */
3422 ){
3423   completion_cursor *pCur = (completion_cursor*)cur;
3424   switch( i ){
3425     case COMPLETION_COLUMN_CANDIDATE: {
3426       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
3427       break;
3428     }
3429     case COMPLETION_COLUMN_PREFIX: {
3430       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3431       break;
3432     }
3433     case COMPLETION_COLUMN_WHOLELINE: {
3434       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3435       break;
3436     }
3437     case COMPLETION_COLUMN_PHASE: {
3438       sqlite3_result_int(ctx, pCur->ePhase);
3439       break;
3440     }
3441   }
3442   return SQLITE_OK;
3443 }
3444
3445 /*
3446 ** Return the rowid for the current row.  In this implementation, the
3447 ** rowid is the same as the output value.
3448 */
3449 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3450   completion_cursor *pCur = (completion_cursor*)cur;
3451   *pRowid = pCur->iRowid;
3452   return SQLITE_OK;
3453 }
3454
3455 /*
3456 ** Return TRUE if the cursor has been moved off of the last
3457 ** row of output.
3458 */
3459 static int completionEof(sqlite3_vtab_cursor *cur){
3460   completion_cursor *pCur = (completion_cursor*)cur;
3461   return pCur->ePhase >= COMPLETION_EOF;
3462 }
3463
3464 /*
3465 ** This method is called to "rewind" the completion_cursor object back
3466 ** to the first row of output.  This method is always called at least
3467 ** once prior to any call to completionColumn() or completionRowid() or 
3468 ** completionEof().
3469 */
3470 static int completionFilter(
3471   sqlite3_vtab_cursor *pVtabCursor, 
3472   int idxNum, const char *idxStr,
3473   int argc, sqlite3_value **argv
3474 ){
3475   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3476   int iArg = 0;
3477   (void)(idxStr);   /* Unused parameter */
3478   (void)(argc);     /* Unused parameter */
3479   completionCursorReset(pCur);
3480   if( idxNum & 1 ){
3481     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3482     if( pCur->nPrefix>0 ){
3483       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3484       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3485     }
3486     iArg = 1;
3487   }
3488   if( idxNum & 2 ){
3489     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3490     if( pCur->nLine>0 ){
3491       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3492       if( pCur->zLine==0 ) return SQLITE_NOMEM;
3493     }
3494   }
3495   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3496     int i = pCur->nLine;
3497     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3498       i--;
3499     }
3500     pCur->nPrefix = pCur->nLine - i;
3501     if( pCur->nPrefix>0 ){
3502       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3503       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3504     }
3505   }
3506   pCur->iRowid = 0;
3507   pCur->ePhase = COMPLETION_FIRST_PHASE;
3508   return completionNext(pVtabCursor);
3509 }
3510
3511 /*
3512 ** SQLite will invoke this method one or more times while planning a query
3513 ** that uses the completion virtual table.  This routine needs to create
3514 ** a query plan for each invocation and compute an estimated cost for that
3515 ** plan.
3516 **
3517 ** There are two hidden parameters that act as arguments to the table-valued
3518 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
3519 ** is available and bit 1 is set if "wholeline" is available.
3520 */
3521 static int completionBestIndex(
3522   sqlite3_vtab *tab,
3523   sqlite3_index_info *pIdxInfo
3524 ){
3525   int i;                 /* Loop over constraints */
3526   int idxNum = 0;        /* The query plan bitmask */
3527   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
3528   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3529   int nArg = 0;          /* Number of arguments that completeFilter() expects */
3530   const struct sqlite3_index_constraint *pConstraint;
3531
3532   (void)(tab);    /* Unused parameter */
3533   pConstraint = pIdxInfo->aConstraint;
3534   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3535     if( pConstraint->usable==0 ) continue;
3536     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3537     switch( pConstraint->iColumn ){
3538       case COMPLETION_COLUMN_PREFIX:
3539         prefixIdx = i;
3540         idxNum |= 1;
3541         break;
3542       case COMPLETION_COLUMN_WHOLELINE:
3543         wholelineIdx = i;
3544         idxNum |= 2;
3545         break;
3546     }
3547   }
3548   if( prefixIdx>=0 ){
3549     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3550     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3551   }
3552   if( wholelineIdx>=0 ){
3553     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3554     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3555   }
3556   pIdxInfo->idxNum = idxNum;
3557   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3558   pIdxInfo->estimatedRows = 500 - 100*nArg;
3559   return SQLITE_OK;
3560 }
3561
3562 /*
3563 ** This following structure defines all the methods for the 
3564 ** completion virtual table.
3565 */
3566 static sqlite3_module completionModule = {
3567   0,                         /* iVersion */
3568   0,                         /* xCreate */
3569   completionConnect,         /* xConnect */
3570   completionBestIndex,       /* xBestIndex */
3571   completionDisconnect,      /* xDisconnect */
3572   0,                         /* xDestroy */
3573   completionOpen,            /* xOpen - open a cursor */
3574   completionClose,           /* xClose - close a cursor */
3575   completionFilter,          /* xFilter - configure scan constraints */
3576   completionNext,            /* xNext - advance a cursor */
3577   completionEof,             /* xEof - check for end of scan */
3578   completionColumn,          /* xColumn - read data */
3579   completionRowid,           /* xRowid - read data */
3580   0,                         /* xUpdate */
3581   0,                         /* xBegin */
3582   0,                         /* xSync */
3583   0,                         /* xCommit */
3584   0,                         /* xRollback */
3585   0,                         /* xFindMethod */
3586   0,                         /* xRename */
3587   0,                         /* xSavepoint */
3588   0,                         /* xRelease */
3589   0,                         /* xRollbackTo */
3590   0                          /* xShadowName */
3591 };
3592
3593 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3594
3595 int sqlite3CompletionVtabInit(sqlite3 *db){
3596   int rc = SQLITE_OK;
3597 #ifndef SQLITE_OMIT_VIRTUALTABLE
3598   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3599 #endif
3600   return rc;
3601 }
3602
3603 #ifdef _WIN32
3604
3605 #endif
3606 int sqlite3_completion_init(
3607   sqlite3 *db, 
3608   char **pzErrMsg, 
3609   const sqlite3_api_routines *pApi
3610 ){
3611   int rc = SQLITE_OK;
3612   SQLITE_EXTENSION_INIT2(pApi);
3613   (void)(pzErrMsg);  /* Unused parameter */
3614 #ifndef SQLITE_OMIT_VIRTUALTABLE
3615   rc = sqlite3CompletionVtabInit(db);
3616 #endif
3617   return rc;
3618 }
3619
3620 /************************* End ../ext/misc/completion.c ********************/
3621 /************************* Begin ../ext/misc/appendvfs.c ******************/
3622 /*
3623 ** 2017-10-20
3624 **
3625 ** The author disclaims copyright to this source code.  In place of
3626 ** a legal notice, here is a blessing:
3627 **
3628 **    May you do good and not evil.
3629 **    May you find forgiveness for yourself and forgive others.
3630 **    May you share freely, never taking more than you give.
3631 **
3632 ******************************************************************************
3633 **
3634 ** This file implements a VFS shim that allows an SQLite database to be
3635 ** appended onto the end of some other file, such as an executable.
3636 **
3637 ** A special record must appear at the end of the file that identifies the
3638 ** file as an appended database and provides an offset to page 1.  For
3639 ** best performance page 1 should be located at a disk page boundary, though
3640 ** that is not required.
3641 **
3642 ** When opening a database using this VFS, the connection might treat
3643 ** the file as an ordinary SQLite database, or it might treat is as a
3644 ** database appended onto some other file.  Here are the rules:
3645 **
3646 **  (1)  When opening a new empty file, that file is treated as an ordinary
3647 **       database.
3648 **
3649 **  (2)  When opening a file that begins with the standard SQLite prefix
3650 **       string "SQLite format 3", that file is treated as an ordinary
3651 **       database.
3652 **
3653 **  (3)  When opening a file that ends with the appendvfs trailer string
3654 **       "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
3655 **       database.
3656 **
3657 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
3658 **       set, then a new database is appended to the already existing file.
3659 **
3660 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
3661 **
3662 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3663 ** the file containing the database is limited to 1GB.  This VFS will refuse
3664 ** to read or write past the 1GB mark.  This restriction might be lifted in
3665 ** future versions.  For now, if you need a large database, then keep the
3666 ** database in a separate file.
3667 **
3668 ** If the file being opened is not an appended database, then this shim is
3669 ** a pass-through into the default underlying VFS.
3670 **/
3671 /* #include "sqlite3ext.h" */
3672 SQLITE_EXTENSION_INIT1
3673 #include <string.h>
3674 #include <assert.h>
3675
3676 /* The append mark at the end of the database is:
3677 **
3678 **     Start-Of-SQLite3-NNNNNNNN
3679 **     123456789 123456789 12345
3680 **
3681 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3682 ** the offset to page 1.
3683 */
3684 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
3685 #define APND_MARK_PREFIX_SZ  17
3686 #define APND_MARK_SIZE       25
3687
3688 /*
3689 ** Maximum size of the combined prefix + database + append-mark.  This
3690 ** must be less than 0x40000000 to avoid locking issues on Windows.
3691 */
3692 #define APND_MAX_SIZE  (65536*15259)
3693
3694 /*
3695 ** Forward declaration of objects used by this utility
3696 */
3697 typedef struct sqlite3_vfs ApndVfs;
3698 typedef struct ApndFile ApndFile;
3699
3700 /* Access to a lower-level VFS that (might) implement dynamic loading,
3701 ** access to randomness, etc.
3702 */
3703 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
3704 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3705
3706 /* An open file */
3707 struct ApndFile {
3708   sqlite3_file base;              /* IO methods */
3709   sqlite3_int64 iPgOne;           /* File offset to page 1 */
3710   sqlite3_int64 iMark;            /* Start of the append-mark */
3711 };
3712
3713 /*
3714 ** Methods for ApndFile
3715 */
3716 static int apndClose(sqlite3_file*);
3717 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3718 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3719 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3720 static int apndSync(sqlite3_file*, int flags);
3721 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3722 static int apndLock(sqlite3_file*, int);
3723 static int apndUnlock(sqlite3_file*, int);
3724 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3725 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3726 static int apndSectorSize(sqlite3_file*);
3727 static int apndDeviceCharacteristics(sqlite3_file*);
3728 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3729 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3730 static void apndShmBarrier(sqlite3_file*);
3731 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3732 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3733 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3734
3735 /*
3736 ** Methods for ApndVfs
3737 */
3738 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3739 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3740 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3741 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3742 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3743 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3744 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3745 static void apndDlClose(sqlite3_vfs*, void*);
3746 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3747 static int apndSleep(sqlite3_vfs*, int microseconds);
3748 static int apndCurrentTime(sqlite3_vfs*, double*);
3749 static int apndGetLastError(sqlite3_vfs*, int, char *);
3750 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3751 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3752 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3753 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3754
3755 static sqlite3_vfs apnd_vfs = {
3756   3,                            /* iVersion (set when registered) */
3757   0,                            /* szOsFile (set when registered) */
3758   1024,                         /* mxPathname */
3759   0,                            /* pNext */
3760   "apndvfs",                    /* zName */
3761   0,                            /* pAppData (set when registered) */ 
3762   apndOpen,                     /* xOpen */
3763   apndDelete,                   /* xDelete */
3764   apndAccess,                   /* xAccess */
3765   apndFullPathname,             /* xFullPathname */
3766   apndDlOpen,                   /* xDlOpen */
3767   apndDlError,                  /* xDlError */
3768   apndDlSym,                    /* xDlSym */
3769   apndDlClose,                  /* xDlClose */
3770   apndRandomness,               /* xRandomness */
3771   apndSleep,                    /* xSleep */
3772   apndCurrentTime,              /* xCurrentTime */
3773   apndGetLastError,             /* xGetLastError */
3774   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
3775   apndSetSystemCall,            /* xSetSystemCall */
3776   apndGetSystemCall,            /* xGetSystemCall */
3777   apndNextSystemCall            /* xNextSystemCall */
3778 };
3779
3780 static const sqlite3_io_methods apnd_io_methods = {
3781   3,                              /* iVersion */
3782   apndClose,                      /* xClose */
3783   apndRead,                       /* xRead */
3784   apndWrite,                      /* xWrite */
3785   apndTruncate,                   /* xTruncate */
3786   apndSync,                       /* xSync */
3787   apndFileSize,                   /* xFileSize */
3788   apndLock,                       /* xLock */
3789   apndUnlock,                     /* xUnlock */
3790   apndCheckReservedLock,          /* xCheckReservedLock */
3791   apndFileControl,                /* xFileControl */
3792   apndSectorSize,                 /* xSectorSize */
3793   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
3794   apndShmMap,                     /* xShmMap */
3795   apndShmLock,                    /* xShmLock */
3796   apndShmBarrier,                 /* xShmBarrier */
3797   apndShmUnmap,                   /* xShmUnmap */
3798   apndFetch,                      /* xFetch */
3799   apndUnfetch                     /* xUnfetch */
3800 };
3801
3802
3803
3804 /*
3805 ** Close an apnd-file.
3806 */
3807 static int apndClose(sqlite3_file *pFile){
3808   pFile = ORIGFILE(pFile);
3809   return pFile->pMethods->xClose(pFile);
3810 }
3811
3812 /*
3813 ** Read data from an apnd-file.
3814 */
3815 static int apndRead(
3816   sqlite3_file *pFile, 
3817   void *zBuf, 
3818   int iAmt, 
3819   sqlite_int64 iOfst
3820 ){
3821   ApndFile *p = (ApndFile *)pFile;
3822   pFile = ORIGFILE(pFile);
3823   return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3824 }
3825
3826 /*
3827 ** Add the append-mark onto the end of the file.
3828 */
3829 static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
3830   int i;
3831   unsigned char a[APND_MARK_SIZE];
3832   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3833   for(i=0; i<8; i++){
3834     a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
3835   }
3836   return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
3837 }
3838
3839 /*
3840 ** Write data to an apnd-file.
3841 */
3842 static int apndWrite(
3843   sqlite3_file *pFile,
3844   const void *zBuf,
3845   int iAmt,
3846   sqlite_int64 iOfst
3847 ){
3848   int rc;
3849   ApndFile *p = (ApndFile *)pFile;
3850   pFile = ORIGFILE(pFile);
3851   if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
3852   rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3853   if( rc==SQLITE_OK &&  iOfst + iAmt + p->iPgOne > p->iMark ){
3854     sqlite3_int64 sz = 0;
3855     rc = pFile->pMethods->xFileSize(pFile, &sz);
3856     if( rc==SQLITE_OK ){
3857       p->iMark = sz - APND_MARK_SIZE;
3858       if( iOfst + iAmt + p->iPgOne > p->iMark ){
3859         p->iMark = p->iPgOne + iOfst + iAmt;
3860         rc = apndWriteMark(p, pFile);
3861       }
3862     }
3863   }
3864   return rc;
3865 }
3866
3867 /*
3868 ** Truncate an apnd-file.
3869 */
3870 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3871   int rc;
3872   ApndFile *p = (ApndFile *)pFile;
3873   pFile = ORIGFILE(pFile);
3874   rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
3875   if( rc==SQLITE_OK ){
3876     p->iMark = p->iPgOne+size;
3877     rc = apndWriteMark(p, pFile);
3878   }
3879   return rc;
3880 }
3881
3882 /*
3883 ** Sync an apnd-file.
3884 */
3885 static int apndSync(sqlite3_file *pFile, int flags){
3886   pFile = ORIGFILE(pFile);
3887   return pFile->pMethods->xSync(pFile, flags);
3888 }
3889
3890 /*
3891 ** Return the current file-size of an apnd-file.
3892 */
3893 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3894   ApndFile *p = (ApndFile *)pFile;
3895   int rc;
3896   pFile = ORIGFILE(p);
3897   rc = pFile->pMethods->xFileSize(pFile, pSize);
3898   if( rc==SQLITE_OK && p->iPgOne ){
3899     *pSize -= p->iPgOne + APND_MARK_SIZE;
3900   }
3901   return rc;
3902 }
3903
3904 /*
3905 ** Lock an apnd-file.
3906 */
3907 static int apndLock(sqlite3_file *pFile, int eLock){
3908   pFile = ORIGFILE(pFile);
3909   return pFile->pMethods->xLock(pFile, eLock);
3910 }
3911
3912 /*
3913 ** Unlock an apnd-file.
3914 */
3915 static int apndUnlock(sqlite3_file *pFile, int eLock){
3916   pFile = ORIGFILE(pFile);
3917   return pFile->pMethods->xUnlock(pFile, eLock);
3918 }
3919
3920 /*
3921 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3922 */
3923 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3924   pFile = ORIGFILE(pFile);
3925   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3926 }
3927
3928 /*
3929 ** File control method. For custom operations on an apnd-file.
3930 */
3931 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3932   ApndFile *p = (ApndFile *)pFile;
3933   int rc;
3934   pFile = ORIGFILE(pFile);
3935   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3936   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3937     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
3938   }
3939   return rc;
3940 }
3941
3942 /*
3943 ** Return the sector-size in bytes for an apnd-file.
3944 */
3945 static int apndSectorSize(sqlite3_file *pFile){
3946   pFile = ORIGFILE(pFile);
3947   return pFile->pMethods->xSectorSize(pFile);
3948 }
3949
3950 /*
3951 ** Return the device characteristic flags supported by an apnd-file.
3952 */
3953 static int apndDeviceCharacteristics(sqlite3_file *pFile){
3954   pFile = ORIGFILE(pFile);
3955   return pFile->pMethods->xDeviceCharacteristics(pFile);
3956 }
3957
3958 /* Create a shared memory file mapping */
3959 static int apndShmMap(
3960   sqlite3_file *pFile,
3961   int iPg,
3962   int pgsz,
3963   int bExtend,
3964   void volatile **pp
3965 ){
3966   pFile = ORIGFILE(pFile);
3967   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
3968 }
3969
3970 /* Perform locking on a shared-memory segment */
3971 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
3972   pFile = ORIGFILE(pFile);
3973   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
3974 }
3975
3976 /* Memory barrier operation on shared memory */
3977 static void apndShmBarrier(sqlite3_file *pFile){
3978   pFile = ORIGFILE(pFile);
3979   pFile->pMethods->xShmBarrier(pFile);
3980 }
3981
3982 /* Unmap a shared memory segment */
3983 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
3984   pFile = ORIGFILE(pFile);
3985   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
3986 }
3987
3988 /* Fetch a page of a memory-mapped file */
3989 static int apndFetch(
3990   sqlite3_file *pFile,
3991   sqlite3_int64 iOfst,
3992   int iAmt,
3993   void **pp
3994 ){
3995   ApndFile *p = (ApndFile *)pFile;
3996   pFile = ORIGFILE(pFile);
3997   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
3998 }
3999
4000 /* Release a memory-mapped page */
4001 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
4002   ApndFile *p = (ApndFile *)pFile;
4003   pFile = ORIGFILE(pFile);
4004   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
4005 }
4006
4007 /*
4008 ** Check to see if the file is an ordinary SQLite database file.
4009 */
4010 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
4011   int rc;
4012   char zHdr[16];
4013   static const char aSqliteHdr[] = "SQLite format 3";
4014   if( sz<512 ) return 0;
4015   rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
4016   if( rc ) return 0;
4017   return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
4018 }
4019
4020 /*
4021 ** Try to read the append-mark off the end of a file.  Return the
4022 ** start of the appended database if the append-mark is present.  If
4023 ** there is no append-mark, return -1;
4024 */
4025 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
4026   int rc, i;
4027   sqlite3_int64 iMark;
4028   unsigned char a[APND_MARK_SIZE];
4029
4030   if( sz<=APND_MARK_SIZE ) return -1;
4031   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
4032   if( rc ) return -1;
4033   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
4034   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
4035   for(i=1; i<8; i++){    
4036     iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
4037   }
4038   return iMark;
4039 }
4040
4041 /*
4042 ** Open an apnd file handle.
4043 */
4044 static int apndOpen(
4045   sqlite3_vfs *pVfs,
4046   const char *zName,
4047   sqlite3_file *pFile,
4048   int flags,
4049   int *pOutFlags
4050 ){
4051   ApndFile *p;
4052   sqlite3_file *pSubFile;
4053   sqlite3_vfs *pSubVfs;
4054   int rc;
4055   sqlite3_int64 sz;
4056   pSubVfs = ORIGVFS(pVfs);
4057   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
4058     return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
4059   }
4060   p = (ApndFile*)pFile;
4061   memset(p, 0, sizeof(*p));
4062   pSubFile = ORIGFILE(pFile);
4063   pFile->pMethods = &apnd_io_methods;
4064   rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
4065   if( rc ) goto apnd_open_done;
4066   rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
4067   if( rc ){
4068     pSubFile->pMethods->xClose(pSubFile);
4069     goto apnd_open_done;
4070   }
4071   if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
4072     memmove(pFile, pSubFile, pSubVfs->szOsFile);
4073     return SQLITE_OK;
4074   }
4075   p->iMark = 0;
4076   p->iPgOne = apndReadMark(sz, pFile);
4077   if( p->iPgOne>0 ){
4078     return SQLITE_OK;
4079   }
4080   if( (flags & SQLITE_OPEN_CREATE)==0 ){
4081     pSubFile->pMethods->xClose(pSubFile);
4082     rc = SQLITE_CANTOPEN;
4083   }
4084   p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
4085 apnd_open_done:
4086   if( rc ) pFile->pMethods = 0;
4087   return rc;
4088 }
4089
4090 /*
4091 ** All other VFS methods are pass-thrus.
4092 */
4093 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
4094   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
4095 }
4096 static int apndAccess(
4097   sqlite3_vfs *pVfs, 
4098   const char *zPath, 
4099   int flags, 
4100   int *pResOut
4101 ){
4102   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
4103 }
4104 static int apndFullPathname(
4105   sqlite3_vfs *pVfs, 
4106   const char *zPath, 
4107   int nOut, 
4108   char *zOut
4109 ){
4110   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
4111 }
4112 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
4113   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
4114 }
4115 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
4116   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
4117 }
4118 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
4119   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
4120 }
4121 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
4122   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
4123 }
4124 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
4125   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
4126 }
4127 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
4128   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
4129 }
4130 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
4131   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
4132 }
4133 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
4134   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
4135 }
4136 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
4137   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
4138 }
4139 static int apndSetSystemCall(
4140   sqlite3_vfs *pVfs,
4141   const char *zName,
4142   sqlite3_syscall_ptr pCall
4143 ){
4144   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
4145 }
4146 static sqlite3_syscall_ptr apndGetSystemCall(
4147   sqlite3_vfs *pVfs,
4148   const char *zName
4149 ){
4150   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
4151 }
4152 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
4153   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
4154 }
4155
4156   
4157 #ifdef _WIN32
4158
4159 #endif
4160 /* 
4161 ** This routine is called when the extension is loaded.
4162 ** Register the new VFS.
4163 */
4164 int sqlite3_appendvfs_init(
4165   sqlite3 *db, 
4166   char **pzErrMsg, 
4167   const sqlite3_api_routines *pApi
4168 ){
4169   int rc = SQLITE_OK;
4170   sqlite3_vfs *pOrig;
4171   SQLITE_EXTENSION_INIT2(pApi);
4172   (void)pzErrMsg;
4173   (void)db;
4174   pOrig = sqlite3_vfs_find(0);
4175   apnd_vfs.iVersion = pOrig->iVersion;
4176   apnd_vfs.pAppData = pOrig;
4177   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4178   rc = sqlite3_vfs_register(&apnd_vfs, 0);
4179 #ifdef APPENDVFS_TEST
4180   if( rc==SQLITE_OK ){
4181     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4182   }
4183 #endif
4184   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4185   return rc;
4186 }
4187
4188 /************************* End ../ext/misc/appendvfs.c ********************/
4189 /************************* Begin ../ext/misc/memtrace.c ******************/
4190 /*
4191 ** 2019-01-21
4192 **
4193 ** The author disclaims copyright to this source code.  In place of
4194 ** a legal notice, here is a blessing:
4195 **
4196 **    May you do good and not evil.
4197 **    May you find forgiveness for yourself and forgive others.
4198 **    May you share freely, never taking more than you give.
4199 **
4200 *************************************************************************
4201 **
4202 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
4203 ** mechanism to add a tracing layer on top of SQLite.  If this extension
4204 ** is registered prior to sqlite3_initialize(), it will cause all memory
4205 ** allocation activities to be logged on standard output, or to some other
4206 ** FILE specified by the initializer.
4207 **
4208 ** This file needs to be compiled into the application that uses it.
4209 **
4210 ** This extension is used to implement the --memtrace option of the
4211 ** command-line shell.
4212 */
4213 #include <assert.h>
4214 #include <string.h>
4215 #include <stdio.h>
4216
4217 /* The original memory allocation routines */
4218 static sqlite3_mem_methods memtraceBase;
4219 static FILE *memtraceOut;
4220
4221 /* Methods that trace memory allocations */
4222 static void *memtraceMalloc(int n){
4223   if( memtraceOut ){
4224     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n", 
4225             memtraceBase.xRoundup(n));
4226   }
4227   return memtraceBase.xMalloc(n);
4228 }
4229 static void memtraceFree(void *p){
4230   if( p==0 ) return;
4231   if( memtraceOut ){
4232     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
4233   }
4234   memtraceBase.xFree(p);
4235 }
4236 static void *memtraceRealloc(void *p, int n){
4237   if( p==0 ) return memtraceMalloc(n);
4238   if( n==0 ){
4239     memtraceFree(p);
4240     return 0;
4241   }
4242   if( memtraceOut ){
4243     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
4244             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
4245   }
4246   return memtraceBase.xRealloc(p, n);
4247 }
4248 static int memtraceSize(void *p){
4249   return memtraceBase.xSize(p);
4250 }
4251 static int memtraceRoundup(int n){
4252   return memtraceBase.xRoundup(n);
4253 }
4254 static int memtraceInit(void *p){
4255   return memtraceBase.xInit(p);
4256 }
4257 static void memtraceShutdown(void *p){
4258   memtraceBase.xShutdown(p);
4259 }
4260
4261 /* The substitute memory allocator */
4262 static sqlite3_mem_methods ersaztMethods = {
4263   memtraceMalloc,
4264   memtraceFree,
4265   memtraceRealloc,
4266   memtraceSize,
4267   memtraceRoundup,
4268   memtraceInit,
4269   memtraceShutdown,
4270   0
4271 };
4272
4273 /* Begin tracing memory allocations to out. */
4274 int sqlite3MemTraceActivate(FILE *out){
4275   int rc = SQLITE_OK;
4276   if( memtraceBase.xMalloc==0 ){
4277     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
4278     if( rc==SQLITE_OK ){
4279       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
4280     }
4281   }
4282   memtraceOut = out;
4283   return rc;
4284 }
4285
4286 /* Deactivate memory tracing */
4287 int sqlite3MemTraceDeactivate(void){
4288   int rc = SQLITE_OK;
4289   if( memtraceBase.xMalloc!=0 ){
4290     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
4291     if( rc==SQLITE_OK ){
4292       memset(&memtraceBase, 0, sizeof(memtraceBase));
4293     }
4294   }
4295   memtraceOut = 0;
4296   return rc;
4297 }
4298
4299 /************************* End ../ext/misc/memtrace.c ********************/
4300 /************************* Begin ../ext/misc/uint.c ******************/
4301 /*
4302 ** 2020-04-14
4303 **
4304 ** The author disclaims copyright to this source code.  In place of
4305 ** a legal notice, here is a blessing:
4306 **
4307 **    May you do good and not evil.
4308 **    May you find forgiveness for yourself and forgive others.
4309 **    May you share freely, never taking more than you give.
4310 **
4311 ******************************************************************************
4312 **
4313 ** This SQLite extension implements the UINT collating sequence.
4314 **
4315 ** UINT works like BINARY for text, except that embedded strings
4316 ** of digits compare in numeric order.
4317 **
4318 **     *   Leading zeros are handled properly, in the sense that
4319 **         they do not mess of the maginitude comparison of embedded
4320 **         strings of digits.  "x00123y" is equal to "x123y".
4321 **
4322 **     *   Only unsigned integers are recognized.  Plus and minus
4323 **         signs are ignored.  Decimal points and exponential notation
4324 **         are ignored.
4325 **
4326 **     *   Embedded integers can be of arbitrary length.  Comparison
4327 **         is *not* limited integers that can be expressed as a
4328 **         64-bit machine integer.
4329 */
4330 /* #include "sqlite3ext.h" */
4331 SQLITE_EXTENSION_INIT1
4332 #include <assert.h>
4333 #include <string.h>
4334 #include <ctype.h>
4335
4336 /*
4337 ** Compare text in lexicographic order, except strings of digits
4338 ** compare in numeric order.
4339 */
4340 static int uintCollFunc(
4341   void *notUsed,
4342   int nKey1, const void *pKey1,
4343   int nKey2, const void *pKey2
4344 ){
4345   const unsigned char *zA = (const unsigned char*)pKey1;
4346   const unsigned char *zB = (const unsigned char*)pKey2;
4347   int i=0, j=0, x;
4348   (void)notUsed;
4349   while( i<nKey1 && j<nKey2 ){
4350     x = zA[i] - zB[j];
4351     if( isdigit(zA[i]) ){
4352       int k;
4353       if( !isdigit(zB[j]) ) return x;
4354       while( i<nKey1 && zA[i]=='0' ){ i++; }
4355       while( j<nKey2 && zB[j]=='0' ){ j++; }
4356       k = 0;
4357       while( i+k<nKey1 && isdigit(zA[i+k])
4358              && j+k<nKey2 && isdigit(zB[j+k]) ){
4359         k++;
4360       }
4361       if( i+k<nKey1 && isdigit(zA[i+k]) ){
4362         return +1;
4363       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
4364         return -1;
4365       }else{
4366         x = memcmp(zA+i, zB+j, k);
4367         if( x ) return x;
4368         i += k;
4369         j += k;
4370       }
4371     }else if( x ){
4372       return x;
4373     }else{
4374       i++;
4375       j++;
4376     }
4377   }
4378   return (nKey1 - i) - (nKey2 - j);
4379 }
4380
4381 #ifdef _WIN32
4382
4383 #endif
4384 int sqlite3_uint_init(
4385   sqlite3 *db, 
4386   char **pzErrMsg, 
4387   const sqlite3_api_routines *pApi
4388 ){
4389   SQLITE_EXTENSION_INIT2(pApi);
4390   (void)pzErrMsg;  /* Unused parameter */
4391   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
4392 }
4393
4394 /************************* End ../ext/misc/uint.c ********************/
4395 /************************* Begin ../ext/misc/decimal.c ******************/
4396 /*
4397 ** 2020-06-22
4398 **
4399 ** The author disclaims copyright to this source code.  In place of
4400 ** a legal notice, here is a blessing:
4401 **
4402 **    May you do good and not evil.
4403 **    May you find forgiveness for yourself and forgive others.
4404 **    May you share freely, never taking more than you give.
4405 **
4406 ******************************************************************************
4407 **
4408 ** Routines to implement arbitrary-precision decimal math.
4409 **
4410 ** The focus here is on simplicity and correctness, not performance.
4411 */
4412 /* #include "sqlite3ext.h" */
4413 SQLITE_EXTENSION_INIT1
4414 #include <assert.h>
4415 #include <string.h>
4416 #include <ctype.h>
4417 #include <stdlib.h>
4418
4419 /* Mark a function parameter as unused, to suppress nuisance compiler
4420 ** warnings. */
4421 #ifndef UNUSED_PARAMETER
4422 # define UNUSED_PARAMETER(X)  (void)(X)
4423 #endif
4424
4425
4426 /* A decimal object */
4427 typedef struct Decimal Decimal;
4428 struct Decimal {
4429   char sign;        /* 0 for positive, 1 for negative */
4430   char oom;         /* True if an OOM is encountered */
4431   char isNull;      /* True if holds a NULL rather than a number */
4432   char isInit;      /* True upon initialization */
4433   int nDigit;       /* Total number of digits */
4434   int nFrac;        /* Number of digits to the right of the decimal point */
4435   signed char *a;   /* Array of digits.  Most significant first. */
4436 };
4437
4438 /*
4439 ** Release memory held by a Decimal, but do not free the object itself.
4440 */
4441 static void decimal_clear(Decimal *p){
4442   sqlite3_free(p->a);
4443 }
4444
4445 /*
4446 ** Destroy a Decimal object
4447 */
4448 static void decimal_free(Decimal *p){
4449   if( p ){
4450     decimal_clear(p);
4451     sqlite3_free(p);
4452   }
4453 }
4454
4455 /*
4456 ** Allocate a new Decimal object.  Initialize it to the number given
4457 ** by the input string.
4458 */
4459 static Decimal *decimal_new(
4460   sqlite3_context *pCtx,
4461   sqlite3_value *pIn,
4462   int nAlt,
4463   const unsigned char *zAlt
4464 ){
4465   Decimal *p;
4466   int n, i;
4467   const unsigned char *zIn;
4468   int iExp = 0;
4469   p = sqlite3_malloc( sizeof(*p) );
4470   if( p==0 ) goto new_no_mem;
4471   p->sign = 0;
4472   p->oom = 0;
4473   p->isInit = 1;
4474   p->isNull = 0;
4475   p->nDigit = 0;
4476   p->nFrac = 0;
4477   if( zAlt ){
4478     n = nAlt,
4479     zIn = zAlt;
4480   }else{
4481     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
4482       p->a = 0;
4483       p->isNull = 1;
4484       return p;
4485     }
4486     n = sqlite3_value_bytes(pIn);
4487     zIn = sqlite3_value_text(pIn);
4488   }
4489   p->a = sqlite3_malloc64( n+1 );
4490   if( p->a==0 ) goto new_no_mem;
4491   for(i=0; isspace(zIn[i]); i++){}
4492   if( zIn[i]=='-' ){
4493     p->sign = 1;
4494     i++;
4495   }else if( zIn[i]=='+' ){
4496     i++;
4497   }
4498   while( i<n && zIn[i]=='0' ) i++;
4499   while( i<n ){
4500     char c = zIn[i];
4501     if( c>='0' && c<='9' ){
4502       p->a[p->nDigit++] = c - '0';
4503     }else if( c=='.' ){
4504       p->nFrac = p->nDigit + 1;
4505     }else if( c=='e' || c=='E' ){
4506       int j = i+1;
4507       int neg = 0;
4508       if( j>=n ) break;
4509       if( zIn[j]=='-' ){
4510         neg = 1;
4511         j++;
4512       }else if( zIn[j]=='+' ){
4513         j++;
4514       }
4515       while( j<n && iExp<1000000 ){
4516         if( zIn[j]>='0' && zIn[j]<='9' ){
4517           iExp = iExp*10 + zIn[j] - '0';
4518         }
4519         j++;
4520       }
4521       if( neg ) iExp = -iExp;
4522       break;
4523     }
4524     i++;
4525   }
4526   if( p->nFrac ){
4527     p->nFrac = p->nDigit - (p->nFrac - 1);
4528   }
4529   if( iExp>0 ){
4530     if( p->nFrac>0 ){
4531       if( iExp<=p->nFrac ){
4532         p->nFrac -= iExp;
4533         iExp = 0;
4534       }else{
4535         iExp -= p->nFrac;
4536         p->nFrac = 0;
4537       }
4538     }
4539     if( iExp>0 ){   
4540       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
4541       if( p->a==0 ) goto new_no_mem;
4542       memset(p->a+p->nDigit, 0, iExp);
4543       p->nDigit += iExp;
4544     }
4545   }else if( iExp<0 ){
4546     int nExtra;
4547     iExp = -iExp;
4548     nExtra = p->nDigit - p->nFrac - 1;
4549     if( nExtra ){
4550       if( nExtra>=iExp ){
4551         p->nFrac += iExp;
4552         iExp  = 0;
4553       }else{
4554         iExp -= nExtra;
4555         p->nFrac = p->nDigit - 1;
4556       }
4557     }
4558     if( iExp>0 ){
4559       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
4560       if( p->a==0 ) goto new_no_mem;
4561       memmove(p->a+iExp, p->a, p->nDigit);
4562       memset(p->a, 0, iExp);
4563       p->nDigit += iExp;
4564       p->nFrac += iExp;
4565     }
4566   }
4567   return p;
4568
4569 new_no_mem:
4570   if( pCtx ) sqlite3_result_error_nomem(pCtx);
4571   sqlite3_free(p);
4572   return 0;
4573 }
4574
4575 /*
4576 ** Make the given Decimal the result.
4577 */
4578 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
4579   char *z;
4580   int i, j;
4581   int n;
4582   if( p==0 || p->oom ){
4583     sqlite3_result_error_nomem(pCtx);
4584     return;
4585   }
4586   if( p->isNull ){
4587     sqlite3_result_null(pCtx);
4588     return;
4589   }
4590   z = sqlite3_malloc( p->nDigit+4 );
4591   if( z==0 ){
4592     sqlite3_result_error_nomem(pCtx);
4593     return;
4594   }
4595   i = 0;
4596   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
4597     p->sign = 0;
4598   }
4599   if( p->sign ){
4600     z[0] = '-';
4601     i = 1;
4602   }
4603   n = p->nDigit - p->nFrac;
4604   if( n<=0 ){
4605     z[i++] = '0';
4606   }
4607   j = 0;
4608   while( n>1 && p->a[j]==0 ){
4609     j++;
4610     n--;
4611   }
4612   while( n>0  ){
4613     z[i++] = p->a[j] + '0';
4614     j++;
4615     n--;
4616   }
4617   if( p->nFrac ){
4618     z[i++] = '.';
4619     do{
4620       z[i++] = p->a[j] + '0';
4621       j++;
4622     }while( j<p->nDigit );
4623   }
4624   z[i] = 0;
4625   sqlite3_result_text(pCtx, z, i, sqlite3_free);
4626 }
4627
4628 /*
4629 ** SQL Function:   decimal(X)
4630 **
4631 ** Convert input X into decimal and then back into text
4632 */
4633 static void decimalFunc(
4634   sqlite3_context *context,
4635   int argc,
4636   sqlite3_value **argv
4637 ){
4638   Decimal *p = decimal_new(context, argv[0], 0, 0);
4639   UNUSED_PARAMETER(argc);
4640   decimal_result(context, p);
4641   decimal_free(p);
4642 }
4643
4644 /*
4645 ** Compare to Decimal objects.  Return negative, 0, or positive if the
4646 ** first object is less than, equal to, or greater than the second.
4647 **
4648 ** Preconditions for this routine:
4649 **
4650 **    pA!=0
4651 **    pA->isNull==0
4652 **    pB!=0
4653 **    pB->isNull==0
4654 */
4655 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4656   int nASig, nBSig, rc, n;
4657   if( pA->sign!=pB->sign ){
4658     return pA->sign ? -1 : +1;
4659   }
4660   if( pA->sign ){
4661     const Decimal *pTemp = pA;
4662     pA = pB;
4663     pB = pTemp;
4664   }
4665   nASig = pA->nDigit - pA->nFrac;
4666   nBSig = pB->nDigit - pB->nFrac;
4667   if( nASig!=nBSig ){
4668     return nASig - nBSig;
4669   }
4670   n = pA->nDigit;
4671   if( n>pB->nDigit ) n = pB->nDigit;
4672   rc = memcmp(pA->a, pB->a, n);
4673   if( rc==0 ){
4674     rc = pA->nDigit - pB->nDigit;
4675   }
4676   return rc;
4677 }
4678
4679 /*
4680 ** SQL Function:   decimal_cmp(X, Y)
4681 **
4682 ** Return negative, zero, or positive if X is less then, equal to, or
4683 ** greater than Y.
4684 */
4685 static void decimalCmpFunc(
4686   sqlite3_context *context,
4687   int argc,
4688   sqlite3_value **argv
4689 ){
4690   Decimal *pA = 0, *pB = 0;
4691   int rc;
4692
4693   UNUSED_PARAMETER(argc);
4694   pA = decimal_new(context, argv[0], 0, 0);
4695   if( pA==0 || pA->isNull ) goto cmp_done;
4696   pB = decimal_new(context, argv[1], 0, 0);
4697   if( pB==0 || pB->isNull ) goto cmp_done;
4698   rc = decimal_cmp(pA, pB);
4699   if( rc<0 ) rc = -1;
4700   else if( rc>0 ) rc = +1;
4701   sqlite3_result_int(context, rc);
4702 cmp_done:
4703   decimal_free(pA);
4704   decimal_free(pB);
4705 }
4706
4707 /*
4708 ** Expand the Decimal so that it has a least nDigit digits and nFrac
4709 ** digits to the right of the decimal point.
4710 */
4711 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4712   int nAddSig;
4713   int nAddFrac;
4714   if( p==0 ) return;
4715   nAddFrac = nFrac - p->nFrac;
4716   nAddSig = (nDigit - p->nDigit) - nAddFrac;
4717   if( nAddFrac==0 && nAddSig==0 ) return;
4718   p->a = sqlite3_realloc64(p->a, nDigit+1);
4719   if( p->a==0 ){
4720     p->oom = 1;
4721     return;
4722   }
4723   if( nAddSig ){
4724     memmove(p->a+nAddSig, p->a, p->nDigit);
4725     memset(p->a, 0, nAddSig);
4726     p->nDigit += nAddSig;
4727   }
4728   if( nAddFrac ){
4729     memset(p->a+p->nDigit, 0, nAddFrac);
4730     p->nDigit += nAddFrac;
4731     p->nFrac += nAddFrac;
4732   }
4733 }
4734
4735 /*
4736 ** Add the value pB into pA.
4737 **
4738 ** Both pA and pB might become denormalized by this routine.
4739 */
4740 static void decimal_add(Decimal *pA, Decimal *pB){
4741   int nSig, nFrac, nDigit;
4742   int i, rc;
4743   if( pA==0 ){
4744     return;
4745   }
4746   if( pA->oom || pB==0 || pB->oom ){
4747     pA->oom = 1;
4748     return;
4749   }
4750   if( pA->isNull || pB->isNull ){
4751     pA->isNull = 1;
4752     return;
4753   }
4754   nSig = pA->nDigit - pA->nFrac;
4755   if( nSig && pA->a[0]==0 ) nSig--;
4756   if( nSig<pB->nDigit-pB->nFrac ){
4757     nSig = pB->nDigit - pB->nFrac;
4758   }
4759   nFrac = pA->nFrac;
4760   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4761   nDigit = nSig + nFrac + 1;
4762   decimal_expand(pA, nDigit, nFrac);
4763   decimal_expand(pB, nDigit, nFrac);
4764   if( pA->oom || pB->oom ){
4765     pA->oom = 1;
4766   }else{
4767     if( pA->sign==pB->sign ){
4768       int carry = 0;
4769       for(i=nDigit-1; i>=0; i--){
4770         int x = pA->a[i] + pB->a[i] + carry;
4771         if( x>=10 ){
4772           carry = 1;
4773           pA->a[i] = x - 10;
4774         }else{
4775           carry = 0;
4776           pA->a[i] = x;
4777         }
4778       }
4779     }else{
4780       signed char *aA, *aB;
4781       int borrow = 0;
4782       rc = memcmp(pA->a, pB->a, nDigit);
4783       if( rc<0 ){
4784         aA = pB->a;
4785         aB = pA->a;
4786         pA->sign = !pA->sign;
4787       }else{
4788         aA = pA->a;
4789         aB = pB->a;
4790       }
4791       for(i=nDigit-1; i>=0; i--){
4792         int x = aA[i] - aB[i] - borrow;
4793         if( x<0 ){
4794           pA->a[i] = x+10;
4795           borrow = 1;
4796         }else{
4797           pA->a[i] = x;
4798           borrow = 0;
4799         }
4800       }
4801     }
4802   }
4803 }
4804
4805 /*
4806 ** Compare text in decimal order.
4807 */
4808 static int decimalCollFunc(
4809   void *notUsed,
4810   int nKey1, const void *pKey1,
4811   int nKey2, const void *pKey2
4812 ){
4813   const unsigned char *zA = (const unsigned char*)pKey1;
4814   const unsigned char *zB = (const unsigned char*)pKey2;
4815   Decimal *pA = decimal_new(0, 0, nKey1, zA);
4816   Decimal *pB = decimal_new(0, 0, nKey2, zB);
4817   int rc;
4818   UNUSED_PARAMETER(notUsed);
4819   if( pA==0 || pB==0 ){
4820     rc = 0;
4821   }else{
4822     rc = decimal_cmp(pA, pB);
4823   }
4824   decimal_free(pA);
4825   decimal_free(pB);
4826   return rc;
4827 }
4828
4829
4830 /*
4831 ** SQL Function:   decimal_add(X, Y)
4832 **                 decimal_sub(X, Y)
4833 **
4834 ** Return the sum or difference of X and Y.
4835 */
4836 static void decimalAddFunc(
4837   sqlite3_context *context,
4838   int argc,
4839   sqlite3_value **argv
4840 ){
4841   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4842   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4843   UNUSED_PARAMETER(argc);
4844   decimal_add(pA, pB);
4845   decimal_result(context, pA);
4846   decimal_free(pA);
4847   decimal_free(pB);
4848 }
4849 static void decimalSubFunc(
4850   sqlite3_context *context,
4851   int argc,
4852   sqlite3_value **argv
4853 ){
4854   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4855   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4856   UNUSED_PARAMETER(argc);
4857   if( pB==0 ) return;
4858   pB->sign = !pB->sign;
4859   decimal_add(pA, pB);
4860   decimal_result(context, pA);
4861   decimal_free(pA);
4862   decimal_free(pB);
4863 }
4864
4865 /* Aggregate funcion:   decimal_sum(X)
4866 **
4867 ** Works like sum() except that it uses decimal arithmetic for unlimited
4868 ** precision.
4869 */
4870 static void decimalSumStep(
4871   sqlite3_context *context,
4872   int argc,
4873   sqlite3_value **argv
4874 ){
4875   Decimal *p;
4876   Decimal *pArg;
4877   UNUSED_PARAMETER(argc);
4878   p = sqlite3_aggregate_context(context, sizeof(*p));
4879   if( p==0 ) return;
4880   if( !p->isInit ){
4881     p->isInit = 1;
4882     p->a = sqlite3_malloc(2);
4883     if( p->a==0 ){
4884       p->oom = 1;
4885     }else{
4886       p->a[0] = 0;
4887     }
4888     p->nDigit = 1;
4889     p->nFrac = 0;
4890   }
4891   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4892   pArg = decimal_new(context, argv[0], 0, 0);
4893   decimal_add(p, pArg);
4894   decimal_free(pArg);
4895 }
4896 static void decimalSumInverse(
4897   sqlite3_context *context,
4898   int argc,
4899   sqlite3_value **argv
4900 ){
4901   Decimal *p;
4902   Decimal *pArg;
4903   UNUSED_PARAMETER(argc);
4904   p = sqlite3_aggregate_context(context, sizeof(*p));
4905   if( p==0 ) return;
4906   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4907   pArg = decimal_new(context, argv[0], 0, 0);
4908   if( pArg ) pArg->sign = !pArg->sign;
4909   decimal_add(p, pArg);
4910   decimal_free(pArg);
4911 }
4912 static void decimalSumValue(sqlite3_context *context){
4913   Decimal *p = sqlite3_aggregate_context(context, 0);
4914   if( p==0 ) return;
4915   decimal_result(context, p);
4916 }
4917 static void decimalSumFinalize(sqlite3_context *context){
4918   Decimal *p = sqlite3_aggregate_context(context, 0);
4919   if( p==0 ) return;
4920   decimal_result(context, p);
4921   decimal_clear(p);
4922 }
4923
4924 /*
4925 ** SQL Function:   decimal_mul(X, Y)
4926 **
4927 ** Return the product of X and Y.
4928 **
4929 ** All significant digits after the decimal point are retained.
4930 ** Trailing zeros after the decimal point are omitted as long as
4931 ** the number of digits after the decimal point is no less than
4932 ** either the number of digits in either input.
4933 */
4934 static void decimalMulFunc(
4935   sqlite3_context *context,
4936   int argc,
4937   sqlite3_value **argv
4938 ){
4939   Decimal *pA = decimal_new(context, argv[0], 0, 0);
4940   Decimal *pB = decimal_new(context, argv[1], 0, 0);
4941   signed char *acc = 0;
4942   int i, j, k;
4943   int minFrac;
4944   UNUSED_PARAMETER(argc);
4945   if( pA==0 || pA->oom || pA->isNull
4946    || pB==0 || pB->oom || pB->isNull 
4947   ){
4948     goto mul_end;
4949   }
4950   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4951   if( acc==0 ){
4952     sqlite3_result_error_nomem(context);
4953     goto mul_end;
4954   }
4955   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4956   minFrac = pA->nFrac;
4957   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4958   for(i=pA->nDigit-1; i>=0; i--){
4959     signed char f = pA->a[i];
4960     int carry = 0, x;
4961     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4962       x = acc[k] + f*pB->a[j] + carry;
4963       acc[k] = x%10;
4964       carry = x/10;
4965     }
4966     x = acc[k] + carry;
4967     acc[k] = x%10;
4968     acc[k-1] += x/10;
4969   }
4970   sqlite3_free(pA->a);
4971   pA->a = acc;
4972   acc = 0;
4973   pA->nDigit += pB->nDigit + 2;
4974   pA->nFrac += pB->nFrac;
4975   pA->sign ^= pB->sign;
4976   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4977     pA->nFrac--;
4978     pA->nDigit--;
4979   }
4980   decimal_result(context, pA);
4981
4982 mul_end:
4983   sqlite3_free(acc);
4984   decimal_free(pA);
4985   decimal_free(pB);
4986 }
4987
4988 #ifdef _WIN32
4989
4990 #endif
4991 int sqlite3_decimal_init(
4992   sqlite3 *db, 
4993   char **pzErrMsg, 
4994   const sqlite3_api_routines *pApi
4995 ){
4996   int rc = SQLITE_OK;
4997   static const struct {
4998     const char *zFuncName;
4999     int nArg;
5000     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5001   } aFunc[] = {
5002     { "decimal",       1,   decimalFunc        },
5003     { "decimal_cmp",   2,   decimalCmpFunc     },
5004     { "decimal_add",   2,   decimalAddFunc     },
5005     { "decimal_sub",   2,   decimalSubFunc     },
5006     { "decimal_mul",   2,   decimalMulFunc     },
5007   };
5008   unsigned int i;
5009   (void)pzErrMsg;  /* Unused parameter */
5010
5011   SQLITE_EXTENSION_INIT2(pApi);
5012
5013   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5014     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
5015                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5016                    0, aFunc[i].xFunc, 0, 0);
5017   }
5018   if( rc==SQLITE_OK ){
5019     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
5020                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
5021                    decimalSumStep, decimalSumFinalize,
5022                    decimalSumValue, decimalSumInverse, 0);
5023   }
5024   if( rc==SQLITE_OK ){
5025     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
5026                                   0, decimalCollFunc);
5027   }
5028   return rc;
5029 }
5030
5031 /************************* End ../ext/misc/decimal.c ********************/
5032 /************************* Begin ../ext/misc/ieee754.c ******************/
5033 /*
5034 ** 2013-04-17
5035 **
5036 ** The author disclaims copyright to this source code.  In place of
5037 ** a legal notice, here is a blessing:
5038 **
5039 **    May you do good and not evil.
5040 **    May you find forgiveness for yourself and forgive others.
5041 **    May you share freely, never taking more than you give.
5042 **
5043 ******************************************************************************
5044 **
5045 ** This SQLite extension implements functions for the exact display
5046 ** and input of IEEE754 Binary64 floating-point numbers.
5047 **
5048 **   ieee754(X)
5049 **   ieee754(Y,Z)
5050 **
5051 ** In the first form, the value X should be a floating-point number.
5052 ** The function will return a string of the form 'ieee754(Y,Z)' where
5053 ** Y and Z are integers such that X==Y*pow(2,Z).
5054 **
5055 ** In the second form, Y and Z are integers which are the mantissa and
5056 ** base-2 exponent of a new floating point number.  The function returns
5057 ** a floating-point value equal to Y*pow(2,Z).
5058 **
5059 ** Examples:
5060 **
5061 **     ieee754(2.0)             ->     'ieee754(2,0)'
5062 **     ieee754(45.25)           ->     'ieee754(181,-2)'
5063 **     ieee754(2, 0)            ->     2.0
5064 **     ieee754(181, -2)         ->     45.25
5065 **
5066 ** Two additional functions break apart the one-argument ieee754()
5067 ** result into separate integer values:
5068 **
5069 **     ieee754_mantissa(45.25)  ->     181
5070 **     ieee754_exponent(45.25)  ->     -2
5071 **
5072 ** These functions convert binary64 numbers into blobs and back again.
5073 **
5074 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5075 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5076 **
5077 ** In all single-argument functions, if the argument is an 8-byte blob
5078 ** then that blob is interpreted as a big-endian binary64 value.
5079 **
5080 **
5081 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5082 ** -----------------------------------------------
5083 **
5084 ** This extension in combination with the separate 'decimal' extension
5085 ** can be used to compute the exact decimal representation of binary64
5086 ** values.  To begin, first compute a table of exponent values:
5087 **
5088 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5089 **    WITH RECURSIVE c(x,v) AS (
5090 **      VALUES(0,'1')
5091 **      UNION ALL
5092 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5093 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5094 **    WITH RECURSIVE c(x,v) AS (
5095 **      VALUES(-1,'0.5')
5096 **      UNION ALL
5097 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5098 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5099 **
5100 ** Then, to compute the exact decimal representation of a floating
5101 ** point value (the value 47.49 is used in the example) do:
5102 **
5103 **    WITH c(n) AS (VALUES(47.49))
5104 **          ---------------^^^^^---- Replace with whatever you want
5105 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5106 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5107 **
5108 ** Here is a query to show various boundry values for the binary64
5109 ** number format:
5110 **
5111 **    WITH c(name,bin) AS (VALUES
5112 **       ('minimum positive value',        x'0000000000000001'),
5113 **       ('maximum subnormal value',       x'000fffffffffffff'),
5114 **       ('mininum positive nornal value', x'0010000000000000'),
5115 **       ('maximum value',                 x'7fefffffffffffff'))
5116 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5117 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5118 **
5119 */
5120 /* #include "sqlite3ext.h" */
5121 SQLITE_EXTENSION_INIT1
5122 #include <assert.h>
5123 #include <string.h>
5124
5125 /* Mark a function parameter as unused, to suppress nuisance compiler
5126 ** warnings. */
5127 #ifndef UNUSED_PARAMETER
5128 # define UNUSED_PARAMETER(X)  (void)(X)
5129 #endif
5130
5131 /*
5132 ** Implementation of the ieee754() function
5133 */
5134 static void ieee754func(
5135   sqlite3_context *context,
5136   int argc,
5137   sqlite3_value **argv
5138 ){
5139   if( argc==1 ){
5140     sqlite3_int64 m, a;
5141     double r;
5142     int e;
5143     int isNeg;
5144     char zResult[100];
5145     assert( sizeof(m)==sizeof(r) );
5146     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5147      && sqlite3_value_bytes(argv[0])==sizeof(r)
5148     ){
5149       const unsigned char *x = sqlite3_value_blob(argv[0]);
5150       unsigned int i;
5151       sqlite3_uint64 v = 0;
5152       for(i=0; i<sizeof(r); i++){
5153         v = (v<<8) | x[i];
5154       }
5155       memcpy(&r, &v, sizeof(r));
5156     }else{
5157       r = sqlite3_value_double(argv[0]);
5158     }
5159     if( r<0.0 ){
5160       isNeg = 1;
5161       r = -r;
5162     }else{
5163       isNeg = 0;
5164     }
5165     memcpy(&a,&r,sizeof(a));
5166     if( a==0 ){
5167       e = 0;
5168       m = 0;
5169     }else{
5170       e = a>>52;
5171       m = a & ((((sqlite3_int64)1)<<52)-1);
5172       if( e==0 ){
5173         m <<= 1;
5174       }else{
5175         m |= ((sqlite3_int64)1)<<52;
5176       }
5177       while( e<1075 && m>0 && (m&1)==0 ){
5178         m >>= 1;
5179         e++;
5180       }
5181       if( isNeg ) m = -m;
5182     }
5183     switch( *(int*)sqlite3_user_data(context) ){
5184       case 0:
5185         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5186                          m, e-1075);
5187         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5188         break;
5189       case 1:
5190         sqlite3_result_int64(context, m);
5191         break;
5192       case 2:
5193         sqlite3_result_int(context, e-1075);
5194         break;
5195     }
5196   }else{
5197     sqlite3_int64 m, e, a;
5198     double r;
5199     int isNeg = 0;
5200     m = sqlite3_value_int64(argv[0]);
5201     e = sqlite3_value_int64(argv[1]);
5202     if( m<0 ){
5203       isNeg = 1;
5204       m = -m;
5205       if( m<0 ) return;
5206     }else if( m==0 && e>-1000 && e<1000 ){
5207       sqlite3_result_double(context, 0.0);
5208       return;
5209     }
5210     while( (m>>32)&0xffe00000 ){
5211       m >>= 1;
5212       e++;
5213     }
5214     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5215       m <<= 1;
5216       e--;
5217     }
5218     e += 1075;
5219     if( e<=0 ){
5220       /* Subnormal */
5221       m >>= 1-e;
5222       e = 0;
5223     }else if( e>0x7ff ){
5224       e = 0x7ff;
5225     }
5226     a = m & ((((sqlite3_int64)1)<<52)-1);
5227     a |= e<<52;
5228     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5229     memcpy(&r, &a, sizeof(r));
5230     sqlite3_result_double(context, r);
5231   }
5232 }
5233
5234 /*
5235 ** Functions to convert between blobs and floats.
5236 */
5237 static void ieee754func_from_blob(
5238   sqlite3_context *context,
5239   int argc,
5240   sqlite3_value **argv
5241 ){
5242   UNUSED_PARAMETER(argc);
5243   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5244    && sqlite3_value_bytes(argv[0])==sizeof(double)
5245   ){
5246     double r;
5247     const unsigned char *x = sqlite3_value_blob(argv[0]);
5248     unsigned int i;
5249     sqlite3_uint64 v = 0;
5250     for(i=0; i<sizeof(r); i++){
5251       v = (v<<8) | x[i];
5252     }
5253     memcpy(&r, &v, sizeof(r));
5254     sqlite3_result_double(context, r);
5255   }
5256 }
5257 static void ieee754func_to_blob(
5258   sqlite3_context *context,
5259   int argc,
5260   sqlite3_value **argv
5261 ){
5262   UNUSED_PARAMETER(argc);
5263   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5264    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5265   ){
5266     double r = sqlite3_value_double(argv[0]);
5267     sqlite3_uint64 v;
5268     unsigned char a[sizeof(r)];
5269     unsigned int i;
5270     memcpy(&v, &r, sizeof(r));
5271     for(i=1; i<=sizeof(r); i++){
5272       a[sizeof(r)-i] = v&0xff;
5273       v >>= 8;
5274     }
5275     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5276   }
5277 }
5278
5279
5280 #ifdef _WIN32
5281
5282 #endif
5283 int sqlite3_ieee_init(
5284   sqlite3 *db, 
5285   char **pzErrMsg, 
5286   const sqlite3_api_routines *pApi
5287 ){
5288   static const struct {
5289     char *zFName;
5290     int nArg;
5291     int iAux;
5292     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5293   } aFunc[] = {
5294     { "ieee754",           1,   0, ieee754func },
5295     { "ieee754",           2,   0, ieee754func },
5296     { "ieee754_mantissa",  1,   1, ieee754func },
5297     { "ieee754_exponent",  1,   2, ieee754func },
5298     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5299     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5300
5301   };
5302   unsigned int i;
5303   int rc = SQLITE_OK;
5304   SQLITE_EXTENSION_INIT2(pApi);
5305   (void)pzErrMsg;  /* Unused parameter */
5306   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5307     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,    
5308                                SQLITE_UTF8|SQLITE_INNOCUOUS,
5309                                (void*)&aFunc[i].iAux,
5310                                aFunc[i].xFunc, 0, 0);
5311   }
5312   return rc;
5313 }
5314
5315 /************************* End ../ext/misc/ieee754.c ********************/
5316 /************************* Begin ../ext/misc/series.c ******************/
5317 /*
5318 ** 2015-08-18
5319 **
5320 ** The author disclaims copyright to this source code.  In place of
5321 ** a legal notice, here is a blessing:
5322 **
5323 **    May you do good and not evil.
5324 **    May you find forgiveness for yourself and forgive others.
5325 **    May you share freely, never taking more than you give.
5326 **
5327 *************************************************************************
5328 **
5329 ** This file demonstrates how to create a table-valued-function using
5330 ** a virtual table.  This demo implements the generate_series() function
5331 ** which gives similar results to the eponymous function in PostgreSQL.
5332 ** Examples:
5333 **
5334 **      SELECT * FROM generate_series(0,100,5);
5335 **
5336 ** The query above returns integers from 0 through 100 counting by steps
5337 ** of 5.
5338 **
5339 **      SELECT * FROM generate_series(0,100);
5340 **
5341 ** Integers from 0 through 100 with a step size of 1.
5342 **
5343 **      SELECT * FROM generate_series(20) LIMIT 10;
5344 **
5345 ** Integers 20 through 29.
5346 **
5347 ** HOW IT WORKS
5348 **
5349 ** The generate_series "function" is really a virtual table with the
5350 ** following schema:
5351 **
5352 **     CREATE TABLE generate_series(
5353 **       value,
5354 **       start HIDDEN,
5355 **       stop HIDDEN,
5356 **       step HIDDEN
5357 **     );
5358 **
5359 ** Function arguments in queries against this virtual table are translated
5360 ** into equality constraints against successive hidden columns.  In other
5361 ** words, the following pairs of queries are equivalent to each other:
5362 **
5363 **    SELECT * FROM generate_series(0,100,5);
5364 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5365 **
5366 **    SELECT * FROM generate_series(0,100);
5367 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5368 **
5369 **    SELECT * FROM generate_series(20) LIMIT 10;
5370 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5371 **
5372 ** The generate_series virtual table implementation leaves the xCreate method
5373 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5374 ** TABLE command with "generate_series" as the USING argument.  Instead, there
5375 ** is a single generate_series virtual table that is always available without
5376 ** having to be created first.
5377 **
5378 ** The xBestIndex method looks for equality constraints against the hidden
5379 ** start, stop, and step columns, and if present, it uses those constraints
5380 ** to bound the sequence of generated values.  If the equality constraints
5381 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5382 ** xBestIndex returns a small cost when both start and stop are available,
5383 ** and a very large cost if either start or stop are unavailable.  This
5384 ** encourages the query planner to order joins such that the bounds of the
5385 ** series are well-defined.
5386 */
5387 /* #include "sqlite3ext.h" */
5388 SQLITE_EXTENSION_INIT1
5389 #include <assert.h>
5390 #include <string.h>
5391
5392 #ifndef SQLITE_OMIT_VIRTUALTABLE
5393
5394
5395 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5396 ** serve as the underlying representation of a cursor that scans
5397 ** over rows of the result
5398 */
5399 typedef struct series_cursor series_cursor;
5400 struct series_cursor {
5401   sqlite3_vtab_cursor base;  /* Base class - must be first */
5402   int isDesc;                /* True to count down rather than up */
5403   sqlite3_int64 iRowid;      /* The rowid */
5404   sqlite3_int64 iValue;      /* Current value ("value") */
5405   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
5406   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
5407   sqlite3_int64 iStep;       /* Increment ("step") */
5408 };
5409
5410 /*
5411 ** The seriesConnect() method is invoked to create a new
5412 ** series_vtab that describes the generate_series virtual table.
5413 **
5414 ** Think of this routine as the constructor for series_vtab objects.
5415 **
5416 ** All this routine needs to do is:
5417 **
5418 **    (1) Allocate the series_vtab object and initialize all fields.
5419 **
5420 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5421 **        result set of queries against generate_series will look like.
5422 */
5423 static int seriesConnect(
5424   sqlite3 *db,
5425   void *pUnused,
5426   int argcUnused, const char *const*argvUnused,
5427   sqlite3_vtab **ppVtab,
5428   char **pzErrUnused
5429 ){
5430   sqlite3_vtab *pNew;
5431   int rc;
5432
5433 /* Column numbers */
5434 #define SERIES_COLUMN_VALUE 0
5435 #define SERIES_COLUMN_START 1
5436 #define SERIES_COLUMN_STOP  2
5437 #define SERIES_COLUMN_STEP  3
5438
5439   (void)pUnused;
5440   (void)argcUnused;
5441   (void)argvUnused;
5442   (void)pzErrUnused;
5443   rc = sqlite3_declare_vtab(db,
5444      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5445   if( rc==SQLITE_OK ){
5446     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5447     if( pNew==0 ) return SQLITE_NOMEM;
5448     memset(pNew, 0, sizeof(*pNew));
5449     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5450   }
5451   return rc;
5452 }
5453
5454 /*
5455 ** This method is the destructor for series_cursor objects.
5456 */
5457 static int seriesDisconnect(sqlite3_vtab *pVtab){
5458   sqlite3_free(pVtab);
5459   return SQLITE_OK;
5460 }
5461
5462 /*
5463 ** Constructor for a new series_cursor object.
5464 */
5465 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5466   series_cursor *pCur;
5467   (void)pUnused;
5468   pCur = sqlite3_malloc( sizeof(*pCur) );
5469   if( pCur==0 ) return SQLITE_NOMEM;
5470   memset(pCur, 0, sizeof(*pCur));
5471   *ppCursor = &pCur->base;
5472   return SQLITE_OK;
5473 }
5474
5475 /*
5476 ** Destructor for a series_cursor.
5477 */
5478 static int seriesClose(sqlite3_vtab_cursor *cur){
5479   sqlite3_free(cur);
5480   return SQLITE_OK;
5481 }
5482
5483
5484 /*
5485 ** Advance a series_cursor to its next row of output.
5486 */
5487 static int seriesNext(sqlite3_vtab_cursor *cur){
5488   series_cursor *pCur = (series_cursor*)cur;
5489   if( pCur->isDesc ){
5490     pCur->iValue -= pCur->iStep;
5491   }else{
5492     pCur->iValue += pCur->iStep;
5493   }
5494   pCur->iRowid++;
5495   return SQLITE_OK;
5496 }
5497
5498 /*
5499 ** Return values of columns for the row at which the series_cursor
5500 ** is currently pointing.
5501 */
5502 static int seriesColumn(
5503   sqlite3_vtab_cursor *cur,   /* The cursor */
5504   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5505   int i                       /* Which column to return */
5506 ){
5507   series_cursor *pCur = (series_cursor*)cur;
5508   sqlite3_int64 x = 0;
5509   switch( i ){
5510     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
5511     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
5512     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
5513     default:                   x = pCur->iValue;  break;
5514   }
5515   sqlite3_result_int64(ctx, x);
5516   return SQLITE_OK;
5517 }
5518
5519 /*
5520 ** Return the rowid for the current row. In this implementation, the
5521 ** first row returned is assigned rowid value 1, and each subsequent
5522 ** row a value 1 more than that of the previous.
5523 */
5524 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5525   series_cursor *pCur = (series_cursor*)cur;
5526   *pRowid = pCur->iRowid;
5527   return SQLITE_OK;
5528 }
5529
5530 /*
5531 ** Return TRUE if the cursor has been moved off of the last
5532 ** row of output.
5533 */
5534 static int seriesEof(sqlite3_vtab_cursor *cur){
5535   series_cursor *pCur = (series_cursor*)cur;
5536   if( pCur->isDesc ){
5537     return pCur->iValue < pCur->mnValue;
5538   }else{
5539     return pCur->iValue > pCur->mxValue;
5540   }
5541 }
5542
5543 /* True to cause run-time checking of the start=, stop=, and/or step= 
5544 ** parameters.  The only reason to do this is for testing the
5545 ** constraint checking logic for virtual tables in the SQLite core.
5546 */
5547 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5548 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5549 #endif
5550
5551 /*
5552 ** This method is called to "rewind" the series_cursor object back
5553 ** to the first row of output.  This method is always called at least
5554 ** once prior to any call to seriesColumn() or seriesRowid() or 
5555 ** seriesEof().
5556 **
5557 ** The query plan selected by seriesBestIndex is passed in the idxNum
5558 ** parameter.  (idxStr is not used in this implementation.)  idxNum
5559 ** is a bitmask showing which constraints are available:
5560 **
5561 **    1:    start=VALUE
5562 **    2:    stop=VALUE
5563 **    4:    step=VALUE
5564 **
5565 ** Also, if bit 8 is set, that means that the series should be output
5566 ** in descending order rather than in ascending order.
5567 **
5568 ** This routine should initialize the cursor and position it so that it
5569 ** is pointing at the first row, or pointing off the end of the table
5570 ** (so that seriesEof() will return true) if the table is empty.
5571 */
5572 static int seriesFilter(
5573   sqlite3_vtab_cursor *pVtabCursor, 
5574   int idxNum, const char *idxStrUnused,
5575   int argc, sqlite3_value **argv
5576 ){
5577   series_cursor *pCur = (series_cursor *)pVtabCursor;
5578   int i = 0;
5579   (void)idxStrUnused;
5580   if( idxNum & 1 ){
5581     pCur->mnValue = sqlite3_value_int64(argv[i++]);
5582   }else{
5583     pCur->mnValue = 0;
5584   }
5585   if( idxNum & 2 ){
5586     pCur->mxValue = sqlite3_value_int64(argv[i++]);
5587   }else{
5588     pCur->mxValue = 0xffffffff;
5589   }
5590   if( idxNum & 4 ){
5591     pCur->iStep = sqlite3_value_int64(argv[i++]);
5592     if( pCur->iStep<1 ) pCur->iStep = 1;
5593   }else{
5594     pCur->iStep = 1;
5595   }
5596   for(i=0; i<argc; i++){
5597     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
5598       /* If any of the constraints have a NULL value, then return no rows.
5599       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
5600       pCur->mnValue = 1;
5601       pCur->mxValue = 0;
5602       break;
5603     }
5604   }
5605   if( idxNum & 8 ){
5606     pCur->isDesc = 1;
5607     pCur->iValue = pCur->mxValue;
5608     if( pCur->iStep>0 ){
5609       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
5610     }
5611   }else{
5612     pCur->isDesc = 0;
5613     pCur->iValue = pCur->mnValue;
5614   }
5615   pCur->iRowid = 1;
5616   return SQLITE_OK;
5617 }
5618
5619 /*
5620 ** SQLite will invoke this method one or more times while planning a query
5621 ** that uses the generate_series virtual table.  This routine needs to create
5622 ** a query plan for each invocation and compute an estimated cost for that
5623 ** plan.
5624 **
5625 ** In this implementation idxNum is used to represent the
5626 ** query plan.  idxStr is unused.
5627 **
5628 ** The query plan is represented by bits in idxNum:
5629 **
5630 **  (1)  start = $value  -- constraint exists
5631 **  (2)  stop = $value   -- constraint exists
5632 **  (4)  step = $value   -- constraint exists
5633 **  (8)  output in descending order
5634 */
5635 static int seriesBestIndex(
5636   sqlite3_vtab *tabUnused,
5637   sqlite3_index_info *pIdxInfo
5638 ){
5639   int i, j;              /* Loop over constraints */
5640   int idxNum = 0;        /* The query plan bitmask */
5641   int unusableMask = 0;  /* Mask of unusable constraints */
5642   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
5643   int aIdx[3];           /* Constraints on start, stop, and step */
5644   const struct sqlite3_index_constraint *pConstraint;
5645
5646   /* This implementation assumes that the start, stop, and step columns
5647   ** are the last three columns in the virtual table. */
5648   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
5649   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
5650   (void)tabUnused;
5651   aIdx[0] = aIdx[1] = aIdx[2] = -1;
5652   pConstraint = pIdxInfo->aConstraint;
5653   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
5654     int iCol;    /* 0 for start, 1 for stop, 2 for step */
5655     int iMask;   /* bitmask for those column */
5656     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
5657     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
5658     assert( iCol>=0 && iCol<=2 );
5659     iMask = 1 << iCol;
5660     if( pConstraint->usable==0 ){
5661       unusableMask |=  iMask;
5662       continue;
5663     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
5664       idxNum |= iMask;
5665       aIdx[iCol] = i;
5666     }
5667   }
5668   for(i=0; i<3; i++){
5669     if( (j = aIdx[i])>=0 ){
5670       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
5671       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
5672     }
5673   }
5674   if( (unusableMask & ~idxNum)!=0 ){
5675     /* The start, stop, and step columns are inputs.  Therefore if there
5676     ** are unusable constraints on any of start, stop, or step then
5677     ** this plan is unusable */
5678     return SQLITE_CONSTRAINT;
5679   }
5680   if( (idxNum & 3)==3 ){
5681     /* Both start= and stop= boundaries are available.  This is the 
5682     ** the preferred case */
5683     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
5684     pIdxInfo->estimatedRows = 1000;
5685     if( pIdxInfo->nOrderBy==1 ){
5686       if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
5687       pIdxInfo->orderByConsumed = 1;
5688     }
5689   }else{
5690     /* If either boundary is missing, we have to generate a huge span
5691     ** of numbers.  Make this case very expensive so that the query
5692     ** planner will work hard to avoid it. */
5693     pIdxInfo->estimatedRows = 2147483647;
5694   }
5695   pIdxInfo->idxNum = idxNum;
5696   return SQLITE_OK;
5697 }
5698
5699 /*
5700 ** This following structure defines all the methods for the 
5701 ** generate_series virtual table.
5702 */
5703 static sqlite3_module seriesModule = {
5704   0,                         /* iVersion */
5705   0,                         /* xCreate */
5706   seriesConnect,             /* xConnect */
5707   seriesBestIndex,           /* xBestIndex */
5708   seriesDisconnect,          /* xDisconnect */
5709   0,                         /* xDestroy */
5710   seriesOpen,                /* xOpen - open a cursor */
5711   seriesClose,               /* xClose - close a cursor */
5712   seriesFilter,              /* xFilter - configure scan constraints */
5713   seriesNext,                /* xNext - advance a cursor */
5714   seriesEof,                 /* xEof - check for end of scan */
5715   seriesColumn,              /* xColumn - read data */
5716   seriesRowid,               /* xRowid - read data */
5717   0,                         /* xUpdate */
5718   0,                         /* xBegin */
5719   0,                         /* xSync */
5720   0,                         /* xCommit */
5721   0,                         /* xRollback */
5722   0,                         /* xFindMethod */
5723   0,                         /* xRename */
5724   0,                         /* xSavepoint */
5725   0,                         /* xRelease */
5726   0,                         /* xRollbackTo */
5727   0                          /* xShadowName */
5728 };
5729
5730 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5731
5732 #ifdef _WIN32
5733
5734 #endif
5735 int sqlite3_series_init(
5736   sqlite3 *db, 
5737   char **pzErrMsg, 
5738   const sqlite3_api_routines *pApi
5739 ){
5740   int rc = SQLITE_OK;
5741   SQLITE_EXTENSION_INIT2(pApi);
5742 #ifndef SQLITE_OMIT_VIRTUALTABLE
5743   if( sqlite3_libversion_number()<3008012 ){
5744     *pzErrMsg = sqlite3_mprintf(
5745         "generate_series() requires SQLite 3.8.12 or later");
5746     return SQLITE_ERROR;
5747   }
5748   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
5749 #endif
5750   return rc;
5751 }
5752
5753 /************************* End ../ext/misc/series.c ********************/
5754 #ifdef SQLITE_HAVE_ZLIB
5755 /************************* Begin ../ext/misc/zipfile.c ******************/
5756 /*
5757 ** 2017-12-26
5758 **
5759 ** The author disclaims copyright to this source code.  In place of
5760 ** a legal notice, here is a blessing:
5761 **
5762 **    May you do good and not evil.
5763 **    May you find forgiveness for yourself and forgive others.
5764 **    May you share freely, never taking more than you give.
5765 **
5766 ******************************************************************************
5767 **
5768 ** This file implements a virtual table for reading and writing ZIP archive
5769 ** files.
5770 **
5771 ** Usage example:
5772 **
5773 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
5774 **
5775 ** Current limitations:
5776 **
5777 **    *  No support for encryption
5778 **    *  No support for ZIP archives spanning multiple files
5779 **    *  No support for zip64 extensions
5780 **    *  Only the "inflate/deflate" (zlib) compression method is supported
5781 */
5782 /* #include "sqlite3ext.h" */
5783 SQLITE_EXTENSION_INIT1
5784 #include <stdio.h>
5785 #include <string.h>
5786 #include <assert.h>
5787
5788 #include <zlib.h>
5789
5790 #ifndef SQLITE_OMIT_VIRTUALTABLE
5791
5792 #ifndef SQLITE_AMALGAMATION
5793
5794 /* typedef sqlite3_int64 i64; */
5795 /* typedef unsigned char u8; */
5796 typedef unsigned short u16;
5797 typedef unsigned long u32;
5798 #define MIN(a,b) ((a)<(b) ? (a) : (b))
5799
5800 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
5801 # define ALWAYS(X)      (1)
5802 # define NEVER(X)       (0)
5803 #elif !defined(NDEBUG)
5804 # define ALWAYS(X)      ((X)?1:(assert(0),0))
5805 # define NEVER(X)       ((X)?(assert(0),1):0)
5806 #else
5807 # define ALWAYS(X)      (X)
5808 # define NEVER(X)       (X)
5809 #endif
5810
5811 #endif   /* SQLITE_AMALGAMATION */
5812
5813 /*
5814 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
5815 **
5816 ** In some ways it would be better to obtain these values from system 
5817 ** header files. But, the dependency is undesirable and (a) these
5818 ** have been stable for decades, (b) the values are part of POSIX and
5819 ** are also made explicit in [man stat], and (c) are part of the 
5820 ** file format for zip archives.
5821 */
5822 #ifndef S_IFDIR
5823 # define S_IFDIR 0040000
5824 #endif
5825 #ifndef S_IFREG
5826 # define S_IFREG 0100000
5827 #endif
5828 #ifndef S_IFLNK
5829 # define S_IFLNK 0120000
5830 #endif
5831
5832 static const char ZIPFILE_SCHEMA[] = 
5833   "CREATE TABLE y("
5834     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
5835     "mode,"              /* 1: POSIX mode for file */
5836     "mtime,"             /* 2: Last modification time (secs since 1970)*/
5837     "sz,"                /* 3: Size of object */
5838     "rawdata,"           /* 4: Raw data */
5839     "data,"              /* 5: Uncompressed data */
5840     "method,"            /* 6: Compression method (integer) */
5841     "z HIDDEN"           /* 7: Name of zip file */
5842   ") WITHOUT ROWID;";
5843
5844 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
5845 #define ZIPFILE_BUFFER_SIZE (64*1024)
5846
5847
5848 /*
5849 ** Magic numbers used to read and write zip files.
5850 **
5851 ** ZIPFILE_NEWENTRY_MADEBY:
5852 **   Use this value for the "version-made-by" field in new zip file
5853 **   entries. The upper byte indicates "unix", and the lower byte 
5854 **   indicates that the zip file matches pkzip specification 3.0. 
5855 **   This is what info-zip seems to do.
5856 **
5857 ** ZIPFILE_NEWENTRY_REQUIRED:
5858 **   Value for "version-required-to-extract" field of new entries.
5859 **   Version 2.0 is required to support folders and deflate compression.
5860 **
5861 ** ZIPFILE_NEWENTRY_FLAGS:
5862 **   Value for "general-purpose-bit-flags" field of new entries. Bit
5863 **   11 means "utf-8 filename and comment".
5864 **
5865 ** ZIPFILE_SIGNATURE_CDS:
5866 **   First 4 bytes of a valid CDS record.
5867 **
5868 ** ZIPFILE_SIGNATURE_LFH:
5869 **   First 4 bytes of a valid LFH record.
5870 **
5871 ** ZIPFILE_SIGNATURE_EOCD
5872 **   First 4 bytes of a valid EOCD record.
5873 */
5874 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
5875 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
5876 #define ZIPFILE_NEWENTRY_REQUIRED 20
5877 #define ZIPFILE_NEWENTRY_FLAGS    0x800
5878 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
5879 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
5880 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
5881
5882 /*
5883 ** The sizes of the fixed-size part of each of the three main data 
5884 ** structures in a zip archive.
5885 */
5886 #define ZIPFILE_LFH_FIXED_SZ      30
5887 #define ZIPFILE_EOCD_FIXED_SZ     22
5888 #define ZIPFILE_CDS_FIXED_SZ      46
5889
5890 /*
5891 *** 4.3.16  End of central directory record:
5892 ***
5893 ***   end of central dir signature    4 bytes  (0x06054b50)
5894 ***   number of this disk             2 bytes
5895 ***   number of the disk with the
5896 ***   start of the central directory  2 bytes
5897 ***   total number of entries in the
5898 ***   central directory on this disk  2 bytes
5899 ***   total number of entries in
5900 ***   the central directory           2 bytes
5901 ***   size of the central directory   4 bytes
5902 ***   offset of start of central
5903 ***   directory with respect to
5904 ***   the starting disk number        4 bytes
5905 ***   .ZIP file comment length        2 bytes
5906 ***   .ZIP file comment       (variable size)
5907 */
5908 typedef struct ZipfileEOCD ZipfileEOCD;
5909 struct ZipfileEOCD {
5910   u16 iDisk;
5911   u16 iFirstDisk;
5912   u16 nEntry;
5913   u16 nEntryTotal;
5914   u32 nSize;
5915   u32 iOffset;
5916 };
5917
5918 /*
5919 *** 4.3.12  Central directory structure:
5920 ***
5921 *** ...
5922 ***
5923 ***   central file header signature   4 bytes  (0x02014b50)
5924 ***   version made by                 2 bytes
5925 ***   version needed to extract       2 bytes
5926 ***   general purpose bit flag        2 bytes
5927 ***   compression method              2 bytes
5928 ***   last mod file time              2 bytes
5929 ***   last mod file date              2 bytes
5930 ***   crc-32                          4 bytes
5931 ***   compressed size                 4 bytes
5932 ***   uncompressed size               4 bytes
5933 ***   file name length                2 bytes
5934 ***   extra field length              2 bytes
5935 ***   file comment length             2 bytes
5936 ***   disk number start               2 bytes
5937 ***   internal file attributes        2 bytes
5938 ***   external file attributes        4 bytes
5939 ***   relative offset of local header 4 bytes
5940 */
5941 typedef struct ZipfileCDS ZipfileCDS;
5942 struct ZipfileCDS {
5943   u16 iVersionMadeBy;
5944   u16 iVersionExtract;
5945   u16 flags;
5946   u16 iCompression;
5947   u16 mTime;
5948   u16 mDate;
5949   u32 crc32;
5950   u32 szCompressed;
5951   u32 szUncompressed;
5952   u16 nFile;
5953   u16 nExtra;
5954   u16 nComment;
5955   u16 iDiskStart;
5956   u16 iInternalAttr;
5957   u32 iExternalAttr;
5958   u32 iOffset;
5959   char *zFile;                    /* Filename (sqlite3_malloc()) */
5960 };
5961
5962 /*
5963 *** 4.3.7  Local file header:
5964 ***
5965 ***   local file header signature     4 bytes  (0x04034b50)
5966 ***   version needed to extract       2 bytes
5967 ***   general purpose bit flag        2 bytes
5968 ***   compression method              2 bytes
5969 ***   last mod file time              2 bytes
5970 ***   last mod file date              2 bytes
5971 ***   crc-32                          4 bytes
5972 ***   compressed size                 4 bytes
5973 ***   uncompressed size               4 bytes
5974 ***   file name length                2 bytes
5975 ***   extra field length              2 bytes
5976 ***   
5977 */
5978 typedef struct ZipfileLFH ZipfileLFH;
5979 struct ZipfileLFH {
5980   u16 iVersionExtract;
5981   u16 flags;
5982   u16 iCompression;
5983   u16 mTime;
5984   u16 mDate;
5985   u32 crc32;
5986   u32 szCompressed;
5987   u32 szUncompressed;
5988   u16 nFile;
5989   u16 nExtra;
5990 };
5991
5992 typedef struct ZipfileEntry ZipfileEntry;
5993 struct ZipfileEntry {
5994   ZipfileCDS cds;            /* Parsed CDS record */
5995   u32 mUnixTime;             /* Modification time, in UNIX format */
5996   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
5997   i64 iDataOff;              /* Offset to data in file (if aData==0) */
5998   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
5999   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
6000 };
6001
6002 /* 
6003 ** Cursor type for zipfile tables.
6004 */
6005 typedef struct ZipfileCsr ZipfileCsr;
6006 struct ZipfileCsr {
6007   sqlite3_vtab_cursor base;  /* Base class - must be first */
6008   i64 iId;                   /* Cursor ID */
6009   u8 bEof;                   /* True when at EOF */
6010   u8 bNoop;                  /* If next xNext() call is no-op */
6011
6012   /* Used outside of write transactions */
6013   FILE *pFile;               /* Zip file */
6014   i64 iNextOff;              /* Offset of next record in central directory */
6015   ZipfileEOCD eocd;          /* Parse of central directory record */
6016
6017   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
6018   ZipfileEntry *pCurrent;    /* Current entry */
6019   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
6020 };
6021
6022 typedef struct ZipfileTab ZipfileTab;
6023 struct ZipfileTab {
6024   sqlite3_vtab base;         /* Base class - must be first */
6025   char *zFile;               /* Zip file this table accesses (may be NULL) */
6026   sqlite3 *db;               /* Host database connection */
6027   u8 *aBuffer;               /* Temporary buffer used for various tasks */
6028
6029   ZipfileCsr *pCsrList;      /* List of cursors */
6030   i64 iNextCsrid;
6031
6032   /* The following are used by write transactions only */
6033   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
6034   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
6035   FILE *pWriteFd;            /* File handle open on zip archive */
6036   i64 szCurrent;             /* Current size of zip archive */
6037   i64 szOrig;                /* Size of archive at start of transaction */
6038 };
6039
6040 /*
6041 ** Set the error message contained in context ctx to the results of
6042 ** vprintf(zFmt, ...).
6043 */
6044 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
6045   char *zMsg = 0;
6046   va_list ap;
6047   va_start(ap, zFmt);
6048   zMsg = sqlite3_vmprintf(zFmt, ap);
6049   sqlite3_result_error(ctx, zMsg, -1);
6050   sqlite3_free(zMsg);
6051   va_end(ap);
6052 }
6053
6054 /*
6055 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
6056 ** is not quoted, do nothing.
6057 */
6058 static void zipfileDequote(char *zIn){
6059   char q = zIn[0];
6060   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
6061     int iIn = 1;
6062     int iOut = 0;
6063     if( q=='[' ) q = ']';
6064     while( ALWAYS(zIn[iIn]) ){
6065       char c = zIn[iIn++];
6066       if( c==q && zIn[iIn++]!=q ) break;
6067       zIn[iOut++] = c;
6068     }
6069     zIn[iOut] = '\0';
6070   }
6071 }
6072
6073 /*
6074 ** Construct a new ZipfileTab virtual table object.
6075 ** 
6076 **   argv[0]   -> module name  ("zipfile")
6077 **   argv[1]   -> database name
6078 **   argv[2]   -> table name
6079 **   argv[...] -> "column name" and other module argument fields.
6080 */
6081 static int zipfileConnect(
6082   sqlite3 *db,
6083   void *pAux,
6084   int argc, const char *const*argv,
6085   sqlite3_vtab **ppVtab,
6086   char **pzErr
6087 ){
6088   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
6089   int nFile = 0;
6090   const char *zFile = 0;
6091   ZipfileTab *pNew = 0;
6092   int rc;
6093
6094   /* If the table name is not "zipfile", require that the argument be
6095   ** specified. This stops zipfile tables from being created as:
6096   **
6097   **   CREATE VIRTUAL TABLE zzz USING zipfile();
6098   **
6099   ** It does not prevent:
6100   **
6101   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
6102   */
6103   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
6104   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
6105     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
6106     return SQLITE_ERROR;
6107   }
6108
6109   if( argc>3 ){
6110     zFile = argv[3];
6111     nFile = (int)strlen(zFile)+1;
6112   }
6113
6114   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
6115   if( rc==SQLITE_OK ){
6116     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
6117     if( pNew==0 ) return SQLITE_NOMEM;
6118     memset(pNew, 0, nByte+nFile);
6119     pNew->db = db;
6120     pNew->aBuffer = (u8*)&pNew[1];
6121     if( zFile ){
6122       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
6123       memcpy(pNew->zFile, zFile, nFile);
6124       zipfileDequote(pNew->zFile);
6125     }
6126   }
6127   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
6128   *ppVtab = (sqlite3_vtab*)pNew;
6129   return rc;
6130 }
6131
6132 /*
6133 ** Free the ZipfileEntry structure indicated by the only argument.
6134 */
6135 static void zipfileEntryFree(ZipfileEntry *p){
6136   if( p ){
6137     sqlite3_free(p->cds.zFile);
6138     sqlite3_free(p);
6139   }
6140 }
6141
6142 /*
6143 ** Release resources that should be freed at the end of a write 
6144 ** transaction.
6145 */
6146 static void zipfileCleanupTransaction(ZipfileTab *pTab){
6147   ZipfileEntry *pEntry;
6148   ZipfileEntry *pNext;
6149
6150   if( pTab->pWriteFd ){
6151     fclose(pTab->pWriteFd);
6152     pTab->pWriteFd = 0;
6153   }
6154   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
6155     pNext = pEntry->pNext;
6156     zipfileEntryFree(pEntry);
6157   }
6158   pTab->pFirstEntry = 0;
6159   pTab->pLastEntry = 0;
6160   pTab->szCurrent = 0;
6161   pTab->szOrig = 0;
6162 }
6163
6164 /*
6165 ** This method is the destructor for zipfile vtab objects.
6166 */
6167 static int zipfileDisconnect(sqlite3_vtab *pVtab){
6168   zipfileCleanupTransaction((ZipfileTab*)pVtab);
6169   sqlite3_free(pVtab);
6170   return SQLITE_OK;
6171 }
6172
6173 /*
6174 ** Constructor for a new ZipfileCsr object.
6175 */
6176 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
6177   ZipfileTab *pTab = (ZipfileTab*)p;
6178   ZipfileCsr *pCsr;
6179   pCsr = sqlite3_malloc(sizeof(*pCsr));
6180   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
6181   if( pCsr==0 ){
6182     return SQLITE_NOMEM;
6183   }
6184   memset(pCsr, 0, sizeof(*pCsr));
6185   pCsr->iId = ++pTab->iNextCsrid;
6186   pCsr->pCsrNext = pTab->pCsrList;
6187   pTab->pCsrList = pCsr;
6188   return SQLITE_OK;
6189 }
6190
6191 /*
6192 ** Reset a cursor back to the state it was in when first returned
6193 ** by zipfileOpen().
6194 */
6195 static void zipfileResetCursor(ZipfileCsr *pCsr){
6196   ZipfileEntry *p;
6197   ZipfileEntry *pNext;
6198
6199   pCsr->bEof = 0;
6200   if( pCsr->pFile ){
6201     fclose(pCsr->pFile);
6202     pCsr->pFile = 0;
6203     zipfileEntryFree(pCsr->pCurrent);
6204     pCsr->pCurrent = 0;
6205   }
6206
6207   for(p=pCsr->pFreeEntry; p; p=pNext){
6208     pNext = p->pNext;
6209     zipfileEntryFree(p);
6210   }
6211 }
6212
6213 /*
6214 ** Destructor for an ZipfileCsr.
6215 */
6216 static int zipfileClose(sqlite3_vtab_cursor *cur){
6217   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6218   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
6219   ZipfileCsr **pp;
6220   zipfileResetCursor(pCsr);
6221
6222   /* Remove this cursor from the ZipfileTab.pCsrList list. */
6223   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
6224   *pp = pCsr->pCsrNext;
6225
6226   sqlite3_free(pCsr);
6227   return SQLITE_OK;
6228 }
6229
6230 /*
6231 ** Set the error message for the virtual table associated with cursor
6232 ** pCsr to the results of vprintf(zFmt, ...).
6233 */
6234 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
6235   va_list ap;
6236   va_start(ap, zFmt);
6237   sqlite3_free(pTab->base.zErrMsg);
6238   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
6239   va_end(ap);
6240 }
6241 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
6242   va_list ap;
6243   va_start(ap, zFmt);
6244   sqlite3_free(pCsr->base.pVtab->zErrMsg);
6245   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
6246   va_end(ap);
6247 }
6248
6249 /*
6250 ** Read nRead bytes of data from offset iOff of file pFile into buffer
6251 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
6252 ** otherwise. 
6253 **
6254 ** If an error does occur, output variable (*pzErrmsg) may be set to point
6255 ** to an English language error message. It is the responsibility of the
6256 ** caller to eventually free this buffer using
6257 ** sqlite3_free().
6258 */
6259 static int zipfileReadData(
6260   FILE *pFile,                    /* Read from this file */
6261   u8 *aRead,                      /* Read into this buffer */
6262   int nRead,                      /* Number of bytes to read */
6263   i64 iOff,                       /* Offset to read from */
6264   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
6265 ){
6266   size_t n;
6267   fseek(pFile, (long)iOff, SEEK_SET);
6268   n = fread(aRead, 1, nRead, pFile);
6269   if( (int)n!=nRead ){
6270     *pzErrmsg = sqlite3_mprintf("error in fread()");
6271     return SQLITE_ERROR;
6272   }
6273   return SQLITE_OK;
6274 }
6275
6276 static int zipfileAppendData(
6277   ZipfileTab *pTab,
6278   const u8 *aWrite,
6279   int nWrite
6280 ){
6281   if( nWrite>0 ){
6282     size_t n = nWrite;
6283     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
6284     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
6285     if( (int)n!=nWrite ){
6286       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
6287       return SQLITE_ERROR;
6288     }
6289     pTab->szCurrent += nWrite;
6290   }
6291   return SQLITE_OK;
6292 }
6293
6294 /*
6295 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
6296 */
6297 static u16 zipfileGetU16(const u8 *aBuf){
6298   return (aBuf[1] << 8) + aBuf[0];
6299 }
6300
6301 /*
6302 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
6303 */
6304 static u32 zipfileGetU32(const u8 *aBuf){
6305   return ((u32)(aBuf[3]) << 24)
6306        + ((u32)(aBuf[2]) << 16)
6307        + ((u32)(aBuf[1]) <<  8)
6308        + ((u32)(aBuf[0]) <<  0);
6309 }
6310
6311 /*
6312 ** Write a 16-bit little endiate integer into buffer aBuf.
6313 */
6314 static void zipfilePutU16(u8 *aBuf, u16 val){
6315   aBuf[0] = val & 0xFF;
6316   aBuf[1] = (val>>8) & 0xFF;
6317 }
6318
6319 /*
6320 ** Write a 32-bit little endiate integer into buffer aBuf.
6321 */
6322 static void zipfilePutU32(u8 *aBuf, u32 val){
6323   aBuf[0] = val & 0xFF;
6324   aBuf[1] = (val>>8) & 0xFF;
6325   aBuf[2] = (val>>16) & 0xFF;
6326   aBuf[3] = (val>>24) & 0xFF;
6327 }
6328
6329 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
6330 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
6331
6332 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
6333 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
6334
6335 /*
6336 ** Magic numbers used to read CDS records.
6337 */
6338 #define ZIPFILE_CDS_NFILE_OFF        28
6339 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
6340
6341 /*
6342 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
6343 ** if the record is not well-formed, or SQLITE_OK otherwise.
6344 */
6345 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
6346   u8 *aRead = aBuf;
6347   u32 sig = zipfileRead32(aRead);
6348   int rc = SQLITE_OK;
6349   if( sig!=ZIPFILE_SIGNATURE_CDS ){
6350     rc = SQLITE_ERROR;
6351   }else{
6352     pCDS->iVersionMadeBy = zipfileRead16(aRead);
6353     pCDS->iVersionExtract = zipfileRead16(aRead);
6354     pCDS->flags = zipfileRead16(aRead);
6355     pCDS->iCompression = zipfileRead16(aRead);
6356     pCDS->mTime = zipfileRead16(aRead);
6357     pCDS->mDate = zipfileRead16(aRead);
6358     pCDS->crc32 = zipfileRead32(aRead);
6359     pCDS->szCompressed = zipfileRead32(aRead);
6360     pCDS->szUncompressed = zipfileRead32(aRead);
6361     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
6362     pCDS->nFile = zipfileRead16(aRead);
6363     pCDS->nExtra = zipfileRead16(aRead);
6364     pCDS->nComment = zipfileRead16(aRead);
6365     pCDS->iDiskStart = zipfileRead16(aRead);
6366     pCDS->iInternalAttr = zipfileRead16(aRead);
6367     pCDS->iExternalAttr = zipfileRead32(aRead);
6368     pCDS->iOffset = zipfileRead32(aRead);
6369     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
6370   }
6371
6372   return rc;
6373 }
6374
6375 /*
6376 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
6377 ** if the record is not well-formed, or SQLITE_OK otherwise.
6378 */
6379 static int zipfileReadLFH(
6380   u8 *aBuffer,
6381   ZipfileLFH *pLFH
6382 ){
6383   u8 *aRead = aBuffer;
6384   int rc = SQLITE_OK;
6385
6386   u32 sig = zipfileRead32(aRead);
6387   if( sig!=ZIPFILE_SIGNATURE_LFH ){
6388     rc = SQLITE_ERROR;
6389   }else{
6390     pLFH->iVersionExtract = zipfileRead16(aRead);
6391     pLFH->flags = zipfileRead16(aRead);
6392     pLFH->iCompression = zipfileRead16(aRead);
6393     pLFH->mTime = zipfileRead16(aRead);
6394     pLFH->mDate = zipfileRead16(aRead);
6395     pLFH->crc32 = zipfileRead32(aRead);
6396     pLFH->szCompressed = zipfileRead32(aRead);
6397     pLFH->szUncompressed = zipfileRead32(aRead);
6398     pLFH->nFile = zipfileRead16(aRead);
6399     pLFH->nExtra = zipfileRead16(aRead);
6400   }
6401   return rc;
6402 }
6403
6404
6405 /*
6406 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
6407 ** Scan through this buffer to find an "extra-timestamp" field. If one
6408 ** exists, extract the 32-bit modification-timestamp from it and store
6409 ** the value in output parameter *pmTime.
6410 **
6411 ** Zero is returned if no extra-timestamp record could be found (and so
6412 ** *pmTime is left unchanged), or non-zero otherwise.
6413 **
6414 ** The general format of an extra field is:
6415 **
6416 **   Header ID    2 bytes
6417 **   Data Size    2 bytes
6418 **   Data         N bytes
6419 */
6420 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
6421   int ret = 0;
6422   u8 *p = aExtra;
6423   u8 *pEnd = &aExtra[nExtra];
6424
6425   while( p<pEnd ){
6426     u16 id = zipfileRead16(p);
6427     u16 nByte = zipfileRead16(p);
6428
6429     switch( id ){
6430       case ZIPFILE_EXTRA_TIMESTAMP: {
6431         u8 b = p[0];
6432         if( b & 0x01 ){     /* 0x01 -> modtime is present */
6433           *pmTime = zipfileGetU32(&p[1]);
6434           ret = 1;
6435         }
6436         break;
6437       }
6438     }
6439
6440     p += nByte;
6441   }
6442   return ret;
6443 }
6444
6445 /*
6446 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
6447 ** fields of the CDS structure passed as the only argument to a 32-bit
6448 ** UNIX seconds-since-the-epoch timestamp. Return the result.
6449 **
6450 ** "Standard" MS-DOS time format:
6451 **
6452 **   File modification time:
6453 **     Bits 00-04: seconds divided by 2
6454 **     Bits 05-10: minute
6455 **     Bits 11-15: hour
6456 **   File modification date:
6457 **     Bits 00-04: day
6458 **     Bits 05-08: month (1-12)
6459 **     Bits 09-15: years from 1980 
6460 **
6461 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
6462 */
6463 static u32 zipfileMtime(ZipfileCDS *pCDS){
6464   int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
6465   int M = ((pCDS->mDate >> 5) & 0x0F);
6466   int D = (pCDS->mDate & 0x1F);
6467   int B = -13;
6468
6469   int sec = (pCDS->mTime & 0x1F)*2;
6470   int min = (pCDS->mTime >> 5) & 0x3F;
6471   int hr = (pCDS->mTime >> 11) & 0x1F;
6472   i64 JD;
6473
6474   /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
6475
6476   /* Calculate the JD in seconds for noon on the day in question */
6477   if( M<3 ){
6478     Y = Y-1;
6479     M = M+12;
6480   }
6481   JD = (i64)(24*60*60) * (
6482       (int)(365.25 * (Y + 4716))
6483     + (int)(30.6001 * (M + 1))
6484     + D + B - 1524
6485   );
6486
6487   /* Correct the JD for the time within the day */
6488   JD += (hr-12) * 3600 + min * 60 + sec;
6489
6490   /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
6491   return (u32)(JD - (i64)(24405875) * 24*60*6);
6492 }
6493
6494 /*
6495 ** The opposite of zipfileMtime(). This function populates the mTime and
6496 ** mDate fields of the CDS structure passed as the first argument according
6497 ** to the UNIX timestamp value passed as the second.
6498 */
6499 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
6500   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
6501   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
6502
6503   int A, B, C, D, E;
6504   int yr, mon, day;
6505   int hr, min, sec;
6506
6507   A = (int)((JD - 1867216.25)/36524.25);
6508   A = (int)(JD + 1 + A - (A/4));
6509   B = A + 1524;
6510   C = (int)((B - 122.1)/365.25);
6511   D = (36525*(C&32767))/100;
6512   E = (int)((B-D)/30.6001);
6513
6514   day = B - D - (int)(30.6001*E);
6515   mon = (E<14 ? E-1 : E-13);
6516   yr = mon>2 ? C-4716 : C-4715;
6517
6518   hr = (mUnixTime % (24*60*60)) / (60*60);
6519   min = (mUnixTime % (60*60)) / 60;
6520   sec = (mUnixTime % 60);
6521
6522   if( yr>=1980 ){
6523     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
6524     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
6525   }else{
6526     pCds->mDate = pCds->mTime = 0;
6527   }
6528
6529   assert( mUnixTime<315507600 
6530        || mUnixTime==zipfileMtime(pCds) 
6531        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) 
6532        /* || (mUnixTime % 2) */
6533   );
6534 }
6535
6536 /*
6537 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
6538 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
6539 ** then pFile is a file-handle open on a zip file. In either case, this
6540 ** function creates a ZipfileEntry object based on the zip archive entry
6541 ** for which the CDS record is at offset iOff.
6542 **
6543 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
6544 ** the new object. Otherwise, an SQLite error code is returned and the
6545 ** final value of (*ppEntry) undefined.
6546 */
6547 static int zipfileGetEntry(
6548   ZipfileTab *pTab,               /* Store any error message here */
6549   const u8 *aBlob,                /* Pointer to in-memory file image */
6550   int nBlob,                      /* Size of aBlob[] in bytes */
6551   FILE *pFile,                    /* If aBlob==0, read from this file */
6552   i64 iOff,                       /* Offset of CDS record */
6553   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
6554 ){
6555   u8 *aRead;
6556   char **pzErr = &pTab->base.zErrMsg;
6557   int rc = SQLITE_OK;
6558
6559   if( aBlob==0 ){
6560     aRead = pTab->aBuffer;
6561     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
6562   }else{
6563     aRead = (u8*)&aBlob[iOff];
6564   }
6565
6566   if( rc==SQLITE_OK ){
6567     sqlite3_int64 nAlloc;
6568     ZipfileEntry *pNew;
6569
6570     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
6571     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
6572     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
6573
6574     nAlloc = sizeof(ZipfileEntry) + nExtra;
6575     if( aBlob ){
6576       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
6577     }
6578
6579     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
6580     if( pNew==0 ){
6581       rc = SQLITE_NOMEM;
6582     }else{
6583       memset(pNew, 0, sizeof(ZipfileEntry));
6584       rc = zipfileReadCDS(aRead, &pNew->cds);
6585       if( rc!=SQLITE_OK ){
6586         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
6587       }else if( aBlob==0 ){
6588         rc = zipfileReadData(
6589             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
6590         );
6591       }else{
6592         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
6593       }
6594     }
6595
6596     if( rc==SQLITE_OK ){
6597       u32 *pt = &pNew->mUnixTime;
6598       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); 
6599       pNew->aExtra = (u8*)&pNew[1];
6600       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
6601       if( pNew->cds.zFile==0 ){
6602         rc = SQLITE_NOMEM;
6603       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
6604         pNew->mUnixTime = zipfileMtime(&pNew->cds);
6605       }
6606     }
6607
6608     if( rc==SQLITE_OK ){
6609       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
6610       ZipfileLFH lfh;
6611       if( pFile ){
6612         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
6613       }else{
6614         aRead = (u8*)&aBlob[pNew->cds.iOffset];
6615       }
6616
6617       rc = zipfileReadLFH(aRead, &lfh);
6618       if( rc==SQLITE_OK ){
6619         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
6620         pNew->iDataOff += lfh.nFile + lfh.nExtra;
6621         if( aBlob && pNew->cds.szCompressed ){
6622           pNew->aData = &pNew->aExtra[nExtra];
6623           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
6624         }
6625       }else{
6626         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", 
6627             (int)pNew->cds.iOffset
6628         );
6629       }
6630     }
6631
6632     if( rc!=SQLITE_OK ){
6633       zipfileEntryFree(pNew);
6634     }else{
6635       *ppEntry = pNew;
6636     }
6637   }
6638
6639   return rc;
6640 }
6641
6642 /*
6643 ** Advance an ZipfileCsr to its next row of output.
6644 */
6645 static int zipfileNext(sqlite3_vtab_cursor *cur){
6646   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6647   int rc = SQLITE_OK;
6648
6649   if( pCsr->pFile ){
6650     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
6651     zipfileEntryFree(pCsr->pCurrent);
6652     pCsr->pCurrent = 0;
6653     if( pCsr->iNextOff>=iEof ){
6654       pCsr->bEof = 1;
6655     }else{
6656       ZipfileEntry *p = 0;
6657       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
6658       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
6659       if( rc==SQLITE_OK ){
6660         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
6661         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
6662       }
6663       pCsr->pCurrent = p;
6664     }
6665   }else{
6666     if( !pCsr->bNoop ){
6667       pCsr->pCurrent = pCsr->pCurrent->pNext;
6668     }
6669     if( pCsr->pCurrent==0 ){
6670       pCsr->bEof = 1;
6671     }
6672   }
6673
6674   pCsr->bNoop = 0;
6675   return rc;
6676 }
6677
6678 static void zipfileFree(void *p) { 
6679   sqlite3_free(p); 
6680 }
6681
6682 /*
6683 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
6684 ** size is nOut bytes. This function uncompresses the data and sets the
6685 ** return value in context pCtx to the result (a blob).
6686 **
6687 ** If an error occurs, an error code is left in pCtx instead.
6688 */
6689 static void zipfileInflate(
6690   sqlite3_context *pCtx,          /* Store result here */
6691   const u8 *aIn,                  /* Compressed data */
6692   int nIn,                        /* Size of buffer aIn[] in bytes */
6693   int nOut                        /* Expected output size */
6694 ){
6695   u8 *aRes = sqlite3_malloc(nOut);
6696   if( aRes==0 ){
6697     sqlite3_result_error_nomem(pCtx);
6698   }else{
6699     int err;
6700     z_stream str;
6701     memset(&str, 0, sizeof(str));
6702
6703     str.next_in = (Byte*)aIn;
6704     str.avail_in = nIn;
6705     str.next_out = (Byte*)aRes;
6706     str.avail_out = nOut;
6707
6708     err = inflateInit2(&str, -15);
6709     if( err!=Z_OK ){
6710       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
6711     }else{
6712       err = inflate(&str, Z_NO_FLUSH);
6713       if( err!=Z_STREAM_END ){
6714         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
6715       }else{
6716         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
6717         aRes = 0;
6718       }
6719     }
6720     sqlite3_free(aRes);
6721     inflateEnd(&str);
6722   }
6723 }
6724
6725 /*
6726 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
6727 ** compresses it and sets (*ppOut) to point to a buffer containing the
6728 ** compressed data. The caller is responsible for eventually calling
6729 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) 
6730 ** is set to the size of buffer (*ppOut) in bytes.
6731 **
6732 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
6733 ** code is returned and an error message left in virtual-table handle
6734 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
6735 ** case.
6736 */
6737 static int zipfileDeflate(
6738   const u8 *aIn, int nIn,         /* Input */
6739   u8 **ppOut, int *pnOut,         /* Output */
6740   char **pzErr                    /* OUT: Error message */
6741 ){
6742   int rc = SQLITE_OK;
6743   sqlite3_int64 nAlloc;
6744   z_stream str;
6745   u8 *aOut;
6746
6747   memset(&str, 0, sizeof(str));
6748   str.next_in = (Bytef*)aIn;
6749   str.avail_in = nIn;
6750   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
6751
6752   nAlloc = deflateBound(&str, nIn);
6753   aOut = (u8*)sqlite3_malloc64(nAlloc);
6754   if( aOut==0 ){
6755     rc = SQLITE_NOMEM;
6756   }else{
6757     int res;
6758     str.next_out = aOut;
6759     str.avail_out = nAlloc;
6760     res = deflate(&str, Z_FINISH);
6761     if( res==Z_STREAM_END ){
6762       *ppOut = aOut;
6763       *pnOut = (int)str.total_out;
6764     }else{
6765       sqlite3_free(aOut);
6766       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
6767       rc = SQLITE_ERROR;
6768     }
6769     deflateEnd(&str);
6770   }
6771
6772   return rc;
6773 }
6774
6775
6776 /*
6777 ** Return values of columns for the row at which the series_cursor
6778 ** is currently pointing.
6779 */
6780 static int zipfileColumn(
6781   sqlite3_vtab_cursor *cur,   /* The cursor */
6782   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6783   int i                       /* Which column to return */
6784 ){
6785   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6786   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
6787   int rc = SQLITE_OK;
6788   switch( i ){
6789     case 0:   /* name */
6790       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
6791       break;
6792     case 1:   /* mode */
6793       /* TODO: Whether or not the following is correct surely depends on
6794       ** the platform on which the archive was created.  */
6795       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
6796       break;
6797     case 2: { /* mtime */
6798       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
6799       break;
6800     }
6801     case 3: { /* sz */
6802       if( sqlite3_vtab_nochange(ctx)==0 ){
6803         sqlite3_result_int64(ctx, pCDS->szUncompressed);
6804       }
6805       break;
6806     }
6807     case 4:   /* rawdata */
6808       if( sqlite3_vtab_nochange(ctx) ) break;
6809     case 5: { /* data */
6810       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
6811         int sz = pCDS->szCompressed;
6812         int szFinal = pCDS->szUncompressed;
6813         if( szFinal>0 ){
6814           u8 *aBuf;
6815           u8 *aFree = 0;
6816           if( pCsr->pCurrent->aData ){
6817             aBuf = pCsr->pCurrent->aData;
6818           }else{
6819             aBuf = aFree = sqlite3_malloc64(sz);
6820             if( aBuf==0 ){
6821               rc = SQLITE_NOMEM;
6822             }else{
6823               FILE *pFile = pCsr->pFile;
6824               if( pFile==0 ){
6825                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
6826               }
6827               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
6828                   &pCsr->base.pVtab->zErrMsg
6829               );
6830             }
6831           }
6832           if( rc==SQLITE_OK ){
6833             if( i==5 && pCDS->iCompression ){
6834               zipfileInflate(ctx, aBuf, sz, szFinal);
6835             }else{
6836               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
6837             }
6838           }
6839           sqlite3_free(aFree);
6840         }else{
6841           /* Figure out if this is a directory or a zero-sized file. Consider
6842           ** it to be a directory either if the mode suggests so, or if
6843           ** the final character in the name is '/'.  */
6844           u32 mode = pCDS->iExternalAttr >> 16;
6845           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
6846             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
6847           }
6848         }
6849       }
6850       break;
6851     }
6852     case 6:   /* method */
6853       sqlite3_result_int(ctx, pCDS->iCompression);
6854       break;
6855     default:  /* z */
6856       assert( i==7 );
6857       sqlite3_result_int64(ctx, pCsr->iId);
6858       break;
6859   }
6860
6861   return rc;
6862 }
6863
6864 /*
6865 ** Return TRUE if the cursor is at EOF.
6866 */
6867 static int zipfileEof(sqlite3_vtab_cursor *cur){
6868   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
6869   return pCsr->bEof;
6870 }
6871
6872 /*
6873 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
6874 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
6875 ** is guaranteed to be a file-handle open on a zip file.
6876 **
6877 ** This function attempts to locate the EOCD record within the zip archive
6878 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
6879 ** returned if successful. Otherwise, an SQLite error code is returned and
6880 ** an English language error message may be left in virtual-table pTab.
6881 */
6882 static int zipfileReadEOCD(
6883   ZipfileTab *pTab,               /* Return errors here */
6884   const u8 *aBlob,                /* Pointer to in-memory file image */
6885   int nBlob,                      /* Size of aBlob[] in bytes */
6886   FILE *pFile,                    /* Read from this file if aBlob==0 */
6887   ZipfileEOCD *pEOCD              /* Object to populate */
6888 ){
6889   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
6890   int nRead;                      /* Bytes to read from file */
6891   int rc = SQLITE_OK;
6892
6893   if( aBlob==0 ){
6894     i64 iOff;                     /* Offset to read from */
6895     i64 szFile;                   /* Total size of file in bytes */
6896     fseek(pFile, 0, SEEK_END);
6897     szFile = (i64)ftell(pFile);
6898     if( szFile==0 ){
6899       memset(pEOCD, 0, sizeof(ZipfileEOCD));
6900       return SQLITE_OK;
6901     }
6902     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
6903     iOff = szFile - nRead;
6904     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
6905   }else{
6906     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
6907     aRead = (u8*)&aBlob[nBlob-nRead];
6908   }
6909
6910   if( rc==SQLITE_OK ){
6911     int i;
6912
6913     /* Scan backwards looking for the signature bytes */
6914     for(i=nRead-20; i>=0; i--){
6915       if( aRead[i]==0x50 && aRead[i+1]==0x4b 
6916        && aRead[i+2]==0x05 && aRead[i+3]==0x06 
6917       ){
6918         break;
6919       }
6920     }
6921     if( i<0 ){
6922       pTab->base.zErrMsg = sqlite3_mprintf(
6923           "cannot find end of central directory record"
6924       );
6925       return SQLITE_ERROR;
6926     }
6927
6928     aRead += i+4;
6929     pEOCD->iDisk = zipfileRead16(aRead);
6930     pEOCD->iFirstDisk = zipfileRead16(aRead);
6931     pEOCD->nEntry = zipfileRead16(aRead);
6932     pEOCD->nEntryTotal = zipfileRead16(aRead);
6933     pEOCD->nSize = zipfileRead32(aRead);
6934     pEOCD->iOffset = zipfileRead32(aRead);
6935   }
6936
6937   return rc;
6938 }
6939
6940 /*
6941 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry 
6942 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
6943 ** to the end of the list. Otherwise, it is added to the list immediately
6944 ** before pBefore (which is guaranteed to be a part of said list).
6945 */
6946 static void zipfileAddEntry(
6947   ZipfileTab *pTab, 
6948   ZipfileEntry *pBefore, 
6949   ZipfileEntry *pNew
6950 ){
6951   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
6952   assert( pNew->pNext==0 );
6953   if( pBefore==0 ){
6954     if( pTab->pFirstEntry==0 ){
6955       pTab->pFirstEntry = pTab->pLastEntry = pNew;
6956     }else{
6957       assert( pTab->pLastEntry->pNext==0 );
6958       pTab->pLastEntry->pNext = pNew;
6959       pTab->pLastEntry = pNew;
6960     }
6961   }else{
6962     ZipfileEntry **pp;
6963     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
6964     pNew->pNext = pBefore;
6965     *pp = pNew;
6966   }
6967 }
6968
6969 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
6970   ZipfileEOCD eocd;
6971   int rc;
6972   int i;
6973   i64 iOff;
6974
6975   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
6976   iOff = eocd.iOffset;
6977   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
6978     ZipfileEntry *pNew = 0;
6979     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
6980
6981     if( rc==SQLITE_OK ){
6982       zipfileAddEntry(pTab, 0, pNew);
6983       iOff += ZIPFILE_CDS_FIXED_SZ;
6984       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
6985     }
6986   }
6987   return rc;
6988 }
6989
6990 /*
6991 ** xFilter callback.
6992 */
6993 static int zipfileFilter(
6994   sqlite3_vtab_cursor *cur, 
6995   int idxNum, const char *idxStr,
6996   int argc, sqlite3_value **argv
6997 ){
6998   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
6999   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7000   const char *zFile = 0;          /* Zip file to scan */
7001   int rc = SQLITE_OK;             /* Return Code */
7002   int bInMemory = 0;              /* True for an in-memory zipfile */
7003
7004   zipfileResetCursor(pCsr);
7005
7006   if( pTab->zFile ){
7007     zFile = pTab->zFile;
7008   }else if( idxNum==0 ){
7009     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
7010     return SQLITE_ERROR;
7011   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
7012     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
7013     int nBlob = sqlite3_value_bytes(argv[0]);
7014     assert( pTab->pFirstEntry==0 );
7015     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
7016     pCsr->pFreeEntry = pTab->pFirstEntry;
7017     pTab->pFirstEntry = pTab->pLastEntry = 0;
7018     if( rc!=SQLITE_OK ) return rc;
7019     bInMemory = 1;
7020   }else{
7021     zFile = (const char*)sqlite3_value_text(argv[0]);
7022   }
7023
7024   if( 0==pTab->pWriteFd && 0==bInMemory ){
7025     pCsr->pFile = fopen(zFile, "rb");
7026     if( pCsr->pFile==0 ){
7027       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
7028       rc = SQLITE_ERROR;
7029     }else{
7030       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
7031       if( rc==SQLITE_OK ){
7032         if( pCsr->eocd.nEntry==0 ){
7033           pCsr->bEof = 1;
7034         }else{
7035           pCsr->iNextOff = pCsr->eocd.iOffset;
7036           rc = zipfileNext(cur);
7037         }
7038       }
7039     }
7040   }else{
7041     pCsr->bNoop = 1;
7042     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
7043     rc = zipfileNext(cur);
7044   }
7045
7046   return rc;
7047 }
7048
7049 /*
7050 ** xBestIndex callback.
7051 */
7052 static int zipfileBestIndex(
7053   sqlite3_vtab *tab,
7054   sqlite3_index_info *pIdxInfo
7055 ){
7056   int i;
7057   int idx = -1;
7058   int unusable = 0;
7059
7060   for(i=0; i<pIdxInfo->nConstraint; i++){
7061     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
7062     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
7063     if( pCons->usable==0 ){
7064       unusable = 1;
7065     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
7066       idx = i;
7067     }
7068   }
7069   pIdxInfo->estimatedCost = 1000.0;
7070   if( idx>=0 ){
7071     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
7072     pIdxInfo->aConstraintUsage[idx].omit = 1;
7073     pIdxInfo->idxNum = 1;
7074   }else if( unusable ){
7075     return SQLITE_CONSTRAINT;
7076   }
7077   return SQLITE_OK;
7078 }
7079
7080 static ZipfileEntry *zipfileNewEntry(const char *zPath){
7081   ZipfileEntry *pNew;
7082   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
7083   if( pNew ){
7084     memset(pNew, 0, sizeof(ZipfileEntry));
7085     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
7086     if( pNew->cds.zFile==0 ){
7087       sqlite3_free(pNew);
7088       pNew = 0;
7089     }
7090   }
7091   return pNew;
7092 }
7093
7094 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
7095   ZipfileCDS *pCds = &pEntry->cds;
7096   u8 *a = aBuf;
7097
7098   pCds->nExtra = 9;
7099
7100   /* Write the LFH itself */
7101   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
7102   zipfileWrite16(a, pCds->iVersionExtract);
7103   zipfileWrite16(a, pCds->flags);
7104   zipfileWrite16(a, pCds->iCompression);
7105   zipfileWrite16(a, pCds->mTime);
7106   zipfileWrite16(a, pCds->mDate);
7107   zipfileWrite32(a, pCds->crc32);
7108   zipfileWrite32(a, pCds->szCompressed);
7109   zipfileWrite32(a, pCds->szUncompressed);
7110   zipfileWrite16(a, (u16)pCds->nFile);
7111   zipfileWrite16(a, pCds->nExtra);
7112   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
7113
7114   /* Add the file name */
7115   memcpy(a, pCds->zFile, (int)pCds->nFile);
7116   a += (int)pCds->nFile;
7117
7118   /* The "extra" data */
7119   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
7120   zipfileWrite16(a, 5);
7121   *a++ = 0x01;
7122   zipfileWrite32(a, pEntry->mUnixTime);
7123
7124   return a-aBuf;
7125 }
7126
7127 static int zipfileAppendEntry(
7128   ZipfileTab *pTab,
7129   ZipfileEntry *pEntry,
7130   const u8 *pData,
7131   int nData
7132 ){
7133   u8 *aBuf = pTab->aBuffer;
7134   int nBuf;
7135   int rc;
7136
7137   nBuf = zipfileSerializeLFH(pEntry, aBuf);
7138   rc = zipfileAppendData(pTab, aBuf, nBuf);
7139   if( rc==SQLITE_OK ){
7140     pEntry->iDataOff = pTab->szCurrent;
7141     rc = zipfileAppendData(pTab, pData, nData);
7142   }
7143
7144   return rc;
7145 }
7146
7147 static int zipfileGetMode(
7148   sqlite3_value *pVal, 
7149   int bIsDir,                     /* If true, default to directory */
7150   u32 *pMode,                     /* OUT: Mode value */
7151   char **pzErr                    /* OUT: Error message */
7152 ){
7153   const char *z = (const char*)sqlite3_value_text(pVal);
7154   u32 mode = 0;
7155   if( z==0 ){
7156     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
7157   }else if( z[0]>='0' && z[0]<='9' ){
7158     mode = (unsigned int)sqlite3_value_int(pVal);
7159   }else{
7160     const char zTemplate[11] = "-rwxrwxrwx";
7161     int i;
7162     if( strlen(z)!=10 ) goto parse_error;
7163     switch( z[0] ){
7164       case '-': mode |= S_IFREG; break;
7165       case 'd': mode |= S_IFDIR; break;
7166       case 'l': mode |= S_IFLNK; break;
7167       default: goto parse_error;
7168     }
7169     for(i=1; i<10; i++){
7170       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
7171       else if( z[i]!='-' ) goto parse_error;
7172     }
7173   }
7174   if( ((mode & S_IFDIR)==0)==bIsDir ){
7175     /* The "mode" attribute is a directory, but data has been specified.
7176     ** Or vice-versa - no data but "mode" is a file or symlink.  */
7177     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
7178     return SQLITE_CONSTRAINT;
7179   }
7180   *pMode = mode;
7181   return SQLITE_OK;
7182
7183  parse_error:
7184   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
7185   return SQLITE_ERROR;
7186 }
7187
7188 /*
7189 ** Both (const char*) arguments point to nul-terminated strings. Argument
7190 ** nB is the value of strlen(zB). This function returns 0 if the strings are
7191 ** identical, ignoring any trailing '/' character in either path.  */
7192 static int zipfileComparePath(const char *zA, const char *zB, int nB){
7193   int nA = (int)strlen(zA);
7194   if( nA>0 && zA[nA-1]=='/' ) nA--;
7195   if( nB>0 && zB[nB-1]=='/' ) nB--;
7196   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
7197   return 1;
7198 }
7199
7200 static int zipfileBegin(sqlite3_vtab *pVtab){
7201   ZipfileTab *pTab = (ZipfileTab*)pVtab;
7202   int rc = SQLITE_OK;
7203
7204   assert( pTab->pWriteFd==0 );
7205   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
7206     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
7207     return SQLITE_ERROR;
7208   }
7209
7210   /* Open a write fd on the file. Also load the entire central directory
7211   ** structure into memory. During the transaction any new file data is 
7212   ** appended to the archive file, but the central directory is accumulated
7213   ** in main-memory until the transaction is committed.  */
7214   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
7215   if( pTab->pWriteFd==0 ){
7216     pTab->base.zErrMsg = sqlite3_mprintf(
7217         "zipfile: failed to open file %s for writing", pTab->zFile
7218         );
7219     rc = SQLITE_ERROR;
7220   }else{
7221     fseek(pTab->pWriteFd, 0, SEEK_END);
7222     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
7223     rc = zipfileLoadDirectory(pTab, 0, 0);
7224   }
7225
7226   if( rc!=SQLITE_OK ){
7227     zipfileCleanupTransaction(pTab);
7228   }
7229
7230   return rc;
7231 }
7232
7233 /*
7234 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
7235 ** time(2)).
7236 */
7237 static u32 zipfileTime(void){
7238   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
7239   u32 ret;
7240   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
7241     i64 ms;
7242     pVfs->xCurrentTimeInt64(pVfs, &ms);
7243     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
7244   }else{
7245     double day;
7246     pVfs->xCurrentTime(pVfs, &day);
7247     ret = (u32)((day - 2440587.5) * 86400);
7248   }
7249   return ret;
7250 }
7251
7252 /*
7253 ** Return a 32-bit timestamp in UNIX epoch format.
7254 **
7255 ** If the value passed as the only argument is either NULL or an SQL NULL,
7256 ** return the current time. Otherwise, return the value stored in (*pVal)
7257 ** cast to a 32-bit unsigned integer.
7258 */
7259 static u32 zipfileGetTime(sqlite3_value *pVal){
7260   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
7261     return zipfileTime();
7262   }
7263   return (u32)sqlite3_value_int64(pVal);
7264 }
7265
7266 /*
7267 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
7268 ** linked list.  Remove it from the list and free the object.
7269 */
7270 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
7271   if( pOld ){
7272     ZipfileEntry **pp;
7273     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
7274     *pp = (*pp)->pNext;
7275     zipfileEntryFree(pOld);
7276   }
7277 }
7278
7279 /*
7280 ** xUpdate method.
7281 */
7282 static int zipfileUpdate(
7283   sqlite3_vtab *pVtab, 
7284   int nVal, 
7285   sqlite3_value **apVal, 
7286   sqlite_int64 *pRowid
7287 ){
7288   ZipfileTab *pTab = (ZipfileTab*)pVtab;
7289   int rc = SQLITE_OK;             /* Return Code */
7290   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
7291
7292   u32 mode = 0;                   /* Mode for new entry */
7293   u32 mTime = 0;                  /* Modification time for new entry */
7294   i64 sz = 0;                     /* Uncompressed size */
7295   const char *zPath = 0;          /* Path for new entry */
7296   int nPath = 0;                  /* strlen(zPath) */
7297   const u8 *pData = 0;            /* Pointer to buffer containing content */
7298   int nData = 0;                  /* Size of pData buffer in bytes */
7299   int iMethod = 0;                /* Compression method for new entry */
7300   u8 *pFree = 0;                  /* Free this */
7301   char *zFree = 0;                /* Also free this */
7302   ZipfileEntry *pOld = 0;
7303   ZipfileEntry *pOld2 = 0;
7304   int bUpdate = 0;                /* True for an update that modifies "name" */
7305   int bIsDir = 0;
7306   u32 iCrc32 = 0;
7307
7308   if( pTab->pWriteFd==0 ){
7309     rc = zipfileBegin(pVtab);
7310     if( rc!=SQLITE_OK ) return rc;
7311   }
7312
7313   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
7314   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
7315     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
7316     int nDelete = (int)strlen(zDelete);
7317     if( nVal>1 ){
7318       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
7319       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
7320         bUpdate = 1;
7321       }
7322     }
7323     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
7324       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
7325         break;
7326       }
7327       assert( pOld->pNext );
7328     }
7329   }
7330
7331   if( nVal>1 ){
7332     /* Check that "sz" and "rawdata" are both NULL: */
7333     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
7334       zipfileTableErr(pTab, "sz must be NULL");
7335       rc = SQLITE_CONSTRAINT;
7336     }
7337     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
7338       zipfileTableErr(pTab, "rawdata must be NULL"); 
7339       rc = SQLITE_CONSTRAINT;
7340     }
7341
7342     if( rc==SQLITE_OK ){
7343       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
7344         /* data=NULL. A directory */
7345         bIsDir = 1;
7346       }else{
7347         /* Value specified for "data", and possibly "method". This must be
7348         ** a regular file or a symlink. */
7349         const u8 *aIn = sqlite3_value_blob(apVal[7]);
7350         int nIn = sqlite3_value_bytes(apVal[7]);
7351         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
7352
7353         iMethod = sqlite3_value_int(apVal[8]);
7354         sz = nIn;
7355         pData = aIn;
7356         nData = nIn;
7357         if( iMethod!=0 && iMethod!=8 ){
7358           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
7359           rc = SQLITE_CONSTRAINT;
7360         }else{
7361           if( bAuto || iMethod ){
7362             int nCmp;
7363             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
7364             if( rc==SQLITE_OK ){
7365               if( iMethod || nCmp<nIn ){
7366                 iMethod = 8;
7367                 pData = pFree;
7368                 nData = nCmp;
7369               }
7370             }
7371           }
7372           iCrc32 = crc32(0, aIn, nIn);
7373         }
7374       }
7375     }
7376
7377     if( rc==SQLITE_OK ){
7378       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
7379     }
7380
7381     if( rc==SQLITE_OK ){
7382       zPath = (const char*)sqlite3_value_text(apVal[2]);
7383       if( zPath==0 ) zPath = "";
7384       nPath = (int)strlen(zPath);
7385       mTime = zipfileGetTime(apVal[4]);
7386     }
7387
7388     if( rc==SQLITE_OK && bIsDir ){
7389       /* For a directory, check that the last character in the path is a
7390       ** '/'. This appears to be required for compatibility with info-zip
7391       ** (the unzip command on unix). It does not create directories
7392       ** otherwise.  */
7393       if( nPath<=0 || zPath[nPath-1]!='/' ){
7394         zFree = sqlite3_mprintf("%s/", zPath);
7395         zPath = (const char*)zFree;
7396         if( zFree==0 ){
7397           rc = SQLITE_NOMEM;
7398           nPath = 0;
7399         }else{
7400           nPath = (int)strlen(zPath);
7401         }
7402       }
7403     }
7404
7405     /* Check that we're not inserting a duplicate entry -OR- updating an
7406     ** entry with a path, thereby making it into a duplicate. */
7407     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
7408       ZipfileEntry *p;
7409       for(p=pTab->pFirstEntry; p; p=p->pNext){
7410         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
7411           switch( sqlite3_vtab_on_conflict(pTab->db) ){
7412             case SQLITE_IGNORE: {
7413               goto zipfile_update_done;
7414             }
7415             case SQLITE_REPLACE: {
7416               pOld2 = p;
7417               break;
7418             }
7419             default: {
7420               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
7421               rc = SQLITE_CONSTRAINT;
7422               break;
7423             }
7424           }
7425           break;
7426         }
7427       }
7428     }
7429
7430     if( rc==SQLITE_OK ){
7431       /* Create the new CDS record. */
7432       pNew = zipfileNewEntry(zPath);
7433       if( pNew==0 ){
7434         rc = SQLITE_NOMEM;
7435       }else{
7436         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
7437         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
7438         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
7439         pNew->cds.iCompression = (u16)iMethod;
7440         zipfileMtimeToDos(&pNew->cds, mTime);
7441         pNew->cds.crc32 = iCrc32;
7442         pNew->cds.szCompressed = nData;
7443         pNew->cds.szUncompressed = (u32)sz;
7444         pNew->cds.iExternalAttr = (mode<<16);
7445         pNew->cds.iOffset = (u32)pTab->szCurrent;
7446         pNew->cds.nFile = (u16)nPath;
7447         pNew->mUnixTime = (u32)mTime;
7448         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
7449         zipfileAddEntry(pTab, pOld, pNew);
7450       }
7451     }
7452   }
7453
7454   if( rc==SQLITE_OK && (pOld || pOld2) ){
7455     ZipfileCsr *pCsr;
7456     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
7457       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
7458         pCsr->pCurrent = pCsr->pCurrent->pNext;
7459         pCsr->bNoop = 1;
7460       }
7461     }
7462
7463     zipfileRemoveEntryFromList(pTab, pOld);
7464     zipfileRemoveEntryFromList(pTab, pOld2);
7465   }
7466
7467 zipfile_update_done:
7468   sqlite3_free(pFree);
7469   sqlite3_free(zFree);
7470   return rc;
7471 }
7472
7473 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
7474   u8 *a = aBuf;
7475   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
7476   zipfileWrite16(a, p->iDisk);
7477   zipfileWrite16(a, p->iFirstDisk);
7478   zipfileWrite16(a, p->nEntry);
7479   zipfileWrite16(a, p->nEntryTotal);
7480   zipfileWrite32(a, p->nSize);
7481   zipfileWrite32(a, p->iOffset);
7482   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
7483
7484   return a-aBuf;
7485 }
7486
7487 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
7488   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
7489   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
7490   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
7491 }
7492
7493 /*
7494 ** Serialize the CDS structure into buffer aBuf[]. Return the number
7495 ** of bytes written.
7496 */
7497 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
7498   u8 *a = aBuf;
7499   ZipfileCDS *pCDS = &pEntry->cds;
7500
7501   if( pEntry->aExtra==0 ){
7502     pCDS->nExtra = 9;
7503   }
7504
7505   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
7506   zipfileWrite16(a, pCDS->iVersionMadeBy);
7507   zipfileWrite16(a, pCDS->iVersionExtract);
7508   zipfileWrite16(a, pCDS->flags);
7509   zipfileWrite16(a, pCDS->iCompression);
7510   zipfileWrite16(a, pCDS->mTime);
7511   zipfileWrite16(a, pCDS->mDate);
7512   zipfileWrite32(a, pCDS->crc32);
7513   zipfileWrite32(a, pCDS->szCompressed);
7514   zipfileWrite32(a, pCDS->szUncompressed);
7515   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
7516   zipfileWrite16(a, pCDS->nFile);
7517   zipfileWrite16(a, pCDS->nExtra);
7518   zipfileWrite16(a, pCDS->nComment);
7519   zipfileWrite16(a, pCDS->iDiskStart);
7520   zipfileWrite16(a, pCDS->iInternalAttr);
7521   zipfileWrite32(a, pCDS->iExternalAttr);
7522   zipfileWrite32(a, pCDS->iOffset);
7523
7524   memcpy(a, pCDS->zFile, pCDS->nFile);
7525   a += pCDS->nFile;
7526
7527   if( pEntry->aExtra ){
7528     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
7529     memcpy(a, pEntry->aExtra, n);
7530     a += n;
7531   }else{
7532     assert( pCDS->nExtra==9 );
7533     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
7534     zipfileWrite16(a, 5);
7535     *a++ = 0x01;
7536     zipfileWrite32(a, pEntry->mUnixTime);
7537   }
7538
7539   return a-aBuf;
7540 }
7541
7542 static int zipfileCommit(sqlite3_vtab *pVtab){
7543   ZipfileTab *pTab = (ZipfileTab*)pVtab;
7544   int rc = SQLITE_OK;
7545   if( pTab->pWriteFd ){
7546     i64 iOffset = pTab->szCurrent;
7547     ZipfileEntry *p;
7548     ZipfileEOCD eocd;
7549     int nEntry = 0;
7550
7551     /* Write out all entries */
7552     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
7553       int n = zipfileSerializeCDS(p, pTab->aBuffer);
7554       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
7555       nEntry++;
7556     }
7557
7558     /* Write out the EOCD record */
7559     eocd.iDisk = 0;
7560     eocd.iFirstDisk = 0;
7561     eocd.nEntry = (u16)nEntry;
7562     eocd.nEntryTotal = (u16)nEntry;
7563     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
7564     eocd.iOffset = (u32)iOffset;
7565     rc = zipfileAppendEOCD(pTab, &eocd);
7566
7567     zipfileCleanupTransaction(pTab);
7568   }
7569   return rc;
7570 }
7571
7572 static int zipfileRollback(sqlite3_vtab *pVtab){
7573   return zipfileCommit(pVtab);
7574 }
7575
7576 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
7577   ZipfileCsr *pCsr;
7578   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
7579     if( iId==pCsr->iId ) break;
7580   }
7581   return pCsr;
7582 }
7583
7584 static void zipfileFunctionCds(
7585   sqlite3_context *context,
7586   int argc,
7587   sqlite3_value **argv
7588 ){
7589   ZipfileCsr *pCsr;
7590   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
7591   assert( argc>0 );
7592
7593   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
7594   if( pCsr ){
7595     ZipfileCDS *p = &pCsr->pCurrent->cds;
7596     char *zRes = sqlite3_mprintf("{"
7597         "\"version-made-by\" : %u, "
7598         "\"version-to-extract\" : %u, "
7599         "\"flags\" : %u, "
7600         "\"compression\" : %u, "
7601         "\"time\" : %u, "
7602         "\"date\" : %u, "
7603         "\"crc32\" : %u, "
7604         "\"compressed-size\" : %u, "
7605         "\"uncompressed-size\" : %u, "
7606         "\"file-name-length\" : %u, "
7607         "\"extra-field-length\" : %u, "
7608         "\"file-comment-length\" : %u, "
7609         "\"disk-number-start\" : %u, "
7610         "\"internal-attr\" : %u, "
7611         "\"external-attr\" : %u, "
7612         "\"offset\" : %u }",
7613         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
7614         (u32)p->flags, (u32)p->iCompression,
7615         (u32)p->mTime, (u32)p->mDate,
7616         (u32)p->crc32, (u32)p->szCompressed,
7617         (u32)p->szUncompressed, (u32)p->nFile,
7618         (u32)p->nExtra, (u32)p->nComment,
7619         (u32)p->iDiskStart, (u32)p->iInternalAttr,
7620         (u32)p->iExternalAttr, (u32)p->iOffset
7621     );
7622
7623     if( zRes==0 ){
7624       sqlite3_result_error_nomem(context);
7625     }else{
7626       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
7627       sqlite3_free(zRes);
7628     }
7629   }
7630 }
7631
7632 /*
7633 ** xFindFunction method.
7634 */
7635 static int zipfileFindFunction(
7636   sqlite3_vtab *pVtab,            /* Virtual table handle */
7637   int nArg,                       /* Number of SQL function arguments */
7638   const char *zName,              /* Name of SQL function */
7639   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
7640   void **ppArg                    /* OUT: User data for *pxFunc */
7641 ){
7642   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
7643     *pxFunc = zipfileFunctionCds;
7644     *ppArg = (void*)pVtab;
7645     return 1;
7646   }
7647   return 0;
7648 }
7649
7650 typedef struct ZipfileBuffer ZipfileBuffer;
7651 struct ZipfileBuffer {
7652   u8 *a;                          /* Pointer to buffer */
7653   int n;                          /* Size of buffer in bytes */
7654   int nAlloc;                     /* Byte allocated at a[] */
7655 };
7656
7657 typedef struct ZipfileCtx ZipfileCtx;
7658 struct ZipfileCtx {
7659   int nEntry;
7660   ZipfileBuffer body;
7661   ZipfileBuffer cds;
7662 };
7663
7664 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
7665   if( pBuf->n+nByte>pBuf->nAlloc ){
7666     u8 *aNew;
7667     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
7668     int nReq = pBuf->n + nByte;
7669
7670     while( nNew<nReq ) nNew = nNew*2;
7671     aNew = sqlite3_realloc64(pBuf->a, nNew);
7672     if( aNew==0 ) return SQLITE_NOMEM;
7673     pBuf->a = aNew;
7674     pBuf->nAlloc = (int)nNew;
7675   }
7676   return SQLITE_OK;
7677 }
7678
7679 /*
7680 ** xStep() callback for the zipfile() aggregate. This can be called in
7681 ** any of the following ways:
7682 **
7683 **   SELECT zipfile(name,data) ...
7684 **   SELECT zipfile(name,mode,mtime,data) ...
7685 **   SELECT zipfile(name,mode,mtime,data,method) ...
7686 */
7687 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
7688   ZipfileCtx *p;                  /* Aggregate function context */
7689   ZipfileEntry e;                 /* New entry to add to zip archive */
7690
7691   sqlite3_value *pName = 0;
7692   sqlite3_value *pMode = 0;
7693   sqlite3_value *pMtime = 0;
7694   sqlite3_value *pData = 0;
7695   sqlite3_value *pMethod = 0;
7696
7697   int bIsDir = 0;
7698   u32 mode;
7699   int rc = SQLITE_OK;
7700   char *zErr = 0;
7701
7702   int iMethod = -1;               /* Compression method to use (0 or 8) */
7703
7704   const u8 *aData = 0;            /* Possibly compressed data for new entry */
7705   int nData = 0;                  /* Size of aData[] in bytes */
7706   int szUncompressed = 0;         /* Size of data before compression */
7707   u8 *aFree = 0;                  /* Free this before returning */
7708   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
7709
7710   char *zName = 0;                /* Path (name) of new entry */
7711   int nName = 0;                  /* Size of zName in bytes */
7712   char *zFree = 0;                /* Free this before returning */
7713   int nByte;
7714
7715   memset(&e, 0, sizeof(e));
7716   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
7717   if( p==0 ) return;
7718
7719   /* Martial the arguments into stack variables */
7720   if( nVal!=2 && nVal!=4 && nVal!=5 ){
7721     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
7722     rc = SQLITE_ERROR;
7723     goto zipfile_step_out;
7724   }
7725   pName = apVal[0];
7726   if( nVal==2 ){
7727     pData = apVal[1];
7728   }else{
7729     pMode = apVal[1];
7730     pMtime = apVal[2];
7731     pData = apVal[3];
7732     if( nVal==5 ){
7733       pMethod = apVal[4];
7734     }
7735   }
7736
7737   /* Check that the 'name' parameter looks ok. */
7738   zName = (char*)sqlite3_value_text(pName);
7739   nName = sqlite3_value_bytes(pName);
7740   if( zName==0 ){
7741     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
7742     rc = SQLITE_ERROR;
7743     goto zipfile_step_out;
7744   }
7745
7746   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
7747   ** deflate compression) or NULL (choose automatically).  */
7748   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
7749     iMethod = (int)sqlite3_value_int64(pMethod);
7750     if( iMethod!=0 && iMethod!=8 ){
7751       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
7752       rc = SQLITE_ERROR;
7753       goto zipfile_step_out;
7754     }
7755   }
7756
7757   /* Now inspect the data. If this is NULL, then the new entry must be a
7758   ** directory.  Otherwise, figure out whether or not the data should
7759   ** be deflated or simply stored in the zip archive. */
7760   if( sqlite3_value_type(pData)==SQLITE_NULL ){
7761     bIsDir = 1;
7762     iMethod = 0;
7763   }else{
7764     aData = sqlite3_value_blob(pData);
7765     szUncompressed = nData = sqlite3_value_bytes(pData);
7766     iCrc32 = crc32(0, aData, nData);
7767     if( iMethod<0 || iMethod==8 ){
7768       int nOut = 0;
7769       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
7770       if( rc!=SQLITE_OK ){
7771         goto zipfile_step_out;
7772       }
7773       if( iMethod==8 || nOut<nData ){
7774         aData = aFree;
7775         nData = nOut;
7776         iMethod = 8;
7777       }else{
7778         iMethod = 0;
7779       }
7780     }
7781   }
7782
7783   /* Decode the "mode" argument. */
7784   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
7785   if( rc ) goto zipfile_step_out;
7786
7787   /* Decode the "mtime" argument. */
7788   e.mUnixTime = zipfileGetTime(pMtime);
7789
7790   /* If this is a directory entry, ensure that there is exactly one '/'
7791   ** at the end of the path. Or, if this is not a directory and the path
7792   ** ends in '/' it is an error. */
7793   if( bIsDir==0 ){
7794     if( nName>0 && zName[nName-1]=='/' ){
7795       zErr = sqlite3_mprintf("non-directory name must not end with /");
7796       rc = SQLITE_ERROR;
7797       goto zipfile_step_out;
7798     }
7799   }else{
7800     if( nName==0 || zName[nName-1]!='/' ){
7801       zName = zFree = sqlite3_mprintf("%s/", zName);
7802       if( zName==0 ){
7803         rc = SQLITE_NOMEM;
7804         goto zipfile_step_out;
7805       }
7806       nName = (int)strlen(zName);
7807     }else{
7808       while( nName>1 && zName[nName-2]=='/' ) nName--;
7809     }
7810   }
7811
7812   /* Assemble the ZipfileEntry object for the new zip archive entry */
7813   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
7814   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
7815   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
7816   e.cds.iCompression = (u16)iMethod;
7817   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
7818   e.cds.crc32 = iCrc32;
7819   e.cds.szCompressed = nData;
7820   e.cds.szUncompressed = szUncompressed;
7821   e.cds.iExternalAttr = (mode<<16);
7822   e.cds.iOffset = p->body.n;
7823   e.cds.nFile = (u16)nName;
7824   e.cds.zFile = zName;
7825
7826   /* Append the LFH to the body of the new archive */
7827   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
7828   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
7829   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
7830
7831   /* Append the data to the body of the new archive */
7832   if( nData>0 ){
7833     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
7834     memcpy(&p->body.a[p->body.n], aData, nData);
7835     p->body.n += nData;
7836   }
7837
7838   /* Append the CDS record to the directory of the new archive */
7839   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
7840   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
7841   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
7842
7843   /* Increment the count of entries in the archive */
7844   p->nEntry++;
7845
7846  zipfile_step_out:
7847   sqlite3_free(aFree);
7848   sqlite3_free(zFree);
7849   if( rc ){
7850     if( zErr ){
7851       sqlite3_result_error(pCtx, zErr, -1);
7852     }else{
7853       sqlite3_result_error_code(pCtx, rc);
7854     }
7855   }
7856   sqlite3_free(zErr);
7857 }
7858
7859 /*
7860 ** xFinalize() callback for zipfile aggregate function.
7861 */
7862 void zipfileFinal(sqlite3_context *pCtx){
7863   ZipfileCtx *p;
7864   ZipfileEOCD eocd;
7865   sqlite3_int64 nZip;
7866   u8 *aZip;
7867
7868   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
7869   if( p==0 ) return;
7870   if( p->nEntry>0 ){
7871     memset(&eocd, 0, sizeof(eocd));
7872     eocd.nEntry = (u16)p->nEntry;
7873     eocd.nEntryTotal = (u16)p->nEntry;
7874     eocd.nSize = p->cds.n;
7875     eocd.iOffset = p->body.n;
7876
7877     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
7878     aZip = (u8*)sqlite3_malloc64(nZip);
7879     if( aZip==0 ){
7880       sqlite3_result_error_nomem(pCtx);
7881     }else{
7882       memcpy(aZip, p->body.a, p->body.n);
7883       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
7884       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
7885       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
7886     }
7887   }
7888
7889   sqlite3_free(p->body.a);
7890   sqlite3_free(p->cds.a);
7891 }
7892
7893
7894 /*
7895 ** Register the "zipfile" virtual table.
7896 */
7897 static int zipfileRegister(sqlite3 *db){
7898   static sqlite3_module zipfileModule = {
7899     1,                         /* iVersion */
7900     zipfileConnect,            /* xCreate */
7901     zipfileConnect,            /* xConnect */
7902     zipfileBestIndex,          /* xBestIndex */
7903     zipfileDisconnect,         /* xDisconnect */
7904     zipfileDisconnect,         /* xDestroy */
7905     zipfileOpen,               /* xOpen - open a cursor */
7906     zipfileClose,              /* xClose - close a cursor */
7907     zipfileFilter,             /* xFilter - configure scan constraints */
7908     zipfileNext,               /* xNext - advance a cursor */
7909     zipfileEof,                /* xEof - check for end of scan */
7910     zipfileColumn,             /* xColumn - read data */
7911     0,                         /* xRowid - read data */
7912     zipfileUpdate,             /* xUpdate */
7913     zipfileBegin,              /* xBegin */
7914     0,                         /* xSync */
7915     zipfileCommit,             /* xCommit */
7916     zipfileRollback,           /* xRollback */
7917     zipfileFindFunction,       /* xFindMethod */
7918     0,                         /* xRename */
7919   };
7920
7921   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
7922   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
7923   if( rc==SQLITE_OK ){
7924     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, 
7925         zipfileStep, zipfileFinal
7926     );
7927   }
7928   return rc;
7929 }
7930 #else         /* SQLITE_OMIT_VIRTUALTABLE */
7931 # define zipfileRegister(x) SQLITE_OK
7932 #endif
7933
7934 #ifdef _WIN32
7935
7936 #endif
7937 int sqlite3_zipfile_init(
7938   sqlite3 *db, 
7939   char **pzErrMsg, 
7940   const sqlite3_api_routines *pApi
7941 ){
7942   SQLITE_EXTENSION_INIT2(pApi);
7943   (void)pzErrMsg;  /* Unused parameter */
7944   return zipfileRegister(db);
7945 }
7946
7947 /************************* End ../ext/misc/zipfile.c ********************/
7948 /************************* Begin ../ext/misc/sqlar.c ******************/
7949 /*
7950 ** 2017-12-17
7951 **
7952 ** The author disclaims copyright to this source code.  In place of
7953 ** a legal notice, here is a blessing:
7954 **
7955 **    May you do good and not evil.
7956 **    May you find forgiveness for yourself and forgive others.
7957 **    May you share freely, never taking more than you give.
7958 **
7959 ******************************************************************************
7960 **
7961 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
7962 ** for working with sqlar archives and used by the shell tool's built-in
7963 ** sqlar support.
7964 */
7965 /* #include "sqlite3ext.h" */
7966 SQLITE_EXTENSION_INIT1
7967 #include <zlib.h>
7968 #include <assert.h>
7969
7970 /*
7971 ** Implementation of the "sqlar_compress(X)" SQL function.
7972 **
7973 ** If the type of X is SQLITE_BLOB, and compressing that blob using
7974 ** zlib utility function compress() yields a smaller blob, return the
7975 ** compressed blob. Otherwise, return a copy of X.
7976 **
7977 ** SQLar uses the "zlib format" for compressed content.  The zlib format
7978 ** contains a two-byte identification header and a four-byte checksum at
7979 ** the end.  This is different from ZIP which uses the raw deflate format.
7980 **
7981 ** Future enhancements to SQLar might add support for new compression formats.
7982 ** If so, those new formats will be identified by alternative headers in the
7983 ** compressed data.
7984 */
7985 static void sqlarCompressFunc(
7986   sqlite3_context *context,
7987   int argc,
7988   sqlite3_value **argv
7989 ){
7990   assert( argc==1 );
7991   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
7992     const Bytef *pData = sqlite3_value_blob(argv[0]);
7993     uLong nData = sqlite3_value_bytes(argv[0]);
7994     uLongf nOut = compressBound(nData);
7995     Bytef *pOut;
7996
7997     pOut = (Bytef*)sqlite3_malloc(nOut);
7998     if( pOut==0 ){
7999       sqlite3_result_error_nomem(context);
8000       return;
8001     }else{
8002       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
8003         sqlite3_result_error(context, "error in compress()", -1);
8004       }else if( nOut<nData ){
8005         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
8006       }else{
8007         sqlite3_result_value(context, argv[0]);
8008       }
8009       sqlite3_free(pOut);
8010     }
8011   }else{
8012     sqlite3_result_value(context, argv[0]);
8013   }
8014 }
8015
8016 /*
8017 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
8018 **
8019 ** Parameter SZ is interpreted as an integer. If it is less than or
8020 ** equal to zero, then this function returns a copy of X. Or, if
8021 ** SZ is equal to the size of X when interpreted as a blob, also
8022 ** return a copy of X. Otherwise, decompress blob X using zlib
8023 ** utility function uncompress() and return the results (another
8024 ** blob).
8025 */
8026 static void sqlarUncompressFunc(
8027   sqlite3_context *context,
8028   int argc,
8029   sqlite3_value **argv
8030 ){
8031   uLong nData;
8032   uLongf sz;
8033
8034   assert( argc==2 );
8035   sz = sqlite3_value_int(argv[1]);
8036
8037   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
8038     sqlite3_result_value(context, argv[0]);
8039   }else{
8040     const Bytef *pData= sqlite3_value_blob(argv[0]);
8041     Bytef *pOut = sqlite3_malloc(sz);
8042     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
8043       sqlite3_result_error(context, "error in uncompress()", -1);
8044     }else{
8045       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
8046     }
8047     sqlite3_free(pOut);
8048   }
8049 }
8050
8051
8052 #ifdef _WIN32
8053
8054 #endif
8055 int sqlite3_sqlar_init(
8056   sqlite3 *db, 
8057   char **pzErrMsg, 
8058   const sqlite3_api_routines *pApi
8059 ){
8060   int rc = SQLITE_OK;
8061   SQLITE_EXTENSION_INIT2(pApi);
8062   (void)pzErrMsg;  /* Unused parameter */
8063   rc = sqlite3_create_function(db, "sqlar_compress", 1, 
8064                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
8065                                sqlarCompressFunc, 0, 0);
8066   if( rc==SQLITE_OK ){
8067     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
8068                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
8069                                  sqlarUncompressFunc, 0, 0);
8070   }
8071   return rc;
8072 }
8073
8074 /************************* End ../ext/misc/sqlar.c ********************/
8075 #endif
8076 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
8077 /*
8078 ** 2017 April 07
8079 **
8080 ** The author disclaims copyright to this source code.  In place of
8081 ** a legal notice, here is a blessing:
8082 **
8083 **    May you do good and not evil.
8084 **    May you find forgiveness for yourself and forgive others.
8085 **    May you share freely, never taking more than you give.
8086 **
8087 *************************************************************************
8088 */
8089 #if !defined(SQLITEEXPERT_H)
8090 #define SQLITEEXPERT_H 1
8091 /* #include "sqlite3.h" */
8092
8093 typedef struct sqlite3expert sqlite3expert;
8094
8095 /*
8096 ** Create a new sqlite3expert object.
8097 **
8098 ** If successful, a pointer to the new object is returned and (*pzErr) set
8099 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
8100 ** an English-language error message. In this case it is the responsibility
8101 ** of the caller to eventually free the error message buffer using
8102 ** sqlite3_free().
8103 */
8104 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
8105
8106 /*
8107 ** Configure an sqlite3expert object.
8108 **
8109 ** EXPERT_CONFIG_SAMPLE:
8110 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
8111 **   each candidate index. This involves scanning and sorting the entire
8112 **   contents of each user database table once for each candidate index
8113 **   associated with the table. For large databases, this can be 
8114 **   prohibitively slow. This option allows the sqlite3expert object to
8115 **   be configured so that sqlite_stat1 data is instead generated based on a
8116 **   subset of each table, or so that no sqlite_stat1 data is used at all.
8117 **
8118 **   A single integer argument is passed to this option. If the value is less
8119 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
8120 **   the analysis - indexes are recommended based on the database schema only.
8121 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
8122 **   generated for each candidate index (this is the default). Finally, if the
8123 **   value falls between 0 and 100, then it represents the percentage of user
8124 **   table rows that should be considered when generating sqlite_stat1 data.
8125 **
8126 **   Examples:
8127 **
8128 **     // Do not generate any sqlite_stat1 data
8129 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
8130 **
8131 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
8132 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
8133 */
8134 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
8135
8136 #define EXPERT_CONFIG_SAMPLE 1    /* int */
8137
8138 /*
8139 ** Specify zero or more SQL statements to be included in the analysis.
8140 **
8141 ** Buffer zSql must contain zero or more complete SQL statements. This
8142 ** function parses all statements contained in the buffer and adds them
8143 ** to the internal list of statements to analyze. If successful, SQLITE_OK
8144 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
8145 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
8146 ** may be set to point to an English language error message. In this case
8147 ** the caller is responsible for eventually freeing the error message buffer
8148 ** using sqlite3_free().
8149 **
8150 ** If an error does occur while processing one of the statements in the
8151 ** buffer passed as the second argument, none of the statements in the
8152 ** buffer are added to the analysis.
8153 **
8154 ** This function must be called before sqlite3_expert_analyze(). If a call
8155 ** to this function is made on an sqlite3expert object that has already
8156 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
8157 ** immediately and no statements are added to the analysis.
8158 */
8159 int sqlite3_expert_sql(
8160   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
8161   const char *zSql,               /* SQL statement(s) to add */
8162   char **pzErr                    /* OUT: Error message (if any) */
8163 );
8164
8165
8166 /*
8167 ** This function is called after the sqlite3expert object has been configured
8168 ** with all SQL statements using sqlite3_expert_sql() to actually perform
8169 ** the analysis. Once this function has been called, it is not possible to
8170 ** add further SQL statements to the analysis.
8171 **
8172 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
8173 ** an error occurs, an SQLite error code is returned and (*pzErr) set to 
8174 ** point to a buffer containing an English language error message. In this
8175 ** case it is the responsibility of the caller to eventually free the buffer
8176 ** using sqlite3_free().
8177 **
8178 ** If an error does occur within this function, the sqlite3expert object
8179 ** is no longer useful for any purpose. At that point it is no longer
8180 ** possible to add further SQL statements to the object or to re-attempt
8181 ** the analysis. The sqlite3expert object must still be freed using a call
8182 ** sqlite3_expert_destroy().
8183 */
8184 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
8185
8186 /*
8187 ** Return the total number of statements loaded using sqlite3_expert_sql().
8188 ** The total number of SQL statements may be different from the total number
8189 ** to calls to sqlite3_expert_sql().
8190 */
8191 int sqlite3_expert_count(sqlite3expert*);
8192
8193 /*
8194 ** Return a component of the report.
8195 **
8196 ** This function is called after sqlite3_expert_analyze() to extract the
8197 ** results of the analysis. Each call to this function returns either a
8198 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
8199 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
8200 ** #define constants defined below.
8201 **
8202 ** For some EXPERT_REPORT_* parameters, the buffer returned contains 
8203 ** information relating to a specific SQL statement. In these cases that
8204 ** SQL statement is identified by the value passed as the second argument.
8205 ** SQL statements are numbered from 0 in the order in which they are parsed.
8206 ** If an out-of-range value (less than zero or equal to or greater than the
8207 ** value returned by sqlite3_expert_count()) is passed as the second argument
8208 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
8209 **
8210 ** EXPERT_REPORT_SQL:
8211 **   Return the text of SQL statement iStmt.
8212 **
8213 ** EXPERT_REPORT_INDEXES:
8214 **   Return a buffer containing the CREATE INDEX statements for all recommended
8215 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL 
8216 **   is returned.
8217 **
8218 ** EXPERT_REPORT_PLAN:
8219 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
8220 **   iStmt after the proposed indexes have been added to the database schema.
8221 **
8222 ** EXPERT_REPORT_CANDIDATES:
8223 **   Return a pointer to a buffer containing the CREATE INDEX statements 
8224 **   for all indexes that were tested (for all SQL statements). The iStmt
8225 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
8226 */
8227 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
8228
8229 /*
8230 ** Values for the third argument passed to sqlite3_expert_report().
8231 */
8232 #define EXPERT_REPORT_SQL        1
8233 #define EXPERT_REPORT_INDEXES    2
8234 #define EXPERT_REPORT_PLAN       3
8235 #define EXPERT_REPORT_CANDIDATES 4
8236
8237 /*
8238 ** Free an (sqlite3expert*) handle and all associated resources. There 
8239 ** should be one call to this function for each successful call to 
8240 ** sqlite3-expert_new().
8241 */
8242 void sqlite3_expert_destroy(sqlite3expert*);
8243
8244 #endif  /* !defined(SQLITEEXPERT_H) */
8245
8246 /************************* End ../ext/expert/sqlite3expert.h ********************/
8247 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
8248 /*
8249 ** 2017 April 09
8250 **
8251 ** The author disclaims copyright to this source code.  In place of
8252 ** a legal notice, here is a blessing:
8253 **
8254 **    May you do good and not evil.
8255 **    May you find forgiveness for yourself and forgive others.
8256 **    May you share freely, never taking more than you give.
8257 **
8258 *************************************************************************
8259 */
8260 /* #include "sqlite3expert.h" */
8261 #include <assert.h>
8262 #include <string.h>
8263 #include <stdio.h>
8264
8265 #ifndef SQLITE_OMIT_VIRTUALTABLE 
8266
8267 /* typedef sqlite3_int64 i64; */
8268 /* typedef sqlite3_uint64 u64; */
8269
8270 typedef struct IdxColumn IdxColumn;
8271 typedef struct IdxConstraint IdxConstraint;
8272 typedef struct IdxScan IdxScan;
8273 typedef struct IdxStatement IdxStatement;
8274 typedef struct IdxTable IdxTable;
8275 typedef struct IdxWrite IdxWrite;
8276
8277 #define STRLEN  (int)strlen
8278
8279 /*
8280 ** A temp table name that we assume no user database will actually use.
8281 ** If this assumption proves incorrect triggers on the table with the
8282 ** conflicting name will be ignored.
8283 */
8284 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
8285
8286 /*
8287 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
8288 ** any other type of single-ended range constraint on a column).
8289 **
8290 ** pLink:
8291 **   Used to temporarily link IdxConstraint objects into lists while
8292 **   creating candidate indexes.
8293 */
8294 struct IdxConstraint {
8295   char *zColl;                    /* Collation sequence */
8296   int bRange;                     /* True for range, false for eq */
8297   int iCol;                       /* Constrained table column */
8298   int bFlag;                      /* Used by idxFindCompatible() */
8299   int bDesc;                      /* True if ORDER BY <expr> DESC */
8300   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
8301   IdxConstraint *pLink;           /* See above */
8302 };
8303
8304 /*
8305 ** A single scan of a single table.
8306 */
8307 struct IdxScan {
8308   IdxTable *pTab;                 /* Associated table object */
8309   int iDb;                        /* Database containing table zTable */
8310   i64 covering;                   /* Mask of columns required for cov. index */
8311   IdxConstraint *pOrder;          /* ORDER BY columns */
8312   IdxConstraint *pEq;             /* List of == constraints */
8313   IdxConstraint *pRange;          /* List of < constraints */
8314   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
8315 };
8316
8317 /*
8318 ** Information regarding a single database table. Extracted from 
8319 ** "PRAGMA table_info" by function idxGetTableInfo().
8320 */
8321 struct IdxColumn {
8322   char *zName;
8323   char *zColl;
8324   int iPk;
8325 };
8326 struct IdxTable {
8327   int nCol;
8328   char *zName;                    /* Table name */
8329   IdxColumn *aCol;
8330   IdxTable *pNext;                /* Next table in linked list of all tables */
8331 };
8332
8333 /*
8334 ** An object of the following type is created for each unique table/write-op
8335 ** seen. The objects are stored in a singly-linked list beginning at
8336 ** sqlite3expert.pWrite.
8337 */
8338 struct IdxWrite {
8339   IdxTable *pTab;
8340   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
8341   IdxWrite *pNext;
8342 };
8343
8344 /*
8345 ** Each statement being analyzed is represented by an instance of this
8346 ** structure.
8347 */
8348 struct IdxStatement {
8349   int iId;                        /* Statement number */
8350   char *zSql;                     /* SQL statement */
8351   char *zIdx;                     /* Indexes */
8352   char *zEQP;                     /* Plan */
8353   IdxStatement *pNext;
8354 };
8355
8356
8357 /*
8358 ** A hash table for storing strings. With space for a payload string
8359 ** with each entry. Methods are:
8360 **
8361 **   idxHashInit()
8362 **   idxHashClear()
8363 **   idxHashAdd()
8364 **   idxHashSearch()
8365 */
8366 #define IDX_HASH_SIZE 1023
8367 typedef struct IdxHashEntry IdxHashEntry;
8368 typedef struct IdxHash IdxHash;
8369 struct IdxHashEntry {
8370   char *zKey;                     /* nul-terminated key */
8371   char *zVal;                     /* nul-terminated value string */
8372   char *zVal2;                    /* nul-terminated value string 2 */
8373   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
8374   IdxHashEntry *pNext;            /* Next entry in hash */
8375 };
8376 struct IdxHash {
8377   IdxHashEntry *pFirst;
8378   IdxHashEntry *aHash[IDX_HASH_SIZE];
8379 };
8380
8381 /*
8382 ** sqlite3expert object.
8383 */
8384 struct sqlite3expert {
8385   int iSample;                    /* Percentage of tables to sample for stat1 */
8386   sqlite3 *db;                    /* User database */
8387   sqlite3 *dbm;                   /* In-memory db for this analysis */
8388   sqlite3 *dbv;                   /* Vtab schema for this analysis */
8389   IdxTable *pTable;               /* List of all IdxTable objects */
8390   IdxScan *pScan;                 /* List of scan objects */
8391   IdxWrite *pWrite;               /* List of write objects */
8392   IdxStatement *pStatement;       /* List of IdxStatement objects */
8393   int bRun;                       /* True once analysis has run */
8394   char **pzErrmsg;
8395   int rc;                         /* Error code from whereinfo hook */
8396   IdxHash hIdx;                   /* Hash containing all candidate indexes */
8397   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
8398 };
8399
8400
8401 /*
8402 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). 
8403 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
8404 */
8405 static void *idxMalloc(int *pRc, int nByte){
8406   void *pRet;
8407   assert( *pRc==SQLITE_OK );
8408   assert( nByte>0 );
8409   pRet = sqlite3_malloc(nByte);
8410   if( pRet ){
8411     memset(pRet, 0, nByte);
8412   }else{
8413     *pRc = SQLITE_NOMEM;
8414   }
8415   return pRet;
8416 }
8417
8418 /*
8419 ** Initialize an IdxHash hash table.
8420 */
8421 static void idxHashInit(IdxHash *pHash){
8422   memset(pHash, 0, sizeof(IdxHash));
8423 }
8424
8425 /*
8426 ** Reset an IdxHash hash table.
8427 */
8428 static void idxHashClear(IdxHash *pHash){
8429   int i;
8430   for(i=0; i<IDX_HASH_SIZE; i++){
8431     IdxHashEntry *pEntry;
8432     IdxHashEntry *pNext;
8433     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
8434       pNext = pEntry->pHashNext;
8435       sqlite3_free(pEntry->zVal2);
8436       sqlite3_free(pEntry);
8437     }
8438   }
8439   memset(pHash, 0, sizeof(IdxHash));
8440 }
8441
8442 /*
8443 ** Return the index of the hash bucket that the string specified by the
8444 ** arguments to this function belongs.
8445 */
8446 static int idxHashString(const char *z, int n){
8447   unsigned int ret = 0;
8448   int i;
8449   for(i=0; i<n; i++){
8450     ret += (ret<<3) + (unsigned char)(z[i]);
8451   }
8452   return (int)(ret % IDX_HASH_SIZE);
8453 }
8454
8455 /*
8456 ** If zKey is already present in the hash table, return non-zero and do
8457 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
8458 ** the hash table passed as the second argument. 
8459 */
8460 static int idxHashAdd(
8461   int *pRc, 
8462   IdxHash *pHash, 
8463   const char *zKey,
8464   const char *zVal
8465 ){
8466   int nKey = STRLEN(zKey);
8467   int iHash = idxHashString(zKey, nKey);
8468   int nVal = (zVal ? STRLEN(zVal) : 0);
8469   IdxHashEntry *pEntry;
8470   assert( iHash>=0 );
8471   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
8472     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
8473       return 1;
8474     }
8475   }
8476   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
8477   if( pEntry ){
8478     pEntry->zKey = (char*)&pEntry[1];
8479     memcpy(pEntry->zKey, zKey, nKey);
8480     if( zVal ){
8481       pEntry->zVal = &pEntry->zKey[nKey+1];
8482       memcpy(pEntry->zVal, zVal, nVal);
8483     }
8484     pEntry->pHashNext = pHash->aHash[iHash];
8485     pHash->aHash[iHash] = pEntry;
8486
8487     pEntry->pNext = pHash->pFirst;
8488     pHash->pFirst = pEntry;
8489   }
8490   return 0;
8491 }
8492
8493 /*
8494 ** If zKey/nKey is present in the hash table, return a pointer to the 
8495 ** hash-entry object.
8496 */
8497 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
8498   int iHash;
8499   IdxHashEntry *pEntry;
8500   if( nKey<0 ) nKey = STRLEN(zKey);
8501   iHash = idxHashString(zKey, nKey);
8502   assert( iHash>=0 );
8503   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
8504     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
8505       return pEntry;
8506     }
8507   }
8508   return 0;
8509 }
8510
8511 /*
8512 ** If the hash table contains an entry with a key equal to the string
8513 ** passed as the final two arguments to this function, return a pointer
8514 ** to the payload string. Otherwise, if zKey/nKey is not present in the
8515 ** hash table, return NULL.
8516 */
8517 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
8518   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
8519   if( pEntry ) return pEntry->zVal;
8520   return 0;
8521 }
8522
8523 /*
8524 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
8525 ** variable to point to a copy of nul-terminated string zColl.
8526 */
8527 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
8528   IdxConstraint *pNew;
8529   int nColl = STRLEN(zColl);
8530
8531   assert( *pRc==SQLITE_OK );
8532   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
8533   if( pNew ){
8534     pNew->zColl = (char*)&pNew[1];
8535     memcpy(pNew->zColl, zColl, nColl+1);
8536   }
8537   return pNew;
8538 }
8539
8540 /*
8541 ** An error associated with database handle db has just occurred. Pass
8542 ** the error message to callback function xOut.
8543 */
8544 static void idxDatabaseError(
8545   sqlite3 *db,                    /* Database handle */
8546   char **pzErrmsg                 /* Write error here */
8547 ){
8548   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
8549 }
8550
8551 /*
8552 ** Prepare an SQL statement.
8553 */
8554 static int idxPrepareStmt(
8555   sqlite3 *db,                    /* Database handle to compile against */
8556   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
8557   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
8558   const char *zSql                /* SQL statement to compile */
8559 ){
8560   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
8561   if( rc!=SQLITE_OK ){
8562     *ppStmt = 0;
8563     idxDatabaseError(db, pzErrmsg);
8564   }
8565   return rc;
8566 }
8567
8568 /*
8569 ** Prepare an SQL statement using the results of a printf() formatting.
8570 */
8571 static int idxPrintfPrepareStmt(
8572   sqlite3 *db,                    /* Database handle to compile against */
8573   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
8574   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
8575   const char *zFmt,               /* printf() format of SQL statement */
8576   ...                             /* Trailing printf() arguments */
8577 ){
8578   va_list ap;
8579   int rc;
8580   char *zSql;
8581   va_start(ap, zFmt);
8582   zSql = sqlite3_vmprintf(zFmt, ap);
8583   if( zSql==0 ){
8584     rc = SQLITE_NOMEM;
8585   }else{
8586     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
8587     sqlite3_free(zSql);
8588   }
8589   va_end(ap);
8590   return rc;
8591 }
8592
8593
8594 /*************************************************************************
8595 ** Beginning of virtual table implementation.
8596 */
8597 typedef struct ExpertVtab ExpertVtab;
8598 struct ExpertVtab {
8599   sqlite3_vtab base;
8600   IdxTable *pTab;
8601   sqlite3expert *pExpert;
8602 };
8603
8604 typedef struct ExpertCsr ExpertCsr;
8605 struct ExpertCsr {
8606   sqlite3_vtab_cursor base;
8607   sqlite3_stmt *pData;
8608 };
8609
8610 static char *expertDequote(const char *zIn){
8611   int n = STRLEN(zIn);
8612   char *zRet = sqlite3_malloc(n);
8613
8614   assert( zIn[0]=='\'' );
8615   assert( zIn[n-1]=='\'' );
8616
8617   if( zRet ){
8618     int iOut = 0;
8619     int iIn = 0;
8620     for(iIn=1; iIn<(n-1); iIn++){
8621       if( zIn[iIn]=='\'' ){
8622         assert( zIn[iIn+1]=='\'' );
8623         iIn++;
8624       }
8625       zRet[iOut++] = zIn[iIn];
8626     }
8627     zRet[iOut] = '\0';
8628   }
8629
8630   return zRet;
8631 }
8632
8633 /* 
8634 ** This function is the implementation of both the xConnect and xCreate
8635 ** methods of the r-tree virtual table.
8636 **
8637 **   argv[0]   -> module name
8638 **   argv[1]   -> database name
8639 **   argv[2]   -> table name
8640 **   argv[...] -> column names...
8641 */
8642 static int expertConnect(
8643   sqlite3 *db,
8644   void *pAux,
8645   int argc, const char *const*argv,
8646   sqlite3_vtab **ppVtab,
8647   char **pzErr
8648 ){
8649   sqlite3expert *pExpert = (sqlite3expert*)pAux;
8650   ExpertVtab *p = 0;
8651   int rc;
8652
8653   if( argc!=4 ){
8654     *pzErr = sqlite3_mprintf("internal error!");
8655     rc = SQLITE_ERROR;
8656   }else{
8657     char *zCreateTable = expertDequote(argv[3]);
8658     if( zCreateTable ){
8659       rc = sqlite3_declare_vtab(db, zCreateTable);
8660       if( rc==SQLITE_OK ){
8661         p = idxMalloc(&rc, sizeof(ExpertVtab));
8662       }
8663       if( rc==SQLITE_OK ){
8664         p->pExpert = pExpert;
8665         p->pTab = pExpert->pTable;
8666         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
8667       }
8668       sqlite3_free(zCreateTable);
8669     }else{
8670       rc = SQLITE_NOMEM;
8671     }
8672   }
8673
8674   *ppVtab = (sqlite3_vtab*)p;
8675   return rc;
8676 }
8677
8678 static int expertDisconnect(sqlite3_vtab *pVtab){
8679   ExpertVtab *p = (ExpertVtab*)pVtab;
8680   sqlite3_free(p);
8681   return SQLITE_OK;
8682 }
8683
8684 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
8685   ExpertVtab *p = (ExpertVtab*)pVtab;
8686   int rc = SQLITE_OK;
8687   int n = 0;
8688   IdxScan *pScan;
8689   const int opmask = 
8690     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
8691     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
8692     SQLITE_INDEX_CONSTRAINT_LE;
8693
8694   pScan = idxMalloc(&rc, sizeof(IdxScan));
8695   if( pScan ){
8696     int i;
8697
8698     /* Link the new scan object into the list */
8699     pScan->pTab = p->pTab;
8700     pScan->pNextScan = p->pExpert->pScan;
8701     p->pExpert->pScan = pScan;
8702
8703     /* Add the constraints to the IdxScan object */
8704     for(i=0; i<pIdxInfo->nConstraint; i++){
8705       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
8706       if( pCons->usable 
8707        && pCons->iColumn>=0 
8708        && p->pTab->aCol[pCons->iColumn].iPk==0
8709        && (pCons->op & opmask) 
8710       ){
8711         IdxConstraint *pNew;
8712         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
8713         pNew = idxNewConstraint(&rc, zColl);
8714         if( pNew ){
8715           pNew->iCol = pCons->iColumn;
8716           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
8717             pNew->pNext = pScan->pEq;
8718             pScan->pEq = pNew;
8719           }else{
8720             pNew->bRange = 1;
8721             pNew->pNext = pScan->pRange;
8722             pScan->pRange = pNew;
8723           }
8724         }
8725         n++;
8726         pIdxInfo->aConstraintUsage[i].argvIndex = n;
8727       }
8728     }
8729
8730     /* Add the ORDER BY to the IdxScan object */
8731     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
8732       int iCol = pIdxInfo->aOrderBy[i].iColumn;
8733       if( iCol>=0 ){
8734         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
8735         if( pNew ){
8736           pNew->iCol = iCol;
8737           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
8738           pNew->pNext = pScan->pOrder;
8739           pNew->pLink = pScan->pOrder;
8740           pScan->pOrder = pNew;
8741           n++;
8742         }
8743       }
8744     }
8745   }
8746
8747   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
8748   return rc;
8749 }
8750
8751 static int expertUpdate(
8752   sqlite3_vtab *pVtab, 
8753   int nData, 
8754   sqlite3_value **azData, 
8755   sqlite_int64 *pRowid
8756 ){
8757   (void)pVtab;
8758   (void)nData;
8759   (void)azData;
8760   (void)pRowid;
8761   return SQLITE_OK;
8762 }
8763
8764 /* 
8765 ** Virtual table module xOpen method.
8766 */
8767 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
8768   int rc = SQLITE_OK;
8769   ExpertCsr *pCsr;
8770   (void)pVTab;
8771   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
8772   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
8773   return rc;
8774 }
8775
8776 /* 
8777 ** Virtual table module xClose method.
8778 */
8779 static int expertClose(sqlite3_vtab_cursor *cur){
8780   ExpertCsr *pCsr = (ExpertCsr*)cur;
8781   sqlite3_finalize(pCsr->pData);
8782   sqlite3_free(pCsr);
8783   return SQLITE_OK;
8784 }
8785
8786 /*
8787 ** Virtual table module xEof method.
8788 **
8789 ** Return non-zero if the cursor does not currently point to a valid 
8790 ** record (i.e if the scan has finished), or zero otherwise.
8791 */
8792 static int expertEof(sqlite3_vtab_cursor *cur){
8793   ExpertCsr *pCsr = (ExpertCsr*)cur;
8794   return pCsr->pData==0;
8795 }
8796
8797 /* 
8798 ** Virtual table module xNext method.
8799 */
8800 static int expertNext(sqlite3_vtab_cursor *cur){
8801   ExpertCsr *pCsr = (ExpertCsr*)cur;
8802   int rc = SQLITE_OK;
8803
8804   assert( pCsr->pData );
8805   rc = sqlite3_step(pCsr->pData);
8806   if( rc!=SQLITE_ROW ){
8807     rc = sqlite3_finalize(pCsr->pData);
8808     pCsr->pData = 0;
8809   }else{
8810     rc = SQLITE_OK;
8811   }
8812
8813   return rc;
8814 }
8815
8816 /* 
8817 ** Virtual table module xRowid method.
8818 */
8819 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8820   (void)cur;
8821   *pRowid = 0;
8822   return SQLITE_OK;
8823 }
8824
8825 /* 
8826 ** Virtual table module xColumn method.
8827 */
8828 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
8829   ExpertCsr *pCsr = (ExpertCsr*)cur;
8830   sqlite3_value *pVal;
8831   pVal = sqlite3_column_value(pCsr->pData, i);
8832   if( pVal ){
8833     sqlite3_result_value(ctx, pVal);
8834   }
8835   return SQLITE_OK;
8836 }
8837
8838 /* 
8839 ** Virtual table module xFilter method.
8840 */
8841 static int expertFilter(
8842   sqlite3_vtab_cursor *cur, 
8843   int idxNum, const char *idxStr,
8844   int argc, sqlite3_value **argv
8845 ){
8846   ExpertCsr *pCsr = (ExpertCsr*)cur;
8847   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
8848   sqlite3expert *pExpert = pVtab->pExpert;
8849   int rc;
8850
8851   (void)idxNum;
8852   (void)idxStr;
8853   (void)argc;
8854   (void)argv;
8855   rc = sqlite3_finalize(pCsr->pData);
8856   pCsr->pData = 0;
8857   if( rc==SQLITE_OK ){
8858     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
8859         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
8860     );
8861   }
8862
8863   if( rc==SQLITE_OK ){
8864     rc = expertNext(cur);
8865   }
8866   return rc;
8867 }
8868
8869 static int idxRegisterVtab(sqlite3expert *p){
8870   static sqlite3_module expertModule = {
8871     2,                            /* iVersion */
8872     expertConnect,                /* xCreate - create a table */
8873     expertConnect,                /* xConnect - connect to an existing table */
8874     expertBestIndex,              /* xBestIndex - Determine search strategy */
8875     expertDisconnect,             /* xDisconnect - Disconnect from a table */
8876     expertDisconnect,             /* xDestroy - Drop a table */
8877     expertOpen,                   /* xOpen - open a cursor */
8878     expertClose,                  /* xClose - close a cursor */
8879     expertFilter,                 /* xFilter - configure scan constraints */
8880     expertNext,                   /* xNext - advance a cursor */
8881     expertEof,                    /* xEof */
8882     expertColumn,                 /* xColumn - read data */
8883     expertRowid,                  /* xRowid - read data */
8884     expertUpdate,                 /* xUpdate - write data */
8885     0,                            /* xBegin - begin transaction */
8886     0,                            /* xSync - sync transaction */
8887     0,                            /* xCommit - commit transaction */
8888     0,                            /* xRollback - rollback transaction */
8889     0,                            /* xFindFunction - function overloading */
8890     0,                            /* xRename - rename the table */
8891     0,                            /* xSavepoint */
8892     0,                            /* xRelease */
8893     0,                            /* xRollbackTo */
8894     0,                            /* xShadowName */
8895   };
8896
8897   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
8898 }
8899 /*
8900 ** End of virtual table implementation.
8901 *************************************************************************/
8902 /*
8903 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
8904 ** is called, set it to the return value of sqlite3_finalize() before
8905 ** returning. Otherwise, discard the sqlite3_finalize() return value.
8906 */
8907 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
8908   int rc = sqlite3_finalize(pStmt);
8909   if( *pRc==SQLITE_OK ) *pRc = rc;
8910 }
8911
8912 /*
8913 ** Attempt to allocate an IdxTable structure corresponding to table zTab
8914 ** in the main database of connection db. If successful, set (*ppOut) to
8915 ** point to the new object and return SQLITE_OK. Otherwise, return an
8916 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
8917 ** set to point to an error string.
8918 **
8919 ** It is the responsibility of the caller to eventually free either the
8920 ** IdxTable object or error message using sqlite3_free().
8921 */
8922 static int idxGetTableInfo(
8923   sqlite3 *db,                    /* Database connection to read details from */
8924   const char *zTab,               /* Table name */
8925   IdxTable **ppOut,               /* OUT: New object (if successful) */
8926   char **pzErrmsg                 /* OUT: Error message (if not) */
8927 ){
8928   sqlite3_stmt *p1 = 0;
8929   int nCol = 0;
8930   int nTab = STRLEN(zTab);
8931   int nByte = sizeof(IdxTable) + nTab + 1;
8932   IdxTable *pNew = 0;
8933   int rc, rc2;
8934   char *pCsr = 0;
8935   int nPk = 0;
8936
8937   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
8938   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
8939     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
8940     nByte += 1 + STRLEN(zCol);
8941     rc = sqlite3_table_column_metadata(
8942         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
8943     );
8944     nByte += 1 + STRLEN(zCol);
8945     nCol++;
8946     nPk += (sqlite3_column_int(p1, 5)>0);
8947   }
8948   rc2 = sqlite3_reset(p1);
8949   if( rc==SQLITE_OK ) rc = rc2;
8950
8951   nByte += sizeof(IdxColumn) * nCol;
8952   if( rc==SQLITE_OK ){
8953     pNew = idxMalloc(&rc, nByte);
8954   }
8955   if( rc==SQLITE_OK ){
8956     pNew->aCol = (IdxColumn*)&pNew[1];
8957     pNew->nCol = nCol;
8958     pCsr = (char*)&pNew->aCol[nCol];
8959   }
8960
8961   nCol = 0;
8962   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
8963     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
8964     int nCopy = STRLEN(zCol) + 1;
8965     pNew->aCol[nCol].zName = pCsr;
8966     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
8967     memcpy(pCsr, zCol, nCopy);
8968     pCsr += nCopy;
8969
8970     rc = sqlite3_table_column_metadata(
8971         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
8972     );
8973     if( rc==SQLITE_OK ){
8974       nCopy = STRLEN(zCol) + 1;
8975       pNew->aCol[nCol].zColl = pCsr;
8976       memcpy(pCsr, zCol, nCopy);
8977       pCsr += nCopy;
8978     }
8979
8980     nCol++;
8981   }
8982   idxFinalize(&rc, p1);
8983
8984   if( rc!=SQLITE_OK ){
8985     sqlite3_free(pNew);
8986     pNew = 0;
8987   }else{
8988     pNew->zName = pCsr;
8989     memcpy(pNew->zName, zTab, nTab+1);
8990   }
8991
8992   *ppOut = pNew;
8993   return rc;
8994 }
8995
8996 /*
8997 ** This function is a no-op if *pRc is set to anything other than 
8998 ** SQLITE_OK when it is called.
8999 **
9000 ** If *pRc is initially set to SQLITE_OK, then the text specified by
9001 ** the printf() style arguments is appended to zIn and the result returned
9002 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
9003 ** zIn before returning.
9004 */
9005 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
9006   va_list ap;
9007   char *zAppend = 0;
9008   char *zRet = 0;
9009   int nIn = zIn ? STRLEN(zIn) : 0;
9010   int nAppend = 0;
9011   va_start(ap, zFmt);
9012   if( *pRc==SQLITE_OK ){
9013     zAppend = sqlite3_vmprintf(zFmt, ap);
9014     if( zAppend ){
9015       nAppend = STRLEN(zAppend);
9016       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
9017     }
9018     if( zAppend && zRet ){
9019       if( nIn ) memcpy(zRet, zIn, nIn);
9020       memcpy(&zRet[nIn], zAppend, nAppend+1);
9021     }else{
9022       sqlite3_free(zRet);
9023       zRet = 0;
9024       *pRc = SQLITE_NOMEM;
9025     }
9026     sqlite3_free(zAppend);
9027     sqlite3_free(zIn);
9028   }
9029   va_end(ap);
9030   return zRet;
9031 }
9032
9033 /*
9034 ** Return true if zId must be quoted in order to use it as an SQL
9035 ** identifier, or false otherwise.
9036 */
9037 static int idxIdentifierRequiresQuotes(const char *zId){
9038   int i;
9039   for(i=0; zId[i]; i++){
9040     if( !(zId[i]=='_')
9041      && !(zId[i]>='0' && zId[i]<='9')
9042      && !(zId[i]>='a' && zId[i]<='z')
9043      && !(zId[i]>='A' && zId[i]<='Z')
9044     ){
9045       return 1;
9046     }
9047   }
9048   return 0;
9049 }
9050
9051 /*
9052 ** This function appends an index column definition suitable for constraint
9053 ** pCons to the string passed as zIn and returns the result.
9054 */
9055 static char *idxAppendColDefn(
9056   int *pRc,                       /* IN/OUT: Error code */
9057   char *zIn,                      /* Column defn accumulated so far */
9058   IdxTable *pTab,                 /* Table index will be created on */
9059   IdxConstraint *pCons
9060 ){
9061   char *zRet = zIn;
9062   IdxColumn *p = &pTab->aCol[pCons->iCol];
9063   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
9064
9065   if( idxIdentifierRequiresQuotes(p->zName) ){
9066     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
9067   }else{
9068     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
9069   }
9070
9071   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
9072     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
9073       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
9074     }else{
9075       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
9076     }
9077   }
9078
9079   if( pCons->bDesc ){
9080     zRet = idxAppendText(pRc, zRet, " DESC");
9081   }
9082   return zRet;
9083 }
9084
9085 /*
9086 ** Search database dbm for an index compatible with the one idxCreateFromCons()
9087 ** would create from arguments pScan, pEq and pTail. If no error occurs and 
9088 ** such an index is found, return non-zero. Or, if no such index is found,
9089 ** return zero.
9090 **
9091 ** If an error occurs, set *pRc to an SQLite error code and return zero.
9092 */
9093 static int idxFindCompatible(
9094   int *pRc,                       /* OUT: Error code */
9095   sqlite3* dbm,                   /* Database to search */
9096   IdxScan *pScan,                 /* Scan for table to search for index on */
9097   IdxConstraint *pEq,             /* List of == constraints */
9098   IdxConstraint *pTail            /* List of range constraints */
9099 ){
9100   const char *zTbl = pScan->pTab->zName;
9101   sqlite3_stmt *pIdxList = 0;
9102   IdxConstraint *pIter;
9103   int nEq = 0;                    /* Number of elements in pEq */
9104   int rc;
9105
9106   /* Count the elements in list pEq */
9107   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
9108
9109   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
9110   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
9111     int bMatch = 1;
9112     IdxConstraint *pT = pTail;
9113     sqlite3_stmt *pInfo = 0;
9114     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
9115
9116     /* Zero the IdxConstraint.bFlag values in the pEq list */
9117     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
9118
9119     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
9120     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
9121       int iIdx = sqlite3_column_int(pInfo, 0);
9122       int iCol = sqlite3_column_int(pInfo, 1);
9123       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
9124
9125       if( iIdx<nEq ){
9126         for(pIter=pEq; pIter; pIter=pIter->pLink){
9127           if( pIter->bFlag ) continue;
9128           if( pIter->iCol!=iCol ) continue;
9129           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
9130           pIter->bFlag = 1;
9131           break;
9132         }
9133         if( pIter==0 ){
9134           bMatch = 0;
9135           break;
9136         }
9137       }else{
9138         if( pT ){
9139           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
9140             bMatch = 0;
9141             break;
9142           }
9143           pT = pT->pLink;
9144         }
9145       }
9146     }
9147     idxFinalize(&rc, pInfo);
9148
9149     if( rc==SQLITE_OK && bMatch ){
9150       sqlite3_finalize(pIdxList);
9151       return 1;
9152     }
9153   }
9154   idxFinalize(&rc, pIdxList);
9155
9156   *pRc = rc;
9157   return 0;
9158 }
9159
9160 static int idxCreateFromCons(
9161   sqlite3expert *p,
9162   IdxScan *pScan,
9163   IdxConstraint *pEq, 
9164   IdxConstraint *pTail
9165 ){
9166   sqlite3 *dbm = p->dbm;
9167   int rc = SQLITE_OK;
9168   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
9169     IdxTable *pTab = pScan->pTab;
9170     char *zCols = 0;
9171     char *zIdx = 0;
9172     IdxConstraint *pCons;
9173     unsigned int h = 0;
9174     const char *zFmt;
9175
9176     for(pCons=pEq; pCons; pCons=pCons->pLink){
9177       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
9178     }
9179     for(pCons=pTail; pCons; pCons=pCons->pLink){
9180       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
9181     }
9182
9183     if( rc==SQLITE_OK ){
9184       /* Hash the list of columns to come up with a name for the index */
9185       const char *zTable = pScan->pTab->zName;
9186       char *zName;                /* Index name */
9187       int i;
9188       for(i=0; zCols[i]; i++){
9189         h += ((h<<3) + zCols[i]);
9190       }
9191       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
9192       if( zName==0 ){ 
9193         rc = SQLITE_NOMEM;
9194       }else{
9195         if( idxIdentifierRequiresQuotes(zTable) ){
9196           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
9197         }else{
9198           zFmt = "CREATE INDEX %s ON %s(%s)";
9199         }
9200         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
9201         if( !zIdx ){
9202           rc = SQLITE_NOMEM;
9203         }else{
9204           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
9205           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
9206         }
9207         sqlite3_free(zName);
9208         sqlite3_free(zIdx);
9209       }
9210     }
9211
9212     sqlite3_free(zCols);
9213   }
9214   return rc;
9215 }
9216
9217 /*
9218 ** Return true if list pList (linked by IdxConstraint.pLink) contains
9219 ** a constraint compatible with *p. Otherwise return false.
9220 */
9221 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
9222   IdxConstraint *pCmp;
9223   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
9224     if( p->iCol==pCmp->iCol ) return 1;
9225   }
9226   return 0;
9227 }
9228
9229 static int idxCreateFromWhere(
9230   sqlite3expert *p, 
9231   IdxScan *pScan,                 /* Create indexes for this scan */
9232   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
9233 ){
9234   IdxConstraint *p1 = 0;
9235   IdxConstraint *pCon;
9236   int rc;
9237
9238   /* Gather up all the == constraints. */
9239   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
9240     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
9241       pCon->pLink = p1;
9242       p1 = pCon;
9243     }
9244   }
9245
9246   /* Create an index using the == constraints collected above. And the
9247   ** range constraint/ORDER BY terms passed in by the caller, if any. */
9248   rc = idxCreateFromCons(p, pScan, p1, pTail);
9249
9250   /* If no range/ORDER BY passed by the caller, create a version of the
9251   ** index for each range constraint.  */
9252   if( pTail==0 ){
9253     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
9254       assert( pCon->pLink==0 );
9255       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
9256         rc = idxCreateFromCons(p, pScan, p1, pCon);
9257       }
9258     }
9259   }
9260
9261   return rc;
9262 }
9263
9264 /*
9265 ** Create candidate indexes in database [dbm] based on the data in 
9266 ** linked-list pScan.
9267 */
9268 static int idxCreateCandidates(sqlite3expert *p){
9269   int rc = SQLITE_OK;
9270   IdxScan *pIter;
9271
9272   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
9273     rc = idxCreateFromWhere(p, pIter, 0);
9274     if( rc==SQLITE_OK && pIter->pOrder ){
9275       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
9276     }
9277   }
9278
9279   return rc;
9280 }
9281
9282 /*
9283 ** Free all elements of the linked list starting at pConstraint.
9284 */
9285 static void idxConstraintFree(IdxConstraint *pConstraint){
9286   IdxConstraint *pNext;
9287   IdxConstraint *p;
9288
9289   for(p=pConstraint; p; p=pNext){
9290     pNext = p->pNext;
9291     sqlite3_free(p);
9292   }
9293 }
9294
9295 /*
9296 ** Free all elements of the linked list starting from pScan up until pLast
9297 ** (pLast is not freed).
9298 */
9299 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
9300   IdxScan *p;
9301   IdxScan *pNext;
9302   for(p=pScan; p!=pLast; p=pNext){
9303     pNext = p->pNextScan;
9304     idxConstraintFree(p->pOrder);
9305     idxConstraintFree(p->pEq);
9306     idxConstraintFree(p->pRange);
9307     sqlite3_free(p);
9308   }
9309 }
9310
9311 /*
9312 ** Free all elements of the linked list starting from pStatement up 
9313 ** until pLast (pLast is not freed).
9314 */
9315 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
9316   IdxStatement *p;
9317   IdxStatement *pNext;
9318   for(p=pStatement; p!=pLast; p=pNext){
9319     pNext = p->pNext;
9320     sqlite3_free(p->zEQP);
9321     sqlite3_free(p->zIdx);
9322     sqlite3_free(p);
9323   }
9324 }
9325
9326 /*
9327 ** Free the linked list of IdxTable objects starting at pTab.
9328 */
9329 static void idxTableFree(IdxTable *pTab){
9330   IdxTable *pIter;
9331   IdxTable *pNext;
9332   for(pIter=pTab; pIter; pIter=pNext){
9333     pNext = pIter->pNext;
9334     sqlite3_free(pIter);
9335   }
9336 }
9337
9338 /*
9339 ** Free the linked list of IdxWrite objects starting at pTab.
9340 */
9341 static void idxWriteFree(IdxWrite *pTab){
9342   IdxWrite *pIter;
9343   IdxWrite *pNext;
9344   for(pIter=pTab; pIter; pIter=pNext){
9345     pNext = pIter->pNext;
9346     sqlite3_free(pIter);
9347   }
9348 }
9349
9350
9351
9352 /*
9353 ** This function is called after candidate indexes have been created. It
9354 ** runs all the queries to see which indexes they prefer, and populates
9355 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
9356 */
9357 int idxFindIndexes(
9358   sqlite3expert *p,
9359   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
9360 ){
9361   IdxStatement *pStmt;
9362   sqlite3 *dbm = p->dbm;
9363   int rc = SQLITE_OK;
9364
9365   IdxHash hIdx;
9366   idxHashInit(&hIdx);
9367
9368   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
9369     IdxHashEntry *pEntry;
9370     sqlite3_stmt *pExplain = 0;
9371     idxHashClear(&hIdx);
9372     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
9373         "EXPLAIN QUERY PLAN %s", pStmt->zSql
9374     );
9375     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
9376       /* int iId = sqlite3_column_int(pExplain, 0); */
9377       /* int iParent = sqlite3_column_int(pExplain, 1); */
9378       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
9379       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
9380       int nDetail;
9381       int i;
9382
9383       if( !zDetail ) continue;
9384       nDetail = STRLEN(zDetail);
9385
9386       for(i=0; i<nDetail; i++){
9387         const char *zIdx = 0;
9388         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
9389           zIdx = &zDetail[i+13];
9390         }else if( i+22<nDetail 
9391             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 
9392         ){
9393           zIdx = &zDetail[i+22];
9394         }
9395         if( zIdx ){
9396           const char *zSql;
9397           int nIdx = 0;
9398           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
9399             nIdx++;
9400           }
9401           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
9402           if( zSql ){
9403             idxHashAdd(&rc, &hIdx, zSql, 0);
9404             if( rc ) goto find_indexes_out;
9405           }
9406           break;
9407         }
9408       }
9409
9410       if( zDetail[0]!='-' ){
9411         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
9412       }
9413     }
9414
9415     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
9416       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
9417     }
9418
9419     idxFinalize(&rc, pExplain);
9420   }
9421
9422  find_indexes_out:
9423   idxHashClear(&hIdx);
9424   return rc;
9425 }
9426
9427 static int idxAuthCallback(
9428   void *pCtx,
9429   int eOp,
9430   const char *z3,
9431   const char *z4,
9432   const char *zDb,
9433   const char *zTrigger
9434 ){
9435   int rc = SQLITE_OK;
9436   (void)z4;
9437   (void)zTrigger;
9438   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
9439     if( sqlite3_stricmp(zDb, "main")==0 ){
9440       sqlite3expert *p = (sqlite3expert*)pCtx;
9441       IdxTable *pTab;
9442       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
9443         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
9444       }
9445       if( pTab ){
9446         IdxWrite *pWrite;
9447         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
9448           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
9449         }
9450         if( pWrite==0 ){
9451           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
9452           if( rc==SQLITE_OK ){
9453             pWrite->pTab = pTab;
9454             pWrite->eOp = eOp;
9455             pWrite->pNext = p->pWrite;
9456             p->pWrite = pWrite;
9457           }
9458         }
9459       }
9460     }
9461   }
9462   return rc;
9463 }
9464
9465 static int idxProcessOneTrigger(
9466   sqlite3expert *p, 
9467   IdxWrite *pWrite, 
9468   char **pzErr
9469 ){
9470   static const char *zInt = UNIQUE_TABLE_NAME;
9471   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
9472   IdxTable *pTab = pWrite->pTab;
9473   const char *zTab = pTab->zName;
9474   const char *zSql = 
9475     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
9476     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
9477     "ORDER BY type;";
9478   sqlite3_stmt *pSelect = 0;
9479   int rc = SQLITE_OK;
9480   char *zWrite = 0;
9481
9482   /* Create the table and its triggers in the temp schema */
9483   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
9484   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
9485     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
9486     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
9487   }
9488   idxFinalize(&rc, pSelect);
9489
9490   /* Rename the table in the temp schema to zInt */
9491   if( rc==SQLITE_OK ){
9492     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
9493     if( z==0 ){
9494       rc = SQLITE_NOMEM;
9495     }else{
9496       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
9497       sqlite3_free(z);
9498     }
9499   }
9500
9501   switch( pWrite->eOp ){
9502     case SQLITE_INSERT: {
9503       int i;
9504       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
9505       for(i=0; i<pTab->nCol; i++){
9506         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
9507       }
9508       zWrite = idxAppendText(&rc, zWrite, ")");
9509       break;
9510     }
9511     case SQLITE_UPDATE: {
9512       int i;
9513       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
9514       for(i=0; i<pTab->nCol; i++){
9515         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", 
9516             pTab->aCol[i].zName
9517         );
9518       }
9519       break;
9520     }
9521     default: {
9522       assert( pWrite->eOp==SQLITE_DELETE );
9523       if( rc==SQLITE_OK ){
9524         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
9525         if( zWrite==0 ) rc = SQLITE_NOMEM;
9526       }
9527     }
9528   }
9529
9530   if( rc==SQLITE_OK ){
9531     sqlite3_stmt *pX = 0;
9532     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
9533     idxFinalize(&rc, pX);
9534     if( rc!=SQLITE_OK ){
9535       idxDatabaseError(p->dbv, pzErr);
9536     }
9537   }
9538   sqlite3_free(zWrite);
9539
9540   if( rc==SQLITE_OK ){
9541     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
9542   }
9543
9544   return rc;
9545 }
9546
9547 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
9548   int rc = SQLITE_OK;
9549   IdxWrite *pEnd = 0;
9550   IdxWrite *pFirst = p->pWrite;
9551
9552   while( rc==SQLITE_OK && pFirst!=pEnd ){
9553     IdxWrite *pIter;
9554     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
9555       rc = idxProcessOneTrigger(p, pIter, pzErr);
9556     }
9557     pEnd = pFirst;
9558     pFirst = p->pWrite;
9559   }
9560
9561   return rc;
9562 }
9563
9564
9565 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
9566   int rc = idxRegisterVtab(p);
9567   sqlite3_stmt *pSchema = 0;
9568
9569   /* For each table in the main db schema:
9570   **
9571   **   1) Add an entry to the p->pTable list, and
9572   **   2) Create the equivalent virtual table in dbv.
9573   */
9574   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
9575       "SELECT type, name, sql, 1 FROM sqlite_schema "
9576       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
9577       " UNION ALL "
9578       "SELECT type, name, sql, 2 FROM sqlite_schema "
9579       "WHERE type = 'trigger'"
9580       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
9581       "ORDER BY 4, 1"
9582   );
9583   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
9584     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
9585     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
9586     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
9587
9588     if( zType[0]=='v' || zType[1]=='r' ){
9589       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
9590     }else{
9591       IdxTable *pTab;
9592       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
9593       if( rc==SQLITE_OK ){
9594         int i;
9595         char *zInner = 0;
9596         char *zOuter = 0;
9597         pTab->pNext = p->pTable;
9598         p->pTable = pTab;
9599
9600         /* The statement the vtab will pass to sqlite3_declare_vtab() */
9601         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
9602         for(i=0; i<pTab->nCol; i++){
9603           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", 
9604               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
9605           );
9606         }
9607         zInner = idxAppendText(&rc, zInner, ")");
9608
9609         /* The CVT statement to create the vtab */
9610         zOuter = idxAppendText(&rc, 0, 
9611             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
9612         );
9613         if( rc==SQLITE_OK ){
9614           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
9615         }
9616         sqlite3_free(zInner);
9617         sqlite3_free(zOuter);
9618       }
9619     }
9620   }
9621   idxFinalize(&rc, pSchema);
9622   return rc;
9623 }
9624
9625 struct IdxSampleCtx {
9626   int iTarget;
9627   double target;                  /* Target nRet/nRow value */
9628   double nRow;                    /* Number of rows seen */
9629   double nRet;                    /* Number of rows returned */
9630 };
9631
9632 static void idxSampleFunc(
9633   sqlite3_context *pCtx,
9634   int argc,
9635   sqlite3_value **argv
9636 ){
9637   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
9638   int bRet;
9639
9640   (void)argv;
9641   assert( argc==0 );
9642   if( p->nRow==0.0 ){
9643     bRet = 1;
9644   }else{
9645     bRet = (p->nRet / p->nRow) <= p->target;
9646     if( bRet==0 ){
9647       unsigned short rnd;
9648       sqlite3_randomness(2, (void*)&rnd);
9649       bRet = ((int)rnd % 100) <= p->iTarget;
9650     }
9651   }
9652
9653   sqlite3_result_int(pCtx, bRet);
9654   p->nRow += 1.0;
9655   p->nRet += (double)bRet;
9656 }
9657
9658 struct IdxRemCtx {
9659   int nSlot;
9660   struct IdxRemSlot {
9661     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
9662     i64 iVal;                     /* SQLITE_INTEGER value */
9663     double rVal;                  /* SQLITE_FLOAT value */
9664     int nByte;                    /* Bytes of space allocated at z */
9665     int n;                        /* Size of buffer z */
9666     char *z;                      /* SQLITE_TEXT/BLOB value */
9667   } aSlot[1];
9668 };
9669
9670 /*
9671 ** Implementation of scalar function rem().
9672 */
9673 static void idxRemFunc(
9674   sqlite3_context *pCtx,
9675   int argc,
9676   sqlite3_value **argv
9677 ){
9678   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
9679   struct IdxRemSlot *pSlot;
9680   int iSlot;
9681   assert( argc==2 );
9682
9683   iSlot = sqlite3_value_int(argv[0]);
9684   assert( iSlot<=p->nSlot );
9685   pSlot = &p->aSlot[iSlot];
9686
9687   switch( pSlot->eType ){
9688     case SQLITE_NULL:
9689       /* no-op */
9690       break;
9691
9692     case SQLITE_INTEGER:
9693       sqlite3_result_int64(pCtx, pSlot->iVal);
9694       break;
9695
9696     case SQLITE_FLOAT:
9697       sqlite3_result_double(pCtx, pSlot->rVal);
9698       break;
9699
9700     case SQLITE_BLOB:
9701       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
9702       break;
9703
9704     case SQLITE_TEXT:
9705       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
9706       break;
9707   }
9708
9709   pSlot->eType = sqlite3_value_type(argv[1]);
9710   switch( pSlot->eType ){
9711     case SQLITE_NULL:
9712       /* no-op */
9713       break;
9714
9715     case SQLITE_INTEGER:
9716       pSlot->iVal = sqlite3_value_int64(argv[1]);
9717       break;
9718
9719     case SQLITE_FLOAT:
9720       pSlot->rVal = sqlite3_value_double(argv[1]);
9721       break;
9722
9723     case SQLITE_BLOB:
9724     case SQLITE_TEXT: {
9725       int nByte = sqlite3_value_bytes(argv[1]);
9726       if( nByte>pSlot->nByte ){
9727         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
9728         if( zNew==0 ){
9729           sqlite3_result_error_nomem(pCtx);
9730           return;
9731         }
9732         pSlot->nByte = nByte*2;
9733         pSlot->z = zNew;
9734       }
9735       pSlot->n = nByte;
9736       if( pSlot->eType==SQLITE_BLOB ){
9737         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
9738       }else{
9739         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
9740       }
9741       break;
9742     }
9743   }
9744 }
9745
9746 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
9747   int rc = SQLITE_OK;
9748   const char *zMax = 
9749     "SELECT max(i.seqno) FROM "
9750     "  sqlite_schema AS s, "
9751     "  pragma_index_list(s.name) AS l, "
9752     "  pragma_index_info(l.name) AS i "
9753     "WHERE s.type = 'table'";
9754   sqlite3_stmt *pMax = 0;
9755
9756   *pnMax = 0;
9757   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
9758   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
9759     *pnMax = sqlite3_column_int(pMax, 0) + 1;
9760   }
9761   idxFinalize(&rc, pMax);
9762
9763   return rc;
9764 }
9765
9766 static int idxPopulateOneStat1(
9767   sqlite3expert *p,
9768   sqlite3_stmt *pIndexXInfo,
9769   sqlite3_stmt *pWriteStat,
9770   const char *zTab,
9771   const char *zIdx,
9772   char **pzErr
9773 ){
9774   char *zCols = 0;
9775   char *zOrder = 0;
9776   char *zQuery = 0;
9777   int nCol = 0;
9778   int i;
9779   sqlite3_stmt *pQuery = 0;
9780   int *aStat = 0;
9781   int rc = SQLITE_OK;
9782
9783   assert( p->iSample>0 );
9784
9785   /* Formulate the query text */
9786   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
9787   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
9788     const char *zComma = zCols==0 ? "" : ", ";
9789     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
9790     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
9791     zCols = idxAppendText(&rc, zCols, 
9792         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
9793     );
9794     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
9795   }
9796   sqlite3_reset(pIndexXInfo);
9797   if( rc==SQLITE_OK ){
9798     if( p->iSample==100 ){
9799       zQuery = sqlite3_mprintf(
9800           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
9801       );
9802     }else{
9803       zQuery = sqlite3_mprintf(
9804           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
9805       );
9806     }
9807   }
9808   sqlite3_free(zCols);
9809   sqlite3_free(zOrder);
9810
9811   /* Formulate the query text */
9812   if( rc==SQLITE_OK ){
9813     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
9814     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
9815   }
9816   sqlite3_free(zQuery);
9817
9818   if( rc==SQLITE_OK ){
9819     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
9820   }
9821   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
9822     IdxHashEntry *pEntry;
9823     char *zStat = 0;
9824     for(i=0; i<=nCol; i++) aStat[i] = 1;
9825     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
9826       aStat[0]++;
9827       for(i=0; i<nCol; i++){
9828         if( sqlite3_column_int(pQuery, i)==0 ) break;
9829       }
9830       for(/*no-op*/; i<nCol; i++){
9831         aStat[i+1]++;
9832       }
9833     }
9834
9835     if( rc==SQLITE_OK ){
9836       int s0 = aStat[0];
9837       zStat = sqlite3_mprintf("%d", s0);
9838       if( zStat==0 ) rc = SQLITE_NOMEM;
9839       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
9840         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
9841       }
9842     }
9843
9844     if( rc==SQLITE_OK ){
9845       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
9846       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
9847       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
9848       sqlite3_step(pWriteStat);
9849       rc = sqlite3_reset(pWriteStat);
9850     }
9851
9852     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
9853     if( pEntry ){
9854       assert( pEntry->zVal2==0 );
9855       pEntry->zVal2 = zStat;
9856     }else{
9857       sqlite3_free(zStat);
9858     }
9859   }
9860   sqlite3_free(aStat);
9861   idxFinalize(&rc, pQuery);
9862
9863   return rc;
9864 }
9865
9866 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
9867   int rc;
9868   char *zSql;
9869
9870   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
9871   if( rc!=SQLITE_OK ) return rc;
9872
9873   zSql = sqlite3_mprintf(
9874       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
9875   );
9876   if( zSql==0 ) return SQLITE_NOMEM;
9877   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
9878   sqlite3_free(zSql);
9879
9880   return rc;
9881 }
9882
9883 /*
9884 ** This function is called as part of sqlite3_expert_analyze(). Candidate
9885 ** indexes have already been created in database sqlite3expert.dbm, this
9886 ** function populates sqlite_stat1 table in the same database.
9887 **
9888 ** The stat1 data is generated by querying the 
9889 */
9890 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
9891   int rc = SQLITE_OK;
9892   int nMax =0;
9893   struct IdxRemCtx *pCtx = 0;
9894   struct IdxSampleCtx samplectx; 
9895   int i;
9896   i64 iPrev = -100000;
9897   sqlite3_stmt *pAllIndex = 0;
9898   sqlite3_stmt *pIndexXInfo = 0;
9899   sqlite3_stmt *pWrite = 0;
9900
9901   const char *zAllIndex =
9902     "SELECT s.rowid, s.name, l.name FROM "
9903     "  sqlite_schema AS s, "
9904     "  pragma_index_list(s.name) AS l "
9905     "WHERE s.type = 'table'";
9906   const char *zIndexXInfo = 
9907     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
9908   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
9909
9910   /* If iSample==0, no sqlite_stat1 data is required. */
9911   if( p->iSample==0 ) return SQLITE_OK;
9912
9913   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
9914   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
9915
9916   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
9917
9918   if( rc==SQLITE_OK ){
9919     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
9920     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
9921   }
9922
9923   if( rc==SQLITE_OK ){
9924     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
9925     rc = sqlite3_create_function(
9926         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
9927     );
9928   }
9929   if( rc==SQLITE_OK ){
9930     rc = sqlite3_create_function(
9931         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
9932     );
9933   }
9934
9935   if( rc==SQLITE_OK ){
9936     pCtx->nSlot = nMax+1;
9937     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
9938   }
9939   if( rc==SQLITE_OK ){
9940     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
9941   }
9942   if( rc==SQLITE_OK ){
9943     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
9944   }
9945
9946   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
9947     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
9948     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
9949     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
9950     if( p->iSample<100 && iPrev!=iRowid ){
9951       samplectx.target = (double)p->iSample / 100.0;
9952       samplectx.iTarget = p->iSample;
9953       samplectx.nRow = 0.0;
9954       samplectx.nRet = 0.0;
9955       rc = idxBuildSampleTable(p, zTab);
9956       if( rc!=SQLITE_OK ) break;
9957     }
9958     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
9959     iPrev = iRowid;
9960   }
9961   if( rc==SQLITE_OK && p->iSample<100 ){
9962     rc = sqlite3_exec(p->dbv, 
9963         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
9964     );
9965   }
9966
9967   idxFinalize(&rc, pAllIndex);
9968   idxFinalize(&rc, pIndexXInfo);
9969   idxFinalize(&rc, pWrite);
9970
9971   for(i=0; i<pCtx->nSlot; i++){
9972     sqlite3_free(pCtx->aSlot[i].z);
9973   }
9974   sqlite3_free(pCtx);
9975
9976   if( rc==SQLITE_OK ){
9977     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
9978   }
9979
9980   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
9981   return rc;
9982 }
9983
9984 /*
9985 ** Allocate a new sqlite3expert object.
9986 */
9987 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
9988   int rc = SQLITE_OK;
9989   sqlite3expert *pNew;
9990
9991   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
9992
9993   /* Open two in-memory databases to work with. The "vtab database" (dbv)
9994   ** will contain a virtual table corresponding to each real table in
9995   ** the user database schema, and a copy of each view. It is used to
9996   ** collect information regarding the WHERE, ORDER BY and other clauses
9997   ** of the user's query.
9998   */
9999   if( rc==SQLITE_OK ){
10000     pNew->db = db;
10001     pNew->iSample = 100;
10002     rc = sqlite3_open(":memory:", &pNew->dbv);
10003   }
10004   if( rc==SQLITE_OK ){
10005     rc = sqlite3_open(":memory:", &pNew->dbm);
10006     if( rc==SQLITE_OK ){
10007       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
10008     }
10009   }
10010   
10011
10012   /* Copy the entire schema of database [db] into [dbm]. */
10013   if( rc==SQLITE_OK ){
10014     sqlite3_stmt *pSql;
10015     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, 
10016         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
10017         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
10018     );
10019     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
10020       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
10021       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
10022     }
10023     idxFinalize(&rc, pSql);
10024   }
10025
10026   /* Create the vtab schema */
10027   if( rc==SQLITE_OK ){
10028     rc = idxCreateVtabSchema(pNew, pzErrmsg);
10029   }
10030
10031   /* Register the auth callback with dbv */
10032   if( rc==SQLITE_OK ){
10033     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
10034   }
10035
10036   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
10037   ** return the new sqlite3expert handle.  */
10038   if( rc!=SQLITE_OK ){
10039     sqlite3_expert_destroy(pNew);
10040     pNew = 0;
10041   }
10042   return pNew;
10043 }
10044
10045 /*
10046 ** Configure an sqlite3expert object.
10047 */
10048 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
10049   int rc = SQLITE_OK;
10050   va_list ap;
10051   va_start(ap, op);
10052   switch( op ){
10053     case EXPERT_CONFIG_SAMPLE: {
10054       int iVal = va_arg(ap, int);
10055       if( iVal<0 ) iVal = 0;
10056       if( iVal>100 ) iVal = 100;
10057       p->iSample = iVal;
10058       break;
10059     }
10060     default:
10061       rc = SQLITE_NOTFOUND;
10062       break;
10063   }
10064
10065   va_end(ap);
10066   return rc;
10067 }
10068
10069 /*
10070 ** Add an SQL statement to the analysis.
10071 */
10072 int sqlite3_expert_sql(
10073   sqlite3expert *p,               /* From sqlite3_expert_new() */
10074   const char *zSql,               /* SQL statement to add */
10075   char **pzErr                    /* OUT: Error message (if any) */
10076 ){
10077   IdxScan *pScanOrig = p->pScan;
10078   IdxStatement *pStmtOrig = p->pStatement;
10079   int rc = SQLITE_OK;
10080   const char *zStmt = zSql;
10081
10082   if( p->bRun ) return SQLITE_MISUSE;
10083
10084   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
10085     sqlite3_stmt *pStmt = 0;
10086     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
10087     if( rc==SQLITE_OK ){
10088       if( pStmt ){
10089         IdxStatement *pNew;
10090         const char *z = sqlite3_sql(pStmt);
10091         int n = STRLEN(z);
10092         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
10093         if( rc==SQLITE_OK ){
10094           pNew->zSql = (char*)&pNew[1];
10095           memcpy(pNew->zSql, z, n+1);
10096           pNew->pNext = p->pStatement;
10097           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
10098           p->pStatement = pNew;
10099         }
10100         sqlite3_finalize(pStmt);
10101       }
10102     }else{
10103       idxDatabaseError(p->dbv, pzErr);
10104     }
10105   }
10106
10107   if( rc!=SQLITE_OK ){
10108     idxScanFree(p->pScan, pScanOrig);
10109     idxStatementFree(p->pStatement, pStmtOrig);
10110     p->pScan = pScanOrig;
10111     p->pStatement = pStmtOrig;
10112   }
10113
10114   return rc;
10115 }
10116
10117 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
10118   int rc;
10119   IdxHashEntry *pEntry;
10120
10121   /* Do trigger processing to collect any extra IdxScan structures */
10122   rc = idxProcessTriggers(p, pzErr);
10123
10124   /* Create candidate indexes within the in-memory database file */
10125   if( rc==SQLITE_OK ){
10126     rc = idxCreateCandidates(p);
10127   }
10128
10129   /* Generate the stat1 data */
10130   if( rc==SQLITE_OK ){
10131     rc = idxPopulateStat1(p, pzErr);
10132   }
10133
10134   /* Formulate the EXPERT_REPORT_CANDIDATES text */
10135   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
10136     p->zCandidates = idxAppendText(&rc, p->zCandidates, 
10137         "%s;%s%s\n", pEntry->zVal, 
10138         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
10139     );
10140   }
10141
10142   /* Figure out which of the candidate indexes are preferred by the query
10143   ** planner and report the results to the user.  */
10144   if( rc==SQLITE_OK ){
10145     rc = idxFindIndexes(p, pzErr);
10146   }
10147
10148   if( rc==SQLITE_OK ){
10149     p->bRun = 1;
10150   }
10151   return rc;
10152 }
10153
10154 /*
10155 ** Return the total number of statements that have been added to this
10156 ** sqlite3expert using sqlite3_expert_sql().
10157 */
10158 int sqlite3_expert_count(sqlite3expert *p){
10159   int nRet = 0;
10160   if( p->pStatement ) nRet = p->pStatement->iId+1;
10161   return nRet;
10162 }
10163
10164 /*
10165 ** Return a component of the report.
10166 */
10167 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
10168   const char *zRet = 0;
10169   IdxStatement *pStmt;
10170
10171   if( p->bRun==0 ) return 0;
10172   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
10173   switch( eReport ){
10174     case EXPERT_REPORT_SQL:
10175       if( pStmt ) zRet = pStmt->zSql;
10176       break;
10177     case EXPERT_REPORT_INDEXES:
10178       if( pStmt ) zRet = pStmt->zIdx;
10179       break;
10180     case EXPERT_REPORT_PLAN:
10181       if( pStmt ) zRet = pStmt->zEQP;
10182       break;
10183     case EXPERT_REPORT_CANDIDATES:
10184       zRet = p->zCandidates;
10185       break;
10186   }
10187   return zRet;
10188 }
10189
10190 /*
10191 ** Free an sqlite3expert object.
10192 */
10193 void sqlite3_expert_destroy(sqlite3expert *p){
10194   if( p ){
10195     sqlite3_close(p->dbm);
10196     sqlite3_close(p->dbv);
10197     idxScanFree(p->pScan, 0);
10198     idxStatementFree(p->pStatement, 0);
10199     idxTableFree(p->pTable);
10200     idxWriteFree(p->pWrite);
10201     idxHashClear(&p->hIdx);
10202     sqlite3_free(p->zCandidates);
10203     sqlite3_free(p);
10204   }
10205 }
10206
10207 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
10208
10209 /************************* End ../ext/expert/sqlite3expert.c ********************/
10210
10211 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
10212 /************************* Begin ../ext/misc/dbdata.c ******************/
10213 /*
10214 ** 2019-04-17
10215 **
10216 ** The author disclaims copyright to this source code.  In place of
10217 ** a legal notice, here is a blessing:
10218 **
10219 **    May you do good and not evil.
10220 **    May you find forgiveness for yourself and forgive others.
10221 **    May you share freely, never taking more than you give.
10222 **
10223 ******************************************************************************
10224 **
10225 ** This file contains an implementation of two eponymous virtual tables,
10226 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
10227 ** "sqlite_dbpage" eponymous virtual table be available.
10228 **
10229 ** SQLITE_DBDATA:
10230 **   sqlite_dbdata is used to extract data directly from a database b-tree
10231 **   page and its associated overflow pages, bypassing the b-tree layer.
10232 **   The table schema is equivalent to:
10233 **
10234 **     CREATE TABLE sqlite_dbdata(
10235 **       pgno INTEGER,
10236 **       cell INTEGER,
10237 **       field INTEGER,
10238 **       value ANY,
10239 **       schema TEXT HIDDEN
10240 **     );
10241 **
10242 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
10243 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
10244 **   "schema".
10245 **
10246 **   Each page of the database is inspected. If it cannot be interpreted as
10247 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
10248 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
10249 **   table contains one row for each field in the record associated with
10250 **   each cell on the page. For intkey b-trees, the key value is stored in
10251 **   field -1.
10252 **
10253 **   For example, for the database:
10254 **
10255 **     CREATE TABLE t1(a, b);     -- root page is page 2
10256 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
10257 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
10258 **
10259 **   the sqlite_dbdata table contains, as well as from entries related to 
10260 **   page 1, content equivalent to:
10261 **
10262 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
10263 **         (2, 0, -1, 5     ),
10264 **         (2, 0,  0, 'v'   ),
10265 **         (2, 0,  1, 'five'),
10266 **         (2, 1, -1, 10    ),
10267 **         (2, 1,  0, 'x'   ),
10268 **         (2, 1,  1, 'ten' );
10269 **
10270 **   If database corruption is encountered, this module does not report an
10271 **   error. Instead, it attempts to extract as much data as possible and
10272 **   ignores the corruption.
10273 **
10274 ** SQLITE_DBPTR:
10275 **   The sqlite_dbptr table has the following schema:
10276 **
10277 **     CREATE TABLE sqlite_dbptr(
10278 **       pgno INTEGER,
10279 **       child INTEGER,
10280 **       schema TEXT HIDDEN
10281 **     );
10282 **
10283 **   It contains one entry for each b-tree pointer between a parent and
10284 **   child page in the database.
10285 */
10286 #if !defined(SQLITEINT_H) 
10287 /* #include "sqlite3ext.h" */
10288
10289 /* typedef unsigned char u8; */
10290
10291 #endif
10292 SQLITE_EXTENSION_INIT1
10293 #include <string.h>
10294 #include <assert.h>
10295
10296 #define DBDATA_PADDING_BYTES 100 
10297
10298 typedef struct DbdataTable DbdataTable;
10299 typedef struct DbdataCursor DbdataCursor;
10300
10301 /* Cursor object */
10302 struct DbdataCursor {
10303   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
10304   sqlite3_stmt *pStmt;            /* For fetching database pages */
10305
10306   int iPgno;                      /* Current page number */
10307   u8 *aPage;                      /* Buffer containing page */
10308   int nPage;                      /* Size of aPage[] in bytes */
10309   int nCell;                      /* Number of cells on aPage[] */
10310   int iCell;                      /* Current cell number */
10311   int bOnePage;                   /* True to stop after one page */
10312   int szDb;
10313   sqlite3_int64 iRowid;
10314
10315   /* Only for the sqlite_dbdata table */
10316   u8 *pRec;                       /* Buffer containing current record */
10317   int nRec;                       /* Size of pRec[] in bytes */
10318   int nHdr;                       /* Size of header in bytes */
10319   int iField;                     /* Current field number */
10320   u8 *pHdrPtr;
10321   u8 *pPtr;
10322   
10323   sqlite3_int64 iIntkey;          /* Integer key value */
10324 };
10325
10326 /* Table object */
10327 struct DbdataTable {
10328   sqlite3_vtab base;              /* Base class.  Must be first */
10329   sqlite3 *db;                    /* The database connection */
10330   sqlite3_stmt *pStmt;            /* For fetching database pages */
10331   int bPtr;                       /* True for sqlite3_dbptr table */
10332 };
10333
10334 /* Column and schema definitions for sqlite_dbdata */
10335 #define DBDATA_COLUMN_PGNO        0
10336 #define DBDATA_COLUMN_CELL        1
10337 #define DBDATA_COLUMN_FIELD       2
10338 #define DBDATA_COLUMN_VALUE       3
10339 #define DBDATA_COLUMN_SCHEMA      4
10340 #define DBDATA_SCHEMA             \
10341       "CREATE TABLE x("           \
10342       "  pgno INTEGER,"           \
10343       "  cell INTEGER,"           \
10344       "  field INTEGER,"          \
10345       "  value ANY,"              \
10346       "  schema TEXT HIDDEN"      \
10347       ")"
10348
10349 /* Column and schema definitions for sqlite_dbptr */
10350 #define DBPTR_COLUMN_PGNO         0
10351 #define DBPTR_COLUMN_CHILD        1
10352 #define DBPTR_COLUMN_SCHEMA       2
10353 #define DBPTR_SCHEMA              \
10354       "CREATE TABLE x("           \
10355       "  pgno INTEGER,"           \
10356       "  child INTEGER,"          \
10357       "  schema TEXT HIDDEN"      \
10358       ")"
10359
10360 /*
10361 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual 
10362 ** table.
10363 */
10364 static int dbdataConnect(
10365   sqlite3 *db,
10366   void *pAux,
10367   int argc, const char *const*argv,
10368   sqlite3_vtab **ppVtab,
10369   char **pzErr
10370 ){
10371   DbdataTable *pTab = 0;
10372   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
10373
10374   if( rc==SQLITE_OK ){
10375     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
10376     if( pTab==0 ){
10377       rc = SQLITE_NOMEM;
10378     }else{
10379       memset(pTab, 0, sizeof(DbdataTable));
10380       pTab->db = db;
10381       pTab->bPtr = (pAux!=0);
10382     }
10383   }
10384
10385   *ppVtab = (sqlite3_vtab*)pTab;
10386   return rc;
10387 }
10388
10389 /*
10390 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
10391 */
10392 static int dbdataDisconnect(sqlite3_vtab *pVtab){
10393   DbdataTable *pTab = (DbdataTable*)pVtab;
10394   if( pTab ){
10395     sqlite3_finalize(pTab->pStmt);
10396     sqlite3_free(pVtab);
10397   }
10398   return SQLITE_OK;
10399 }
10400
10401 /*
10402 ** This function interprets two types of constraints:
10403 **
10404 **       schema=?
10405 **       pgno=?
10406 **
10407 ** If neither are present, idxNum is set to 0. If schema=? is present,
10408 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
10409 ** in idxNum is set.
10410 **
10411 ** If both parameters are present, schema is in position 0 and pgno in
10412 ** position 1.
10413 */
10414 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
10415   DbdataTable *pTab = (DbdataTable*)tab;
10416   int i;
10417   int iSchema = -1;
10418   int iPgno = -1;
10419   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
10420
10421   for(i=0; i<pIdx->nConstraint; i++){
10422     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
10423     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10424       if( p->iColumn==colSchema ){
10425         if( p->usable==0 ) return SQLITE_CONSTRAINT;
10426         iSchema = i;
10427       }
10428       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
10429         iPgno = i;
10430       }
10431     }
10432   }
10433
10434   if( iSchema>=0 ){
10435     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
10436     pIdx->aConstraintUsage[iSchema].omit = 1;
10437   }
10438   if( iPgno>=0 ){
10439     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
10440     pIdx->aConstraintUsage[iPgno].omit = 1;
10441     pIdx->estimatedCost = 100;
10442     pIdx->estimatedRows =  50;
10443
10444     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
10445       int iCol = pIdx->aOrderBy[0].iColumn;
10446       if( pIdx->nOrderBy==1 ){
10447         pIdx->orderByConsumed = (iCol==0 || iCol==1);
10448       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
10449         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
10450       }
10451     }
10452
10453   }else{
10454     pIdx->estimatedCost = 100000000;
10455     pIdx->estimatedRows = 1000000000;
10456   }
10457   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
10458   return SQLITE_OK;
10459 }
10460
10461 /*
10462 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
10463 */
10464 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
10465   DbdataCursor *pCsr;
10466
10467   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
10468   if( pCsr==0 ){
10469     return SQLITE_NOMEM;
10470   }else{
10471     memset(pCsr, 0, sizeof(DbdataCursor));
10472     pCsr->base.pVtab = pVTab;
10473   }
10474
10475   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
10476   return SQLITE_OK;
10477 }
10478
10479 /*
10480 ** Restore a cursor object to the state it was in when first allocated 
10481 ** by dbdataOpen().
10482 */
10483 static void dbdataResetCursor(DbdataCursor *pCsr){
10484   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
10485   if( pTab->pStmt==0 ){
10486     pTab->pStmt = pCsr->pStmt;
10487   }else{
10488     sqlite3_finalize(pCsr->pStmt);
10489   }
10490   pCsr->pStmt = 0;
10491   pCsr->iPgno = 1;
10492   pCsr->iCell = 0;
10493   pCsr->iField = 0;
10494   pCsr->bOnePage = 0;
10495   sqlite3_free(pCsr->aPage);
10496   sqlite3_free(pCsr->pRec);
10497   pCsr->pRec = 0;
10498   pCsr->aPage = 0;
10499 }
10500
10501 /*
10502 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
10503 */
10504 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
10505   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10506   dbdataResetCursor(pCsr);
10507   sqlite3_free(pCsr);
10508   return SQLITE_OK;
10509 }
10510
10511 /* 
10512 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers. 
10513 */
10514 static unsigned int get_uint16(unsigned char *a){
10515   return (a[0]<<8)|a[1];
10516 }
10517 static unsigned int get_uint32(unsigned char *a){
10518   return ((unsigned int)a[0]<<24)
10519        | ((unsigned int)a[1]<<16)
10520        | ((unsigned int)a[2]<<8)
10521        | ((unsigned int)a[3]);
10522 }
10523
10524 /*
10525 ** Load page pgno from the database via the sqlite_dbpage virtual table.
10526 ** If successful, set (*ppPage) to point to a buffer containing the page
10527 ** data, (*pnPage) to the size of that buffer in bytes and return
10528 ** SQLITE_OK. In this case it is the responsibility of the caller to
10529 ** eventually free the buffer using sqlite3_free().
10530 **
10531 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
10532 ** return an SQLite error code.
10533 */
10534 static int dbdataLoadPage(
10535   DbdataCursor *pCsr,             /* Cursor object */
10536   unsigned int pgno,              /* Page number of page to load */
10537   u8 **ppPage,                    /* OUT: pointer to page buffer */
10538   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
10539 ){
10540   int rc2;
10541   int rc = SQLITE_OK;
10542   sqlite3_stmt *pStmt = pCsr->pStmt;
10543
10544   *ppPage = 0;
10545   *pnPage = 0;
10546   sqlite3_bind_int64(pStmt, 2, pgno);
10547   if( SQLITE_ROW==sqlite3_step(pStmt) ){
10548     int nCopy = sqlite3_column_bytes(pStmt, 0);
10549     if( nCopy>0 ){
10550       u8 *pPage;
10551       pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
10552       if( pPage==0 ){
10553         rc = SQLITE_NOMEM;
10554       }else{
10555         const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
10556         memcpy(pPage, pCopy, nCopy);
10557         memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
10558       }
10559       *ppPage = pPage;
10560       *pnPage = nCopy;
10561     }
10562   }
10563   rc2 = sqlite3_reset(pStmt);
10564   if( rc==SQLITE_OK ) rc = rc2;
10565
10566   return rc;
10567 }
10568
10569 /*
10570 ** Read a varint.  Put the value in *pVal and return the number of bytes.
10571 */
10572 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
10573   sqlite3_int64 v = 0;
10574   int i;
10575   for(i=0; i<8; i++){
10576     v = (v<<7) + (z[i]&0x7f);
10577     if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
10578   }
10579   v = (v<<8) + (z[i]&0xff);
10580   *pVal = v;
10581   return 9;
10582 }
10583
10584 /*
10585 ** Return the number of bytes of space used by an SQLite value of type
10586 ** eType.
10587 */
10588 static int dbdataValueBytes(int eType){
10589   switch( eType ){
10590     case 0: case 8: case 9:
10591     case 10: case 11:
10592       return 0;
10593     case 1:
10594       return 1;
10595     case 2:
10596       return 2;
10597     case 3:
10598       return 3;
10599     case 4:
10600       return 4;
10601     case 5:
10602       return 6;
10603     case 6:
10604     case 7:
10605       return 8;
10606     default:
10607       if( eType>0 ){
10608         return ((eType-12) / 2);
10609       }
10610       return 0;
10611   }
10612 }
10613
10614 /*
10615 ** Load a value of type eType from buffer pData and use it to set the
10616 ** result of context object pCtx.
10617 */
10618 static void dbdataValue(
10619   sqlite3_context *pCtx, 
10620   int eType, 
10621   u8 *pData,
10622   int nData
10623 ){
10624   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
10625     switch( eType ){
10626       case 0: 
10627       case 10: 
10628       case 11: 
10629         sqlite3_result_null(pCtx);
10630         break;
10631       
10632       case 8: 
10633         sqlite3_result_int(pCtx, 0);
10634         break;
10635       case 9:
10636         sqlite3_result_int(pCtx, 1);
10637         break;
10638   
10639       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
10640         sqlite3_uint64 v = (signed char)pData[0];
10641         pData++;
10642         switch( eType ){
10643           case 7:
10644           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
10645           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
10646           case 4:  v = (v<<8) + pData[0];  pData++;
10647           case 3:  v = (v<<8) + pData[0];  pData++;
10648           case 2:  v = (v<<8) + pData[0];  pData++;
10649         }
10650   
10651         if( eType==7 ){
10652           double r;
10653           memcpy(&r, &v, sizeof(r));
10654           sqlite3_result_double(pCtx, r);
10655         }else{
10656           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
10657         }
10658         break;
10659       }
10660   
10661       default: {
10662         int n = ((eType-12) / 2);
10663         if( eType % 2 ){
10664           sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
10665         }else{
10666           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
10667         }
10668       }
10669     }
10670   }
10671 }
10672
10673 /*
10674 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
10675 */
10676 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
10677   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10678   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
10679
10680   pCsr->iRowid++;
10681   while( 1 ){
10682     int rc;
10683     int iOff = (pCsr->iPgno==1 ? 100 : 0);
10684     int bNextPage = 0;
10685
10686     if( pCsr->aPage==0 ){
10687       while( 1 ){
10688         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
10689         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
10690         if( rc!=SQLITE_OK ) return rc;
10691         if( pCsr->aPage ) break;
10692         pCsr->iPgno++;
10693       }
10694       pCsr->iCell = pTab->bPtr ? -2 : 0;
10695       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
10696     }
10697
10698     if( pTab->bPtr ){
10699       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
10700         pCsr->iCell = pCsr->nCell;
10701       }
10702       pCsr->iCell++;
10703       if( pCsr->iCell>=pCsr->nCell ){
10704         sqlite3_free(pCsr->aPage);
10705         pCsr->aPage = 0;
10706         if( pCsr->bOnePage ) return SQLITE_OK;
10707         pCsr->iPgno++;
10708       }else{
10709         return SQLITE_OK;
10710       }
10711     }else{
10712       /* If there is no record loaded, load it now. */
10713       if( pCsr->pRec==0 ){
10714         int bHasRowid = 0;
10715         int nPointer = 0;
10716         sqlite3_int64 nPayload = 0;
10717         sqlite3_int64 nHdr = 0;
10718         int iHdr;
10719         int U, X;
10720         int nLocal;
10721   
10722         switch( pCsr->aPage[iOff] ){
10723           case 0x02:
10724             nPointer = 4;
10725             break;
10726           case 0x0a:
10727             break;
10728           case 0x0d:
10729             bHasRowid = 1;
10730             break;
10731           default:
10732             /* This is not a b-tree page with records on it. Continue. */
10733             pCsr->iCell = pCsr->nCell;
10734             break;
10735         }
10736
10737         if( pCsr->iCell>=pCsr->nCell ){
10738           bNextPage = 1;
10739         }else{
10740   
10741           iOff += 8 + nPointer + pCsr->iCell*2;
10742           if( iOff>pCsr->nPage ){
10743             bNextPage = 1;
10744           }else{
10745             iOff = get_uint16(&pCsr->aPage[iOff]);
10746           }
10747     
10748           /* For an interior node cell, skip past the child-page number */
10749           iOff += nPointer;
10750     
10751           /* Load the "byte of payload including overflow" field */
10752           if( bNextPage || iOff>pCsr->nPage ){
10753             bNextPage = 1;
10754           }else{
10755             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
10756           }
10757     
10758           /* If this is a leaf intkey cell, load the rowid */
10759           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
10760             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
10761           }
10762     
10763           /* Figure out how much data to read from the local page */
10764           U = pCsr->nPage;
10765           if( bHasRowid ){
10766             X = U-35;
10767           }else{
10768             X = ((U-12)*64/255)-23;
10769           }
10770           if( nPayload<=X ){
10771             nLocal = nPayload;
10772           }else{
10773             int M, K;
10774             M = ((U-12)*32/255)-23;
10775             K = M+((nPayload-M)%(U-4));
10776             if( K<=X ){
10777               nLocal = K;
10778             }else{
10779               nLocal = M;
10780             }
10781           }
10782
10783           if( bNextPage || nLocal+iOff>pCsr->nPage ){
10784             bNextPage = 1;
10785           }else{
10786
10787             /* Allocate space for payload. And a bit more to catch small buffer
10788             ** overruns caused by attempting to read a varint or similar from 
10789             ** near the end of a corrupt record.  */
10790             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
10791             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
10792             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
10793             pCsr->nRec = nPayload;
10794
10795             /* Load the nLocal bytes of payload */
10796             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
10797             iOff += nLocal;
10798
10799             /* Load content from overflow pages */
10800             if( nPayload>nLocal ){
10801               sqlite3_int64 nRem = nPayload - nLocal;
10802               unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
10803               while( nRem>0 ){
10804                 u8 *aOvfl = 0;
10805                 int nOvfl = 0;
10806                 int nCopy;
10807                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
10808                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
10809                 if( rc!=SQLITE_OK ) return rc;
10810                 if( aOvfl==0 ) break;
10811
10812                 nCopy = U-4;
10813                 if( nCopy>nRem ) nCopy = nRem;
10814                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
10815                 nRem -= nCopy;
10816
10817                 pgnoOvfl = get_uint32(aOvfl);
10818                 sqlite3_free(aOvfl);
10819               }
10820             }
10821     
10822             iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
10823             pCsr->nHdr = nHdr;
10824             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
10825             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
10826             pCsr->iField = (bHasRowid ? -1 : 0);
10827           }
10828         }
10829       }else{
10830         pCsr->iField++;
10831         if( pCsr->iField>0 ){
10832           sqlite3_int64 iType;
10833           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
10834             bNextPage = 1;
10835           }else{
10836             pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
10837             pCsr->pPtr += dbdataValueBytes(iType);
10838           }
10839         }
10840       }
10841
10842       if( bNextPage ){
10843         sqlite3_free(pCsr->aPage);
10844         sqlite3_free(pCsr->pRec);
10845         pCsr->aPage = 0;
10846         pCsr->pRec = 0;
10847         if( pCsr->bOnePage ) return SQLITE_OK;
10848         pCsr->iPgno++;
10849       }else{
10850         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
10851           return SQLITE_OK;
10852         }
10853
10854         /* Advance to the next cell. The next iteration of the loop will load
10855         ** the record and so on. */
10856         sqlite3_free(pCsr->pRec);
10857         pCsr->pRec = 0;
10858         pCsr->iCell++;
10859       }
10860     }
10861   }
10862
10863   assert( !"can't get here" );
10864   return SQLITE_OK;
10865 }
10866
10867 /* 
10868 ** Return true if the cursor is at EOF.
10869 */
10870 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
10871   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10872   return pCsr->aPage==0;
10873 }
10874
10875 /* 
10876 ** Determine the size in pages of database zSchema (where zSchema is
10877 ** "main", "temp" or the name of an attached database) and set 
10878 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
10879 ** an SQLite error code.
10880 */
10881 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
10882   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
10883   char *zSql = 0;
10884   int rc, rc2;
10885   sqlite3_stmt *pStmt = 0;
10886
10887   zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
10888   if( zSql==0 ) return SQLITE_NOMEM;
10889   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
10890   sqlite3_free(zSql);
10891   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
10892     pCsr->szDb = sqlite3_column_int(pStmt, 0);
10893   }
10894   rc2 = sqlite3_finalize(pStmt);
10895   if( rc==SQLITE_OK ) rc = rc2;
10896   return rc;
10897 }
10898
10899 /* 
10900 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
10901 */
10902 static int dbdataFilter(
10903   sqlite3_vtab_cursor *pCursor, 
10904   int idxNum, const char *idxStr,
10905   int argc, sqlite3_value **argv
10906 ){
10907   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10908   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
10909   int rc = SQLITE_OK;
10910   const char *zSchema = "main";
10911
10912   dbdataResetCursor(pCsr);
10913   assert( pCsr->iPgno==1 );
10914   if( idxNum & 0x01 ){
10915     zSchema = (const char*)sqlite3_value_text(argv[0]);
10916   }
10917   if( idxNum & 0x02 ){
10918     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
10919     pCsr->bOnePage = 1;
10920   }else{
10921     pCsr->nPage = dbdataDbsize(pCsr, zSchema);
10922     rc = dbdataDbsize(pCsr, zSchema);
10923   }
10924
10925   if( rc==SQLITE_OK ){
10926     if( pTab->pStmt ){
10927       pCsr->pStmt = pTab->pStmt;
10928       pTab->pStmt = 0;
10929     }else{
10930       rc = sqlite3_prepare_v2(pTab->db, 
10931           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
10932           &pCsr->pStmt, 0
10933       );
10934     }
10935   }
10936   if( rc==SQLITE_OK ){
10937     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
10938   }else{
10939     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
10940   }
10941   if( rc==SQLITE_OK ){
10942     rc = dbdataNext(pCursor);
10943   }
10944   return rc;
10945 }
10946
10947 /* 
10948 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
10949 */
10950 static int dbdataColumn(
10951   sqlite3_vtab_cursor *pCursor, 
10952   sqlite3_context *ctx, 
10953   int i
10954 ){
10955   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
10956   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
10957   if( pTab->bPtr ){
10958     switch( i ){
10959       case DBPTR_COLUMN_PGNO:
10960         sqlite3_result_int64(ctx, pCsr->iPgno);
10961         break;
10962       case DBPTR_COLUMN_CHILD: {
10963         int iOff = pCsr->iPgno==1 ? 100 : 0;
10964         if( pCsr->iCell<0 ){
10965           iOff += 8;
10966         }else{
10967           iOff += 12 + pCsr->iCell*2;
10968           if( iOff>pCsr->nPage ) return SQLITE_OK;
10969           iOff = get_uint16(&pCsr->aPage[iOff]);
10970         }
10971         if( iOff<=pCsr->nPage ){
10972           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
10973         }
10974         break;
10975       }
10976     }
10977   }else{
10978     switch( i ){
10979       case DBDATA_COLUMN_PGNO:
10980         sqlite3_result_int64(ctx, pCsr->iPgno);
10981         break;
10982       case DBDATA_COLUMN_CELL:
10983         sqlite3_result_int(ctx, pCsr->iCell);
10984         break;
10985       case DBDATA_COLUMN_FIELD:
10986         sqlite3_result_int(ctx, pCsr->iField);
10987         break;
10988       case DBDATA_COLUMN_VALUE: {
10989         if( pCsr->iField<0 ){
10990           sqlite3_result_int64(ctx, pCsr->iIntkey);
10991         }else{
10992           sqlite3_int64 iType;
10993           dbdataGetVarint(pCsr->pHdrPtr, &iType);
10994           dbdataValue(
10995               ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
10996           );
10997         }
10998         break;
10999       }
11000     }
11001   }
11002   return SQLITE_OK;
11003 }
11004
11005 /* 
11006 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
11007 */
11008 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
11009   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11010   *pRowid = pCsr->iRowid;
11011   return SQLITE_OK;
11012 }
11013
11014
11015 /*
11016 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
11017 */
11018 static int sqlite3DbdataRegister(sqlite3 *db){
11019   static sqlite3_module dbdata_module = {
11020     0,                            /* iVersion */
11021     0,                            /* xCreate */
11022     dbdataConnect,                /* xConnect */
11023     dbdataBestIndex,              /* xBestIndex */
11024     dbdataDisconnect,             /* xDisconnect */
11025     0,                            /* xDestroy */
11026     dbdataOpen,                   /* xOpen - open a cursor */
11027     dbdataClose,                  /* xClose - close a cursor */
11028     dbdataFilter,                 /* xFilter - configure scan constraints */
11029     dbdataNext,                   /* xNext - advance a cursor */
11030     dbdataEof,                    /* xEof - check for end of scan */
11031     dbdataColumn,                 /* xColumn - read data */
11032     dbdataRowid,                  /* xRowid - read data */
11033     0,                            /* xUpdate */
11034     0,                            /* xBegin */
11035     0,                            /* xSync */
11036     0,                            /* xCommit */
11037     0,                            /* xRollback */
11038     0,                            /* xFindMethod */
11039     0,                            /* xRename */
11040     0,                            /* xSavepoint */
11041     0,                            /* xRelease */
11042     0,                            /* xRollbackTo */
11043     0                             /* xShadowName */
11044   };
11045
11046   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
11047   if( rc==SQLITE_OK ){
11048     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
11049   }
11050   return rc;
11051 }
11052
11053 #ifdef _WIN32
11054
11055 #endif
11056 int sqlite3_dbdata_init(
11057   sqlite3 *db, 
11058   char **pzErrMsg, 
11059   const sqlite3_api_routines *pApi
11060 ){
11061   SQLITE_EXTENSION_INIT2(pApi);
11062   return sqlite3DbdataRegister(db);
11063 }
11064
11065 /************************* End ../ext/misc/dbdata.c ********************/
11066 #endif
11067
11068 #if defined(SQLITE_ENABLE_SESSION)
11069 /*
11070 ** State information for a single open session
11071 */
11072 typedef struct OpenSession OpenSession;
11073 struct OpenSession {
11074   char *zName;             /* Symbolic name for this session */
11075   int nFilter;             /* Number of xFilter rejection GLOB patterns */
11076   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
11077   sqlite3_session *p;      /* The open session */
11078 };
11079 #endif
11080
11081 typedef struct ExpertInfo ExpertInfo;
11082 struct ExpertInfo {
11083   sqlite3expert *pExpert;
11084   int bVerbose;
11085 };
11086
11087 /* A single line in the EQP output */
11088 typedef struct EQPGraphRow EQPGraphRow;
11089 struct EQPGraphRow {
11090   int iEqpId;           /* ID for this row */
11091   int iParentId;        /* ID of the parent row */
11092   EQPGraphRow *pNext;   /* Next row in sequence */
11093   char zText[1];        /* Text to display for this row */
11094 };
11095
11096 /* All EQP output is collected into an instance of the following */
11097 typedef struct EQPGraph EQPGraph;
11098 struct EQPGraph {
11099   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
11100   EQPGraphRow *pLast;   /* Last element of the pRow list */
11101   char zPrefix[100];    /* Graph prefix */
11102 };
11103
11104 /*
11105 ** State information about the database connection is contained in an
11106 ** instance of the following structure.
11107 */
11108 typedef struct ShellState ShellState;
11109 struct ShellState {
11110   sqlite3 *db;           /* The database */
11111   u8 autoExplain;        /* Automatically turn on .explain mode */
11112   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
11113   u8 autoEQPtest;        /* autoEQP is in test mode */
11114   u8 autoEQPtrace;       /* autoEQP is in trace mode */
11115   u8 statsOn;            /* True to display memory stats before each finalize */
11116   u8 scanstatsOn;        /* True to display scan stats before each finalize */
11117   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
11118   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
11119   u8 nEqpLevel;          /* Depth of the EQP output graph */
11120   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
11121   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
11122   int outCount;          /* Revert to stdout when reaching zero */
11123   int cnt;               /* Number of records displayed so far */
11124   int lineno;            /* Line number of last line read from in */
11125   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
11126   FILE *in;              /* Read commands from this stream */
11127   FILE *out;             /* Write results here */
11128   FILE *traceOut;        /* Output for sqlite3_trace() */
11129   int nErr;              /* Number of errors seen */
11130   int mode;              /* An output mode setting */
11131   int modePrior;         /* Saved mode */
11132   int cMode;             /* temporary output mode for the current query */
11133   int normalMode;        /* Output mode before ".explain on" */
11134   int writableSchema;    /* True if PRAGMA writable_schema=ON */
11135   int showHeader;        /* True to show column names in List or Column mode */
11136   int nCheck;            /* Number of ".check" commands run */
11137   unsigned nProgress;    /* Number of progress callbacks encountered */
11138   unsigned mxProgress;   /* Maximum progress callbacks before failing */
11139   unsigned flgProgress;  /* Flags for the progress callback */
11140   unsigned shellFlgs;    /* Various flags */
11141   unsigned priorShFlgs;  /* Saved copy of flags */
11142   sqlite3_int64 szMax;   /* --maxsize argument to .open */
11143   char *zDestTable;      /* Name of destination table when MODE_Insert */
11144   char *zTempFile;       /* Temporary file that might need deleting */
11145   char zTestcase[30];    /* Name of current test case */
11146   char colSeparator[20]; /* Column separator character for several modes */
11147   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
11148   char colSepPrior[20];  /* Saved column separator */
11149   char rowSepPrior[20];  /* Saved row separator */
11150   int *colWidth;         /* Requested width of each column in columnar modes */
11151   int *actualWidth;      /* Actual width of each column */
11152   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
11153   char nullValue[20];    /* The text to print when a NULL comes back from
11154                          ** the database */
11155   char outfile[FILENAME_MAX]; /* Filename for *out */
11156   const char *zDbFilename;    /* name of the database file */
11157   char *zFreeOnClose;         /* Filename to free when closing */
11158   const char *zVfs;           /* Name of VFS to use */
11159   sqlite3_stmt *pStmt;   /* Current statement if any. */
11160   FILE *pLog;            /* Write log output here */
11161   int *aiIndent;         /* Array of indents used in MODE_Explain */
11162   int nIndent;           /* Size of array aiIndent[] */
11163   int iIndent;           /* Index of current op in aiIndent[] */
11164   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
11165 #if defined(SQLITE_ENABLE_SESSION)
11166   int nSession;             /* Number of active sessions */
11167   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
11168 #endif
11169   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
11170 };
11171
11172
11173 /* Allowed values for ShellState.autoEQP
11174 */
11175 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
11176 #define AUTOEQP_on       1           /* Automatic EQP is on */
11177 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
11178 #define AUTOEQP_full     3           /* Show full EXPLAIN */
11179
11180 /* Allowed values for ShellState.openMode
11181 */
11182 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
11183 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
11184 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
11185 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
11186 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
11187 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
11188 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
11189
11190 /* Allowed values for ShellState.eTraceType
11191 */
11192 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
11193 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
11194 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
11195
11196 /* Bits in the ShellState.flgProgress variable */
11197 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
11198 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
11199                                    ** callback limit is reached, and for each
11200                                    ** top-level SQL statement */
11201 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
11202
11203 /*
11204 ** These are the allowed shellFlgs values
11205 */
11206 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
11207 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
11208 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
11209 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
11210 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
11211 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
11212 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
11213 #define SHFLG_HeaderSet      0x00000080 /* .header has been used */
11214 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
11215 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
11216
11217 /*
11218 ** Macros for testing and setting shellFlgs
11219 */
11220 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
11221 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
11222 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
11223
11224 /*
11225 ** These are the allowed modes.
11226 */
11227 #define MODE_Line     0  /* One column per line.  Blank line between records */
11228 #define MODE_Column   1  /* One record per line in neat columns */
11229 #define MODE_List     2  /* One record per line with a separator */
11230 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
11231 #define MODE_Html     4  /* Generate an XHTML table */
11232 #define MODE_Insert   5  /* Generate SQL "insert" statements */
11233 #define MODE_Quote    6  /* Quote values as for SQL */
11234 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
11235 #define MODE_Csv      8  /* Quote strings, numbers are plain */
11236 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
11237 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
11238 #define MODE_Pretty  11  /* Pretty-print schemas */
11239 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
11240 #define MODE_Json    13  /* Output JSON */
11241 #define MODE_Markdown 14 /* Markdown formatting */
11242 #define MODE_Table   15  /* MySQL-style table formatting */
11243 #define MODE_Box     16  /* Unicode box-drawing characters */
11244
11245 static const char *modeDescr[] = {
11246   "line",
11247   "column",
11248   "list",
11249   "semi",
11250   "html",
11251   "insert",
11252   "quote",
11253   "tcl",
11254   "csv",
11255   "explain",
11256   "ascii",
11257   "prettyprint",
11258   "eqp",
11259   "json",
11260   "markdown",
11261   "table",
11262   "box"
11263 };
11264
11265 /*
11266 ** These are the column/row/line separators used by the various
11267 ** import/export modes.
11268 */
11269 #define SEP_Column    "|"
11270 #define SEP_Row       "\n"
11271 #define SEP_Tab       "\t"
11272 #define SEP_Space     " "
11273 #define SEP_Comma     ","
11274 #define SEP_CrLf      "\r\n"
11275 #define SEP_Unit      "\x1F"
11276 #define SEP_Record    "\x1E"
11277
11278 /*
11279 ** A callback for the sqlite3_log() interface.
11280 */
11281 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
11282   ShellState *p = (ShellState*)pArg;
11283   if( p->pLog==0 ) return;
11284   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
11285   fflush(p->pLog);
11286 }
11287
11288 /*
11289 ** SQL function:  shell_putsnl(X)
11290 **
11291 ** Write the text X to the screen (or whatever output is being directed)
11292 ** adding a newline at the end, and then return X.
11293 */
11294 static void shellPutsFunc(
11295   sqlite3_context *pCtx,
11296   int nVal,
11297   sqlite3_value **apVal
11298 ){
11299   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
11300   (void)nVal;
11301   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
11302   sqlite3_result_value(pCtx, apVal[0]);
11303 }
11304
11305 /*
11306 ** SQL function:   edit(VALUE)
11307 **                 edit(VALUE,EDITOR)
11308 **
11309 ** These steps:
11310 **
11311 **     (1) Write VALUE into a temporary file.
11312 **     (2) Run program EDITOR on that temporary file.
11313 **     (3) Read the temporary file back and return its content as the result.
11314 **     (4) Delete the temporary file
11315 **
11316 ** If the EDITOR argument is omitted, use the value in the VISUAL
11317 ** environment variable.  If still there is no EDITOR, through an error.
11318 **
11319 ** Also throw an error if the EDITOR program returns a non-zero exit code.
11320 */
11321 #ifndef SQLITE_NOHAVE_SYSTEM
11322 static void editFunc(
11323   sqlite3_context *context,
11324   int argc,
11325   sqlite3_value **argv
11326 ){
11327   const char *zEditor;
11328   char *zTempFile = 0;
11329   sqlite3 *db;
11330   char *zCmd = 0;
11331   int bBin;
11332   int rc;
11333   int hasCRNL = 0;
11334   FILE *f = 0;
11335   sqlite3_int64 sz;
11336   sqlite3_int64 x;
11337   unsigned char *p = 0;
11338
11339   if( argc==2 ){
11340     zEditor = (const char*)sqlite3_value_text(argv[1]);
11341   }else{
11342     zEditor = getenv("VISUAL");
11343   }
11344   if( zEditor==0 ){
11345     sqlite3_result_error(context, "no editor for edit()", -1);
11346     return;
11347   }
11348   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
11349     sqlite3_result_error(context, "NULL input to edit()", -1);
11350     return;
11351   }
11352   db = sqlite3_context_db_handle(context);
11353   zTempFile = 0;
11354   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
11355   if( zTempFile==0 ){
11356     sqlite3_uint64 r = 0;
11357     sqlite3_randomness(sizeof(r), &r);
11358     zTempFile = sqlite3_mprintf("temp%llx", r);
11359     if( zTempFile==0 ){
11360       sqlite3_result_error_nomem(context);
11361       return;
11362     }
11363   }
11364   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
11365   /* When writing the file to be edited, do \n to \r\n conversions on systems
11366   ** that want \r\n line endings */
11367   f = fopen(zTempFile, bBin ? "wb" : "w");
11368   if( f==0 ){
11369     sqlite3_result_error(context, "edit() cannot open temp file", -1);
11370     goto edit_func_end;
11371   }
11372   sz = sqlite3_value_bytes(argv[0]);
11373   if( bBin ){
11374     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
11375   }else{
11376     const char *z = (const char*)sqlite3_value_text(argv[0]);
11377     /* Remember whether or not the value originally contained \r\n */
11378     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
11379     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
11380   }
11381   fclose(f);
11382   f = 0;
11383   if( x!=sz ){
11384     sqlite3_result_error(context, "edit() could not write the whole file", -1);
11385     goto edit_func_end;
11386   }
11387   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
11388   if( zCmd==0 ){
11389     sqlite3_result_error_nomem(context);
11390     goto edit_func_end;
11391   }
11392   rc = system(zCmd);
11393   sqlite3_free(zCmd);
11394   if( rc ){
11395     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
11396     goto edit_func_end;
11397   }
11398   f = fopen(zTempFile, "rb");
11399   if( f==0 ){
11400     sqlite3_result_error(context,
11401       "edit() cannot reopen temp file after edit", -1);
11402     goto edit_func_end;
11403   }
11404   fseek(f, 0, SEEK_END);
11405   sz = ftell(f);
11406   rewind(f);
11407   p = sqlite3_malloc64( sz+1 );
11408   if( p==0 ){
11409     sqlite3_result_error_nomem(context);
11410     goto edit_func_end;
11411   }
11412   x = fread(p, 1, (size_t)sz, f);
11413   fclose(f);
11414   f = 0;
11415   if( x!=sz ){
11416     sqlite3_result_error(context, "could not read back the whole file", -1);
11417     goto edit_func_end;
11418   }
11419   if( bBin ){
11420     sqlite3_result_blob64(context, p, sz, sqlite3_free);
11421   }else{
11422     sqlite3_int64 i, j;
11423     if( hasCRNL ){
11424       /* If the original contains \r\n then do no conversions back to \n */
11425       j = sz;
11426     }else{
11427       /* If the file did not originally contain \r\n then convert any new
11428       ** \r\n back into \n */
11429       for(i=j=0; i<sz; i++){
11430         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
11431         p[j++] = p[i];
11432       }
11433       sz = j;
11434       p[sz] = 0;
11435     } 
11436     sqlite3_result_text64(context, (const char*)p, sz,
11437                           sqlite3_free, SQLITE_UTF8);
11438   }
11439   p = 0;
11440
11441 edit_func_end:
11442   if( f ) fclose(f);
11443   unlink(zTempFile);
11444   sqlite3_free(zTempFile);
11445   sqlite3_free(p);
11446 }
11447 #endif /* SQLITE_NOHAVE_SYSTEM */
11448
11449 /*
11450 ** Save or restore the current output mode
11451 */
11452 static void outputModePush(ShellState *p){
11453   p->modePrior = p->mode;
11454   p->priorShFlgs = p->shellFlgs;
11455   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
11456   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
11457 }
11458 static void outputModePop(ShellState *p){
11459   p->mode = p->modePrior;
11460   p->shellFlgs = p->priorShFlgs;
11461   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
11462   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
11463 }
11464
11465 /*
11466 ** Output the given string as a hex-encoded blob (eg. X'1234' )
11467 */
11468 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
11469   int i;
11470   char *zBlob = (char *)pBlob;
11471   raw_printf(out,"X'");
11472   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
11473   raw_printf(out,"'");
11474 }
11475
11476 /*
11477 ** Find a string that is not found anywhere in z[].  Return a pointer
11478 ** to that string.
11479 **
11480 ** Try to use zA and zB first.  If both of those are already found in z[]
11481 ** then make up some string and store it in the buffer zBuf.
11482 */
11483 static const char *unused_string(
11484   const char *z,                    /* Result must not appear anywhere in z */
11485   const char *zA, const char *zB,   /* Try these first */
11486   char *zBuf                        /* Space to store a generated string */
11487 ){
11488   unsigned i = 0;
11489   if( strstr(z, zA)==0 ) return zA;
11490   if( strstr(z, zB)==0 ) return zB;
11491   do{
11492     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
11493   }while( strstr(z,zBuf)!=0 );
11494   return zBuf;
11495 }
11496
11497 /*
11498 ** Output the given string as a quoted string using SQL quoting conventions.
11499 **
11500 ** See also: output_quoted_escaped_string()
11501 */
11502 static void output_quoted_string(FILE *out, const char *z){
11503   int i;
11504   char c;
11505   setBinaryMode(out, 1);
11506   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
11507   if( c==0 ){
11508     utf8_printf(out,"'%s'",z);
11509   }else{
11510     raw_printf(out, "'");
11511     while( *z ){
11512       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
11513       if( c=='\'' ) i++;
11514       if( i ){
11515         utf8_printf(out, "%.*s", i, z);
11516         z += i;
11517       }
11518       if( c=='\'' ){
11519         raw_printf(out, "'");
11520         continue;
11521       }
11522       if( c==0 ){
11523         break;
11524       }
11525       z++;
11526     }
11527     raw_printf(out, "'");
11528   }
11529   setTextMode(out, 1);
11530 }
11531
11532 /*
11533 ** Output the given string as a quoted string using SQL quoting conventions.
11534 ** Additionallly , escape the "\n" and "\r" characters so that they do not
11535 ** get corrupted by end-of-line translation facilities in some operating
11536 ** systems.
11537 **
11538 ** This is like output_quoted_string() but with the addition of the \r\n
11539 ** escape mechanism.
11540 */
11541 static void output_quoted_escaped_string(FILE *out, const char *z){
11542   int i;
11543   char c;
11544   setBinaryMode(out, 1);
11545   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
11546   if( c==0 ){
11547     utf8_printf(out,"'%s'",z);
11548   }else{
11549     const char *zNL = 0;
11550     const char *zCR = 0;
11551     int nNL = 0;
11552     int nCR = 0;
11553     char zBuf1[20], zBuf2[20];
11554     for(i=0; z[i]; i++){
11555       if( z[i]=='\n' ) nNL++;
11556       if( z[i]=='\r' ) nCR++;
11557     }
11558     if( nNL ){
11559       raw_printf(out, "replace(");
11560       zNL = unused_string(z, "\\n", "\\012", zBuf1);
11561     }
11562     if( nCR ){
11563       raw_printf(out, "replace(");
11564       zCR = unused_string(z, "\\r", "\\015", zBuf2);
11565     }
11566     raw_printf(out, "'");
11567     while( *z ){
11568       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
11569       if( c=='\'' ) i++;
11570       if( i ){
11571         utf8_printf(out, "%.*s", i, z);
11572         z += i;
11573       }
11574       if( c=='\'' ){
11575         raw_printf(out, "'");
11576         continue;
11577       }
11578       if( c==0 ){
11579         break;
11580       }
11581       z++;
11582       if( c=='\n' ){
11583         raw_printf(out, "%s", zNL);
11584         continue;
11585       }
11586       raw_printf(out, "%s", zCR);
11587     }
11588     raw_printf(out, "'");
11589     if( nCR ){
11590       raw_printf(out, ",'%s',char(13))", zCR);
11591     }
11592     if( nNL ){
11593       raw_printf(out, ",'%s',char(10))", zNL);
11594     }
11595   }
11596   setTextMode(out, 1);
11597 }
11598
11599 /*
11600 ** Output the given string as a quoted according to C or TCL quoting rules.
11601 */
11602 static void output_c_string(FILE *out, const char *z){
11603   unsigned int c;
11604   fputc('"', out);
11605   while( (c = *(z++))!=0 ){
11606     if( c=='\\' ){
11607       fputc(c, out);
11608       fputc(c, out);
11609     }else if( c=='"' ){
11610       fputc('\\', out);
11611       fputc('"', out);
11612     }else if( c=='\t' ){
11613       fputc('\\', out);
11614       fputc('t', out);
11615     }else if( c=='\n' ){
11616       fputc('\\', out);
11617       fputc('n', out);
11618     }else if( c=='\r' ){
11619       fputc('\\', out);
11620       fputc('r', out);
11621     }else if( !isprint(c&0xff) ){
11622       raw_printf(out, "\\%03o", c&0xff);
11623     }else{
11624       fputc(c, out);
11625     }
11626   }
11627   fputc('"', out);
11628 }
11629
11630 /*
11631 ** Output the given string as a quoted according to JSON quoting rules.
11632 */
11633 static void output_json_string(FILE *out, const char *z, int n){
11634   unsigned int c;
11635   if( n<0 ) n = (int)strlen(z);
11636   fputc('"', out);
11637   while( n-- ){
11638     c = *(z++);
11639     if( c=='\\' || c=='"' ){
11640       fputc('\\', out);
11641       fputc(c, out);
11642     }else if( c<=0x1f ){
11643       fputc('\\', out);
11644       if( c=='\b' ){
11645         fputc('b', out);
11646       }else if( c=='\f' ){
11647         fputc('f', out);
11648       }else if( c=='\n' ){
11649         fputc('n', out);
11650       }else if( c=='\r' ){
11651         fputc('r', out);
11652       }else if( c=='\t' ){
11653         fputc('t', out);
11654       }else{
11655          raw_printf(out, "u%04x",c);
11656       }
11657     }else{
11658       fputc(c, out);
11659     }
11660   }
11661   fputc('"', out);
11662 }
11663
11664 /*
11665 ** Output the given string with characters that are special to
11666 ** HTML escaped.
11667 */
11668 static void output_html_string(FILE *out, const char *z){
11669   int i;
11670   if( z==0 ) z = "";
11671   while( *z ){
11672     for(i=0;   z[i]
11673             && z[i]!='<'
11674             && z[i]!='&'
11675             && z[i]!='>'
11676             && z[i]!='\"'
11677             && z[i]!='\'';
11678         i++){}
11679     if( i>0 ){
11680       utf8_printf(out,"%.*s",i,z);
11681     }
11682     if( z[i]=='<' ){
11683       raw_printf(out,"&lt;");
11684     }else if( z[i]=='&' ){
11685       raw_printf(out,"&amp;");
11686     }else if( z[i]=='>' ){
11687       raw_printf(out,"&gt;");
11688     }else if( z[i]=='\"' ){
11689       raw_printf(out,"&quot;");
11690     }else if( z[i]=='\'' ){
11691       raw_printf(out,"&#39;");
11692     }else{
11693       break;
11694     }
11695     z += i + 1;
11696   }
11697 }
11698
11699 /*
11700 ** If a field contains any character identified by a 1 in the following
11701 ** array, then the string must be quoted for CSV.
11702 */
11703 static const char needCsvQuote[] = {
11704   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11705   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11706   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
11707   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11708   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11709   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11710   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
11711   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
11712   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11713   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11714   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11715   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11716   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11717   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11718   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11719   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
11720 };
11721
11722 /*
11723 ** Output a single term of CSV.  Actually, p->colSeparator is used for
11724 ** the separator, which may or may not be a comma.  p->nullValue is
11725 ** the null value.  Strings are quoted if necessary.  The separator
11726 ** is only issued if bSep is true.
11727 */
11728 static void output_csv(ShellState *p, const char *z, int bSep){
11729   FILE *out = p->out;
11730   if( z==0 ){
11731     utf8_printf(out,"%s",p->nullValue);
11732   }else{
11733     int i;
11734     int nSep = strlen30(p->colSeparator);
11735     for(i=0; z[i]; i++){
11736       if( needCsvQuote[((unsigned char*)z)[i]]
11737          || (z[i]==p->colSeparator[0] &&
11738              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
11739         i = 0;
11740         break;
11741       }
11742     }
11743     if( i==0 ){
11744       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
11745       utf8_printf(out, "%s", zQuoted);
11746       sqlite3_free(zQuoted);
11747     }else{
11748       utf8_printf(out, "%s", z);
11749     }
11750   }
11751   if( bSep ){
11752     utf8_printf(p->out, "%s", p->colSeparator);
11753   }
11754 }
11755
11756 /*
11757 ** This routine runs when the user presses Ctrl-C
11758 */
11759 static void interrupt_handler(int NotUsed){
11760   UNUSED_PARAMETER(NotUsed);
11761   seenInterrupt++;
11762   if( seenInterrupt>2 ) exit(1);
11763   if( globalDb ) sqlite3_interrupt(globalDb);
11764 }
11765
11766 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11767 /*
11768 ** This routine runs for console events (e.g. Ctrl-C) on Win32
11769 */
11770 static BOOL WINAPI ConsoleCtrlHandler(
11771   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
11772 ){
11773   if( dwCtrlType==CTRL_C_EVENT ){
11774     interrupt_handler(0);
11775     return TRUE;
11776   }
11777   return FALSE;
11778 }
11779 #endif
11780
11781 #ifndef SQLITE_OMIT_AUTHORIZATION
11782 /*
11783 ** When the ".auth ON" is set, the following authorizer callback is
11784 ** invoked.  It always returns SQLITE_OK.
11785 */
11786 static int shellAuth(
11787   void *pClientData,
11788   int op,
11789   const char *zA1,
11790   const char *zA2,
11791   const char *zA3,
11792   const char *zA4
11793 ){
11794   ShellState *p = (ShellState*)pClientData;
11795   static const char *azAction[] = { 0,
11796      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
11797      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
11798      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
11799      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
11800      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
11801      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
11802      "PRAGMA",               "READ",                 "SELECT",
11803      "TRANSACTION",          "UPDATE",               "ATTACH",
11804      "DETACH",               "ALTER_TABLE",          "REINDEX",
11805      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
11806      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
11807   };
11808   int i;
11809   const char *az[4];
11810   az[0] = zA1;
11811   az[1] = zA2;
11812   az[2] = zA3;
11813   az[3] = zA4;
11814   utf8_printf(p->out, "authorizer: %s", azAction[op]);
11815   for(i=0; i<4; i++){
11816     raw_printf(p->out, " ");
11817     if( az[i] ){
11818       output_c_string(p->out, az[i]);
11819     }else{
11820       raw_printf(p->out, "NULL");
11821     }
11822   }
11823   raw_printf(p->out, "\n");
11824   return SQLITE_OK;
11825 }
11826 #endif
11827
11828 /*
11829 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
11830 **
11831 ** This routine converts some CREATE TABLE statements for shadow tables
11832 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
11833 */
11834 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
11835   if( z==0 ) return;
11836   if( zTail==0 ) return;
11837   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
11838     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
11839   }else{
11840     utf8_printf(out, "%s%s", z, zTail);
11841   }
11842 }
11843 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
11844   char c = z[n];
11845   z[n] = 0;
11846   printSchemaLine(out, z, zTail);
11847   z[n] = c;
11848 }
11849
11850 /*
11851 ** Return true if string z[] has nothing but whitespace and comments to the
11852 ** end of the first line.
11853 */
11854 static int wsToEol(const char *z){
11855   int i;
11856   for(i=0; z[i]; i++){
11857     if( z[i]=='\n' ) return 1;
11858     if( IsSpace(z[i]) ) continue;
11859     if( z[i]=='-' && z[i+1]=='-' ) return 1;
11860     return 0;
11861   }
11862   return 1;
11863 }
11864
11865 /*
11866 ** Add a new entry to the EXPLAIN QUERY PLAN data
11867 */
11868 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
11869   EQPGraphRow *pNew;
11870   int nText = strlen30(zText);
11871   if( p->autoEQPtest ){
11872     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
11873   }
11874   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
11875   if( pNew==0 ) shell_out_of_memory();
11876   pNew->iEqpId = iEqpId;
11877   pNew->iParentId = p2;
11878   memcpy(pNew->zText, zText, nText+1);
11879   pNew->pNext = 0;
11880   if( p->sGraph.pLast ){
11881     p->sGraph.pLast->pNext = pNew;
11882   }else{
11883     p->sGraph.pRow = pNew;
11884   }
11885   p->sGraph.pLast = pNew;
11886 }
11887
11888 /*
11889 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
11890 ** in p->sGraph.
11891 */
11892 static void eqp_reset(ShellState *p){
11893   EQPGraphRow *pRow, *pNext;
11894   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
11895     pNext = pRow->pNext;
11896     sqlite3_free(pRow);
11897   }
11898   memset(&p->sGraph, 0, sizeof(p->sGraph));
11899 }
11900
11901 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
11902 ** pOld, or return the first such line if pOld is NULL
11903 */
11904 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
11905   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
11906   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
11907   return pRow;
11908 }
11909
11910 /* Render a single level of the graph that has iEqpId as its parent.  Called
11911 ** recursively to render sublevels.
11912 */
11913 static void eqp_render_level(ShellState *p, int iEqpId){
11914   EQPGraphRow *pRow, *pNext;
11915   int n = strlen30(p->sGraph.zPrefix);
11916   char *z;
11917   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
11918     pNext = eqp_next_row(p, iEqpId, pRow);
11919     z = pRow->zText;
11920     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
11921                 pNext ? "|--" : "`--", z);
11922     if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
11923       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
11924       eqp_render_level(p, pRow->iEqpId);
11925       p->sGraph.zPrefix[n] = 0;
11926     }
11927   }
11928 }
11929
11930 /*
11931 ** Display and reset the EXPLAIN QUERY PLAN data
11932 */
11933 static void eqp_render(ShellState *p){
11934   EQPGraphRow *pRow = p->sGraph.pRow;
11935   if( pRow ){
11936     if( pRow->zText[0]=='-' ){
11937       if( pRow->pNext==0 ){
11938         eqp_reset(p);
11939         return;
11940       }
11941       utf8_printf(p->out, "%s\n", pRow->zText+3);
11942       p->sGraph.pRow = pRow->pNext;
11943       sqlite3_free(pRow);
11944     }else{
11945       utf8_printf(p->out, "QUERY PLAN\n");
11946     }
11947     p->sGraph.zPrefix[0] = 0;
11948     eqp_render_level(p, 0);
11949     eqp_reset(p);
11950   }
11951 }
11952
11953 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
11954 /*
11955 ** Progress handler callback.
11956 */
11957 static int progress_handler(void *pClientData) {
11958   ShellState *p = (ShellState*)pClientData;
11959   p->nProgress++;
11960   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
11961     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
11962     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11963     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
11964     return 1;
11965   }
11966   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
11967     raw_printf(p->out, "Progress %u\n", p->nProgress);
11968   }
11969   return 0;
11970 }
11971 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
11972
11973 /*
11974 ** Print N dashes
11975 */
11976 static void print_dashes(FILE *out, int N){
11977   const char zDash[] = "--------------------------------------------------";
11978   const int nDash = sizeof(zDash) - 1;
11979   while( N>nDash ){
11980     fputs(zDash, out);
11981     N -= nDash;
11982   }
11983   raw_printf(out, "%.*s", N, zDash);
11984 }
11985
11986 /*
11987 ** Print a markdown or table-style row separator using ascii-art
11988 */
11989 static void print_row_separator(
11990   ShellState *p,
11991   int nArg,
11992   const char *zSep
11993 ){
11994   int i;
11995   if( nArg>0 ){
11996     fputs(zSep, p->out);
11997     print_dashes(p->out, p->actualWidth[0]+2);
11998     for(i=1; i<nArg; i++){
11999       fputs(zSep, p->out);
12000       print_dashes(p->out, p->actualWidth[i]+2);
12001     }
12002     fputs(zSep, p->out);
12003   }
12004   fputs("\n", p->out);
12005 }
12006
12007 /*
12008 ** This is the callback routine that the shell
12009 ** invokes for each row of a query result.
12010 */
12011 static int shell_callback(
12012   void *pArg,
12013   int nArg,        /* Number of result columns */
12014   char **azArg,    /* Text of each result column */
12015   char **azCol,    /* Column names */
12016   int *aiType      /* Column types.  Might be NULL */
12017 ){
12018   int i;
12019   ShellState *p = (ShellState*)pArg;
12020
12021   if( azArg==0 ) return 0;
12022   switch( p->cMode ){
12023     case MODE_Line: {
12024       int w = 5;
12025       if( azArg==0 ) break;
12026       for(i=0; i<nArg; i++){
12027         int len = strlen30(azCol[i] ? azCol[i] : "");
12028         if( len>w ) w = len;
12029       }
12030       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
12031       for(i=0; i<nArg; i++){
12032         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
12033                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
12034       }
12035       break;
12036     }
12037     case MODE_Explain: {
12038       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
12039       if( nArg>ArraySize(aExplainWidth) ){
12040         nArg = ArraySize(aExplainWidth);
12041       }
12042       if( p->cnt++==0 ){
12043         for(i=0; i<nArg; i++){
12044           int w = aExplainWidth[i];
12045           utf8_width_print(p->out, w, azCol[i]);
12046           fputs(i==nArg-1 ? "\n" : "  ", p->out);
12047         }
12048         for(i=0; i<nArg; i++){
12049           int w = aExplainWidth[i];
12050           print_dashes(p->out, w);
12051           fputs(i==nArg-1 ? "\n" : "  ", p->out);
12052         }
12053       }
12054       if( azArg==0 ) break;
12055       for(i=0; i<nArg; i++){
12056         int w = aExplainWidth[i];
12057         if( azArg[i] && strlenChar(azArg[i])>w ){
12058           w = strlenChar(azArg[i]);
12059         }
12060         if( i==1 && p->aiIndent && p->pStmt ){
12061           if( p->iIndent<p->nIndent ){
12062             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
12063           }
12064           p->iIndent++;
12065         }
12066         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
12067         fputs(i==nArg-1 ? "\n" : "  ", p->out);
12068       }
12069       break;
12070     }
12071     case MODE_Semi: {   /* .schema and .fullschema output */
12072       printSchemaLine(p->out, azArg[0], ";\n");
12073       break;
12074     }
12075     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
12076       char *z;
12077       int j;
12078       int nParen = 0;
12079       char cEnd = 0;
12080       char c;
12081       int nLine = 0;
12082       assert( nArg==1 );
12083       if( azArg[0]==0 ) break;
12084       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
12085        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
12086       ){
12087         utf8_printf(p->out, "%s;\n", azArg[0]);
12088         break;
12089       }
12090       z = sqlite3_mprintf("%s", azArg[0]);
12091       j = 0;
12092       for(i=0; IsSpace(z[i]); i++){}
12093       for(; (c = z[i])!=0; i++){
12094         if( IsSpace(c) ){
12095           if( z[j-1]=='\r' ) z[j-1] = '\n';
12096           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
12097         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
12098           j--;
12099         }
12100         z[j++] = c;
12101       }
12102       while( j>0 && IsSpace(z[j-1]) ){ j--; }
12103       z[j] = 0;
12104       if( strlen30(z)>=79 ){
12105         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
12106           if( c==cEnd ){
12107             cEnd = 0;
12108           }else if( c=='"' || c=='\'' || c=='`' ){
12109             cEnd = c;
12110           }else if( c=='[' ){
12111             cEnd = ']';
12112           }else if( c=='-' && z[i+1]=='-' ){
12113             cEnd = '\n';
12114           }else if( c=='(' ){
12115             nParen++;
12116           }else if( c==')' ){
12117             nParen--;
12118             if( nLine>0 && nParen==0 && j>0 ){
12119               printSchemaLineN(p->out, z, j, "\n");
12120               j = 0;
12121             }
12122           }
12123           z[j++] = c;
12124           if( nParen==1 && cEnd==0
12125            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
12126           ){
12127             if( c=='\n' ) j--;
12128             printSchemaLineN(p->out, z, j, "\n  ");
12129             j = 0;
12130             nLine++;
12131             while( IsSpace(z[i+1]) ){ i++; }
12132           }
12133         }
12134         z[j] = 0;
12135       }
12136       printSchemaLine(p->out, z, ";\n");
12137       sqlite3_free(z);
12138       break;
12139     }
12140     case MODE_List: {
12141       if( p->cnt++==0 && p->showHeader ){
12142         for(i=0; i<nArg; i++){
12143           utf8_printf(p->out,"%s%s",azCol[i],
12144                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
12145         }
12146       }
12147       if( azArg==0 ) break;
12148       for(i=0; i<nArg; i++){
12149         char *z = azArg[i];
12150         if( z==0 ) z = p->nullValue;
12151         utf8_printf(p->out, "%s", z);
12152         if( i<nArg-1 ){
12153           utf8_printf(p->out, "%s", p->colSeparator);
12154         }else{
12155           utf8_printf(p->out, "%s", p->rowSeparator);
12156         }
12157       }
12158       break;
12159     }
12160     case MODE_Html: {
12161       if( p->cnt++==0 && p->showHeader ){
12162         raw_printf(p->out,"<TR>");
12163         for(i=0; i<nArg; i++){
12164           raw_printf(p->out,"<TH>");
12165           output_html_string(p->out, azCol[i]);
12166           raw_printf(p->out,"</TH>\n");
12167         }
12168         raw_printf(p->out,"</TR>\n");
12169       }
12170       if( azArg==0 ) break;
12171       raw_printf(p->out,"<TR>");
12172       for(i=0; i<nArg; i++){
12173         raw_printf(p->out,"<TD>");
12174         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
12175         raw_printf(p->out,"</TD>\n");
12176       }
12177       raw_printf(p->out,"</TR>\n");
12178       break;
12179     }
12180     case MODE_Tcl: {
12181       if( p->cnt++==0 && p->showHeader ){
12182         for(i=0; i<nArg; i++){
12183           output_c_string(p->out,azCol[i] ? azCol[i] : "");
12184           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
12185         }
12186         utf8_printf(p->out, "%s", p->rowSeparator);
12187       }
12188       if( azArg==0 ) break;
12189       for(i=0; i<nArg; i++){
12190         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
12191         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
12192       }
12193       utf8_printf(p->out, "%s", p->rowSeparator);
12194       break;
12195     }
12196     case MODE_Csv: {
12197       setBinaryMode(p->out, 1);
12198       if( p->cnt++==0 && p->showHeader ){
12199         for(i=0; i<nArg; i++){
12200           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
12201         }
12202         utf8_printf(p->out, "%s", p->rowSeparator);
12203       }
12204       if( nArg>0 ){
12205         for(i=0; i<nArg; i++){
12206           output_csv(p, azArg[i], i<nArg-1);
12207         }
12208         utf8_printf(p->out, "%s", p->rowSeparator);
12209       }
12210       setTextMode(p->out, 1);
12211       break;
12212     }
12213     case MODE_Insert: {
12214       if( azArg==0 ) break;
12215       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
12216       if( p->showHeader ){
12217         raw_printf(p->out,"(");
12218         for(i=0; i<nArg; i++){
12219           if( i>0 ) raw_printf(p->out, ",");
12220           if( quoteChar(azCol[i]) ){
12221             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
12222             utf8_printf(p->out, "%s", z);
12223             sqlite3_free(z);
12224           }else{
12225             raw_printf(p->out, "%s", azCol[i]);
12226           }
12227         }
12228         raw_printf(p->out,")");
12229       }
12230       p->cnt++;
12231       for(i=0; i<nArg; i++){
12232         raw_printf(p->out, i>0 ? "," : " VALUES(");
12233         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
12234           utf8_printf(p->out,"NULL");
12235         }else if( aiType && aiType[i]==SQLITE_TEXT ){
12236           if( ShellHasFlag(p, SHFLG_Newlines) ){
12237             output_quoted_string(p->out, azArg[i]);
12238           }else{
12239             output_quoted_escaped_string(p->out, azArg[i]);
12240           }
12241         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
12242           utf8_printf(p->out,"%s", azArg[i]);
12243         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
12244           char z[50];
12245           double r = sqlite3_column_double(p->pStmt, i);
12246           sqlite3_uint64 ur;
12247           memcpy(&ur,&r,sizeof(r));
12248           if( ur==0x7ff0000000000000LL ){
12249             raw_printf(p->out, "1e999");
12250           }else if( ur==0xfff0000000000000LL ){
12251             raw_printf(p->out, "-1e999");
12252           }else{
12253             sqlite3_snprintf(50,z,"%!.20g", r);
12254             raw_printf(p->out, "%s", z);
12255           }
12256         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
12257           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
12258           int nBlob = sqlite3_column_bytes(p->pStmt, i);
12259           output_hex_blob(p->out, pBlob, nBlob);
12260         }else if( isNumber(azArg[i], 0) ){
12261           utf8_printf(p->out,"%s", azArg[i]);
12262         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
12263           output_quoted_string(p->out, azArg[i]);
12264         }else{
12265           output_quoted_escaped_string(p->out, azArg[i]);
12266         }
12267       }
12268       raw_printf(p->out,");\n");
12269       break;
12270     }
12271     case MODE_Json: {
12272       if( azArg==0 ) break;
12273       if( p->cnt==0 ){
12274         fputs("[{", p->out);
12275       }else{
12276         fputs(",\n{", p->out);
12277       }
12278       p->cnt++;
12279       for(i=0; i<nArg; i++){
12280         output_json_string(p->out, azCol[i], -1);
12281         putc(':', p->out);
12282         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
12283           fputs("null",p->out);
12284         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
12285           char z[50];
12286           double r = sqlite3_column_double(p->pStmt, i);
12287           sqlite3_uint64 ur;
12288           memcpy(&ur,&r,sizeof(r));
12289           if( ur==0x7ff0000000000000LL ){
12290             raw_printf(p->out, "1e999");
12291           }else if( ur==0xfff0000000000000LL ){
12292             raw_printf(p->out, "-1e999");
12293           }else{
12294             sqlite3_snprintf(50,z,"%!.20g", r);
12295             raw_printf(p->out, "%s", z);
12296           }
12297         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
12298           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
12299           int nBlob = sqlite3_column_bytes(p->pStmt, i);
12300           output_json_string(p->out, pBlob, nBlob);
12301         }else if( aiType && aiType[i]==SQLITE_TEXT ){
12302           output_json_string(p->out, azArg[i], -1);
12303         }else{
12304           utf8_printf(p->out,"%s", azArg[i]);
12305         }
12306         if( i<nArg-1 ){
12307           putc(',', p->out);
12308         }
12309       }
12310       putc('}', p->out);
12311       break;
12312     }
12313     case MODE_Quote: {
12314       if( azArg==0 ) break;
12315       if( p->cnt==0 && p->showHeader ){
12316         for(i=0; i<nArg; i++){
12317           if( i>0 ) fputs(p->colSeparator, p->out);
12318           output_quoted_string(p->out, azCol[i]);
12319         }
12320         fputs(p->rowSeparator, p->out);
12321       }
12322       p->cnt++;
12323       for(i=0; i<nArg; i++){
12324         if( i>0 ) fputs(p->colSeparator, p->out);
12325         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
12326           utf8_printf(p->out,"NULL");
12327         }else if( aiType && aiType[i]==SQLITE_TEXT ){
12328           output_quoted_string(p->out, azArg[i]);
12329         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
12330           utf8_printf(p->out,"%s", azArg[i]);
12331         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
12332           char z[50];
12333           double r = sqlite3_column_double(p->pStmt, i);
12334           sqlite3_snprintf(50,z,"%!.20g", r);
12335           raw_printf(p->out, "%s", z);
12336         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
12337           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
12338           int nBlob = sqlite3_column_bytes(p->pStmt, i);
12339           output_hex_blob(p->out, pBlob, nBlob);
12340         }else if( isNumber(azArg[i], 0) ){
12341           utf8_printf(p->out,"%s", azArg[i]);
12342         }else{
12343           output_quoted_string(p->out, azArg[i]);
12344         }
12345       }
12346       fputs(p->rowSeparator, p->out);
12347       break;
12348     }
12349     case MODE_Ascii: {
12350       if( p->cnt++==0 && p->showHeader ){
12351         for(i=0; i<nArg; i++){
12352           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
12353           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
12354         }
12355         utf8_printf(p->out, "%s", p->rowSeparator);
12356       }
12357       if( azArg==0 ) break;
12358       for(i=0; i<nArg; i++){
12359         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
12360         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
12361       }
12362       utf8_printf(p->out, "%s", p->rowSeparator);
12363       break;
12364     }
12365     case MODE_EQP: {
12366       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
12367       break;
12368     }
12369   }
12370   return 0;
12371 }
12372
12373 /*
12374 ** This is the callback routine that the SQLite library
12375 ** invokes for each row of a query result.
12376 */
12377 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
12378   /* since we don't have type info, call the shell_callback with a NULL value */
12379   return shell_callback(pArg, nArg, azArg, azCol, NULL);
12380 }
12381
12382 /*
12383 ** This is the callback routine from sqlite3_exec() that appends all
12384 ** output onto the end of a ShellText object.
12385 */
12386 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
12387   ShellText *p = (ShellText*)pArg;
12388   int i;
12389   UNUSED_PARAMETER(az);
12390   if( azArg==0 ) return 0;
12391   if( p->n ) appendText(p, "|", 0);
12392   for(i=0; i<nArg; i++){
12393     if( i ) appendText(p, ",", 0);
12394     if( azArg[i] ) appendText(p, azArg[i], 0);
12395   }
12396   return 0;
12397 }
12398
12399 /*
12400 ** Generate an appropriate SELFTEST table in the main database.
12401 */
12402 static void createSelftestTable(ShellState *p){
12403   char *zErrMsg = 0;
12404   sqlite3_exec(p->db,
12405     "SAVEPOINT selftest_init;\n"
12406     "CREATE TABLE IF NOT EXISTS selftest(\n"
12407     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
12408     "  op TEXT,\n"                   /* Operator:  memo run */
12409     "  cmd TEXT,\n"                  /* Command text */
12410     "  ans TEXT\n"                   /* Desired answer */
12411     ");"
12412     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
12413     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
12414     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
12415     "         'memo','Tests generated by --init');\n"
12416     "INSERT INTO [_shell$self]\n"
12417     "  SELECT 'run',\n"
12418     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
12419                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
12420     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
12421                           "FROM sqlite_schema ORDER BY 2',224));\n"
12422     "INSERT INTO [_shell$self]\n"
12423     "  SELECT 'run',"
12424     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
12425     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
12426     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
12427     "  FROM (\n"
12428     "    SELECT name FROM sqlite_schema\n"
12429     "     WHERE type='table'\n"
12430     "       AND name<>'selftest'\n"
12431     "       AND coalesce(rootpage,0)>0\n"
12432     "  )\n"
12433     " ORDER BY name;\n"
12434     "INSERT INTO [_shell$self]\n"
12435     "  VALUES('run','PRAGMA integrity_check','ok');\n"
12436     "INSERT INTO selftest(tno,op,cmd,ans)"
12437     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
12438     "DROP TABLE [_shell$self];"
12439     ,0,0,&zErrMsg);
12440   if( zErrMsg ){
12441     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
12442     sqlite3_free(zErrMsg);
12443   }
12444   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
12445 }
12446
12447
12448 /*
12449 ** Set the destination table field of the ShellState structure to
12450 ** the name of the table given.  Escape any quote characters in the
12451 ** table name.
12452 */
12453 static void set_table_name(ShellState *p, const char *zName){
12454   int i, n;
12455   char cQuote;
12456   char *z;
12457
12458   if( p->zDestTable ){
12459     free(p->zDestTable);
12460     p->zDestTable = 0;
12461   }
12462   if( zName==0 ) return;
12463   cQuote = quoteChar(zName);
12464   n = strlen30(zName);
12465   if( cQuote ) n += n+2;
12466   z = p->zDestTable = malloc( n+1 );
12467   if( z==0 ) shell_out_of_memory();
12468   n = 0;
12469   if( cQuote ) z[n++] = cQuote;
12470   for(i=0; zName[i]; i++){
12471     z[n++] = zName[i];
12472     if( zName[i]==cQuote ) z[n++] = cQuote;
12473   }
12474   if( cQuote ) z[n++] = cQuote;
12475   z[n] = 0;
12476 }
12477
12478
12479 /*
12480 ** Execute a query statement that will generate SQL output.  Print
12481 ** the result columns, comma-separated, on a line and then add a
12482 ** semicolon terminator to the end of that line.
12483 **
12484 ** If the number of columns is 1 and that column contains text "--"
12485 ** then write the semicolon on a separate line.  That way, if a
12486 ** "--" comment occurs at the end of the statement, the comment
12487 ** won't consume the semicolon terminator.
12488 */
12489 static int run_table_dump_query(
12490   ShellState *p,           /* Query context */
12491   const char *zSelect      /* SELECT statement to extract content */
12492 ){
12493   sqlite3_stmt *pSelect;
12494   int rc;
12495   int nResult;
12496   int i;
12497   const char *z;
12498   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
12499   if( rc!=SQLITE_OK || !pSelect ){
12500     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
12501                 sqlite3_errmsg(p->db));
12502     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
12503     return rc;
12504   }
12505   rc = sqlite3_step(pSelect);
12506   nResult = sqlite3_column_count(pSelect);
12507   while( rc==SQLITE_ROW ){
12508     z = (const char*)sqlite3_column_text(pSelect, 0);
12509     utf8_printf(p->out, "%s", z);
12510     for(i=1; i<nResult; i++){
12511       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
12512     }
12513     if( z==0 ) z = "";
12514     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
12515     if( z[0] ){
12516       raw_printf(p->out, "\n;\n");
12517     }else{
12518       raw_printf(p->out, ";\n");
12519     }
12520     rc = sqlite3_step(pSelect);
12521   }
12522   rc = sqlite3_finalize(pSelect);
12523   if( rc!=SQLITE_OK ){
12524     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
12525                 sqlite3_errmsg(p->db));
12526     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
12527   }
12528   return rc;
12529 }
12530
12531 /*
12532 ** Allocate space and save off current error string.
12533 */
12534 static char *save_err_msg(
12535   sqlite3 *db            /* Database to query */
12536 ){
12537   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
12538   char *zErrMsg = sqlite3_malloc64(nErrMsg);
12539   if( zErrMsg ){
12540     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
12541   }
12542   return zErrMsg;
12543 }
12544
12545 #ifdef __linux__
12546 /*
12547 ** Attempt to display I/O stats on Linux using /proc/PID/io
12548 */
12549 static void displayLinuxIoStats(FILE *out){
12550   FILE *in;
12551   char z[200];
12552   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
12553   in = fopen(z, "rb");
12554   if( in==0 ) return;
12555   while( fgets(z, sizeof(z), in)!=0 ){
12556     static const struct {
12557       const char *zPattern;
12558       const char *zDesc;
12559     } aTrans[] = {
12560       { "rchar: ",                  "Bytes received by read():" },
12561       { "wchar: ",                  "Bytes sent to write():"    },
12562       { "syscr: ",                  "Read() system calls:"      },
12563       { "syscw: ",                  "Write() system calls:"     },
12564       { "read_bytes: ",             "Bytes read from storage:"  },
12565       { "write_bytes: ",            "Bytes written to storage:" },
12566       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
12567     };
12568     int i;
12569     for(i=0; i<ArraySize(aTrans); i++){
12570       int n = strlen30(aTrans[i].zPattern);
12571       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
12572         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
12573         break;
12574       }
12575     }
12576   }
12577   fclose(in);
12578 }
12579 #endif
12580
12581 /*
12582 ** Display a single line of status using 64-bit values.
12583 */
12584 static void displayStatLine(
12585   ShellState *p,            /* The shell context */
12586   char *zLabel,             /* Label for this one line */
12587   char *zFormat,            /* Format for the result */
12588   int iStatusCtrl,          /* Which status to display */
12589   int bReset                /* True to reset the stats */
12590 ){
12591   sqlite3_int64 iCur = -1;
12592   sqlite3_int64 iHiwtr = -1;
12593   int i, nPercent;
12594   char zLine[200];
12595   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
12596   for(i=0, nPercent=0; zFormat[i]; i++){
12597     if( zFormat[i]=='%' ) nPercent++;
12598   }
12599   if( nPercent>1 ){
12600     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
12601   }else{
12602     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
12603   }
12604   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
12605 }
12606
12607 /*
12608 ** Display memory stats.
12609 */
12610 static int display_stats(
12611   sqlite3 *db,                /* Database to query */
12612   ShellState *pArg,           /* Pointer to ShellState */
12613   int bReset                  /* True to reset the stats */
12614 ){
12615   int iCur;
12616   int iHiwtr;
12617   FILE *out;
12618   if( pArg==0 || pArg->out==0 ) return 0;
12619   out = pArg->out;
12620
12621   if( pArg->pStmt && (pArg->statsOn & 2) ){
12622     int nCol, i, x;
12623     sqlite3_stmt *pStmt = pArg->pStmt;
12624     char z[100];
12625     nCol = sqlite3_column_count(pStmt);
12626     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
12627     for(i=0; i<nCol; i++){
12628       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
12629       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
12630 #ifndef SQLITE_OMIT_DECLTYPE
12631       sqlite3_snprintf(30, z+x, "declared type:");
12632       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
12633 #endif
12634 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12635       sqlite3_snprintf(30, z+x, "database name:");
12636       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
12637       sqlite3_snprintf(30, z+x, "table name:");
12638       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
12639       sqlite3_snprintf(30, z+x, "origin name:");
12640       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
12641 #endif
12642     }
12643   }
12644
12645   displayStatLine(pArg, "Memory Used:",
12646      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
12647   displayStatLine(pArg, "Number of Outstanding Allocations:",
12648      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
12649   if( pArg->shellFlgs & SHFLG_Pagecache ){
12650     displayStatLine(pArg, "Number of Pcache Pages Used:",
12651        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
12652   }
12653   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
12654      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
12655   displayStatLine(pArg, "Largest Allocation:",
12656      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
12657   displayStatLine(pArg, "Largest Pcache Allocation:",
12658      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
12659 #ifdef YYTRACKMAXSTACKDEPTH
12660   displayStatLine(pArg, "Deepest Parser Stack:",
12661      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
12662 #endif
12663
12664   if( db ){
12665     if( pArg->shellFlgs & SHFLG_Lookaside ){
12666       iHiwtr = iCur = -1;
12667       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
12668                         &iCur, &iHiwtr, bReset);
12669       raw_printf(pArg->out,
12670               "Lookaside Slots Used:                %d (max %d)\n",
12671               iCur, iHiwtr);
12672       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
12673                         &iCur, &iHiwtr, bReset);
12674       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
12675               iHiwtr);
12676       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
12677                         &iCur, &iHiwtr, bReset);
12678       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
12679               iHiwtr);
12680       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
12681                         &iCur, &iHiwtr, bReset);
12682       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
12683               iHiwtr);
12684     }
12685     iHiwtr = iCur = -1;
12686     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
12687     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
12688             iCur);
12689     iHiwtr = iCur = -1;
12690     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
12691     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
12692     iHiwtr = iCur = -1;
12693     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
12694     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
12695     iHiwtr = iCur = -1;
12696     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
12697     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
12698     iHiwtr = iCur = -1;
12699     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
12700     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
12701     iHiwtr = iCur = -1;
12702     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
12703     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
12704             iCur);
12705     iHiwtr = iCur = -1;
12706     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
12707     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
12708             iCur);
12709   }
12710
12711   if( pArg->pStmt ){
12712     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
12713                                bReset);
12714     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
12715     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
12716     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
12717     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
12718     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
12719     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
12720     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
12721     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
12722     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
12723     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
12724     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
12725     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
12726     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
12727   }
12728
12729 #ifdef __linux__
12730   displayLinuxIoStats(pArg->out);
12731 #endif
12732
12733   /* Do not remove this machine readable comment: extra-stats-output-here */
12734
12735   return 0;
12736 }
12737
12738 /*
12739 ** Display scan stats.
12740 */
12741 static void display_scanstats(
12742   sqlite3 *db,                    /* Database to query */
12743   ShellState *pArg                /* Pointer to ShellState */
12744 ){
12745 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
12746   UNUSED_PARAMETER(db);
12747   UNUSED_PARAMETER(pArg);
12748 #else
12749   int i, k, n, mx;
12750   raw_printf(pArg->out, "-------- scanstats --------\n");
12751   mx = 0;
12752   for(k=0; k<=mx; k++){
12753     double rEstLoop = 1.0;
12754     for(i=n=0; 1; i++){
12755       sqlite3_stmt *p = pArg->pStmt;
12756       sqlite3_int64 nLoop, nVisit;
12757       double rEst;
12758       int iSid;
12759       const char *zExplain;
12760       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
12761         break;
12762       }
12763       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
12764       if( iSid>mx ) mx = iSid;
12765       if( iSid!=k ) continue;
12766       if( n==0 ){
12767         rEstLoop = (double)nLoop;
12768         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
12769       }
12770       n++;
12771       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
12772       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
12773       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
12774       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
12775       rEstLoop *= rEst;
12776       raw_printf(pArg->out,
12777           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
12778           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
12779       );
12780     }
12781   }
12782   raw_printf(pArg->out, "---------------------------\n");
12783 #endif
12784 }
12785
12786 /*
12787 ** Parameter azArray points to a zero-terminated array of strings. zStr
12788 ** points to a single nul-terminated string. Return non-zero if zStr
12789 ** is equal, according to strcmp(), to any of the strings in the array.
12790 ** Otherwise, return zero.
12791 */
12792 static int str_in_array(const char *zStr, const char **azArray){
12793   int i;
12794   for(i=0; azArray[i]; i++){
12795     if( 0==strcmp(zStr, azArray[i]) ) return 1;
12796   }
12797   return 0;
12798 }
12799
12800 /*
12801 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
12802 ** and populate the ShellState.aiIndent[] array with the number of
12803 ** spaces each opcode should be indented before it is output.
12804 **
12805 ** The indenting rules are:
12806 **
12807 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
12808 **       all opcodes that occur between the p2 jump destination and the opcode
12809 **       itself by 2 spaces.
12810 **
12811 **     * For each "Goto", if the jump destination is earlier in the program
12812 **       and ends on one of:
12813 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
12814 **       or if the P1 parameter is one instead of zero,
12815 **       then indent all opcodes between the earlier instruction
12816 **       and "Goto" by 2 spaces.
12817 */
12818 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
12819   const char *zSql;               /* The text of the SQL statement */
12820   const char *z;                  /* Used to check if this is an EXPLAIN */
12821   int *abYield = 0;               /* True if op is an OP_Yield */
12822   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
12823   int iOp;                        /* Index of operation in p->aiIndent[] */
12824
12825   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
12826   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
12827                             "Rewind", 0 };
12828   const char *azGoto[] = { "Goto", 0 };
12829
12830   /* Try to figure out if this is really an EXPLAIN statement. If this
12831   ** cannot be verified, return early.  */
12832   if( sqlite3_column_count(pSql)!=8 ){
12833     p->cMode = p->mode;
12834     return;
12835   }
12836   zSql = sqlite3_sql(pSql);
12837   if( zSql==0 ) return;
12838   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
12839   if( sqlite3_strnicmp(z, "explain", 7) ){
12840     p->cMode = p->mode;
12841     return;
12842   }
12843
12844   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
12845     int i;
12846     int iAddr = sqlite3_column_int(pSql, 0);
12847     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
12848
12849     /* Set p2 to the P2 field of the current opcode. Then, assuming that
12850     ** p2 is an instruction address, set variable p2op to the index of that
12851     ** instruction in the aiIndent[] array. p2 and p2op may be different if
12852     ** the current instruction is part of a sub-program generated by an
12853     ** SQL trigger or foreign key.  */
12854     int p2 = sqlite3_column_int(pSql, 3);
12855     int p2op = (p2 + (iOp-iAddr));
12856
12857     /* Grow the p->aiIndent array as required */
12858     if( iOp>=nAlloc ){
12859       if( iOp==0 ){
12860         /* Do further verfication that this is explain output.  Abort if
12861         ** it is not */
12862         static const char *explainCols[] = {
12863            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
12864         int jj;
12865         for(jj=0; jj<ArraySize(explainCols); jj++){
12866           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
12867             p->cMode = p->mode;
12868             sqlite3_reset(pSql);
12869             return;
12870           }
12871         }
12872       }
12873       nAlloc += 100;
12874       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
12875       if( p->aiIndent==0 ) shell_out_of_memory();
12876       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
12877       if( abYield==0 ) shell_out_of_memory();
12878     }
12879     abYield[iOp] = str_in_array(zOp, azYield);
12880     p->aiIndent[iOp] = 0;
12881     p->nIndent = iOp+1;
12882
12883     if( str_in_array(zOp, azNext) ){
12884       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
12885     }
12886     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
12887      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
12888     ){
12889       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
12890     }
12891   }
12892
12893   p->iIndent = 0;
12894   sqlite3_free(abYield);
12895   sqlite3_reset(pSql);
12896 }
12897
12898 /*
12899 ** Free the array allocated by explain_data_prepare().
12900 */
12901 static void explain_data_delete(ShellState *p){
12902   sqlite3_free(p->aiIndent);
12903   p->aiIndent = 0;
12904   p->nIndent = 0;
12905   p->iIndent = 0;
12906 }
12907
12908 /*
12909 ** Disable and restore .wheretrace and .selecttrace settings.
12910 */
12911 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
12912 extern unsigned int sqlite3_unsupported_selecttrace;
12913 static int savedSelectTrace;
12914 #endif
12915 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
12916 extern int sqlite3WhereTrace;
12917 static int savedWhereTrace;
12918 #endif
12919 static void disable_debug_trace_modes(void){
12920 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
12921   savedSelectTrace = sqlite3_unsupported_selecttrace;
12922   sqlite3_unsupported_selecttrace = 0;
12923 #endif
12924 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
12925   savedWhereTrace = sqlite3WhereTrace;
12926   sqlite3WhereTrace = 0;
12927 #endif
12928 }
12929 static void restore_debug_trace_modes(void){
12930 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
12931   sqlite3_unsupported_selecttrace = savedSelectTrace;
12932 #endif
12933 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
12934   sqlite3WhereTrace = savedWhereTrace;
12935 #endif
12936 }
12937
12938 /* Create the TEMP table used to store parameter bindings */
12939 static void bind_table_init(ShellState *p){
12940   int wrSchema = 0;
12941   int defensiveMode = 0;
12942   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
12943   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
12944   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
12945   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
12946   sqlite3_exec(p->db,
12947     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
12948     "  key TEXT PRIMARY KEY,\n"
12949     "  value ANY\n"
12950     ") WITHOUT ROWID;",
12951     0, 0, 0);
12952   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
12953   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
12954 }
12955
12956 /*
12957 ** Bind parameters on a prepared statement.
12958 **
12959 ** Parameter bindings are taken from a TEMP table of the form:
12960 **
12961 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
12962 **    WITHOUT ROWID;
12963 **
12964 ** No bindings occur if this table does not exist.  The name of the table
12965 ** begins with "sqlite_" so that it will not collide with ordinary application
12966 ** tables.  The table must be in the TEMP schema.
12967 */
12968 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
12969   int nVar;
12970   int i;
12971   int rc;
12972   sqlite3_stmt *pQ = 0;
12973
12974   nVar = sqlite3_bind_parameter_count(pStmt);
12975   if( nVar==0 ) return;  /* Nothing to do */
12976   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
12977                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
12978     return; /* Parameter table does not exist */
12979   }
12980   rc = sqlite3_prepare_v2(pArg->db,
12981           "SELECT value FROM temp.sqlite_parameters"
12982           " WHERE key=?1", -1, &pQ, 0);
12983   if( rc || pQ==0 ) return;
12984   for(i=1; i<=nVar; i++){
12985     char zNum[30];
12986     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
12987     if( zVar==0 ){
12988       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
12989       zVar = zNum;
12990     }
12991     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
12992     if( sqlite3_step(pQ)==SQLITE_ROW ){
12993       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
12994     }else{
12995       sqlite3_bind_null(pStmt, i);
12996     }
12997     sqlite3_reset(pQ);
12998   }
12999   sqlite3_finalize(pQ);
13000 }
13001
13002 /*
13003 ** UTF8 box-drawing characters.  Imagine box lines like this:
13004 **
13005 **           1
13006 **           |
13007 **       4 --+-- 2
13008 **           |
13009 **           3
13010 **
13011 ** Each box characters has between 2 and 4 of the lines leading from
13012 ** the center.  The characters are here identified by the numbers of
13013 ** their corresponding lines.
13014 */
13015 #define BOX_24   "\342\224\200"  /* U+2500 --- */
13016 #define BOX_13   "\342\224\202"  /* U+2502  |  */
13017 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
13018 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
13019 #define BOX_12   "\342\224\224"  /* U+2514  '- */
13020 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
13021 #define BOX_123  "\342\224\234"  /* U+251c  |- */
13022 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
13023 #define BOX_234  "\342\224\254"  /* U+252c -,- */
13024 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
13025 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
13026
13027 /* Draw horizontal line N characters long using unicode box
13028 ** characters
13029 */
13030 static void print_box_line(FILE *out, int N){
13031   const char zDash[] = 
13032       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
13033       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
13034   const int nDash = sizeof(zDash) - 1;
13035   N *= 3;
13036   while( N>nDash ){
13037     utf8_printf(out, zDash);
13038     N -= nDash;
13039   }
13040   utf8_printf(out, "%.*s", N, zDash);
13041 }
13042
13043 /*
13044 ** Draw a horizontal separator for a MODE_Box table.
13045 */
13046 static void print_box_row_separator(
13047   ShellState *p,
13048   int nArg,
13049   const char *zSep1,
13050   const char *zSep2,
13051   const char *zSep3
13052 ){
13053   int i;
13054   if( nArg>0 ){
13055     utf8_printf(p->out, "%s", zSep1);
13056     print_box_line(p->out, p->actualWidth[0]+2);
13057     for(i=1; i<nArg; i++){
13058       utf8_printf(p->out, "%s", zSep2);
13059       print_box_line(p->out, p->actualWidth[i]+2);
13060     }
13061     utf8_printf(p->out, "%s", zSep3);
13062   }
13063   fputs("\n", p->out);
13064 }
13065
13066
13067
13068 /*
13069 ** Run a prepared statement and output the result in one of the
13070 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
13071 ** or MODE_Box.
13072 **
13073 ** This is different from ordinary exec_prepared_stmt() in that
13074 ** it has to run the entire query and gather the results into memory
13075 ** first, in order to determine column widths, before providing
13076 ** any output.
13077 */
13078 static void exec_prepared_stmt_columnar(
13079   ShellState *p,                        /* Pointer to ShellState */
13080   sqlite3_stmt *pStmt                   /* Statment to run */
13081 ){
13082   sqlite3_int64 nRow = 0;
13083   int nColumn = 0;
13084   char **azData = 0;
13085   sqlite3_int64 nAlloc = 0;
13086   const char *z;
13087   int rc;
13088   sqlite3_int64 i, nData;
13089   int j, nTotal, w, n;
13090   const char *colSep = 0;
13091   const char *rowSep = 0;
13092
13093   rc = sqlite3_step(pStmt);
13094   if( rc!=SQLITE_ROW ) return;
13095   nColumn = sqlite3_column_count(pStmt);
13096   nAlloc = nColumn*4;
13097   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
13098   if( azData==0 ) shell_out_of_memory();
13099   for(i=0; i<nColumn; i++){
13100     azData[i] = strdup(sqlite3_column_name(pStmt,i));
13101   }
13102   do{
13103     if( (nRow+2)*nColumn >= nAlloc ){
13104       nAlloc *= 2;
13105       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
13106       if( azData==0 ) shell_out_of_memory();
13107     }
13108     nRow++;
13109     for(i=0; i<nColumn; i++){
13110       z = (const char*)sqlite3_column_text(pStmt,i);
13111       azData[nRow*nColumn + i] = z ? strdup(z) : 0;
13112     }
13113   }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
13114   if( nColumn>p->nWidth ){
13115     p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
13116     if( p->colWidth==0 ) shell_out_of_memory();
13117     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
13118     p->nWidth = nColumn;
13119     p->actualWidth = &p->colWidth[nColumn];
13120   }
13121   memset(p->actualWidth, 0, nColumn*sizeof(int));
13122   for(i=0; i<nColumn; i++){
13123     w = p->colWidth[i];
13124     if( w<0 ) w = -w;
13125     p->actualWidth[i] = w;
13126   }
13127   nTotal = nColumn*(nRow+1);
13128   for(i=0; i<nTotal; i++){
13129     z = azData[i];
13130     if( z==0 ) z = p->nullValue;
13131     n = strlenChar(z);
13132     j = i%nColumn;
13133     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
13134   }
13135   if( seenInterrupt ) goto columnar_end;
13136   switch( p->cMode ){
13137     case MODE_Column: {
13138       colSep = "  ";
13139       rowSep = "\n";
13140       if( p->showHeader ){
13141         for(i=0; i<nColumn; i++){
13142           w = p->actualWidth[i];
13143           if( p->colWidth[i]<0 ) w = -w;
13144           utf8_width_print(p->out, w, azData[i]);
13145           fputs(i==nColumn-1?"\n":"  ", p->out);
13146         }
13147         for(i=0; i<nColumn; i++){
13148           print_dashes(p->out, p->actualWidth[i]);
13149           fputs(i==nColumn-1?"\n":"  ", p->out);
13150         }
13151       }
13152       break;
13153     }
13154     case MODE_Table: {
13155       colSep = " | ";
13156       rowSep = " |\n";
13157       print_row_separator(p, nColumn, "+");
13158       fputs("| ", p->out);
13159       for(i=0; i<nColumn; i++){
13160         w = p->actualWidth[i];
13161         n = strlenChar(azData[i]);
13162         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
13163         fputs(i==nColumn-1?" |\n":" | ", p->out);
13164       }
13165       print_row_separator(p, nColumn, "+");
13166       break;
13167     }
13168     case MODE_Markdown: {
13169       colSep = " | ";
13170       rowSep = " |\n";
13171       fputs("| ", p->out);
13172       for(i=0; i<nColumn; i++){
13173         w = p->actualWidth[i];
13174         n = strlenChar(azData[i]);
13175         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
13176         fputs(i==nColumn-1?" |\n":" | ", p->out);
13177       }
13178       print_row_separator(p, nColumn, "|");
13179       break;
13180     }
13181     case MODE_Box: {
13182       colSep = " " BOX_13 " ";
13183       rowSep = " " BOX_13 "\n";
13184       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
13185       utf8_printf(p->out, BOX_13 " ");
13186       for(i=0; i<nColumn; i++){
13187         w = p->actualWidth[i];
13188         n = strlenChar(azData[i]);
13189         utf8_printf(p->out, "%*s%s%*s%s",
13190             (w-n)/2, "", azData[i], (w-n+1)/2, "",
13191             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
13192       }
13193       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
13194       break;
13195     }
13196   }
13197   for(i=nColumn, j=0; i<nTotal; i++, j++){
13198     if( j==0 && p->cMode!=MODE_Column ){
13199       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
13200     }
13201     z = azData[i];
13202     if( z==0 ) z = p->nullValue;
13203     w = p->actualWidth[j];
13204     if( p->colWidth[j]<0 ) w = -w;
13205     utf8_width_print(p->out, w, z);
13206     if( j==nColumn-1 ){
13207       utf8_printf(p->out, "%s", rowSep);
13208       j = -1;
13209       if( seenInterrupt ) goto columnar_end;
13210     }else{
13211       utf8_printf(p->out, "%s", colSep);
13212     }
13213   }
13214   if( p->cMode==MODE_Table ){
13215     print_row_separator(p, nColumn, "+");
13216   }else if( p->cMode==MODE_Box ){
13217     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
13218   }
13219 columnar_end:
13220   if( seenInterrupt ){
13221     utf8_printf(p->out, "Interrupt\n");
13222   }
13223   nData = (nRow+1)*nColumn;
13224   for(i=0; i<nData; i++) free(azData[i]);
13225   sqlite3_free(azData);
13226 }
13227
13228 /*
13229 ** Run a prepared statement
13230 */
13231 static void exec_prepared_stmt(
13232   ShellState *pArg,                                /* Pointer to ShellState */
13233   sqlite3_stmt *pStmt                              /* Statment to run */
13234 ){
13235   int rc;
13236
13237   if( pArg->cMode==MODE_Column
13238    || pArg->cMode==MODE_Table
13239    || pArg->cMode==MODE_Box
13240    || pArg->cMode==MODE_Markdown
13241   ){
13242     exec_prepared_stmt_columnar(pArg, pStmt);
13243     return;
13244   }
13245
13246   /* perform the first step.  this will tell us if we
13247   ** have a result set or not and how wide it is.
13248   */
13249   rc = sqlite3_step(pStmt);
13250   /* if we have a result set... */
13251   if( SQLITE_ROW == rc ){
13252     /* allocate space for col name ptr, value ptr, and type */
13253     int nCol = sqlite3_column_count(pStmt);
13254     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
13255     if( !pData ){
13256       rc = SQLITE_NOMEM;
13257     }else{
13258       char **azCols = (char **)pData;      /* Names of result columns */
13259       char **azVals = &azCols[nCol];       /* Results */
13260       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
13261       int i, x;
13262       assert(sizeof(int) <= sizeof(char *));
13263       /* save off ptrs to column names */
13264       for(i=0; i<nCol; i++){
13265         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
13266       }
13267       do{
13268         /* extract the data and data types */
13269         for(i=0; i<nCol; i++){
13270           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
13271           if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
13272             azVals[i] = "";
13273           }else{
13274             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
13275           }
13276           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
13277             rc = SQLITE_NOMEM;
13278             break; /* from for */
13279           }
13280         } /* end for */
13281
13282         /* if data and types extracted successfully... */
13283         if( SQLITE_ROW == rc ){
13284           /* call the supplied callback with the result row data */
13285           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
13286             rc = SQLITE_ABORT;
13287           }else{
13288             rc = sqlite3_step(pStmt);
13289           }
13290         }
13291       } while( SQLITE_ROW == rc );
13292       sqlite3_free(pData);
13293       if( pArg->cMode==MODE_Json ){
13294         fputs("]\n", pArg->out);
13295       }
13296     }
13297   }
13298 }
13299
13300 #ifndef SQLITE_OMIT_VIRTUALTABLE
13301 /*
13302 ** This function is called to process SQL if the previous shell command
13303 ** was ".expert". It passes the SQL in the second argument directly to
13304 ** the sqlite3expert object.
13305 **
13306 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
13307 ** code. In this case, (*pzErr) may be set to point to a buffer containing
13308 ** an English language error message. It is the responsibility of the
13309 ** caller to eventually free this buffer using sqlite3_free().
13310 */
13311 static int expertHandleSQL(
13312   ShellState *pState, 
13313   const char *zSql, 
13314   char **pzErr
13315 ){
13316   assert( pState->expert.pExpert );
13317   assert( pzErr==0 || *pzErr==0 );
13318   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
13319 }
13320
13321 /*
13322 ** This function is called either to silently clean up the object
13323 ** created by the ".expert" command (if bCancel==1), or to generate a 
13324 ** report from it and then clean it up (if bCancel==0).
13325 **
13326 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
13327 ** code. In this case, (*pzErr) may be set to point to a buffer containing
13328 ** an English language error message. It is the responsibility of the
13329 ** caller to eventually free this buffer using sqlite3_free().
13330 */
13331 static int expertFinish(
13332   ShellState *pState,
13333   int bCancel,
13334   char **pzErr
13335 ){
13336   int rc = SQLITE_OK;
13337   sqlite3expert *p = pState->expert.pExpert;
13338   assert( p );
13339   assert( bCancel || pzErr==0 || *pzErr==0 );
13340   if( bCancel==0 ){
13341     FILE *out = pState->out;
13342     int bVerbose = pState->expert.bVerbose;
13343
13344     rc = sqlite3_expert_analyze(p, pzErr);
13345     if( rc==SQLITE_OK ){
13346       int nQuery = sqlite3_expert_count(p);
13347       int i;
13348
13349       if( bVerbose ){
13350         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
13351         raw_printf(out, "-- Candidates -----------------------------\n");
13352         raw_printf(out, "%s\n", zCand);
13353       }
13354       for(i=0; i<nQuery; i++){
13355         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
13356         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
13357         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
13358         if( zIdx==0 ) zIdx = "(no new indexes)\n";
13359         if( bVerbose ){
13360           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
13361           raw_printf(out, "%s\n\n", zSql);
13362         }
13363         raw_printf(out, "%s\n", zIdx);
13364         raw_printf(out, "%s\n", zEQP);
13365       }
13366     }
13367   }
13368   sqlite3_expert_destroy(p);
13369   pState->expert.pExpert = 0;
13370   return rc;
13371 }
13372
13373 /*
13374 ** Implementation of ".expert" dot command.
13375 */
13376 static int expertDotCommand(
13377   ShellState *pState,             /* Current shell tool state */
13378   char **azArg,                   /* Array of arguments passed to dot command */
13379   int nArg                        /* Number of entries in azArg[] */
13380 ){
13381   int rc = SQLITE_OK;
13382   char *zErr = 0;
13383   int i;
13384   int iSample = 0;
13385
13386   assert( pState->expert.pExpert==0 );
13387   memset(&pState->expert, 0, sizeof(ExpertInfo));
13388
13389   for(i=1; rc==SQLITE_OK && i<nArg; i++){
13390     char *z = azArg[i];
13391     int n;
13392     if( z[0]=='-' && z[1]=='-' ) z++;
13393     n = strlen30(z);
13394     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
13395       pState->expert.bVerbose = 1;
13396     }
13397     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
13398       if( i==(nArg-1) ){
13399         raw_printf(stderr, "option requires an argument: %s\n", z);
13400         rc = SQLITE_ERROR;
13401       }else{
13402         iSample = (int)integerValue(azArg[++i]);
13403         if( iSample<0 || iSample>100 ){
13404           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
13405           rc = SQLITE_ERROR;
13406         }
13407       }
13408     }
13409     else{
13410       raw_printf(stderr, "unknown option: %s\n", z);
13411       rc = SQLITE_ERROR;
13412     }
13413   }
13414
13415   if( rc==SQLITE_OK ){
13416     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
13417     if( pState->expert.pExpert==0 ){
13418       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
13419       rc = SQLITE_ERROR;
13420     }else{
13421       sqlite3_expert_config(
13422           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
13423       );
13424     }
13425   }
13426
13427   return rc;
13428 }
13429 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13430
13431 /*
13432 ** Execute a statement or set of statements.  Print
13433 ** any result rows/columns depending on the current mode
13434 ** set via the supplied callback.
13435 **
13436 ** This is very similar to SQLite's built-in sqlite3_exec()
13437 ** function except it takes a slightly different callback
13438 ** and callback data argument.
13439 */
13440 static int shell_exec(
13441   ShellState *pArg,                         /* Pointer to ShellState */
13442   const char *zSql,                         /* SQL to be evaluated */
13443   char **pzErrMsg                           /* Error msg written here */
13444 ){
13445   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
13446   int rc = SQLITE_OK;             /* Return Code */
13447   int rc2;
13448   const char *zLeftover;          /* Tail of unprocessed SQL */
13449   sqlite3 *db = pArg->db;
13450
13451   if( pzErrMsg ){
13452     *pzErrMsg = NULL;
13453   }
13454
13455 #ifndef SQLITE_OMIT_VIRTUALTABLE
13456   if( pArg->expert.pExpert ){
13457     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
13458     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
13459   }
13460 #endif
13461
13462   while( zSql[0] && (SQLITE_OK == rc) ){
13463     static const char *zStmtSql;
13464     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
13465     if( SQLITE_OK != rc ){
13466       if( pzErrMsg ){
13467         *pzErrMsg = save_err_msg(db);
13468       }
13469     }else{
13470       if( !pStmt ){
13471         /* this happens for a comment or white-space */
13472         zSql = zLeftover;
13473         while( IsSpace(zSql[0]) ) zSql++;
13474         continue;
13475       }
13476       zStmtSql = sqlite3_sql(pStmt);
13477       if( zStmtSql==0 ) zStmtSql = "";
13478       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
13479
13480       /* save off the prepared statment handle and reset row count */
13481       if( pArg ){
13482         pArg->pStmt = pStmt;
13483         pArg->cnt = 0;
13484       }
13485
13486       /* echo the sql statement if echo on */
13487       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
13488         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
13489       }
13490
13491       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
13492       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
13493         sqlite3_stmt *pExplain;
13494         char *zEQP;
13495         int triggerEQP = 0;
13496         disable_debug_trace_modes();
13497         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
13498         if( pArg->autoEQP>=AUTOEQP_trigger ){
13499           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
13500         }
13501         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
13502         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
13503         if( rc==SQLITE_OK ){
13504           while( sqlite3_step(pExplain)==SQLITE_ROW ){
13505             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
13506             int iEqpId = sqlite3_column_int(pExplain, 0);
13507             int iParentId = sqlite3_column_int(pExplain, 1);
13508             if( zEQPLine==0 ) zEQPLine = "";
13509             if( zEQPLine[0]=='-' ) eqp_render(pArg);
13510             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
13511           }
13512           eqp_render(pArg);
13513         }
13514         sqlite3_finalize(pExplain);
13515         sqlite3_free(zEQP);
13516         if( pArg->autoEQP>=AUTOEQP_full ){
13517           /* Also do an EXPLAIN for ".eqp full" mode */
13518           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
13519           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
13520           if( rc==SQLITE_OK ){
13521             pArg->cMode = MODE_Explain;
13522             explain_data_prepare(pArg, pExplain);
13523             exec_prepared_stmt(pArg, pExplain);
13524             explain_data_delete(pArg);
13525           }
13526           sqlite3_finalize(pExplain);
13527           sqlite3_free(zEQP);
13528         }
13529         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
13530           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
13531           /* Reprepare pStmt before reactiving trace modes */
13532           sqlite3_finalize(pStmt);
13533           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
13534           if( pArg ) pArg->pStmt = pStmt;
13535         }
13536         restore_debug_trace_modes();
13537       }
13538
13539       if( pArg ){
13540         pArg->cMode = pArg->mode;
13541         if( pArg->autoExplain ){
13542           if( sqlite3_stmt_isexplain(pStmt)==1 ){
13543             pArg->cMode = MODE_Explain;
13544           }
13545           if( sqlite3_stmt_isexplain(pStmt)==2 ){
13546             pArg->cMode = MODE_EQP;
13547           }
13548         }
13549
13550         /* If the shell is currently in ".explain" mode, gather the extra
13551         ** data required to add indents to the output.*/
13552         if( pArg->cMode==MODE_Explain ){
13553           explain_data_prepare(pArg, pStmt);
13554         }
13555       }
13556
13557       bind_prepared_stmt(pArg, pStmt);
13558       exec_prepared_stmt(pArg, pStmt);
13559       explain_data_delete(pArg);
13560       eqp_render(pArg);
13561
13562       /* print usage stats if stats on */
13563       if( pArg && pArg->statsOn ){
13564         display_stats(db, pArg, 0);
13565       }
13566
13567       /* print loop-counters if required */
13568       if( pArg && pArg->scanstatsOn ){
13569         display_scanstats(db, pArg);
13570       }
13571
13572       /* Finalize the statement just executed. If this fails, save a
13573       ** copy of the error message. Otherwise, set zSql to point to the
13574       ** next statement to execute. */
13575       rc2 = sqlite3_finalize(pStmt);
13576       if( rc!=SQLITE_NOMEM ) rc = rc2;
13577       if( rc==SQLITE_OK ){
13578         zSql = zLeftover;
13579         while( IsSpace(zSql[0]) ) zSql++;
13580       }else if( pzErrMsg ){
13581         *pzErrMsg = save_err_msg(db);
13582       }
13583
13584       /* clear saved stmt handle */
13585       if( pArg ){
13586         pArg->pStmt = NULL;
13587       }
13588     }
13589   } /* end while */
13590
13591   return rc;
13592 }
13593
13594 /*
13595 ** Release memory previously allocated by tableColumnList().
13596 */
13597 static void freeColumnList(char **azCol){
13598   int i;
13599   for(i=1; azCol[i]; i++){
13600     sqlite3_free(azCol[i]);
13601   }
13602   /* azCol[0] is a static string */
13603   sqlite3_free(azCol);
13604 }
13605
13606 /*
13607 ** Return a list of pointers to strings which are the names of all
13608 ** columns in table zTab.   The memory to hold the names is dynamically
13609 ** allocated and must be released by the caller using a subsequent call
13610 ** to freeColumnList().
13611 **
13612 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
13613 ** value that needs to be preserved, then azCol[0] is filled in with the
13614 ** name of the rowid column.
13615 **
13616 ** The first regular column in the table is azCol[1].  The list is terminated
13617 ** by an entry with azCol[i]==0.
13618 */
13619 static char **tableColumnList(ShellState *p, const char *zTab){
13620   char **azCol = 0;
13621   sqlite3_stmt *pStmt;
13622   char *zSql;
13623   int nCol = 0;
13624   int nAlloc = 0;
13625   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
13626   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
13627   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
13628   int rc;
13629
13630   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
13631   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13632   sqlite3_free(zSql);
13633   if( rc ) return 0;
13634   while( sqlite3_step(pStmt)==SQLITE_ROW ){
13635     if( nCol>=nAlloc-2 ){
13636       nAlloc = nAlloc*2 + nCol + 10;
13637       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
13638       if( azCol==0 ) shell_out_of_memory();
13639     }
13640     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
13641     if( sqlite3_column_int(pStmt, 5) ){
13642       nPK++;
13643       if( nPK==1
13644        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
13645                           "INTEGER")==0
13646       ){
13647         isIPK = 1;
13648       }else{
13649         isIPK = 0;
13650       }
13651     }
13652   }
13653   sqlite3_finalize(pStmt);
13654   if( azCol==0 ) return 0;
13655   azCol[0] = 0;
13656   azCol[nCol+1] = 0;
13657
13658   /* The decision of whether or not a rowid really needs to be preserved
13659   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
13660   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
13661   ** rowids on tables where the rowid is inaccessible because there are other
13662   ** columns in the table named "rowid", "_rowid_", and "oid".
13663   */
13664   if( preserveRowid && isIPK ){
13665     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
13666     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
13667     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
13668     ** ROWID aliases.  To distinguish these cases, check to see if
13669     ** there is a "pk" entry in "PRAGMA index_list".  There will be
13670     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
13671     */
13672     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
13673                            " WHERE origin='pk'", zTab);
13674     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13675     sqlite3_free(zSql);
13676     if( rc ){
13677       freeColumnList(azCol);
13678       return 0;
13679     }
13680     rc = sqlite3_step(pStmt);
13681     sqlite3_finalize(pStmt);
13682     preserveRowid = rc==SQLITE_ROW;
13683   }
13684   if( preserveRowid ){
13685     /* Only preserve the rowid if we can find a name to use for the
13686     ** rowid */
13687     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
13688     int i, j;
13689     for(j=0; j<3; j++){
13690       for(i=1; i<=nCol; i++){
13691         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
13692       }
13693       if( i>nCol ){
13694         /* At this point, we know that azRowid[j] is not the name of any
13695         ** ordinary column in the table.  Verify that azRowid[j] is a valid
13696         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
13697         ** tables will fail this last check */
13698         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
13699         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
13700         break;
13701       }
13702     }
13703   }
13704   return azCol;
13705 }
13706
13707 /*
13708 ** Toggle the reverse_unordered_selects setting.
13709 */
13710 static void toggleSelectOrder(sqlite3 *db){
13711   sqlite3_stmt *pStmt = 0;
13712   int iSetting = 0;
13713   char zStmt[100];
13714   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
13715   if( sqlite3_step(pStmt)==SQLITE_ROW ){
13716     iSetting = sqlite3_column_int(pStmt, 0);
13717   }
13718   sqlite3_finalize(pStmt);
13719   sqlite3_snprintf(sizeof(zStmt), zStmt,
13720        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
13721   sqlite3_exec(db, zStmt, 0, 0, 0);
13722 }
13723
13724 /*
13725 ** This is a different callback routine used for dumping the database.
13726 ** Each row received by this callback consists of a table name,
13727 ** the table type ("index" or "table") and SQL to create the table.
13728 ** This routine should print text sufficient to recreate the table.
13729 */
13730 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
13731   int rc;
13732   const char *zTable;
13733   const char *zType;
13734   const char *zSql;
13735   ShellState *p = (ShellState *)pArg;
13736   int dataOnly;
13737   int noSys;
13738
13739   UNUSED_PARAMETER(azNotUsed);
13740   if( nArg!=3 || azArg==0 ) return 0;
13741   zTable = azArg[0];
13742   zType = azArg[1];
13743   zSql = azArg[2];
13744   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
13745   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
13746
13747   if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
13748     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
13749   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
13750     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
13751   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
13752     return 0;
13753   }else if( dataOnly ){
13754     /* no-op */
13755   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
13756     char *zIns;
13757     if( !p->writableSchema ){
13758       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
13759       p->writableSchema = 1;
13760     }
13761     zIns = sqlite3_mprintf(
13762        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
13763        "VALUES('table','%q','%q',0,'%q');",
13764        zTable, zTable, zSql);
13765     utf8_printf(p->out, "%s\n", zIns);
13766     sqlite3_free(zIns);
13767     return 0;
13768   }else{
13769     printSchemaLine(p->out, zSql, ";\n");
13770   }
13771
13772   if( strcmp(zType, "table")==0 ){
13773     ShellText sSelect;
13774     ShellText sTable;
13775     char **azCol;
13776     int i;
13777     char *savedDestTable;
13778     int savedMode;
13779
13780     azCol = tableColumnList(p, zTable);
13781     if( azCol==0 ){
13782       p->nErr++;
13783       return 0;
13784     }
13785
13786     /* Always quote the table name, even if it appears to be pure ascii,
13787     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
13788     initText(&sTable);
13789     appendText(&sTable, zTable, quoteChar(zTable));
13790     /* If preserving the rowid, add a column list after the table name.
13791     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
13792     ** instead of the usual "INSERT INTO tab VALUES(...)".
13793     */
13794     if( azCol[0] ){
13795       appendText(&sTable, "(", 0);
13796       appendText(&sTable, azCol[0], 0);
13797       for(i=1; azCol[i]; i++){
13798         appendText(&sTable, ",", 0);
13799         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
13800       }
13801       appendText(&sTable, ")", 0);
13802     }
13803
13804     /* Build an appropriate SELECT statement */
13805     initText(&sSelect);
13806     appendText(&sSelect, "SELECT ", 0);
13807     if( azCol[0] ){
13808       appendText(&sSelect, azCol[0], 0);
13809       appendText(&sSelect, ",", 0);
13810     }
13811     for(i=1; azCol[i]; i++){
13812       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
13813       if( azCol[i+1] ){
13814         appendText(&sSelect, ",", 0);
13815       }
13816     }
13817     freeColumnList(azCol);
13818     appendText(&sSelect, " FROM ", 0);
13819     appendText(&sSelect, zTable, quoteChar(zTable));
13820
13821     savedDestTable = p->zDestTable;
13822     savedMode = p->mode;
13823     p->zDestTable = sTable.z;
13824     p->mode = p->cMode = MODE_Insert;
13825     rc = shell_exec(p, sSelect.z, 0);
13826     if( (rc&0xff)==SQLITE_CORRUPT ){
13827       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
13828       toggleSelectOrder(p->db);
13829       shell_exec(p, sSelect.z, 0);
13830       toggleSelectOrder(p->db);
13831     }
13832     p->zDestTable = savedDestTable;
13833     p->mode = savedMode;
13834     freeText(&sTable);
13835     freeText(&sSelect);
13836     if( rc ) p->nErr++;
13837   }
13838   return 0;
13839 }
13840
13841 /*
13842 ** Run zQuery.  Use dump_callback() as the callback routine so that
13843 ** the contents of the query are output as SQL statements.
13844 **
13845 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
13846 ** "ORDER BY rowid DESC" to the end.
13847 */
13848 static int run_schema_dump_query(
13849   ShellState *p,
13850   const char *zQuery
13851 ){
13852   int rc;
13853   char *zErr = 0;
13854   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
13855   if( rc==SQLITE_CORRUPT ){
13856     char *zQ2;
13857     int len = strlen30(zQuery);
13858     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
13859     if( zErr ){
13860       utf8_printf(p->out, "/****** %s ******/\n", zErr);
13861       sqlite3_free(zErr);
13862       zErr = 0;
13863     }
13864     zQ2 = malloc( len+100 );
13865     if( zQ2==0 ) return rc;
13866     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
13867     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
13868     if( rc ){
13869       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
13870     }else{
13871       rc = SQLITE_CORRUPT;
13872     }
13873     sqlite3_free(zErr);
13874     free(zQ2);
13875   }
13876   return rc;
13877 }
13878
13879 /*
13880 ** Text of help messages.
13881 **
13882 ** The help text for each individual command begins with a line that starts
13883 ** with ".".  Subsequent lines are supplimental information.
13884 **
13885 ** There must be two or more spaces between the end of the command and the
13886 ** start of the description of what that command does.
13887 */
13888 static const char *(azHelp[]) = {
13889 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
13890   ".archive ...             Manage SQL archives",
13891   "   Each command must have exactly one of the following options:",
13892   "     -c, --create               Create a new archive",
13893   "     -u, --update               Add or update files with changed mtime",
13894   "     -i, --insert               Like -u but always add even if unchanged",
13895   "     -t, --list                 List contents of archive",
13896   "     -x, --extract              Extract files from archive",
13897   "   Optional arguments:",
13898   "     -v, --verbose              Print each filename as it is processed",
13899   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
13900   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
13901   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
13902   "     -n, --dryrun               Show the SQL that would have occurred",
13903   "   Examples:",
13904   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
13905   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
13906   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
13907   "   See also:",
13908   "      http://sqlite.org/cli.html#sqlar_archive_support",
13909 #endif
13910 #ifndef SQLITE_OMIT_AUTHORIZATION
13911   ".auth ON|OFF             Show authorizer callbacks",
13912 #endif
13913   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
13914   "       --append            Use the appendvfs",
13915   "       --async             Write to FILE without journal and fsync()",
13916   ".bail on|off             Stop after hitting an error.  Default OFF",
13917   ".binary on|off           Turn binary output on or off.  Default OFF",
13918   ".cd DIRECTORY            Change the working directory to DIRECTORY",
13919   ".changes on|off          Show number of rows changed by SQL",
13920   ".check GLOB              Fail if output since .testcase does not match",
13921   ".clone NEWDB             Clone data into NEWDB from the existing database",
13922   ".databases               List names and files of attached databases",
13923   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
13924   ".dbinfo ?DB?             Show status information about the database",
13925   ".dump ?TABLE?            Render database content as SQL",
13926   "   Options:",
13927   "     --data-only            Output only INSERT statements",
13928   "     --newlines             Allow unescaped newline characters in output",
13929   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
13930   "     --preserve-rowids      Include ROWID values in the output",
13931   "   TABLE is a LIKE pattern for the tables to dump",
13932   "   Additional LIKE patterns can be given in subsequent arguments",
13933   ".echo on|off             Turn command echo on or off",
13934   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
13935   "   Other Modes:",
13936 #ifdef SQLITE_DEBUG
13937   "      test                  Show raw EXPLAIN QUERY PLAN output",
13938   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
13939 #endif
13940   "      trigger               Like \"full\" but also show trigger bytecode",
13941   ".excel                   Display the output of next command in spreadsheet",
13942   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
13943   ".exit ?CODE?             Exit this program with return-code CODE",
13944   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
13945   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
13946   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
13947   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
13948   "   --help                  Show CMD details",
13949   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
13950   ".headers on|off          Turn display of headers on or off",
13951   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
13952   ".import FILE TABLE       Import data from FILE into TABLE",
13953   "   Options:",
13954   "     --ascii               Use \\037 and \\036 as column and row separators",
13955   "     --csv                 Use , and \\n as column and row separators",
13956   "     --skip N              Skip the first N rows of input",
13957   "     -v                    \"Verbose\" - increase auxiliary output",
13958   "   Notes:",
13959   "     *  If TABLE does not exist, it is created.  The first row of input",
13960   "        determines the column names.",
13961   "     *  If neither --csv or --ascii are used, the input mode is derived",
13962   "        from the \".mode\" output mode",
13963   "     *  If FILE begins with \"|\" then it is a command that generates the",
13964   "        input text.",
13965 #ifndef SQLITE_OMIT_TEST_CONTROL
13966   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
13967 #endif
13968   ".indexes ?TABLE?         Show names of indexes",
13969   "                           If TABLE is specified, only show indexes for",
13970   "                           tables matching TABLE using the LIKE operator.",
13971 #ifdef SQLITE_ENABLE_IOTRACE
13972   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
13973 #endif
13974   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
13975   ".lint OPTIONS            Report potential schema issues.",
13976   "     Options:",
13977   "        fkey-indexes     Find missing foreign key indexes",
13978 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13979   ".load FILE ?ENTRY?       Load an extension library",
13980 #endif
13981   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
13982   ".mode MODE ?TABLE?       Set output mode",
13983   "   MODE is one of:",
13984   "     ascii     Columns/rows delimited by 0x1F and 0x1E",
13985   "     box       Tables using unicode box-drawing characters",
13986   "     csv       Comma-separated values",
13987   "     column    Output in columns.  (See .width)",
13988   "     html      HTML <table> code",
13989   "     insert    SQL insert statements for TABLE",
13990   "     json      Results in a JSON array",
13991   "     line      One value per line",
13992   "     list      Values delimited by \"|\"",
13993   "     markdown  Markdown table format",
13994   "     quote     Escape answers as for SQL",
13995   "     table     ASCII-art table",
13996   "     tabs      Tab-separated values",
13997   "     tcl       TCL list elements",
13998   ".nullvalue STRING        Use STRING in place of NULL values",
13999   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
14000   "     If FILE begins with '|' then open as a pipe",
14001   "       --bom  Put a UTF8 byte-order mark at the beginning",
14002   "       -e     Send output to the system text editor",
14003   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
14004 #ifdef SQLITE_DEBUG
14005   ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
14006 #endif 
14007   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
14008   "     Options:",
14009   "        --append        Use appendvfs to append database to the end of FILE",
14010 #ifdef SQLITE_ENABLE_DESERIALIZE
14011   "        --deserialize   Load into memory useing sqlite3_deserialize()",
14012   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
14013   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
14014 #endif
14015   "        --new           Initialize FILE to an empty database",
14016   "        --nofollow      Do not follow symbolic links",
14017   "        --readonly      Open FILE readonly",
14018   "        --zip           FILE is a ZIP archive",
14019   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
14020   "   If FILE begins with '|' then open it as a pipe.",
14021   "   Options:",
14022   "     --bom                 Prefix output with a UTF8 byte-order mark",
14023   "     -e                    Send output to the system text editor",
14024   "     -x                    Send output as CSV to a spreadsheet",
14025   ".parameter CMD ...       Manage SQL parameter bindings",
14026   "   clear                   Erase all bindings",
14027   "   init                    Initialize the TEMP table that holds bindings",
14028   "   list                    List the current parameter bindings",
14029   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
14030   "                           PARAMETER should start with one of: $ : @ ?",
14031   "   unset PARAMETER         Remove PARAMETER from the binding table",
14032   ".print STRING...         Print literal STRING",
14033 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
14034   ".progress N              Invoke progress handler after every N opcodes",
14035   "   --limit N                 Interrupt after N progress callbacks",
14036   "   --once                    Do no more than one progress interrupt",
14037   "   --quiet|-q                No output except at interrupts",
14038   "   --reset                   Reset the count for each input and interrupt",
14039 #endif
14040   ".prompt MAIN CONTINUE    Replace the standard prompts",
14041   ".quit                    Exit this program",
14042   ".read FILE               Read input from FILE",
14043 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
14044   ".recover                 Recover as much data as possible from corrupt db.",
14045   "   --freelist-corrupt       Assume the freelist is corrupt",
14046   "   --recovery-db NAME       Store recovery metadata in database file NAME",
14047   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
14048   "   --no-rowids              Do not attempt to recover rowid values",
14049   "                            that are not also INTEGER PRIMARY KEYs",
14050 #endif
14051   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
14052   ".save FILE               Write in-memory database into FILE",
14053   ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
14054   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
14055   "   Options:",
14056   "      --indent             Try to pretty-print the schema",
14057   "      --nosys              Omit objects whose names start with \"sqlite_\"",
14058   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
14059   "    Options:",
14060   "       --init               Create a new SELFTEST table",
14061   "       -v                   Verbose output",
14062   ".separator COL ?ROW?     Change the column and row separators",
14063 #if defined(SQLITE_ENABLE_SESSION)
14064   ".session ?NAME? CMD ...  Create or control sessions",
14065   "   Subcommands:",
14066   "     attach TABLE             Attach TABLE",
14067   "     changeset FILE           Write a changeset into FILE",
14068   "     close                    Close one session",
14069   "     enable ?BOOLEAN?         Set or query the enable bit",
14070   "     filter GLOB...           Reject tables matching GLOBs",
14071   "     indirect ?BOOLEAN?       Mark or query the indirect status",
14072   "     isempty                  Query whether the session is empty",
14073   "     list                     List currently open session names",
14074   "     open DB NAME             Open a new session on DB",
14075   "     patchset FILE            Write a patchset into FILE",
14076   "   If ?NAME? is omitted, the first defined session is used.",
14077 #endif
14078   ".sha3sum ...             Compute a SHA3 hash of database content",
14079   "    Options:",
14080   "      --schema              Also hash the sqlite_schema table",
14081   "      --sha3-224            Use the sha3-224 algorithm",
14082   "      --sha3-256            Use the sha3-256 algorithm (default)",
14083   "      --sha3-384            Use the sha3-384 algorithm",
14084   "      --sha3-512            Use the sha3-512 algorithm",
14085   "    Any other argument is a LIKE pattern for tables to hash",
14086 #ifndef SQLITE_NOHAVE_SYSTEM
14087   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
14088 #endif
14089   ".show                    Show the current values for various settings",
14090   ".stats ?on|off?          Show stats or turn stats on or off",
14091 #ifndef SQLITE_NOHAVE_SYSTEM
14092   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
14093 #endif
14094   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
14095   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
14096   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
14097   "                           Run \".testctrl\" with no arguments for details",
14098   ".timeout MS              Try opening locked tables for MS milliseconds",
14099   ".timer on|off            Turn SQL timer on or off",
14100 #ifndef SQLITE_OMIT_TRACE
14101   ".trace ?OPTIONS?         Output each SQL statement as it is run",
14102   "    FILE                    Send output to FILE",
14103   "    stdout                  Send output to stdout",
14104   "    stderr                  Send output to stderr",
14105   "    off                     Disable tracing",
14106   "    --expanded              Expand query parameters",
14107 #ifdef SQLITE_ENABLE_NORMALIZE
14108   "    --normalized            Normal the SQL statements",
14109 #endif
14110   "    --plain                 Show SQL as it is input",
14111   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
14112   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
14113   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
14114   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
14115 #endif /* SQLITE_OMIT_TRACE */
14116 #ifdef SQLITE_DEBUG
14117   ".unmodule NAME ...       Unregister virtual table modules",
14118   "    --allexcept             Unregister everything except those named",
14119 #endif
14120   ".vfsinfo ?AUX?           Information about the top-level VFS",
14121   ".vfslist                 List all available VFSes",
14122   ".vfsname ?AUX?           Print the name of the VFS stack",
14123   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
14124   "     Negative values right-justify",
14125 };
14126
14127 /*
14128 ** Output help text.
14129 **
14130 ** zPattern describes the set of commands for which help text is provided.
14131 ** If zPattern is NULL, then show all commands, but only give a one-line
14132 ** description of each.
14133 **
14134 ** Return the number of matches.
14135 */
14136 static int showHelp(FILE *out, const char *zPattern){
14137   int i = 0;
14138   int j = 0;
14139   int n = 0;
14140   char *zPat;
14141   if( zPattern==0
14142    || zPattern[0]=='0'
14143    || strcmp(zPattern,"-a")==0
14144    || strcmp(zPattern,"-all")==0
14145    || strcmp(zPattern,"--all")==0
14146   ){
14147     /* Show all commands, but only one line per command */
14148     if( zPattern==0 ) zPattern = "";
14149     for(i=0; i<ArraySize(azHelp); i++){
14150       if( azHelp[i][0]=='.' || zPattern[0] ){
14151         utf8_printf(out, "%s\n", azHelp[i]);
14152         n++;
14153       }
14154     }
14155   }else{
14156     /* Look for commands that for which zPattern is an exact prefix */
14157     zPat = sqlite3_mprintf(".%s*", zPattern);
14158     for(i=0; i<ArraySize(azHelp); i++){
14159       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
14160         utf8_printf(out, "%s\n", azHelp[i]);
14161         j = i+1;
14162         n++;
14163       }
14164     }
14165     sqlite3_free(zPat);
14166     if( n ){
14167       if( n==1 ){
14168         /* when zPattern is a prefix of exactly one command, then include the
14169         ** details of that command, which should begin at offset j */
14170         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
14171           utf8_printf(out, "%s\n", azHelp[j]);
14172           j++;
14173         }
14174       }
14175       return n;
14176     }
14177     /* Look for commands that contain zPattern anywhere.  Show the complete
14178     ** text of all commands that match. */
14179     zPat = sqlite3_mprintf("%%%s%%", zPattern);
14180     for(i=0; i<ArraySize(azHelp); i++){
14181       if( azHelp[i][0]=='.' ) j = i;
14182       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
14183         utf8_printf(out, "%s\n", azHelp[j]);
14184         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
14185           j++;
14186           utf8_printf(out, "%s\n", azHelp[j]);
14187         }
14188         i = j;
14189         n++;
14190       }
14191     }
14192     sqlite3_free(zPat);
14193   }
14194   return n;
14195 }
14196
14197 /* Forward reference */
14198 static int process_input(ShellState *p);
14199
14200 /*
14201 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
14202 ** and return a pointer to the buffer. The caller is responsible for freeing
14203 ** the memory.
14204 **
14205 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
14206 ** read.
14207 **
14208 ** For convenience, a nul-terminator byte is always appended to the data read
14209 ** from the file before the buffer is returned. This byte is not included in
14210 ** the final value of (*pnByte), if applicable.
14211 **
14212 ** NULL is returned if any error is encountered. The final value of *pnByte
14213 ** is undefined in this case.
14214 */
14215 static char *readFile(const char *zName, int *pnByte){
14216   FILE *in = fopen(zName, "rb");
14217   long nIn;
14218   size_t nRead;
14219   char *pBuf;
14220   if( in==0 ) return 0;
14221   fseek(in, 0, SEEK_END);
14222   nIn = ftell(in);
14223   rewind(in);
14224   pBuf = sqlite3_malloc64( nIn+1 );
14225   if( pBuf==0 ){ fclose(in); return 0; }
14226   nRead = fread(pBuf, nIn, 1, in);
14227   fclose(in);
14228   if( nRead!=1 ){
14229     sqlite3_free(pBuf);
14230     return 0;
14231   }
14232   pBuf[nIn] = 0;
14233   if( pnByte ) *pnByte = nIn;
14234   return pBuf;
14235 }
14236
14237 #if defined(SQLITE_ENABLE_SESSION)
14238 /*
14239 ** Close a single OpenSession object and release all of its associated
14240 ** resources.
14241 */
14242 static void session_close(OpenSession *pSession){
14243   int i;
14244   sqlite3session_delete(pSession->p);
14245   sqlite3_free(pSession->zName);
14246   for(i=0; i<pSession->nFilter; i++){
14247     sqlite3_free(pSession->azFilter[i]);
14248   }
14249   sqlite3_free(pSession->azFilter);
14250   memset(pSession, 0, sizeof(OpenSession));
14251 }
14252 #endif
14253
14254 /*
14255 ** Close all OpenSession objects and release all associated resources.
14256 */
14257 #if defined(SQLITE_ENABLE_SESSION)
14258 static void session_close_all(ShellState *p){
14259   int i;
14260   for(i=0; i<p->nSession; i++){
14261     session_close(&p->aSession[i]);
14262   }
14263   p->nSession = 0;
14264 }
14265 #else
14266 # define session_close_all(X)
14267 #endif
14268
14269 /*
14270 ** Implementation of the xFilter function for an open session.  Omit
14271 ** any tables named by ".session filter" but let all other table through.
14272 */
14273 #if defined(SQLITE_ENABLE_SESSION)
14274 static int session_filter(void *pCtx, const char *zTab){
14275   OpenSession *pSession = (OpenSession*)pCtx;
14276   int i;
14277   for(i=0; i<pSession->nFilter; i++){
14278     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
14279   }
14280   return 1;
14281 }
14282 #endif
14283
14284 /*
14285 ** Try to deduce the type of file for zName based on its content.  Return
14286 ** one of the SHELL_OPEN_* constants.
14287 **
14288 ** If the file does not exist or is empty but its name looks like a ZIP
14289 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
14290 ** Otherwise, assume an ordinary database regardless of the filename if
14291 ** the type cannot be determined from content.
14292 */
14293 int deduceDatabaseType(const char *zName, int dfltZip){
14294   FILE *f = fopen(zName, "rb");
14295   size_t n;
14296   int rc = SHELL_OPEN_UNSPEC;
14297   char zBuf[100];
14298   if( f==0 ){
14299     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
14300        return SHELL_OPEN_ZIPFILE;
14301     }else{
14302        return SHELL_OPEN_NORMAL;
14303     }
14304   }
14305   n = fread(zBuf, 16, 1, f);
14306   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
14307     fclose(f);
14308     return SHELL_OPEN_NORMAL;
14309   }
14310   fseek(f, -25, SEEK_END);
14311   n = fread(zBuf, 25, 1, f);
14312   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
14313     rc = SHELL_OPEN_APPENDVFS;
14314   }else{
14315     fseek(f, -22, SEEK_END);
14316     n = fread(zBuf, 22, 1, f);
14317     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
14318        && zBuf[3]==0x06 ){
14319       rc = SHELL_OPEN_ZIPFILE;
14320     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
14321       rc = SHELL_OPEN_ZIPFILE;
14322     }
14323   }
14324   fclose(f);
14325   return rc;  
14326 }
14327
14328 #ifdef SQLITE_ENABLE_DESERIALIZE
14329 /*
14330 ** Reconstruct an in-memory database using the output from the "dbtotxt"
14331 ** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
14332 ** is 0, then read from standard input.
14333 */
14334 static unsigned char *readHexDb(ShellState *p, int *pnData){
14335   unsigned char *a = 0;
14336   int nLine;
14337   int n = 0;
14338   int pgsz = 0;
14339   int iOffset = 0;
14340   int j, k;
14341   int rc;
14342   FILE *in;
14343   unsigned int x[16];
14344   char zLine[1000];
14345   if( p->zDbFilename ){
14346     in = fopen(p->zDbFilename, "r");
14347     if( in==0 ){
14348       utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
14349       return 0;
14350     }
14351     nLine = 0;
14352   }else{
14353     in = p->in;
14354     nLine = p->lineno;
14355     if( in==0 ) in = stdin;
14356   }
14357   *pnData = 0;
14358   nLine++;
14359   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
14360   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
14361   if( rc!=2 ) goto readHexDb_error;
14362   if( n<0 ) goto readHexDb_error;
14363   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
14364   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
14365   a = sqlite3_malloc( n ? n : 1 );
14366   if( a==0 ){
14367     utf8_printf(stderr, "Out of memory!\n");
14368     goto readHexDb_error;
14369   }
14370   memset(a, 0, n);
14371   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
14372     utf8_printf(stderr, "invalid pagesize\n");
14373     goto readHexDb_error;
14374   }
14375   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
14376     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
14377     if( rc==2 ){
14378       iOffset = k;
14379       continue;
14380     }
14381     if( strncmp(zLine, "| end ", 6)==0 ){
14382       break;
14383     }
14384     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
14385                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
14386                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
14387     if( rc==17 ){
14388       k = iOffset+j;
14389       if( k+16<=n ){
14390         int ii;
14391         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
14392       }
14393     }
14394   }
14395   *pnData = n;
14396   if( in!=p->in ){
14397     fclose(in);
14398   }else{
14399     p->lineno = nLine;
14400   }
14401   return a;
14402
14403 readHexDb_error:
14404   if( in!=p->in ){
14405     fclose(in);
14406   }else{
14407     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
14408       nLine++;
14409       if(strncmp(zLine, "| end ", 6)==0 ) break;
14410     }
14411     p->lineno = nLine;
14412   }
14413   sqlite3_free(a);
14414   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
14415   return 0;
14416 }
14417 #endif /* SQLITE_ENABLE_DESERIALIZE */
14418
14419 /*
14420 ** Scalar function "shell_int32". The first argument to this function
14421 ** must be a blob. The second a non-negative integer. This function
14422 ** reads and returns a 32-bit big-endian integer from byte
14423 ** offset (4*<arg2>) of the blob.
14424 */
14425 static void shellInt32(
14426   sqlite3_context *context, 
14427   int argc, 
14428   sqlite3_value **argv
14429 ){
14430   const unsigned char *pBlob;
14431   int nBlob;
14432   int iInt;
14433
14434   UNUSED_PARAMETER(argc);
14435   nBlob = sqlite3_value_bytes(argv[0]);
14436   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
14437   iInt = sqlite3_value_int(argv[1]);
14438
14439   if( iInt>=0 && (iInt+1)*4<=nBlob ){
14440     const unsigned char *a = &pBlob[iInt*4];
14441     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
14442                        + ((sqlite3_int64)a[1]<<16)
14443                        + ((sqlite3_int64)a[2]<< 8)
14444                        + ((sqlite3_int64)a[3]<< 0);
14445     sqlite3_result_int64(context, iVal);
14446   }
14447 }
14448
14449 /*
14450 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
14451 ** using "..." with internal double-quote characters doubled.
14452 */
14453 static void shellIdQuote(
14454   sqlite3_context *context, 
14455   int argc, 
14456   sqlite3_value **argv
14457 ){
14458   const char *zName = (const char*)sqlite3_value_text(argv[0]);
14459   UNUSED_PARAMETER(argc);
14460   if( zName ){
14461     char *z = sqlite3_mprintf("\"%w\"", zName);
14462     sqlite3_result_text(context, z, -1, sqlite3_free);
14463   }
14464 }
14465
14466 /*
14467 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
14468 */
14469 static void shellUSleepFunc(
14470   sqlite3_context *context, 
14471   int argcUnused, 
14472   sqlite3_value **argv
14473 ){
14474   int sleep = sqlite3_value_int(argv[0]);
14475   (void)argcUnused;
14476   sqlite3_sleep(sleep/1000);
14477   sqlite3_result_int(context, sleep);
14478 }
14479
14480 /*
14481 ** Scalar function "shell_escape_crnl" used by the .recover command.
14482 ** The argument passed to this function is the output of built-in
14483 ** function quote(). If the first character of the input is "'", 
14484 ** indicating that the value passed to quote() was a text value,
14485 ** then this function searches the input for "\n" and "\r" characters
14486 ** and adds a wrapper similar to the following:
14487 **
14488 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
14489 **
14490 ** Or, if the first character of the input is not "'", then a copy
14491 ** of the input is returned.
14492 */
14493 static void shellEscapeCrnl(
14494   sqlite3_context *context, 
14495   int argc, 
14496   sqlite3_value **argv
14497 ){
14498   const char *zText = (const char*)sqlite3_value_text(argv[0]);
14499   UNUSED_PARAMETER(argc);
14500   if( zText[0]=='\'' ){
14501     int nText = sqlite3_value_bytes(argv[0]);
14502     int i;
14503     char zBuf1[20];
14504     char zBuf2[20];
14505     const char *zNL = 0;
14506     const char *zCR = 0;
14507     int nCR = 0;
14508     int nNL = 0;
14509
14510     for(i=0; zText[i]; i++){
14511       if( zNL==0 && zText[i]=='\n' ){
14512         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
14513         nNL = (int)strlen(zNL);
14514       }
14515       if( zCR==0 && zText[i]=='\r' ){
14516         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
14517         nCR = (int)strlen(zCR);
14518       }
14519     }
14520
14521     if( zNL || zCR ){
14522       int iOut = 0;
14523       i64 nMax = (nNL > nCR) ? nNL : nCR;
14524       i64 nAlloc = nMax * nText + (nMax+64)*2;
14525       char *zOut = (char*)sqlite3_malloc64(nAlloc);
14526       if( zOut==0 ){
14527         sqlite3_result_error_nomem(context);
14528         return;
14529       }
14530
14531       if( zNL && zCR ){
14532         memcpy(&zOut[iOut], "replace(replace(", 16);
14533         iOut += 16;
14534       }else{
14535         memcpy(&zOut[iOut], "replace(", 8);
14536         iOut += 8;
14537       }
14538       for(i=0; zText[i]; i++){
14539         if( zText[i]=='\n' ){
14540           memcpy(&zOut[iOut], zNL, nNL);
14541           iOut += nNL;
14542         }else if( zText[i]=='\r' ){
14543           memcpy(&zOut[iOut], zCR, nCR);
14544           iOut += nCR;
14545         }else{
14546           zOut[iOut] = zText[i];
14547           iOut++;
14548         }
14549       }
14550
14551       if( zNL ){
14552         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14553         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
14554         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
14555       }
14556       if( zCR ){
14557         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14558         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
14559         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
14560       }
14561
14562       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
14563       sqlite3_free(zOut);
14564       return;
14565     }
14566   }
14567
14568   sqlite3_result_value(context, argv[0]);
14569 }
14570
14571 /* Flags for open_db().
14572 **
14573 ** The default behavior of open_db() is to exit(1) if the database fails to
14574 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
14575 ** but still returns without calling exit.
14576 **
14577 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
14578 ** ZIP archive if the file does not exist or is empty and its name matches
14579 ** the *.zip pattern.
14580 */
14581 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
14582 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
14583
14584 /*
14585 ** Make sure the database is open.  If it is not, then open it.  If
14586 ** the database fails to open, print an error message and exit.
14587 */
14588 static void open_db(ShellState *p, int openFlags){
14589   if( p->db==0 ){
14590     if( p->openMode==SHELL_OPEN_UNSPEC ){
14591       if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
14592         p->openMode = SHELL_OPEN_NORMAL;
14593       }else{
14594         p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 
14595                              (openFlags & OPEN_DB_ZIPFILE)!=0);
14596       }
14597     }
14598     switch( p->openMode ){
14599       case SHELL_OPEN_APPENDVFS: {
14600         sqlite3_open_v2(p->zDbFilename, &p->db, 
14601            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
14602         break;
14603       }
14604       case SHELL_OPEN_HEXDB:
14605       case SHELL_OPEN_DESERIALIZE: {
14606         sqlite3_open(0, &p->db);
14607         break;
14608       }
14609       case SHELL_OPEN_ZIPFILE: {
14610         sqlite3_open(":memory:", &p->db);
14611         break;
14612       }
14613       case SHELL_OPEN_READONLY: {
14614         sqlite3_open_v2(p->zDbFilename, &p->db,
14615             SQLITE_OPEN_READONLY|p->openFlags, 0);
14616         break;
14617       }
14618       case SHELL_OPEN_UNSPEC:
14619       case SHELL_OPEN_NORMAL: {
14620         sqlite3_open_v2(p->zDbFilename, &p->db,
14621            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
14622         break;
14623       }
14624     }
14625     globalDb = p->db;
14626     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
14627       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
14628           p->zDbFilename, sqlite3_errmsg(p->db));
14629       if( openFlags & OPEN_DB_KEEPALIVE ){
14630         sqlite3_open(":memory:", &p->db);
14631         return;
14632       }
14633       exit(1);
14634     }
14635 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14636     sqlite3_enable_load_extension(p->db, 1);
14637 #endif
14638     sqlite3_fileio_init(p->db, 0, 0);
14639     sqlite3_shathree_init(p->db, 0, 0);
14640     sqlite3_completion_init(p->db, 0, 0);
14641     sqlite3_uint_init(p->db, 0, 0);
14642     sqlite3_decimal_init(p->db, 0, 0);
14643     sqlite3_ieee_init(p->db, 0, 0);
14644     sqlite3_series_init(p->db, 0, 0);
14645 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
14646     sqlite3_dbdata_init(p->db, 0, 0);
14647 #endif
14648 #ifdef SQLITE_HAVE_ZLIB
14649     sqlite3_zipfile_init(p->db, 0, 0);
14650     sqlite3_sqlar_init(p->db, 0, 0);
14651 #endif
14652     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
14653                             shellAddSchemaName, 0, 0);
14654     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
14655                             shellModuleSchema, 0, 0);
14656     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
14657                             shellPutsFunc, 0, 0);
14658     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
14659                             shellEscapeCrnl, 0, 0);
14660     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
14661                             shellInt32, 0, 0);
14662     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
14663                             shellIdQuote, 0, 0);
14664     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
14665                             shellUSleepFunc, 0, 0);
14666 #ifndef SQLITE_NOHAVE_SYSTEM
14667     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
14668                             editFunc, 0, 0);
14669     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
14670                             editFunc, 0, 0);
14671 #endif
14672     if( p->openMode==SHELL_OPEN_ZIPFILE ){
14673       char *zSql = sqlite3_mprintf(
14674          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
14675       sqlite3_exec(p->db, zSql, 0, 0, 0);
14676       sqlite3_free(zSql);
14677     }
14678 #ifdef SQLITE_ENABLE_DESERIALIZE
14679     else
14680     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
14681       int rc;
14682       int nData = 0;
14683       unsigned char *aData;
14684       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
14685         aData = (unsigned char*)readFile(p->zDbFilename, &nData);
14686       }else{
14687         aData = readHexDb(p, &nData);
14688         if( aData==0 ){
14689           return;
14690         }
14691       }
14692       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
14693                    SQLITE_DESERIALIZE_RESIZEABLE |
14694                    SQLITE_DESERIALIZE_FREEONCLOSE);
14695       if( rc ){
14696         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
14697       }
14698       if( p->szMax>0 ){
14699         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
14700       }
14701     }
14702 #endif
14703   }
14704 }
14705
14706 /*
14707 ** Attempt to close the databaes connection.  Report errors.
14708 */
14709 void close_db(sqlite3 *db){
14710   int rc = sqlite3_close(db);
14711   if( rc ){
14712     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
14713         rc, sqlite3_errmsg(db));
14714   } 
14715 }
14716
14717 #if HAVE_READLINE || HAVE_EDITLINE
14718 /*
14719 ** Readline completion callbacks
14720 */
14721 static char *readline_completion_generator(const char *text, int state){
14722   static sqlite3_stmt *pStmt = 0;
14723   char *zRet;
14724   if( state==0 ){
14725     char *zSql;
14726     sqlite3_finalize(pStmt);
14727     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
14728                            "  FROM completion(%Q) ORDER BY 1", text);
14729     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
14730     sqlite3_free(zSql);
14731   }
14732   if( sqlite3_step(pStmt)==SQLITE_ROW ){
14733     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
14734   }else{
14735     sqlite3_finalize(pStmt);
14736     pStmt = 0;
14737     zRet = 0;
14738   }
14739   return zRet;
14740 }
14741 static char **readline_completion(const char *zText, int iStart, int iEnd){
14742   rl_attempted_completion_over = 1;
14743   return rl_completion_matches(zText, readline_completion_generator);
14744 }
14745
14746 #elif HAVE_LINENOISE
14747 /*
14748 ** Linenoise completion callback
14749 */
14750 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
14751   int nLine = strlen30(zLine);
14752   int i, iStart;
14753   sqlite3_stmt *pStmt = 0;
14754   char *zSql;
14755   char zBuf[1000];
14756
14757   if( nLine>sizeof(zBuf)-30 ) return;
14758   if( zLine[0]=='.' || zLine[0]=='#') return;
14759   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
14760   if( i==nLine-1 ) return;
14761   iStart = i+1;
14762   memcpy(zBuf, zLine, iStart);
14763   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
14764                          "  FROM completion(%Q,%Q) ORDER BY 1",
14765                          &zLine[iStart], zLine);
14766   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
14767   sqlite3_free(zSql);
14768   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
14769   while( sqlite3_step(pStmt)==SQLITE_ROW ){
14770     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
14771     int nCompletion = sqlite3_column_bytes(pStmt, 0);
14772     if( iStart+nCompletion < sizeof(zBuf)-1 ){
14773       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
14774       linenoiseAddCompletion(lc, zBuf);
14775     }
14776   }
14777   sqlite3_finalize(pStmt);
14778 }
14779 #endif
14780
14781 /*
14782 ** Do C-language style dequoting.
14783 **
14784 **    \a    -> alarm
14785 **    \b    -> backspace
14786 **    \t    -> tab
14787 **    \n    -> newline
14788 **    \v    -> vertical tab
14789 **    \f    -> form feed
14790 **    \r    -> carriage return
14791 **    \s    -> space
14792 **    \"    -> "
14793 **    \'    -> '
14794 **    \\    -> backslash
14795 **    \NNN  -> ascii character NNN in octal
14796 */
14797 static void resolve_backslashes(char *z){
14798   int i, j;
14799   char c;
14800   while( *z && *z!='\\' ) z++;
14801   for(i=j=0; (c = z[i])!=0; i++, j++){
14802     if( c=='\\' && z[i+1]!=0 ){
14803       c = z[++i];
14804       if( c=='a' ){
14805         c = '\a';
14806       }else if( c=='b' ){
14807         c = '\b';
14808       }else if( c=='t' ){
14809         c = '\t';
14810       }else if( c=='n' ){
14811         c = '\n';
14812       }else if( c=='v' ){
14813         c = '\v';
14814       }else if( c=='f' ){
14815         c = '\f';
14816       }else if( c=='r' ){
14817         c = '\r';
14818       }else if( c=='"' ){
14819         c = '"';
14820       }else if( c=='\'' ){
14821         c = '\'';
14822       }else if( c=='\\' ){
14823         c = '\\';
14824       }else if( c>='0' && c<='7' ){
14825         c -= '0';
14826         if( z[i+1]>='0' && z[i+1]<='7' ){
14827           i++;
14828           c = (c<<3) + z[i] - '0';
14829           if( z[i+1]>='0' && z[i+1]<='7' ){
14830             i++;
14831             c = (c<<3) + z[i] - '0';
14832           }
14833         }
14834       }
14835     }
14836     z[j] = c;
14837   }
14838   if( j<i ) z[j] = 0;
14839 }
14840
14841 /*
14842 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
14843 ** for TRUE and FALSE.  Return the integer value if appropriate.
14844 */
14845 static int booleanValue(const char *zArg){
14846   int i;
14847   if( zArg[0]=='0' && zArg[1]=='x' ){
14848     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
14849   }else{
14850     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
14851   }
14852   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
14853   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
14854     return 1;
14855   }
14856   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
14857     return 0;
14858   }
14859   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
14860           zArg);
14861   return 0;
14862 }
14863
14864 /*
14865 ** Set or clear a shell flag according to a boolean value.
14866 */
14867 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
14868   if( booleanValue(zArg) ){
14869     ShellSetFlag(p, mFlag);
14870   }else{
14871     ShellClearFlag(p, mFlag);
14872   }
14873 }
14874
14875 /*
14876 ** Close an output file, assuming it is not stderr or stdout
14877 */
14878 static void output_file_close(FILE *f){
14879   if( f && f!=stdout && f!=stderr ) fclose(f);
14880 }
14881
14882 /*
14883 ** Try to open an output file.   The names "stdout" and "stderr" are
14884 ** recognized and do the right thing.  NULL is returned if the output
14885 ** filename is "off".
14886 */
14887 static FILE *output_file_open(const char *zFile, int bTextMode){
14888   FILE *f;
14889   if( strcmp(zFile,"stdout")==0 ){
14890     f = stdout;
14891   }else if( strcmp(zFile, "stderr")==0 ){
14892     f = stderr;
14893   }else if( strcmp(zFile, "off")==0 ){
14894     f = 0;
14895   }else{
14896     f = fopen(zFile, bTextMode ? "w" : "wb");
14897     if( f==0 ){
14898       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
14899     }
14900   }
14901   return f;
14902 }
14903
14904 #ifndef SQLITE_OMIT_TRACE
14905 /*
14906 ** A routine for handling output from sqlite3_trace().
14907 */
14908 static int sql_trace_callback(
14909   unsigned mType,         /* The trace type */
14910   void *pArg,             /* The ShellState pointer */
14911   void *pP,               /* Usually a pointer to sqlite_stmt */
14912   void *pX                /* Auxiliary output */
14913 ){
14914   ShellState *p = (ShellState*)pArg;
14915   sqlite3_stmt *pStmt;
14916   const char *zSql;
14917   int nSql;
14918   if( p->traceOut==0 ) return 0;
14919   if( mType==SQLITE_TRACE_CLOSE ){
14920     utf8_printf(p->traceOut, "-- closing database connection\n");
14921     return 0;
14922   }
14923   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
14924     zSql = (const char*)pX;
14925   }else{
14926     pStmt = (sqlite3_stmt*)pP;
14927     switch( p->eTraceType ){
14928       case SHELL_TRACE_EXPANDED: {
14929         zSql = sqlite3_expanded_sql(pStmt);
14930         break;
14931       }
14932 #ifdef SQLITE_ENABLE_NORMALIZE
14933       case SHELL_TRACE_NORMALIZED: {
14934         zSql = sqlite3_normalized_sql(pStmt);
14935         break;
14936       }
14937 #endif
14938       default: {
14939         zSql = sqlite3_sql(pStmt);
14940         break;
14941       }
14942     }
14943   }
14944   if( zSql==0 ) return 0;
14945   nSql = strlen30(zSql);
14946   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
14947   switch( mType ){
14948     case SQLITE_TRACE_ROW:
14949     case SQLITE_TRACE_STMT: {
14950       utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
14951       break;
14952     }
14953     case SQLITE_TRACE_PROFILE: {
14954       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
14955       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
14956       break;
14957     }
14958   }
14959   return 0;
14960 }
14961 #endif
14962
14963 /*
14964 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
14965 ** a useful spot to set a debugger breakpoint.
14966 */
14967 static void test_breakpoint(void){
14968   static int nCall = 0;
14969   nCall++;
14970 }
14971
14972 /*
14973 ** An object used to read a CSV and other files for import.
14974 */
14975 typedef struct ImportCtx ImportCtx;
14976 struct ImportCtx {
14977   const char *zFile;  /* Name of the input file */
14978   FILE *in;           /* Read the CSV text from this input stream */
14979   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
14980   char *z;            /* Accumulated text for a field */
14981   int n;              /* Number of bytes in z */
14982   int nAlloc;         /* Space allocated for z[] */
14983   int nLine;          /* Current line number */
14984   int nRow;           /* Number of rows imported */
14985   int nErr;           /* Number of errors encountered */
14986   int bNotFirst;      /* True if one or more bytes already read */
14987   int cTerm;          /* Character that terminated the most recent field */
14988   int cColSep;        /* The column separator character.  (Usually ",") */
14989   int cRowSep;        /* The row separator character.  (Usually "\n") */
14990 };
14991
14992 /* Clean up resourced used by an ImportCtx */
14993 static void import_cleanup(ImportCtx *p){
14994   if( p->in!=0 && p->xCloser!=0 ){
14995     p->xCloser(p->in);
14996     p->in = 0;
14997   }
14998   sqlite3_free(p->z);
14999   p->z = 0;
15000 }
15001
15002 /* Append a single byte to z[] */
15003 static void import_append_char(ImportCtx *p, int c){
15004   if( p->n+1>=p->nAlloc ){
15005     p->nAlloc += p->nAlloc + 100;
15006     p->z = sqlite3_realloc64(p->z, p->nAlloc);
15007     if( p->z==0 ) shell_out_of_memory();
15008   }
15009   p->z[p->n++] = (char)c;
15010 }
15011
15012 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
15013 ** with the option of having a separator other than ",".
15014 **
15015 **   +  Input comes from p->in.
15016 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
15017 **      from sqlite3_malloc64().
15018 **   +  Use p->cSep as the column separator.  The default is ",".
15019 **   +  Use p->rSep as the row separator.  The default is "\n".
15020 **   +  Keep track of the line number in p->nLine.
15021 **   +  Store the character that terminates the field in p->cTerm.  Store
15022 **      EOF on end-of-file.
15023 **   +  Report syntax errors on stderr
15024 */
15025 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
15026   int c;
15027   int cSep = p->cColSep;
15028   int rSep = p->cRowSep;
15029   p->n = 0;
15030   c = fgetc(p->in);
15031   if( c==EOF || seenInterrupt ){
15032     p->cTerm = EOF;
15033     return 0;
15034   }
15035   if( c=='"' ){
15036     int pc, ppc;
15037     int startLine = p->nLine;
15038     int cQuote = c;
15039     pc = ppc = 0;
15040     while( 1 ){
15041       c = fgetc(p->in);
15042       if( c==rSep ) p->nLine++;
15043       if( c==cQuote ){
15044         if( pc==cQuote ){
15045           pc = 0;
15046           continue;
15047         }
15048       }
15049       if( (c==cSep && pc==cQuote)
15050        || (c==rSep && pc==cQuote)
15051        || (c==rSep && pc=='\r' && ppc==cQuote)
15052        || (c==EOF && pc==cQuote)
15053       ){
15054         do{ p->n--; }while( p->z[p->n]!=cQuote );
15055         p->cTerm = c;
15056         break;
15057       }
15058       if( pc==cQuote && c!='\r' ){
15059         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
15060                 p->zFile, p->nLine, cQuote);
15061       }
15062       if( c==EOF ){
15063         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
15064                 p->zFile, startLine, cQuote);
15065         p->cTerm = c;
15066         break;
15067       }
15068       import_append_char(p, c);
15069       ppc = pc;
15070       pc = c;
15071     }
15072   }else{
15073     /* If this is the first field being parsed and it begins with the
15074     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
15075     if( (c&0xff)==0xef && p->bNotFirst==0 ){
15076       import_append_char(p, c);
15077       c = fgetc(p->in);
15078       if( (c&0xff)==0xbb ){
15079         import_append_char(p, c);
15080         c = fgetc(p->in);
15081         if( (c&0xff)==0xbf ){
15082           p->bNotFirst = 1;
15083           p->n = 0;
15084           return csv_read_one_field(p);
15085         }
15086       }
15087     }
15088     while( c!=EOF && c!=cSep && c!=rSep ){
15089       import_append_char(p, c);
15090       c = fgetc(p->in);
15091     }
15092     if( c==rSep ){
15093       p->nLine++;
15094       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
15095     }
15096     p->cTerm = c;
15097   }
15098   if( p->z ) p->z[p->n] = 0;
15099   p->bNotFirst = 1;
15100   return p->z;
15101 }
15102
15103 /* Read a single field of ASCII delimited text.
15104 **
15105 **   +  Input comes from p->in.
15106 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
15107 **      from sqlite3_malloc64().
15108 **   +  Use p->cSep as the column separator.  The default is "\x1F".
15109 **   +  Use p->rSep as the row separator.  The default is "\x1E".
15110 **   +  Keep track of the row number in p->nLine.
15111 **   +  Store the character that terminates the field in p->cTerm.  Store
15112 **      EOF on end-of-file.
15113 **   +  Report syntax errors on stderr
15114 */
15115 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
15116   int c;
15117   int cSep = p->cColSep;
15118   int rSep = p->cRowSep;
15119   p->n = 0;
15120   c = fgetc(p->in);
15121   if( c==EOF || seenInterrupt ){
15122     p->cTerm = EOF;
15123     return 0;
15124   }
15125   while( c!=EOF && c!=cSep && c!=rSep ){
15126     import_append_char(p, c);
15127     c = fgetc(p->in);
15128   }
15129   if( c==rSep ){
15130     p->nLine++;
15131   }
15132   p->cTerm = c;
15133   if( p->z ) p->z[p->n] = 0;
15134   return p->z;
15135 }
15136
15137 /*
15138 ** Try to transfer data for table zTable.  If an error is seen while
15139 ** moving forward, try to go backwards.  The backwards movement won't
15140 ** work for WITHOUT ROWID tables.
15141 */
15142 static void tryToCloneData(
15143   ShellState *p,
15144   sqlite3 *newDb,
15145   const char *zTable
15146 ){
15147   sqlite3_stmt *pQuery = 0;
15148   sqlite3_stmt *pInsert = 0;
15149   char *zQuery = 0;
15150   char *zInsert = 0;
15151   int rc;
15152   int i, j, n;
15153   int nTable = strlen30(zTable);
15154   int k = 0;
15155   int cnt = 0;
15156   const int spinRate = 10000;
15157
15158   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
15159   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15160   if( rc ){
15161     utf8_printf(stderr, "Error %d: %s on [%s]\n",
15162             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
15163             zQuery);
15164     goto end_data_xfer;
15165   }
15166   n = sqlite3_column_count(pQuery);
15167   zInsert = sqlite3_malloc64(200 + nTable + n*3);
15168   if( zInsert==0 ) shell_out_of_memory();
15169   sqlite3_snprintf(200+nTable,zInsert,
15170                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
15171   i = strlen30(zInsert);
15172   for(j=1; j<n; j++){
15173     memcpy(zInsert+i, ",?", 2);
15174     i += 2;
15175   }
15176   memcpy(zInsert+i, ");", 3);
15177   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
15178   if( rc ){
15179     utf8_printf(stderr, "Error %d: %s on [%s]\n",
15180             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
15181             zQuery);
15182     goto end_data_xfer;
15183   }
15184   for(k=0; k<2; k++){
15185     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
15186       for(i=0; i<n; i++){
15187         switch( sqlite3_column_type(pQuery, i) ){
15188           case SQLITE_NULL: {
15189             sqlite3_bind_null(pInsert, i+1);
15190             break;
15191           }
15192           case SQLITE_INTEGER: {
15193             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
15194             break;
15195           }
15196           case SQLITE_FLOAT: {
15197             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
15198             break;
15199           }
15200           case SQLITE_TEXT: {
15201             sqlite3_bind_text(pInsert, i+1,
15202                              (const char*)sqlite3_column_text(pQuery,i),
15203                              -1, SQLITE_STATIC);
15204             break;
15205           }
15206           case SQLITE_BLOB: {
15207             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
15208                                             sqlite3_column_bytes(pQuery,i),
15209                                             SQLITE_STATIC);
15210             break;
15211           }
15212         }
15213       } /* End for */
15214       rc = sqlite3_step(pInsert);
15215       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
15216         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
15217                         sqlite3_errmsg(newDb));
15218       }
15219       sqlite3_reset(pInsert);
15220       cnt++;
15221       if( (cnt%spinRate)==0 ){
15222         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
15223         fflush(stdout);
15224       }
15225     } /* End while */
15226     if( rc==SQLITE_DONE ) break;
15227     sqlite3_finalize(pQuery);
15228     sqlite3_free(zQuery);
15229     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
15230                              zTable);
15231     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15232     if( rc ){
15233       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
15234       break;
15235     }
15236   } /* End for(k=0...) */
15237
15238 end_data_xfer:
15239   sqlite3_finalize(pQuery);
15240   sqlite3_finalize(pInsert);
15241   sqlite3_free(zQuery);
15242   sqlite3_free(zInsert);
15243 }
15244
15245
15246 /*
15247 ** Try to transfer all rows of the schema that match zWhere.  For
15248 ** each row, invoke xForEach() on the object defined by that row.
15249 ** If an error is encountered while moving forward through the
15250 ** sqlite_schema table, try again moving backwards.
15251 */
15252 static void tryToCloneSchema(
15253   ShellState *p,
15254   sqlite3 *newDb,
15255   const char *zWhere,
15256   void (*xForEach)(ShellState*,sqlite3*,const char*)
15257 ){
15258   sqlite3_stmt *pQuery = 0;
15259   char *zQuery = 0;
15260   int rc;
15261   const unsigned char *zName;
15262   const unsigned char *zSql;
15263   char *zErrMsg = 0;
15264
15265   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
15266                            " WHERE %s", zWhere);
15267   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15268   if( rc ){
15269     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
15270                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
15271                     zQuery);
15272     goto end_schema_xfer;
15273   }
15274   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
15275     zName = sqlite3_column_text(pQuery, 0);
15276     zSql = sqlite3_column_text(pQuery, 1);
15277     printf("%s... ", zName); fflush(stdout);
15278     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
15279     if( zErrMsg ){
15280       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
15281       sqlite3_free(zErrMsg);
15282       zErrMsg = 0;
15283     }
15284     if( xForEach ){
15285       xForEach(p, newDb, (const char*)zName);
15286     }
15287     printf("done\n");
15288   }
15289   if( rc!=SQLITE_DONE ){
15290     sqlite3_finalize(pQuery);
15291     sqlite3_free(zQuery);
15292     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
15293                              " WHERE %s ORDER BY rowid DESC", zWhere);
15294     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
15295     if( rc ){
15296       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
15297                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
15298                       zQuery);
15299       goto end_schema_xfer;
15300     }
15301     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
15302       zName = sqlite3_column_text(pQuery, 0);
15303       zSql = sqlite3_column_text(pQuery, 1);
15304       printf("%s... ", zName); fflush(stdout);
15305       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
15306       if( zErrMsg ){
15307         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
15308         sqlite3_free(zErrMsg);
15309         zErrMsg = 0;
15310       }
15311       if( xForEach ){
15312         xForEach(p, newDb, (const char*)zName);
15313       }
15314       printf("done\n");
15315     }
15316   }
15317 end_schema_xfer:
15318   sqlite3_finalize(pQuery);
15319   sqlite3_free(zQuery);
15320 }
15321
15322 /*
15323 ** Open a new database file named "zNewDb".  Try to recover as much information
15324 ** as possible out of the main database (which might be corrupt) and write it
15325 ** into zNewDb.
15326 */
15327 static void tryToClone(ShellState *p, const char *zNewDb){
15328   int rc;
15329   sqlite3 *newDb = 0;
15330   if( access(zNewDb,0)==0 ){
15331     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
15332     return;
15333   }
15334   rc = sqlite3_open(zNewDb, &newDb);
15335   if( rc ){
15336     utf8_printf(stderr, "Cannot create output database: %s\n",
15337             sqlite3_errmsg(newDb));
15338   }else{
15339     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
15340     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
15341     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
15342     tryToCloneSchema(p, newDb, "type!='table'", 0);
15343     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
15344     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
15345   }
15346   close_db(newDb);
15347 }
15348
15349 /*
15350 ** Change the output file back to stdout.
15351 **
15352 ** If the p->doXdgOpen flag is set, that means the output was being
15353 ** redirected to a temporary file named by p->zTempFile.  In that case,
15354 ** launch start/open/xdg-open on that temporary file.
15355 */
15356 static void output_reset(ShellState *p){
15357   if( p->outfile[0]=='|' ){
15358 #ifndef SQLITE_OMIT_POPEN
15359     pclose(p->out);
15360 #endif
15361   }else{
15362     output_file_close(p->out);
15363 #ifndef SQLITE_NOHAVE_SYSTEM
15364     if( p->doXdgOpen ){
15365       const char *zXdgOpenCmd =
15366 #if defined(_WIN32)
15367       "start";
15368 #elif defined(__APPLE__)
15369       "open";
15370 #else
15371       "xdg-open";
15372 #endif
15373       char *zCmd;
15374       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
15375       if( system(zCmd) ){
15376         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
15377       }else{
15378         /* Give the start/open/xdg-open command some time to get
15379         ** going before we continue, and potential delete the
15380         ** p->zTempFile data file out from under it */
15381         sqlite3_sleep(2000);
15382       }
15383       sqlite3_free(zCmd);
15384       outputModePop(p);
15385       p->doXdgOpen = 0;
15386     }
15387 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
15388   }
15389   p->outfile[0] = 0;
15390   p->out = stdout;
15391 }
15392
15393 /*
15394 ** Run an SQL command and return the single integer result.
15395 */
15396 static int db_int(ShellState *p, const char *zSql){
15397   sqlite3_stmt *pStmt;
15398   int res = 0;
15399   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
15400   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
15401     res = sqlite3_column_int(pStmt,0);
15402   }
15403   sqlite3_finalize(pStmt);
15404   return res;
15405 }
15406
15407 /*
15408 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
15409 */
15410 static unsigned int get2byteInt(unsigned char *a){
15411   return (a[0]<<8) + a[1];
15412 }
15413 static unsigned int get4byteInt(unsigned char *a){
15414   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
15415 }
15416
15417 /*
15418 ** Implementation of the ".dbinfo" command.
15419 **
15420 ** Return 1 on error, 2 to exit, and 0 otherwise.
15421 */
15422 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
15423   static const struct { const char *zName; int ofst; } aField[] = {
15424      { "file change counter:",  24  },
15425      { "database page count:",  28  },
15426      { "freelist page count:",  36  },
15427      { "schema cookie:",        40  },
15428      { "schema format:",        44  },
15429      { "default cache size:",   48  },
15430      { "autovacuum top root:",  52  },
15431      { "incremental vacuum:",   64  },
15432      { "text encoding:",        56  },
15433      { "user version:",         60  },
15434      { "application id:",       68  },
15435      { "software version:",     96  },
15436   };
15437   static const struct { const char *zName; const char *zSql; } aQuery[] = {
15438      { "number of tables:",
15439        "SELECT count(*) FROM %s WHERE type='table'" },
15440      { "number of indexes:",
15441        "SELECT count(*) FROM %s WHERE type='index'" },
15442      { "number of triggers:",
15443        "SELECT count(*) FROM %s WHERE type='trigger'" },
15444      { "number of views:",
15445        "SELECT count(*) FROM %s WHERE type='view'" },
15446      { "schema size:",
15447        "SELECT total(length(sql)) FROM %s" },
15448   };
15449   int i, rc;
15450   unsigned iDataVersion;
15451   char *zSchemaTab;
15452   char *zDb = nArg>=2 ? azArg[1] : "main";
15453   sqlite3_stmt *pStmt = 0;
15454   unsigned char aHdr[100];
15455   open_db(p, 0);
15456   if( p->db==0 ) return 1;
15457   rc = sqlite3_prepare_v2(p->db,
15458              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
15459              -1, &pStmt, 0);
15460   if( rc ){
15461     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
15462     sqlite3_finalize(pStmt);
15463     return 1;
15464   }
15465   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
15466   if( sqlite3_step(pStmt)==SQLITE_ROW
15467    && sqlite3_column_bytes(pStmt,0)>100
15468   ){
15469     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
15470     sqlite3_finalize(pStmt);
15471   }else{
15472     raw_printf(stderr, "unable to read database header\n");
15473     sqlite3_finalize(pStmt);
15474     return 1;
15475   }
15476   i = get2byteInt(aHdr+16);
15477   if( i==1 ) i = 65536;
15478   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
15479   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
15480   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
15481   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
15482   for(i=0; i<ArraySize(aField); i++){
15483     int ofst = aField[i].ofst;
15484     unsigned int val = get4byteInt(aHdr + ofst);
15485     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
15486     switch( ofst ){
15487       case 56: {
15488         if( val==1 ) raw_printf(p->out, " (utf8)");
15489         if( val==2 ) raw_printf(p->out, " (utf16le)");
15490         if( val==3 ) raw_printf(p->out, " (utf16be)");
15491       }
15492     }
15493     raw_printf(p->out, "\n");
15494   }
15495   if( zDb==0 ){
15496     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
15497   }else if( strcmp(zDb,"temp")==0 ){
15498     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
15499   }else{
15500     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
15501   }
15502   for(i=0; i<ArraySize(aQuery); i++){
15503     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
15504     int val = db_int(p, zSql);
15505     sqlite3_free(zSql);
15506     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
15507   }
15508   sqlite3_free(zSchemaTab);
15509   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
15510   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
15511   return 0;
15512 }
15513
15514 /*
15515 ** Print the current sqlite3_errmsg() value to stderr and return 1.
15516 */
15517 static int shellDatabaseError(sqlite3 *db){
15518   const char *zErr = sqlite3_errmsg(db);
15519   utf8_printf(stderr, "Error: %s\n", zErr);
15520   return 1;
15521 }
15522
15523 /*
15524 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
15525 ** if they match and FALSE (0) if they do not match.
15526 **
15527 ** Globbing rules:
15528 **
15529 **      '*'       Matches any sequence of zero or more characters.
15530 **
15531 **      '?'       Matches exactly one character.
15532 **
15533 **     [...]      Matches one character from the enclosed list of
15534 **                characters.
15535 **
15536 **     [^...]     Matches one character not in the enclosed list.
15537 **
15538 **      '#'       Matches any sequence of one or more digits with an
15539 **                optional + or - sign in front
15540 **
15541 **      ' '       Any span of whitespace matches any other span of
15542 **                whitespace.
15543 **
15544 ** Extra whitespace at the end of z[] is ignored.
15545 */
15546 static int testcase_glob(const char *zGlob, const char *z){
15547   int c, c2;
15548   int invert;
15549   int seen;
15550
15551   while( (c = (*(zGlob++)))!=0 ){
15552     if( IsSpace(c) ){
15553       if( !IsSpace(*z) ) return 0;
15554       while( IsSpace(*zGlob) ) zGlob++;
15555       while( IsSpace(*z) ) z++;
15556     }else if( c=='*' ){
15557       while( (c=(*(zGlob++))) == '*' || c=='?' ){
15558         if( c=='?' && (*(z++))==0 ) return 0;
15559       }
15560       if( c==0 ){
15561         return 1;
15562       }else if( c=='[' ){
15563         while( *z && testcase_glob(zGlob-1,z)==0 ){
15564           z++;
15565         }
15566         return (*z)!=0;
15567       }
15568       while( (c2 = (*(z++)))!=0 ){
15569         while( c2!=c ){
15570           c2 = *(z++);
15571           if( c2==0 ) return 0;
15572         }
15573         if( testcase_glob(zGlob,z) ) return 1;
15574       }
15575       return 0;
15576     }else if( c=='?' ){
15577       if( (*(z++))==0 ) return 0;
15578     }else if( c=='[' ){
15579       int prior_c = 0;
15580       seen = 0;
15581       invert = 0;
15582       c = *(z++);
15583       if( c==0 ) return 0;
15584       c2 = *(zGlob++);
15585       if( c2=='^' ){
15586         invert = 1;
15587         c2 = *(zGlob++);
15588       }
15589       if( c2==']' ){
15590         if( c==']' ) seen = 1;
15591         c2 = *(zGlob++);
15592       }
15593       while( c2 && c2!=']' ){
15594         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
15595           c2 = *(zGlob++);
15596           if( c>=prior_c && c<=c2 ) seen = 1;
15597           prior_c = 0;
15598         }else{
15599           if( c==c2 ){
15600             seen = 1;
15601           }
15602           prior_c = c2;
15603         }
15604         c2 = *(zGlob++);
15605       }
15606       if( c2==0 || (seen ^ invert)==0 ) return 0;
15607     }else if( c=='#' ){
15608       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
15609       if( !IsDigit(z[0]) ) return 0;
15610       z++;
15611       while( IsDigit(z[0]) ){ z++; }
15612     }else{
15613       if( c!=(*(z++)) ) return 0;
15614     }
15615   }
15616   while( IsSpace(*z) ){ z++; }
15617   return *z==0;
15618 }
15619
15620
15621 /*
15622 ** Compare the string as a command-line option with either one or two
15623 ** initial "-" characters.
15624 */
15625 static int optionMatch(const char *zStr, const char *zOpt){
15626   if( zStr[0]!='-' ) return 0;
15627   zStr++;
15628   if( zStr[0]=='-' ) zStr++;
15629   return strcmp(zStr, zOpt)==0;
15630 }
15631
15632 /*
15633 ** Delete a file.
15634 */
15635 int shellDeleteFile(const char *zFilename){
15636   int rc;
15637 #ifdef _WIN32
15638   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
15639   rc = _wunlink(z);
15640   sqlite3_free(z);
15641 #else
15642   rc = unlink(zFilename);
15643 #endif
15644   return rc;
15645 }
15646
15647 /*
15648 ** Try to delete the temporary file (if there is one) and free the
15649 ** memory used to hold the name of the temp file.
15650 */
15651 static void clearTempFile(ShellState *p){
15652   if( p->zTempFile==0 ) return;
15653   if( p->doXdgOpen ) return;
15654   if( shellDeleteFile(p->zTempFile) ) return;
15655   sqlite3_free(p->zTempFile);
15656   p->zTempFile = 0;
15657 }
15658
15659 /*
15660 ** Create a new temp file name with the given suffix.
15661 */
15662 static void newTempFile(ShellState *p, const char *zSuffix){
15663   clearTempFile(p);
15664   sqlite3_free(p->zTempFile);
15665   p->zTempFile = 0;
15666   if( p->db ){
15667     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
15668   }
15669   if( p->zTempFile==0 ){
15670     /* If p->db is an in-memory database then the TEMPFILENAME file-control
15671     ** will not work and we will need to fallback to guessing */
15672     char *zTemp;
15673     sqlite3_uint64 r;
15674     sqlite3_randomness(sizeof(r), &r);
15675     zTemp = getenv("TEMP");
15676     if( zTemp==0 ) zTemp = getenv("TMP");
15677     if( zTemp==0 ){
15678 #ifdef _WIN32
15679       zTemp = "\\tmp";
15680 #else
15681       zTemp = "/tmp";
15682 #endif
15683     }
15684     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
15685   }else{
15686     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
15687   }
15688   if( p->zTempFile==0 ){
15689     raw_printf(stderr, "out of memory\n");
15690     exit(1);
15691   }
15692 }
15693
15694
15695 /*
15696 ** The implementation of SQL scalar function fkey_collate_clause(), used
15697 ** by the ".lint fkey-indexes" command. This scalar function is always
15698 ** called with four arguments - the parent table name, the parent column name,
15699 ** the child table name and the child column name.
15700 **
15701 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
15702 **
15703 ** If either of the named tables or columns do not exist, this function
15704 ** returns an empty string. An empty string is also returned if both tables
15705 ** and columns exist but have the same default collation sequence. Or,
15706 ** if both exist but the default collation sequences are different, this
15707 ** function returns the string " COLLATE <parent-collation>", where
15708 ** <parent-collation> is the default collation sequence of the parent column.
15709 */
15710 static void shellFkeyCollateClause(
15711   sqlite3_context *pCtx,
15712   int nVal,
15713   sqlite3_value **apVal
15714 ){
15715   sqlite3 *db = sqlite3_context_db_handle(pCtx);
15716   const char *zParent;
15717   const char *zParentCol;
15718   const char *zParentSeq;
15719   const char *zChild;
15720   const char *zChildCol;
15721   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
15722   int rc;
15723
15724   assert( nVal==4 );
15725   zParent = (const char*)sqlite3_value_text(apVal[0]);
15726   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
15727   zChild = (const char*)sqlite3_value_text(apVal[2]);
15728   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
15729
15730   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
15731   rc = sqlite3_table_column_metadata(
15732       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
15733   );
15734   if( rc==SQLITE_OK ){
15735     rc = sqlite3_table_column_metadata(
15736         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
15737     );
15738   }
15739
15740   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
15741     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
15742     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
15743     sqlite3_free(z);
15744   }
15745 }
15746
15747
15748 /*
15749 ** The implementation of dot-command ".lint fkey-indexes".
15750 */
15751 static int lintFkeyIndexes(
15752   ShellState *pState,             /* Current shell tool state */
15753   char **azArg,                   /* Array of arguments passed to dot command */
15754   int nArg                        /* Number of entries in azArg[] */
15755 ){
15756   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
15757   FILE *out = pState->out;        /* Stream to write non-error output to */
15758   int bVerbose = 0;               /* If -verbose is present */
15759   int bGroupByParent = 0;         /* If -groupbyparent is present */
15760   int i;                          /* To iterate through azArg[] */
15761   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
15762   int rc;                         /* Return code */
15763   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
15764
15765   /*
15766   ** This SELECT statement returns one row for each foreign key constraint
15767   ** in the schema of the main database. The column values are:
15768   **
15769   ** 0. The text of an SQL statement similar to:
15770   **
15771   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
15772   **
15773   **    This SELECT is similar to the one that the foreign keys implementation
15774   **    needs to run internally on child tables. If there is an index that can
15775   **    be used to optimize this query, then it can also be used by the FK
15776   **    implementation to optimize DELETE or UPDATE statements on the parent
15777   **    table.
15778   **
15779   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
15780   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
15781   **    contains an index that can be used to optimize the query.
15782   **
15783   ** 2. Human readable text that describes the child table and columns. e.g.
15784   **
15785   **       "child_table(child_key1, child_key2)"
15786   **
15787   ** 3. Human readable text that describes the parent table and columns. e.g.
15788   **
15789   **       "parent_table(parent_key1, parent_key2)"
15790   **
15791   ** 4. A full CREATE INDEX statement for an index that could be used to
15792   **    optimize DELETE or UPDATE statements on the parent table. e.g.
15793   **
15794   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
15795   **
15796   ** 5. The name of the parent table.
15797   **
15798   ** These six values are used by the C logic below to generate the report.
15799   */
15800   const char *zSql =
15801   "SELECT "
15802     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
15803     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
15804     "  || fkey_collate_clause("
15805     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
15806     ", "
15807     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
15808     "  || group_concat('*=?', ' AND ') || ')'"
15809     ", "
15810     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
15811     ", "
15812     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
15813     ", "
15814     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
15815     "  || ' ON ' || quote(s.name) || '('"
15816     "  || group_concat(quote(f.[from]) ||"
15817     "        fkey_collate_clause("
15818     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
15819     "  || ');'"
15820     ", "
15821     "     f.[table] "
15822     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
15823     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
15824     "GROUP BY s.name, f.id "
15825     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
15826   ;
15827   const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
15828
15829   for(i=2; i<nArg; i++){
15830     int n = strlen30(azArg[i]);
15831     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
15832       bVerbose = 1;
15833     }
15834     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
15835       bGroupByParent = 1;
15836       zIndent = "    ";
15837     }
15838     else{
15839       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
15840           azArg[0], azArg[1]
15841       );
15842       return SQLITE_ERROR;
15843     }
15844   }
15845
15846   /* Register the fkey_collate_clause() SQL function */
15847   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
15848       0, shellFkeyCollateClause, 0, 0
15849   );
15850
15851
15852   if( rc==SQLITE_OK ){
15853     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
15854   }
15855   if( rc==SQLITE_OK ){
15856     sqlite3_bind_int(pSql, 1, bGroupByParent);
15857   }
15858
15859   if( rc==SQLITE_OK ){
15860     int rc2;
15861     char *zPrev = 0;
15862     while( SQLITE_ROW==sqlite3_step(pSql) ){
15863       int res = -1;
15864       sqlite3_stmt *pExplain = 0;
15865       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
15866       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
15867       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
15868       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
15869       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
15870       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
15871
15872       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
15873       if( rc!=SQLITE_OK ) break;
15874       if( SQLITE_ROW==sqlite3_step(pExplain) ){
15875         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
15876         res = (
15877               0==sqlite3_strglob(zGlob, zPlan)
15878            || 0==sqlite3_strglob(zGlobIPK, zPlan)
15879         );
15880       }
15881       rc = sqlite3_finalize(pExplain);
15882       if( rc!=SQLITE_OK ) break;
15883
15884       if( res<0 ){
15885         raw_printf(stderr, "Error: internal error");
15886         break;
15887       }else{
15888         if( bGroupByParent
15889         && (bVerbose || res==0)
15890         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
15891         ){
15892           raw_printf(out, "-- Parent table %s\n", zParent);
15893           sqlite3_free(zPrev);
15894           zPrev = sqlite3_mprintf("%s", zParent);
15895         }
15896
15897         if( res==0 ){
15898           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
15899         }else if( bVerbose ){
15900           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
15901               zIndent, zFrom, zTarget
15902           );
15903         }
15904       }
15905     }
15906     sqlite3_free(zPrev);
15907
15908     if( rc!=SQLITE_OK ){
15909       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
15910     }
15911
15912     rc2 = sqlite3_finalize(pSql);
15913     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
15914       rc = rc2;
15915       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
15916     }
15917   }else{
15918     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
15919   }
15920
15921   return rc;
15922 }
15923
15924 /*
15925 ** Implementation of ".lint" dot command.
15926 */
15927 static int lintDotCommand(
15928   ShellState *pState,             /* Current shell tool state */
15929   char **azArg,                   /* Array of arguments passed to dot command */
15930   int nArg                        /* Number of entries in azArg[] */
15931 ){
15932   int n;
15933   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
15934   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
15935   return lintFkeyIndexes(pState, azArg, nArg);
15936
15937  usage:
15938   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
15939   raw_printf(stderr, "Where sub-commands are:\n");
15940   raw_printf(stderr, "    fkey-indexes\n");
15941   return SQLITE_ERROR;
15942 }
15943
15944 #if !defined SQLITE_OMIT_VIRTUALTABLE
15945 static void shellPrepare(
15946   sqlite3 *db, 
15947   int *pRc, 
15948   const char *zSql, 
15949   sqlite3_stmt **ppStmt
15950 ){
15951   *ppStmt = 0;
15952   if( *pRc==SQLITE_OK ){
15953     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
15954     if( rc!=SQLITE_OK ){
15955       raw_printf(stderr, "sql error: %s (%d)\n", 
15956           sqlite3_errmsg(db), sqlite3_errcode(db)
15957       );
15958       *pRc = rc;
15959     }
15960   }
15961 }
15962
15963 /*
15964 ** Create a prepared statement using printf-style arguments for the SQL.
15965 **
15966 ** This routine is could be marked "static".  But it is not always used,
15967 ** depending on compile-time options.  By omitting the "static", we avoid
15968 ** nuisance compiler warnings about "defined but not used".
15969 */
15970 void shellPreparePrintf(
15971   sqlite3 *db, 
15972   int *pRc, 
15973   sqlite3_stmt **ppStmt,
15974   const char *zFmt, 
15975   ...
15976 ){
15977   *ppStmt = 0;
15978   if( *pRc==SQLITE_OK ){
15979     va_list ap;
15980     char *z;
15981     va_start(ap, zFmt);
15982     z = sqlite3_vmprintf(zFmt, ap);
15983     va_end(ap);
15984     if( z==0 ){
15985       *pRc = SQLITE_NOMEM;
15986     }else{
15987       shellPrepare(db, pRc, z, ppStmt);
15988       sqlite3_free(z);
15989     }
15990   }
15991 }
15992
15993 /* Finalize the prepared statement created using shellPreparePrintf().
15994 **
15995 ** This routine is could be marked "static".  But it is not always used,
15996 ** depending on compile-time options.  By omitting the "static", we avoid
15997 ** nuisance compiler warnings about "defined but not used".
15998 */
15999 void shellFinalize(
16000   int *pRc, 
16001   sqlite3_stmt *pStmt
16002 ){
16003   if( pStmt ){
16004     sqlite3 *db = sqlite3_db_handle(pStmt);
16005     int rc = sqlite3_finalize(pStmt);
16006     if( *pRc==SQLITE_OK ){
16007       if( rc!=SQLITE_OK ){
16008         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
16009       }
16010       *pRc = rc;
16011     }
16012   }
16013 }
16014
16015 /* Reset the prepared statement created using shellPreparePrintf().
16016 **
16017 ** This routine is could be marked "static".  But it is not always used,
16018 ** depending on compile-time options.  By omitting the "static", we avoid
16019 ** nuisance compiler warnings about "defined but not used".
16020 */
16021 void shellReset(
16022   int *pRc, 
16023   sqlite3_stmt *pStmt
16024 ){
16025   int rc = sqlite3_reset(pStmt);
16026   if( *pRc==SQLITE_OK ){
16027     if( rc!=SQLITE_OK ){
16028       sqlite3 *db = sqlite3_db_handle(pStmt);
16029       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
16030     }
16031     *pRc = rc;
16032   }
16033 }
16034 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
16035
16036 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16037 /******************************************************************************
16038 ** The ".archive" or ".ar" command.
16039 */
16040 /*
16041 ** Structure representing a single ".ar" command.
16042 */
16043 typedef struct ArCommand ArCommand;
16044 struct ArCommand {
16045   u8 eCmd;                        /* An AR_CMD_* value */
16046   u8 bVerbose;                    /* True if --verbose */
16047   u8 bZip;                        /* True if the archive is a ZIP */
16048   u8 bDryRun;                     /* True if --dry-run */
16049   u8 bAppend;                     /* True if --append */
16050   u8 fromCmdLine;                 /* Run from -A instead of .archive */
16051   int nArg;                       /* Number of command arguments */
16052   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
16053   const char *zFile;              /* --file argument, or NULL */
16054   const char *zDir;               /* --directory argument, or NULL */
16055   char **azArg;                   /* Array of command arguments */
16056   ShellState *p;                  /* Shell state */
16057   sqlite3 *db;                    /* Database containing the archive */
16058 };
16059
16060 /*
16061 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
16062 */
16063 static int arUsage(FILE *f){
16064   showHelp(f,"archive");
16065   return SQLITE_ERROR;
16066 }
16067
16068 /*
16069 ** Print an error message for the .ar command to stderr and return 
16070 ** SQLITE_ERROR.
16071 */
16072 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
16073   va_list ap;
16074   char *z;
16075   va_start(ap, zFmt);
16076   z = sqlite3_vmprintf(zFmt, ap);
16077   va_end(ap);
16078   utf8_printf(stderr, "Error: %s\n", z);
16079   if( pAr->fromCmdLine ){
16080     utf8_printf(stderr, "Use \"-A\" for more help\n");
16081   }else{
16082     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
16083   }
16084   sqlite3_free(z);
16085   return SQLITE_ERROR;
16086 }
16087
16088 /*
16089 ** Values for ArCommand.eCmd.
16090 */
16091 #define AR_CMD_CREATE       1
16092 #define AR_CMD_UPDATE       2
16093 #define AR_CMD_INSERT       3
16094 #define AR_CMD_EXTRACT      4
16095 #define AR_CMD_LIST         5
16096 #define AR_CMD_HELP         6
16097
16098 /*
16099 ** Other (non-command) switches.
16100 */
16101 #define AR_SWITCH_VERBOSE     7
16102 #define AR_SWITCH_FILE        8
16103 #define AR_SWITCH_DIRECTORY   9
16104 #define AR_SWITCH_APPEND     10
16105 #define AR_SWITCH_DRYRUN     11
16106
16107 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
16108   switch( eSwitch ){
16109     case AR_CMD_CREATE:
16110     case AR_CMD_EXTRACT:
16111     case AR_CMD_LIST:
16112     case AR_CMD_UPDATE:
16113     case AR_CMD_INSERT:
16114     case AR_CMD_HELP:
16115       if( pAr->eCmd ){
16116         return arErrorMsg(pAr, "multiple command options");
16117       }
16118       pAr->eCmd = eSwitch;
16119       break;
16120
16121     case AR_SWITCH_DRYRUN:
16122       pAr->bDryRun = 1;
16123       break;
16124     case AR_SWITCH_VERBOSE:
16125       pAr->bVerbose = 1;
16126       break;
16127     case AR_SWITCH_APPEND:
16128       pAr->bAppend = 1;
16129       /* Fall thru into --file */
16130     case AR_SWITCH_FILE:
16131       pAr->zFile = zArg;
16132       break;
16133     case AR_SWITCH_DIRECTORY:
16134       pAr->zDir = zArg;
16135       break;
16136   }
16137
16138   return SQLITE_OK;
16139 }
16140
16141 /*
16142 ** Parse the command line for an ".ar" command. The results are written into
16143 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
16144 ** successfully, otherwise an error message is written to stderr and 
16145 ** SQLITE_ERROR returned.
16146 */
16147 static int arParseCommand(
16148   char **azArg,                   /* Array of arguments passed to dot command */
16149   int nArg,                       /* Number of entries in azArg[] */
16150   ArCommand *pAr                  /* Populate this object */
16151 ){
16152   struct ArSwitch {
16153     const char *zLong;
16154     char cShort;
16155     u8 eSwitch;
16156     u8 bArg;
16157   } aSwitch[] = {
16158     { "create",    'c', AR_CMD_CREATE,       0 },
16159     { "extract",   'x', AR_CMD_EXTRACT,      0 },
16160     { "insert",    'i', AR_CMD_INSERT,       0 },
16161     { "list",      't', AR_CMD_LIST,         0 },
16162     { "update",    'u', AR_CMD_UPDATE,       0 },
16163     { "help",      'h', AR_CMD_HELP,         0 },
16164     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
16165     { "file",      'f', AR_SWITCH_FILE,      1 },
16166     { "append",    'a', AR_SWITCH_APPEND,    1 },
16167     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
16168     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
16169   };
16170   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
16171   struct ArSwitch *pEnd = &aSwitch[nSwitch];
16172
16173   if( nArg<=1 ){
16174     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
16175     return arUsage(stderr);
16176   }else{
16177     char *z = azArg[1];
16178     if( z[0]!='-' ){
16179       /* Traditional style [tar] invocation */
16180       int i;
16181       int iArg = 2;
16182       for(i=0; z[i]; i++){
16183         const char *zArg = 0;
16184         struct ArSwitch *pOpt;
16185         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
16186           if( z[i]==pOpt->cShort ) break;
16187         }
16188         if( pOpt==pEnd ){
16189           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
16190         }
16191         if( pOpt->bArg ){
16192           if( iArg>=nArg ){
16193             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
16194           }
16195           zArg = azArg[iArg++];
16196         }
16197         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
16198       }
16199       pAr->nArg = nArg-iArg;
16200       if( pAr->nArg>0 ){
16201         pAr->azArg = &azArg[iArg];
16202       }
16203     }else{
16204       /* Non-traditional invocation */
16205       int iArg;
16206       for(iArg=1; iArg<nArg; iArg++){
16207         int n;
16208         z = azArg[iArg];
16209         if( z[0]!='-' ){
16210           /* All remaining command line words are command arguments. */
16211           pAr->azArg = &azArg[iArg];
16212           pAr->nArg = nArg-iArg;
16213           break;
16214         }
16215         n = strlen30(z);
16216
16217         if( z[1]!='-' ){
16218           int i;
16219           /* One or more short options */
16220           for(i=1; i<n; i++){
16221             const char *zArg = 0;
16222             struct ArSwitch *pOpt;
16223             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
16224               if( z[i]==pOpt->cShort ) break;
16225             }
16226             if( pOpt==pEnd ){
16227               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
16228             }
16229             if( pOpt->bArg ){
16230               if( i<(n-1) ){
16231                 zArg = &z[i+1];
16232                 i = n;
16233               }else{
16234                 if( iArg>=(nArg-1) ){
16235                   return arErrorMsg(pAr, "option requires an argument: %c",
16236                                     z[i]);
16237                 }
16238                 zArg = azArg[++iArg];
16239               }
16240             }
16241             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
16242           }
16243         }else if( z[2]=='\0' ){
16244           /* A -- option, indicating that all remaining command line words
16245           ** are command arguments.  */
16246           pAr->azArg = &azArg[iArg+1];
16247           pAr->nArg = nArg-iArg-1;
16248           break;
16249         }else{
16250           /* A long option */
16251           const char *zArg = 0;             /* Argument for option, if any */
16252           struct ArSwitch *pMatch = 0;      /* Matching option */
16253           struct ArSwitch *pOpt;            /* Iterator */
16254           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
16255             const char *zLong = pOpt->zLong;
16256             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
16257               if( pMatch ){
16258                 return arErrorMsg(pAr, "ambiguous option: %s",z);
16259               }else{
16260                 pMatch = pOpt;
16261               }
16262             }
16263           }
16264
16265           if( pMatch==0 ){
16266             return arErrorMsg(pAr, "unrecognized option: %s", z);
16267           }
16268           if( pMatch->bArg ){
16269             if( iArg>=(nArg-1) ){
16270               return arErrorMsg(pAr, "option requires an argument: %s", z);
16271             }
16272             zArg = azArg[++iArg];
16273           }
16274           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
16275         }
16276       }
16277     }
16278   }
16279
16280   return SQLITE_OK;
16281 }
16282
16283 /*
16284 ** This function assumes that all arguments within the ArCommand.azArg[]
16285 ** array refer to archive members, as for the --extract or --list commands. 
16286 ** It checks that each of them are present. If any specified file is not
16287 ** present in the archive, an error is printed to stderr and an error
16288 ** code returned. Otherwise, if all specified arguments are present in
16289 ** the archive, SQLITE_OK is returned.
16290 **
16291 ** This function strips any trailing '/' characters from each argument.
16292 ** This is consistent with the way the [tar] command seems to work on
16293 ** Linux.
16294 */
16295 static int arCheckEntries(ArCommand *pAr){
16296   int rc = SQLITE_OK;
16297   if( pAr->nArg ){
16298     int i, j;
16299     sqlite3_stmt *pTest = 0;
16300
16301     shellPreparePrintf(pAr->db, &rc, &pTest,
16302         "SELECT name FROM %s WHERE name=$name", 
16303         pAr->zSrcTable
16304     );
16305     j = sqlite3_bind_parameter_index(pTest, "$name");
16306     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
16307       char *z = pAr->azArg[i];
16308       int n = strlen30(z);
16309       int bOk = 0;
16310       while( n>0 && z[n-1]=='/' ) n--;
16311       z[n] = '\0';
16312       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
16313       if( SQLITE_ROW==sqlite3_step(pTest) ){
16314         bOk = 1;
16315       }
16316       shellReset(&rc, pTest);
16317       if( rc==SQLITE_OK && bOk==0 ){
16318         utf8_printf(stderr, "not found in archive: %s\n", z);
16319         rc = SQLITE_ERROR;
16320       }
16321     }
16322     shellFinalize(&rc, pTest);
16323   }
16324   return rc;
16325 }
16326
16327 /*
16328 ** Format a WHERE clause that can be used against the "sqlar" table to
16329 ** identify all archive members that match the command arguments held
16330 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
16331 ** The caller is responsible for eventually calling sqlite3_free() on
16332 ** any non-NULL (*pzWhere) value.
16333 */
16334 static void arWhereClause(
16335   int *pRc, 
16336   ArCommand *pAr, 
16337   char **pzWhere                  /* OUT: New WHERE clause */
16338 ){
16339   char *zWhere = 0;
16340   if( *pRc==SQLITE_OK ){
16341     if( pAr->nArg==0 ){
16342       zWhere = sqlite3_mprintf("1");
16343     }else{
16344       int i;
16345       const char *zSep = "";
16346       for(i=0; i<pAr->nArg; i++){
16347         const char *z = pAr->azArg[i];
16348         zWhere = sqlite3_mprintf(
16349           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 
16350           zWhere, zSep, z, strlen30(z)+1, z
16351         );
16352         if( zWhere==0 ){
16353           *pRc = SQLITE_NOMEM;
16354           break;
16355         }
16356         zSep = " OR ";
16357       }
16358     }
16359   }
16360   *pzWhere = zWhere;
16361 }
16362
16363 /*
16364 ** Implementation of .ar "lisT" command. 
16365 */
16366 static int arListCommand(ArCommand *pAr){
16367   const char *zSql = "SELECT %s FROM %s WHERE %s"; 
16368   const char *azCols[] = {
16369     "name",
16370     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
16371   };
16372
16373   char *zWhere = 0;
16374   sqlite3_stmt *pSql = 0;
16375   int rc;
16376
16377   rc = arCheckEntries(pAr);
16378   arWhereClause(&rc, pAr, &zWhere);
16379
16380   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
16381                      pAr->zSrcTable, zWhere);
16382   if( pAr->bDryRun ){
16383     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
16384   }else{
16385     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
16386       if( pAr->bVerbose ){
16387         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
16388             sqlite3_column_text(pSql, 0),
16389             sqlite3_column_int(pSql, 1), 
16390             sqlite3_column_text(pSql, 2),
16391             sqlite3_column_text(pSql, 3)
16392         );
16393       }else{
16394         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
16395       }
16396     }
16397   }
16398   shellFinalize(&rc, pSql);
16399   sqlite3_free(zWhere);
16400   return rc;
16401 }
16402
16403
16404 /*
16405 ** Implementation of .ar "eXtract" command. 
16406 */
16407 static int arExtractCommand(ArCommand *pAr){
16408   const char *zSql1 = 
16409     "SELECT "
16410     " ($dir || name),"
16411     " writefile(($dir || name), %s, mode, mtime) "
16412     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
16413     " AND name NOT GLOB '*..[/\\]*'";
16414
16415   const char *azExtraArg[] = { 
16416     "sqlar_uncompress(data, sz)",
16417     "data"
16418   };
16419
16420   sqlite3_stmt *pSql = 0;
16421   int rc = SQLITE_OK;
16422   char *zDir = 0;
16423   char *zWhere = 0;
16424   int i, j;
16425
16426   /* If arguments are specified, check that they actually exist within
16427   ** the archive before proceeding. And formulate a WHERE clause to
16428   ** match them.  */
16429   rc = arCheckEntries(pAr);
16430   arWhereClause(&rc, pAr, &zWhere);
16431
16432   if( rc==SQLITE_OK ){
16433     if( pAr->zDir ){
16434       zDir = sqlite3_mprintf("%s/", pAr->zDir);
16435     }else{
16436       zDir = sqlite3_mprintf("");
16437     }
16438     if( zDir==0 ) rc = SQLITE_NOMEM;
16439   }
16440
16441   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 
16442       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
16443   );
16444
16445   if( rc==SQLITE_OK ){
16446     j = sqlite3_bind_parameter_index(pSql, "$dir");
16447     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
16448
16449     /* Run the SELECT statement twice. The first time, writefile() is called
16450     ** for all archive members that should be extracted. The second time,
16451     ** only for the directories. This is because the timestamps for
16452     ** extracted directories must be reset after they are populated (as
16453     ** populating them changes the timestamp).  */
16454     for(i=0; i<2; i++){
16455       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
16456       sqlite3_bind_int(pSql, j, i);
16457       if( pAr->bDryRun ){
16458         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
16459       }else{
16460         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
16461           if( i==0 && pAr->bVerbose ){
16462             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
16463           }
16464         }
16465       }
16466       shellReset(&rc, pSql);
16467     }
16468     shellFinalize(&rc, pSql);
16469   }
16470
16471   sqlite3_free(zDir);
16472   sqlite3_free(zWhere);
16473   return rc;
16474 }
16475
16476 /*
16477 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
16478 */
16479 static int arExecSql(ArCommand *pAr, const char *zSql){
16480   int rc;
16481   if( pAr->bDryRun ){
16482     utf8_printf(pAr->p->out, "%s\n", zSql);
16483     rc = SQLITE_OK;
16484   }else{
16485     char *zErr = 0;
16486     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
16487     if( zErr ){
16488       utf8_printf(stdout, "ERROR: %s\n", zErr);
16489       sqlite3_free(zErr);
16490     }
16491   }
16492   return rc;
16493 }
16494
16495
16496 /*
16497 ** Implementation of .ar "create", "insert", and "update" commands.
16498 **
16499 **     create    ->     Create a new SQL archive
16500 **     insert    ->     Insert or reinsert all files listed
16501 **     update    ->     Insert files that have changed or that were not
16502 **                      previously in the archive
16503 **
16504 ** Create the "sqlar" table in the database if it does not already exist.
16505 ** Then add each file in the azFile[] array to the archive. Directories
16506 ** are added recursively. If argument bVerbose is non-zero, a message is
16507 ** printed on stdout for each file archived.
16508 **
16509 ** The create command is the same as update, except that it drops
16510 ** any existing "sqlar" table before beginning.  The "insert" command
16511 ** always overwrites every file named on the command-line, where as
16512 ** "update" only overwrites if the size or mtime or mode has changed.
16513 */
16514 static int arCreateOrUpdateCommand(
16515   ArCommand *pAr,                 /* Command arguments and options */
16516   int bUpdate,                    /* true for a --create. */
16517   int bOnlyIfChanged              /* Only update if file has changed */
16518 ){
16519   const char *zCreate = 
16520       "CREATE TABLE IF NOT EXISTS sqlar(\n"
16521       "  name TEXT PRIMARY KEY,  -- name of the file\n"
16522       "  mode INT,               -- access permissions\n"
16523       "  mtime INT,              -- last modification time\n"
16524       "  sz INT,                 -- original file size\n"
16525       "  data BLOB               -- compressed content\n"
16526       ")";
16527   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
16528   const char *zInsertFmt[2] = {
16529      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
16530      "  SELECT\n"
16531      "    %s,\n"
16532      "    mode,\n"
16533      "    mtime,\n"
16534      "    CASE substr(lsmode(mode),1,1)\n"
16535      "      WHEN '-' THEN length(data)\n"
16536      "      WHEN 'd' THEN 0\n"
16537      "      ELSE -1 END,\n"
16538      "    sqlar_compress(data)\n"
16539      "  FROM fsdir(%Q,%Q) AS disk\n"
16540      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
16541      ,
16542      "REPLACE INTO %s(name,mode,mtime,data)\n"
16543      "  SELECT\n"
16544      "    %s,\n"
16545      "    mode,\n"
16546      "    mtime,\n"
16547      "    data\n"
16548      "  FROM fsdir(%Q,%Q) AS disk\n"
16549      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
16550   };
16551   int i;                          /* For iterating through azFile[] */
16552   int rc;                         /* Return code */
16553   const char *zTab = 0;           /* SQL table into which to insert */
16554   char *zSql;
16555   char zTemp[50];
16556   char *zExists = 0;
16557
16558   arExecSql(pAr, "PRAGMA page_size=512");
16559   rc = arExecSql(pAr, "SAVEPOINT ar;");
16560   if( rc!=SQLITE_OK ) return rc;
16561   zTemp[0] = 0; 
16562   if( pAr->bZip ){
16563     /* Initialize the zipfile virtual table, if necessary */
16564     if( pAr->zFile ){
16565       sqlite3_uint64 r;
16566       sqlite3_randomness(sizeof(r),&r);
16567       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
16568       zTab = zTemp;
16569       zSql = sqlite3_mprintf(
16570          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
16571          zTab, pAr->zFile
16572       );
16573       rc = arExecSql(pAr, zSql);
16574       sqlite3_free(zSql);
16575     }else{
16576       zTab = "zip";
16577     }
16578   }else{
16579     /* Initialize the table for an SQLAR */
16580     zTab = "sqlar";
16581     if( bUpdate==0 ){
16582       rc = arExecSql(pAr, zDrop);
16583       if( rc!=SQLITE_OK ) goto end_ar_transaction;
16584     }
16585     rc = arExecSql(pAr, zCreate);
16586   }
16587   if( bOnlyIfChanged ){
16588     zExists = sqlite3_mprintf(
16589       " AND NOT EXISTS("
16590           "SELECT 1 FROM %s AS mem"
16591           " WHERE mem.name=disk.name"
16592           " AND mem.mtime=disk.mtime"
16593           " AND mem.mode=disk.mode)", zTab);
16594   }else{
16595     zExists = sqlite3_mprintf("");
16596   }
16597   if( zExists==0 ) rc = SQLITE_NOMEM;
16598   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
16599     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
16600         pAr->bVerbose ? "shell_putsnl(name)" : "name",
16601         pAr->azArg[i], pAr->zDir, zExists);
16602     rc = arExecSql(pAr, zSql2);
16603     sqlite3_free(zSql2);
16604   }
16605 end_ar_transaction:
16606   if( rc!=SQLITE_OK ){
16607     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
16608   }else{
16609     rc = arExecSql(pAr, "RELEASE ar;");
16610     if( pAr->bZip && pAr->zFile ){
16611       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
16612       arExecSql(pAr, zSql);
16613       sqlite3_free(zSql);
16614     }
16615   }
16616   sqlite3_free(zExists);
16617   return rc;
16618 }
16619
16620 /*
16621 ** Implementation of ".ar" dot command.
16622 */
16623 static int arDotCommand(
16624   ShellState *pState,          /* Current shell tool state */
16625   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
16626   char **azArg,                /* Array of arguments passed to dot command */
16627   int nArg                     /* Number of entries in azArg[] */
16628 ){
16629   ArCommand cmd;
16630   int rc;
16631   memset(&cmd, 0, sizeof(cmd));
16632   cmd.fromCmdLine = fromCmdLine;
16633   rc = arParseCommand(azArg, nArg, &cmd);
16634   if( rc==SQLITE_OK ){
16635     int eDbType = SHELL_OPEN_UNSPEC;
16636     cmd.p = pState;
16637     cmd.db = pState->db;
16638     if( cmd.zFile ){
16639       eDbType = deduceDatabaseType(cmd.zFile, 1);
16640     }else{
16641       eDbType = pState->openMode;
16642     }
16643     if( eDbType==SHELL_OPEN_ZIPFILE ){
16644       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
16645         if( cmd.zFile==0 ){
16646           cmd.zSrcTable = sqlite3_mprintf("zip");
16647         }else{
16648           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
16649         }
16650       }
16651       cmd.bZip = 1;
16652     }else if( cmd.zFile ){
16653       int flags;
16654       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
16655       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 
16656            || cmd.eCmd==AR_CMD_UPDATE ){
16657         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
16658       }else{
16659         flags = SQLITE_OPEN_READONLY;
16660       }
16661       cmd.db = 0;
16662       if( cmd.bDryRun ){
16663         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
16664              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
16665       }
16666       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 
16667              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
16668       if( rc!=SQLITE_OK ){
16669         utf8_printf(stderr, "cannot open file: %s (%s)\n", 
16670             cmd.zFile, sqlite3_errmsg(cmd.db)
16671         );
16672         goto end_ar_command;
16673       }
16674       sqlite3_fileio_init(cmd.db, 0, 0);
16675       sqlite3_sqlar_init(cmd.db, 0, 0);
16676       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
16677                               shellPutsFunc, 0, 0);
16678
16679     }
16680     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
16681       if( cmd.eCmd!=AR_CMD_CREATE
16682        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
16683       ){
16684         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
16685         rc = SQLITE_ERROR;
16686         goto end_ar_command;
16687       }
16688       cmd.zSrcTable = sqlite3_mprintf("sqlar");
16689     }
16690
16691     switch( cmd.eCmd ){
16692       case AR_CMD_CREATE:
16693         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
16694         break;
16695
16696       case AR_CMD_EXTRACT:
16697         rc = arExtractCommand(&cmd);
16698         break;
16699
16700       case AR_CMD_LIST:
16701         rc = arListCommand(&cmd);
16702         break;
16703
16704       case AR_CMD_HELP:
16705         arUsage(pState->out);
16706         break;
16707
16708       case AR_CMD_INSERT:
16709         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
16710         break;
16711
16712       default:
16713         assert( cmd.eCmd==AR_CMD_UPDATE );
16714         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
16715         break;
16716     }
16717   }
16718 end_ar_command:
16719   if( cmd.db!=pState->db ){
16720     close_db(cmd.db);
16721   }
16722   sqlite3_free(cmd.zSrcTable);
16723
16724   return rc;
16725 }
16726 /* End of the ".archive" or ".ar" command logic
16727 *******************************************************************************/
16728 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
16729
16730 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
16731 /*
16732 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
16733 ** Otherwise, the SQL statement or statements in zSql are executed using
16734 ** database connection db and the error code written to *pRc before
16735 ** this function returns.
16736 */
16737 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
16738   int rc = *pRc;
16739   if( rc==SQLITE_OK ){
16740     char *zErr = 0;
16741     rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
16742     if( rc!=SQLITE_OK ){
16743       raw_printf(stderr, "SQL error: %s\n", zErr);
16744     }
16745     *pRc = rc;
16746   }
16747 }
16748
16749 /*
16750 ** Like shellExec(), except that zFmt is a printf() style format string.
16751 */
16752 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
16753   char *z = 0;
16754   if( *pRc==SQLITE_OK ){
16755     va_list ap;
16756     va_start(ap, zFmt);
16757     z = sqlite3_vmprintf(zFmt, ap);
16758     va_end(ap);
16759     if( z==0 ){
16760       *pRc = SQLITE_NOMEM;
16761     }else{
16762       shellExec(db, pRc, z);
16763     }
16764     sqlite3_free(z);
16765   }
16766 }
16767
16768 /*
16769 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
16770 ** Otherwise, an attempt is made to allocate, zero and return a pointer
16771 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
16772 ** to SQLITE_NOMEM and NULL returned.
16773 */
16774 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
16775   void *pRet = 0;
16776   if( *pRc==SQLITE_OK ){
16777     pRet = sqlite3_malloc64(nByte);
16778     if( pRet==0 ){
16779       *pRc = SQLITE_NOMEM;
16780     }else{
16781       memset(pRet, 0, nByte);
16782     }
16783   }
16784   return pRet;
16785 }
16786
16787 /*
16788 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
16789 ** Otherwise, zFmt is treated as a printf() style string. The result of
16790 ** formatting it along with any trailing arguments is written into a 
16791 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
16792 ** It is the responsibility of the caller to eventually free this buffer
16793 ** using a call to sqlite3_free().
16794 ** 
16795 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 
16796 ** pointer returned.
16797 */
16798 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
16799   char *z = 0;
16800   if( *pRc==SQLITE_OK ){
16801     va_list ap;
16802     va_start(ap, zFmt);
16803     z = sqlite3_vmprintf(zFmt, ap);
16804     va_end(ap);
16805     if( z==0 ){
16806       *pRc = SQLITE_NOMEM;
16807     }
16808   }
16809   return z;
16810 }
16811
16812 /*
16813 ** When running the ".recover" command, each output table, and the special
16814 ** orphaned row table if it is required, is represented by an instance
16815 ** of the following struct.
16816 */
16817 typedef struct RecoverTable RecoverTable;
16818 struct RecoverTable {
16819   char *zQuoted;                  /* Quoted version of table name */
16820   int nCol;                       /* Number of columns in table */
16821   char **azlCol;                  /* Array of column lists */
16822   int iPk;                        /* Index of IPK column */
16823 };
16824
16825 /*
16826 ** Free a RecoverTable object allocated by recoverFindTable() or
16827 ** recoverOrphanTable().
16828 */
16829 static void recoverFreeTable(RecoverTable *pTab){
16830   if( pTab ){
16831     sqlite3_free(pTab->zQuoted);
16832     if( pTab->azlCol ){
16833       int i;
16834       for(i=0; i<=pTab->nCol; i++){
16835         sqlite3_free(pTab->azlCol[i]);
16836       }
16837       sqlite3_free(pTab->azlCol);
16838     }
16839     sqlite3_free(pTab);
16840   }
16841 }
16842
16843 /*
16844 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
16845 ** Otherwise, it allocates and returns a RecoverTable object based on the
16846 ** final four arguments passed to this function. It is the responsibility
16847 ** of the caller to eventually free the returned object using
16848 ** recoverFreeTable().
16849 */
16850 static RecoverTable *recoverNewTable(
16851   int *pRc,                       /* IN/OUT: Error code */
16852   const char *zName,              /* Name of table */
16853   const char *zSql,               /* CREATE TABLE statement */
16854   int bIntkey, 
16855   int nCol
16856 ){
16857   sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
16858   int rc = *pRc;
16859   RecoverTable *pTab = 0;
16860
16861   pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
16862   if( rc==SQLITE_OK ){
16863     int nSqlCol = 0;
16864     int bSqlIntkey = 0;
16865     sqlite3_stmt *pStmt = 0;
16866     
16867     rc = sqlite3_open("", &dbtmp);
16868     if( rc==SQLITE_OK ){
16869       sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
16870                               shellIdQuote, 0, 0);
16871     }
16872     if( rc==SQLITE_OK ){
16873       rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
16874     }
16875     if( rc==SQLITE_OK ){
16876       rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
16877       if( rc==SQLITE_ERROR ){
16878         rc = SQLITE_OK;
16879         goto finished;
16880       }
16881     }
16882     shellPreparePrintf(dbtmp, &rc, &pStmt, 
16883         "SELECT count(*) FROM pragma_table_info(%Q)", zName
16884     );
16885     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
16886       nSqlCol = sqlite3_column_int(pStmt, 0);
16887     }
16888     shellFinalize(&rc, pStmt);
16889
16890     if( rc!=SQLITE_OK || nSqlCol<nCol ){
16891       goto finished;
16892     }
16893
16894     shellPreparePrintf(dbtmp, &rc, &pStmt, 
16895       "SELECT ("
16896       "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
16897       ") FROM sqlite_schema WHERE name = %Q", zName
16898     );
16899     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
16900       bSqlIntkey = sqlite3_column_int(pStmt, 0);
16901     }
16902     shellFinalize(&rc, pStmt);
16903
16904     if( bIntkey==bSqlIntkey ){
16905       int i;
16906       const char *zPk = "_rowid_";
16907       sqlite3_stmt *pPkFinder = 0;
16908
16909       /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
16910       ** set zPk to the name of the PK column, and pTab->iPk to the index
16911       ** of the column, where columns are 0-numbered from left to right.
16912       ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
16913       ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
16914       pTab->iPk = -2;
16915       if( bIntkey ){
16916         shellPreparePrintf(dbtmp, &rc, &pPkFinder, 
16917           "SELECT cid, name FROM pragma_table_info(%Q) "
16918           "  WHERE pk=1 AND type='integer' COLLATE nocase"
16919           "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
16920           , zName, zName
16921         );
16922         if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
16923           pTab->iPk = sqlite3_column_int(pPkFinder, 0);
16924           zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
16925         }
16926       }
16927
16928       pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
16929       pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
16930       pTab->nCol = nSqlCol;
16931
16932       if( bIntkey ){
16933         pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
16934       }else{
16935         pTab->azlCol[0] = shellMPrintf(&rc, "");
16936       }
16937       i = 1;
16938       shellPreparePrintf(dbtmp, &rc, &pStmt, 
16939           "SELECT %Q || group_concat(shell_idquote(name), ', ') "
16940           "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
16941           "FROM pragma_table_info(%Q)", 
16942           bIntkey ? ", " : "", pTab->iPk, 
16943           bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
16944           zName
16945       );
16946       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
16947         const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
16948         pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
16949         i++;
16950       }
16951       shellFinalize(&rc, pStmt);
16952
16953       shellFinalize(&rc, pPkFinder);
16954     }
16955   }
16956
16957  finished:
16958   sqlite3_close(dbtmp);
16959   *pRc = rc;
16960   if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
16961     recoverFreeTable(pTab);
16962     pTab = 0;
16963   }
16964   return pTab;
16965 }
16966
16967 /*
16968 ** This function is called to search the schema recovered from the
16969 ** sqlite_schema table of the (possibly) corrupt database as part
16970 ** of a ".recover" command. Specifically, for a table with root page
16971 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
16972 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
16973 ** those.
16974 **
16975 ** If a table is found, a (RecoverTable*) object is returned. Or, if
16976 ** no such table is found, but bIntkey is false and iRoot is the 
16977 ** root page of an index in the recovered schema, then (*pbNoop) is
16978 ** set to true and NULL returned. Or, if there is no such table or
16979 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
16980 ** the caller should write data to the orphans table.
16981 */
16982 static RecoverTable *recoverFindTable(
16983   ShellState *pState,             /* Shell state object */
16984   int *pRc,                       /* IN/OUT: Error code */
16985   int iRoot,                      /* Root page of table */
16986   int bIntkey,                    /* True for an intkey table */
16987   int nCol,                       /* Number of columns in table */
16988   int *pbNoop                     /* OUT: True if iRoot is root of index */
16989 ){
16990   sqlite3_stmt *pStmt = 0;
16991   RecoverTable *pRet = 0;
16992   int bNoop = 0;
16993   const char *zSql = 0;
16994   const char *zName = 0;
16995
16996   /* Search the recovered schema for an object with root page iRoot. */
16997   shellPreparePrintf(pState->db, pRc, &pStmt,
16998       "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
16999   );
17000   while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17001     const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
17002     if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
17003       bNoop = 1;
17004       break;
17005     }
17006     if( sqlite3_stricmp(zType, "table")==0 ){
17007       zName = (const char*)sqlite3_column_text(pStmt, 1);
17008       zSql = (const char*)sqlite3_column_text(pStmt, 2);
17009       pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
17010       break;
17011     }
17012   }
17013
17014   shellFinalize(pRc, pStmt);
17015   *pbNoop = bNoop;
17016   return pRet;
17017 }
17018
17019 /*
17020 ** Return a RecoverTable object representing the orphans table.
17021 */
17022 static RecoverTable *recoverOrphanTable(
17023   ShellState *pState,             /* Shell state object */
17024   int *pRc,                       /* IN/OUT: Error code */
17025   const char *zLostAndFound,      /* Base name for orphans table */
17026   int nCol                        /* Number of user data columns */
17027 ){
17028   RecoverTable *pTab = 0;
17029   if( nCol>=0 && *pRc==SQLITE_OK ){
17030     int i;
17031
17032     /* This block determines the name of the orphan table. The prefered
17033     ** name is zLostAndFound. But if that clashes with another name
17034     ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
17035     ** and so on until a non-clashing name is found.  */
17036     int iTab = 0;
17037     char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
17038     sqlite3_stmt *pTest = 0;
17039     shellPrepare(pState->db, pRc,
17040         "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
17041     );
17042     if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
17043     while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
17044       shellReset(pRc, pTest);
17045       sqlite3_free(zTab);
17046       zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
17047       sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
17048     }
17049     shellFinalize(pRc, pTest);
17050
17051     pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
17052     if( pTab ){
17053       pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
17054       pTab->nCol = nCol;
17055       pTab->iPk = -2;
17056       if( nCol>0 ){
17057         pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
17058         if( pTab->azlCol ){
17059           pTab->azlCol[nCol] = shellMPrintf(pRc, "");
17060           for(i=nCol-1; i>=0; i--){
17061             pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
17062           }
17063         }
17064       }
17065
17066       if( *pRc!=SQLITE_OK ){
17067         recoverFreeTable(pTab);
17068         pTab = 0;
17069       }else{
17070         raw_printf(pState->out, 
17071             "CREATE TABLE %s(rootpgno INTEGER, "
17072             "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
17073         );
17074         for(i=0; i<nCol; i++){
17075           raw_printf(pState->out, ", c%d", i);
17076         }
17077         raw_printf(pState->out, ");\n");
17078       }
17079     }
17080     sqlite3_free(zTab);
17081   }
17082   return pTab;
17083 }
17084
17085 /*
17086 ** This function is called to recover data from the database. A script
17087 ** to construct a new database containing all recovered data is output
17088 ** on stream pState->out.
17089 */
17090 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
17091   int rc = SQLITE_OK;
17092   sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
17093   sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
17094   sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
17095   const char *zRecoveryDb = "";   /* Name of "recovery" database */
17096   const char *zLostAndFound = "lost_and_found";
17097   int i;
17098   int nOrphan = -1;
17099   RecoverTable *pOrphan = 0;
17100
17101   int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
17102   int bRowids = 1;                /* 0 if --no-rowids */
17103   for(i=1; i<nArg; i++){
17104     char *z = azArg[i];
17105     int n;
17106     if( z[0]=='-' && z[1]=='-' ) z++;
17107     n = strlen30(z);
17108     if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
17109       bFreelist = 0;
17110     }else
17111     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
17112       i++;
17113       zRecoveryDb = azArg[i];
17114     }else
17115     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
17116       i++;
17117       zLostAndFound = azArg[i];
17118     }else
17119     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
17120       bRowids = 0;
17121     }
17122     else{
17123       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 
17124       showHelp(pState->out, azArg[0]);
17125       return 1;
17126     }
17127   }
17128
17129   shellExecPrintf(pState->db, &rc,
17130     /* Attach an in-memory database named 'recovery'. Create an indexed 
17131     ** cache of the sqlite_dbptr virtual table. */
17132     "PRAGMA writable_schema = on;"
17133     "ATTACH %Q AS recovery;"
17134     "DROP TABLE IF EXISTS recovery.dbptr;"
17135     "DROP TABLE IF EXISTS recovery.freelist;"
17136     "DROP TABLE IF EXISTS recovery.map;"
17137     "DROP TABLE IF EXISTS recovery.schema;"
17138     "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
17139   );
17140
17141   if( bFreelist ){
17142     shellExec(pState->db, &rc,
17143       "WITH trunk(pgno) AS ("
17144       "  SELECT shell_int32("
17145       "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
17146       "      WHERE x>0"
17147       "    UNION"
17148       "  SELECT shell_int32("
17149       "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
17150       "      FROM trunk WHERE x>0"
17151       "),"
17152       "freelist(data, n, freepgno) AS ("
17153       "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
17154       "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
17155       "    UNION ALL"
17156       "  SELECT data, n-1, shell_int32(data, 2+n) "
17157       "      FROM freelist WHERE n>=0"
17158       ")"
17159       "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
17160     );
17161   }
17162
17163   /* If this is an auto-vacuum database, add all pointer-map pages to
17164   ** the freelist table. Do this regardless of whether or not 
17165   ** --freelist-corrupt was specified.  */
17166   shellExec(pState->db, &rc, 
17167     "WITH ptrmap(pgno) AS ("
17168     "  SELECT 2 WHERE shell_int32("
17169     "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
17170     "  )"
17171     "    UNION ALL "
17172     "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
17173     "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
17174     ")"
17175     "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
17176   );
17177
17178   shellExec(pState->db, &rc, 
17179     "CREATE TABLE recovery.dbptr("
17180     "      pgno, child, PRIMARY KEY(child, pgno)"
17181     ") WITHOUT ROWID;"
17182     "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
17183     "    SELECT * FROM sqlite_dbptr"
17184     "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
17185
17186     /* Delete any pointer to page 1. This ensures that page 1 is considered
17187     ** a root page, regardless of how corrupt the db is. */
17188     "DELETE FROM recovery.dbptr WHERE child = 1;"
17189
17190     /* Delete all pointers to any pages that have more than one pointer
17191     ** to them. Such pages will be treated as root pages when recovering
17192     ** data.  */
17193     "DELETE FROM recovery.dbptr WHERE child IN ("
17194     "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
17195     ");"
17196
17197     /* Create the "map" table that will (eventually) contain instructions
17198     ** for dealing with each page in the db that contains one or more 
17199     ** records. */
17200     "CREATE TABLE recovery.map("
17201       "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
17202     ");"
17203
17204     /* Populate table [map]. If there are circular loops of pages in the
17205     ** database, the following adds all pages in such a loop to the map
17206     ** as individual root pages. This could be handled better.  */
17207     "WITH pages(i, maxlen) AS ("
17208     "  SELECT page_count, ("
17209     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
17210     "  ) FROM pragma_page_count WHERE page_count>0"
17211     "    UNION ALL"
17212     "  SELECT i-1, ("
17213     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
17214     "  ) FROM pages WHERE i>=2"
17215     ")"
17216     "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
17217     "  SELECT i, maxlen, NULL, ("
17218     "    WITH p(orig, pgno, parent) AS ("
17219     "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
17220     "        UNION "
17221     "      SELECT i, p.parent, "
17222     "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
17223     "    )"
17224     "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
17225     ") "
17226     "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
17227     "UPDATE recovery.map AS o SET intkey = ("
17228     "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
17229     ");"
17230
17231     /* Extract data from page 1 and any linked pages into table
17232     ** recovery.schema. With the same schema as an sqlite_schema table.  */
17233     "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
17234     "INSERT INTO recovery.schema SELECT "
17235     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
17236     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
17237     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
17238     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
17239     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
17240     "FROM sqlite_dbdata WHERE pgno IN ("
17241     "  SELECT pgno FROM recovery.map WHERE root=1"
17242     ")"
17243     "GROUP BY pgno, cell;"
17244     "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
17245   );
17246
17247   /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 
17248   ** CREATE TABLE statements that extracted from the existing schema.  */
17249   if( rc==SQLITE_OK ){
17250     sqlite3_stmt *pStmt = 0;
17251     /* ".recover" might output content in an order which causes immediate
17252     ** foreign key constraints to be violated. So disable foreign-key
17253     ** constraint enforcement to prevent problems when running the output
17254     ** script. */
17255     raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
17256     raw_printf(pState->out, "BEGIN;\n");
17257     raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
17258     shellPrepare(pState->db, &rc,
17259         "SELECT sql FROM recovery.schema "
17260         "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
17261     );
17262     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17263       const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
17264       raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 
17265           &zCreateTable[12]
17266       );
17267     }
17268     shellFinalize(&rc, pStmt);
17269   }
17270
17271   /* Figure out if an orphan table will be required. And if so, how many
17272   ** user columns it should contain */
17273   shellPrepare(pState->db, &rc, 
17274       "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
17275       , &pLoop
17276   );
17277   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
17278     nOrphan = sqlite3_column_int(pLoop, 0);
17279   }
17280   shellFinalize(&rc, pLoop);
17281   pLoop = 0;
17282
17283   shellPrepare(pState->db, &rc,
17284       "SELECT pgno FROM recovery.map WHERE root=?", &pPages
17285   );
17286
17287   shellPrepare(pState->db, &rc,
17288       "SELECT max(field), group_concat(shell_escape_crnl(quote"
17289       "(case when (? AND field<0) then NULL else value end)"
17290       "), ', ')"
17291       ", min(field) "
17292       "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
17293       "GROUP BY cell", &pCells
17294   );
17295
17296   /* Loop through each root page. */
17297   shellPrepare(pState->db, &rc, 
17298       "SELECT root, intkey, max(maxlen) FROM recovery.map" 
17299       " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
17300       "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
17301       ")", &pLoop
17302   );
17303   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
17304     int iRoot = sqlite3_column_int(pLoop, 0);
17305     int bIntkey = sqlite3_column_int(pLoop, 1);
17306     int nCol = sqlite3_column_int(pLoop, 2);
17307     int bNoop = 0;
17308     RecoverTable *pTab;
17309
17310     assert( bIntkey==0 || bIntkey==1 );
17311     pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
17312     if( bNoop || rc ) continue;
17313     if( pTab==0 ){
17314       if( pOrphan==0 ){
17315         pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
17316       }
17317       pTab = pOrphan;
17318       if( pTab==0 ) break;
17319     }
17320
17321     if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
17322       raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
17323     }
17324     sqlite3_bind_int(pPages, 1, iRoot);
17325     if( bRowids==0 && pTab->iPk<0 ){
17326       sqlite3_bind_int(pCells, 1, 1);
17327     }else{
17328       sqlite3_bind_int(pCells, 1, 0);
17329     }
17330     sqlite3_bind_int(pCells, 3, pTab->iPk);
17331
17332     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
17333       int iPgno = sqlite3_column_int(pPages, 0);
17334       sqlite3_bind_int(pCells, 2, iPgno);
17335       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
17336         int nField = sqlite3_column_int(pCells, 0);
17337         int iMin = sqlite3_column_int(pCells, 2);
17338         const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
17339
17340         RecoverTable *pTab2 = pTab;
17341         if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
17342           if( pOrphan==0 ){
17343             pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
17344           }
17345           pTab2 = pOrphan;
17346           if( pTab2==0 ) break;
17347         }
17348
17349         nField = nField+1;
17350         if( pTab2==pOrphan ){
17351           raw_printf(pState->out, 
17352               "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
17353               pTab2->zQuoted, iRoot, iPgno, nField,
17354               iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
17355           );
17356         }else{
17357           raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 
17358               pTab2->zQuoted, pTab2->azlCol[nField], zVal
17359           );
17360         }
17361       }
17362       shellReset(&rc, pCells);
17363     }
17364     shellReset(&rc, pPages);
17365     if( pTab!=pOrphan ) recoverFreeTable(pTab);
17366   }
17367   shellFinalize(&rc, pLoop);
17368   shellFinalize(&rc, pPages);
17369   shellFinalize(&rc, pCells);
17370   recoverFreeTable(pOrphan);
17371
17372   /* The rest of the schema */
17373   if( rc==SQLITE_OK ){
17374     sqlite3_stmt *pStmt = 0;
17375     shellPrepare(pState->db, &rc, 
17376         "SELECT sql, name FROM recovery.schema "
17377         "WHERE sql NOT LIKE 'create table%'", &pStmt
17378     );
17379     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
17380       const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
17381       if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
17382         const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
17383         char *zPrint = shellMPrintf(&rc, 
17384           "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
17385           zName, zName, zSql
17386         );
17387         raw_printf(pState->out, "%s;\n", zPrint);
17388         sqlite3_free(zPrint);
17389       }else{
17390         raw_printf(pState->out, "%s;\n", zSql);
17391       }
17392     }
17393     shellFinalize(&rc, pStmt);
17394   }
17395
17396   if( rc==SQLITE_OK ){
17397     raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
17398     raw_printf(pState->out, "COMMIT;\n");
17399   }
17400   sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
17401   return rc;
17402 }
17403 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
17404
17405
17406 /*
17407 ** If an input line begins with "." then invoke this routine to
17408 ** process that line.
17409 **
17410 ** Return 1 on error, 2 to exit, and 0 otherwise.
17411 */
17412 static int do_meta_command(char *zLine, ShellState *p){
17413   int h = 1;
17414   int nArg = 0;
17415   int n, c;
17416   int rc = 0;
17417   char *azArg[52];
17418
17419 #ifndef SQLITE_OMIT_VIRTUALTABLE
17420   if( p->expert.pExpert ){
17421     expertFinish(p, 1, 0);
17422   }
17423 #endif
17424
17425   /* Parse the input line into tokens.
17426   */
17427   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
17428     while( IsSpace(zLine[h]) ){ h++; }
17429     if( zLine[h]==0 ) break;
17430     if( zLine[h]=='\'' || zLine[h]=='"' ){
17431       int delim = zLine[h++];
17432       azArg[nArg++] = &zLine[h];
17433       while( zLine[h] && zLine[h]!=delim ){
17434         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
17435         h++;
17436       }
17437       if( zLine[h]==delim ){
17438         zLine[h++] = 0;
17439       }
17440       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
17441     }else{
17442       azArg[nArg++] = &zLine[h];
17443       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
17444       if( zLine[h] ) zLine[h++] = 0;
17445       resolve_backslashes(azArg[nArg-1]);
17446     }
17447   }
17448   azArg[nArg] = 0;
17449
17450   /* Process the input line.
17451   */
17452   if( nArg==0 ) return 0; /* no tokens, no error */
17453   n = strlen30(azArg[0]);
17454   c = azArg[0][0];
17455   clearTempFile(p);
17456
17457 #ifndef SQLITE_OMIT_AUTHORIZATION
17458   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
17459     if( nArg!=2 ){
17460       raw_printf(stderr, "Usage: .auth ON|OFF\n");
17461       rc = 1;
17462       goto meta_command_exit;
17463     }
17464     open_db(p, 0);
17465     if( booleanValue(azArg[1]) ){
17466       sqlite3_set_authorizer(p->db, shellAuth, p);
17467     }else{
17468       sqlite3_set_authorizer(p->db, 0, 0);
17469     }
17470   }else
17471 #endif
17472
17473 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
17474   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
17475     open_db(p, 0);
17476     rc = arDotCommand(p, 0, azArg, nArg);
17477   }else
17478 #endif
17479
17480   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
17481    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
17482   ){
17483     const char *zDestFile = 0;
17484     const char *zDb = 0;
17485     sqlite3 *pDest;
17486     sqlite3_backup *pBackup;
17487     int j;
17488     int bAsync = 0;
17489     const char *zVfs = 0;
17490     for(j=1; j<nArg; j++){
17491       const char *z = azArg[j];
17492       if( z[0]=='-' ){
17493         if( z[1]=='-' ) z++;
17494         if( strcmp(z, "-append")==0 ){
17495           zVfs = "apndvfs";
17496         }else
17497         if( strcmp(z, "-async")==0 ){
17498           bAsync = 1;
17499         }else
17500         {
17501           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
17502           return 1;
17503         }
17504       }else if( zDestFile==0 ){
17505         zDestFile = azArg[j];
17506       }else if( zDb==0 ){
17507         zDb = zDestFile;
17508         zDestFile = azArg[j];
17509       }else{
17510         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
17511         return 1;
17512       }
17513     }
17514     if( zDestFile==0 ){
17515       raw_printf(stderr, "missing FILENAME argument on .backup\n");
17516       return 1;
17517     }
17518     if( zDb==0 ) zDb = "main";
17519     rc = sqlite3_open_v2(zDestFile, &pDest, 
17520                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
17521     if( rc!=SQLITE_OK ){
17522       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
17523       close_db(pDest);
17524       return 1;
17525     }
17526     if( bAsync ){
17527       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
17528                    0, 0, 0);
17529     }
17530     open_db(p, 0);
17531     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
17532     if( pBackup==0 ){
17533       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
17534       close_db(pDest);
17535       return 1;
17536     }
17537     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
17538     sqlite3_backup_finish(pBackup);
17539     if( rc==SQLITE_DONE ){
17540       rc = 0;
17541     }else{
17542       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
17543       rc = 1;
17544     }
17545     close_db(pDest);
17546   }else
17547
17548   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
17549     if( nArg==2 ){
17550       bail_on_error = booleanValue(azArg[1]);
17551     }else{
17552       raw_printf(stderr, "Usage: .bail on|off\n");
17553       rc = 1;
17554     }
17555   }else
17556
17557   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
17558     if( nArg==2 ){
17559       if( booleanValue(azArg[1]) ){
17560         setBinaryMode(p->out, 1);
17561       }else{
17562         setTextMode(p->out, 1);
17563       }
17564     }else{
17565       raw_printf(stderr, "Usage: .binary on|off\n");
17566       rc = 1;
17567     }
17568   }else
17569
17570   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
17571     if( nArg==2 ){
17572 #if defined(_WIN32) || defined(WIN32)
17573       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
17574       rc = !SetCurrentDirectoryW(z);
17575       sqlite3_free(z);
17576 #else
17577       rc = chdir(azArg[1]);
17578 #endif
17579       if( rc ){
17580         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
17581         rc = 1;
17582       }
17583     }else{
17584       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
17585       rc = 1;
17586     }
17587   }else
17588
17589   /* The undocumented ".breakpoint" command causes a call to the no-op
17590   ** routine named test_breakpoint().
17591   */
17592   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
17593     test_breakpoint();
17594   }else
17595
17596   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
17597     if( nArg==2 ){
17598       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
17599     }else{
17600       raw_printf(stderr, "Usage: .changes on|off\n");
17601       rc = 1;
17602     }
17603   }else
17604
17605   /* Cancel output redirection, if it is currently set (by .testcase)
17606   ** Then read the content of the testcase-out.txt file and compare against
17607   ** azArg[1].  If there are differences, report an error and exit.
17608   */
17609   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
17610     char *zRes = 0;
17611     output_reset(p);
17612     if( nArg!=2 ){
17613       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
17614       rc = 2;
17615     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
17616       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
17617       rc = 2;
17618     }else if( testcase_glob(azArg[1],zRes)==0 ){
17619       utf8_printf(stderr,
17620                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
17621                  p->zTestcase, azArg[1], zRes);
17622       rc = 1;
17623     }else{
17624       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
17625       p->nCheck++;
17626     }
17627     sqlite3_free(zRes);
17628   }else
17629
17630   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
17631     if( nArg==2 ){
17632       tryToClone(p, azArg[1]);
17633     }else{
17634       raw_printf(stderr, "Usage: .clone FILENAME\n");
17635       rc = 1;
17636     }
17637   }else
17638
17639   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
17640     char **azName = 0;
17641     int nName = 0;
17642     sqlite3_stmt *pStmt;
17643     int i;
17644     open_db(p, 0);
17645     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
17646     if( rc ){
17647       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
17648       rc = 1;
17649     }else{
17650       while( sqlite3_step(pStmt)==SQLITE_ROW ){
17651         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
17652         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
17653         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
17654         if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
17655         azName[nName*2] = strdup(zSchema);
17656         azName[nName*2+1] = strdup(zFile);
17657         nName++;
17658       }
17659     }
17660     sqlite3_finalize(pStmt);
17661     for(i=0; i<nName; i++){
17662       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
17663       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
17664       const char *z = azName[i*2+1];
17665       utf8_printf(p->out, "%s: %s %s%s\n",
17666          azName[i*2],
17667          z && z[0] ? z : "\"\"",
17668          bRdonly ? "r/o" : "r/w",
17669          eTxn==SQLITE_TXN_NONE ? "" :
17670             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
17671       free(azName[i*2]);
17672       free(azName[i*2+1]);
17673     }
17674     sqlite3_free(azName);
17675   }else
17676
17677   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
17678     static const struct DbConfigChoices {
17679       const char *zName;
17680       int op;
17681     } aDbConfig[] = {
17682         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
17683         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
17684         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
17685         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
17686         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
17687         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
17688         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
17689         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
17690         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
17691         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
17692         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
17693         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
17694         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
17695         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
17696         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
17697         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
17698     };
17699     int ii, v;
17700     open_db(p, 0);
17701     for(ii=0; ii<ArraySize(aDbConfig); ii++){
17702       if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
17703       if( nArg>=3 ){
17704         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
17705       }
17706       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
17707       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
17708       if( nArg>1 ) break;
17709     }
17710     if( nArg>1 && ii==ArraySize(aDbConfig) ){
17711       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
17712       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
17713     }   
17714   }else
17715
17716   if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
17717     rc = shell_dbinfo_command(p, nArg, azArg);
17718   }else
17719
17720 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
17721   if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
17722     open_db(p, 0);
17723     rc = recoverDatabaseCmd(p, nArg, azArg);
17724   }else
17725 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
17726
17727   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
17728     char *zLike = 0;
17729     char *zSql;
17730     int i;
17731     int savedShowHeader = p->showHeader;
17732     int savedShellFlags = p->shellFlgs;
17733     ShellClearFlag(p, 
17734        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
17735        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
17736     for(i=1; i<nArg; i++){
17737       if( azArg[i][0]=='-' ){
17738         const char *z = azArg[i]+1;
17739         if( z[0]=='-' ) z++;
17740         if( strcmp(z,"preserve-rowids")==0 ){
17741 #ifdef SQLITE_OMIT_VIRTUALTABLE
17742           raw_printf(stderr, "The --preserve-rowids option is not compatible"
17743                              " with SQLITE_OMIT_VIRTUALTABLE\n");
17744           rc = 1;
17745           sqlite3_free(zLike);
17746           goto meta_command_exit;
17747 #else
17748           ShellSetFlag(p, SHFLG_PreserveRowid);
17749 #endif
17750         }else
17751         if( strcmp(z,"newlines")==0 ){
17752           ShellSetFlag(p, SHFLG_Newlines);
17753         }else
17754         if( strcmp(z,"data-only")==0 ){
17755           ShellSetFlag(p, SHFLG_DumpDataOnly);
17756         }else
17757         if( strcmp(z,"nosys")==0 ){
17758           ShellSetFlag(p, SHFLG_DumpNoSys);
17759         }else
17760         {
17761           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
17762           rc = 1;
17763           sqlite3_free(zLike);
17764           goto meta_command_exit;
17765         }
17766       }else if( zLike ){
17767         zLike = sqlite3_mprintf("%z OR name LIKE %Q ESCAPE '\\'",
17768                 zLike, azArg[i]);
17769       }else{
17770         zLike = sqlite3_mprintf("name LIKE %Q ESCAPE '\\'", azArg[i]);
17771       }
17772     }
17773
17774     open_db(p, 0);
17775
17776     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
17777       /* When playing back a "dump", the content might appear in an order
17778       ** which causes immediate foreign key constraints to be violated.
17779       ** So disable foreign-key constraint enforcement to prevent problems. */
17780       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
17781       raw_printf(p->out, "BEGIN TRANSACTION;\n");
17782     }
17783     p->writableSchema = 0;
17784     p->showHeader = 0;
17785     /* Set writable_schema=ON since doing so forces SQLite to initialize
17786     ** as much of the schema as it can even if the sqlite_schema table is
17787     ** corrupt. */
17788     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
17789     p->nErr = 0;
17790     if( zLike==0 ) zLike = sqlite3_mprintf("true");
17791     zSql = sqlite3_mprintf(
17792       "SELECT name, type, sql FROM sqlite_schema "
17793       "WHERE (%s) AND type=='table'"
17794       "  AND sql NOT NULL"
17795       " ORDER BY tbl_name='sqlite_sequence', rowid",
17796       zLike
17797     );
17798     run_schema_dump_query(p,zSql);
17799     sqlite3_free(zSql);
17800     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
17801       zSql = sqlite3_mprintf(
17802         "SELECT sql FROM sqlite_schema "
17803         "WHERE (%s) AND sql NOT NULL"
17804         "  AND type IN ('index','trigger','view')",
17805         zLike
17806       );
17807       run_table_dump_query(p, zSql);
17808       sqlite3_free(zSql);
17809     }
17810     sqlite3_free(zLike);
17811     if( p->writableSchema ){
17812       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
17813       p->writableSchema = 0;
17814     }
17815     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
17816     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
17817     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
17818       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
17819     }
17820     p->showHeader = savedShowHeader;
17821     p->shellFlgs = savedShellFlags;
17822   }else
17823
17824   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
17825     if( nArg==2 ){
17826       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
17827     }else{
17828       raw_printf(stderr, "Usage: .echo on|off\n");
17829       rc = 1;
17830     }
17831   }else
17832
17833   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
17834     if( nArg==2 ){
17835       p->autoEQPtest = 0;
17836       if( p->autoEQPtrace ){
17837         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
17838         p->autoEQPtrace = 0;
17839       }
17840       if( strcmp(azArg[1],"full")==0 ){
17841         p->autoEQP = AUTOEQP_full;
17842       }else if( strcmp(azArg[1],"trigger")==0 ){
17843         p->autoEQP = AUTOEQP_trigger;
17844 #ifdef SQLITE_DEBUG
17845       }else if( strcmp(azArg[1],"test")==0 ){
17846         p->autoEQP = AUTOEQP_on;
17847         p->autoEQPtest = 1;
17848       }else if( strcmp(azArg[1],"trace")==0 ){
17849         p->autoEQP = AUTOEQP_full;
17850         p->autoEQPtrace = 1;
17851         open_db(p, 0);
17852         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
17853         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
17854 #endif
17855       }else{
17856         p->autoEQP = (u8)booleanValue(azArg[1]);
17857       }
17858     }else{
17859       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
17860       rc = 1;
17861     }
17862   }else
17863
17864   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
17865     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
17866     rc = 2;
17867   }else
17868
17869   /* The ".explain" command is automatic now.  It is largely pointless.  It
17870   ** retained purely for backwards compatibility */
17871   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
17872     int val = 1;
17873     if( nArg>=2 ){
17874       if( strcmp(azArg[1],"auto")==0 ){
17875         val = 99;
17876       }else{
17877         val =  booleanValue(azArg[1]);
17878       }
17879     }
17880     if( val==1 && p->mode!=MODE_Explain ){
17881       p->normalMode = p->mode;
17882       p->mode = MODE_Explain;
17883       p->autoExplain = 0;
17884     }else if( val==0 ){
17885       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
17886       p->autoExplain = 0;
17887     }else if( val==99 ){
17888       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
17889       p->autoExplain = 1;
17890     }
17891   }else
17892
17893 #ifndef SQLITE_OMIT_VIRTUALTABLE
17894   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
17895     open_db(p, 0);
17896     expertDotCommand(p, azArg, nArg);
17897   }else
17898 #endif
17899
17900   if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
17901     static const struct {
17902        const char *zCtrlName;   /* Name of a test-control option */
17903        int ctrlCode;            /* Integer code for that option */
17904        const char *zUsage;      /* Usage notes */
17905     } aCtrl[] = {
17906       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
17907       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
17908    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
17909       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
17910       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
17911    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
17912       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
17913       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
17914       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
17915       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
17916     };
17917     int filectrl = -1;
17918     int iCtrl = -1;
17919     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
17920     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
17921     int n2, i;
17922     const char *zCmd = 0;
17923     const char *zSchema = 0;
17924
17925     open_db(p, 0);
17926     zCmd = nArg>=2 ? azArg[1] : "help";
17927
17928     if( zCmd[0]=='-' 
17929      && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
17930      && nArg>=4
17931     ){
17932       zSchema = azArg[2];
17933       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
17934       nArg -= 2;
17935       zCmd = azArg[1];
17936     }
17937
17938     /* The argument can optionally begin with "-" or "--" */
17939     if( zCmd[0]=='-' && zCmd[1] ){
17940       zCmd++;
17941       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
17942     }
17943
17944     /* --help lists all file-controls */
17945     if( strcmp(zCmd,"help")==0 ){
17946       utf8_printf(p->out, "Available file-controls:\n");
17947       for(i=0; i<ArraySize(aCtrl); i++){
17948         utf8_printf(p->out, "  .filectrl %s %s\n",
17949                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
17950       }
17951       rc = 1;
17952       goto meta_command_exit;
17953     }
17954
17955     /* convert filectrl text option to value. allow any unique prefix
17956     ** of the option name, or a numerical value. */
17957     n2 = strlen30(zCmd);
17958     for(i=0; i<ArraySize(aCtrl); i++){
17959       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
17960         if( filectrl<0 ){
17961           filectrl = aCtrl[i].ctrlCode;
17962           iCtrl = i;
17963         }else{
17964           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
17965                               "Use \".filectrl --help\" for help\n", zCmd);
17966           rc = 1;
17967           goto meta_command_exit;
17968         }
17969       }
17970     }
17971     if( filectrl<0 ){
17972       utf8_printf(stderr,"Error: unknown file-control: %s\n"
17973                          "Use \".filectrl --help\" for help\n", zCmd);
17974     }else{
17975       switch(filectrl){
17976         case SQLITE_FCNTL_SIZE_LIMIT: {
17977           if( nArg!=2 && nArg!=3 ) break;
17978           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
17979           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
17980           isOk = 1;
17981           break;
17982         }
17983         case SQLITE_FCNTL_LOCK_TIMEOUT:
17984         case SQLITE_FCNTL_CHUNK_SIZE: {
17985           int x;
17986           if( nArg!=3 ) break;
17987           x = (int)integerValue(azArg[2]);
17988           sqlite3_file_control(p->db, zSchema, filectrl, &x);
17989           isOk = 2;
17990           break;
17991         }
17992         case SQLITE_FCNTL_PERSIST_WAL:
17993         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
17994           int x;
17995           if( nArg!=2 && nArg!=3 ) break;
17996           x = nArg==3 ? booleanValue(azArg[2]) : -1;
17997           sqlite3_file_control(p->db, zSchema, filectrl, &x);
17998           iRes = x;
17999           isOk = 1;
18000           break;
18001         }
18002         case SQLITE_FCNTL_HAS_MOVED: {
18003           int x;
18004           if( nArg!=2 ) break;
18005           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18006           iRes = x;
18007           isOk = 1;
18008           break;
18009         }
18010         case SQLITE_FCNTL_TEMPFILENAME: {
18011           char *z = 0;
18012           if( nArg!=2 ) break;
18013           sqlite3_file_control(p->db, zSchema, filectrl, &z);
18014           if( z ){
18015             utf8_printf(p->out, "%s\n", z);
18016             sqlite3_free(z);
18017           }
18018           isOk = 2;
18019           break;
18020         }
18021         case SQLITE_FCNTL_RESERVE_BYTES: {
18022           int x;
18023           if( nArg>=3 ){
18024             x = atoi(azArg[2]);
18025             sqlite3_file_control(p->db, zSchema, filectrl, &x);
18026           }
18027           x = -1;
18028           sqlite3_file_control(p->db, zSchema, filectrl, &x);
18029           utf8_printf(p->out,"%d\n", x);
18030           isOk = 2;
18031           break;
18032         }
18033       }
18034     }
18035     if( isOk==0 && iCtrl>=0 ){
18036       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
18037       rc = 1;
18038     }else if( isOk==1 ){
18039       char zBuf[100];
18040       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
18041       raw_printf(p->out, "%s\n", zBuf);
18042     }
18043   }else
18044
18045   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
18046     ShellState data;
18047     char *zErrMsg = 0;
18048     int doStats = 0;
18049     memcpy(&data, p, sizeof(data));
18050     data.showHeader = 0;
18051     data.cMode = data.mode = MODE_Semi;
18052     if( nArg==2 && optionMatch(azArg[1], "indent") ){
18053       data.cMode = data.mode = MODE_Pretty;
18054       nArg = 1;
18055     }
18056     if( nArg!=1 ){
18057       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
18058       rc = 1;
18059       goto meta_command_exit;
18060     }
18061     open_db(p, 0);
18062     rc = sqlite3_exec(p->db,
18063        "SELECT sql FROM"
18064        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
18065        "     FROM sqlite_schema UNION ALL"
18066        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
18067        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
18068        "ORDER BY rowid",
18069        callback, &data, &zErrMsg
18070     );
18071     if( rc==SQLITE_OK ){
18072       sqlite3_stmt *pStmt;
18073       rc = sqlite3_prepare_v2(p->db,
18074                "SELECT rowid FROM sqlite_schema"
18075                " WHERE name GLOB 'sqlite_stat[134]'",
18076                -1, &pStmt, 0);
18077       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
18078       sqlite3_finalize(pStmt);
18079     }
18080     if( doStats==0 ){
18081       raw_printf(p->out, "/* No STAT tables available */\n");
18082     }else{
18083       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
18084       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
18085                    callback, &data, &zErrMsg);
18086       data.cMode = data.mode = MODE_Insert;
18087       data.zDestTable = "sqlite_stat1";
18088       shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
18089       data.zDestTable = "sqlite_stat4";
18090       shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
18091       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
18092     }
18093   }else
18094
18095   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
18096     if( nArg==2 ){
18097       p->showHeader = booleanValue(azArg[1]);
18098       p->shellFlgs |= SHFLG_HeaderSet;
18099     }else{
18100       raw_printf(stderr, "Usage: .headers on|off\n");
18101       rc = 1;
18102     }
18103   }else
18104
18105   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
18106     if( nArg>=2 ){
18107       n = showHelp(p->out, azArg[1]);
18108       if( n==0 ){
18109         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
18110       }
18111     }else{
18112       showHelp(p->out, 0);
18113     }
18114   }else
18115
18116   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
18117     char *zTable = 0;           /* Insert data into this table */
18118     char *zFile = 0;            /* Name of file to extra content from */
18119     sqlite3_stmt *pStmt = NULL; /* A statement */
18120     int nCol;                   /* Number of columns in the table */
18121     int nByte;                  /* Number of bytes in an SQL string */
18122     int i, j;                   /* Loop counters */
18123     int needCommit;             /* True to COMMIT or ROLLBACK at end */
18124     int nSep;                   /* Number of bytes in p->colSeparator[] */
18125     char *zSql;                 /* An SQL statement */
18126     ImportCtx sCtx;             /* Reader context */
18127     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
18128     int eVerbose = 0;           /* Larger for more console output */
18129     int nSkip = 0;              /* Initial lines to skip */
18130     int useOutputMode = 1;      /* Use output mode to determine separators */
18131
18132     memset(&sCtx, 0, sizeof(sCtx));
18133     if( p->mode==MODE_Ascii ){
18134       xRead = ascii_read_one_field;
18135     }else{
18136       xRead = csv_read_one_field;
18137     }
18138     for(i=1; i<nArg; i++){
18139       char *z = azArg[i];
18140       if( z[0]=='-' && z[1]=='-' ) z++;
18141       if( z[0]!='-' ){
18142         if( zFile==0 ){
18143           zFile = z;
18144         }else if( zTable==0 ){
18145           zTable = z;
18146         }else{
18147           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
18148           showHelp(p->out, "import");
18149           rc = 1;
18150           goto meta_command_exit;
18151         }
18152       }else if( strcmp(z,"-v")==0 ){
18153         eVerbose++;
18154       }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
18155         nSkip = integerValue(azArg[++i]);
18156       }else if( strcmp(z,"-ascii")==0 ){
18157         sCtx.cColSep = SEP_Unit[0];
18158         sCtx.cRowSep = SEP_Record[0];
18159         xRead = ascii_read_one_field;
18160         useOutputMode = 0;
18161       }else if( strcmp(z,"-csv")==0 ){
18162         sCtx.cColSep = ',';
18163         sCtx.cRowSep = '\n';
18164         xRead = csv_read_one_field;
18165         useOutputMode = 0;
18166       }else{
18167         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
18168         showHelp(p->out, "import");
18169         rc = 1;
18170         goto meta_command_exit;
18171       }
18172     }
18173     if( zTable==0 ){
18174       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
18175                   zFile==0 ? "FILE" : "TABLE");
18176       showHelp(p->out, "import");
18177       rc = 1;
18178       goto meta_command_exit;
18179     }
18180     seenInterrupt = 0;
18181     open_db(p, 0);
18182     if( useOutputMode ){
18183       /* If neither the --csv or --ascii options are specified, then set
18184       ** the column and row separator characters from the output mode. */
18185       nSep = strlen30(p->colSeparator);
18186       if( nSep==0 ){
18187         raw_printf(stderr,
18188                    "Error: non-null column separator required for import\n");
18189         rc = 1;
18190         goto meta_command_exit;
18191       }
18192       if( nSep>1 ){
18193         raw_printf(stderr, 
18194               "Error: multi-character column separators not allowed"
18195               " for import\n");
18196         rc = 1;
18197         goto meta_command_exit;
18198       }
18199       nSep = strlen30(p->rowSeparator);
18200       if( nSep==0 ){
18201         raw_printf(stderr,
18202             "Error: non-null row separator required for import\n");
18203         rc = 1;
18204         goto meta_command_exit;
18205       }
18206       if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
18207         /* When importing CSV (only), if the row separator is set to the
18208         ** default output row separator, change it to the default input
18209         ** row separator.  This avoids having to maintain different input
18210         ** and output row separators. */
18211         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18212         nSep = strlen30(p->rowSeparator);
18213       }
18214       if( nSep>1 ){
18215         raw_printf(stderr, "Error: multi-character row separators not allowed"
18216                            " for import\n");
18217         rc = 1;
18218         goto meta_command_exit;
18219       }
18220       sCtx.cColSep = p->colSeparator[0];
18221       sCtx.cRowSep = p->rowSeparator[0];
18222     }
18223     sCtx.zFile = zFile;
18224     sCtx.nLine = 1;
18225     if( sCtx.zFile[0]=='|' ){
18226 #ifdef SQLITE_OMIT_POPEN
18227       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
18228       rc = 1;
18229       goto meta_command_exit;
18230 #else
18231       sCtx.in = popen(sCtx.zFile+1, "r");
18232       sCtx.zFile = "<pipe>";
18233       sCtx.xCloser = pclose;
18234 #endif
18235     }else{
18236       sCtx.in = fopen(sCtx.zFile, "rb");
18237       sCtx.xCloser = fclose;
18238     }
18239     if( sCtx.in==0 ){
18240       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
18241       rc = 1;
18242       goto meta_command_exit;
18243     }
18244     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
18245       char zSep[2];
18246       zSep[1] = 0;
18247       zSep[0] = sCtx.cColSep;
18248       utf8_printf(p->out, "Column separator ");
18249       output_c_string(p->out, zSep);
18250       utf8_printf(p->out, ", row separator ");
18251       zSep[0] = sCtx.cRowSep;
18252       output_c_string(p->out, zSep);
18253       utf8_printf(p->out, "\n");
18254     }
18255     while( (nSkip--)>0 ){
18256       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
18257     }
18258     zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
18259     if( zSql==0 ){
18260       import_cleanup(&sCtx);
18261       shell_out_of_memory();
18262     }
18263     nByte = strlen30(zSql);
18264     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18265     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
18266     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
18267       char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
18268       char cSep = '(';
18269       while( xRead(&sCtx) ){
18270         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
18271         cSep = ',';
18272         if( sCtx.cTerm!=sCtx.cColSep ) break;
18273       }
18274       if( cSep=='(' ){
18275         sqlite3_free(zCreate);
18276         import_cleanup(&sCtx);
18277         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
18278         rc = 1;
18279         goto meta_command_exit;
18280       }
18281       zCreate = sqlite3_mprintf("%z\n)", zCreate);
18282       if( eVerbose>=1 ){
18283         utf8_printf(p->out, "%s\n", zCreate);
18284       }
18285       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
18286       sqlite3_free(zCreate);
18287       if( rc ){
18288         utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
18289                 sqlite3_errmsg(p->db));
18290         import_cleanup(&sCtx);
18291         rc = 1;
18292         goto meta_command_exit;
18293       }
18294       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18295     }
18296     sqlite3_free(zSql);
18297     if( rc ){
18298       if (pStmt) sqlite3_finalize(pStmt);
18299       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
18300       import_cleanup(&sCtx);
18301       rc = 1;
18302       goto meta_command_exit;
18303     }
18304     nCol = sqlite3_column_count(pStmt);
18305     sqlite3_finalize(pStmt);
18306     pStmt = 0;
18307     if( nCol==0 ) return 0; /* no columns, no error */
18308     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
18309     if( zSql==0 ){
18310       import_cleanup(&sCtx);
18311       shell_out_of_memory();
18312     }
18313     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
18314     j = strlen30(zSql);
18315     for(i=1; i<nCol; i++){
18316       zSql[j++] = ',';
18317       zSql[j++] = '?';
18318     }
18319     zSql[j++] = ')';
18320     zSql[j] = 0;
18321     if( eVerbose>=2 ){
18322       utf8_printf(p->out, "Insert using: %s\n", zSql);
18323     }
18324     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18325     sqlite3_free(zSql);
18326     if( rc ){
18327       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
18328       if (pStmt) sqlite3_finalize(pStmt);
18329       import_cleanup(&sCtx);
18330       rc = 1;
18331       goto meta_command_exit;
18332     }
18333     needCommit = sqlite3_get_autocommit(p->db);
18334     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
18335     do{
18336       int startLine = sCtx.nLine;
18337       for(i=0; i<nCol; i++){
18338         char *z = xRead(&sCtx);
18339         /*
18340         ** Did we reach end-of-file before finding any columns?
18341         ** If so, stop instead of NULL filling the remaining columns.
18342         */
18343         if( z==0 && i==0 ) break;
18344         /*
18345         ** Did we reach end-of-file OR end-of-line before finding any
18346         ** columns in ASCII mode?  If so, stop instead of NULL filling
18347         ** the remaining columns.
18348         */
18349         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
18350         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
18351         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
18352           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
18353                           "filling the rest with NULL\n",
18354                           sCtx.zFile, startLine, nCol, i+1);
18355           i += 2;
18356           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
18357         }
18358       }
18359       if( sCtx.cTerm==sCtx.cColSep ){
18360         do{
18361           xRead(&sCtx);
18362           i++;
18363         }while( sCtx.cTerm==sCtx.cColSep );
18364         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
18365                         "extras ignored\n",
18366                         sCtx.zFile, startLine, nCol, i);
18367       }
18368       if( i>=nCol ){
18369         sqlite3_step(pStmt);
18370         rc = sqlite3_reset(pStmt);
18371         if( rc!=SQLITE_OK ){
18372           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
18373                       startLine, sqlite3_errmsg(p->db));
18374           sCtx.nErr++;
18375         }else{
18376           sCtx.nRow++;
18377         }
18378       }
18379     }while( sCtx.cTerm!=EOF );
18380
18381     import_cleanup(&sCtx);
18382     sqlite3_finalize(pStmt);
18383     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
18384     if( eVerbose>0 ){
18385       utf8_printf(p->out,
18386           "Added %d rows with %d errors using %d lines of input\n",
18387           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
18388     }
18389   }else
18390
18391 #ifndef SQLITE_UNTESTABLE
18392   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
18393     char *zSql;
18394     char *zCollist = 0;
18395     sqlite3_stmt *pStmt;
18396     int tnum = 0;
18397     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
18398     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
18399     int i;
18400     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
18401       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
18402                           "       .imposter off\n");
18403       /* Also allowed, but not documented:
18404       **
18405       **    .imposter TABLE IMPOSTER
18406       **
18407       ** where TABLE is a WITHOUT ROWID table.  In that case, the
18408       ** imposter is another WITHOUT ROWID table with the columns in
18409       ** storage order. */
18410       rc = 1;
18411       goto meta_command_exit;
18412     }
18413     open_db(p, 0);
18414     if( nArg==2 ){
18415       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
18416       goto meta_command_exit;
18417     }
18418     zSql = sqlite3_mprintf(
18419       "SELECT rootpage, 0 FROM sqlite_schema"
18420       " WHERE name='%q' AND type='index'"
18421       "UNION ALL "
18422       "SELECT rootpage, 1 FROM sqlite_schema"
18423       " WHERE name='%q' AND type='table'"
18424       "   AND sql LIKE '%%without%%rowid%%'",
18425       azArg[1], azArg[1]
18426     );
18427     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18428     sqlite3_free(zSql);
18429     if( sqlite3_step(pStmt)==SQLITE_ROW ){
18430       tnum = sqlite3_column_int(pStmt, 0);
18431       isWO = sqlite3_column_int(pStmt, 1);
18432     }
18433     sqlite3_finalize(pStmt);
18434     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
18435     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18436     sqlite3_free(zSql);
18437     i = 0;
18438     while( sqlite3_step(pStmt)==SQLITE_ROW ){
18439       char zLabel[20];
18440       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
18441       i++;
18442       if( zCol==0 ){
18443         if( sqlite3_column_int(pStmt,1)==-1 ){
18444           zCol = "_ROWID_";
18445         }else{
18446           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
18447           zCol = zLabel;
18448         }
18449       }
18450       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
18451         lenPK = (int)strlen(zCollist);
18452       }
18453       if( zCollist==0 ){
18454         zCollist = sqlite3_mprintf("\"%w\"", zCol);
18455       }else{
18456         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
18457       }
18458     }
18459     sqlite3_finalize(pStmt);
18460     if( i==0 || tnum==0 ){
18461       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
18462       rc = 1;
18463       sqlite3_free(zCollist);
18464       goto meta_command_exit;
18465     }
18466     if( lenPK==0 ) lenPK = 100000;
18467     zSql = sqlite3_mprintf(
18468           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
18469           azArg[2], zCollist, lenPK, zCollist);
18470     sqlite3_free(zCollist);
18471     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
18472     if( rc==SQLITE_OK ){
18473       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
18474       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
18475       if( rc ){
18476         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
18477       }else{
18478         utf8_printf(stdout, "%s;\n", zSql);
18479         raw_printf(stdout,
18480           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
18481           azArg[1], isWO ? "table" : "index"
18482         );
18483       }
18484     }else{
18485       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
18486       rc = 1;
18487     }
18488     sqlite3_free(zSql);
18489   }else
18490 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
18491
18492 #ifdef SQLITE_ENABLE_IOTRACE
18493   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
18494     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
18495     if( iotrace && iotrace!=stdout ) fclose(iotrace);
18496     iotrace = 0;
18497     if( nArg<2 ){
18498       sqlite3IoTrace = 0;
18499     }else if( strcmp(azArg[1], "-")==0 ){
18500       sqlite3IoTrace = iotracePrintf;
18501       iotrace = stdout;
18502     }else{
18503       iotrace = fopen(azArg[1], "w");
18504       if( iotrace==0 ){
18505         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
18506         sqlite3IoTrace = 0;
18507         rc = 1;
18508       }else{
18509         sqlite3IoTrace = iotracePrintf;
18510       }
18511     }
18512   }else
18513 #endif
18514
18515   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
18516     static const struct {
18517        const char *zLimitName;   /* Name of a limit */
18518        int limitCode;            /* Integer code for that limit */
18519     } aLimit[] = {
18520       { "length",                SQLITE_LIMIT_LENGTH                    },
18521       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
18522       { "column",                SQLITE_LIMIT_COLUMN                    },
18523       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
18524       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
18525       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
18526       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
18527       { "attached",              SQLITE_LIMIT_ATTACHED                  },
18528       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
18529       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
18530       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
18531       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
18532     };
18533     int i, n2;
18534     open_db(p, 0);
18535     if( nArg==1 ){
18536       for(i=0; i<ArraySize(aLimit); i++){
18537         printf("%20s %d\n", aLimit[i].zLimitName,
18538                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
18539       }
18540     }else if( nArg>3 ){
18541       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
18542       rc = 1;
18543       goto meta_command_exit;
18544     }else{
18545       int iLimit = -1;
18546       n2 = strlen30(azArg[1]);
18547       for(i=0; i<ArraySize(aLimit); i++){
18548         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
18549           if( iLimit<0 ){
18550             iLimit = i;
18551           }else{
18552             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
18553             rc = 1;
18554             goto meta_command_exit;
18555           }
18556         }
18557       }
18558       if( iLimit<0 ){
18559         utf8_printf(stderr, "unknown limit: \"%s\"\n"
18560                         "enter \".limits\" with no arguments for a list.\n",
18561                          azArg[1]);
18562         rc = 1;
18563         goto meta_command_exit;
18564       }
18565       if( nArg==3 ){
18566         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
18567                       (int)integerValue(azArg[2]));
18568       }
18569       printf("%20s %d\n", aLimit[iLimit].zLimitName,
18570              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
18571     }
18572   }else
18573
18574   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
18575     open_db(p, 0);
18576     lintDotCommand(p, azArg, nArg);
18577   }else
18578
18579 #ifndef SQLITE_OMIT_LOAD_EXTENSION
18580   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
18581     const char *zFile, *zProc;
18582     char *zErrMsg = 0;
18583     if( nArg<2 ){
18584       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
18585       rc = 1;
18586       goto meta_command_exit;
18587     }
18588     zFile = azArg[1];
18589     zProc = nArg>=3 ? azArg[2] : 0;
18590     open_db(p, 0);
18591     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
18592     if( rc!=SQLITE_OK ){
18593       utf8_printf(stderr, "Error: %s\n", zErrMsg);
18594       sqlite3_free(zErrMsg);
18595       rc = 1;
18596     }
18597   }else
18598 #endif
18599
18600   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
18601     if( nArg!=2 ){
18602       raw_printf(stderr, "Usage: .log FILENAME\n");
18603       rc = 1;
18604     }else{
18605       const char *zFile = azArg[1];
18606       output_file_close(p->pLog);
18607       p->pLog = output_file_open(zFile, 0);
18608     }
18609   }else
18610
18611   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
18612     const char *zMode = nArg>=2 ? azArg[1] : "";
18613     int n2 = strlen30(zMode);
18614     int c2 = zMode[0];
18615     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
18616       p->mode = MODE_Line;
18617       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18618     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
18619       p->mode = MODE_Column;
18620       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
18621         p->showHeader = 1;
18622       }
18623       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18624     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
18625       p->mode = MODE_List;
18626       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
18627       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18628     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
18629       p->mode = MODE_Html;
18630     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
18631       p->mode = MODE_Tcl;
18632       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
18633       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18634     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
18635       p->mode = MODE_Csv;
18636       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
18637       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
18638     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
18639       p->mode = MODE_List;
18640       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
18641     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
18642       p->mode = MODE_Insert;
18643       set_table_name(p, nArg>=3 ? azArg[2] : "table");
18644     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
18645       p->mode = MODE_Quote;
18646       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
18647       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
18648     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
18649       p->mode = MODE_Ascii;
18650       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
18651       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
18652     }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
18653       p->mode = MODE_Markdown;
18654     }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
18655       p->mode = MODE_Table;
18656     }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
18657       p->mode = MODE_Box;
18658     }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
18659       p->mode = MODE_Json;
18660     }else if( nArg==1 ){
18661       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
18662     }else{
18663       raw_printf(stderr, "Error: mode should be one of: "
18664          "ascii box column csv html insert json line list markdown "
18665          "quote table tabs tcl\n");
18666       rc = 1;
18667     }
18668     p->cMode = p->mode;
18669   }else
18670
18671   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
18672     if( nArg==2 ){
18673       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
18674                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
18675     }else{
18676       raw_printf(stderr, "Usage: .nullvalue STRING\n");
18677       rc = 1;
18678     }
18679   }else
18680
18681 #ifdef SQLITE_DEBUG
18682   if( c=='o' && strcmp(azArg[0],"oom")==0 ){
18683     int i;
18684     for(i=1; i<nArg; i++){
18685       const char *z = azArg[i];
18686       if( z[0]=='-' && z[1]=='-' ) z++;
18687       if( strcmp(z,"-repeat")==0 ){
18688         if( i==nArg-1 ){
18689           raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
18690           rc = 1;
18691         }else{
18692           oomRepeat = (int)integerValue(azArg[++i]);
18693         }
18694       }else if( IsDigit(z[0]) ){
18695         oomCounter = (int)integerValue(azArg[i]);
18696       }else{
18697         raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
18698         raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
18699         rc = 1;
18700       }
18701     }
18702     if( rc==0 ){
18703       raw_printf(p->out, "oomCounter = %d\n", oomCounter);
18704       raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
18705     }
18706   }else
18707 #endif /* SQLITE_DEBUG */
18708
18709   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
18710     char *zNewFilename;  /* Name of the database file to open */
18711     int iName = 1;       /* Index in azArg[] of the filename */
18712     int newFlag = 0;     /* True to delete file before opening */
18713     /* Close the existing database */
18714     session_close_all(p);
18715     close_db(p->db);
18716     p->db = 0;
18717     p->zDbFilename = 0;
18718     sqlite3_free(p->zFreeOnClose);
18719     p->zFreeOnClose = 0;
18720     p->openMode = SHELL_OPEN_UNSPEC;
18721     p->openFlags = 0;
18722     p->szMax = 0;
18723     /* Check for command-line arguments */
18724     for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
18725       const char *z = azArg[iName];
18726       if( optionMatch(z,"new") ){
18727         newFlag = 1;
18728 #ifdef SQLITE_HAVE_ZLIB
18729       }else if( optionMatch(z, "zip") ){
18730         p->openMode = SHELL_OPEN_ZIPFILE;
18731 #endif
18732       }else if( optionMatch(z, "append") ){
18733         p->openMode = SHELL_OPEN_APPENDVFS;
18734       }else if( optionMatch(z, "readonly") ){
18735         p->openMode = SHELL_OPEN_READONLY;
18736       }else if( optionMatch(z, "nofollow") ){
18737         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
18738 #ifdef SQLITE_ENABLE_DESERIALIZE
18739       }else if( optionMatch(z, "deserialize") ){
18740         p->openMode = SHELL_OPEN_DESERIALIZE;
18741       }else if( optionMatch(z, "hexdb") ){
18742         p->openMode = SHELL_OPEN_HEXDB;
18743       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
18744         p->szMax = integerValue(azArg[++iName]);
18745 #endif /* SQLITE_ENABLE_DESERIALIZE */
18746       }else if( z[0]=='-' ){
18747         utf8_printf(stderr, "unknown option: %s\n", z);
18748         rc = 1;
18749         goto meta_command_exit;
18750       }
18751     }
18752     /* If a filename is specified, try to open it first */
18753     zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
18754     if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
18755       if( newFlag ) shellDeleteFile(zNewFilename);
18756       p->zDbFilename = zNewFilename;
18757       open_db(p, OPEN_DB_KEEPALIVE);
18758       if( p->db==0 ){
18759         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
18760         sqlite3_free(zNewFilename);
18761       }else{
18762         p->zFreeOnClose = zNewFilename;
18763       }
18764     }
18765     if( p->db==0 ){
18766       /* As a fall-back open a TEMP database */
18767       p->zDbFilename = 0;
18768       open_db(p, 0);
18769     }
18770   }else
18771
18772   if( (c=='o'
18773         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
18774    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
18775   ){
18776     const char *zFile = 0;
18777     int bTxtMode = 0;
18778     int i;
18779     int eMode = 0;
18780     int bBOM = 0;
18781     int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
18782
18783     if( c=='e' ){
18784       eMode = 'x';
18785       bOnce = 2;
18786     }else if( strncmp(azArg[0],"once",n)==0 ){
18787       bOnce = 1;
18788     }
18789     for(i=1; i<nArg; i++){
18790       char *z = azArg[i];
18791       if( z[0]=='-' ){
18792         if( z[1]=='-' ) z++;
18793         if( strcmp(z,"-bom")==0 ){
18794           bBOM = 1;
18795         }else if( c!='e' && strcmp(z,"-x")==0 ){
18796           eMode = 'x';  /* spreadsheet */
18797         }else if( c!='e' && strcmp(z,"-e")==0 ){
18798           eMode = 'e';  /* text editor */
18799         }else{
18800           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
18801                       azArg[i]);
18802           showHelp(p->out, azArg[0]);
18803           rc = 1;
18804           goto meta_command_exit;
18805         }
18806       }else if( zFile==0 ){
18807         zFile = z;
18808       }else{
18809         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
18810                     azArg[i]);
18811         showHelp(p->out, azArg[0]);
18812         rc = 1;
18813         goto meta_command_exit;
18814       }
18815     }
18816     if( zFile==0 ) zFile = "stdout";
18817     if( bOnce ){
18818       p->outCount = 2;
18819     }else{
18820       p->outCount = 0;
18821     }
18822     output_reset(p);
18823 #ifndef SQLITE_NOHAVE_SYSTEM
18824     if( eMode=='e' || eMode=='x' ){
18825       p->doXdgOpen = 1;
18826       outputModePush(p);
18827       if( eMode=='x' ){
18828         /* spreadsheet mode.  Output as CSV. */
18829         newTempFile(p, "csv");
18830         ShellClearFlag(p, SHFLG_Echo);
18831         p->mode = MODE_Csv;
18832         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
18833         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
18834       }else{
18835         /* text editor mode */
18836         newTempFile(p, "txt");
18837         bTxtMode = 1;
18838       }
18839       zFile = p->zTempFile;
18840     }
18841 #endif /* SQLITE_NOHAVE_SYSTEM */
18842     if( zFile[0]=='|' ){
18843 #ifdef SQLITE_OMIT_POPEN
18844       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
18845       rc = 1;
18846       p->out = stdout;
18847 #else
18848       p->out = popen(zFile + 1, "w");
18849       if( p->out==0 ){
18850         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
18851         p->out = stdout;
18852         rc = 1;
18853       }else{
18854         if( bBOM ) fprintf(p->out,"\357\273\277");
18855         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
18856       }
18857 #endif
18858     }else{
18859       p->out = output_file_open(zFile, bTxtMode);
18860       if( p->out==0 ){
18861         if( strcmp(zFile,"off")!=0 ){
18862           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
18863         }
18864         p->out = stdout;
18865         rc = 1;
18866       } else {
18867         if( bBOM ) fprintf(p->out,"\357\273\277");
18868         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
18869       }
18870     }
18871   }else
18872
18873   if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
18874     open_db(p,0);
18875     if( nArg<=1 ) goto parameter_syntax_error;
18876
18877     /* .parameter clear
18878     ** Clear all bind parameters by dropping the TEMP table that holds them.
18879     */
18880     if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
18881       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
18882                    0, 0, 0);
18883     }else
18884
18885     /* .parameter list
18886     ** List all bind parameters.
18887     */
18888     if( nArg==2 && strcmp(azArg[1],"list")==0 ){
18889       sqlite3_stmt *pStmt = 0;
18890       int rx;
18891       int len = 0;
18892       rx = sqlite3_prepare_v2(p->db,
18893              "SELECT max(length(key)) "
18894              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
18895       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
18896         len = sqlite3_column_int(pStmt, 0);
18897         if( len>40 ) len = 40;
18898       }
18899       sqlite3_finalize(pStmt);
18900       pStmt = 0;
18901       if( len ){
18902         rx = sqlite3_prepare_v2(p->db,
18903              "SELECT key, quote(value) "
18904              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
18905         while( sqlite3_step(pStmt)==SQLITE_ROW ){
18906           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
18907                       sqlite3_column_text(pStmt,1));
18908         }
18909         sqlite3_finalize(pStmt);
18910       }
18911     }else
18912
18913     /* .parameter init
18914     ** Make sure the TEMP table used to hold bind parameters exists.
18915     ** Create it if necessary.
18916     */
18917     if( nArg==2 && strcmp(azArg[1],"init")==0 ){
18918       bind_table_init(p);
18919     }else
18920
18921     /* .parameter set NAME VALUE
18922     ** Set or reset a bind parameter.  NAME should be the full parameter
18923     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
18924     ** VALUE can be in either SQL literal notation, or if not it will be
18925     ** understood to be a text string.
18926     */
18927     if( nArg==4 && strcmp(azArg[1],"set")==0 ){
18928       int rx;
18929       char *zSql;
18930       sqlite3_stmt *pStmt;
18931       const char *zKey = azArg[2];
18932       const char *zValue = azArg[3];
18933       bind_table_init(p);
18934       zSql = sqlite3_mprintf(
18935                   "REPLACE INTO temp.sqlite_parameters(key,value)"
18936                   "VALUES(%Q,%s);", zKey, zValue);
18937       if( zSql==0 ) shell_out_of_memory();
18938       pStmt = 0;
18939       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18940       sqlite3_free(zSql);
18941       if( rx!=SQLITE_OK ){
18942         sqlite3_finalize(pStmt);
18943         pStmt = 0;
18944         zSql = sqlite3_mprintf(
18945                    "REPLACE INTO temp.sqlite_parameters(key,value)"
18946                    "VALUES(%Q,%Q);", zKey, zValue);
18947         if( zSql==0 ) shell_out_of_memory();
18948         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
18949         sqlite3_free(zSql);
18950         if( rx!=SQLITE_OK ){
18951           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
18952           sqlite3_finalize(pStmt);
18953           pStmt = 0;
18954           rc = 1;
18955         }
18956       }
18957       sqlite3_step(pStmt);
18958       sqlite3_finalize(pStmt);
18959     }else
18960
18961     /* .parameter unset NAME
18962     ** Remove the NAME binding from the parameter binding table, if it
18963     ** exists.
18964     */
18965     if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
18966       char *zSql = sqlite3_mprintf(
18967           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
18968       if( zSql==0 ) shell_out_of_memory();
18969       sqlite3_exec(p->db, zSql, 0, 0, 0);
18970       sqlite3_free(zSql);
18971     }else
18972     /* If no command name matches, show a syntax error */
18973     parameter_syntax_error:
18974     showHelp(p->out, "parameter");
18975   }else
18976
18977   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
18978     int i;
18979     for(i=1; i<nArg; i++){
18980       if( i>1 ) raw_printf(p->out, " ");
18981       utf8_printf(p->out, "%s", azArg[i]);
18982     }
18983     raw_printf(p->out, "\n");
18984   }else
18985
18986 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
18987   if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
18988     int i;
18989     int nn = 0;
18990     p->flgProgress = 0;
18991     p->mxProgress = 0;
18992     p->nProgress = 0;
18993     for(i=1; i<nArg; i++){
18994       const char *z = azArg[i];
18995       if( z[0]=='-' ){
18996         z++;
18997         if( z[0]=='-' ) z++;
18998         if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
18999           p->flgProgress |= SHELL_PROGRESS_QUIET;
19000           continue;
19001         }
19002         if( strcmp(z,"reset")==0 ){
19003           p->flgProgress |= SHELL_PROGRESS_RESET;
19004           continue;
19005         }
19006         if( strcmp(z,"once")==0 ){
19007           p->flgProgress |= SHELL_PROGRESS_ONCE;
19008           continue;
19009         }
19010         if( strcmp(z,"limit")==0 ){
19011           if( i+1>=nArg ){
19012             utf8_printf(stderr, "Error: missing argument on --limit\n");
19013             rc = 1;
19014             goto meta_command_exit;
19015           }else{
19016             p->mxProgress = (int)integerValue(azArg[++i]);
19017           }
19018           continue;
19019         }
19020         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
19021         rc = 1;
19022         goto meta_command_exit;
19023       }else{
19024         nn = (int)integerValue(z);
19025       }
19026     }
19027     open_db(p, 0);
19028     sqlite3_progress_handler(p->db, nn, progress_handler, p);
19029   }else
19030 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
19031
19032   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
19033     if( nArg >= 2) {
19034       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
19035     }
19036     if( nArg >= 3) {
19037       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
19038     }
19039   }else
19040
19041   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
19042     rc = 2;
19043   }else
19044
19045   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
19046     FILE *inSaved = p->in;
19047     int savedLineno = p->lineno;
19048     if( nArg!=2 ){
19049       raw_printf(stderr, "Usage: .read FILE\n");
19050       rc = 1;
19051       goto meta_command_exit;
19052     }
19053     if( azArg[1][0]=='|' ){
19054       p->in = popen(azArg[1]+1, "r");
19055       if( p->in==0 ){
19056         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
19057         rc = 1;
19058       }else{
19059         rc = process_input(p);
19060         pclose(p->in);
19061       }
19062     }else if( notNormalFile(azArg[1]) || (p->in = fopen(azArg[1], "rb"))==0 ){
19063       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
19064       rc = 1;
19065     }else{
19066       rc = process_input(p);
19067       fclose(p->in);
19068     }
19069     p->in = inSaved;
19070     p->lineno = savedLineno;
19071   }else
19072
19073   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
19074     const char *zSrcFile;
19075     const char *zDb;
19076     sqlite3 *pSrc;
19077     sqlite3_backup *pBackup;
19078     int nTimeout = 0;
19079
19080     if( nArg==2 ){
19081       zSrcFile = azArg[1];
19082       zDb = "main";
19083     }else if( nArg==3 ){
19084       zSrcFile = azArg[2];
19085       zDb = azArg[1];
19086     }else{
19087       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
19088       rc = 1;
19089       goto meta_command_exit;
19090     }
19091     rc = sqlite3_open(zSrcFile, &pSrc);
19092     if( rc!=SQLITE_OK ){
19093       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
19094       close_db(pSrc);
19095       return 1;
19096     }
19097     open_db(p, 0);
19098     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
19099     if( pBackup==0 ){
19100       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19101       close_db(pSrc);
19102       return 1;
19103     }
19104     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
19105           || rc==SQLITE_BUSY  ){
19106       if( rc==SQLITE_BUSY ){
19107         if( nTimeout++ >= 3 ) break;
19108         sqlite3_sleep(100);
19109       }
19110     }
19111     sqlite3_backup_finish(pBackup);
19112     if( rc==SQLITE_DONE ){
19113       rc = 0;
19114     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
19115       raw_printf(stderr, "Error: source database is busy\n");
19116       rc = 1;
19117     }else{
19118       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19119       rc = 1;
19120     }
19121     close_db(pSrc);
19122   }else
19123
19124   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
19125     if( nArg==2 ){
19126       p->scanstatsOn = (u8)booleanValue(azArg[1]);
19127 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
19128       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
19129 #endif
19130     }else{
19131       raw_printf(stderr, "Usage: .scanstats on|off\n");
19132       rc = 1;
19133     }
19134   }else
19135
19136   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
19137     ShellText sSelect;
19138     ShellState data;
19139     char *zErrMsg = 0;
19140     const char *zDiv = "(";
19141     const char *zName = 0;
19142     int iSchema = 0;
19143     int bDebug = 0;
19144     int bNoSystemTabs = 0;
19145     int ii;
19146
19147     open_db(p, 0);
19148     memcpy(&data, p, sizeof(data));
19149     data.showHeader = 0;
19150     data.cMode = data.mode = MODE_Semi;
19151     initText(&sSelect);
19152     for(ii=1; ii<nArg; ii++){
19153       if( optionMatch(azArg[ii],"indent") ){
19154         data.cMode = data.mode = MODE_Pretty;
19155       }else if( optionMatch(azArg[ii],"debug") ){
19156         bDebug = 1;
19157       }else if( optionMatch(azArg[ii],"nosys") ){
19158         bNoSystemTabs = 1;
19159       }else if( azArg[ii][0]=='-' ){
19160         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
19161         rc = 1;
19162         goto meta_command_exit;
19163       }else if( zName==0 ){
19164         zName = azArg[ii];
19165       }else{
19166         raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
19167         rc = 1;
19168         goto meta_command_exit;
19169       }
19170     }
19171     if( zName!=0 ){
19172       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
19173                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
19174                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
19175                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
19176       if( isSchema ){
19177         char *new_argv[2], *new_colv[2];
19178         new_argv[0] = sqlite3_mprintf(
19179                       "CREATE TABLE %s (\n"
19180                       "  type text,\n"
19181                       "  name text,\n"
19182                       "  tbl_name text,\n"
19183                       "  rootpage integer,\n"
19184                       "  sql text\n"
19185                       ")", zName);
19186         new_argv[1] = 0;
19187         new_colv[0] = "sql";
19188         new_colv[1] = 0;
19189         callback(&data, 1, new_argv, new_colv);
19190         sqlite3_free(new_argv[0]);
19191       }
19192     }
19193     if( zDiv ){
19194       sqlite3_stmt *pStmt = 0;
19195       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
19196                               -1, &pStmt, 0);
19197       if( rc ){
19198         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19199         sqlite3_finalize(pStmt);
19200         rc = 1;
19201         goto meta_command_exit;
19202       }
19203       appendText(&sSelect, "SELECT sql FROM", 0);
19204       iSchema = 0;
19205       while( sqlite3_step(pStmt)==SQLITE_ROW ){
19206         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
19207         char zScNum[30];
19208         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
19209         appendText(&sSelect, zDiv, 0);
19210         zDiv = " UNION ALL ";
19211         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
19212         if( sqlite3_stricmp(zDb, "main")!=0 ){
19213           appendText(&sSelect, zDb, '\'');
19214         }else{
19215           appendText(&sSelect, "NULL", 0);
19216         }
19217         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
19218         appendText(&sSelect, zScNum, 0);
19219         appendText(&sSelect, " AS snum, ", 0);
19220         appendText(&sSelect, zDb, '\'');
19221         appendText(&sSelect, " AS sname FROM ", 0);
19222         appendText(&sSelect, zDb, quoteChar(zDb));
19223         appendText(&sSelect, ".sqlite_schema", 0);
19224       }
19225       sqlite3_finalize(pStmt);
19226 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
19227       if( zName ){
19228         appendText(&sSelect,
19229            " UNION ALL SELECT shell_module_schema(name),"
19230            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
19231         0);
19232       }
19233 #endif
19234       appendText(&sSelect, ") WHERE ", 0);
19235       if( zName ){
19236         char *zQarg = sqlite3_mprintf("%Q", zName);
19237         int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
19238                     strchr(zName, '[') != 0;
19239         if( strchr(zName, '.') ){
19240           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
19241         }else{
19242           appendText(&sSelect, "lower(tbl_name)", 0);
19243         }
19244         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
19245         appendText(&sSelect, zQarg, 0);
19246         if( !bGlob ){
19247           appendText(&sSelect, " ESCAPE '\\' ", 0);
19248         }
19249         appendText(&sSelect, " AND ", 0);
19250         sqlite3_free(zQarg);
19251       }
19252       if( bNoSystemTabs ){
19253         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
19254       }
19255       appendText(&sSelect, "sql IS NOT NULL"
19256                            " ORDER BY snum, rowid", 0);
19257       if( bDebug ){
19258         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
19259       }else{
19260         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
19261       }
19262       freeText(&sSelect);
19263     }
19264     if( zErrMsg ){
19265       utf8_printf(stderr,"Error: %s\n", zErrMsg);
19266       sqlite3_free(zErrMsg);
19267       rc = 1;
19268     }else if( rc != SQLITE_OK ){
19269       raw_printf(stderr,"Error: querying schema information\n");
19270       rc = 1;
19271     }else{
19272       rc = 0;
19273     }
19274   }else
19275
19276 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
19277   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
19278     sqlite3_unsupported_selecttrace = nArg>=2 ? (int)integerValue(azArg[1]) : 0xffff;
19279   }else
19280 #endif
19281
19282 #if defined(SQLITE_ENABLE_SESSION)
19283   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
19284     OpenSession *pSession = &p->aSession[0];
19285     char **azCmd = &azArg[1];
19286     int iSes = 0;
19287     int nCmd = nArg - 1;
19288     int i;
19289     if( nArg<=1 ) goto session_syntax_error;
19290     open_db(p, 0);
19291     if( nArg>=3 ){
19292       for(iSes=0; iSes<p->nSession; iSes++){
19293         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
19294       }
19295       if( iSes<p->nSession ){
19296         pSession = &p->aSession[iSes];
19297         azCmd++;
19298         nCmd--;
19299       }else{
19300         pSession = &p->aSession[0];
19301         iSes = 0;
19302       }
19303     }
19304
19305     /* .session attach TABLE
19306     ** Invoke the sqlite3session_attach() interface to attach a particular
19307     ** table so that it is never filtered.
19308     */
19309     if( strcmp(azCmd[0],"attach")==0 ){
19310       if( nCmd!=2 ) goto session_syntax_error;
19311       if( pSession->p==0 ){
19312         session_not_open:
19313         raw_printf(stderr, "ERROR: No sessions are open\n");
19314       }else{
19315         rc = sqlite3session_attach(pSession->p, azCmd[1]);
19316         if( rc ){
19317           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
19318           rc = 0;
19319         }
19320       }
19321     }else
19322
19323     /* .session changeset FILE
19324     ** .session patchset FILE
19325     ** Write a changeset or patchset into a file.  The file is overwritten.
19326     */
19327     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
19328       FILE *out = 0;
19329       if( nCmd!=2 ) goto session_syntax_error;
19330       if( pSession->p==0 ) goto session_not_open;
19331       out = fopen(azCmd[1], "wb");
19332       if( out==0 ){
19333         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
19334                     azCmd[1]);
19335       }else{
19336         int szChng;
19337         void *pChng;
19338         if( azCmd[0][0]=='c' ){
19339           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
19340         }else{
19341           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
19342         }
19343         if( rc ){
19344           printf("Error: error code %d\n", rc);
19345           rc = 0;
19346         }
19347         if( pChng
19348           && fwrite(pChng, szChng, 1, out)!=1 ){
19349           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
19350                   szChng);
19351         }
19352         sqlite3_free(pChng);
19353         fclose(out);
19354       }
19355     }else
19356
19357     /* .session close
19358     ** Close the identified session
19359     */
19360     if( strcmp(azCmd[0], "close")==0 ){
19361       if( nCmd!=1 ) goto session_syntax_error;
19362       if( p->nSession ){
19363         session_close(pSession);
19364         p->aSession[iSes] = p->aSession[--p->nSession];
19365       }
19366     }else
19367
19368     /* .session enable ?BOOLEAN?
19369     ** Query or set the enable flag
19370     */
19371     if( strcmp(azCmd[0], "enable")==0 ){
19372       int ii;
19373       if( nCmd>2 ) goto session_syntax_error;
19374       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
19375       if( p->nSession ){
19376         ii = sqlite3session_enable(pSession->p, ii);
19377         utf8_printf(p->out, "session %s enable flag = %d\n",
19378                     pSession->zName, ii);
19379       }
19380     }else
19381
19382     /* .session filter GLOB ....
19383     ** Set a list of GLOB patterns of table names to be excluded.
19384     */
19385     if( strcmp(azCmd[0], "filter")==0 ){
19386       int ii, nByte;
19387       if( nCmd<2 ) goto session_syntax_error;
19388       if( p->nSession ){
19389         for(ii=0; ii<pSession->nFilter; ii++){
19390           sqlite3_free(pSession->azFilter[ii]);
19391         }
19392         sqlite3_free(pSession->azFilter);
19393         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
19394         pSession->azFilter = sqlite3_malloc( nByte );
19395         if( pSession->azFilter==0 ){
19396           raw_printf(stderr, "Error: out or memory\n");
19397           exit(1);
19398         }
19399         for(ii=1; ii<nCmd; ii++){
19400           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
19401         }
19402         pSession->nFilter = ii-1;
19403       }
19404     }else
19405
19406     /* .session indirect ?BOOLEAN?
19407     ** Query or set the indirect flag
19408     */
19409     if( strcmp(azCmd[0], "indirect")==0 ){
19410       int ii;
19411       if( nCmd>2 ) goto session_syntax_error;
19412       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
19413       if( p->nSession ){
19414         ii = sqlite3session_indirect(pSession->p, ii);
19415         utf8_printf(p->out, "session %s indirect flag = %d\n",
19416                     pSession->zName, ii);
19417       }
19418     }else
19419
19420     /* .session isempty
19421     ** Determine if the session is empty
19422     */
19423     if( strcmp(azCmd[0], "isempty")==0 ){
19424       int ii;
19425       if( nCmd!=1 ) goto session_syntax_error;
19426       if( p->nSession ){
19427         ii = sqlite3session_isempty(pSession->p);
19428         utf8_printf(p->out, "session %s isempty flag = %d\n",
19429                     pSession->zName, ii);
19430       }
19431     }else
19432
19433     /* .session list
19434     ** List all currently open sessions
19435     */
19436     if( strcmp(azCmd[0],"list")==0 ){
19437       for(i=0; i<p->nSession; i++){
19438         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
19439       }
19440     }else
19441
19442     /* .session open DB NAME
19443     ** Open a new session called NAME on the attached database DB.
19444     ** DB is normally "main".
19445     */
19446     if( strcmp(azCmd[0],"open")==0 ){
19447       char *zName;
19448       if( nCmd!=3 ) goto session_syntax_error;
19449       zName = azCmd[2];
19450       if( zName[0]==0 ) goto session_syntax_error;
19451       for(i=0; i<p->nSession; i++){
19452         if( strcmp(p->aSession[i].zName,zName)==0 ){
19453           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
19454           goto meta_command_exit;
19455         }
19456       }
19457       if( p->nSession>=ArraySize(p->aSession) ){
19458         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
19459         goto meta_command_exit;
19460       }
19461       pSession = &p->aSession[p->nSession];
19462       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
19463       if( rc ){
19464         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
19465         rc = 0;
19466         goto meta_command_exit;
19467       }
19468       pSession->nFilter = 0;
19469       sqlite3session_table_filter(pSession->p, session_filter, pSession);
19470       p->nSession++;
19471       pSession->zName = sqlite3_mprintf("%s", zName);
19472     }else
19473     /* If no command name matches, show a syntax error */
19474     session_syntax_error:
19475     showHelp(p->out, "session");
19476   }else
19477 #endif
19478
19479 #ifdef SQLITE_DEBUG
19480   /* Undocumented commands for internal testing.  Subject to change
19481   ** without notice. */
19482   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
19483     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
19484       int i, v;
19485       for(i=1; i<nArg; i++){
19486         v = booleanValue(azArg[i]);
19487         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
19488       }
19489     }
19490     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
19491       int i; sqlite3_int64 v;
19492       for(i=1; i<nArg; i++){
19493         char zBuf[200];
19494         v = integerValue(azArg[i]);
19495         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
19496         utf8_printf(p->out, "%s", zBuf);
19497       }
19498     }
19499   }else
19500 #endif
19501
19502   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
19503     int bIsInit = 0;         /* True to initialize the SELFTEST table */
19504     int bVerbose = 0;        /* Verbose output */
19505     int bSelftestExists;     /* True if SELFTEST already exists */
19506     int i, k;                /* Loop counters */
19507     int nTest = 0;           /* Number of tests runs */
19508     int nErr = 0;            /* Number of errors seen */
19509     ShellText str;           /* Answer for a query */
19510     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
19511
19512     open_db(p,0);
19513     for(i=1; i<nArg; i++){
19514       const char *z = azArg[i];
19515       if( z[0]=='-' && z[1]=='-' ) z++;
19516       if( strcmp(z,"-init")==0 ){
19517         bIsInit = 1;
19518       }else
19519       if( strcmp(z,"-v")==0 ){
19520         bVerbose++;
19521       }else
19522       {
19523         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
19524                     azArg[i], azArg[0]);
19525         raw_printf(stderr, "Should be one of: --init -v\n");
19526         rc = 1;
19527         goto meta_command_exit;
19528       }
19529     }
19530     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
19531            != SQLITE_OK ){
19532       bSelftestExists = 0;
19533     }else{
19534       bSelftestExists = 1;
19535     }
19536     if( bIsInit ){
19537       createSelftestTable(p);
19538       bSelftestExists = 1;
19539     }
19540     initText(&str);
19541     appendText(&str, "x", 0);
19542     for(k=bSelftestExists; k>=0; k--){
19543       if( k==1 ){
19544         rc = sqlite3_prepare_v2(p->db,
19545             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
19546             -1, &pStmt, 0);
19547       }else{
19548         rc = sqlite3_prepare_v2(p->db,
19549           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
19550           "      (1,'run','PRAGMA integrity_check','ok')",
19551           -1, &pStmt, 0);
19552       }
19553       if( rc ){
19554         raw_printf(stderr, "Error querying the selftest table\n");
19555         rc = 1;
19556         sqlite3_finalize(pStmt);
19557         goto meta_command_exit;
19558       }
19559       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
19560         int tno = sqlite3_column_int(pStmt, 0);
19561         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
19562         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
19563         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
19564
19565         k = 0;
19566         if( bVerbose>0 ){
19567           char *zQuote = sqlite3_mprintf("%q", zSql);
19568           printf("%d: %s %s\n", tno, zOp, zSql);
19569           sqlite3_free(zQuote);
19570         }
19571         if( strcmp(zOp,"memo")==0 ){
19572           utf8_printf(p->out, "%s\n", zSql);
19573         }else
19574         if( strcmp(zOp,"run")==0 ){
19575           char *zErrMsg = 0;
19576           str.n = 0;
19577           str.z[0] = 0;
19578           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
19579           nTest++;
19580           if( bVerbose ){
19581             utf8_printf(p->out, "Result: %s\n", str.z);
19582           }
19583           if( rc || zErrMsg ){
19584             nErr++;
19585             rc = 1;
19586             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
19587             sqlite3_free(zErrMsg);
19588           }else if( strcmp(zAns,str.z)!=0 ){
19589             nErr++;
19590             rc = 1;
19591             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
19592             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
19593           }
19594         }else
19595         {
19596           utf8_printf(stderr,
19597             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
19598           rc = 1;
19599           break;
19600         }
19601       } /* End loop over rows of content from SELFTEST */
19602       sqlite3_finalize(pStmt);
19603     } /* End loop over k */
19604     freeText(&str);
19605     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
19606   }else
19607
19608   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
19609     if( nArg<2 || nArg>3 ){
19610       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
19611       rc = 1;
19612     }
19613     if( nArg>=2 ){
19614       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
19615                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
19616     }
19617     if( nArg>=3 ){
19618       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
19619                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
19620     }
19621   }else
19622
19623   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
19624     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
19625     int i;                   /* Loop counter */
19626     int bSchema = 0;         /* Also hash the schema */
19627     int bSeparate = 0;       /* Hash each table separately */
19628     int iSize = 224;         /* Hash algorithm to use */
19629     int bDebug = 0;          /* Only show the query that would have run */
19630     sqlite3_stmt *pStmt;     /* For querying tables names */
19631     char *zSql;              /* SQL to be run */
19632     char *zSep;              /* Separator */
19633     ShellText sSql;          /* Complete SQL for the query to run the hash */
19634     ShellText sQuery;        /* Set of queries used to read all content */
19635     open_db(p, 0);
19636     for(i=1; i<nArg; i++){
19637       const char *z = azArg[i];
19638       if( z[0]=='-' ){
19639         z++;
19640         if( z[0]=='-' ) z++;
19641         if( strcmp(z,"schema")==0 ){
19642           bSchema = 1;
19643         }else
19644         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
19645          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
19646         ){
19647           iSize = atoi(&z[5]);
19648         }else
19649         if( strcmp(z,"debug")==0 ){
19650           bDebug = 1;
19651         }else
19652         {
19653           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
19654                       azArg[i], azArg[0]);
19655           showHelp(p->out, azArg[0]);
19656           rc = 1;
19657           goto meta_command_exit;
19658         }
19659       }else if( zLike ){
19660         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
19661         rc = 1;
19662         goto meta_command_exit;
19663       }else{
19664         zLike = z;
19665         bSeparate = 1;
19666         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
19667       }
19668     }
19669     if( bSchema ){
19670       zSql = "SELECT lower(name) FROM sqlite_schema"
19671              " WHERE type='table' AND coalesce(rootpage,0)>1"
19672              " UNION ALL SELECT 'sqlite_schema'"
19673              " ORDER BY 1 collate nocase";
19674     }else{
19675       zSql = "SELECT lower(name) FROM sqlite_schema"
19676              " WHERE type='table' AND coalesce(rootpage,0)>1"
19677              " AND name NOT LIKE 'sqlite_%'"
19678              " ORDER BY 1 collate nocase";
19679     }
19680     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19681     initText(&sQuery);
19682     initText(&sSql);
19683     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
19684     zSep = "VALUES(";
19685     while( SQLITE_ROW==sqlite3_step(pStmt) ){
19686       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
19687       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
19688       if( strncmp(zTab, "sqlite_",7)!=0 ){
19689         appendText(&sQuery,"SELECT * FROM ", 0);
19690         appendText(&sQuery,zTab,'"');
19691         appendText(&sQuery," NOT INDEXED;", 0);
19692       }else if( strcmp(zTab, "sqlite_schema")==0 ){
19693         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
19694                            " ORDER BY name;", 0);
19695       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
19696         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
19697                            " ORDER BY name;", 0);
19698       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
19699         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
19700                            " ORDER BY tbl,idx;", 0);
19701       }else if( strcmp(zTab, "sqlite_stat4")==0 ){
19702         appendText(&sQuery, "SELECT * FROM ", 0);
19703         appendText(&sQuery, zTab, 0);
19704         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
19705       }
19706       appendText(&sSql, zSep, 0);
19707       appendText(&sSql, sQuery.z, '\'');
19708       sQuery.n = 0;
19709       appendText(&sSql, ",", 0);
19710       appendText(&sSql, zTab, '\'');
19711       zSep = "),(";
19712     }
19713     sqlite3_finalize(pStmt);
19714     if( bSeparate ){
19715       zSql = sqlite3_mprintf(
19716           "%s))"
19717           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
19718           "   FROM [sha3sum$query]",
19719           sSql.z, iSize);
19720     }else{
19721       zSql = sqlite3_mprintf(
19722           "%s))"
19723           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
19724           "   FROM [sha3sum$query]",
19725           sSql.z, iSize);
19726     }
19727     freeText(&sQuery);
19728     freeText(&sSql);
19729     if( bDebug ){
19730       utf8_printf(p->out, "%s\n", zSql);
19731     }else{
19732       shell_exec(p, zSql, 0);
19733     }
19734     sqlite3_free(zSql);
19735   }else
19736
19737 #ifndef SQLITE_NOHAVE_SYSTEM
19738   if( c=='s'
19739    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
19740   ){
19741     char *zCmd;
19742     int i, x;
19743     if( nArg<2 ){
19744       raw_printf(stderr, "Usage: .system COMMAND\n");
19745       rc = 1;
19746       goto meta_command_exit;
19747     }
19748     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
19749     for(i=2; i<nArg; i++){
19750       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
19751                              zCmd, azArg[i]);
19752     }
19753     x = system(zCmd);
19754     sqlite3_free(zCmd);
19755     if( x ) raw_printf(stderr, "System command returns %d\n", x);
19756   }else
19757 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
19758
19759   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
19760     static const char *azBool[] = { "off", "on", "trigger", "full"};
19761     int i;
19762     if( nArg!=1 ){
19763       raw_printf(stderr, "Usage: .show\n");
19764       rc = 1;
19765       goto meta_command_exit;
19766     }
19767     utf8_printf(p->out, "%12.12s: %s\n","echo",
19768                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
19769     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
19770     utf8_printf(p->out, "%12.12s: %s\n","explain",
19771          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
19772     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
19773     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
19774     utf8_printf(p->out, "%12.12s: ", "nullvalue");
19775       output_c_string(p->out, p->nullValue);
19776       raw_printf(p->out, "\n");
19777     utf8_printf(p->out,"%12.12s: %s\n","output",
19778             strlen30(p->outfile) ? p->outfile : "stdout");
19779     utf8_printf(p->out,"%12.12s: ", "colseparator");
19780       output_c_string(p->out, p->colSeparator);
19781       raw_printf(p->out, "\n");
19782     utf8_printf(p->out,"%12.12s: ", "rowseparator");
19783       output_c_string(p->out, p->rowSeparator);
19784       raw_printf(p->out, "\n");
19785     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
19786     utf8_printf(p->out, "%12.12s: ", "width");
19787     for (i=0;i<p->nWidth;i++) {
19788       raw_printf(p->out, "%d ", p->colWidth[i]);
19789     }
19790     raw_printf(p->out, "\n");
19791     utf8_printf(p->out, "%12.12s: %s\n", "filename",
19792                 p->zDbFilename ? p->zDbFilename : "");
19793   }else
19794
19795   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
19796     if( nArg==2 ){
19797       p->statsOn = (u8)booleanValue(azArg[1]);
19798     }else if( nArg==1 ){
19799       display_stats(p->db, p, 0);
19800     }else{
19801       raw_printf(stderr, "Usage: .stats ?on|off?\n");
19802       rc = 1;
19803     }
19804   }else
19805
19806   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
19807    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
19808                  || strncmp(azArg[0], "indexes", n)==0) )
19809   ){
19810     sqlite3_stmt *pStmt;
19811     char **azResult;
19812     int nRow, nAlloc;
19813     int ii;
19814     ShellText s;
19815     initText(&s);
19816     open_db(p, 0);
19817     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
19818     if( rc ){
19819       sqlite3_finalize(pStmt);
19820       return shellDatabaseError(p->db);
19821     }
19822
19823     if( nArg>2 && c=='i' ){
19824       /* It is an historical accident that the .indexes command shows an error
19825       ** when called with the wrong number of arguments whereas the .tables
19826       ** command does not. */
19827       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
19828       rc = 1;
19829       sqlite3_finalize(pStmt);
19830       goto meta_command_exit;
19831     }
19832     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
19833       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
19834       if( zDbName==0 ) continue;
19835       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
19836       if( sqlite3_stricmp(zDbName, "main")==0 ){
19837         appendText(&s, "SELECT name FROM ", 0);
19838       }else{
19839         appendText(&s, "SELECT ", 0);
19840         appendText(&s, zDbName, '\'');
19841         appendText(&s, "||'.'||name FROM ", 0);
19842       }
19843       appendText(&s, zDbName, '"');
19844       appendText(&s, ".sqlite_schema ", 0);
19845       if( c=='t' ){
19846         appendText(&s," WHERE type IN ('table','view')"
19847                       "   AND name NOT LIKE 'sqlite_%'"
19848                       "   AND name LIKE ?1", 0);
19849       }else{
19850         appendText(&s," WHERE type='index'"
19851                       "   AND tbl_name LIKE ?1", 0);
19852       }
19853     }
19854     rc = sqlite3_finalize(pStmt);
19855     appendText(&s, " ORDER BY 1", 0);
19856     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
19857     freeText(&s);
19858     if( rc ) return shellDatabaseError(p->db);
19859
19860     /* Run the SQL statement prepared by the above block. Store the results
19861     ** as an array of nul-terminated strings in azResult[].  */
19862     nRow = nAlloc = 0;
19863     azResult = 0;
19864     if( nArg>1 ){
19865       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
19866     }else{
19867       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
19868     }
19869     while( sqlite3_step(pStmt)==SQLITE_ROW ){
19870       if( nRow>=nAlloc ){
19871         char **azNew;
19872         int n2 = nAlloc*2 + 10;
19873         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
19874         if( azNew==0 ) shell_out_of_memory();
19875         nAlloc = n2;
19876         azResult = azNew;
19877       }
19878       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
19879       if( 0==azResult[nRow] ) shell_out_of_memory();
19880       nRow++;
19881     }
19882     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
19883       rc = shellDatabaseError(p->db);
19884     }
19885
19886     /* Pretty-print the contents of array azResult[] to the output */
19887     if( rc==0 && nRow>0 ){
19888       int len, maxlen = 0;
19889       int i, j;
19890       int nPrintCol, nPrintRow;
19891       for(i=0; i<nRow; i++){
19892         len = strlen30(azResult[i]);
19893         if( len>maxlen ) maxlen = len;
19894       }
19895       nPrintCol = 80/(maxlen+2);
19896       if( nPrintCol<1 ) nPrintCol = 1;
19897       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
19898       for(i=0; i<nPrintRow; i++){
19899         for(j=i; j<nRow; j+=nPrintRow){
19900           char *zSp = j<nPrintRow ? "" : "  ";
19901           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
19902                       azResult[j] ? azResult[j]:"");
19903         }
19904         raw_printf(p->out, "\n");
19905       }
19906     }
19907
19908     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
19909     sqlite3_free(azResult);
19910   }else
19911
19912   /* Begin redirecting output to the file "testcase-out.txt" */
19913   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
19914     output_reset(p);
19915     p->out = output_file_open("testcase-out.txt", 0);
19916     if( p->out==0 ){
19917       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
19918     }
19919     if( nArg>=2 ){
19920       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
19921     }else{
19922       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
19923     }
19924   }else
19925
19926 #ifndef SQLITE_UNTESTABLE
19927   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
19928     static const struct {
19929        const char *zCtrlName;   /* Name of a test-control option */
19930        int ctrlCode;            /* Integer code for that option */
19931        const char *zUsage;      /* Usage notes */
19932     } aCtrl[] = {
19933       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
19934       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
19935     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
19936     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
19937       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
19938       { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
19939     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
19940       { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
19941       { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
19942       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
19943       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
19944       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
19945 #ifdef YYCOVERAGE
19946       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
19947 #endif
19948       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
19949       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
19950       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
19951       { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
19952       { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,    ""               },
19953     };
19954     int testctrl = -1;
19955     int iCtrl = -1;
19956     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
19957     int isOk = 0;
19958     int i, n2;
19959     const char *zCmd = 0;
19960
19961     open_db(p, 0);
19962     zCmd = nArg>=2 ? azArg[1] : "help";
19963
19964     /* The argument can optionally begin with "-" or "--" */
19965     if( zCmd[0]=='-' && zCmd[1] ){
19966       zCmd++;
19967       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
19968     }
19969
19970     /* --help lists all test-controls */
19971     if( strcmp(zCmd,"help")==0 ){
19972       utf8_printf(p->out, "Available test-controls:\n");
19973       for(i=0; i<ArraySize(aCtrl); i++){
19974         utf8_printf(p->out, "  .testctrl %s %s\n",
19975                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
19976       }
19977       rc = 1;
19978       goto meta_command_exit;
19979     }
19980
19981     /* convert testctrl text option to value. allow any unique prefix
19982     ** of the option name, or a numerical value. */
19983     n2 = strlen30(zCmd);
19984     for(i=0; i<ArraySize(aCtrl); i++){
19985       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
19986         if( testctrl<0 ){
19987           testctrl = aCtrl[i].ctrlCode;
19988           iCtrl = i;
19989         }else{
19990           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
19991                               "Use \".testctrl --help\" for help\n", zCmd);
19992           rc = 1;
19993           goto meta_command_exit;
19994         }
19995       }
19996     }
19997     if( testctrl<0 ){
19998       utf8_printf(stderr,"Error: unknown test-control: %s\n"
19999                          "Use \".testctrl --help\" for help\n", zCmd);
20000     }else{
20001       switch(testctrl){
20002
20003         /* sqlite3_test_control(int, db, int) */
20004         case SQLITE_TESTCTRL_OPTIMIZATIONS:
20005           if( nArg==3 ){
20006             int opt = (int)strtol(azArg[2], 0, 0);
20007             rc2 = sqlite3_test_control(testctrl, p->db, opt);
20008             isOk = 3;
20009           }
20010           break;
20011
20012         /* sqlite3_test_control(int) */
20013         case SQLITE_TESTCTRL_PRNG_SAVE:
20014         case SQLITE_TESTCTRL_PRNG_RESTORE:
20015         case SQLITE_TESTCTRL_BYTEORDER:
20016           if( nArg==2 ){
20017             rc2 = sqlite3_test_control(testctrl);
20018             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
20019           }
20020           break;
20021
20022         /* sqlite3_test_control(int, uint) */
20023         case SQLITE_TESTCTRL_PENDING_BYTE:
20024           if( nArg==3 ){
20025             unsigned int opt = (unsigned int)integerValue(azArg[2]);
20026             rc2 = sqlite3_test_control(testctrl, opt);
20027             isOk = 3;
20028           }
20029           break;
20030
20031         /* sqlite3_test_control(int, int, sqlite3*) */
20032         case SQLITE_TESTCTRL_PRNG_SEED:
20033           if( nArg==3 || nArg==4 ){
20034             int ii = (int)integerValue(azArg[2]);
20035             sqlite3 *db;
20036             if( ii==0 && strcmp(azArg[2],"random")==0 ){
20037               sqlite3_randomness(sizeof(ii),&ii);
20038               printf("-- random seed: %d\n", ii);
20039             }
20040             if( nArg==3 ){
20041               db = 0;
20042             }else{
20043               db = p->db;
20044               /* Make sure the schema has been loaded */
20045               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
20046             }
20047             rc2 = sqlite3_test_control(testctrl, ii, db);
20048             isOk = 3;
20049           }
20050           break;
20051
20052         /* sqlite3_test_control(int, int) */
20053         case SQLITE_TESTCTRL_ASSERT:
20054         case SQLITE_TESTCTRL_ALWAYS:
20055           if( nArg==3 ){
20056             int opt = booleanValue(azArg[2]);
20057             rc2 = sqlite3_test_control(testctrl, opt);
20058             isOk = 1;
20059           }
20060           break;
20061
20062         /* sqlite3_test_control(int, int) */
20063         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
20064         case SQLITE_TESTCTRL_NEVER_CORRUPT:
20065           if( nArg==3 ){
20066             int opt = booleanValue(azArg[2]);
20067             rc2 = sqlite3_test_control(testctrl, opt);
20068             isOk = 3;
20069           }
20070           break;
20071
20072         /* sqlite3_test_control(sqlite3*) */
20073         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
20074           rc2 = sqlite3_test_control(testctrl, p->db);
20075           isOk = 3;
20076           break;
20077
20078         case SQLITE_TESTCTRL_IMPOSTER:
20079           if( nArg==5 ){
20080             rc2 = sqlite3_test_control(testctrl, p->db,
20081                           azArg[2],
20082                           integerValue(azArg[3]),
20083                           integerValue(azArg[4]));
20084             isOk = 3;
20085           }
20086           break;
20087
20088         case SQLITE_TESTCTRL_SEEK_COUNT: {
20089           u64 x = 0;
20090           rc2 = sqlite3_test_control(testctrl, p->db, &x);
20091           utf8_printf(p->out, "%llu\n", x);
20092           isOk = 3;
20093           break;
20094         }
20095
20096 #ifdef YYCOVERAGE
20097         case SQLITE_TESTCTRL_PARSER_COVERAGE:
20098           if( nArg==2 ){
20099             sqlite3_test_control(testctrl, p->out);
20100             isOk = 3;
20101           }
20102 #endif
20103       }
20104     }
20105     if( isOk==0 && iCtrl>=0 ){
20106       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
20107       rc = 1;
20108     }else if( isOk==1 ){
20109       raw_printf(p->out, "%d\n", rc2);
20110     }else if( isOk==2 ){
20111       raw_printf(p->out, "0x%08x\n", rc2);
20112     }
20113   }else
20114 #endif /* !defined(SQLITE_UNTESTABLE) */
20115
20116   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
20117     open_db(p, 0);
20118     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
20119   }else
20120
20121   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
20122     if( nArg==2 ){
20123       enableTimer = booleanValue(azArg[1]);
20124       if( enableTimer && !HAS_TIMER ){
20125         raw_printf(stderr, "Error: timer not available on this system.\n");
20126         enableTimer = 0;
20127       }
20128     }else{
20129       raw_printf(stderr, "Usage: .timer on|off\n");
20130       rc = 1;
20131     }
20132   }else
20133
20134 #ifndef SQLITE_OMIT_TRACE
20135   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
20136     int mType = 0;
20137     int jj;
20138     open_db(p, 0);
20139     for(jj=1; jj<nArg; jj++){
20140       const char *z = azArg[jj];
20141       if( z[0]=='-' ){
20142         if( optionMatch(z, "expanded") ){
20143           p->eTraceType = SHELL_TRACE_EXPANDED;
20144         }
20145 #ifdef SQLITE_ENABLE_NORMALIZE
20146         else if( optionMatch(z, "normalized") ){
20147           p->eTraceType = SHELL_TRACE_NORMALIZED;
20148         }
20149 #endif
20150         else if( optionMatch(z, "plain") ){
20151           p->eTraceType = SHELL_TRACE_PLAIN;
20152         }
20153         else if( optionMatch(z, "profile") ){
20154           mType |= SQLITE_TRACE_PROFILE;
20155         }
20156         else if( optionMatch(z, "row") ){
20157           mType |= SQLITE_TRACE_ROW;
20158         }
20159         else if( optionMatch(z, "stmt") ){
20160           mType |= SQLITE_TRACE_STMT;
20161         }
20162         else if( optionMatch(z, "close") ){
20163           mType |= SQLITE_TRACE_CLOSE;
20164         }
20165         else {
20166           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
20167           rc = 1;
20168           goto meta_command_exit;
20169         }
20170       }else{
20171         output_file_close(p->traceOut);
20172         p->traceOut = output_file_open(azArg[1], 0);
20173       }
20174     }
20175     if( p->traceOut==0 ){
20176       sqlite3_trace_v2(p->db, 0, 0, 0);
20177     }else{
20178       if( mType==0 ) mType = SQLITE_TRACE_STMT;
20179       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
20180     }
20181   }else
20182 #endif /* !defined(SQLITE_OMIT_TRACE) */
20183
20184 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
20185   if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
20186     int ii;
20187     int lenOpt;
20188     char *zOpt;
20189     if( nArg<2 ){
20190       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
20191       rc = 1;
20192       goto meta_command_exit;
20193     }
20194     open_db(p, 0);
20195     zOpt = azArg[1];
20196     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
20197     lenOpt = (int)strlen(zOpt);
20198     if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
20199       assert( azArg[nArg]==0 );
20200       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
20201     }else{
20202       for(ii=1; ii<nArg; ii++){
20203         sqlite3_create_module(p->db, azArg[ii], 0, 0);
20204       }
20205     }
20206   }else
20207 #endif
20208
20209 #if SQLITE_USER_AUTHENTICATION
20210   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
20211     if( nArg<2 ){
20212       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
20213       rc = 1;
20214       goto meta_command_exit;
20215     }
20216     open_db(p, 0);
20217     if( strcmp(azArg[1],"login")==0 ){
20218       if( nArg!=4 ){
20219         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
20220         rc = 1;
20221         goto meta_command_exit;
20222       }
20223       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
20224                                      strlen30(azArg[3]));
20225       if( rc ){
20226         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
20227         rc = 1;
20228       }
20229     }else if( strcmp(azArg[1],"add")==0 ){
20230       if( nArg!=5 ){
20231         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
20232         rc = 1;
20233         goto meta_command_exit;
20234       }
20235       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
20236                             booleanValue(azArg[4]));
20237       if( rc ){
20238         raw_printf(stderr, "User-Add failed: %d\n", rc);
20239         rc = 1;
20240       }
20241     }else if( strcmp(azArg[1],"edit")==0 ){
20242       if( nArg!=5 ){
20243         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
20244         rc = 1;
20245         goto meta_command_exit;
20246       }
20247       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
20248                               booleanValue(azArg[4]));
20249       if( rc ){
20250         raw_printf(stderr, "User-Edit failed: %d\n", rc);
20251         rc = 1;
20252       }
20253     }else if( strcmp(azArg[1],"delete")==0 ){
20254       if( nArg!=3 ){
20255         raw_printf(stderr, "Usage: .user delete USER\n");
20256         rc = 1;
20257         goto meta_command_exit;
20258       }
20259       rc = sqlite3_user_delete(p->db, azArg[2]);
20260       if( rc ){
20261         raw_printf(stderr, "User-Delete failed: %d\n", rc);
20262         rc = 1;
20263       }
20264     }else{
20265       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
20266       rc = 1;
20267       goto meta_command_exit;
20268     }
20269   }else
20270 #endif /* SQLITE_USER_AUTHENTICATION */
20271
20272   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
20273     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
20274         sqlite3_libversion(), sqlite3_sourceid());
20275 #if SQLITE_HAVE_ZLIB
20276     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
20277 #endif
20278 #define CTIMEOPT_VAL_(opt) #opt
20279 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
20280 #if defined(__clang__) && defined(__clang_major__)
20281     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
20282                     CTIMEOPT_VAL(__clang_minor__) "."
20283                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
20284 #elif defined(_MSC_VER)
20285     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
20286 #elif defined(__GNUC__) && defined(__VERSION__)
20287     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
20288 #endif
20289   }else
20290
20291   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
20292     const char *zDbName = nArg==2 ? azArg[1] : "main";
20293     sqlite3_vfs *pVfs = 0;
20294     if( p->db ){
20295       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
20296       if( pVfs ){
20297         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
20298         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
20299         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
20300         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
20301       }
20302     }
20303   }else
20304
20305   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
20306     sqlite3_vfs *pVfs;
20307     sqlite3_vfs *pCurrent = 0;
20308     if( p->db ){
20309       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
20310     }
20311     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
20312       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
20313            pVfs==pCurrent ? "  <--- CURRENT" : "");
20314       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
20315       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
20316       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
20317       if( pVfs->pNext ){
20318         raw_printf(p->out, "-----------------------------------\n");
20319       }
20320     }
20321   }else
20322
20323   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
20324     const char *zDbName = nArg==2 ? azArg[1] : "main";
20325     char *zVfsName = 0;
20326     if( p->db ){
20327       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
20328       if( zVfsName ){
20329         utf8_printf(p->out, "%s\n", zVfsName);
20330         sqlite3_free(zVfsName);
20331       }
20332     }
20333   }else
20334
20335 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
20336   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
20337     sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
20338   }else
20339 #endif
20340
20341   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
20342     int j;
20343     assert( nArg<=ArraySize(azArg) );
20344     p->nWidth = nArg-1;
20345     p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
20346     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
20347     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
20348     for(j=1; j<nArg; j++){
20349       p->colWidth[j-1] = (int)integerValue(azArg[j]);
20350     }
20351   }else
20352
20353   {
20354     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
20355       " \"%s\". Enter \".help\" for help\n", azArg[0]);
20356     rc = 1;
20357   }
20358
20359 meta_command_exit:
20360   if( p->outCount ){
20361     p->outCount--;
20362     if( p->outCount==0 ) output_reset(p);
20363   }
20364   return rc;
20365 }
20366
20367 /*
20368 ** Return TRUE if a semicolon occurs anywhere in the first N characters
20369 ** of string z[].
20370 */
20371 static int line_contains_semicolon(const char *z, int N){
20372   int i;
20373   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
20374   return 0;
20375 }
20376
20377 /*
20378 ** Test to see if a line consists entirely of whitespace.
20379 */
20380 static int _all_whitespace(const char *z){
20381   for(; *z; z++){
20382     if( IsSpace(z[0]) ) continue;
20383     if( *z=='/' && z[1]=='*' ){
20384       z += 2;
20385       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
20386       if( *z==0 ) return 0;
20387       z++;
20388       continue;
20389     }
20390     if( *z=='-' && z[1]=='-' ){
20391       z += 2;
20392       while( *z && *z!='\n' ){ z++; }
20393       if( *z==0 ) return 1;
20394       continue;
20395     }
20396     return 0;
20397   }
20398   return 1;
20399 }
20400
20401 /*
20402 ** Return TRUE if the line typed in is an SQL command terminator other
20403 ** than a semi-colon.  The SQL Server style "go" command is understood
20404 ** as is the Oracle "/".
20405 */
20406 static int line_is_command_terminator(const char *zLine){
20407   while( IsSpace(zLine[0]) ){ zLine++; };
20408   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
20409     return 1;  /* Oracle */
20410   }
20411   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
20412          && _all_whitespace(&zLine[2]) ){
20413     return 1;  /* SQL Server */
20414   }
20415   return 0;
20416 }
20417
20418 /*
20419 ** We need a default sqlite3_complete() implementation to use in case
20420 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
20421 ** any arbitrary text is a complete SQL statement.  This is not very
20422 ** user-friendly, but it does seem to work.
20423 */
20424 #ifdef SQLITE_OMIT_COMPLETE
20425 #define sqlite3_complete(x) 1
20426 #endif
20427
20428 /*
20429 ** Return true if zSql is a complete SQL statement.  Return false if it
20430 ** ends in the middle of a string literal or C-style comment.
20431 */
20432 static int line_is_complete(char *zSql, int nSql){
20433   int rc;
20434   if( zSql==0 ) return 1;
20435   zSql[nSql] = ';';
20436   zSql[nSql+1] = 0;
20437   rc = sqlite3_complete(zSql);
20438   zSql[nSql] = 0;
20439   return rc;
20440 }
20441
20442 /*
20443 ** Run a single line of SQL.  Return the number of errors.
20444 */
20445 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
20446   int rc;
20447   char *zErrMsg = 0;
20448
20449   open_db(p, 0);
20450   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
20451   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
20452   BEGIN_TIMER;
20453   rc = shell_exec(p, zSql, &zErrMsg);
20454   END_TIMER;
20455   if( rc || zErrMsg ){
20456     char zPrefix[100];
20457     if( in!=0 || !stdin_is_interactive ){
20458       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
20459                        "Error: near line %d:", startline);
20460     }else{
20461       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
20462     }
20463     if( zErrMsg!=0 ){
20464       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
20465       sqlite3_free(zErrMsg);
20466       zErrMsg = 0;
20467     }else{
20468       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
20469     }
20470     return 1;
20471   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
20472     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
20473             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
20474   }
20475   return 0;
20476 }
20477
20478
20479 /*
20480 ** Read input from *in and process it.  If *in==0 then input
20481 ** is interactive - the user is typing it it.  Otherwise, input
20482 ** is coming from a file or device.  A prompt is issued and history
20483 ** is saved only if input is interactive.  An interrupt signal will
20484 ** cause this routine to exit immediately, unless input is interactive.
20485 **
20486 ** Return the number of errors.
20487 */
20488 static int process_input(ShellState *p){
20489   char *zLine = 0;          /* A single input line */
20490   char *zSql = 0;           /* Accumulated SQL text */
20491   int nLine;                /* Length of current line */
20492   int nSql = 0;             /* Bytes of zSql[] used */
20493   int nAlloc = 0;           /* Allocated zSql[] space */
20494   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
20495   int rc;                   /* Error code */
20496   int errCnt = 0;           /* Number of errors seen */
20497   int startline = 0;        /* Line number for start of current input */
20498
20499   p->lineno = 0;
20500   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
20501     fflush(p->out);
20502     zLine = one_input_line(p->in, zLine, nSql>0);
20503     if( zLine==0 ){
20504       /* End of input */
20505       if( p->in==0 && stdin_is_interactive ) printf("\n");
20506       break;
20507     }
20508     if( seenInterrupt ){
20509       if( p->in!=0 ) break;
20510       seenInterrupt = 0;
20511     }
20512     p->lineno++;
20513     if( nSql==0 && _all_whitespace(zLine) ){
20514       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
20515       continue;
20516     }
20517     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
20518       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
20519       if( zLine[0]=='.' ){
20520         rc = do_meta_command(zLine, p);
20521         if( rc==2 ){ /* exit requested */
20522           break;
20523         }else if( rc ){
20524           errCnt++;
20525         }
20526       }
20527       continue;
20528     }
20529     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
20530       memcpy(zLine,";",2);
20531     }
20532     nLine = strlen30(zLine);
20533     if( nSql+nLine+2>=nAlloc ){
20534       nAlloc = nSql+nLine+100;
20535       zSql = realloc(zSql, nAlloc);
20536       if( zSql==0 ) shell_out_of_memory();
20537     }
20538     nSqlPrior = nSql;
20539     if( nSql==0 ){
20540       int i;
20541       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
20542       assert( nAlloc>0 && zSql!=0 );
20543       memcpy(zSql, zLine+i, nLine+1-i);
20544       startline = p->lineno;
20545       nSql = nLine-i;
20546     }else{
20547       zSql[nSql++] = '\n';
20548       memcpy(zSql+nSql, zLine, nLine+1);
20549       nSql += nLine;
20550     }
20551     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
20552                 && sqlite3_complete(zSql) ){
20553       errCnt += runOneSqlLine(p, zSql, p->in, startline);
20554       nSql = 0;
20555       if( p->outCount ){
20556         output_reset(p);
20557         p->outCount = 0;
20558       }else{
20559         clearTempFile(p);
20560       }
20561     }else if( nSql && _all_whitespace(zSql) ){
20562       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
20563       nSql = 0;
20564     }
20565   }
20566   if( nSql && !_all_whitespace(zSql) ){
20567     errCnt += runOneSqlLine(p, zSql, p->in, startline);
20568   }
20569   free(zSql);
20570   free(zLine);
20571   return errCnt>0;
20572 }
20573
20574 /*
20575 ** Return a pathname which is the user's home directory.  A
20576 ** 0 return indicates an error of some kind.
20577 */
20578 static char *find_home_dir(int clearFlag){
20579   static char *home_dir = NULL;
20580   if( clearFlag ){
20581     free(home_dir);
20582     home_dir = 0;
20583     return 0;
20584   }
20585   if( home_dir ) return home_dir;
20586
20587 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
20588      && !defined(__RTP__) && !defined(_WRS_KERNEL)
20589   {
20590     struct passwd *pwent;
20591     uid_t uid = getuid();
20592     if( (pwent=getpwuid(uid)) != NULL) {
20593       home_dir = pwent->pw_dir;
20594     }
20595   }
20596 #endif
20597
20598 #if defined(_WIN32_WCE)
20599   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
20600    */
20601   home_dir = "/";
20602 #else
20603
20604 #if defined(_WIN32) || defined(WIN32)
20605   if (!home_dir) {
20606     home_dir = getenv("USERPROFILE");
20607   }
20608 #endif
20609
20610   if (!home_dir) {
20611     home_dir = getenv("HOME");
20612   }
20613
20614 #if defined(_WIN32) || defined(WIN32)
20615   if (!home_dir) {
20616     char *zDrive, *zPath;
20617     int n;
20618     zDrive = getenv("HOMEDRIVE");
20619     zPath = getenv("HOMEPATH");
20620     if( zDrive && zPath ){
20621       n = strlen30(zDrive) + strlen30(zPath) + 1;
20622       home_dir = malloc( n );
20623       if( home_dir==0 ) return 0;
20624       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
20625       return home_dir;
20626     }
20627     home_dir = "c:\\";
20628   }
20629 #endif
20630
20631 #endif /* !_WIN32_WCE */
20632
20633   if( home_dir ){
20634     int n = strlen30(home_dir) + 1;
20635     char *z = malloc( n );
20636     if( z ) memcpy(z, home_dir, n);
20637     home_dir = z;
20638   }
20639
20640   return home_dir;
20641 }
20642
20643 /*
20644 ** Read input from the file given by sqliterc_override.  Or if that
20645 ** parameter is NULL, take input from ~/.sqliterc
20646 **
20647 ** Returns the number of errors.
20648 */
20649 static void process_sqliterc(
20650   ShellState *p,                  /* Configuration data */
20651   const char *sqliterc_override   /* Name of config file. NULL to use default */
20652 ){
20653   char *home_dir = NULL;
20654   const char *sqliterc = sqliterc_override;
20655   char *zBuf = 0;
20656   FILE *inSaved = p->in;
20657   int savedLineno = p->lineno;
20658
20659   if (sqliterc == NULL) {
20660     home_dir = find_home_dir(0);
20661     if( home_dir==0 ){
20662       raw_printf(stderr, "-- warning: cannot find home directory;"
20663                       " cannot read ~/.sqliterc\n");
20664       return;
20665     }
20666     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
20667     sqliterc = zBuf;
20668   }
20669   p->in = fopen(sqliterc,"rb");
20670   if( p->in ){
20671     if( stdin_is_interactive ){
20672       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
20673     }
20674     if( process_input(p) && bail_on_error ) exit(1);
20675     fclose(p->in);
20676   }else if( sqliterc_override!=0 ){
20677     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
20678     if( bail_on_error ) exit(1);
20679   }
20680   p->in = inSaved;
20681   p->lineno = savedLineno;
20682   sqlite3_free(zBuf);
20683 }
20684
20685 /*
20686 ** Show available command line options
20687 */
20688 static const char zOptions[] =
20689 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
20690   "   -A ARGS...           run \".archive ARGS\" and exit\n"
20691 #endif
20692   "   -append              append the database to the end of the file\n"
20693   "   -ascii               set output mode to 'ascii'\n"
20694   "   -bail                stop after hitting an error\n"
20695   "   -batch               force batch I/O\n"
20696   "   -box                 set output mode to 'box'\n"
20697   "   -column              set output mode to 'column'\n"
20698   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
20699   "   -csv                 set output mode to 'csv'\n"
20700 #if defined(SQLITE_ENABLE_DESERIALIZE)
20701   "   -deserialize         open the database using sqlite3_deserialize()\n"
20702 #endif
20703   "   -echo                print commands before execution\n"
20704   "   -init FILENAME       read/process named file\n"
20705   "   -[no]header          turn headers on or off\n"
20706 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
20707   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
20708 #endif
20709   "   -help                show this message\n"
20710   "   -html                set output mode to HTML\n"
20711   "   -interactive         force interactive I/O\n"
20712   "   -json                set output mode to 'json'\n"
20713   "   -line                set output mode to 'line'\n"
20714   "   -list                set output mode to 'list'\n"
20715   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
20716   "   -markdown            set output mode to 'markdown'\n"
20717 #if defined(SQLITE_ENABLE_DESERIALIZE)
20718   "   -maxsize N           maximum size for a --deserialize database\n"
20719 #endif
20720   "   -memtrace            trace all memory allocations and deallocations\n"
20721   "   -mmap N              default mmap size set to N\n"
20722 #ifdef SQLITE_ENABLE_MULTIPLEX
20723   "   -multiplex           enable the multiplexor VFS\n"
20724 #endif
20725   "   -newline SEP         set output row separator. Default: '\\n'\n"
20726   "   -nofollow            refuse to open symbolic links to database files\n"
20727   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
20728   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
20729   "   -quote               set output mode to 'quote'\n"
20730   "   -readonly            open the database read-only\n"
20731   "   -separator SEP       set output column separator. Default: '|'\n"
20732 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
20733   "   -sorterref SIZE      sorter references threshold size\n"
20734 #endif
20735   "   -stats               print memory stats before each finalize\n"
20736   "   -table               set output mode to 'table'\n"
20737   "   -tabs                set output mode to 'tabs'\n"
20738   "   -version             show SQLite version\n"
20739   "   -vfs NAME            use NAME as the default VFS\n"
20740 #ifdef SQLITE_ENABLE_VFSTRACE
20741   "   -vfstrace            enable tracing of all VFS calls\n"
20742 #endif
20743 #ifdef SQLITE_HAVE_ZLIB
20744   "   -zip                 open the file as a ZIP Archive\n"
20745 #endif
20746 ;
20747 static void usage(int showDetail){
20748   utf8_printf(stderr,
20749       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
20750       "FILENAME is the name of an SQLite database. A new database is created\n"
20751       "if the file does not previously exist.\n", Argv0);
20752   if( showDetail ){
20753     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
20754   }else{
20755     raw_printf(stderr, "Use the -help option for additional information\n");
20756   }
20757   exit(1);
20758 }
20759
20760 /*
20761 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
20762 ** error message if it is initialized.
20763 */
20764 static void verify_uninitialized(void){
20765   if( sqlite3_config(-1)==SQLITE_MISUSE ){
20766     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
20767                         " initialization.\n");
20768   }
20769 }
20770
20771 /*
20772 ** Initialize the state information in data
20773 */
20774 static void main_init(ShellState *data) {
20775   memset(data, 0, sizeof(*data));
20776   data->normalMode = data->cMode = data->mode = MODE_List;
20777   data->autoExplain = 1;
20778   memcpy(data->colSeparator,SEP_Column, 2);
20779   memcpy(data->rowSeparator,SEP_Row, 2);
20780   data->showHeader = 0;
20781   data->shellFlgs = SHFLG_Lookaside;
20782   verify_uninitialized();
20783   sqlite3_config(SQLITE_CONFIG_URI, 1);
20784   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
20785   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
20786   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
20787   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
20788 }
20789
20790 /*
20791 ** Output text to the console in a font that attracts extra attention.
20792 */
20793 #ifdef _WIN32
20794 static void printBold(const char *zText){
20795 #if !SQLITE_OS_WINRT
20796   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
20797   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
20798   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
20799   SetConsoleTextAttribute(out,
20800          FOREGROUND_RED|FOREGROUND_INTENSITY
20801   );
20802 #endif
20803   printf("%s", zText);
20804 #if !SQLITE_OS_WINRT
20805   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
20806 #endif
20807 }
20808 #else
20809 static void printBold(const char *zText){
20810   printf("\033[1m%s\033[0m", zText);
20811 }
20812 #endif
20813
20814 /*
20815 ** Get the argument to an --option.  Throw an error and die if no argument
20816 ** is available.
20817 */
20818 static char *cmdline_option_value(int argc, char **argv, int i){
20819   if( i==argc ){
20820     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
20821             argv[0], argv[argc-1]);
20822     exit(1);
20823   }
20824   return argv[i];
20825 }
20826
20827 #ifndef SQLITE_SHELL_IS_UTF8
20828 #  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
20829 #    define SQLITE_SHELL_IS_UTF8          (0)
20830 #  else
20831 #    define SQLITE_SHELL_IS_UTF8          (1)
20832 #  endif
20833 #endif
20834
20835 #if SQLITE_SHELL_IS_UTF8
20836 int SQLITE_CDECL main(int argc, char **argv){
20837 #else
20838 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
20839   char **argv;
20840 #endif
20841   char *zErrMsg = 0;
20842   ShellState data;
20843   const char *zInitFile = 0;
20844   int i;
20845   int rc = 0;
20846   int warnInmemoryDb = 0;
20847   int readStdin = 1;
20848   int nCmd = 0;
20849   char **azCmd = 0;
20850   const char *zVfs = 0;           /* Value of -vfs command-line option */
20851 #if !SQLITE_SHELL_IS_UTF8
20852   char **argvToFree = 0;
20853   int argcToFree = 0;
20854 #endif
20855
20856   setBinaryMode(stdin, 0);
20857   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
20858   stdin_is_interactive = isatty(0);
20859   stdout_is_console = isatty(1);
20860
20861 #ifdef SQLITE_DEBUG
20862   registerOomSimulator();
20863 #endif
20864
20865 #if !defined(_WIN32_WCE)
20866   if( getenv("SQLITE_DEBUG_BREAK") ){
20867     if( isatty(0) && isatty(2) ){
20868       fprintf(stderr,
20869           "attach debugger to process %d and press any key to continue.\n",
20870           GETPID());
20871       fgetc(stdin);
20872     }else{
20873 #if defined(_WIN32) || defined(WIN32)
20874 #if SQLITE_OS_WINRT
20875       __debugbreak();
20876 #else
20877       DebugBreak();
20878 #endif
20879 #elif defined(SIGTRAP)
20880       raise(SIGTRAP);
20881 #endif
20882     }
20883   }
20884 #endif
20885
20886 #if USE_SYSTEM_SQLITE+0!=1
20887   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
20888     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
20889             sqlite3_sourceid(), SQLITE_SOURCE_ID);
20890     exit(1);
20891   }
20892 #endif
20893   main_init(&data);
20894
20895   /* On Windows, we must translate command-line arguments into UTF-8.
20896   ** The SQLite memory allocator subsystem has to be enabled in order to
20897   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
20898   ** subsequent sqlite3_config() calls will work.  So copy all results into
20899   ** memory that does not come from the SQLite memory allocator.
20900   */
20901 #if !SQLITE_SHELL_IS_UTF8
20902   sqlite3_initialize();
20903   argvToFree = malloc(sizeof(argv[0])*argc*2);
20904   argcToFree = argc;
20905   argv = argvToFree + argc;
20906   if( argv==0 ) shell_out_of_memory();
20907   for(i=0; i<argc; i++){
20908     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
20909     int n;
20910     if( z==0 ) shell_out_of_memory();
20911     n = (int)strlen(z);
20912     argv[i] = malloc( n+1 );
20913     if( argv[i]==0 ) shell_out_of_memory();
20914     memcpy(argv[i], z, n+1);
20915     argvToFree[i] = argv[i];
20916     sqlite3_free(z);
20917   }
20918   sqlite3_shutdown();
20919 #endif
20920
20921   assert( argc>=1 && argv && argv[0] );
20922   Argv0 = argv[0];
20923
20924   /* Make sure we have a valid signal handler early, before anything
20925   ** else is done.
20926   */
20927 #ifdef SIGINT
20928   signal(SIGINT, interrupt_handler);
20929 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
20930   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
20931 #endif
20932
20933 #ifdef SQLITE_SHELL_DBNAME_PROC
20934   {
20935     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
20936     ** of a C-function that will provide the name of the database file.  Use
20937     ** this compile-time option to embed this shell program in larger
20938     ** applications. */
20939     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
20940     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
20941     warnInmemoryDb = 0;
20942   }
20943 #endif
20944
20945   /* Do an initial pass through the command-line argument to locate
20946   ** the name of the database file, the name of the initialization file,
20947   ** the size of the alternative malloc heap,
20948   ** and the first command to execute.
20949   */
20950   verify_uninitialized();
20951   for(i=1; i<argc; i++){
20952     char *z;
20953     z = argv[i];
20954     if( z[0]!='-' ){
20955       if( data.zDbFilename==0 ){
20956         data.zDbFilename = z;
20957       }else{
20958         /* Excesss arguments are interpreted as SQL (or dot-commands) and
20959         ** mean that nothing is read from stdin */
20960         readStdin = 0;
20961         nCmd++;
20962         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
20963         if( azCmd==0 ) shell_out_of_memory();
20964         azCmd[nCmd-1] = z;
20965       }
20966     }
20967     if( z[1]=='-' ) z++;
20968     if( strcmp(z,"-separator")==0
20969      || strcmp(z,"-nullvalue")==0
20970      || strcmp(z,"-newline")==0
20971      || strcmp(z,"-cmd")==0
20972     ){
20973       (void)cmdline_option_value(argc, argv, ++i);
20974     }else if( strcmp(z,"-init")==0 ){
20975       zInitFile = cmdline_option_value(argc, argv, ++i);
20976     }else if( strcmp(z,"-batch")==0 ){
20977       /* Need to check for batch mode here to so we can avoid printing
20978       ** informational messages (like from process_sqliterc) before
20979       ** we do the actual processing of arguments later in a second pass.
20980       */
20981       stdin_is_interactive = 0;
20982     }else if( strcmp(z,"-heap")==0 ){
20983 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
20984       const char *zSize;
20985       sqlite3_int64 szHeap;
20986
20987       zSize = cmdline_option_value(argc, argv, ++i);
20988       szHeap = integerValue(zSize);
20989       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
20990       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
20991 #else
20992       (void)cmdline_option_value(argc, argv, ++i);
20993 #endif
20994     }else if( strcmp(z,"-pagecache")==0 ){
20995       sqlite3_int64 n, sz;
20996       sz = integerValue(cmdline_option_value(argc,argv,++i));
20997       if( sz>70000 ) sz = 70000;
20998       if( sz<0 ) sz = 0;
20999       n = integerValue(cmdline_option_value(argc,argv,++i));
21000       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
21001         n = 0xffffffffffffLL/sz;
21002       }
21003       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
21004                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
21005       data.shellFlgs |= SHFLG_Pagecache;
21006     }else if( strcmp(z,"-lookaside")==0 ){
21007       int n, sz;
21008       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
21009       if( sz<0 ) sz = 0;
21010       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
21011       if( n<0 ) n = 0;
21012       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
21013       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
21014 #ifdef SQLITE_ENABLE_VFSTRACE
21015     }else if( strcmp(z,"-vfstrace")==0 ){
21016       extern int vfstrace_register(
21017          const char *zTraceName,
21018          const char *zOldVfsName,
21019          int (*xOut)(const char*,void*),
21020          void *pOutArg,
21021          int makeDefault
21022       );
21023       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
21024 #endif
21025 #ifdef SQLITE_ENABLE_MULTIPLEX
21026     }else if( strcmp(z,"-multiplex")==0 ){
21027       extern int sqlite3_multiple_initialize(const char*,int);
21028       sqlite3_multiplex_initialize(0, 1);
21029 #endif
21030     }else if( strcmp(z,"-mmap")==0 ){
21031       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
21032       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
21033 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
21034     }else if( strcmp(z,"-sorterref")==0 ){
21035       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
21036       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
21037 #endif
21038     }else if( strcmp(z,"-vfs")==0 ){
21039       zVfs = cmdline_option_value(argc, argv, ++i);
21040 #ifdef SQLITE_HAVE_ZLIB
21041     }else if( strcmp(z,"-zip")==0 ){
21042       data.openMode = SHELL_OPEN_ZIPFILE;
21043 #endif
21044     }else if( strcmp(z,"-append")==0 ){
21045       data.openMode = SHELL_OPEN_APPENDVFS;
21046 #ifdef SQLITE_ENABLE_DESERIALIZE
21047     }else if( strcmp(z,"-deserialize")==0 ){
21048       data.openMode = SHELL_OPEN_DESERIALIZE;
21049     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
21050       data.szMax = integerValue(argv[++i]);
21051 #endif
21052     }else if( strcmp(z,"-readonly")==0 ){
21053       data.openMode = SHELL_OPEN_READONLY;
21054     }else if( strcmp(z,"-nofollow")==0 ){
21055       data.openFlags = SQLITE_OPEN_NOFOLLOW;
21056 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
21057     }else if( strncmp(z, "-A",2)==0 ){
21058       /* All remaining command-line arguments are passed to the ".archive"
21059       ** command, so ignore them */
21060       break;
21061 #endif
21062     }else if( strcmp(z, "-memtrace")==0 ){
21063       sqlite3MemTraceActivate(stderr);
21064     }else if( strcmp(z,"-bail")==0 ){
21065       bail_on_error = 1;
21066     }
21067   }
21068   verify_uninitialized();
21069
21070
21071 #ifdef SQLITE_SHELL_INIT_PROC
21072   {
21073     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
21074     ** of a C-function that will perform initialization actions on SQLite that
21075     ** occur just before or after sqlite3_initialize(). Use this compile-time
21076     ** option to embed this shell program in larger applications. */
21077     extern void SQLITE_SHELL_INIT_PROC(void);
21078     SQLITE_SHELL_INIT_PROC();
21079   }
21080 #else
21081   /* All the sqlite3_config() calls have now been made. So it is safe
21082   ** to call sqlite3_initialize() and process any command line -vfs option. */
21083   sqlite3_initialize();
21084 #endif
21085
21086   if( zVfs ){
21087     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
21088     if( pVfs ){
21089       sqlite3_vfs_register(pVfs, 1);
21090     }else{
21091       utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
21092       exit(1);
21093     }
21094   }
21095
21096   if( data.zDbFilename==0 ){
21097 #ifndef SQLITE_OMIT_MEMORYDB
21098     data.zDbFilename = ":memory:";
21099     warnInmemoryDb = argc==1;
21100 #else
21101     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
21102     return 1;
21103 #endif
21104   }
21105   data.out = stdout;
21106   sqlite3_appendvfs_init(0,0,0);
21107
21108   /* Go ahead and open the database file if it already exists.  If the
21109   ** file does not exist, delay opening it.  This prevents empty database
21110   ** files from being created if a user mistypes the database name argument
21111   ** to the sqlite command-line tool.
21112   */
21113   if( access(data.zDbFilename, 0)==0 ){
21114     open_db(&data, 0);
21115   }
21116
21117   /* Process the initialization file if there is one.  If no -init option
21118   ** is given on the command line, look for a file named ~/.sqliterc and
21119   ** try to process it.
21120   */
21121   process_sqliterc(&data,zInitFile);
21122
21123   /* Make a second pass through the command-line argument and set
21124   ** options.  This second pass is delayed until after the initialization
21125   ** file is processed so that the command-line arguments will override
21126   ** settings in the initialization file.
21127   */
21128   for(i=1; i<argc; i++){
21129     char *z = argv[i];
21130     if( z[0]!='-' ) continue;
21131     if( z[1]=='-' ){ z++; }
21132     if( strcmp(z,"-init")==0 ){
21133       i++;
21134     }else if( strcmp(z,"-html")==0 ){
21135       data.mode = MODE_Html;
21136     }else if( strcmp(z,"-list")==0 ){
21137       data.mode = MODE_List;
21138     }else if( strcmp(z,"-quote")==0 ){
21139       data.mode = MODE_Quote;
21140       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
21141       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
21142     }else if( strcmp(z,"-line")==0 ){
21143       data.mode = MODE_Line;
21144     }else if( strcmp(z,"-column")==0 ){
21145       data.mode = MODE_Column;
21146     }else if( strcmp(z,"-json")==0 ){
21147       data.mode = MODE_Json;
21148     }else if( strcmp(z,"-markdown")==0 ){
21149       data.mode = MODE_Markdown;
21150     }else if( strcmp(z,"-table")==0 ){
21151       data.mode = MODE_Table;
21152     }else if( strcmp(z,"-box")==0 ){
21153       data.mode = MODE_Box;
21154     }else if( strcmp(z,"-csv")==0 ){
21155       data.mode = MODE_Csv;
21156       memcpy(data.colSeparator,",",2);
21157 #ifdef SQLITE_HAVE_ZLIB
21158     }else if( strcmp(z,"-zip")==0 ){
21159       data.openMode = SHELL_OPEN_ZIPFILE;
21160 #endif
21161     }else if( strcmp(z,"-append")==0 ){
21162       data.openMode = SHELL_OPEN_APPENDVFS;
21163 #ifdef SQLITE_ENABLE_DESERIALIZE
21164     }else if( strcmp(z,"-deserialize")==0 ){
21165       data.openMode = SHELL_OPEN_DESERIALIZE;
21166     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
21167       data.szMax = integerValue(argv[++i]);
21168 #endif
21169     }else if( strcmp(z,"-readonly")==0 ){
21170       data.openMode = SHELL_OPEN_READONLY;
21171     }else if( strcmp(z,"-nofollow")==0 ){
21172       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
21173     }else if( strcmp(z,"-ascii")==0 ){
21174       data.mode = MODE_Ascii;
21175       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
21176       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
21177     }else if( strcmp(z,"-tabs")==0 ){
21178       data.mode = MODE_List;
21179       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
21180       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
21181     }else if( strcmp(z,"-separator")==0 ){
21182       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
21183                        "%s",cmdline_option_value(argc,argv,++i));
21184     }else if( strcmp(z,"-newline")==0 ){
21185       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
21186                        "%s",cmdline_option_value(argc,argv,++i));
21187     }else if( strcmp(z,"-nullvalue")==0 ){
21188       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
21189                        "%s",cmdline_option_value(argc,argv,++i));
21190     }else if( strcmp(z,"-header")==0 ){
21191       data.showHeader = 1;
21192     }else if( strcmp(z,"-noheader")==0 ){
21193       data.showHeader = 0;
21194     }else if( strcmp(z,"-echo")==0 ){
21195       ShellSetFlag(&data, SHFLG_Echo);
21196     }else if( strcmp(z,"-eqp")==0 ){
21197       data.autoEQP = AUTOEQP_on;
21198     }else if( strcmp(z,"-eqpfull")==0 ){
21199       data.autoEQP = AUTOEQP_full;
21200     }else if( strcmp(z,"-stats")==0 ){
21201       data.statsOn = 1;
21202     }else if( strcmp(z,"-scanstats")==0 ){
21203       data.scanstatsOn = 1;
21204     }else if( strcmp(z,"-backslash")==0 ){
21205       /* Undocumented command-line option: -backslash
21206       ** Causes C-style backslash escapes to be evaluated in SQL statements
21207       ** prior to sending the SQL into SQLite.  Useful for injecting
21208       ** crazy bytes in the middle of SQL statements for testing and debugging.
21209       */
21210       ShellSetFlag(&data, SHFLG_Backslash);
21211     }else if( strcmp(z,"-bail")==0 ){
21212       /* No-op.  The bail_on_error flag should already be set. */
21213     }else if( strcmp(z,"-version")==0 ){
21214       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
21215       return 0;
21216     }else if( strcmp(z,"-interactive")==0 ){
21217       stdin_is_interactive = 1;
21218     }else if( strcmp(z,"-batch")==0 ){
21219       stdin_is_interactive = 0;
21220     }else if( strcmp(z,"-heap")==0 ){
21221       i++;
21222     }else if( strcmp(z,"-pagecache")==0 ){
21223       i+=2;
21224     }else if( strcmp(z,"-lookaside")==0 ){
21225       i+=2;
21226     }else if( strcmp(z,"-mmap")==0 ){
21227       i++;
21228     }else if( strcmp(z,"-memtrace")==0 ){
21229       i++;
21230 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
21231     }else if( strcmp(z,"-sorterref")==0 ){
21232       i++;
21233 #endif
21234     }else if( strcmp(z,"-vfs")==0 ){
21235       i++;
21236 #ifdef SQLITE_ENABLE_VFSTRACE
21237     }else if( strcmp(z,"-vfstrace")==0 ){
21238       i++;
21239 #endif
21240 #ifdef SQLITE_ENABLE_MULTIPLEX
21241     }else if( strcmp(z,"-multiplex")==0 ){
21242       i++;
21243 #endif
21244     }else if( strcmp(z,"-help")==0 ){
21245       usage(1);
21246     }else if( strcmp(z,"-cmd")==0 ){
21247       /* Run commands that follow -cmd first and separately from commands
21248       ** that simply appear on the command-line.  This seems goofy.  It would
21249       ** be better if all commands ran in the order that they appear.  But
21250       ** we retain the goofy behavior for historical compatibility. */
21251       if( i==argc-1 ) break;
21252       z = cmdline_option_value(argc,argv,++i);
21253       if( z[0]=='.' ){
21254         rc = do_meta_command(z, &data);
21255         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
21256       }else{
21257         open_db(&data, 0);
21258         rc = shell_exec(&data, z, &zErrMsg);
21259         if( zErrMsg!=0 ){
21260           utf8_printf(stderr,"Error: %s\n", zErrMsg);
21261           if( bail_on_error ) return rc!=0 ? rc : 1;
21262         }else if( rc!=0 ){
21263           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
21264           if( bail_on_error ) return rc;
21265         }
21266       }
21267 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
21268     }else if( strncmp(z, "-A", 2)==0 ){
21269       if( nCmd>0 ){
21270         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
21271                             " with \"%s\"\n", z);
21272         return 1;
21273       }
21274       open_db(&data, OPEN_DB_ZIPFILE);
21275       if( z[2] ){
21276         argv[i] = &z[2];
21277         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
21278       }else{
21279         arDotCommand(&data, 1, argv+i, argc-i);
21280       }
21281       readStdin = 0;
21282       break;
21283 #endif
21284     }else{
21285       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
21286       raw_printf(stderr,"Use -help for a list of options.\n");
21287       return 1;
21288     }
21289     data.cMode = data.mode;
21290   }
21291
21292   if( !readStdin ){
21293     /* Run all arguments that do not begin with '-' as if they were separate
21294     ** command-line inputs, except for the argToSkip argument which contains
21295     ** the database filename.
21296     */
21297     for(i=0; i<nCmd; i++){
21298       if( azCmd[i][0]=='.' ){
21299         rc = do_meta_command(azCmd[i], &data);
21300         if( rc ){
21301           free(azCmd);
21302           return rc==2 ? 0 : rc;
21303         }
21304       }else{
21305         open_db(&data, 0);
21306         rc = shell_exec(&data, azCmd[i], &zErrMsg);
21307         if( zErrMsg || rc ){
21308           if( zErrMsg!=0 ){
21309             utf8_printf(stderr,"Error: %s\n", zErrMsg);
21310           }else{
21311             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
21312           }
21313           sqlite3_free(zErrMsg);
21314           free(azCmd);
21315           return rc!=0 ? rc : 1;
21316         }
21317       }
21318     }
21319   }else{
21320     /* Run commands received from standard input
21321     */
21322     if( stdin_is_interactive ){
21323       char *zHome;
21324       char *zHistory;
21325       int nHistory;
21326       printf(
21327         "SQLite version %s %.19s\n" /*extra-version-info*/
21328         "Enter \".help\" for usage hints.\n",
21329         sqlite3_libversion(), sqlite3_sourceid()
21330       );
21331       if( warnInmemoryDb ){
21332         printf("Connected to a ");
21333         printBold("transient in-memory database");
21334         printf(".\nUse \".open FILENAME\" to reopen on a "
21335                "persistent database.\n");
21336       }
21337       zHistory = getenv("SQLITE_HISTORY");
21338       if( zHistory ){
21339         zHistory = strdup(zHistory);
21340       }else if( (zHome = find_home_dir(0))!=0 ){
21341         nHistory = strlen30(zHome) + 20;
21342         if( (zHistory = malloc(nHistory))!=0 ){
21343           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
21344         }
21345       }
21346       if( zHistory ){ shell_read_history(zHistory); }
21347 #if HAVE_READLINE || HAVE_EDITLINE
21348       rl_attempted_completion_function = readline_completion;
21349 #elif HAVE_LINENOISE
21350       linenoiseSetCompletionCallback(linenoise_completion);
21351 #endif
21352       data.in = 0;
21353       rc = process_input(&data);
21354       if( zHistory ){
21355         shell_stifle_history(2000);
21356         shell_write_history(zHistory);
21357         free(zHistory);
21358       }
21359     }else{
21360       data.in = stdin;
21361       rc = process_input(&data);
21362     }
21363   }
21364   free(azCmd);
21365   set_table_name(&data, 0);
21366   if( data.db ){
21367     session_close_all(&data);
21368     close_db(data.db);
21369   }
21370   sqlite3_free(data.zFreeOnClose);
21371   find_home_dir(1);
21372   output_reset(&data);
21373   data.doXdgOpen = 0;
21374   clearTempFile(&data);
21375 #if !SQLITE_SHELL_IS_UTF8
21376   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
21377   free(argvToFree);
21378 #endif
21379   free(data.colWidth);
21380   /* Clear the global data structure so that valgrind will detect memory
21381   ** leaks */
21382   memset(&data, 0, sizeof(data));
21383   return rc;
21384 }