Home | History | Annotate | Download | only in dist
      1 /* DO NOT EDIT!
      2 ** This file is automatically generated by the script in the canonical
      3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
      4 ** code from various constituent source files of SQLite into this single
      5 ** "shell.c" file used to implement the SQLite command-line shell.
      6 **
      7 ** Most of the code found below comes from the "src/shell.c.in" file in
      8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
      9 ** lines that specify other files in the canonical source tree that are
     10 ** inserted to getnerate this complete program source file.
     11 **
     12 ** The code from multiple files is combined into this single "shell.c"
     13 ** source file to help make the command-line program easier to compile.
     14 **
     15 ** To modify this program, get a copy of the canonical SQLite source tree,
     16 ** edit the src/shell.c.in" and/or some of the other files that are included
     17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
     18 */
     19 /*
     20 ** 2001 September 15
     21 **
     22 ** The author disclaims copyright to this source code.  In place of
     23 ** a legal notice, here is a blessing:
     24 **
     25 **    May you do good and not evil.
     26 **    May you find forgiveness for yourself and forgive others.
     27 **    May you share freely, never taking more than you give.
     28 **
     29 *************************************************************************
     30 ** This file contains code to implement the "sqlite" command line
     31 ** utility for accessing SQLite databases.
     32 */
     33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
     34 /* This needs to come before any includes for MSVC compiler */
     35 #define _CRT_SECURE_NO_WARNINGS
     36 #endif
     37 
     38 /*
     39 ** Warning pragmas copied from msvc.h in the core.
     40 */
     41 #if defined(_MSC_VER)
     42 #pragma warning(disable : 4054)
     43 #pragma warning(disable : 4055)
     44 #pragma warning(disable : 4100)
     45 #pragma warning(disable : 4127)
     46 #pragma warning(disable : 4130)
     47 #pragma warning(disable : 4152)
     48 #pragma warning(disable : 4189)
     49 #pragma warning(disable : 4206)
     50 #pragma warning(disable : 4210)
     51 #pragma warning(disable : 4232)
     52 #pragma warning(disable : 4244)
     53 #pragma warning(disable : 4305)
     54 #pragma warning(disable : 4306)
     55 #pragma warning(disable : 4702)
     56 #pragma warning(disable : 4706)
     57 #endif /* defined(_MSC_VER) */
     58 
     59 /*
     60 ** No support for loadable extensions in VxWorks.
     61 */
     62 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
     63 # define SQLITE_OMIT_LOAD_EXTENSION 1
     64 #endif
     65 
     66 /*
     67 ** Enable large-file support for fopen() and friends on unix.
     68 */
     69 #ifndef SQLITE_DISABLE_LFS
     70 # define _LARGE_FILE       1
     71 # ifndef _FILE_OFFSET_BITS
     72 #   define _FILE_OFFSET_BITS 64
     73 # endif
     74 # define _LARGEFILE_SOURCE 1
     75 #endif
     76 
     77 #include <stdlib.h>
     78 #include <string.h>
     79 #include <stdio.h>
     80 #include <assert.h>
     81 #include "sqlite3.h"
     82 typedef sqlite3_int64 i64;
     83 typedef sqlite3_uint64 u64;
     84 typedef unsigned char u8;
     85 #if SQLITE_USER_AUTHENTICATION
     86 # include "sqlite3userauth.h"
     87 #endif
     88 #include <ctype.h>
     89 #include <stdarg.h>
     90 // Begin Android Add
     91 #ifndef NO_ANDROID_FUNCS
     92 #include "IcuUtils.h"
     93 #include <sqlite3_android.h>
     94 #endif
     95 // End Android Add
     96 
     97 #if !defined(_WIN32) && !defined(WIN32)
     98 # include <signal.h>
     99 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
    100 #  include <pwd.h>
    101 # endif
    102 #endif
    103 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
    104 # include <unistd.h>
    105 # include <dirent.h>
    106 # if defined(__MINGW32__)
    107 #  define DIRENT dirent
    108 #  ifndef S_ISLNK
    109 #   define S_ISLNK(mode) (0)
    110 #  endif
    111 # endif
    112 #endif
    113 #include <sys/types.h>
    114 #include <sys/stat.h>
    115 
    116 #if HAVE_READLINE
    117 # include <readline/readline.h>
    118 # include <readline/history.h>
    119 #endif
    120 
    121 #if HAVE_EDITLINE
    122 # include <editline/readline.h>
    123 #endif
    124 
    125 #if HAVE_EDITLINE || HAVE_READLINE
    126 
    127 # define shell_add_history(X) add_history(X)
    128 # define shell_read_history(X) read_history(X)
    129 # define shell_write_history(X) write_history(X)
    130 # define shell_stifle_history(X) stifle_history(X)
    131 # define shell_readline(X) readline(X)
    132 
    133 #elif HAVE_LINENOISE
    134 
    135 # include "linenoise.h"
    136 # define shell_add_history(X) linenoiseHistoryAdd(X)
    137 # define shell_read_history(X) linenoiseHistoryLoad(X)
    138 # define shell_write_history(X) linenoiseHistorySave(X)
    139 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
    140 # define shell_readline(X) linenoise(X)
    141 
    142 #else
    143 
    144 # define shell_read_history(X)
    145 # define shell_write_history(X)
    146 # define shell_stifle_history(X)
    147 
    148 # define SHELL_USE_LOCAL_GETLINE 1
    149 #endif
    150 
    151 
    152 #if defined(_WIN32) || defined(WIN32)
    153 # include <io.h>
    154 # include <fcntl.h>
    155 # define isatty(h) _isatty(h)
    156 # ifndef access
    157 #  define access(f,m) _access((f),(m))
    158 # endif
    159 # undef popen
    160 # define popen _popen
    161 # undef pclose
    162 # define pclose _pclose
    163 #else
    164  /* Make sure isatty() has a prototype. */
    165  extern int isatty(int);
    166 
    167 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
    168   /* popen and pclose are not C89 functions and so are
    169   ** sometimes omitted from the <stdio.h> header */
    170    extern FILE *popen(const char*,const char*);
    171    extern int pclose(FILE*);
    172 # else
    173 #  define SQLITE_OMIT_POPEN 1
    174 # endif
    175 #endif
    176 
    177 #if defined(_WIN32_WCE)
    178 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
    179  * thus we always assume that we have a console. That can be
    180  * overridden with the -batch command line option.
    181  */
    182 #define isatty(x) 1
    183 #endif
    184 
    185 /* ctype macros that work with signed characters */
    186 #define IsSpace(X)  isspace((unsigned char)X)
    187 #define IsDigit(X)  isdigit((unsigned char)X)
    188 #define ToLower(X)  (char)tolower((unsigned char)X)
    189 
    190 #if defined(_WIN32) || defined(WIN32)
    191 #include <windows.h>
    192 
    193 /* string conversion routines only needed on Win32 */
    194 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
    195 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
    196 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
    197 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
    198 #endif
    199 
    200 /* On Windows, we normally run with output mode of TEXT so that \n characters
    201 ** are automatically translated into \r\n.  However, this behavior needs
    202 ** to be disabled in some cases (ex: when generating CSV output and when
    203 ** rendering quoted strings that contain \n characters).  The following
    204 ** routines take care of that.
    205 */
    206 #if defined(_WIN32) || defined(WIN32)
    207 static void setBinaryMode(FILE *file, int isOutput){
    208   if( isOutput ) fflush(file);
    209   _setmode(_fileno(file), _O_BINARY);
    210 }
    211 static void setTextMode(FILE *file, int isOutput){
    212   if( isOutput ) fflush(file);
    213   _setmode(_fileno(file), _O_TEXT);
    214 }
    215 #else
    216 # define setBinaryMode(X,Y)
    217 # define setTextMode(X,Y)
    218 #endif
    219 
    220 
    221 /* True if the timer is enabled */
    222 static int enableTimer = 0;
    223 
    224 /* Return the current wall-clock time */
    225 static sqlite3_int64 timeOfDay(void){
    226   static sqlite3_vfs *clockVfs = 0;
    227   sqlite3_int64 t;
    228   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
    229   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
    230     clockVfs->xCurrentTimeInt64(clockVfs, &t);
    231   }else{
    232     double r;
    233     clockVfs->xCurrentTime(clockVfs, &r);
    234     t = (sqlite3_int64)(r*86400000.0);
    235   }
    236   return t;
    237 }
    238 
    239 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
    240 #include <sys/time.h>
    241 #include <sys/resource.h>
    242 
    243 /* VxWorks does not support getrusage() as far as we can determine */
    244 #if defined(_WRS_KERNEL) || defined(__RTP__)
    245 struct rusage {
    246   struct timeval ru_utime; /* user CPU time used */
    247   struct timeval ru_stime; /* system CPU time used */
    248 };
    249 #define getrusage(A,B) memset(B,0,sizeof(*B))
    250 #endif
    251 
    252 /* Saved resource information for the beginning of an operation */
    253 static struct rusage sBegin;  /* CPU time at start */
    254 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
    255 
    256 /*
    257 ** Begin timing an operation
    258 */
    259 static void beginTimer(void){
    260   if( enableTimer ){
    261     getrusage(RUSAGE_SELF, &sBegin);
    262     iBegin = timeOfDay();
    263   }
    264 }
    265 
    266 /* Return the difference of two time_structs in seconds */
    267 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
    268   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
    269          (double)(pEnd->tv_sec - pStart->tv_sec);
    270 }
    271 
    272 /*
    273 ** Print the timing results.
    274 */
    275 static void endTimer(void){
    276   if( enableTimer ){
    277     sqlite3_int64 iEnd = timeOfDay();
    278     struct rusage sEnd;
    279     getrusage(RUSAGE_SELF, &sEnd);
    280     printf("Run Time: real %.3f user %f sys %f\n",
    281        (iEnd - iBegin)*0.001,
    282        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
    283        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
    284   }
    285 }
    286 
    287 #define BEGIN_TIMER beginTimer()
    288 #define END_TIMER endTimer()
    289 #define HAS_TIMER 1
    290 
    291 #elif (defined(_WIN32) || defined(WIN32))
    292 
    293 /* Saved resource information for the beginning of an operation */
    294 static HANDLE hProcess;
    295 static FILETIME ftKernelBegin;
    296 static FILETIME ftUserBegin;
    297 static sqlite3_int64 ftWallBegin;
    298 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
    299                                     LPFILETIME, LPFILETIME);
    300 static GETPROCTIMES getProcessTimesAddr = NULL;
    301 
    302 /*
    303 ** Check to see if we have timer support.  Return 1 if necessary
    304 ** support found (or found previously).
    305 */
    306 static int hasTimer(void){
    307   if( getProcessTimesAddr ){
    308     return 1;
    309   } else {
    310     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
    311     ** versions. See if the version we are running on has it, and if it
    312     ** does, save off a pointer to it and the current process handle.
    313     */
    314     hProcess = GetCurrentProcess();
    315     if( hProcess ){
    316       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
    317       if( NULL != hinstLib ){
    318         getProcessTimesAddr =
    319             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
    320         if( NULL != getProcessTimesAddr ){
    321           return 1;
    322         }
    323         FreeLibrary(hinstLib);
    324       }
    325     }
    326   }
    327   return 0;
    328 }
    329 
    330 /*
    331 ** Begin timing an operation
    332 */
    333 static void beginTimer(void){
    334   if( enableTimer && getProcessTimesAddr ){
    335     FILETIME ftCreation, ftExit;
    336     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
    337                         &ftKernelBegin,&ftUserBegin);
    338     ftWallBegin = timeOfDay();
    339   }
    340 }
    341 
    342 /* Return the difference of two FILETIME structs in seconds */
    343 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
    344   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
    345   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
    346   return (double) ((i64End - i64Start) / 10000000.0);
    347 }
    348 
    349 /*
    350 ** Print the timing results.
    351 */
    352 static void endTimer(void){
    353   if( enableTimer && getProcessTimesAddr){
    354     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
    355     sqlite3_int64 ftWallEnd = timeOfDay();
    356     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
    357     printf("Run Time: real %.3f user %f sys %f\n",
    358        (ftWallEnd - ftWallBegin)*0.001,
    359        timeDiff(&ftUserBegin, &ftUserEnd),
    360        timeDiff(&ftKernelBegin, &ftKernelEnd));
    361   }
    362 }
    363 
    364 #define BEGIN_TIMER beginTimer()
    365 #define END_TIMER endTimer()
    366 #define HAS_TIMER hasTimer()
    367 
    368 #else
    369 #define BEGIN_TIMER
    370 #define END_TIMER
    371 #define HAS_TIMER 0
    372 #endif
    373 
    374 /*
    375 ** Used to prevent warnings about unused parameters
    376 */
    377 #define UNUSED_PARAMETER(x) (void)(x)
    378 
    379 /*
    380 ** Number of elements in an array
    381 */
    382 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
    383 
    384 /*
    385 ** If the following flag is set, then command execution stops
    386 ** at an error if we are not interactive.
    387 */
    388 static int bail_on_error = 0;
    389 
    390 /*
    391 ** Threat stdin as an interactive input if the following variable
    392 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
    393 */
    394 static int stdin_is_interactive = 1;
    395 
    396 /*
    397 ** On Windows systems we have to know if standard output is a console
    398 ** in order to translate UTF-8 into MBCS.  The following variable is
    399 ** true if translation is required.
    400 */
    401 static int stdout_is_console = 1;
    402 
    403 /*
    404 ** The following is the open SQLite database.  We make a pointer
    405 ** to this database a static variable so that it can be accessed
    406 ** by the SIGINT handler to interrupt database processing.
    407 */
    408 static sqlite3 *globalDb = 0;
    409 
    410 /*
    411 ** True if an interrupt (Control-C) has been received.
    412 */
    413 static volatile int seenInterrupt = 0;
    414 
    415 /*
    416 ** This is the name of our program. It is set in main(), used
    417 ** in a number of other places, mostly for error messages.
    418 */
    419 static char *Argv0;
    420 
    421 /*
    422 ** Prompt strings. Initialized in main. Settable with
    423 **   .prompt main continue
    424 */
    425 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
    426 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
    427 
    428 /*
    429 ** Render output like fprintf().  Except, if the output is going to the
    430 ** console and if this is running on a Windows machine, translate the
    431 ** output from UTF-8 into MBCS.
    432 */
    433 #if defined(_WIN32) || defined(WIN32)
    434 void utf8_printf(FILE *out, const char *zFormat, ...){
    435   va_list ap;
    436   va_start(ap, zFormat);
    437   if( stdout_is_console && (out==stdout || out==stderr) ){
    438     char *z1 = sqlite3_vmprintf(zFormat, ap);
    439     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
    440     sqlite3_free(z1);
    441     fputs(z2, out);
    442     sqlite3_free(z2);
    443   }else{
    444     vfprintf(out, zFormat, ap);
    445   }
    446   va_end(ap);
    447 }
    448 #elif !defined(utf8_printf)
    449 # define utf8_printf fprintf
    450 #endif
    451 
    452 /*
    453 ** Render output like fprintf().  This should not be used on anything that
    454 ** includes string formatting (e.g. "%s").
    455 */
    456 #if !defined(raw_printf)
    457 # define raw_printf fprintf
    458 #endif
    459 
    460 /*
    461 ** Write I/O traces to the following stream.
    462 */
    463 #ifdef SQLITE_ENABLE_IOTRACE
    464 static FILE *iotrace = 0;
    465 #endif
    466 
    467 /*
    468 ** This routine works like printf in that its first argument is a
    469 ** format string and subsequent arguments are values to be substituted
    470 ** in place of % fields.  The result of formatting this string
    471 ** is written to iotrace.
    472 */
    473 #ifdef SQLITE_ENABLE_IOTRACE
    474 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
    475   va_list ap;
    476   char *z;
    477   if( iotrace==0 ) return;
    478   va_start(ap, zFormat);
    479   z = sqlite3_vmprintf(zFormat, ap);
    480   va_end(ap);
    481   utf8_printf(iotrace, "%s", z);
    482   sqlite3_free(z);
    483 }
    484 #endif
    485 
    486 /*
    487 ** Output string zUtf to stream pOut as w characters.  If w is negative,
    488 ** then right-justify the text.  W is the width in UTF-8 characters, not
    489 ** in bytes.  This is different from the %*.*s specification in printf
    490 ** since with %*.*s the width is measured in bytes, not characters.
    491 */
    492 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
    493   int i;
    494   int n;
    495   int aw = w<0 ? -w : w;
    496   char zBuf[1000];
    497   if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
    498   for(i=n=0; zUtf[i]; i++){
    499     if( (zUtf[i]&0xc0)!=0x80 ){
    500       n++;
    501       if( n==aw ){
    502         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
    503         break;
    504       }
    505     }
    506   }
    507   if( n>=aw ){
    508     utf8_printf(pOut, "%.*s", i, zUtf);
    509   }else if( w<0 ){
    510     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
    511   }else{
    512     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
    513   }
    514 }
    515 
    516 
    517 /*
    518 ** Determines if a string is a number of not.
    519 */
    520 static int isNumber(const char *z, int *realnum){
    521   if( *z=='-' || *z=='+' ) z++;
    522   if( !IsDigit(*z) ){
    523     return 0;
    524   }
    525   z++;
    526   if( realnum ) *realnum = 0;
    527   while( IsDigit(*z) ){ z++; }
    528   if( *z=='.' ){
    529     z++;
    530     if( !IsDigit(*z) ) return 0;
    531     while( IsDigit(*z) ){ z++; }
    532     if( realnum ) *realnum = 1;
    533   }
    534   if( *z=='e' || *z=='E' ){
    535     z++;
    536     if( *z=='+' || *z=='-' ) z++;
    537     if( !IsDigit(*z) ) return 0;
    538     while( IsDigit(*z) ){ z++; }
    539     if( realnum ) *realnum = 1;
    540   }
    541   return *z==0;
    542 }
    543 
    544 /*
    545 ** Compute a string length that is limited to what can be stored in
    546 ** lower 30 bits of a 32-bit signed integer.
    547 */
    548 static int strlen30(const char *z){
    549   const char *z2 = z;
    550   while( *z2 ){ z2++; }
    551   return 0x3fffffff & (int)(z2 - z);
    552 }
    553 
    554 /*
    555 ** Return the length of a string in characters.  Multibyte UTF8 characters
    556 ** count as a single character.
    557 */
    558 static int strlenChar(const char *z){
    559   int n = 0;
    560   while( *z ){
    561     if( (0xc0&*(z++))!=0x80 ) n++;
    562   }
    563   return n;
    564 }
    565 
    566 /*
    567 ** This routine reads a line of text from FILE in, stores
    568 ** the text in memory obtained from malloc() and returns a pointer
    569 ** to the text.  NULL is returned at end of file, or if malloc()
    570 ** fails.
    571 **
    572 ** If zLine is not NULL then it is a malloced buffer returned from
    573 ** a previous call to this routine that may be reused.
    574 */
    575 static char *local_getline(char *zLine, FILE *in){
    576   int nLine = zLine==0 ? 0 : 100;
    577   int n = 0;
    578 
    579   while( 1 ){
    580     if( n+100>nLine ){
    581       nLine = nLine*2 + 100;
    582       zLine = realloc(zLine, nLine);
    583       if( zLine==0 ) return 0;
    584     }
    585     if( fgets(&zLine[n], nLine - n, in)==0 ){
    586       if( n==0 ){
    587         free(zLine);
    588         return 0;
    589       }
    590       zLine[n] = 0;
    591       break;
    592     }
    593     while( zLine[n] ) n++;
    594     if( n>0 && zLine[n-1]=='\n' ){
    595       n--;
    596       if( n>0 && zLine[n-1]=='\r' ) n--;
    597       zLine[n] = 0;
    598       break;
    599     }
    600   }
    601 #if defined(_WIN32) || defined(WIN32)
    602   /* For interactive input on Windows systems, translate the
    603   ** multi-byte characterset characters into UTF-8. */
    604   if( stdin_is_interactive && in==stdin ){
    605     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
    606     if( zTrans ){
    607       int nTrans = strlen30(zTrans)+1;
    608       if( nTrans>nLine ){
    609         zLine = realloc(zLine, nTrans);
    610         if( zLine==0 ){
    611           sqlite3_free(zTrans);
    612           return 0;
    613         }
    614       }
    615       memcpy(zLine, zTrans, nTrans);
    616       sqlite3_free(zTrans);
    617     }
    618   }
    619 #endif /* defined(_WIN32) || defined(WIN32) */
    620   return zLine;
    621 }
    622 
    623 /*
    624 ** Retrieve a single line of input text.
    625 **
    626 ** If in==0 then read from standard input and prompt before each line.
    627 ** If isContinuation is true, then a continuation prompt is appropriate.
    628 ** If isContinuation is zero, then the main prompt should be used.
    629 **
    630 ** If zPrior is not NULL then it is a buffer from a prior call to this
    631 ** routine that can be reused.
    632 **
    633 ** The result is stored in space obtained from malloc() and must either
    634 ** be freed by the caller or else passed back into this routine via the
    635 ** zPrior argument for reuse.
    636 */
    637 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
    638   char *zPrompt;
    639   char *zResult;
    640   if( in!=0 ){
    641     zResult = local_getline(zPrior, in);
    642   }else{
    643     zPrompt = isContinuation ? continuePrompt : mainPrompt;
    644 #if SHELL_USE_LOCAL_GETLINE
    645     printf("%s", zPrompt);
    646     fflush(stdout);
    647     zResult = local_getline(zPrior, stdin);
    648 #else
    649     free(zPrior);
    650     zResult = shell_readline(zPrompt);
    651     if( zResult && *zResult ) shell_add_history(zResult);
    652 #endif
    653   }
    654   return zResult;
    655 }
    656 
    657 
    658 /*
    659 ** Return the value of a hexadecimal digit.  Return -1 if the input
    660 ** is not a hex digit.
    661 */
    662 static int hexDigitValue(char c){
    663   if( c>='0' && c<='9' ) return c - '0';
    664   if( c>='a' && c<='f' ) return c - 'a' + 10;
    665   if( c>='A' && c<='F' ) return c - 'A' + 10;
    666   return -1;
    667 }
    668 
    669 /*
    670 ** Interpret zArg as an integer value, possibly with suffixes.
    671 */
    672 static sqlite3_int64 integerValue(const char *zArg){
    673   sqlite3_int64 v = 0;
    674   static const struct { char *zSuffix; int iMult; } aMult[] = {
    675     { "KiB", 1024 },
    676     { "MiB", 1024*1024 },
    677     { "GiB", 1024*1024*1024 },
    678     { "KB",  1000 },
    679     { "MB",  1000000 },
    680     { "GB",  1000000000 },
    681     { "K",   1000 },
    682     { "M",   1000000 },
    683     { "G",   1000000000 },
    684   };
    685   int i;
    686   int isNeg = 0;
    687   if( zArg[0]=='-' ){
    688     isNeg = 1;
    689     zArg++;
    690   }else if( zArg[0]=='+' ){
    691     zArg++;
    692   }
    693   if( zArg[0]=='0' && zArg[1]=='x' ){
    694     int x;
    695     zArg += 2;
    696     while( (x = hexDigitValue(zArg[0]))>=0 ){
    697       v = (v<<4) + x;
    698       zArg++;
    699     }
    700   }else{
    701     while( IsDigit(zArg[0]) ){
    702       v = v*10 + zArg[0] - '0';
    703       zArg++;
    704     }
    705   }
    706   for(i=0; i<ArraySize(aMult); i++){
    707     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
    708       v *= aMult[i].iMult;
    709       break;
    710     }
    711   }
    712   return isNeg? -v : v;
    713 }
    714 
    715 /*
    716 ** A variable length string to which one can append text.
    717 */
    718 typedef struct ShellText ShellText;
    719 struct ShellText {
    720   char *z;
    721   int n;
    722   int nAlloc;
    723 };
    724 
    725 /*
    726 ** Initialize and destroy a ShellText object
    727 */
    728 static void initText(ShellText *p){
    729   memset(p, 0, sizeof(*p));
    730 }
    731 static void freeText(ShellText *p){
    732   free(p->z);
    733   initText(p);
    734 }
    735 
    736 /* zIn is either a pointer to a NULL-terminated string in memory obtained
    737 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
    738 ** added to zIn, and the result returned in memory obtained from malloc().
    739 ** zIn, if it was not NULL, is freed.
    740 **
    741 ** If the third argument, quote, is not '\0', then it is used as a
    742 ** quote character for zAppend.
    743 */
    744 static void appendText(ShellText *p, char const *zAppend, char quote){
    745   int len;
    746   int i;
    747   int nAppend = strlen30(zAppend);
    748 
    749   len = nAppend+p->n+1;
    750   if( quote ){
    751     len += 2;
    752     for(i=0; i<nAppend; i++){
    753       if( zAppend[i]==quote ) len++;
    754     }
    755   }
    756 
    757   if( p->n+len>=p->nAlloc ){
    758     p->nAlloc = p->nAlloc*2 + len + 20;
    759     p->z = realloc(p->z, p->nAlloc);
    760     if( p->z==0 ){
    761       memset(p, 0, sizeof(*p));
    762       return;
    763     }
    764   }
    765 
    766   if( quote ){
    767     char *zCsr = p->z+p->n;
    768     *zCsr++ = quote;
    769     for(i=0; i<nAppend; i++){
    770       *zCsr++ = zAppend[i];
    771       if( zAppend[i]==quote ) *zCsr++ = quote;
    772     }
    773     *zCsr++ = quote;
    774     p->n = (int)(zCsr - p->z);
    775     *zCsr = '\0';
    776   }else{
    777     memcpy(p->z+p->n, zAppend, nAppend);
    778     p->n += nAppend;
    779     p->z[p->n] = '\0';
    780   }
    781 }
    782 
    783 /*
    784 ** Attempt to determine if identifier zName needs to be quoted, either
    785 ** because it contains non-alphanumeric characters, or because it is an
    786 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
    787 ** that quoting is required.
    788 **
    789 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
    790 */
    791 static char quoteChar(const char *zName){
    792   /* All SQLite keywords, in alphabetical order */
    793   static const char *azKeywords[] = {
    794     "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
    795     "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
    796     "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
    797     "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
    798     "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
    799     "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
    800     "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
    801     "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
    802     "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
    803     "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
    804     "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
    805     "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
    806     "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
    807     "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
    808     "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
    809     "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
    810     "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
    811     "WITH", "WITHOUT",
    812   };
    813   int i, lwr, upr, mid, c;
    814   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
    815   for(i=0; zName[i]; i++){
    816     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
    817   }
    818   lwr = 0;
    819   upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
    820   while( lwr<=upr ){
    821     mid = (lwr+upr)/2;
    822     c = sqlite3_stricmp(azKeywords[mid], zName);
    823     if( c==0 ) return '"';
    824     if( c<0 ){
    825       lwr = mid+1;
    826     }else{
    827       upr = mid-1;
    828     }
    829   }
    830   return 0;
    831 }
    832 
    833 /*
    834 ** Construct a fake object name and column list to describe the structure
    835 ** of the view, virtual table, or table valued function zSchema.zName.
    836 */
    837 static char *shellFakeSchema(
    838   sqlite3 *db,            /* The database connection containing the vtab */
    839   const char *zSchema,    /* Schema of the database holding the vtab */
    840   const char *zName       /* The name of the virtual table */
    841 ){
    842   sqlite3_stmt *pStmt = 0;
    843   char *zSql;
    844   ShellText s;
    845   char cQuote;
    846   char *zDiv = "(";
    847   int nRow = 0;
    848 
    849   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
    850                          zSchema ? zSchema : "main", zName);
    851   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
    852   sqlite3_free(zSql);
    853   initText(&s);
    854   if( zSchema ){
    855     cQuote = quoteChar(zSchema);
    856     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
    857     appendText(&s, zSchema, cQuote);
    858     appendText(&s, ".", 0);
    859   }
    860   cQuote = quoteChar(zName);
    861   appendText(&s, zName, cQuote);
    862   while( sqlite3_step(pStmt)==SQLITE_ROW ){
    863     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
    864     nRow++;
    865     appendText(&s, zDiv, 0);
    866     zDiv = ",";
    867     cQuote = quoteChar(zCol);
    868     appendText(&s, zCol, cQuote);
    869   }
    870   appendText(&s, ")", 0);
    871   sqlite3_finalize(pStmt);
    872   if( nRow==0 ){
    873     freeText(&s);
    874     s.z = 0;
    875   }
    876   return s.z;
    877 }
    878 
    879 /*
    880 ** SQL function:  shell_module_schema(X)
    881 **
    882 ** Return a fake schema for the table-valued function or eponymous virtual
    883 ** table X.
    884 */
    885 static void shellModuleSchema(
    886   sqlite3_context *pCtx,
    887   int nVal,
    888   sqlite3_value **apVal
    889 ){
    890   const char *zName = (const char*)sqlite3_value_text(apVal[0]);
    891   char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
    892   UNUSED_PARAMETER(nVal);
    893   if( zFake ){
    894     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
    895                         -1, sqlite3_free);
    896     free(zFake);
    897   }
    898 }
    899 
    900 /*
    901 ** SQL function:  shell_add_schema(S,X)
    902 **
    903 ** Add the schema name X to the CREATE statement in S and return the result.
    904 ** Examples:
    905 **
    906 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
    907 **
    908 ** Also works on
    909 **
    910 **    CREATE INDEX
    911 **    CREATE UNIQUE INDEX
    912 **    CREATE VIEW
    913 **    CREATE TRIGGER
    914 **    CREATE VIRTUAL TABLE
    915 **
    916 ** This UDF is used by the .schema command to insert the schema name of
    917 ** attached databases into the middle of the sqlite_master.sql field.
    918 */
    919 static void shellAddSchemaName(
    920   sqlite3_context *pCtx,
    921   int nVal,
    922   sqlite3_value **apVal
    923 ){
    924   static const char *aPrefix[] = {
    925      "TABLE",
    926      "INDEX",
    927      "UNIQUE INDEX",
    928      "VIEW",
    929      "TRIGGER",
    930      "VIRTUAL TABLE"
    931   };
    932   int i = 0;
    933   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
    934   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
    935   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
    936   sqlite3 *db = sqlite3_context_db_handle(pCtx);
    937   UNUSED_PARAMETER(nVal);
    938   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
    939     for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
    940       int n = strlen30(aPrefix[i]);
    941       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
    942         char *z = 0;
    943         char *zFake = 0;
    944         if( zSchema ){
    945           char cQuote = quoteChar(zSchema);
    946           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
    947             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
    948           }else{
    949             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
    950           }
    951         }
    952         if( zName
    953          && aPrefix[i][0]=='V'
    954          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
    955         ){
    956           if( z==0 ){
    957             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
    958           }else{
    959             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
    960           }
    961           free(zFake);
    962         }
    963         if( z ){
    964           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
    965           return;
    966         }
    967       }
    968     }
    969   }
    970   sqlite3_result_value(pCtx, apVal[0]);
    971 }
    972 
    973 /*
    974 ** The source code for several run-time loadable extensions is inserted
    975 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
    976 ** code, we need to override some macros to make the included program code
    977 ** work here in the middle of this regular program.
    978 */
    979 #define SQLITE_EXTENSION_INIT1
    980 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
    981 
    982 #if defined(_WIN32) && defined(_MSC_VER)
    983 /************************* Begin test_windirent.h ******************/
    984 /*
    985 ** 2015 November 30
    986 **
    987 ** The author disclaims copyright to this source code.  In place of
    988 ** a legal notice, here is a blessing:
    989 **
    990 **    May you do good and not evil.
    991 **    May you find forgiveness for yourself and forgive others.
    992 **    May you share freely, never taking more than you give.
    993 **
    994 *************************************************************************
    995 ** This file contains declarations for most of the opendir() family of
    996 ** POSIX functions on Win32 using the MSVCRT.
    997 */
    998 
    999 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
   1000 #define SQLITE_WINDIRENT_H
   1001 
   1002 /*
   1003 ** We need several data types from the Windows SDK header.
   1004 */
   1005 
   1006 #define WIN32_LEAN_AND_MEAN
   1007 #include "windows.h"
   1008 
   1009 /*
   1010 ** We need several support functions from the SQLite core.
   1011 */
   1012 
   1013 
   1014 /*
   1015 ** We need several things from the ANSI and MSVCRT headers.
   1016 */
   1017 
   1018 #include <stdio.h>
   1019 #include <stdlib.h>
   1020 #include <errno.h>
   1021 #include <io.h>
   1022 #include <limits.h>
   1023 #include <sys/types.h>
   1024 #include <sys/stat.h>
   1025 
   1026 /*
   1027 ** We may need several defines that should have been in "sys/stat.h".
   1028 */
   1029 
   1030 #ifndef S_ISREG
   1031 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
   1032 #endif
   1033 
   1034 #ifndef S_ISDIR
   1035 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
   1036 #endif
   1037 
   1038 #ifndef S_ISLNK
   1039 #define S_ISLNK(mode) (0)
   1040 #endif
   1041 
   1042 /*
   1043 ** We may need to provide the "mode_t" type.
   1044 */
   1045 
   1046 #ifndef MODE_T_DEFINED
   1047   #define MODE_T_DEFINED
   1048   typedef unsigned short mode_t;
   1049 #endif
   1050 
   1051 /*
   1052 ** We may need to provide the "ino_t" type.
   1053 */
   1054 
   1055 #ifndef INO_T_DEFINED
   1056   #define INO_T_DEFINED
   1057   typedef unsigned short ino_t;
   1058 #endif
   1059 
   1060 /*
   1061 ** We need to define "NAME_MAX" if it was not present in "limits.h".
   1062 */
   1063 
   1064 #ifndef NAME_MAX
   1065 #  ifdef FILENAME_MAX
   1066 #    define NAME_MAX (FILENAME_MAX)
   1067 #  else
   1068 #    define NAME_MAX (260)
   1069 #  endif
   1070 #endif
   1071 
   1072 /*
   1073 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
   1074 */
   1075 
   1076 #ifndef NULL_INTPTR_T
   1077 #  define NULL_INTPTR_T ((intptr_t)(0))
   1078 #endif
   1079 
   1080 #ifndef BAD_INTPTR_T
   1081 #  define BAD_INTPTR_T ((intptr_t)(-1))
   1082 #endif
   1083 
   1084 /*
   1085 ** We need to provide the necessary structures and related types.
   1086 */
   1087 
   1088 #ifndef DIRENT_DEFINED
   1089 #define DIRENT_DEFINED
   1090 typedef struct DIRENT DIRENT;
   1091 typedef DIRENT *LPDIRENT;
   1092 struct DIRENT {
   1093   ino_t d_ino;               /* Sequence number, do not use. */
   1094   unsigned d_attributes;     /* Win32 file attributes. */
   1095   char d_name[NAME_MAX + 1]; /* Name within the directory. */
   1096 };
   1097 #endif
   1098 
   1099 #ifndef DIR_DEFINED
   1100 #define DIR_DEFINED
   1101 typedef struct DIR DIR;
   1102 typedef DIR *LPDIR;
   1103 struct DIR {
   1104   intptr_t d_handle; /* Value returned by "_findfirst". */
   1105   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
   1106   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
   1107 };
   1108 #endif
   1109 
   1110 /*
   1111 ** Provide a macro, for use by the implementation, to determine if a
   1112 ** particular directory entry should be skipped over when searching for
   1113 ** the next directory entry that should be returned by the readdir() or
   1114 ** readdir_r() functions.
   1115 */
   1116 
   1117 #ifndef is_filtered
   1118 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
   1119 #endif
   1120 
   1121 /*
   1122 ** Provide the function prototype for the POSIX compatiable getenv()
   1123 ** function.  This function is not thread-safe.
   1124 */
   1125 
   1126 extern const char *windirent_getenv(const char *name);
   1127 
   1128 /*
   1129 ** Finally, we can provide the function prototypes for the opendir(),
   1130 ** readdir(), readdir_r(), and closedir() POSIX functions.
   1131 */
   1132 
   1133 extern LPDIR opendir(const char *dirname);
   1134 extern LPDIRENT readdir(LPDIR dirp);
   1135 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
   1136 extern INT closedir(LPDIR dirp);
   1137 
   1138 #endif /* defined(WIN32) && defined(_MSC_VER) */
   1139 
   1140 /************************* End test_windirent.h ********************/
   1141 /************************* Begin test_windirent.c ******************/
   1142 /*
   1143 ** 2015 November 30
   1144 **
   1145 ** The author disclaims copyright to this source code.  In place of
   1146 ** a legal notice, here is a blessing:
   1147 **
   1148 **    May you do good and not evil.
   1149 **    May you find forgiveness for yourself and forgive others.
   1150 **    May you share freely, never taking more than you give.
   1151 **
   1152 *************************************************************************
   1153 ** This file contains code to implement most of the opendir() family of
   1154 ** POSIX functions on Win32 using the MSVCRT.
   1155 */
   1156 
   1157 #if defined(_WIN32) && defined(_MSC_VER)
   1158 /* #include "test_windirent.h" */
   1159 
   1160 /*
   1161 ** Implementation of the POSIX getenv() function using the Win32 API.
   1162 ** This function is not thread-safe.
   1163 */
   1164 const char *windirent_getenv(
   1165   const char *name
   1166 ){
   1167   static char value[32768]; /* Maximum length, per MSDN */
   1168   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
   1169   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
   1170 
   1171   memset(value, 0, sizeof(value));
   1172   dwRet = GetEnvironmentVariableA(name, value, dwSize);
   1173   if( dwRet==0 || dwRet>dwSize ){
   1174     /*
   1175     ** The function call to GetEnvironmentVariableA() failed -OR-
   1176     ** the buffer is not large enough.  Either way, return NULL.
   1177     */
   1178     return 0;
   1179   }else{
   1180     /*
   1181     ** The function call to GetEnvironmentVariableA() succeeded
   1182     ** -AND- the buffer contains the entire value.
   1183     */
   1184     return value;
   1185   }
   1186 }
   1187 
   1188 /*
   1189 ** Implementation of the POSIX opendir() function using the MSVCRT.
   1190 */
   1191 LPDIR opendir(
   1192   const char *dirname
   1193 ){
   1194   struct _finddata_t data;
   1195   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
   1196   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
   1197 
   1198   if( dirp==NULL ) return NULL;
   1199   memset(dirp, 0, sizeof(DIR));
   1200 
   1201   /* TODO: Remove this if Unix-style root paths are not used. */
   1202   if( sqlite3_stricmp(dirname, "/")==0 ){
   1203     dirname = windirent_getenv("SystemDrive");
   1204   }
   1205 
   1206   memset(&data, 0, sizeof(struct _finddata_t));
   1207   _snprintf(data.name, namesize, "%s\\*", dirname);
   1208   dirp->d_handle = _findfirst(data.name, &data);
   1209 
   1210   if( dirp->d_handle==BAD_INTPTR_T ){
   1211     closedir(dirp);
   1212     return NULL;
   1213   }
   1214 
   1215   /* TODO: Remove this block to allow hidden and/or system files. */
   1216   if( is_filtered(data) ){
   1217 next:
   1218 
   1219     memset(&data, 0, sizeof(struct _finddata_t));
   1220     if( _findnext(dirp->d_handle, &data)==-1 ){
   1221       closedir(dirp);
   1222       return NULL;
   1223     }
   1224 
   1225     /* TODO: Remove this block to allow hidden and/or system files. */
   1226     if( is_filtered(data) ) goto next;
   1227   }
   1228 
   1229   dirp->d_first.d_attributes = data.attrib;
   1230   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
   1231   dirp->d_first.d_name[NAME_MAX] = '\0';
   1232 
   1233   return dirp;
   1234 }
   1235 
   1236 /*
   1237 ** Implementation of the POSIX readdir() function using the MSVCRT.
   1238 */
   1239 LPDIRENT readdir(
   1240   LPDIR dirp
   1241 ){
   1242   struct _finddata_t data;
   1243 
   1244   if( dirp==NULL ) return NULL;
   1245 
   1246   if( dirp->d_first.d_ino==0 ){
   1247     dirp->d_first.d_ino++;
   1248     dirp->d_next.d_ino++;
   1249 
   1250     return &dirp->d_first;
   1251   }
   1252 
   1253 next:
   1254 
   1255   memset(&data, 0, sizeof(struct _finddata_t));
   1256   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
   1257 
   1258   /* TODO: Remove this block to allow hidden and/or system files. */
   1259   if( is_filtered(data) ) goto next;
   1260 
   1261   dirp->d_next.d_ino++;
   1262   dirp->d_next.d_attributes = data.attrib;
   1263   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
   1264   dirp->d_next.d_name[NAME_MAX] = '\0';
   1265 
   1266   return &dirp->d_next;
   1267 }
   1268 
   1269 /*
   1270 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
   1271 */
   1272 INT readdir_r(
   1273   LPDIR dirp,
   1274   LPDIRENT entry,
   1275   LPDIRENT *result
   1276 ){
   1277   struct _finddata_t data;
   1278 
   1279   if( dirp==NULL ) return EBADF;
   1280 
   1281   if( dirp->d_first.d_ino==0 ){
   1282     dirp->d_first.d_ino++;
   1283     dirp->d_next.d_ino++;
   1284 
   1285     entry->d_ino = dirp->d_first.d_ino;
   1286     entry->d_attributes = dirp->d_first.d_attributes;
   1287     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
   1288     entry->d_name[NAME_MAX] = '\0';
   1289 
   1290     *result = entry;
   1291     return 0;
   1292   }
   1293 
   1294 next:
   1295 
   1296   memset(&data, 0, sizeof(struct _finddata_t));
   1297   if( _findnext(dirp->d_handle, &data)==-1 ){
   1298     *result = NULL;
   1299     return ENOENT;
   1300   }
   1301 
   1302   /* TODO: Remove this block to allow hidden and/or system files. */
   1303   if( is_filtered(data) ) goto next;
   1304 
   1305   entry->d_ino = (ino_t)-1; /* not available */
   1306   entry->d_attributes = data.attrib;
   1307   strncpy(entry->d_name, data.name, NAME_MAX);
   1308   entry->d_name[NAME_MAX] = '\0';
   1309 
   1310   *result = entry;
   1311   return 0;
   1312 }
   1313 
   1314 /*
   1315 ** Implementation of the POSIX closedir() function using the MSVCRT.
   1316 */
   1317 INT closedir(
   1318   LPDIR dirp
   1319 ){
   1320   INT result = 0;
   1321 
   1322   if( dirp==NULL ) return EINVAL;
   1323 
   1324   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
   1325     result = _findclose(dirp->d_handle);
   1326   }
   1327 
   1328   sqlite3_free(dirp);
   1329   return result;
   1330 }
   1331 
   1332 #endif /* defined(WIN32) && defined(_MSC_VER) */
   1333 
   1334 /************************* End test_windirent.c ********************/
   1335 #define dirent DIRENT
   1336 #endif
   1337 /************************* Begin ../ext/misc/shathree.c ******************/
   1338 /*
   1339 ** 2017-03-08
   1340 **
   1341 ** The author disclaims copyright to this source code.  In place of
   1342 ** a legal notice, here is a blessing:
   1343 **
   1344 **    May you do good and not evil.
   1345 **    May you find forgiveness for yourself and forgive others.
   1346 **    May you share freely, never taking more than you give.
   1347 **
   1348 ******************************************************************************
   1349 **
   1350 ** This SQLite extension implements a functions that compute SHA1 hashes.
   1351 ** Two SQL functions are implemented:
   1352 **
   1353 **     sha3(X,SIZE)
   1354 **     sha3_query(Y,SIZE)
   1355 **
   1356 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
   1357 ** X is NULL.
   1358 **
   1359 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
   1360 ** and returns a hash of their results.
   1361 **
   1362 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
   1363 ** is used.  If SIZE is included it must be one of the integers 224, 256,
   1364 ** 384, or 512, to determine SHA3 hash variant that is computed.
   1365 */
   1366 SQLITE_EXTENSION_INIT1
   1367 #include <assert.h>
   1368 #include <string.h>
   1369 #include <stdarg.h>
   1370 /* typedef sqlite3_uint64 u64; */
   1371 
   1372 /******************************************************************************
   1373 ** The Hash Engine
   1374 */
   1375 /*
   1376 ** Macros to determine whether the machine is big or little endian,
   1377 ** and whether or not that determination is run-time or compile-time.
   1378 **
   1379 ** For best performance, an attempt is made to guess at the byte-order
   1380 ** using C-preprocessor macros.  If that is unsuccessful, or if
   1381 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
   1382 ** at run-time.
   1383 */
   1384 #ifndef SHA3_BYTEORDER
   1385 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
   1386      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
   1387      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
   1388      defined(__arm__)
   1389 #   define SHA3_BYTEORDER    1234
   1390 # elif defined(sparc)    || defined(__ppc__)
   1391 #   define SHA3_BYTEORDER    4321
   1392 # else
   1393 #   define SHA3_BYTEORDER 0
   1394 # endif
   1395 #endif
   1396 
   1397 
   1398 /*
   1399 ** State structure for a SHA3 hash in progress
   1400 */
   1401 typedef struct SHA3Context SHA3Context;
   1402 struct SHA3Context {
   1403   union {
   1404     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
   1405     unsigned char x[1600];    /* ... or 1600 bytes */
   1406   } u;
   1407   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
   1408   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
   1409   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
   1410 };
   1411 
   1412 /*
   1413 ** A single step of the Keccak mixing function for a 1600-bit state
   1414 */
   1415 static void KeccakF1600Step(SHA3Context *p){
   1416   int i;
   1417   u64 b0, b1, b2, b3, b4;
   1418   u64 c0, c1, c2, c3, c4;
   1419   u64 d0, d1, d2, d3, d4;
   1420   static const u64 RC[] = {
   1421     0x0000000000000001ULL,  0x0000000000008082ULL,
   1422     0x800000000000808aULL,  0x8000000080008000ULL,
   1423     0x000000000000808bULL,  0x0000000080000001ULL,
   1424     0x8000000080008081ULL,  0x8000000000008009ULL,
   1425     0x000000000000008aULL,  0x0000000000000088ULL,
   1426     0x0000000080008009ULL,  0x000000008000000aULL,
   1427     0x000000008000808bULL,  0x800000000000008bULL,
   1428     0x8000000000008089ULL,  0x8000000000008003ULL,
   1429     0x8000000000008002ULL,  0x8000000000000080ULL,
   1430     0x000000000000800aULL,  0x800000008000000aULL,
   1431     0x8000000080008081ULL,  0x8000000000008080ULL,
   1432     0x0000000080000001ULL,  0x8000000080008008ULL
   1433   };
   1434 # define a00 (p->u.s[0])
   1435 # define a01 (p->u.s[1])
   1436 # define a02 (p->u.s[2])
   1437 # define a03 (p->u.s[3])
   1438 # define a04 (p->u.s[4])
   1439 # define a10 (p->u.s[5])
   1440 # define a11 (p->u.s[6])
   1441 # define a12 (p->u.s[7])
   1442 # define a13 (p->u.s[8])
   1443 # define a14 (p->u.s[9])
   1444 # define a20 (p->u.s[10])
   1445 # define a21 (p->u.s[11])
   1446 # define a22 (p->u.s[12])
   1447 # define a23 (p->u.s[13])
   1448 # define a24 (p->u.s[14])
   1449 # define a30 (p->u.s[15])
   1450 # define a31 (p->u.s[16])
   1451 # define a32 (p->u.s[17])
   1452 # define a33 (p->u.s[18])
   1453 # define a34 (p->u.s[19])
   1454 # define a40 (p->u.s[20])
   1455 # define a41 (p->u.s[21])
   1456 # define a42 (p->u.s[22])
   1457 # define a43 (p->u.s[23])
   1458 # define a44 (p->u.s[24])
   1459 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
   1460 
   1461   for(i=0; i<24; i+=4){
   1462     c0 = a00^a10^a20^a30^a40;
   1463     c1 = a01^a11^a21^a31^a41;
   1464     c2 = a02^a12^a22^a32^a42;
   1465     c3 = a03^a13^a23^a33^a43;
   1466     c4 = a04^a14^a24^a34^a44;
   1467     d0 = c4^ROL64(c1, 1);
   1468     d1 = c0^ROL64(c2, 1);
   1469     d2 = c1^ROL64(c3, 1);
   1470     d3 = c2^ROL64(c4, 1);
   1471     d4 = c3^ROL64(c0, 1);
   1472 
   1473     b0 = (a00^d0);
   1474     b1 = ROL64((a11^d1), 44);
   1475     b2 = ROL64((a22^d2), 43);
   1476     b3 = ROL64((a33^d3), 21);
   1477     b4 = ROL64((a44^d4), 14);
   1478     a00 =   b0 ^((~b1)&  b2 );
   1479     a00 ^= RC[i];
   1480     a11 =   b1 ^((~b2)&  b3 );
   1481     a22 =   b2 ^((~b3)&  b4 );
   1482     a33 =   b3 ^((~b4)&  b0 );
   1483     a44 =   b4 ^((~b0)&  b1 );
   1484 
   1485     b2 = ROL64((a20^d0), 3);
   1486     b3 = ROL64((a31^d1), 45);
   1487     b4 = ROL64((a42^d2), 61);
   1488     b0 = ROL64((a03^d3), 28);
   1489     b1 = ROL64((a14^d4), 20);
   1490     a20 =   b0 ^((~b1)&  b2 );
   1491     a31 =   b1 ^((~b2)&  b3 );
   1492     a42 =   b2 ^((~b3)&  b4 );
   1493     a03 =   b3 ^((~b4)&  b0 );
   1494     a14 =   b4 ^((~b0)&  b1 );
   1495 
   1496     b4 = ROL64((a40^d0), 18);
   1497     b0 = ROL64((a01^d1), 1);
   1498     b1 = ROL64((a12^d2), 6);
   1499     b2 = ROL64((a23^d3), 25);
   1500     b3 = ROL64((a34^d4), 8);
   1501     a40 =   b0 ^((~b1)&  b2 );
   1502     a01 =   b1 ^((~b2)&  b3 );
   1503     a12 =   b2 ^((~b3)&  b4 );
   1504     a23 =   b3 ^((~b4)&  b0 );
   1505     a34 =   b4 ^((~b0)&  b1 );
   1506 
   1507     b1 = ROL64((a10^d0), 36);
   1508     b2 = ROL64((a21^d1), 10);
   1509     b3 = ROL64((a32^d2), 15);
   1510     b4 = ROL64((a43^d3), 56);
   1511     b0 = ROL64((a04^d4), 27);
   1512     a10 =   b0 ^((~b1)&  b2 );
   1513     a21 =   b1 ^((~b2)&  b3 );
   1514     a32 =   b2 ^((~b3)&  b4 );
   1515     a43 =   b3 ^((~b4)&  b0 );
   1516     a04 =   b4 ^((~b0)&  b1 );
   1517 
   1518     b3 = ROL64((a30^d0), 41);
   1519     b4 = ROL64((a41^d1), 2);
   1520     b0 = ROL64((a02^d2), 62);
   1521     b1 = ROL64((a13^d3), 55);
   1522     b2 = ROL64((a24^d4), 39);
   1523     a30 =   b0 ^((~b1)&  b2 );
   1524     a41 =   b1 ^((~b2)&  b3 );
   1525     a02 =   b2 ^((~b3)&  b4 );
   1526     a13 =   b3 ^((~b4)&  b0 );
   1527     a24 =   b4 ^((~b0)&  b1 );
   1528 
   1529     c0 = a00^a20^a40^a10^a30;
   1530     c1 = a11^a31^a01^a21^a41;
   1531     c2 = a22^a42^a12^a32^a02;
   1532     c3 = a33^a03^a23^a43^a13;
   1533     c4 = a44^a14^a34^a04^a24;
   1534     d0 = c4^ROL64(c1, 1);
   1535     d1 = c0^ROL64(c2, 1);
   1536     d2 = c1^ROL64(c3, 1);
   1537     d3 = c2^ROL64(c4, 1);
   1538     d4 = c3^ROL64(c0, 1);
   1539 
   1540     b0 = (a00^d0);
   1541     b1 = ROL64((a31^d1), 44);
   1542     b2 = ROL64((a12^d2), 43);
   1543     b3 = ROL64((a43^d3), 21);
   1544     b4 = ROL64((a24^d4), 14);
   1545     a00 =   b0 ^((~b1)&  b2 );
   1546     a00 ^= RC[i+1];
   1547     a31 =   b1 ^((~b2)&  b3 );
   1548     a12 =   b2 ^((~b3)&  b4 );
   1549     a43 =   b3 ^((~b4)&  b0 );
   1550     a24 =   b4 ^((~b0)&  b1 );
   1551 
   1552     b2 = ROL64((a40^d0), 3);
   1553     b3 = ROL64((a21^d1), 45);
   1554     b4 = ROL64((a02^d2), 61);
   1555     b0 = ROL64((a33^d3), 28);
   1556     b1 = ROL64((a14^d4), 20);
   1557     a40 =   b0 ^((~b1)&  b2 );
   1558     a21 =   b1 ^((~b2)&  b3 );
   1559     a02 =   b2 ^((~b3)&  b4 );
   1560     a33 =   b3 ^((~b4)&  b0 );
   1561     a14 =   b4 ^((~b0)&  b1 );
   1562 
   1563     b4 = ROL64((a30^d0), 18);
   1564     b0 = ROL64((a11^d1), 1);
   1565     b1 = ROL64((a42^d2), 6);
   1566     b2 = ROL64((a23^d3), 25);
   1567     b3 = ROL64((a04^d4), 8);
   1568     a30 =   b0 ^((~b1)&  b2 );
   1569     a11 =   b1 ^((~b2)&  b3 );
   1570     a42 =   b2 ^((~b3)&  b4 );
   1571     a23 =   b3 ^((~b4)&  b0 );
   1572     a04 =   b4 ^((~b0)&  b1 );
   1573 
   1574     b1 = ROL64((a20^d0), 36);
   1575     b2 = ROL64((a01^d1), 10);
   1576     b3 = ROL64((a32^d2), 15);
   1577     b4 = ROL64((a13^d3), 56);
   1578     b0 = ROL64((a44^d4), 27);
   1579     a20 =   b0 ^((~b1)&  b2 );
   1580     a01 =   b1 ^((~b2)&  b3 );
   1581     a32 =   b2 ^((~b3)&  b4 );
   1582     a13 =   b3 ^((~b4)&  b0 );
   1583     a44 =   b4 ^((~b0)&  b1 );
   1584 
   1585     b3 = ROL64((a10^d0), 41);
   1586     b4 = ROL64((a41^d1), 2);
   1587     b0 = ROL64((a22^d2), 62);
   1588     b1 = ROL64((a03^d3), 55);
   1589     b2 = ROL64((a34^d4), 39);
   1590     a10 =   b0 ^((~b1)&  b2 );
   1591     a41 =   b1 ^((~b2)&  b3 );
   1592     a22 =   b2 ^((~b3)&  b4 );
   1593     a03 =   b3 ^((~b4)&  b0 );
   1594     a34 =   b4 ^((~b0)&  b1 );
   1595 
   1596     c0 = a00^a40^a30^a20^a10;
   1597     c1 = a31^a21^a11^a01^a41;
   1598     c2 = a12^a02^a42^a32^a22;
   1599     c3 = a43^a33^a23^a13^a03;
   1600     c4 = a24^a14^a04^a44^a34;
   1601     d0 = c4^ROL64(c1, 1);
   1602     d1 = c0^ROL64(c2, 1);
   1603     d2 = c1^ROL64(c3, 1);
   1604     d3 = c2^ROL64(c4, 1);
   1605     d4 = c3^ROL64(c0, 1);
   1606 
   1607     b0 = (a00^d0);
   1608     b1 = ROL64((a21^d1), 44);
   1609     b2 = ROL64((a42^d2), 43);
   1610     b3 = ROL64((a13^d3), 21);
   1611     b4 = ROL64((a34^d4), 14);
   1612     a00 =   b0 ^((~b1)&  b2 );
   1613     a00 ^= RC[i+2];
   1614     a21 =   b1 ^((~b2)&  b3 );
   1615     a42 =   b2 ^((~b3)&  b4 );
   1616     a13 =   b3 ^((~b4)&  b0 );
   1617     a34 =   b4 ^((~b0)&  b1 );
   1618 
   1619     b2 = ROL64((a30^d0), 3);
   1620     b3 = ROL64((a01^d1), 45);
   1621     b4 = ROL64((a22^d2), 61);
   1622     b0 = ROL64((a43^d3), 28);
   1623     b1 = ROL64((a14^d4), 20);
   1624     a30 =   b0 ^((~b1)&  b2 );
   1625     a01 =   b1 ^((~b2)&  b3 );
   1626     a22 =   b2 ^((~b3)&  b4 );
   1627     a43 =   b3 ^((~b4)&  b0 );
   1628     a14 =   b4 ^((~b0)&  b1 );
   1629 
   1630     b4 = ROL64((a10^d0), 18);
   1631     b0 = ROL64((a31^d1), 1);
   1632     b1 = ROL64((a02^d2), 6);
   1633     b2 = ROL64((a23^d3), 25);
   1634     b3 = ROL64((a44^d4), 8);
   1635     a10 =   b0 ^((~b1)&  b2 );
   1636     a31 =   b1 ^((~b2)&  b3 );
   1637     a02 =   b2 ^((~b3)&  b4 );
   1638     a23 =   b3 ^((~b4)&  b0 );
   1639     a44 =   b4 ^((~b0)&  b1 );
   1640 
   1641     b1 = ROL64((a40^d0), 36);
   1642     b2 = ROL64((a11^d1), 10);
   1643     b3 = ROL64((a32^d2), 15);
   1644     b4 = ROL64((a03^d3), 56);
   1645     b0 = ROL64((a24^d4), 27);
   1646     a40 =   b0 ^((~b1)&  b2 );
   1647     a11 =   b1 ^((~b2)&  b3 );
   1648     a32 =   b2 ^((~b3)&  b4 );
   1649     a03 =   b3 ^((~b4)&  b0 );
   1650     a24 =   b4 ^((~b0)&  b1 );
   1651 
   1652     b3 = ROL64((a20^d0), 41);
   1653     b4 = ROL64((a41^d1), 2);
   1654     b0 = ROL64((a12^d2), 62);
   1655     b1 = ROL64((a33^d3), 55);
   1656     b2 = ROL64((a04^d4), 39);
   1657     a20 =   b0 ^((~b1)&  b2 );
   1658     a41 =   b1 ^((~b2)&  b3 );
   1659     a12 =   b2 ^((~b3)&  b4 );
   1660     a33 =   b3 ^((~b4)&  b0 );
   1661     a04 =   b4 ^((~b0)&  b1 );
   1662 
   1663     c0 = a00^a30^a10^a40^a20;
   1664     c1 = a21^a01^a31^a11^a41;
   1665     c2 = a42^a22^a02^a32^a12;
   1666     c3 = a13^a43^a23^a03^a33;
   1667     c4 = a34^a14^a44^a24^a04;
   1668     d0 = c4^ROL64(c1, 1);
   1669     d1 = c0^ROL64(c2, 1);
   1670     d2 = c1^ROL64(c3, 1);
   1671     d3 = c2^ROL64(c4, 1);
   1672     d4 = c3^ROL64(c0, 1);
   1673 
   1674     b0 = (a00^d0);
   1675     b1 = ROL64((a01^d1), 44);
   1676     b2 = ROL64((a02^d2), 43);
   1677     b3 = ROL64((a03^d3), 21);
   1678     b4 = ROL64((a04^d4), 14);
   1679     a00 =   b0 ^((~b1)&  b2 );
   1680     a00 ^= RC[i+3];
   1681     a01 =   b1 ^((~b2)&  b3 );
   1682     a02 =   b2 ^((~b3)&  b4 );
   1683     a03 =   b3 ^((~b4)&  b0 );
   1684     a04 =   b4 ^((~b0)&  b1 );
   1685 
   1686     b2 = ROL64((a10^d0), 3);
   1687     b3 = ROL64((a11^d1), 45);
   1688     b4 = ROL64((a12^d2), 61);
   1689     b0 = ROL64((a13^d3), 28);
   1690     b1 = ROL64((a14^d4), 20);
   1691     a10 =   b0 ^((~b1)&  b2 );
   1692     a11 =   b1 ^((~b2)&  b3 );
   1693     a12 =   b2 ^((~b3)&  b4 );
   1694     a13 =   b3 ^((~b4)&  b0 );
   1695     a14 =   b4 ^((~b0)&  b1 );
   1696 
   1697     b4 = ROL64((a20^d0), 18);
   1698     b0 = ROL64((a21^d1), 1);
   1699     b1 = ROL64((a22^d2), 6);
   1700     b2 = ROL64((a23^d3), 25);
   1701     b3 = ROL64((a24^d4), 8);
   1702     a20 =   b0 ^((~b1)&  b2 );
   1703     a21 =   b1 ^((~b2)&  b3 );
   1704     a22 =   b2 ^((~b3)&  b4 );
   1705     a23 =   b3 ^((~b4)&  b0 );
   1706     a24 =   b4 ^((~b0)&  b1 );
   1707 
   1708     b1 = ROL64((a30^d0), 36);
   1709     b2 = ROL64((a31^d1), 10);
   1710     b3 = ROL64((a32^d2), 15);
   1711     b4 = ROL64((a33^d3), 56);
   1712     b0 = ROL64((a34^d4), 27);
   1713     a30 =   b0 ^((~b1)&  b2 );
   1714     a31 =   b1 ^((~b2)&  b3 );
   1715     a32 =   b2 ^((~b3)&  b4 );
   1716     a33 =   b3 ^((~b4)&  b0 );
   1717     a34 =   b4 ^((~b0)&  b1 );
   1718 
   1719     b3 = ROL64((a40^d0), 41);
   1720     b4 = ROL64((a41^d1), 2);
   1721     b0 = ROL64((a42^d2), 62);
   1722     b1 = ROL64((a43^d3), 55);
   1723     b2 = ROL64((a44^d4), 39);
   1724     a40 =   b0 ^((~b1)&  b2 );
   1725     a41 =   b1 ^((~b2)&  b3 );
   1726     a42 =   b2 ^((~b3)&  b4 );
   1727     a43 =   b3 ^((~b4)&  b0 );
   1728     a44 =   b4 ^((~b0)&  b1 );
   1729   }
   1730 }
   1731 
   1732 /*
   1733 ** Initialize a new hash.  iSize determines the size of the hash
   1734 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
   1735 ** can be zero to use the default hash size of 256 bits.
   1736 */
   1737 static void SHA3Init(SHA3Context *p, int iSize){
   1738   memset(p, 0, sizeof(*p));
   1739   if( iSize>=128 && iSize<=512 ){
   1740     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
   1741   }else{
   1742     p->nRate = (1600 - 2*256)/8;
   1743   }
   1744 #if SHA3_BYTEORDER==1234
   1745   /* Known to be little-endian at compile-time. No-op */
   1746 #elif SHA3_BYTEORDER==4321
   1747   p->ixMask = 7;  /* Big-endian */
   1748 #else
   1749   {
   1750     static unsigned int one = 1;
   1751     if( 1==*(unsigned char*)&one ){
   1752       /* Little endian.  No byte swapping. */
   1753       p->ixMask = 0;
   1754     }else{
   1755       /* Big endian.  Byte swap. */
   1756       p->ixMask = 7;
   1757     }
   1758   }
   1759 #endif
   1760 }
   1761 
   1762 /*
   1763 ** Make consecutive calls to the SHA3Update function to add new content
   1764 ** to the hash
   1765 */
   1766 static void SHA3Update(
   1767   SHA3Context *p,
   1768   const unsigned char *aData,
   1769   unsigned int nData
   1770 ){
   1771   unsigned int i = 0;
   1772 #if SHA3_BYTEORDER==1234
   1773   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
   1774     for(; i+7<nData; i+=8){
   1775       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
   1776       p->nLoaded += 8;
   1777       if( p->nLoaded>=p->nRate ){
   1778         KeccakF1600Step(p);
   1779         p->nLoaded = 0;
   1780       }
   1781     }
   1782   }
   1783 #endif
   1784   for(; i<nData; i++){
   1785 #if SHA3_BYTEORDER==1234
   1786     p->u.x[p->nLoaded] ^= aData[i];
   1787 #elif SHA3_BYTEORDER==4321
   1788     p->u.x[p->nLoaded^0x07] ^= aData[i];
   1789 #else
   1790     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
   1791 #endif
   1792     p->nLoaded++;
   1793     if( p->nLoaded==p->nRate ){
   1794       KeccakF1600Step(p);
   1795       p->nLoaded = 0;
   1796     }
   1797   }
   1798 }
   1799 
   1800 /*
   1801 ** After all content has been added, invoke SHA3Final() to compute
   1802 ** the final hash.  The function returns a pointer to the binary
   1803 ** hash value.
   1804 */
   1805 static unsigned char *SHA3Final(SHA3Context *p){
   1806   unsigned int i;
   1807   if( p->nLoaded==p->nRate-1 ){
   1808     const unsigned char c1 = 0x86;
   1809     SHA3Update(p, &c1, 1);
   1810   }else{
   1811     const unsigned char c2 = 0x06;
   1812     const unsigned char c3 = 0x80;
   1813     SHA3Update(p, &c2, 1);
   1814     p->nLoaded = p->nRate - 1;
   1815     SHA3Update(p, &c3, 1);
   1816   }
   1817   for(i=0; i<p->nRate; i++){
   1818     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
   1819   }
   1820   return &p->u.x[p->nRate];
   1821 }
   1822 /* End of the hashing logic
   1823 *****************************************************************************/
   1824 
   1825 /*
   1826 ** Implementation of the sha3(X,SIZE) function.
   1827 **
   1828 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
   1829 ** size is 256.  If X is a BLOB, it is hashed as is.
   1830 ** For all other non-NULL types of input, X is converted into a UTF-8 string
   1831 ** and the string is hashed without the trailing 0x00 terminator.  The hash
   1832 ** of a NULL value is NULL.
   1833 */
   1834 static void sha3Func(
   1835   sqlite3_context *context,
   1836   int argc,
   1837   sqlite3_value **argv
   1838 ){
   1839   SHA3Context cx;
   1840   int eType = sqlite3_value_type(argv[0]);
   1841   int nByte = sqlite3_value_bytes(argv[0]);
   1842   int iSize;
   1843   if( argc==1 ){
   1844     iSize = 256;
   1845   }else{
   1846     iSize = sqlite3_value_int(argv[1]);
   1847     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
   1848       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
   1849                                     "384 512", -1);
   1850       return;
   1851     }
   1852   }
   1853   if( eType==SQLITE_NULL ) return;
   1854   SHA3Init(&cx, iSize);
   1855   if( eType==SQLITE_BLOB ){
   1856     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
   1857   }else{
   1858     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
   1859   }
   1860   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
   1861 }
   1862 
   1863 /* Compute a string using sqlite3_vsnprintf() with a maximum length
   1864 ** of 50 bytes and add it to the hash.
   1865 */
   1866 static void hash_step_vformat(
   1867   SHA3Context *p,                 /* Add content to this context */
   1868   const char *zFormat,
   1869   ...
   1870 ){
   1871   va_list ap;
   1872   int n;
   1873   char zBuf[50];
   1874   va_start(ap, zFormat);
   1875   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
   1876   va_end(ap);
   1877   n = (int)strlen(zBuf);
   1878   SHA3Update(p, (unsigned char*)zBuf, n);
   1879 }
   1880 
   1881 /*
   1882 ** Implementation of the sha3_query(SQL,SIZE) function.
   1883 **
   1884 ** This function compiles and runs the SQL statement(s) given in the
   1885 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
   1886 ** size is 256.
   1887 **
   1888 ** The format of the byte stream that is hashed is summarized as follows:
   1889 **
   1890 **       S<n>:<sql>
   1891 **       R
   1892 **       N
   1893 **       I<int>
   1894 **       F<ieee-float>
   1895 **       B<size>:<bytes>
   1896 **       T<size>:<text>
   1897 **
   1898 ** <sql> is the original SQL text for each statement run and <n> is
   1899 ** the size of that text.  The SQL text is UTF-8.  A single R character
   1900 ** occurs before the start of each row.  N means a NULL value.
   1901 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
   1902 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
   1903 ** B means blobs of <size> bytes.  T means text rendered as <size>
   1904 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
   1905 ** text integers.
   1906 **
   1907 ** For each SQL statement in the X input, there is one S segment.  Each
   1908 ** S segment is followed by zero or more R segments, one for each row in the
   1909 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
   1910 ** one for each column in the result set.  Segments are concatentated directly
   1911 ** with no delimiters of any kind.
   1912 */
   1913 static void sha3QueryFunc(
   1914   sqlite3_context *context,
   1915   int argc,
   1916   sqlite3_value **argv
   1917 ){
   1918   sqlite3 *db = sqlite3_context_db_handle(context);
   1919   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
   1920   sqlite3_stmt *pStmt = 0;
   1921   int nCol;                   /* Number of columns in the result set */
   1922   int i;                      /* Loop counter */
   1923   int rc;
   1924   int n;
   1925   const char *z;
   1926   SHA3Context cx;
   1927   int iSize;
   1928 
   1929   if( argc==1 ){
   1930     iSize = 256;
   1931   }else{
   1932     iSize = sqlite3_value_int(argv[1]);
   1933     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
   1934       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
   1935                                     "384 512", -1);
   1936       return;
   1937     }
   1938   }
   1939   if( zSql==0 ) return;
   1940   SHA3Init(&cx, iSize);
   1941   while( zSql[0] ){
   1942     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
   1943     if( rc ){
   1944       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
   1945                                    zSql, sqlite3_errmsg(db));
   1946       sqlite3_finalize(pStmt);
   1947       sqlite3_result_error(context, zMsg, -1);
   1948       sqlite3_free(zMsg);
   1949       return;
   1950     }
   1951     if( !sqlite3_stmt_readonly(pStmt) ){
   1952       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
   1953       sqlite3_finalize(pStmt);
   1954       sqlite3_result_error(context, zMsg, -1);
   1955       sqlite3_free(zMsg);
   1956       return;
   1957     }
   1958     nCol = sqlite3_column_count(pStmt);
   1959     z = sqlite3_sql(pStmt);
   1960     n = (int)strlen(z);
   1961     hash_step_vformat(&cx,"S%d:",n);
   1962     SHA3Update(&cx,(unsigned char*)z,n);
   1963 
   1964     /* Compute a hash over the result of the query */
   1965     while( SQLITE_ROW==sqlite3_step(pStmt) ){
   1966       SHA3Update(&cx,(const unsigned char*)"R",1);
   1967       for(i=0; i<nCol; i++){
   1968         switch( sqlite3_column_type(pStmt,i) ){
   1969           case SQLITE_NULL: {
   1970             SHA3Update(&cx, (const unsigned char*)"N",1);
   1971             break;
   1972           }
   1973           case SQLITE_INTEGER: {
   1974             sqlite3_uint64 u;
   1975             int j;
   1976             unsigned char x[9];
   1977             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
   1978             memcpy(&u, &v, 8);
   1979             for(j=8; j>=1; j--){
   1980               x[j] = u & 0xff;
   1981               u >>= 8;
   1982             }
   1983             x[0] = 'I';
   1984             SHA3Update(&cx, x, 9);
   1985             break;
   1986           }
   1987           case SQLITE_FLOAT: {
   1988             sqlite3_uint64 u;
   1989             int j;
   1990             unsigned char x[9];
   1991             double r = sqlite3_column_double(pStmt,i);
   1992             memcpy(&u, &r, 8);
   1993             for(j=8; j>=1; j--){
   1994               x[j] = u & 0xff;
   1995               u >>= 8;
   1996             }
   1997             x[0] = 'F';
   1998             SHA3Update(&cx,x,9);
   1999             break;
   2000           }
   2001           case SQLITE_TEXT: {
   2002             int n2 = sqlite3_column_bytes(pStmt, i);
   2003             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
   2004             hash_step_vformat(&cx,"T%d:",n2);
   2005             SHA3Update(&cx, z2, n2);
   2006             break;
   2007           }
   2008           case SQLITE_BLOB: {
   2009             int n2 = sqlite3_column_bytes(pStmt, i);
   2010             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
   2011             hash_step_vformat(&cx,"B%d:",n2);
   2012             SHA3Update(&cx, z2, n2);
   2013             break;
   2014           }
   2015         }
   2016       }
   2017     }
   2018     sqlite3_finalize(pStmt);
   2019   }
   2020   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
   2021 }
   2022 
   2023 
   2024 #ifdef _WIN32
   2025 
   2026 #endif
   2027 int sqlite3_shathree_init(
   2028   sqlite3 *db,
   2029   char **pzErrMsg,
   2030   const sqlite3_api_routines *pApi
   2031 ){
   2032   int rc = SQLITE_OK;
   2033   SQLITE_EXTENSION_INIT2(pApi);
   2034   (void)pzErrMsg;  /* Unused parameter */
   2035   rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
   2036                                sha3Func, 0, 0);
   2037   if( rc==SQLITE_OK ){
   2038     rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
   2039                                  sha3Func, 0, 0);
   2040   }
   2041   if( rc==SQLITE_OK ){
   2042     rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
   2043                                  sha3QueryFunc, 0, 0);
   2044   }
   2045   if( rc==SQLITE_OK ){
   2046     rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
   2047                                  sha3QueryFunc, 0, 0);
   2048   }
   2049   return rc;
   2050 }
   2051 
   2052 /************************* End ../ext/misc/shathree.c ********************/
   2053 /************************* Begin ../ext/misc/fileio.c ******************/
   2054 /*
   2055 ** 2014-06-13
   2056 **
   2057 ** The author disclaims copyright to this source code.  In place of
   2058 ** a legal notice, here is a blessing:
   2059 **
   2060 **    May you do good and not evil.
   2061 **    May you find forgiveness for yourself and forgive others.
   2062 **    May you share freely, never taking more than you give.
   2063 **
   2064 ******************************************************************************
   2065 **
   2066 ** This SQLite extension implements SQL functions readfile() and
   2067 ** writefile(), and eponymous virtual type "fsdir".
   2068 **
   2069 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
   2070 **
   2071 **   If neither of the optional arguments is present, then this UDF
   2072 **   function writes blob DATA to file FILE. If successful, the number
   2073 **   of bytes written is returned. If an error occurs, NULL is returned.
   2074 **
   2075 **   If the first option argument - MODE - is present, then it must
   2076 **   be passed an integer value that corresponds to a POSIX mode
   2077 **   value (file type + permissions, as returned in the stat.st_mode
   2078 **   field by the stat() system call). Three types of files may
   2079 **   be written/created:
   2080 **
   2081 **     regular files:  (mode & 0170000)==0100000
   2082 **     symbolic links: (mode & 0170000)==0120000
   2083 **     directories:    (mode & 0170000)==0040000
   2084 **
   2085 **   For a directory, the DATA is ignored. For a symbolic link, it is
   2086 **   interpreted as text and used as the target of the link. For a
   2087 **   regular file, it is interpreted as a blob and written into the
   2088 **   named file. Regardless of the type of file, its permissions are
   2089 **   set to (mode & 0777) before returning.
   2090 **
   2091 **   If the optional MTIME argument is present, then it is interpreted
   2092 **   as an integer - the number of seconds since the unix epoch. The
   2093 **   modification-time of the target file is set to this value before
   2094 **   returning.
   2095 **
   2096 **   If three or more arguments are passed to this function and an
   2097 **   error is encountered, an exception is raised.
   2098 **
   2099 ** READFILE(FILE):
   2100 **
   2101 **   Read and return the contents of file FILE (type blob) from disk.
   2102 **
   2103 ** FSDIR:
   2104 **
   2105 **   Used as follows:
   2106 **
   2107 **     SELECT * FROM fsdir($path [, $dir]);
   2108 **
   2109 **   Parameter $path is an absolute or relative pathname. If the file that it
   2110 **   refers to does not exist, it is an error. If the path refers to a regular
   2111 **   file or symbolic link, it returns a single row. Or, if the path refers
   2112 **   to a directory, it returns one row for the directory, and one row for each
   2113 **   file within the hierarchy rooted at $path.
   2114 **
   2115 **   Each row has the following columns:
   2116 **
   2117 **     name:  Path to file or directory (text value).
   2118 **     mode:  Value of stat.st_mode for directory entry (an integer).
   2119 **     mtime: Value of stat.st_mtime for directory entry (an integer).
   2120 **     data:  For a regular file, a blob containing the file data. For a
   2121 **            symlink, a text value containing the text of the link. For a
   2122 **            directory, NULL.
   2123 **
   2124 **   If a non-NULL value is specified for the optional $dir parameter and
   2125 **   $path is a relative path, then $path is interpreted relative to $dir.
   2126 **   And the paths returned in the "name" column of the table are also
   2127 **   relative to directory $dir.
   2128 */
   2129 SQLITE_EXTENSION_INIT1
   2130 #include <stdio.h>
   2131 #include <string.h>
   2132 #include <assert.h>
   2133 
   2134 #include <sys/types.h>
   2135 #include <sys/stat.h>
   2136 #include <fcntl.h>
   2137 #if !defined(_WIN32) && !defined(WIN32)
   2138 #  include <unistd.h>
   2139 #  include <dirent.h>
   2140 #  include <utime.h>
   2141 #  include <sys/time.h>
   2142 #else
   2143 #  include "windows.h"
   2144 #  include <io.h>
   2145 #  include <direct.h>
   2146 /* #  include "test_windirent.h" */
   2147 #  define dirent DIRENT
   2148 #  ifndef stat
   2149 #    define stat _stat
   2150 #  endif
   2151 #  define mkdir(path,mode) _mkdir(path)
   2152 #  define lstat(path,buf) stat(path,buf)
   2153 #endif
   2154 #include <time.h>
   2155 #include <errno.h>
   2156 
   2157 
   2158 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
   2159 
   2160 /*
   2161 ** Set the result stored by context ctx to a blob containing the
   2162 ** contents of file zName.
   2163 */
   2164 static void readFileContents(sqlite3_context *ctx, const char *zName){
   2165   FILE *in;
   2166   long nIn;
   2167   void *pBuf;
   2168 
   2169   in = fopen(zName, "rb");
   2170   if( in==0 ) return;
   2171   fseek(in, 0, SEEK_END);
   2172   nIn = ftell(in);
   2173   rewind(in);
   2174   pBuf = sqlite3_malloc( nIn );
   2175   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
   2176     sqlite3_result_blob(ctx, pBuf, nIn, sqlite3_free);
   2177   }else{
   2178     sqlite3_free(pBuf);
   2179   }
   2180   fclose(in);
   2181 }
   2182 
   2183 /*
   2184 ** Implementation of the "readfile(X)" SQL function.  The entire content
   2185 ** of the file named X is read and returned as a BLOB.  NULL is returned
   2186 ** if the file does not exist or is unreadable.
   2187 */
   2188 static void readfileFunc(
   2189   sqlite3_context *context,
   2190   int argc,
   2191   sqlite3_value **argv
   2192 ){
   2193   const char *zName;
   2194   (void)(argc);  /* Unused parameter */
   2195   zName = (const char*)sqlite3_value_text(argv[0]);
   2196   if( zName==0 ) return;
   2197   readFileContents(context, zName);
   2198 }
   2199 
   2200 /*
   2201 ** Set the error message contained in context ctx to the results of
   2202 ** vprintf(zFmt, ...).
   2203 */
   2204 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
   2205   char *zMsg = 0;
   2206   va_list ap;
   2207   va_start(ap, zFmt);
   2208   zMsg = sqlite3_vmprintf(zFmt, ap);
   2209   sqlite3_result_error(ctx, zMsg, -1);
   2210   sqlite3_free(zMsg);
   2211   va_end(ap);
   2212 }
   2213 
   2214 /*
   2215 ** Argument zFile is the name of a file that will be created and/or written
   2216 ** by SQL function writefile(). This function ensures that the directory
   2217 ** zFile will be written to exists, creating it if required. The permissions
   2218 ** for any path components created by this function are set to (mode&0777).
   2219 **
   2220 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
   2221 ** SQLITE_OK is returned if the directory is successfully created, or
   2222 ** SQLITE_ERROR otherwise.
   2223 */
   2224 static int makeDirectory(
   2225   const char *zFile,
   2226   mode_t mode
   2227 ){
   2228   char *zCopy = sqlite3_mprintf("%s", zFile);
   2229   int rc = SQLITE_OK;
   2230 
   2231   if( zCopy==0 ){
   2232     rc = SQLITE_NOMEM;
   2233   }else{
   2234     int nCopy = (int)strlen(zCopy);
   2235     int i = 1;
   2236 
   2237     while( rc==SQLITE_OK ){
   2238       struct stat sStat;
   2239       int rc2;
   2240 
   2241       for(; zCopy[i]!='/' && i<nCopy; i++);
   2242       if( i==nCopy ) break;
   2243       zCopy[i] = '\0';
   2244 
   2245       rc2 = stat(zCopy, &sStat);
   2246       if( rc2!=0 ){
   2247         if( mkdir(zCopy, mode & 0777) ) rc = SQLITE_ERROR;
   2248       }else{
   2249         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
   2250       }
   2251       zCopy[i] = '/';
   2252       i++;
   2253     }
   2254 
   2255     sqlite3_free(zCopy);
   2256   }
   2257 
   2258   return rc;
   2259 }
   2260 
   2261 /*
   2262 ** This function does the work for the writefile() UDF. Refer to
   2263 ** header comments at the top of this file for details.
   2264 */
   2265 static int writeFile(
   2266   sqlite3_context *pCtx,          /* Context to return bytes written in */
   2267   const char *zFile,              /* File to write */
   2268   sqlite3_value *pData,           /* Data to write */
   2269   mode_t mode,                    /* MODE parameter passed to writefile() */
   2270   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
   2271 ){
   2272 #if !defined(_WIN32) && !defined(WIN32)
   2273   if( S_ISLNK(mode) ){
   2274     const char *zTo = (const char*)sqlite3_value_text(pData);
   2275     if( symlink(zTo, zFile)<0 ) return 1;
   2276   }else
   2277 #endif
   2278   {
   2279     if( S_ISDIR(mode) ){
   2280       if( mkdir(zFile, mode) ){
   2281         /* The mkdir() call to create the directory failed. This might not
   2282         ** be an error though - if there is already a directory at the same
   2283         ** path and either the permissions already match or can be changed
   2284         ** to do so using chmod(), it is not an error.  */
   2285         struct stat sStat;
   2286         if( errno!=EEXIST
   2287          || 0!=stat(zFile, &sStat)
   2288          || !S_ISDIR(sStat.st_mode)
   2289          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
   2290         ){
   2291           return 1;
   2292         }
   2293       }
   2294     }else{
   2295       sqlite3_int64 nWrite = 0;
   2296       const char *z;
   2297       int rc = 0;
   2298       FILE *out = fopen(zFile, "wb");
   2299       if( out==0 ) return 1;
   2300       z = (const char*)sqlite3_value_blob(pData);
   2301       if( z ){
   2302         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
   2303         nWrite = sqlite3_value_bytes(pData);
   2304         if( nWrite!=n ){
   2305           rc = 1;
   2306         }
   2307       }
   2308       fclose(out);
   2309       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
   2310         rc = 1;
   2311       }
   2312       if( rc ) return 2;
   2313       sqlite3_result_int64(pCtx, nWrite);
   2314     }
   2315   }
   2316 
   2317   if( mtime>=0 ){
   2318 #if defined(_WIN32)
   2319     /* Windows */
   2320     FILETIME lastAccess;
   2321     FILETIME lastWrite;
   2322     SYSTEMTIME currentTime;
   2323     LONGLONG intervals;
   2324     HANDLE hFile;
   2325     GetSystemTime(&currentTime);
   2326     SystemTimeToFileTime(&currentTime, &lastAccess);
   2327     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
   2328     lastWrite.dwLowDateTime = (DWORD)intervals;
   2329     lastWrite.dwHighDateTime = intervals >> 32;
   2330     hFile = CreateFile(
   2331       zFile, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
   2332       FILE_FLAG_BACKUP_SEMANTICS, NULL
   2333     );
   2334     if( hFile!=INVALID_HANDLE_VALUE ){
   2335       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
   2336       CloseHandle(hFile);
   2337       return !bResult;
   2338     }else{
   2339       return 1;
   2340     }
   2341 #elif defined(AT_FDCWD) && 0 /* utimensat() is not univerally available */
   2342     /* Recent unix */
   2343     struct timespec times[2];
   2344     times[0].tv_nsec = times[1].tv_nsec = 0;
   2345     times[0].tv_sec = time(0);
   2346     times[1].tv_sec = mtime;
   2347     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
   2348       return 1;
   2349     }
   2350 #else
   2351     /* Legacy unix */
   2352     struct timeval times[2];
   2353     times[0].tv_usec = times[1].tv_usec = 0;
   2354     times[0].tv_sec = time(0);
   2355     times[1].tv_sec = mtime;
   2356     if( utimes(zFile, times) ){
   2357       return 1;
   2358     }
   2359 #endif
   2360   }
   2361 
   2362   return 0;
   2363 }
   2364 
   2365 /*
   2366 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
   2367 ** Refer to header comments at the top of this file for details.
   2368 */
   2369 static void writefileFunc(
   2370   sqlite3_context *context,
   2371   int argc,
   2372   sqlite3_value **argv
   2373 ){
   2374   const char *zFile;
   2375   mode_t mode = 0;
   2376   int res;
   2377   sqlite3_int64 mtime = -1;
   2378 
   2379   if( argc<2 || argc>4 ){
   2380     sqlite3_result_error(context,
   2381         "wrong number of arguments to function writefile()", -1
   2382     );
   2383     return;
   2384   }
   2385 
   2386   zFile = (const char*)sqlite3_value_text(argv[0]);
   2387   if( zFile==0 ) return;
   2388   if( argc>=3 ){
   2389     mode = (mode_t)sqlite3_value_int(argv[2]);
   2390   }
   2391   if( argc==4 ){
   2392     mtime = sqlite3_value_int64(argv[3]);
   2393   }
   2394 
   2395   res = writeFile(context, zFile, argv[1], mode, mtime);
   2396   if( res==1 && errno==ENOENT ){
   2397     if( makeDirectory(zFile, mode)==SQLITE_OK ){
   2398       res = writeFile(context, zFile, argv[1], mode, mtime);
   2399     }
   2400   }
   2401 
   2402   if( argc>2 && res!=0 ){
   2403     if( S_ISLNK(mode) ){
   2404       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
   2405     }else if( S_ISDIR(mode) ){
   2406       ctxErrorMsg(context, "failed to create directory: %s", zFile);
   2407     }else{
   2408       ctxErrorMsg(context, "failed to write file: %s", zFile);
   2409     }
   2410   }
   2411 }
   2412 
   2413 /*
   2414 ** SQL function:   lsmode(MODE)
   2415 **
   2416 ** Given a numberic st_mode from stat(), convert it into a human-readable
   2417 ** text string in the style of "ls -l".
   2418 */
   2419 static void lsModeFunc(
   2420   sqlite3_context *context,
   2421   int argc,
   2422   sqlite3_value **argv
   2423 ){
   2424   int i;
   2425   int iMode = sqlite3_value_int(argv[0]);
   2426   char z[16];
   2427   (void)argc;
   2428   if( S_ISLNK(iMode) ){
   2429     z[0] = 'l';
   2430   }else if( S_ISREG(iMode) ){
   2431     z[0] = '-';
   2432   }else if( S_ISDIR(iMode) ){
   2433     z[0] = 'd';
   2434   }else{
   2435     z[0] = '?';
   2436   }
   2437   for(i=0; i<3; i++){
   2438     int m = (iMode >> ((2-i)*3));
   2439     char *a = &z[1 + i*3];
   2440     a[0] = (m & 0x4) ? 'r' : '-';
   2441     a[1] = (m & 0x2) ? 'w' : '-';
   2442     a[2] = (m & 0x1) ? 'x' : '-';
   2443   }
   2444   z[10] = '\0';
   2445   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
   2446 }
   2447 
   2448 #ifndef SQLITE_OMIT_VIRTUALTABLE
   2449 
   2450 /*
   2451 ** Cursor type for recursively iterating through a directory structure.
   2452 */
   2453 typedef struct fsdir_cursor fsdir_cursor;
   2454 typedef struct FsdirLevel FsdirLevel;
   2455 
   2456 struct FsdirLevel {
   2457   DIR *pDir;                 /* From opendir() */
   2458   char *zDir;                /* Name of directory (nul-terminated) */
   2459 };
   2460 
   2461 struct fsdir_cursor {
   2462   sqlite3_vtab_cursor base;  /* Base class - must be first */
   2463 
   2464   int nLvl;                  /* Number of entries in aLvl[] array */
   2465   int iLvl;                  /* Index of current entry */
   2466   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
   2467 
   2468   const char *zBase;
   2469   int nBase;
   2470 
   2471   struct stat sStat;         /* Current lstat() results */
   2472   char *zPath;               /* Path to current entry */
   2473   sqlite3_int64 iRowid;      /* Current rowid */
   2474 };
   2475 
   2476 typedef struct fsdir_tab fsdir_tab;
   2477 struct fsdir_tab {
   2478   sqlite3_vtab base;         /* Base class - must be first */
   2479 };
   2480 
   2481 /*
   2482 ** Construct a new fsdir virtual table object.
   2483 */
   2484 static int fsdirConnect(
   2485   sqlite3 *db,
   2486   void *pAux,
   2487   int argc, const char *const*argv,
   2488   sqlite3_vtab **ppVtab,
   2489   char **pzErr
   2490 ){
   2491   fsdir_tab *pNew = 0;
   2492   int rc;
   2493   (void)pAux;
   2494   (void)argc;
   2495   (void)argv;
   2496   (void)pzErr;
   2497   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
   2498   if( rc==SQLITE_OK ){
   2499     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
   2500     if( pNew==0 ) return SQLITE_NOMEM;
   2501     memset(pNew, 0, sizeof(*pNew));
   2502   }
   2503   *ppVtab = (sqlite3_vtab*)pNew;
   2504   return rc;
   2505 }
   2506 
   2507 /*
   2508 ** This method is the destructor for fsdir vtab objects.
   2509 */
   2510 static int fsdirDisconnect(sqlite3_vtab *pVtab){
   2511   sqlite3_free(pVtab);
   2512   return SQLITE_OK;
   2513 }
   2514 
   2515 /*
   2516 ** Constructor for a new fsdir_cursor object.
   2517 */
   2518 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   2519   fsdir_cursor *pCur;
   2520   (void)p;
   2521   pCur = sqlite3_malloc( sizeof(*pCur) );
   2522   if( pCur==0 ) return SQLITE_NOMEM;
   2523   memset(pCur, 0, sizeof(*pCur));
   2524   pCur->iLvl = -1;
   2525   *ppCursor = &pCur->base;
   2526   return SQLITE_OK;
   2527 }
   2528 
   2529 /*
   2530 ** Reset a cursor back to the state it was in when first returned
   2531 ** by fsdirOpen().
   2532 */
   2533 static void fsdirResetCursor(fsdir_cursor *pCur){
   2534   int i;
   2535   for(i=0; i<=pCur->iLvl; i++){
   2536     FsdirLevel *pLvl = &pCur->aLvl[i];
   2537     if( pLvl->pDir ) closedir(pLvl->pDir);
   2538     sqlite3_free(pLvl->zDir);
   2539   }
   2540   sqlite3_free(pCur->zPath);
   2541   pCur->aLvl = 0;
   2542   pCur->zPath = 0;
   2543   pCur->zBase = 0;
   2544   pCur->nBase = 0;
   2545   pCur->iLvl = -1;
   2546   pCur->iRowid = 1;
   2547 }
   2548 
   2549 /*
   2550 ** Destructor for an fsdir_cursor.
   2551 */
   2552 static int fsdirClose(sqlite3_vtab_cursor *cur){
   2553   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   2554 
   2555   fsdirResetCursor(pCur);
   2556   sqlite3_free(pCur->aLvl);
   2557   sqlite3_free(pCur);
   2558   return SQLITE_OK;
   2559 }
   2560 
   2561 /*
   2562 ** Set the error message for the virtual table associated with cursor
   2563 ** pCur to the results of vprintf(zFmt, ...).
   2564 */
   2565 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
   2566   va_list ap;
   2567   va_start(ap, zFmt);
   2568   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
   2569   va_end(ap);
   2570 }
   2571 
   2572 
   2573 /*
   2574 ** Advance an fsdir_cursor to its next row of output.
   2575 */
   2576 static int fsdirNext(sqlite3_vtab_cursor *cur){
   2577   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   2578   mode_t m = pCur->sStat.st_mode;
   2579 
   2580   pCur->iRowid++;
   2581   if( S_ISDIR(m) ){
   2582     /* Descend into this directory */
   2583     int iNew = pCur->iLvl + 1;
   2584     FsdirLevel *pLvl;
   2585     if( iNew>=pCur->nLvl ){
   2586       int nNew = iNew+1;
   2587       int nByte = nNew*sizeof(FsdirLevel);
   2588       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc(pCur->aLvl, nByte);
   2589       if( aNew==0 ) return SQLITE_NOMEM;
   2590       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
   2591       pCur->aLvl = aNew;
   2592       pCur->nLvl = nNew;
   2593     }
   2594     pCur->iLvl = iNew;
   2595     pLvl = &pCur->aLvl[iNew];
   2596 
   2597     pLvl->zDir = pCur->zPath;
   2598     pCur->zPath = 0;
   2599     pLvl->pDir = opendir(pLvl->zDir);
   2600     if( pLvl->pDir==0 ){
   2601       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
   2602       return SQLITE_ERROR;
   2603     }
   2604   }
   2605 
   2606   while( pCur->iLvl>=0 ){
   2607     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
   2608     struct dirent *pEntry = readdir(pLvl->pDir);
   2609     if( pEntry ){
   2610       if( pEntry->d_name[0]=='.' ){
   2611        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
   2612        if( pEntry->d_name[1]=='\0' ) continue;
   2613       }
   2614       sqlite3_free(pCur->zPath);
   2615       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
   2616       if( pCur->zPath==0 ) return SQLITE_NOMEM;
   2617       if( lstat(pCur->zPath, &pCur->sStat) ){
   2618         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
   2619         return SQLITE_ERROR;
   2620       }
   2621       return SQLITE_OK;
   2622     }
   2623     closedir(pLvl->pDir);
   2624     sqlite3_free(pLvl->zDir);
   2625     pLvl->pDir = 0;
   2626     pLvl->zDir = 0;
   2627     pCur->iLvl--;
   2628   }
   2629 
   2630   /* EOF */
   2631   sqlite3_free(pCur->zPath);
   2632   pCur->zPath = 0;
   2633   return SQLITE_OK;
   2634 }
   2635 
   2636 /*
   2637 ** Return values of columns for the row at which the series_cursor
   2638 ** is currently pointing.
   2639 */
   2640 static int fsdirColumn(
   2641   sqlite3_vtab_cursor *cur,   /* The cursor */
   2642   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   2643   int i                       /* Which column to return */
   2644 ){
   2645   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   2646   switch( i ){
   2647     case 0: { /* name */
   2648       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
   2649       break;
   2650     }
   2651 
   2652     case 1: /* mode */
   2653       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
   2654       break;
   2655 
   2656     case 2: /* mtime */
   2657       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
   2658       break;
   2659 
   2660     case 3: { /* data */
   2661       mode_t m = pCur->sStat.st_mode;
   2662       if( S_ISDIR(m) ){
   2663         sqlite3_result_null(ctx);
   2664 #if !defined(_WIN32) && !defined(WIN32)
   2665       }else if( S_ISLNK(m) ){
   2666         char aStatic[64];
   2667         char *aBuf = aStatic;
   2668         int nBuf = 64;
   2669         int n;
   2670 
   2671         while( 1 ){
   2672           n = readlink(pCur->zPath, aBuf, nBuf);
   2673           if( n<nBuf ) break;
   2674           if( aBuf!=aStatic ) sqlite3_free(aBuf);
   2675           nBuf = nBuf*2;
   2676           aBuf = sqlite3_malloc(nBuf);
   2677           if( aBuf==0 ){
   2678             sqlite3_result_error_nomem(ctx);
   2679             return SQLITE_NOMEM;
   2680           }
   2681         }
   2682 
   2683         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
   2684         if( aBuf!=aStatic ) sqlite3_free(aBuf);
   2685 #endif
   2686       }else{
   2687         readFileContents(ctx, pCur->zPath);
   2688       }
   2689     }
   2690   }
   2691   return SQLITE_OK;
   2692 }
   2693 
   2694 /*
   2695 ** Return the rowid for the current row. In this implementation, the
   2696 ** first row returned is assigned rowid value 1, and each subsequent
   2697 ** row a value 1 more than that of the previous.
   2698 */
   2699 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   2700   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   2701   *pRowid = pCur->iRowid;
   2702   return SQLITE_OK;
   2703 }
   2704 
   2705 /*
   2706 ** Return TRUE if the cursor has been moved off of the last
   2707 ** row of output.
   2708 */
   2709 static int fsdirEof(sqlite3_vtab_cursor *cur){
   2710   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   2711   return (pCur->zPath==0);
   2712 }
   2713 
   2714 /*
   2715 ** xFilter callback.
   2716 */
   2717 static int fsdirFilter(
   2718   sqlite3_vtab_cursor *cur,
   2719   int idxNum, const char *idxStr,
   2720   int argc, sqlite3_value **argv
   2721 ){
   2722   const char *zDir = 0;
   2723   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   2724   (void)idxStr;
   2725   fsdirResetCursor(pCur);
   2726 
   2727   if( idxNum==0 ){
   2728     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
   2729     return SQLITE_ERROR;
   2730   }
   2731 
   2732   assert( argc==idxNum && (argc==1 || argc==2) );
   2733   zDir = (const char*)sqlite3_value_text(argv[0]);
   2734   if( zDir==0 ){
   2735     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
   2736     return SQLITE_ERROR;
   2737   }
   2738   if( argc==2 ){
   2739     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
   2740   }
   2741   if( pCur->zBase ){
   2742     pCur->nBase = (int)strlen(pCur->zBase)+1;
   2743     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
   2744   }else{
   2745     pCur->zPath = sqlite3_mprintf("%s", zDir);
   2746   }
   2747 
   2748   if( pCur->zPath==0 ){
   2749     return SQLITE_NOMEM;
   2750   }
   2751   if( lstat(pCur->zPath, &pCur->sStat) ){
   2752     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
   2753     return SQLITE_ERROR;
   2754   }
   2755 
   2756   return SQLITE_OK;
   2757 }
   2758 
   2759 /*
   2760 ** SQLite will invoke this method one or more times while planning a query
   2761 ** that uses the generate_series virtual table.  This routine needs to create
   2762 ** a query plan for each invocation and compute an estimated cost for that
   2763 ** plan.
   2764 **
   2765 ** In this implementation idxNum is used to represent the
   2766 ** query plan.  idxStr is unused.
   2767 **
   2768 ** The query plan is represented by bits in idxNum:
   2769 **
   2770 **  (1)  start = $value  -- constraint exists
   2771 **  (2)  stop = $value   -- constraint exists
   2772 **  (4)  step = $value   -- constraint exists
   2773 **  (8)  output in descending order
   2774 */
   2775 static int fsdirBestIndex(
   2776   sqlite3_vtab *tab,
   2777   sqlite3_index_info *pIdxInfo
   2778 ){
   2779   int i;                 /* Loop over constraints */
   2780   int idx4 = -1;
   2781   int idx5 = -1;
   2782   const struct sqlite3_index_constraint *pConstraint;
   2783 
   2784   (void)tab;
   2785   pConstraint = pIdxInfo->aConstraint;
   2786   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   2787     if( pConstraint->usable==0 ) continue;
   2788     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   2789     if( pConstraint->iColumn==4 ) idx4 = i;
   2790     if( pConstraint->iColumn==5 ) idx5 = i;
   2791   }
   2792 
   2793   if( idx4<0 ){
   2794     pIdxInfo->idxNum = 0;
   2795     pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
   2796   }else{
   2797     pIdxInfo->aConstraintUsage[idx4].omit = 1;
   2798     pIdxInfo->aConstraintUsage[idx4].argvIndex = 1;
   2799     if( idx5>=0 ){
   2800       pIdxInfo->aConstraintUsage[idx5].omit = 1;
   2801       pIdxInfo->aConstraintUsage[idx5].argvIndex = 2;
   2802       pIdxInfo->idxNum = 2;
   2803       pIdxInfo->estimatedCost = 10.0;
   2804     }else{
   2805       pIdxInfo->idxNum = 1;
   2806       pIdxInfo->estimatedCost = 100.0;
   2807     }
   2808   }
   2809 
   2810   return SQLITE_OK;
   2811 }
   2812 
   2813 /*
   2814 ** Register the "fsdir" virtual table.
   2815 */
   2816 static int fsdirRegister(sqlite3 *db){
   2817   static sqlite3_module fsdirModule = {
   2818     0,                         /* iVersion */
   2819     0,                         /* xCreate */
   2820     fsdirConnect,              /* xConnect */
   2821     fsdirBestIndex,            /* xBestIndex */
   2822     fsdirDisconnect,           /* xDisconnect */
   2823     0,                         /* xDestroy */
   2824     fsdirOpen,                 /* xOpen - open a cursor */
   2825     fsdirClose,                /* xClose - close a cursor */
   2826     fsdirFilter,               /* xFilter - configure scan constraints */
   2827     fsdirNext,                 /* xNext - advance a cursor */
   2828     fsdirEof,                  /* xEof - check for end of scan */
   2829     fsdirColumn,               /* xColumn - read data */
   2830     fsdirRowid,                /* xRowid - read data */
   2831     0,                         /* xUpdate */
   2832     0,                         /* xBegin */
   2833     0,                         /* xSync */
   2834     0,                         /* xCommit */
   2835     0,                         /* xRollback */
   2836     0,                         /* xFindMethod */
   2837     0,                         /* xRename */
   2838     0,                         /* xSavepoint */
   2839     0,                         /* xRelease */
   2840     0                          /* xRollbackTo */
   2841   };
   2842 
   2843   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
   2844   return rc;
   2845 }
   2846 #else         /* SQLITE_OMIT_VIRTUALTABLE */
   2847 # define fsdirRegister(x) SQLITE_OK
   2848 #endif
   2849 
   2850 #ifdef _WIN32
   2851 
   2852 #endif
   2853 int sqlite3_fileio_init(
   2854   sqlite3 *db,
   2855   char **pzErrMsg,
   2856   const sqlite3_api_routines *pApi
   2857 ){
   2858   int rc = SQLITE_OK;
   2859   SQLITE_EXTENSION_INIT2(pApi);
   2860   (void)pzErrMsg;  /* Unused parameter */
   2861   rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
   2862                                readfileFunc, 0, 0);
   2863   if( rc==SQLITE_OK ){
   2864     rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
   2865                                  writefileFunc, 0, 0);
   2866   }
   2867   if( rc==SQLITE_OK ){
   2868     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
   2869                                  lsModeFunc, 0, 0);
   2870   }
   2871   if( rc==SQLITE_OK ){
   2872     rc = fsdirRegister(db);
   2873   }
   2874   return rc;
   2875 }
   2876 
   2877 /************************* End ../ext/misc/fileio.c ********************/
   2878 /************************* Begin ../ext/misc/completion.c ******************/
   2879 /*
   2880 ** 2017-07-10
   2881 **
   2882 ** The author disclaims copyright to this source code.  In place of
   2883 ** a legal notice, here is a blessing:
   2884 **
   2885 **    May you do good and not evil.
   2886 **    May you find forgiveness for yourself and forgive others.
   2887 **    May you share freely, never taking more than you give.
   2888 **
   2889 *************************************************************************
   2890 **
   2891 ** This file implements an eponymous virtual table that returns suggested
   2892 ** completions for a partial SQL input.
   2893 **
   2894 ** Suggested usage:
   2895 **
   2896 **     SELECT DISTINCT candidate COLLATE nocase
   2897 **       FROM completion($prefix,$wholeline)
   2898 **      ORDER BY 1;
   2899 **
   2900 ** The two query parameters are optional.  $prefix is the text of the
   2901 ** current word being typed and that is to be completed.  $wholeline is
   2902 ** the complete input line, used for context.
   2903 **
   2904 ** The raw completion() table might return the same candidate multiple
   2905 ** times, for example if the same column name is used to two or more
   2906 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
   2907 ** the DISTINCT and ORDER BY are recommended.
   2908 **
   2909 ** This virtual table operates at the speed of human typing, and so there
   2910 ** is no attempt to make it fast.  Even a slow implementation will be much
   2911 ** faster than any human can type.
   2912 **
   2913 */
   2914 SQLITE_EXTENSION_INIT1
   2915 #include <assert.h>
   2916 #include <string.h>
   2917 #include <ctype.h>
   2918 
   2919 #ifndef SQLITE_OMIT_VIRTUALTABLE
   2920 
   2921 /* completion_vtab is a subclass of sqlite3_vtab which will
   2922 ** serve as the underlying representation of a completion virtual table
   2923 */
   2924 typedef struct completion_vtab completion_vtab;
   2925 struct completion_vtab {
   2926   sqlite3_vtab base;  /* Base class - must be first */
   2927   sqlite3 *db;        /* Database connection for this completion vtab */
   2928 };
   2929 
   2930 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
   2931 ** serve as the underlying representation of a cursor that scans
   2932 ** over rows of the result
   2933 */
   2934 typedef struct completion_cursor completion_cursor;
   2935 struct completion_cursor {
   2936   sqlite3_vtab_cursor base;  /* Base class - must be first */
   2937   sqlite3 *db;               /* Database connection for this cursor */
   2938   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
   2939   char *zPrefix;             /* The prefix for the word we want to complete */
   2940   char *zLine;               /* The whole that we want to complete */
   2941   const char *zCurrentRow;   /* Current output row */
   2942   sqlite3_stmt *pStmt;       /* Current statement */
   2943   sqlite3_int64 iRowid;      /* The rowid */
   2944   int ePhase;                /* Current phase */
   2945   int j;                     /* inter-phase counter */
   2946 };
   2947 
   2948 /* Values for ePhase:
   2949 */
   2950 #define COMPLETION_FIRST_PHASE   1
   2951 #define COMPLETION_KEYWORDS      1
   2952 #define COMPLETION_PRAGMAS       2
   2953 #define COMPLETION_FUNCTIONS     3
   2954 #define COMPLETION_COLLATIONS    4
   2955 #define COMPLETION_INDEXES       5
   2956 #define COMPLETION_TRIGGERS      6
   2957 #define COMPLETION_DATABASES     7
   2958 #define COMPLETION_TABLES        8
   2959 #define COMPLETION_COLUMNS       9
   2960 #define COMPLETION_MODULES       10
   2961 #define COMPLETION_EOF           11
   2962 
   2963 /*
   2964 ** The completionConnect() method is invoked to create a new
   2965 ** completion_vtab that describes the completion virtual table.
   2966 **
   2967 ** Think of this routine as the constructor for completion_vtab objects.
   2968 **
   2969 ** All this routine needs to do is:
   2970 **
   2971 **    (1) Allocate the completion_vtab object and initialize all fields.
   2972 **
   2973 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
   2974 **        result set of queries against completion will look like.
   2975 */
   2976 static int completionConnect(
   2977   sqlite3 *db,
   2978   void *pAux,
   2979   int argc, const char *const*argv,
   2980   sqlite3_vtab **ppVtab,
   2981   char **pzErr
   2982 ){
   2983   completion_vtab *pNew;
   2984   int rc;
   2985 
   2986   (void)(pAux);    /* Unused parameter */
   2987   (void)(argc);    /* Unused parameter */
   2988   (void)(argv);    /* Unused parameter */
   2989   (void)(pzErr);   /* Unused parameter */
   2990 
   2991 /* Column numbers */
   2992 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
   2993 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
   2994 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
   2995 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
   2996 
   2997   rc = sqlite3_declare_vtab(db,
   2998       "CREATE TABLE x("
   2999       "  candidate TEXT,"
   3000       "  prefix TEXT HIDDEN,"
   3001       "  wholeline TEXT HIDDEN,"
   3002       "  phase INT HIDDEN"        /* Used for debugging only */
   3003       ")");
   3004   if( rc==SQLITE_OK ){
   3005     pNew = sqlite3_malloc( sizeof(*pNew) );
   3006     *ppVtab = (sqlite3_vtab*)pNew;
   3007     if( pNew==0 ) return SQLITE_NOMEM;
   3008     memset(pNew, 0, sizeof(*pNew));
   3009     pNew->db = db;
   3010   }
   3011   return rc;
   3012 }
   3013 
   3014 /*
   3015 ** This method is the destructor for completion_cursor objects.
   3016 */
   3017 static int completionDisconnect(sqlite3_vtab *pVtab){
   3018   sqlite3_free(pVtab);
   3019   return SQLITE_OK;
   3020 }
   3021 
   3022 /*
   3023 ** Constructor for a new completion_cursor object.
   3024 */
   3025 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   3026   completion_cursor *pCur;
   3027   pCur = sqlite3_malloc( sizeof(*pCur) );
   3028   if( pCur==0 ) return SQLITE_NOMEM;
   3029   memset(pCur, 0, sizeof(*pCur));
   3030   pCur->db = ((completion_vtab*)p)->db;
   3031   *ppCursor = &pCur->base;
   3032   return SQLITE_OK;
   3033 }
   3034 
   3035 /*
   3036 ** Reset the completion_cursor.
   3037 */
   3038 static void completionCursorReset(completion_cursor *pCur){
   3039   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
   3040   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
   3041   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
   3042   pCur->j = 0;
   3043 }
   3044 
   3045 /*
   3046 ** Destructor for a completion_cursor.
   3047 */
   3048 static int completionClose(sqlite3_vtab_cursor *cur){
   3049   completionCursorReset((completion_cursor*)cur);
   3050   sqlite3_free(cur);
   3051   return SQLITE_OK;
   3052 }
   3053 
   3054 /*
   3055 ** All SQL keywords understood by SQLite
   3056 */
   3057 static const char *completionKwrds[] = {
   3058   "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
   3059   "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
   3060   "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
   3061   "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
   3062   "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
   3063   "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
   3064   "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
   3065   "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
   3066   "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
   3067   "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
   3068   "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
   3069   "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
   3070   "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
   3071   "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
   3072   "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
   3073   "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
   3074   "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
   3075   "WITH", "WITHOUT",
   3076 };
   3077 #define completionKwCount \
   3078    (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0]))
   3079 
   3080 /*
   3081 ** Advance a completion_cursor to its next row of output.
   3082 **
   3083 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
   3084 ** record the current state of the scan.  This routine sets ->zCurrentRow
   3085 ** to the current row of output and then returns.  If no more rows remain,
   3086 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
   3087 ** table that has reached the end of its scan.
   3088 **
   3089 ** The current implementation just lists potential identifiers and
   3090 ** keywords and filters them by zPrefix.  Future enhancements should
   3091 ** take zLine into account to try to restrict the set of identifiers and
   3092 ** keywords based on what would be legal at the current point of input.
   3093 */
   3094 static int completionNext(sqlite3_vtab_cursor *cur){
   3095   completion_cursor *pCur = (completion_cursor*)cur;
   3096   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
   3097   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
   3098   pCur->iRowid++;
   3099   while( pCur->ePhase!=COMPLETION_EOF ){
   3100     switch( pCur->ePhase ){
   3101       case COMPLETION_KEYWORDS: {
   3102         if( pCur->j >= completionKwCount ){
   3103           pCur->zCurrentRow = 0;
   3104           pCur->ePhase = COMPLETION_DATABASES;
   3105         }else{
   3106           pCur->zCurrentRow = completionKwrds[pCur->j++];
   3107         }
   3108         iCol = -1;
   3109         break;
   3110       }
   3111       case COMPLETION_DATABASES: {
   3112         if( pCur->pStmt==0 ){
   3113           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
   3114                              &pCur->pStmt, 0);
   3115         }
   3116         iCol = 1;
   3117         eNextPhase = COMPLETION_TABLES;
   3118         break;
   3119       }
   3120       case COMPLETION_TABLES: {
   3121         if( pCur->pStmt==0 ){
   3122           sqlite3_stmt *pS2;
   3123           char *zSql = 0;
   3124           const char *zSep = "";
   3125           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
   3126           while( sqlite3_step(pS2)==SQLITE_ROW ){
   3127             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
   3128             zSql = sqlite3_mprintf(
   3129                "%z%s"
   3130                "SELECT name FROM \"%w\".sqlite_master"
   3131                " WHERE type='table'",
   3132                zSql, zSep, zDb
   3133             );
   3134             if( zSql==0 ) return SQLITE_NOMEM;
   3135             zSep = " UNION ";
   3136           }
   3137           sqlite3_finalize(pS2);
   3138           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
   3139           sqlite3_free(zSql);
   3140         }
   3141         iCol = 0;
   3142         eNextPhase = COMPLETION_COLUMNS;
   3143         break;
   3144       }
   3145       case COMPLETION_COLUMNS: {
   3146         if( pCur->pStmt==0 ){
   3147           sqlite3_stmt *pS2;
   3148           char *zSql = 0;
   3149           const char *zSep = "";
   3150           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
   3151           while( sqlite3_step(pS2)==SQLITE_ROW ){
   3152             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
   3153             zSql = sqlite3_mprintf(
   3154                "%z%s"
   3155                "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
   3156                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
   3157                " WHERE sm.type='table'",
   3158                zSql, zSep, zDb, zDb
   3159             );
   3160             if( zSql==0 ) return SQLITE_NOMEM;
   3161             zSep = " UNION ";
   3162           }
   3163           sqlite3_finalize(pS2);
   3164           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
   3165           sqlite3_free(zSql);
   3166         }
   3167         iCol = 0;
   3168         eNextPhase = COMPLETION_EOF;
   3169         break;
   3170       }
   3171     }
   3172     if( iCol<0 ){
   3173       /* This case is when the phase presets zCurrentRow */
   3174       if( pCur->zCurrentRow==0 ) continue;
   3175     }else{
   3176       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
   3177         /* Extract the next row of content */
   3178         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
   3179       }else{
   3180         /* When all rows are finished, advance to the next phase */
   3181         sqlite3_finalize(pCur->pStmt);
   3182         pCur->pStmt = 0;
   3183         pCur->ePhase = eNextPhase;
   3184         continue;
   3185       }
   3186     }
   3187     if( pCur->nPrefix==0 ) break;
   3188     if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){
   3189       break;
   3190     }
   3191   }
   3192 
   3193   return SQLITE_OK;
   3194 }
   3195 
   3196 /*
   3197 ** Return values of columns for the row at which the completion_cursor
   3198 ** is currently pointing.
   3199 */
   3200 static int completionColumn(
   3201   sqlite3_vtab_cursor *cur,   /* The cursor */
   3202   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   3203   int i                       /* Which column to return */
   3204 ){
   3205   completion_cursor *pCur = (completion_cursor*)cur;
   3206   switch( i ){
   3207     case COMPLETION_COLUMN_CANDIDATE: {
   3208       sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT);
   3209       break;
   3210     }
   3211     case COMPLETION_COLUMN_PREFIX: {
   3212       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
   3213       break;
   3214     }
   3215     case COMPLETION_COLUMN_WHOLELINE: {
   3216       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
   3217       break;
   3218     }
   3219     case COMPLETION_COLUMN_PHASE: {
   3220       sqlite3_result_int(ctx, pCur->ePhase);
   3221       break;
   3222     }
   3223   }
   3224   return SQLITE_OK;
   3225 }
   3226 
   3227 /*
   3228 ** Return the rowid for the current row.  In this implementation, the
   3229 ** rowid is the same as the output value.
   3230 */
   3231 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   3232   completion_cursor *pCur = (completion_cursor*)cur;
   3233   *pRowid = pCur->iRowid;
   3234   return SQLITE_OK;
   3235 }
   3236 
   3237 /*
   3238 ** Return TRUE if the cursor has been moved off of the last
   3239 ** row of output.
   3240 */
   3241 static int completionEof(sqlite3_vtab_cursor *cur){
   3242   completion_cursor *pCur = (completion_cursor*)cur;
   3243   return pCur->ePhase >= COMPLETION_EOF;
   3244 }
   3245 
   3246 /*
   3247 ** This method is called to "rewind" the completion_cursor object back
   3248 ** to the first row of output.  This method is always called at least
   3249 ** once prior to any call to completionColumn() or completionRowid() or
   3250 ** completionEof().
   3251 */
   3252 static int completionFilter(
   3253   sqlite3_vtab_cursor *pVtabCursor,
   3254   int idxNum, const char *idxStr,
   3255   int argc, sqlite3_value **argv
   3256 ){
   3257   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
   3258   int iArg = 0;
   3259   (void)(idxStr);   /* Unused parameter */
   3260   (void)(argc);     /* Unused parameter */
   3261   completionCursorReset(pCur);
   3262   if( idxNum & 1 ){
   3263     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
   3264     if( pCur->nPrefix>0 ){
   3265       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
   3266       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
   3267     }
   3268     iArg++;
   3269   }
   3270   if( idxNum & 2 ){
   3271     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
   3272     if( pCur->nLine>0 ){
   3273       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
   3274       if( pCur->zLine==0 ) return SQLITE_NOMEM;
   3275     }
   3276     iArg++;
   3277   }
   3278   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
   3279     int i = pCur->nLine;
   3280     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
   3281       i--;
   3282     }
   3283     pCur->nPrefix = pCur->nLine - i;
   3284     if( pCur->nPrefix>0 ){
   3285       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
   3286       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
   3287     }
   3288   }
   3289   pCur->iRowid = 0;
   3290   pCur->ePhase = COMPLETION_FIRST_PHASE;
   3291   return completionNext(pVtabCursor);
   3292 }
   3293 
   3294 /*
   3295 ** SQLite will invoke this method one or more times while planning a query
   3296 ** that uses the completion virtual table.  This routine needs to create
   3297 ** a query plan for each invocation and compute an estimated cost for that
   3298 ** plan.
   3299 **
   3300 ** There are two hidden parameters that act as arguments to the table-valued
   3301 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
   3302 ** is available and bit 1 is set if "wholeline" is available.
   3303 */
   3304 static int completionBestIndex(
   3305   sqlite3_vtab *tab,
   3306   sqlite3_index_info *pIdxInfo
   3307 ){
   3308   int i;                 /* Loop over constraints */
   3309   int idxNum = 0;        /* The query plan bitmask */
   3310   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
   3311   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
   3312   int nArg = 0;          /* Number of arguments that completeFilter() expects */
   3313   const struct sqlite3_index_constraint *pConstraint;
   3314 
   3315   (void)(tab);    /* Unused parameter */
   3316   pConstraint = pIdxInfo->aConstraint;
   3317   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   3318     if( pConstraint->usable==0 ) continue;
   3319     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   3320     switch( pConstraint->iColumn ){
   3321       case COMPLETION_COLUMN_PREFIX:
   3322         prefixIdx = i;
   3323         idxNum |= 1;
   3324         break;
   3325       case COMPLETION_COLUMN_WHOLELINE:
   3326         wholelineIdx = i;
   3327         idxNum |= 2;
   3328         break;
   3329     }
   3330   }
   3331   if( prefixIdx>=0 ){
   3332     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
   3333     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
   3334   }
   3335   if( wholelineIdx>=0 ){
   3336     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
   3337     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
   3338   }
   3339   pIdxInfo->idxNum = idxNum;
   3340   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
   3341   pIdxInfo->estimatedRows = 500 - 100*nArg;
   3342   return SQLITE_OK;
   3343 }
   3344 
   3345 /*
   3346 ** This following structure defines all the methods for the
   3347 ** completion virtual table.
   3348 */
   3349 static sqlite3_module completionModule = {
   3350   0,                         /* iVersion */
   3351   0,                         /* xCreate */
   3352   completionConnect,         /* xConnect */
   3353   completionBestIndex,       /* xBestIndex */
   3354   completionDisconnect,      /* xDisconnect */
   3355   0,                         /* xDestroy */
   3356   completionOpen,            /* xOpen - open a cursor */
   3357   completionClose,           /* xClose - close a cursor */
   3358   completionFilter,          /* xFilter - configure scan constraints */
   3359   completionNext,            /* xNext - advance a cursor */
   3360   completionEof,             /* xEof - check for end of scan */
   3361   completionColumn,          /* xColumn - read data */
   3362   completionRowid,           /* xRowid - read data */
   3363   0,                         /* xUpdate */
   3364   0,                         /* xBegin */
   3365   0,                         /* xSync */
   3366   0,                         /* xCommit */
   3367   0,                         /* xRollback */
   3368   0,                         /* xFindMethod */
   3369   0,                         /* xRename */
   3370   0,                         /* xSavepoint */
   3371   0,                         /* xRelease */
   3372   0                          /* xRollbackTo */
   3373 };
   3374 
   3375 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   3376 
   3377 int sqlite3CompletionVtabInit(sqlite3 *db){
   3378   int rc = SQLITE_OK;
   3379 #ifndef SQLITE_OMIT_VIRTUALTABLE
   3380   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
   3381 #endif
   3382   return rc;
   3383 }
   3384 
   3385 #ifdef _WIN32
   3386 
   3387 #endif
   3388 int sqlite3_completion_init(
   3389   sqlite3 *db,
   3390   char **pzErrMsg,
   3391   const sqlite3_api_routines *pApi
   3392 ){
   3393   int rc = SQLITE_OK;
   3394   SQLITE_EXTENSION_INIT2(pApi);
   3395   (void)(pzErrMsg);  /* Unused parameter */
   3396 #ifndef SQLITE_OMIT_VIRTUALTABLE
   3397   rc = sqlite3CompletionVtabInit(db);
   3398 #endif
   3399   return rc;
   3400 }
   3401 
   3402 /************************* End ../ext/misc/completion.c ********************/
   3403 /************************* Begin ../ext/misc/appendvfs.c ******************/
   3404 /*
   3405 ** 2017-10-20
   3406 **
   3407 ** The author disclaims copyright to this source code.  In place of
   3408 ** a legal notice, here is a blessing:
   3409 **
   3410 **    May you do good and not evil.
   3411 **    May you find forgiveness for yourself and forgive others.
   3412 **    May you share freely, never taking more than you give.
   3413 **
   3414 ******************************************************************************
   3415 **
   3416 ** This file implements a VFS shim that allows an SQLite database to be
   3417 ** appended onto the end of some other file, such as an executable.
   3418 **
   3419 ** A special record must appear at the end of the file that identifies the
   3420 ** file as an appended database and provides an offset to page 1.  For
   3421 ** best performance page 1 should be located at a disk page boundary, though
   3422 ** that is not required.
   3423 **
   3424 ** When opening a database using this VFS, the connection might treat
   3425 ** the file as an ordinary SQLite database, or it might treat is as a
   3426 ** database appended onto some other file.  Here are the rules:
   3427 **
   3428 **  (1)  When opening a new empty file, that file is treated as an ordinary
   3429 **       database.
   3430 **
   3431 **  (2)  When opening a file that begins with the standard SQLite prefix
   3432 **       string "SQLite format 3", that file is treated as an ordinary
   3433 **       database.
   3434 **
   3435 **  (3)  When opening a file that ends with the appendvfs trailer string
   3436 **       "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
   3437 **       database.
   3438 **
   3439 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
   3440 **       set, then a new database is appended to the already existing file.
   3441 **
   3442 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
   3443 **
   3444 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
   3445 ** the file containing the database is limited to 1GB.  This VFS will refuse
   3446 ** to read or write past the 1GB mark.  This restriction might be lifted in
   3447 ** future versions.  For now, if you need a large database, then keep the
   3448 ** database in a separate file.
   3449 **
   3450 ** If the file being opened is not an appended database, then this shim is
   3451 ** a pass-through into the default underlying VFS.
   3452 **/
   3453 SQLITE_EXTENSION_INIT1
   3454 #include <string.h>
   3455 #include <assert.h>
   3456 
   3457 /* The append mark at the end of the database is:
   3458 **
   3459 **     Start-Of-SQLite3-NNNNNNNN
   3460 **     123456789 123456789 12345
   3461 **
   3462 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
   3463 ** the offset to page 1.
   3464 */
   3465 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
   3466 #define APND_MARK_PREFIX_SZ  17
   3467 #define APND_MARK_SIZE       25
   3468 
   3469 /*
   3470 ** Maximum size of the combined prefix + database + append-mark.  This
   3471 ** must be less than 0x40000000 to avoid locking issues on Windows.
   3472 */
   3473 #define APND_MAX_SIZE  (65536*15259)
   3474 
   3475 /*
   3476 ** Forward declaration of objects used by this utility
   3477 */
   3478 typedef struct sqlite3_vfs ApndVfs;
   3479 typedef struct ApndFile ApndFile;
   3480 
   3481 /* Access to a lower-level VFS that (might) implement dynamic loading,
   3482 ** access to randomness, etc.
   3483 */
   3484 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
   3485 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
   3486 
   3487 /* An open file */
   3488 struct ApndFile {
   3489   sqlite3_file base;              /* IO methods */
   3490   sqlite3_int64 iPgOne;           /* File offset to page 1 */
   3491   sqlite3_int64 iMark;            /* Start of the append-mark */
   3492 };
   3493 
   3494 /*
   3495 ** Methods for ApndFile
   3496 */
   3497 static int apndClose(sqlite3_file*);
   3498 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   3499 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
   3500 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
   3501 static int apndSync(sqlite3_file*, int flags);
   3502 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
   3503 static int apndLock(sqlite3_file*, int);
   3504 static int apndUnlock(sqlite3_file*, int);
   3505 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
   3506 static int apndFileControl(sqlite3_file*, int op, void *pArg);
   3507 static int apndSectorSize(sqlite3_file*);
   3508 static int apndDeviceCharacteristics(sqlite3_file*);
   3509 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   3510 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
   3511 static void apndShmBarrier(sqlite3_file*);
   3512 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
   3513 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
   3514 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
   3515 
   3516 /*
   3517 ** Methods for ApndVfs
   3518 */
   3519 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
   3520 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
   3521 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
   3522 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
   3523 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
   3524 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
   3525 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
   3526 static void apndDlClose(sqlite3_vfs*, void*);
   3527 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
   3528 static int apndSleep(sqlite3_vfs*, int microseconds);
   3529 static int apndCurrentTime(sqlite3_vfs*, double*);
   3530 static int apndGetLastError(sqlite3_vfs*, int, char *);
   3531 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
   3532 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
   3533 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
   3534 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
   3535 
   3536 static sqlite3_vfs apnd_vfs = {
   3537   3,                            /* iVersion (set when registered) */
   3538   0,                            /* szOsFile (set when registered) */
   3539   1024,                         /* mxPathname */
   3540   0,                            /* pNext */
   3541   "apndvfs",                    /* zName */
   3542   0,                            /* pAppData (set when registered) */
   3543   apndOpen,                     /* xOpen */
   3544   apndDelete,                   /* xDelete */
   3545   apndAccess,                   /* xAccess */
   3546   apndFullPathname,             /* xFullPathname */
   3547   apndDlOpen,                   /* xDlOpen */
   3548   apndDlError,                  /* xDlError */
   3549   apndDlSym,                    /* xDlSym */
   3550   apndDlClose,                  /* xDlClose */
   3551   apndRandomness,               /* xRandomness */
   3552   apndSleep,                    /* xSleep */
   3553   apndCurrentTime,              /* xCurrentTime */
   3554   apndGetLastError,             /* xGetLastError */
   3555   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
   3556   apndSetSystemCall,            /* xSetSystemCall */
   3557   apndGetSystemCall,            /* xGetSystemCall */
   3558   apndNextSystemCall            /* xNextSystemCall */
   3559 };
   3560 
   3561 static const sqlite3_io_methods apnd_io_methods = {
   3562   3,                              /* iVersion */
   3563   apndClose,                      /* xClose */
   3564   apndRead,                       /* xRead */
   3565   apndWrite,                      /* xWrite */
   3566   apndTruncate,                   /* xTruncate */
   3567   apndSync,                       /* xSync */
   3568   apndFileSize,                   /* xFileSize */
   3569   apndLock,                       /* xLock */
   3570   apndUnlock,                     /* xUnlock */
   3571   apndCheckReservedLock,          /* xCheckReservedLock */
   3572   apndFileControl,                /* xFileControl */
   3573   apndSectorSize,                 /* xSectorSize */
   3574   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
   3575   apndShmMap,                     /* xShmMap */
   3576   apndShmLock,                    /* xShmLock */
   3577   apndShmBarrier,                 /* xShmBarrier */
   3578   apndShmUnmap,                   /* xShmUnmap */
   3579   apndFetch,                      /* xFetch */
   3580   apndUnfetch                     /* xUnfetch */
   3581 };
   3582 
   3583 
   3584 
   3585 /*
   3586 ** Close an apnd-file.
   3587 */
   3588 static int apndClose(sqlite3_file *pFile){
   3589   pFile = ORIGFILE(pFile);
   3590   return pFile->pMethods->xClose(pFile);
   3591 }
   3592 
   3593 /*
   3594 ** Read data from an apnd-file.
   3595 */
   3596 static int apndRead(
   3597   sqlite3_file *pFile,
   3598   void *zBuf,
   3599   int iAmt,
   3600   sqlite_int64 iOfst
   3601 ){
   3602   ApndFile *p = (ApndFile *)pFile;
   3603   pFile = ORIGFILE(pFile);
   3604   return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
   3605 }
   3606 
   3607 /*
   3608 ** Add the append-mark onto the end of the file.
   3609 */
   3610 static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
   3611   int i;
   3612   unsigned char a[APND_MARK_SIZE];
   3613   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
   3614   for(i=0; i<8; i++){
   3615     a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
   3616   }
   3617   return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
   3618 }
   3619 
   3620 /*
   3621 ** Write data to an apnd-file.
   3622 */
   3623 static int apndWrite(
   3624   sqlite3_file *pFile,
   3625   const void *zBuf,
   3626   int iAmt,
   3627   sqlite_int64 iOfst
   3628 ){
   3629   int rc;
   3630   ApndFile *p = (ApndFile *)pFile;
   3631   pFile = ORIGFILE(pFile);
   3632   if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
   3633   rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
   3634   if( rc==SQLITE_OK &&  iOfst + iAmt + p->iPgOne > p->iMark ){
   3635     sqlite3_int64 sz = 0;
   3636     rc = pFile->pMethods->xFileSize(pFile, &sz);
   3637     if( rc==SQLITE_OK ){
   3638       p->iMark = sz - APND_MARK_SIZE;
   3639       if( iOfst + iAmt + p->iPgOne > p->iMark ){
   3640         p->iMark = p->iPgOne + iOfst + iAmt;
   3641         rc = apndWriteMark(p, pFile);
   3642       }
   3643     }
   3644   }
   3645   return rc;
   3646 }
   3647 
   3648 /*
   3649 ** Truncate an apnd-file.
   3650 */
   3651 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
   3652   int rc;
   3653   ApndFile *p = (ApndFile *)pFile;
   3654   pFile = ORIGFILE(pFile);
   3655   rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
   3656   if( rc==SQLITE_OK ){
   3657     p->iMark = p->iPgOne+size;
   3658     rc = apndWriteMark(p, pFile);
   3659   }
   3660   return rc;
   3661 }
   3662 
   3663 /*
   3664 ** Sync an apnd-file.
   3665 */
   3666 static int apndSync(sqlite3_file *pFile, int flags){
   3667   pFile = ORIGFILE(pFile);
   3668   return pFile->pMethods->xSync(pFile, flags);
   3669 }
   3670 
   3671 /*
   3672 ** Return the current file-size of an apnd-file.
   3673 */
   3674 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
   3675   ApndFile *p = (ApndFile *)pFile;
   3676   int rc;
   3677   pFile = ORIGFILE(p);
   3678   rc = pFile->pMethods->xFileSize(pFile, pSize);
   3679   if( rc==SQLITE_OK && p->iPgOne ){
   3680     *pSize -= p->iPgOne + APND_MARK_SIZE;
   3681   }
   3682   return rc;
   3683 }
   3684 
   3685 /*
   3686 ** Lock an apnd-file.
   3687 */
   3688 static int apndLock(sqlite3_file *pFile, int eLock){
   3689   pFile = ORIGFILE(pFile);
   3690   return pFile->pMethods->xLock(pFile, eLock);
   3691 }
   3692 
   3693 /*
   3694 ** Unlock an apnd-file.
   3695 */
   3696 static int apndUnlock(sqlite3_file *pFile, int eLock){
   3697   pFile = ORIGFILE(pFile);
   3698   return pFile->pMethods->xUnlock(pFile, eLock);
   3699 }
   3700 
   3701 /*
   3702 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
   3703 */
   3704 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
   3705   pFile = ORIGFILE(pFile);
   3706   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
   3707 }
   3708 
   3709 /*
   3710 ** File control method. For custom operations on an apnd-file.
   3711 */
   3712 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
   3713   ApndFile *p = (ApndFile *)pFile;
   3714   int rc;
   3715   pFile = ORIGFILE(pFile);
   3716   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
   3717   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
   3718     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
   3719   }
   3720   return rc;
   3721 }
   3722 
   3723 /*
   3724 ** Return the sector-size in bytes for an apnd-file.
   3725 */
   3726 static int apndSectorSize(sqlite3_file *pFile){
   3727   pFile = ORIGFILE(pFile);
   3728   return pFile->pMethods->xSectorSize(pFile);
   3729 }
   3730 
   3731 /*
   3732 ** Return the device characteristic flags supported by an apnd-file.
   3733 */
   3734 static int apndDeviceCharacteristics(sqlite3_file *pFile){
   3735   pFile = ORIGFILE(pFile);
   3736   return pFile->pMethods->xDeviceCharacteristics(pFile);
   3737 }
   3738 
   3739 /* Create a shared memory file mapping */
   3740 static int apndShmMap(
   3741   sqlite3_file *pFile,
   3742   int iPg,
   3743   int pgsz,
   3744   int bExtend,
   3745   void volatile **pp
   3746 ){
   3747   pFile = ORIGFILE(pFile);
   3748   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
   3749 }
   3750 
   3751 /* Perform locking on a shared-memory segment */
   3752 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
   3753   pFile = ORIGFILE(pFile);
   3754   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
   3755 }
   3756 
   3757 /* Memory barrier operation on shared memory */
   3758 static void apndShmBarrier(sqlite3_file *pFile){
   3759   pFile = ORIGFILE(pFile);
   3760   pFile->pMethods->xShmBarrier(pFile);
   3761 }
   3762 
   3763 /* Unmap a shared memory segment */
   3764 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
   3765   pFile = ORIGFILE(pFile);
   3766   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
   3767 }
   3768 
   3769 /* Fetch a page of a memory-mapped file */
   3770 static int apndFetch(
   3771   sqlite3_file *pFile,
   3772   sqlite3_int64 iOfst,
   3773   int iAmt,
   3774   void **pp
   3775 ){
   3776   ApndFile *p = (ApndFile *)pFile;
   3777   pFile = ORIGFILE(pFile);
   3778   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
   3779 }
   3780 
   3781 /* Release a memory-mapped page */
   3782 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
   3783   ApndFile *p = (ApndFile *)pFile;
   3784   pFile = ORIGFILE(pFile);
   3785   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
   3786 }
   3787 
   3788 /*
   3789 ** Check to see if the file is an ordinary SQLite database file.
   3790 */
   3791 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
   3792   int rc;
   3793   char zHdr[16];
   3794   static const char aSqliteHdr[] = "SQLite format 3";
   3795   if( sz<512 ) return 0;
   3796   rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
   3797   if( rc ) return 0;
   3798   return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
   3799 }
   3800 
   3801 /*
   3802 ** Try to read the append-mark off the end of a file.  Return the
   3803 ** start of the appended database if the append-mark is present.  If
   3804 ** there is no append-mark, return -1;
   3805 */
   3806 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
   3807   int rc, i;
   3808   sqlite3_int64 iMark;
   3809   unsigned char a[APND_MARK_SIZE];
   3810 
   3811   if( sz<=APND_MARK_SIZE ) return -1;
   3812   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
   3813   if( rc ) return -1;
   3814   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
   3815   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
   3816   for(i=1; i<8; i++){
   3817     iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
   3818   }
   3819   return iMark;
   3820 }
   3821 
   3822 /*
   3823 ** Open an apnd file handle.
   3824 */
   3825 static int apndOpen(
   3826   sqlite3_vfs *pVfs,
   3827   const char *zName,
   3828   sqlite3_file *pFile,
   3829   int flags,
   3830   int *pOutFlags
   3831 ){
   3832   ApndFile *p;
   3833   sqlite3_file *pSubFile;
   3834   sqlite3_vfs *pSubVfs;
   3835   int rc;
   3836   sqlite3_int64 sz;
   3837   pSubVfs = ORIGVFS(pVfs);
   3838   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
   3839     return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
   3840   }
   3841   p = (ApndFile*)pFile;
   3842   memset(p, 0, sizeof(*p));
   3843   pSubFile = ORIGFILE(pFile);
   3844   p->base.pMethods = &apnd_io_methods;
   3845   rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
   3846   if( rc ) goto apnd_open_done;
   3847   rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
   3848   if( rc ){
   3849     pSubFile->pMethods->xClose(pSubFile);
   3850     goto apnd_open_done;
   3851   }
   3852   if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
   3853     memmove(pFile, pSubFile, pSubVfs->szOsFile);
   3854     return SQLITE_OK;
   3855   }
   3856   p->iMark = 0;
   3857   p->iPgOne = apndReadMark(sz, pFile);
   3858   if( p->iPgOne>0 ){
   3859     return SQLITE_OK;
   3860   }
   3861   if( (flags & SQLITE_OPEN_CREATE)==0 ){
   3862     pSubFile->pMethods->xClose(pSubFile);
   3863     rc = SQLITE_CANTOPEN;
   3864   }
   3865   p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
   3866 apnd_open_done:
   3867   if( rc ) pFile->pMethods = 0;
   3868   return rc;
   3869 }
   3870 
   3871 /*
   3872 ** All other VFS methods are pass-thrus.
   3873 */
   3874 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   3875   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
   3876 }
   3877 static int apndAccess(
   3878   sqlite3_vfs *pVfs,
   3879   const char *zPath,
   3880   int flags,
   3881   int *pResOut
   3882 ){
   3883   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
   3884 }
   3885 static int apndFullPathname(
   3886   sqlite3_vfs *pVfs,
   3887   const char *zPath,
   3888   int nOut,
   3889   char *zOut
   3890 ){
   3891   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
   3892 }
   3893 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   3894   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
   3895 }
   3896 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
   3897   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
   3898 }
   3899 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
   3900   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
   3901 }
   3902 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
   3903   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
   3904 }
   3905 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   3906   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
   3907 }
   3908 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
   3909   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
   3910 }
   3911 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
   3912   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
   3913 }
   3914 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
   3915   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
   3916 }
   3917 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
   3918   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
   3919 }
   3920 static int apndSetSystemCall(
   3921   sqlite3_vfs *pVfs,
   3922   const char *zName,
   3923   sqlite3_syscall_ptr pCall
   3924 ){
   3925   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
   3926 }
   3927 static sqlite3_syscall_ptr apndGetSystemCall(
   3928   sqlite3_vfs *pVfs,
   3929   const char *zName
   3930 ){
   3931   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
   3932 }
   3933 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
   3934   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
   3935 }
   3936 
   3937 
   3938 #ifdef _WIN32
   3939 
   3940 #endif
   3941 /*
   3942 ** This routine is called when the extension is loaded.
   3943 ** Register the new VFS.
   3944 */
   3945 int sqlite3_appendvfs_init(
   3946   sqlite3 *db,
   3947   char **pzErrMsg,
   3948   const sqlite3_api_routines *pApi
   3949 ){
   3950   int rc = SQLITE_OK;
   3951   sqlite3_vfs *pOrig;
   3952   SQLITE_EXTENSION_INIT2(pApi);
   3953   (void)pzErrMsg;
   3954   (void)db;
   3955   pOrig = sqlite3_vfs_find(0);
   3956   apnd_vfs.iVersion = pOrig->iVersion;
   3957   apnd_vfs.pAppData = pOrig;
   3958   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
   3959   rc = sqlite3_vfs_register(&apnd_vfs, 0);
   3960 #ifdef APPENDVFS_TEST
   3961   if( rc==SQLITE_OK ){
   3962     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
   3963   }
   3964 #endif
   3965   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
   3966   return rc;
   3967 }
   3968 
   3969 /************************* End ../ext/misc/appendvfs.c ********************/
   3970 #ifdef SQLITE_HAVE_ZLIB
   3971 /************************* Begin ../ext/misc/zipfile.c ******************/
   3972 /*
   3973 ** 2017-12-26
   3974 **
   3975 ** The author disclaims copyright to this source code.  In place of
   3976 ** a legal notice, here is a blessing:
   3977 **
   3978 **    May you do good and not evil.
   3979 **    May you find forgiveness for yourself and forgive others.
   3980 **    May you share freely, never taking more than you give.
   3981 **
   3982 ******************************************************************************
   3983 **
   3984 ** This file implements a virtual table for reading and writing ZIP archive
   3985 ** files.
   3986 **
   3987 ** Usage example:
   3988 **
   3989 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
   3990 **
   3991 ** Current limitations:
   3992 **
   3993 **    *  No support for encryption
   3994 **    *  No support for ZIP archives spanning multiple files
   3995 **    *  No support for zip64 extensions
   3996 **    *  Only the "inflate/deflate" (zlib) compression method is supported
   3997 */
   3998 SQLITE_EXTENSION_INIT1
   3999 #include <stdio.h>
   4000 #include <string.h>
   4001 #include <assert.h>
   4002 
   4003 #include <sys/types.h>
   4004 #include <sys/stat.h>
   4005 #include <fcntl.h>
   4006 #if !defined(_WIN32) && !defined(WIN32)
   4007 #  include <unistd.h>
   4008 #  include <dirent.h>
   4009 #  include <utime.h>
   4010 #else
   4011 #  include <io.h>
   4012 #endif
   4013 #include <time.h>
   4014 #include <errno.h>
   4015 
   4016 #include <zlib.h>
   4017 
   4018 #ifndef SQLITE_OMIT_VIRTUALTABLE
   4019 
   4020 #ifndef SQLITE_AMALGAMATION
   4021 /* typedef sqlite3_int64 i64; */
   4022 /* typedef unsigned char u8; */
   4023 typedef unsigned short u16;
   4024 typedef unsigned long u32;
   4025 #define MIN(a,b) ((a)<(b) ? (a) : (b))
   4026 #endif
   4027 
   4028 static const char ZIPFILE_SCHEMA[] =
   4029   "CREATE TABLE y("
   4030     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
   4031     "mode,"              /* 1: POSIX mode for file */
   4032     "mtime,"             /* 2: Last modification time (secs since 1970)*/
   4033     "sz,"                /* 3: Size of object */
   4034     "rawdata,"           /* 4: Raw data */
   4035     "data,"              /* 5: Uncompressed data */
   4036     "method,"            /* 6: Compression method (integer) */
   4037     "z HIDDEN"           /* 7: Name of zip file */
   4038   ") WITHOUT ROWID;";
   4039 
   4040 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
   4041 #define ZIPFILE_BUFFER_SIZE (64*1024)
   4042 
   4043 
   4044 /*
   4045 ** Magic numbers used to read and write zip files.
   4046 **
   4047 ** ZIPFILE_NEWENTRY_MADEBY:
   4048 **   Use this value for the "version-made-by" field in new zip file
   4049 **   entries. The upper byte indicates "unix", and the lower byte
   4050 **   indicates that the zip file matches pkzip specification 3.0.
   4051 **   This is what info-zip seems to do.
   4052 **
   4053 ** ZIPFILE_NEWENTRY_REQUIRED:
   4054 **   Value for "version-required-to-extract" field of new entries.
   4055 **   Version 2.0 is required to support folders and deflate compression.
   4056 **
   4057 ** ZIPFILE_NEWENTRY_FLAGS:
   4058 **   Value for "general-purpose-bit-flags" field of new entries. Bit
   4059 **   11 means "utf-8 filename and comment".
   4060 **
   4061 ** ZIPFILE_SIGNATURE_CDS:
   4062 **   First 4 bytes of a valid CDS record.
   4063 **
   4064 ** ZIPFILE_SIGNATURE_LFH:
   4065 **   First 4 bytes of a valid LFH record.
   4066 */
   4067 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
   4068 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
   4069 #define ZIPFILE_NEWENTRY_REQUIRED 20
   4070 #define ZIPFILE_NEWENTRY_FLAGS    0x800
   4071 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
   4072 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
   4073 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
   4074 #define ZIPFILE_LFH_FIXED_SZ      30
   4075 
   4076 /*
   4077 ** Set the error message contained in context ctx to the results of
   4078 ** vprintf(zFmt, ...).
   4079 */
   4080 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
   4081   char *zMsg = 0;
   4082   va_list ap;
   4083   va_start(ap, zFmt);
   4084   zMsg = sqlite3_vmprintf(zFmt, ap);
   4085   sqlite3_result_error(ctx, zMsg, -1);
   4086   sqlite3_free(zMsg);
   4087   va_end(ap);
   4088 }
   4089 
   4090 
   4091 /*
   4092 *** 4.3.16  End of central directory record:
   4093 ***
   4094 ***   end of central dir signature    4 bytes  (0x06054b50)
   4095 ***   number of this disk             2 bytes
   4096 ***   number of the disk with the
   4097 ***   start of the central directory  2 bytes
   4098 ***   total number of entries in the
   4099 ***   central directory on this disk  2 bytes
   4100 ***   total number of entries in
   4101 ***   the central directory           2 bytes
   4102 ***   size of the central directory   4 bytes
   4103 ***   offset of start of central
   4104 ***   directory with respect to
   4105 ***   the starting disk number        4 bytes
   4106 ***   .ZIP file comment length        2 bytes
   4107 ***   .ZIP file comment       (variable size)
   4108 */
   4109 typedef struct ZipfileEOCD ZipfileEOCD;
   4110 struct ZipfileEOCD {
   4111   u16 iDisk;
   4112   u16 iFirstDisk;
   4113   u16 nEntry;
   4114   u16 nEntryTotal;
   4115   u32 nSize;
   4116   u32 iOffset;
   4117 };
   4118 
   4119 /*
   4120 *** 4.3.12  Central directory structure:
   4121 ***
   4122 *** ...
   4123 ***
   4124 ***   central file header signature   4 bytes  (0x02014b50)
   4125 ***   version made by                 2 bytes
   4126 ***   version needed to extract       2 bytes
   4127 ***   general purpose bit flag        2 bytes
   4128 ***   compression method              2 bytes
   4129 ***   last mod file time              2 bytes
   4130 ***   last mod file date              2 bytes
   4131 ***   crc-32                          4 bytes
   4132 ***   compressed size                 4 bytes
   4133 ***   uncompressed size               4 bytes
   4134 ***   file name length                2 bytes
   4135 ***   extra field length              2 bytes
   4136 ***   file comment length             2 bytes
   4137 ***   disk number start               2 bytes
   4138 ***   internal file attributes        2 bytes
   4139 ***   external file attributes        4 bytes
   4140 ***   relative offset of local header 4 bytes
   4141 */
   4142 typedef struct ZipfileCDS ZipfileCDS;
   4143 struct ZipfileCDS {
   4144   u16 iVersionMadeBy;
   4145   u16 iVersionExtract;
   4146   u16 flags;
   4147   u16 iCompression;
   4148   u16 mTime;
   4149   u16 mDate;
   4150   u32 crc32;
   4151   u32 szCompressed;
   4152   u32 szUncompressed;
   4153   u16 nFile;
   4154   u16 nExtra;
   4155   u16 nComment;
   4156   u16 iDiskStart;
   4157   u16 iInternalAttr;
   4158   u32 iExternalAttr;
   4159   u32 iOffset;
   4160   char *zFile;                    /* Filename (sqlite3_malloc()) */
   4161 };
   4162 
   4163 /*
   4164 *** 4.3.7  Local file header:
   4165 ***
   4166 ***   local file header signature     4 bytes  (0x04034b50)
   4167 ***   version needed to extract       2 bytes
   4168 ***   general purpose bit flag        2 bytes
   4169 ***   compression method              2 bytes
   4170 ***   last mod file time              2 bytes
   4171 ***   last mod file date              2 bytes
   4172 ***   crc-32                          4 bytes
   4173 ***   compressed size                 4 bytes
   4174 ***   uncompressed size               4 bytes
   4175 ***   file name length                2 bytes
   4176 ***   extra field length              2 bytes
   4177 ***
   4178 */
   4179 typedef struct ZipfileLFH ZipfileLFH;
   4180 struct ZipfileLFH {
   4181   u16 iVersionExtract;
   4182   u16 flags;
   4183   u16 iCompression;
   4184   u16 mTime;
   4185   u16 mDate;
   4186   u32 crc32;
   4187   u32 szCompressed;
   4188   u32 szUncompressed;
   4189   u16 nFile;
   4190   u16 nExtra;
   4191 };
   4192 
   4193 typedef struct ZipfileEntry ZipfileEntry;
   4194 struct ZipfileEntry {
   4195   char *zPath;               /* Path of zipfile entry */
   4196   u8 *aCdsEntry;             /* Buffer containing entire CDS entry */
   4197   int nCdsEntry;             /* Size of buffer aCdsEntry[] in bytes */
   4198   int bDeleted;              /* True if entry has been deleted */
   4199   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
   4200 };
   4201 
   4202 /*
   4203 ** Cursor type for recursively iterating through a directory structure.
   4204 */
   4205 typedef struct ZipfileCsr ZipfileCsr;
   4206 struct ZipfileCsr {
   4207   sqlite3_vtab_cursor base;  /* Base class - must be first */
   4208   i64 iId;                   /* Cursor ID */
   4209   int bEof;                  /* True when at EOF */
   4210 
   4211   /* Used outside of write transactions */
   4212   FILE *pFile;               /* Zip file */
   4213   i64 iNextOff;              /* Offset of next record in central directory */
   4214   ZipfileEOCD eocd;          /* Parse of central directory record */
   4215 
   4216   /* Used inside write transactions */
   4217   ZipfileEntry *pCurrent;
   4218 
   4219   ZipfileCDS cds;            /* Central Directory Structure */
   4220   ZipfileLFH lfh;            /* Local File Header for current entry */
   4221   i64 iDataOff;              /* Offset in zipfile to data */
   4222   u32 mTime;                 /* Extended mtime value */
   4223   int flags;                 /* Flags byte (see below for bits) */
   4224   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
   4225 };
   4226 
   4227 /*
   4228 ** Values for ZipfileCsr.flags.
   4229 */
   4230 #define ZIPFILE_MTIME_VALID 0x0001
   4231 
   4232 typedef struct ZipfileTab ZipfileTab;
   4233 struct ZipfileTab {
   4234   sqlite3_vtab base;         /* Base class - must be first */
   4235   char *zFile;               /* Zip file this table accesses (may be NULL) */
   4236   u8 *aBuffer;               /* Temporary buffer used for various tasks */
   4237 
   4238   ZipfileCsr *pCsrList;      /* List of cursors */
   4239   i64 iNextCsrid;
   4240 
   4241   /* The following are used by write transactions only */
   4242   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
   4243   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
   4244   FILE *pWriteFd;            /* File handle open on zip archive */
   4245   i64 szCurrent;             /* Current size of zip archive */
   4246   i64 szOrig;                /* Size of archive at start of transaction */
   4247 };
   4248 
   4249 static void zipfileDequote(char *zIn){
   4250   char q = zIn[0];
   4251   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
   4252     char c;
   4253     int iIn = 1;
   4254     int iOut = 0;
   4255     if( q=='[' ) q = ']';
   4256     while( (c = zIn[iIn++]) ){
   4257       if( c==q ){
   4258         if( zIn[iIn++]!=q ) break;
   4259       }
   4260       zIn[iOut++] = c;
   4261     }
   4262     zIn[iOut] = '\0';
   4263   }
   4264 }
   4265 
   4266 /*
   4267 ** Construct a new ZipfileTab virtual table object.
   4268 **
   4269 **   argv[0]   -> module name  ("zipfile")
   4270 **   argv[1]   -> database name
   4271 **   argv[2]   -> table name
   4272 **   argv[...] -> "column name" and other module argument fields.
   4273 */
   4274 static int zipfileConnect(
   4275   sqlite3 *db,
   4276   void *pAux,
   4277   int argc, const char *const*argv,
   4278   sqlite3_vtab **ppVtab,
   4279   char **pzErr
   4280 ){
   4281   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
   4282   int nFile = 0;
   4283   const char *zFile = 0;
   4284   ZipfileTab *pNew = 0;
   4285   int rc;
   4286 
   4287   if( argc>3 ){
   4288     zFile = argv[3];
   4289     nFile = (int)strlen(zFile)+1;
   4290   }
   4291 
   4292   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
   4293   if( rc==SQLITE_OK ){
   4294     pNew = (ZipfileTab*)sqlite3_malloc(nByte+nFile);
   4295     if( pNew==0 ) return SQLITE_NOMEM;
   4296     memset(pNew, 0, nByte+nFile);
   4297     pNew->aBuffer = (u8*)&pNew[1];
   4298     if( zFile ){
   4299       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
   4300       memcpy(pNew->zFile, zFile, nFile);
   4301       zipfileDequote(pNew->zFile);
   4302     }
   4303   }
   4304   *ppVtab = (sqlite3_vtab*)pNew;
   4305   return rc;
   4306 }
   4307 
   4308 /*
   4309 ** This method is the destructor for zipfile vtab objects.
   4310 */
   4311 static int zipfileDisconnect(sqlite3_vtab *pVtab){
   4312   sqlite3_free(pVtab);
   4313   return SQLITE_OK;
   4314 }
   4315 
   4316 /*
   4317 ** Constructor for a new ZipfileCsr object.
   4318 */
   4319 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
   4320   ZipfileTab *pTab = (ZipfileTab*)p;
   4321   ZipfileCsr *pCsr;
   4322   pCsr = sqlite3_malloc(sizeof(*pCsr));
   4323   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
   4324   if( pCsr==0 ){
   4325     return SQLITE_NOMEM;
   4326   }
   4327   memset(pCsr, 0, sizeof(*pCsr));
   4328   pCsr->iId = ++pTab->iNextCsrid;
   4329   pCsr->pCsrNext = pTab->pCsrList;
   4330   pTab->pCsrList = pCsr;
   4331   return SQLITE_OK;
   4332 }
   4333 
   4334 /*
   4335 ** Reset a cursor back to the state it was in when first returned
   4336 ** by zipfileOpen().
   4337 */
   4338 static void zipfileResetCursor(ZipfileCsr *pCsr){
   4339   sqlite3_free(pCsr->cds.zFile);
   4340   pCsr->cds.zFile = 0;
   4341   pCsr->bEof = 0;
   4342   if( pCsr->pFile ){
   4343     fclose(pCsr->pFile);
   4344     pCsr->pFile = 0;
   4345   }
   4346 }
   4347 
   4348 /*
   4349 ** Destructor for an ZipfileCsr.
   4350 */
   4351 static int zipfileClose(sqlite3_vtab_cursor *cur){
   4352   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   4353   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
   4354   ZipfileCsr **pp;
   4355   zipfileResetCursor(pCsr);
   4356 
   4357   /* Remove this cursor from the ZipfileTab.pCsrList list. */
   4358   for(pp=&pTab->pCsrList; *pp; pp=&((*pp)->pCsrNext)){
   4359     if( *pp==pCsr ){
   4360       *pp = pCsr->pCsrNext;
   4361       break;
   4362     }
   4363   }
   4364 
   4365   sqlite3_free(pCsr);
   4366   return SQLITE_OK;
   4367 }
   4368 
   4369 /*
   4370 ** Set the error message for the virtual table associated with cursor
   4371 ** pCsr to the results of vprintf(zFmt, ...).
   4372 */
   4373 static void zipfileSetErrmsg(ZipfileCsr *pCsr, const char *zFmt, ...){
   4374   va_list ap;
   4375   va_start(ap, zFmt);
   4376   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
   4377   va_end(ap);
   4378 }
   4379 
   4380 static int zipfileReadData(
   4381   FILE *pFile,                    /* Read from this file */
   4382   u8 *aRead,                      /* Read into this buffer */
   4383   int nRead,                      /* Number of bytes to read */
   4384   i64 iOff,                       /* Offset to read from */
   4385   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
   4386 ){
   4387   size_t n;
   4388   fseek(pFile, (long)iOff, SEEK_SET);
   4389   n = fread(aRead, 1, nRead, pFile);
   4390   if( (int)n!=nRead ){
   4391     *pzErrmsg = sqlite3_mprintf("error in fread()");
   4392     return SQLITE_ERROR;
   4393   }
   4394   return SQLITE_OK;
   4395 }
   4396 
   4397 static int zipfileAppendData(
   4398   ZipfileTab *pTab,
   4399   const u8 *aWrite,
   4400   int nWrite
   4401 ){
   4402   size_t n;
   4403   fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
   4404   n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
   4405   if( (int)n!=nWrite ){
   4406     pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
   4407     return SQLITE_ERROR;
   4408   }
   4409   pTab->szCurrent += nWrite;
   4410   return SQLITE_OK;
   4411 }
   4412 
   4413 static u16 zipfileGetU16(const u8 *aBuf){
   4414   return (aBuf[1] << 8) + aBuf[0];
   4415 }
   4416 static u32 zipfileGetU32(const u8 *aBuf){
   4417   return ((u32)(aBuf[3]) << 24)
   4418        + ((u32)(aBuf[2]) << 16)
   4419        + ((u32)(aBuf[1]) <<  8)
   4420        + ((u32)(aBuf[0]) <<  0);
   4421 }
   4422 
   4423 static void zipfilePutU16(u8 *aBuf, u16 val){
   4424   aBuf[0] = val & 0xFF;
   4425   aBuf[1] = (val>>8) & 0xFF;
   4426 }
   4427 static void zipfilePutU32(u8 *aBuf, u32 val){
   4428   aBuf[0] = val & 0xFF;
   4429   aBuf[1] = (val>>8) & 0xFF;
   4430   aBuf[2] = (val>>16) & 0xFF;
   4431   aBuf[3] = (val>>24) & 0xFF;
   4432 }
   4433 
   4434 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
   4435 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
   4436 
   4437 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
   4438 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
   4439 
   4440 static u8* zipfileCsrBuffer(ZipfileCsr *pCsr){
   4441   return ((ZipfileTab*)(pCsr->base.pVtab))->aBuffer;
   4442 }
   4443 
   4444 /*
   4445 ** Magic numbers used to read CDS records.
   4446 */
   4447 #define ZIPFILE_CDS_FIXED_SZ         46
   4448 #define ZIPFILE_CDS_NFILE_OFF        28
   4449 
   4450 /*
   4451 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
   4452 ** if the record is not well-formed, or SQLITE_OK otherwise.
   4453 */
   4454 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
   4455   u8 *aRead = aBuf;
   4456   u32 sig = zipfileRead32(aRead);
   4457   int rc = SQLITE_OK;
   4458   if( sig!=ZIPFILE_SIGNATURE_CDS ){
   4459     rc = SQLITE_ERROR;
   4460   }else{
   4461     pCDS->iVersionMadeBy = zipfileRead16(aRead);
   4462     pCDS->iVersionExtract = zipfileRead16(aRead);
   4463     pCDS->flags = zipfileRead16(aRead);
   4464     pCDS->iCompression = zipfileRead16(aRead);
   4465     pCDS->mTime = zipfileRead16(aRead);
   4466     pCDS->mDate = zipfileRead16(aRead);
   4467     pCDS->crc32 = zipfileRead32(aRead);
   4468     pCDS->szCompressed = zipfileRead32(aRead);
   4469     pCDS->szUncompressed = zipfileRead32(aRead);
   4470     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
   4471     pCDS->nFile = zipfileRead16(aRead);
   4472     pCDS->nExtra = zipfileRead16(aRead);
   4473     pCDS->nComment = zipfileRead16(aRead);
   4474     pCDS->iDiskStart = zipfileRead16(aRead);
   4475     pCDS->iInternalAttr = zipfileRead16(aRead);
   4476     pCDS->iExternalAttr = zipfileRead32(aRead);
   4477     pCDS->iOffset = zipfileRead32(aRead);
   4478     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
   4479   }
   4480 
   4481   return rc;
   4482 }
   4483 
   4484 /*
   4485 ** Read the CDS record for the current entry from disk into pCsr->cds.
   4486 */
   4487 static int zipfileCsrReadCDS(ZipfileCsr *pCsr){
   4488   char **pzErr = &pCsr->base.pVtab->zErrMsg;
   4489   u8 *aRead;
   4490   int rc = SQLITE_OK;
   4491 
   4492   sqlite3_free(pCsr->cds.zFile);
   4493   pCsr->cds.zFile = 0;
   4494 
   4495   if( pCsr->pCurrent==0 ){
   4496     aRead = zipfileCsrBuffer(pCsr);
   4497     rc = zipfileReadData(
   4498         pCsr->pFile, aRead, ZIPFILE_CDS_FIXED_SZ, pCsr->iNextOff, pzErr
   4499     );
   4500   }else{
   4501     aRead = pCsr->pCurrent->aCdsEntry;
   4502   }
   4503 
   4504   if( rc==SQLITE_OK ){
   4505     rc = zipfileReadCDS(aRead, &pCsr->cds);
   4506     if( rc!=SQLITE_OK ){
   4507       assert( pCsr->pCurrent==0 );
   4508       zipfileSetErrmsg(pCsr,"failed to read CDS at offset %lld",pCsr->iNextOff);
   4509     }else{
   4510       int nRead;
   4511       if( pCsr->pCurrent==0 ){
   4512         nRead = pCsr->cds.nFile + pCsr->cds.nExtra;
   4513         aRead = zipfileCsrBuffer(pCsr);
   4514         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
   4515         rc = zipfileReadData(pCsr->pFile, aRead, nRead, pCsr->iNextOff, pzErr);
   4516       }else{
   4517         aRead = &aRead[ZIPFILE_CDS_FIXED_SZ];
   4518       }
   4519 
   4520       if( rc==SQLITE_OK ){
   4521         pCsr->cds.zFile = sqlite3_mprintf("%.*s", (int)pCsr->cds.nFile, aRead);
   4522         pCsr->iNextOff += pCsr->cds.nFile;
   4523         pCsr->iNextOff += pCsr->cds.nExtra;
   4524         pCsr->iNextOff += pCsr->cds.nComment;
   4525       }
   4526 
   4527       /* Scan the cds.nExtra bytes of "extra" fields for any that can
   4528       ** be interpreted. The general format of an extra field is:
   4529       **
   4530       **   Header ID    2 bytes
   4531       **   Data Size    2 bytes
   4532       **   Data         N bytes
   4533       **
   4534       */
   4535       if( rc==SQLITE_OK ){
   4536         u8 *p = &aRead[pCsr->cds.nFile];
   4537         u8 *pEnd = &p[pCsr->cds.nExtra];
   4538 
   4539         while( p<pEnd ){
   4540           u16 id = zipfileRead16(p);
   4541           u16 nByte = zipfileRead16(p);
   4542 
   4543           switch( id ){
   4544             case ZIPFILE_EXTRA_TIMESTAMP: {
   4545               u8 b = p[0];
   4546               if( b & 0x01 ){     /* 0x01 -> modtime is present */
   4547                 pCsr->mTime = zipfileGetU32(&p[1]);
   4548                 pCsr->flags |= ZIPFILE_MTIME_VALID;
   4549               }
   4550               break;
   4551             }
   4552           }
   4553 
   4554           p += nByte;
   4555         }
   4556       }
   4557     }
   4558   }
   4559 
   4560   return rc;
   4561 }
   4562 
   4563 static FILE *zipfileGetFd(ZipfileCsr *pCsr){
   4564   if( pCsr->pFile ) return pCsr->pFile;
   4565   return ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
   4566 }
   4567 
   4568 static int zipfileReadLFH(
   4569   FILE *pFd,
   4570   i64 iOffset,
   4571   u8 *aTmp,
   4572   ZipfileLFH *pLFH,
   4573   char **pzErr
   4574 ){
   4575   u8 *aRead = aTmp;
   4576   static const int szFix = ZIPFILE_LFH_FIXED_SZ;
   4577   int rc;
   4578 
   4579   rc = zipfileReadData(pFd, aRead, szFix, iOffset, pzErr);
   4580   if( rc==SQLITE_OK ){
   4581     u32 sig = zipfileRead32(aRead);
   4582     if( sig!=ZIPFILE_SIGNATURE_LFH ){
   4583       *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", (int)iOffset);
   4584       rc = SQLITE_ERROR;
   4585     }else{
   4586       pLFH->iVersionExtract = zipfileRead16(aRead);
   4587       pLFH->flags = zipfileRead16(aRead);
   4588       pLFH->iCompression = zipfileRead16(aRead);
   4589       pLFH->mTime = zipfileRead16(aRead);
   4590       pLFH->mDate = zipfileRead16(aRead);
   4591       pLFH->crc32 = zipfileRead32(aRead);
   4592       pLFH->szCompressed = zipfileRead32(aRead);
   4593       pLFH->szUncompressed = zipfileRead32(aRead);
   4594       pLFH->nFile = zipfileRead16(aRead);
   4595       pLFH->nExtra = zipfileRead16(aRead);
   4596       assert( aRead==&aTmp[szFix] );
   4597     }
   4598   }
   4599   return rc;
   4600 }
   4601 
   4602 static int zipfileCsrReadLFH(ZipfileCsr *pCsr){
   4603   FILE *pFile = zipfileGetFd(pCsr);
   4604   char **pzErr = &pCsr->base.pVtab->zErrMsg;
   4605   u8 *aRead = zipfileCsrBuffer(pCsr);
   4606   int rc = zipfileReadLFH(pFile, pCsr->cds.iOffset, aRead, &pCsr->lfh, pzErr);
   4607   pCsr->iDataOff =  pCsr->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
   4608   pCsr->iDataOff += pCsr->lfh.nFile+pCsr->lfh.nExtra;
   4609   return rc;
   4610 }
   4611 
   4612 
   4613 /*
   4614 ** Advance an ZipfileCsr to its next row of output.
   4615 */
   4616 static int zipfileNext(sqlite3_vtab_cursor *cur){
   4617   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   4618   int rc = SQLITE_OK;
   4619   pCsr->flags = 0;
   4620 
   4621   if( pCsr->pCurrent==0 ){
   4622     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
   4623     if( pCsr->iNextOff>=iEof ){
   4624       pCsr->bEof = 1;
   4625     }
   4626   }else{
   4627     assert( pCsr->pFile==0 );
   4628     do {
   4629       pCsr->pCurrent = pCsr->pCurrent->pNext;
   4630     }while( pCsr->pCurrent && pCsr->pCurrent->bDeleted );
   4631     if( pCsr->pCurrent==0 ){
   4632       pCsr->bEof = 1;
   4633     }
   4634   }
   4635 
   4636   if( pCsr->bEof==0 ){
   4637     rc = zipfileCsrReadCDS(pCsr);
   4638     if( rc==SQLITE_OK ){
   4639       rc = zipfileCsrReadLFH(pCsr);
   4640     }
   4641   }
   4642 
   4643   return rc;
   4644 }
   4645 
   4646 /*
   4647 ** "Standard" MS-DOS time format:
   4648 **
   4649 **   File modification time:
   4650 **     Bits 00-04: seconds divided by 2
   4651 **     Bits 05-10: minute
   4652 **     Bits 11-15: hour
   4653 **   File modification date:
   4654 **     Bits 00-04: day
   4655 **     Bits 05-08: month (1-12)
   4656 **     Bits 09-15: years from 1980
   4657 */
   4658 static time_t zipfileMtime(ZipfileCsr *pCsr){
   4659   struct tm t;
   4660   memset(&t, 0, sizeof(t));
   4661   t.tm_sec = (pCsr->cds.mTime & 0x1F)*2;
   4662   t.tm_min = (pCsr->cds.mTime >> 5) & 0x2F;
   4663   t.tm_hour = (pCsr->cds.mTime >> 11) & 0x1F;
   4664 
   4665   t.tm_mday = (pCsr->cds.mDate & 0x1F);
   4666   t.tm_mon = ((pCsr->cds.mDate >> 5) & 0x0F) - 1;
   4667   t.tm_year = 80 + ((pCsr->cds.mDate >> 9) & 0x7F);
   4668 
   4669   return mktime(&t);
   4670 }
   4671 
   4672 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mTime){
   4673   time_t t = (time_t)mTime;
   4674   struct tm res;
   4675 
   4676 #if !defined(_WIN32) && !defined(WIN32)
   4677   localtime_r(&t, &res);
   4678 #else
   4679   memcpy(&res, localtime(&t), sizeof(struct tm));
   4680 #endif
   4681 
   4682   pCds->mTime = (u16)(
   4683     (res.tm_sec / 2) +
   4684     (res.tm_min << 5) +
   4685     (res.tm_hour << 11));
   4686 
   4687   pCds->mDate = (u16)(
   4688     (res.tm_mday-1) +
   4689     ((res.tm_mon+1) << 5) +
   4690     ((res.tm_year-80) << 9));
   4691 }
   4692 
   4693 static void zipfileInflate(
   4694   sqlite3_context *pCtx,          /* Store error here, if any */
   4695   const u8 *aIn,                  /* Compressed data */
   4696   int nIn,                        /* Size of buffer aIn[] in bytes */
   4697   int nOut                        /* Expected output size */
   4698 ){
   4699   u8 *aRes = sqlite3_malloc(nOut);
   4700   if( aRes==0 ){
   4701     sqlite3_result_error_nomem(pCtx);
   4702   }else{
   4703     int err;
   4704     z_stream str;
   4705     memset(&str, 0, sizeof(str));
   4706 
   4707     str.next_in = (Byte*)aIn;
   4708     str.avail_in = nIn;
   4709     str.next_out = (Byte*)aRes;
   4710     str.avail_out = nOut;
   4711 
   4712     err = inflateInit2(&str, -15);
   4713     if( err!=Z_OK ){
   4714       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
   4715     }else{
   4716       err = inflate(&str, Z_NO_FLUSH);
   4717       if( err!=Z_STREAM_END ){
   4718         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
   4719       }else{
   4720         sqlite3_result_blob(pCtx, aRes, nOut, SQLITE_TRANSIENT);
   4721       }
   4722     }
   4723     sqlite3_free(aRes);
   4724     inflateEnd(&str);
   4725   }
   4726 }
   4727 
   4728 static int zipfileDeflate(
   4729   ZipfileTab *pTab,               /* Set error message here */
   4730   const u8 *aIn, int nIn,         /* Input */
   4731   u8 **ppOut, int *pnOut          /* Output */
   4732 ){
   4733   int nAlloc = (int)compressBound(nIn);
   4734   u8 *aOut;
   4735   int rc = SQLITE_OK;
   4736 
   4737   aOut = (u8*)sqlite3_malloc(nAlloc);
   4738   if( aOut==0 ){
   4739     rc = SQLITE_NOMEM;
   4740   }else{
   4741     int res;
   4742     z_stream str;
   4743     memset(&str, 0, sizeof(str));
   4744     str.next_in = (Bytef*)aIn;
   4745     str.avail_in = nIn;
   4746     str.next_out = aOut;
   4747     str.avail_out = nAlloc;
   4748 
   4749     deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
   4750     res = deflate(&str, Z_FINISH);
   4751 
   4752     if( res==Z_STREAM_END ){
   4753       *ppOut = aOut;
   4754       *pnOut = (int)str.total_out;
   4755     }else{
   4756       sqlite3_free(aOut);
   4757       pTab->base.zErrMsg = sqlite3_mprintf("zipfile: deflate() error");
   4758       rc = SQLITE_ERROR;
   4759     }
   4760     deflateEnd(&str);
   4761   }
   4762 
   4763   return rc;
   4764 }
   4765 
   4766 
   4767 /*
   4768 ** Return values of columns for the row at which the series_cursor
   4769 ** is currently pointing.
   4770 */
   4771 static int zipfileColumn(
   4772   sqlite3_vtab_cursor *cur,   /* The cursor */
   4773   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   4774   int i                       /* Which column to return */
   4775 ){
   4776   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   4777   int rc = SQLITE_OK;
   4778   switch( i ){
   4779     case 0:   /* name */
   4780       sqlite3_result_text(ctx, pCsr->cds.zFile, -1, SQLITE_TRANSIENT);
   4781       break;
   4782     case 1:   /* mode */
   4783       /* TODO: Whether or not the following is correct surely depends on
   4784       ** the platform on which the archive was created.  */
   4785       sqlite3_result_int(ctx, pCsr->cds.iExternalAttr >> 16);
   4786       break;
   4787     case 2: { /* mtime */
   4788       if( pCsr->flags & ZIPFILE_MTIME_VALID ){
   4789         sqlite3_result_int64(ctx, pCsr->mTime);
   4790       }else{
   4791         sqlite3_result_int64(ctx, zipfileMtime(pCsr));
   4792       }
   4793       break;
   4794     }
   4795     case 3: { /* sz */
   4796       if( sqlite3_vtab_nochange(ctx)==0 ){
   4797         sqlite3_result_int64(ctx, pCsr->cds.szUncompressed);
   4798       }
   4799       break;
   4800     }
   4801     case 4:   /* rawdata */
   4802       if( sqlite3_vtab_nochange(ctx) ) break;
   4803     case 5: { /* data */
   4804       if( i==4 || pCsr->cds.iCompression==0 || pCsr->cds.iCompression==8 ){
   4805         int sz = pCsr->cds.szCompressed;
   4806         int szFinal = pCsr->cds.szUncompressed;
   4807         if( szFinal>0 ){
   4808           u8 *aBuf = sqlite3_malloc(sz);
   4809           if( aBuf==0 ){
   4810             rc = SQLITE_NOMEM;
   4811           }else{
   4812             FILE *pFile = zipfileGetFd(pCsr);
   4813             rc = zipfileReadData(pFile, aBuf, sz, pCsr->iDataOff,
   4814                 &pCsr->base.pVtab->zErrMsg
   4815             );
   4816           }
   4817           if( rc==SQLITE_OK ){
   4818             if( i==5 && pCsr->cds.iCompression ){
   4819               zipfileInflate(ctx, aBuf, sz, szFinal);
   4820             }else{
   4821               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
   4822             }
   4823             sqlite3_free(aBuf);
   4824           }
   4825         }else{
   4826           /* Figure out if this is a directory or a zero-sized file. Consider
   4827           ** it to be a directory either if the mode suggests so, or if
   4828           ** the final character in the name is '/'.  */
   4829           u32 mode = pCsr->cds.iExternalAttr >> 16;
   4830           if( !(mode & S_IFDIR) && pCsr->cds.zFile[pCsr->cds.nFile-1]!='/' ){
   4831             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
   4832           }
   4833         }
   4834       }
   4835       break;
   4836     }
   4837     case 6:   /* method */
   4838       sqlite3_result_int(ctx, pCsr->cds.iCompression);
   4839       break;
   4840     case 7:   /* z */
   4841       sqlite3_result_int64(ctx, pCsr->iId);
   4842       break;
   4843   }
   4844 
   4845   return rc;
   4846 }
   4847 
   4848 /*
   4849 ** Return the rowid for the current row.
   4850 */
   4851 static int zipfileRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   4852   assert( 0 );
   4853   return SQLITE_OK;
   4854 }
   4855 
   4856 /*
   4857 ** Return TRUE if the cursor has been moved off of the last
   4858 ** row of output.
   4859 */
   4860 static int zipfileEof(sqlite3_vtab_cursor *cur){
   4861   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   4862   return pCsr->bEof;
   4863 }
   4864 
   4865 /*
   4866 */
   4867 static int zipfileReadEOCD(
   4868   ZipfileTab *pTab,               /* Return errors here */
   4869   FILE *pFile,                    /* Read from this file */
   4870   ZipfileEOCD *pEOCD              /* Object to populate */
   4871 ){
   4872   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
   4873   i64 szFile;                     /* Total size of file in bytes */
   4874   int nRead;                      /* Bytes to read from file */
   4875   i64 iOff;                       /* Offset to read from */
   4876   int rc;
   4877 
   4878   fseek(pFile, 0, SEEK_END);
   4879   szFile = (i64)ftell(pFile);
   4880   if( szFile==0 ){
   4881     memset(pEOCD, 0, sizeof(ZipfileEOCD));
   4882     return SQLITE_OK;
   4883   }
   4884   nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
   4885   iOff = szFile - nRead;
   4886 
   4887   rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
   4888   if( rc==SQLITE_OK ){
   4889     int i;
   4890 
   4891     /* Scan backwards looking for the signature bytes */
   4892     for(i=nRead-20; i>=0; i--){
   4893       if( aRead[i]==0x50 && aRead[i+1]==0x4b
   4894        && aRead[i+2]==0x05 && aRead[i+3]==0x06
   4895       ){
   4896         break;
   4897       }
   4898     }
   4899     if( i<0 ){
   4900       pTab->base.zErrMsg = sqlite3_mprintf(
   4901           "cannot find end of central directory record"
   4902       );
   4903       return SQLITE_ERROR;
   4904     }
   4905 
   4906     aRead += i+4;
   4907     pEOCD->iDisk = zipfileRead16(aRead);
   4908     pEOCD->iFirstDisk = zipfileRead16(aRead);
   4909     pEOCD->nEntry = zipfileRead16(aRead);
   4910     pEOCD->nEntryTotal = zipfileRead16(aRead);
   4911     pEOCD->nSize = zipfileRead32(aRead);
   4912     pEOCD->iOffset = zipfileRead32(aRead);
   4913 
   4914 #if 0
   4915     printf("iDisk=%d  iFirstDisk=%d  nEntry=%d  "
   4916            "nEntryTotal=%d  nSize=%d  iOffset=%d",
   4917            (int)pEOCD->iDisk, (int)pEOCD->iFirstDisk, (int)pEOCD->nEntry,
   4918            (int)pEOCD->nEntryTotal, (int)pEOCD->nSize, (int)pEOCD->iOffset
   4919     );
   4920 #endif
   4921   }
   4922 
   4923   return SQLITE_OK;
   4924 }
   4925 
   4926 /*
   4927 ** xFilter callback.
   4928 */
   4929 static int zipfileFilter(
   4930   sqlite3_vtab_cursor *cur,
   4931   int idxNum, const char *idxStr,
   4932   int argc, sqlite3_value **argv
   4933 ){
   4934   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
   4935   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   4936   const char *zFile;              /* Zip file to scan */
   4937   int rc = SQLITE_OK;             /* Return Code */
   4938 
   4939   zipfileResetCursor(pCsr);
   4940 
   4941   if( pTab->zFile ){
   4942     zFile = pTab->zFile;
   4943   }else if( idxNum==0 ){
   4944     /* Error. This is an eponymous virtual table and the user has not
   4945     ** supplied a file name. */
   4946     zipfileSetErrmsg(pCsr, "table function zipfile() requires an argument");
   4947     return SQLITE_ERROR;
   4948   }else{
   4949     zFile = (const char*)sqlite3_value_text(argv[0]);
   4950   }
   4951 
   4952   if( pTab->pWriteFd==0 ){
   4953     pCsr->pFile = fopen(zFile, "rb");
   4954     if( pCsr->pFile==0 ){
   4955       zipfileSetErrmsg(pCsr, "cannot open file: %s", zFile);
   4956       rc = SQLITE_ERROR;
   4957     }else{
   4958       rc = zipfileReadEOCD(pTab, pCsr->pFile, &pCsr->eocd);
   4959       if( rc==SQLITE_OK ){
   4960         if( pCsr->eocd.nEntry==0 ){
   4961           pCsr->bEof = 1;
   4962         }else{
   4963           pCsr->iNextOff = pCsr->eocd.iOffset;
   4964           rc = zipfileNext(cur);
   4965         }
   4966       }
   4967     }
   4968   }else{
   4969     ZipfileEntry e;
   4970     memset(&e, 0, sizeof(e));
   4971     e.pNext = pTab->pFirstEntry;
   4972     pCsr->pCurrent = &e;
   4973     rc = zipfileNext(cur);
   4974     assert( pCsr->pCurrent!=&e );
   4975   }
   4976 
   4977   return rc;
   4978 }
   4979 
   4980 /*
   4981 ** xBestIndex callback.
   4982 */
   4983 static int zipfileBestIndex(
   4984   sqlite3_vtab *tab,
   4985   sqlite3_index_info *pIdxInfo
   4986 ){
   4987   int i;
   4988 
   4989   for(i=0; i<pIdxInfo->nConstraint; i++){
   4990     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
   4991     if( pCons->usable==0 ) continue;
   4992     if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   4993     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
   4994     break;
   4995   }
   4996 
   4997   if( i<pIdxInfo->nConstraint ){
   4998     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
   4999     pIdxInfo->aConstraintUsage[i].omit = 1;
   5000     pIdxInfo->estimatedCost = 1000.0;
   5001     pIdxInfo->idxNum = 1;
   5002   }else{
   5003     pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
   5004     pIdxInfo->idxNum = 0;
   5005   }
   5006 
   5007   return SQLITE_OK;
   5008 }
   5009 
   5010 /*
   5011 ** Add object pNew to the end of the linked list that begins at
   5012 ** ZipfileTab.pFirstEntry and ends with pLastEntry.
   5013 */
   5014 static void zipfileAddEntry(
   5015   ZipfileTab *pTab,
   5016   ZipfileEntry *pBefore,
   5017   ZipfileEntry *pNew
   5018 ){
   5019   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
   5020   assert( pNew->pNext==0 );
   5021   if( pBefore==0 ){
   5022     if( pTab->pFirstEntry==0 ){
   5023       pTab->pFirstEntry = pTab->pLastEntry = pNew;
   5024     }else{
   5025       assert( pTab->pLastEntry->pNext==0 );
   5026       pTab->pLastEntry->pNext = pNew;
   5027       pTab->pLastEntry = pNew;
   5028     }
   5029   }else{
   5030     ZipfileEntry **pp;
   5031     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
   5032     pNew->pNext = pBefore;
   5033     *pp = pNew;
   5034   }
   5035 }
   5036 
   5037 static int zipfileLoadDirectory(ZipfileTab *pTab){
   5038   ZipfileEOCD eocd;
   5039   int rc;
   5040 
   5041   rc = zipfileReadEOCD(pTab, pTab->pWriteFd, &eocd);
   5042   if( rc==SQLITE_OK && eocd.nEntry>0 ){
   5043     int i;
   5044     int iOff = 0;
   5045     u8 *aBuf = sqlite3_malloc(eocd.nSize);
   5046     if( aBuf==0 ){
   5047       rc = SQLITE_NOMEM;
   5048     }else{
   5049       rc = zipfileReadData(
   5050           pTab->pWriteFd, aBuf, eocd.nSize, eocd.iOffset, &pTab->base.zErrMsg
   5051       );
   5052     }
   5053 
   5054     for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
   5055       u16 nFile;
   5056       u16 nExtra;
   5057       u16 nComment;
   5058       ZipfileEntry *pNew;
   5059       u8 *aRec = &aBuf[iOff];
   5060 
   5061       nFile = zipfileGetU16(&aRec[ZIPFILE_CDS_NFILE_OFF]);
   5062       nExtra = zipfileGetU16(&aRec[ZIPFILE_CDS_NFILE_OFF+2]);
   5063       nComment = zipfileGetU16(&aRec[ZIPFILE_CDS_NFILE_OFF+4]);
   5064 
   5065       pNew = sqlite3_malloc(
   5066           sizeof(ZipfileEntry)
   5067         + nFile+1
   5068         + ZIPFILE_CDS_FIXED_SZ+nFile+nExtra+nComment
   5069       );
   5070       if( pNew==0 ){
   5071         rc = SQLITE_NOMEM;
   5072       }else{
   5073         memset(pNew, 0, sizeof(ZipfileEntry));
   5074         pNew->zPath = (char*)&pNew[1];
   5075         memcpy(pNew->zPath, &aRec[ZIPFILE_CDS_FIXED_SZ], nFile);
   5076         pNew->zPath[nFile] = '\0';
   5077         pNew->aCdsEntry = (u8*)&pNew->zPath[nFile+1];
   5078         pNew->nCdsEntry = ZIPFILE_CDS_FIXED_SZ+nFile+nExtra+nComment;
   5079         memcpy(pNew->aCdsEntry, aRec, pNew->nCdsEntry);
   5080         zipfileAddEntry(pTab, 0, pNew);
   5081       }
   5082 
   5083       iOff += ZIPFILE_CDS_FIXED_SZ+nFile+nExtra+nComment;
   5084     }
   5085 
   5086     sqlite3_free(aBuf);
   5087   }
   5088 
   5089   return rc;
   5090 }
   5091 
   5092 static ZipfileEntry *zipfileNewEntry(
   5093   ZipfileCDS *pCds,               /* Values for fixed size part of CDS */
   5094   const char *zPath,              /* Path for new entry */
   5095   int nPath,                      /* strlen(zPath) */
   5096   u32 mTime                       /* Modification time (or 0) */
   5097 ){
   5098   u8 *aWrite;
   5099   ZipfileEntry *pNew;
   5100   pCds->nFile = (u16)nPath;
   5101   pCds->nExtra = mTime ? 9 : 0;
   5102   pNew = (ZipfileEntry*)sqlite3_malloc(
   5103     sizeof(ZipfileEntry) +
   5104     nPath+1 +
   5105     ZIPFILE_CDS_FIXED_SZ + nPath + pCds->nExtra
   5106   );
   5107 
   5108   if( pNew ){
   5109     memset(pNew, 0, sizeof(ZipfileEntry));
   5110     pNew->zPath = (char*)&pNew[1];
   5111     pNew->aCdsEntry = (u8*)&pNew->zPath[nPath+1];
   5112     pNew->nCdsEntry = ZIPFILE_CDS_FIXED_SZ + nPath + pCds->nExtra;
   5113     memcpy(pNew->zPath, zPath, nPath+1);
   5114 
   5115     aWrite = pNew->aCdsEntry;
   5116     zipfileWrite32(aWrite, ZIPFILE_SIGNATURE_CDS);
   5117     zipfileWrite16(aWrite, pCds->iVersionMadeBy);
   5118     zipfileWrite16(aWrite, pCds->iVersionExtract);
   5119     zipfileWrite16(aWrite, pCds->flags);
   5120     zipfileWrite16(aWrite, pCds->iCompression);
   5121     zipfileWrite16(aWrite, pCds->mTime);
   5122     zipfileWrite16(aWrite, pCds->mDate);
   5123     zipfileWrite32(aWrite, pCds->crc32);
   5124     zipfileWrite32(aWrite, pCds->szCompressed);
   5125     zipfileWrite32(aWrite, pCds->szUncompressed);
   5126     zipfileWrite16(aWrite, pCds->nFile);
   5127     zipfileWrite16(aWrite, pCds->nExtra);
   5128     zipfileWrite16(aWrite, pCds->nComment);      assert( pCds->nComment==0 );
   5129     zipfileWrite16(aWrite, pCds->iDiskStart);
   5130     zipfileWrite16(aWrite, pCds->iInternalAttr);
   5131     zipfileWrite32(aWrite, pCds->iExternalAttr);
   5132     zipfileWrite32(aWrite, pCds->iOffset);
   5133     assert( aWrite==&pNew->aCdsEntry[ZIPFILE_CDS_FIXED_SZ] );
   5134     memcpy(aWrite, zPath, nPath);
   5135     if( pCds->nExtra ){
   5136       aWrite += nPath;
   5137       zipfileWrite16(aWrite, ZIPFILE_EXTRA_TIMESTAMP);
   5138       zipfileWrite16(aWrite, 5);
   5139       *aWrite++ = 0x01;
   5140       zipfileWrite32(aWrite, mTime);
   5141     }
   5142   }
   5143 
   5144   return pNew;
   5145 }
   5146 
   5147 static int zipfileAppendEntry(
   5148   ZipfileTab *pTab,
   5149   ZipfileCDS *pCds,
   5150   const char *zPath,              /* Path for new entry */
   5151   int nPath,                      /* strlen(zPath) */
   5152   const u8 *pData,
   5153   int nData,
   5154   u32 mTime
   5155 ){
   5156   u8 *aBuf = pTab->aBuffer;
   5157   int rc;
   5158 
   5159   zipfileWrite32(aBuf, ZIPFILE_SIGNATURE_LFH);
   5160   zipfileWrite16(aBuf, pCds->iVersionExtract);
   5161   zipfileWrite16(aBuf, pCds->flags);
   5162   zipfileWrite16(aBuf, pCds->iCompression);
   5163   zipfileWrite16(aBuf, pCds->mTime);
   5164   zipfileWrite16(aBuf, pCds->mDate);
   5165   zipfileWrite32(aBuf, pCds->crc32);
   5166   zipfileWrite32(aBuf, pCds->szCompressed);
   5167   zipfileWrite32(aBuf, pCds->szUncompressed);
   5168   zipfileWrite16(aBuf, (u16)nPath);
   5169   zipfileWrite16(aBuf, pCds->nExtra);
   5170   assert( aBuf==&pTab->aBuffer[ZIPFILE_LFH_FIXED_SZ] );
   5171   rc = zipfileAppendData(pTab, pTab->aBuffer, (int)(aBuf - pTab->aBuffer));
   5172   if( rc==SQLITE_OK ){
   5173     rc = zipfileAppendData(pTab, (const u8*)zPath, nPath);
   5174   }
   5175 
   5176   if( rc==SQLITE_OK && pCds->nExtra ){
   5177     aBuf = pTab->aBuffer;
   5178     zipfileWrite16(aBuf, ZIPFILE_EXTRA_TIMESTAMP);
   5179     zipfileWrite16(aBuf, 5);
   5180     *aBuf++ = 0x01;
   5181     zipfileWrite32(aBuf, mTime);
   5182     rc = zipfileAppendData(pTab, pTab->aBuffer, 9);
   5183   }
   5184 
   5185   if( rc==SQLITE_OK ){
   5186     rc = zipfileAppendData(pTab, pData, nData);
   5187   }
   5188 
   5189   return rc;
   5190 }
   5191 
   5192 static int zipfileGetMode(
   5193   ZipfileTab *pTab,
   5194   sqlite3_value *pVal,
   5195   u32 defaultMode,                /* Value to use if pVal IS NULL */
   5196   u32 *pMode
   5197 ){
   5198   const char *z = (const char*)sqlite3_value_text(pVal);
   5199   u32 mode = 0;
   5200   if( z==0 ){
   5201     mode = defaultMode;
   5202   }else if( z[0]>='0' && z[0]<='9' ){
   5203     mode = (unsigned int)sqlite3_value_int(pVal);
   5204   }else{
   5205     const char zTemplate[11] = "-rwxrwxrwx";
   5206     int i;
   5207     if( strlen(z)!=10 ) goto parse_error;
   5208     switch( z[0] ){
   5209       case '-': mode |= S_IFREG; break;
   5210       case 'd': mode |= S_IFDIR; break;
   5211 #if !defined(_WIN32) && !defined(WIN32)
   5212       case 'l': mode |= S_IFLNK; break;
   5213 #endif
   5214       default: goto parse_error;
   5215     }
   5216     for(i=1; i<10; i++){
   5217       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
   5218       else if( z[i]!='-' ) goto parse_error;
   5219     }
   5220   }
   5221   *pMode = mode;
   5222   return SQLITE_OK;
   5223 
   5224  parse_error:
   5225   pTab->base.zErrMsg = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
   5226   return SQLITE_ERROR;
   5227 }
   5228 
   5229 /*
   5230 ** Both (const char*) arguments point to nul-terminated strings. Argument
   5231 ** nB is the value of strlen(zB). This function returns 0 if the strings are
   5232 ** identical, ignoring any trailing '/' character in either path.  */
   5233 static int zipfileComparePath(const char *zA, const char *zB, int nB){
   5234   int nA = (int)strlen(zA);
   5235   if( zA[nA-1]=='/' ) nA--;
   5236   if( zB[nB-1]=='/' ) nB--;
   5237   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
   5238   return 1;
   5239 }
   5240 
   5241 /*
   5242 ** xUpdate method.
   5243 */
   5244 static int zipfileUpdate(
   5245   sqlite3_vtab *pVtab,
   5246   int nVal,
   5247   sqlite3_value **apVal,
   5248   sqlite_int64 *pRowid
   5249 ){
   5250   ZipfileTab *pTab = (ZipfileTab*)pVtab;
   5251   int rc = SQLITE_OK;             /* Return Code */
   5252   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
   5253 
   5254   u32 mode = 0;                   /* Mode for new entry */
   5255   i64 mTime = 0;                  /* Modification time for new entry */
   5256   i64 sz = 0;                     /* Uncompressed size */
   5257   const char *zPath = 0;          /* Path for new entry */
   5258   int nPath = 0;                  /* strlen(zPath) */
   5259   const u8 *pData = 0;            /* Pointer to buffer containing content */
   5260   int nData = 0;                  /* Size of pData buffer in bytes */
   5261   int iMethod = 0;                /* Compression method for new entry */
   5262   u8 *pFree = 0;                  /* Free this */
   5263   char *zFree = 0;                /* Also free this */
   5264   ZipfileCDS cds;                 /* New Central Directory Structure entry */
   5265   ZipfileEntry *pOld = 0;
   5266   int bIsDir = 0;
   5267   u32 iCrc32 = 0;
   5268 
   5269   assert( pTab->zFile );
   5270   assert( pTab->pWriteFd );
   5271 
   5272   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   5273     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
   5274     int nDelete = (int)strlen(zDelete);
   5275     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
   5276       if( pOld->bDeleted ) continue;
   5277       if( zipfileComparePath(pOld->zPath, zDelete, nDelete)==0 ){
   5278         pOld->bDeleted = 1;
   5279         break;
   5280       }
   5281       assert( pOld->pNext );
   5282     }
   5283     if( nVal==1 ) return SQLITE_OK;
   5284   }
   5285 
   5286   /* Check that "sz" and "rawdata" are both NULL: */
   5287   if( sqlite3_value_type(apVal[5])!=SQLITE_NULL
   5288    || sqlite3_value_type(apVal[6])!=SQLITE_NULL
   5289   ){
   5290     rc = SQLITE_CONSTRAINT;
   5291   }
   5292 
   5293   if( rc==SQLITE_OK ){
   5294     if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
   5295       /* data=NULL. A directory */
   5296       bIsDir = 1;
   5297     }else{
   5298       /* Value specified for "data", and possibly "method". This must be
   5299       ** a regular file or a symlink. */
   5300       const u8 *aIn = sqlite3_value_blob(apVal[7]);
   5301       int nIn = sqlite3_value_bytes(apVal[7]);
   5302       int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
   5303 
   5304       iMethod = sqlite3_value_int(apVal[8]);
   5305       sz = nIn;
   5306       pData = aIn;
   5307       nData = nIn;
   5308       if( iMethod!=0 && iMethod!=8 ){
   5309         rc = SQLITE_CONSTRAINT;
   5310       }else{
   5311         if( bAuto || iMethod ){
   5312           int nCmp;
   5313           rc = zipfileDeflate(pTab, aIn, nIn, &pFree, &nCmp);
   5314           if( rc==SQLITE_OK ){
   5315             if( iMethod || nCmp<nIn ){
   5316               iMethod = 8;
   5317               pData = pFree;
   5318               nData = nCmp;
   5319             }
   5320           }
   5321         }
   5322         iCrc32 = crc32(0, aIn, nIn);
   5323       }
   5324     }
   5325   }
   5326 
   5327   if( rc==SQLITE_OK ){
   5328     rc = zipfileGetMode(pTab, apVal[3],
   5329         (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)), &mode
   5330     );
   5331     if( rc==SQLITE_OK && (bIsDir == ((mode & S_IFDIR)==0)) ){
   5332       /* The "mode" attribute is a directory, but data has been specified.
   5333       ** Or vice-versa - no data but "mode" is a file or symlink.  */
   5334       rc = SQLITE_CONSTRAINT;
   5335     }
   5336   }
   5337 
   5338   if( rc==SQLITE_OK ){
   5339     zPath = (const char*)sqlite3_value_text(apVal[2]);
   5340     nPath = (int)strlen(zPath);
   5341     if( sqlite3_value_type(apVal[4])==SQLITE_NULL ){
   5342       mTime = (sqlite3_int64)time(0);
   5343     }else{
   5344       mTime = sqlite3_value_int64(apVal[4]);
   5345     }
   5346   }
   5347 
   5348   if( rc==SQLITE_OK && bIsDir ){
   5349     /* For a directory, check that the last character in the path is a
   5350     ** '/'. This appears to be required for compatibility with info-zip
   5351     ** (the unzip command on unix). It does not create directories
   5352     ** otherwise.  */
   5353     if( zPath[nPath-1]!='/' ){
   5354       zFree = sqlite3_mprintf("%s/", zPath);
   5355       if( zFree==0 ){ rc = SQLITE_NOMEM; }
   5356       zPath = (const char*)zFree;
   5357       nPath++;
   5358     }
   5359   }
   5360 
   5361   /* Check that we're not inserting a duplicate entry */
   5362   if( rc==SQLITE_OK ){
   5363     ZipfileEntry *p;
   5364     for(p=pTab->pFirstEntry; p; p=p->pNext){
   5365       if( p->bDeleted ) continue;
   5366       if( zipfileComparePath(p->zPath, zPath, nPath)==0 ){
   5367         rc = SQLITE_CONSTRAINT;
   5368         break;
   5369       }
   5370     }
   5371   }
   5372 
   5373   if( rc==SQLITE_OK ){
   5374     /* Create the new CDS record. */
   5375     memset(&cds, 0, sizeof(cds));
   5376     cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
   5377     cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
   5378     cds.flags = ZIPFILE_NEWENTRY_FLAGS;
   5379     cds.iCompression = (u16)iMethod;
   5380     zipfileMtimeToDos(&cds, (u32)mTime);
   5381     cds.crc32 = iCrc32;
   5382     cds.szCompressed = nData;
   5383     cds.szUncompressed = (u32)sz;
   5384     cds.iExternalAttr = (mode<<16);
   5385     cds.iOffset = (u32)pTab->szCurrent;
   5386     pNew = zipfileNewEntry(&cds, zPath, nPath, (u32)mTime);
   5387     if( pNew==0 ){
   5388       rc = SQLITE_NOMEM;
   5389     }else{
   5390       zipfileAddEntry(pTab, pOld, pNew);
   5391     }
   5392   }
   5393 
   5394   /* Append the new header+file to the archive */
   5395   if( rc==SQLITE_OK ){
   5396     rc = zipfileAppendEntry(pTab, &cds, zPath, nPath, pData, nData, (u32)mTime);
   5397   }
   5398 
   5399   if( rc!=SQLITE_OK && pOld ){
   5400     pOld->bDeleted = 0;
   5401   }
   5402   sqlite3_free(pFree);
   5403   sqlite3_free(zFree);
   5404   return rc;
   5405 }
   5406 
   5407 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
   5408   u8 *aBuf = pTab->aBuffer;
   5409 
   5410   zipfileWrite32(aBuf, ZIPFILE_SIGNATURE_EOCD);
   5411   zipfileWrite16(aBuf, p->iDisk);
   5412   zipfileWrite16(aBuf, p->iFirstDisk);
   5413   zipfileWrite16(aBuf, p->nEntry);
   5414   zipfileWrite16(aBuf, p->nEntryTotal);
   5415   zipfileWrite32(aBuf, p->nSize);
   5416   zipfileWrite32(aBuf, p->iOffset);
   5417   zipfileWrite16(aBuf, 0);        /* Size of trailing comment in bytes*/
   5418 
   5419   assert( (aBuf-pTab->aBuffer)==22 );
   5420   return zipfileAppendData(pTab, pTab->aBuffer, (int)(aBuf - pTab->aBuffer));
   5421 }
   5422 
   5423 static void zipfileCleanupTransaction(ZipfileTab *pTab){
   5424   ZipfileEntry *pEntry;
   5425   ZipfileEntry *pNext;
   5426 
   5427   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
   5428     pNext = pEntry->pNext;
   5429     sqlite3_free(pEntry);
   5430   }
   5431   pTab->pFirstEntry = 0;
   5432   pTab->pLastEntry = 0;
   5433   fclose(pTab->pWriteFd);
   5434   pTab->pWriteFd = 0;
   5435   pTab->szCurrent = 0;
   5436   pTab->szOrig = 0;
   5437 }
   5438 
   5439 static int zipfileBegin(sqlite3_vtab *pVtab){
   5440   ZipfileTab *pTab = (ZipfileTab*)pVtab;
   5441   int rc = SQLITE_OK;
   5442 
   5443   assert( pTab->pWriteFd==0 );
   5444 
   5445   /* This table is only writable if a default archive path was specified
   5446   ** as part of the CREATE VIRTUAL TABLE statement. */
   5447   if( pTab->zFile==0 ){
   5448     pTab->base.zErrMsg = sqlite3_mprintf(
   5449         "zipfile: writing requires a default archive"
   5450     );
   5451     return SQLITE_ERROR;
   5452   }
   5453 
   5454   /* Open a write fd on the file. Also load the entire central directory
   5455   ** structure into memory. During the transaction any new file data is
   5456   ** appended to the archive file, but the central directory is accumulated
   5457   ** in main-memory until the transaction is committed.  */
   5458   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
   5459   if( pTab->pWriteFd==0 ){
   5460     pTab->base.zErrMsg = sqlite3_mprintf(
   5461         "zipfile: failed to open file %s for writing", pTab->zFile
   5462     );
   5463     rc = SQLITE_ERROR;
   5464   }else{
   5465     fseek(pTab->pWriteFd, 0, SEEK_END);
   5466     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
   5467     rc = zipfileLoadDirectory(pTab);
   5468   }
   5469 
   5470   if( rc!=SQLITE_OK ){
   5471     zipfileCleanupTransaction(pTab);
   5472   }
   5473 
   5474   return rc;
   5475 }
   5476 
   5477 static int zipfileCommit(sqlite3_vtab *pVtab){
   5478   ZipfileTab *pTab = (ZipfileTab*)pVtab;
   5479   int rc = SQLITE_OK;
   5480   if( pTab->pWriteFd ){
   5481     i64 iOffset = pTab->szCurrent;
   5482     ZipfileEntry *p;
   5483     ZipfileEOCD eocd;
   5484     int nEntry = 0;
   5485 
   5486     /* Write out all undeleted entries */
   5487     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
   5488       if( p->bDeleted ) continue;
   5489       rc = zipfileAppendData(pTab, p->aCdsEntry, p->nCdsEntry);
   5490       nEntry++;
   5491     }
   5492 
   5493     /* Write out the EOCD record */
   5494     eocd.iDisk = 0;
   5495     eocd.iFirstDisk = 0;
   5496     eocd.nEntry = (u16)nEntry;
   5497     eocd.nEntryTotal = (u16)nEntry;
   5498     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
   5499     eocd.iOffset = (u32)iOffset;
   5500     rc = zipfileAppendEOCD(pTab, &eocd);
   5501 
   5502     zipfileCleanupTransaction(pTab);
   5503   }
   5504   return rc;
   5505 }
   5506 
   5507 static int zipfileRollback(sqlite3_vtab *pVtab){
   5508   return zipfileCommit(pVtab);
   5509 }
   5510 
   5511 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
   5512   ZipfileCsr *pCsr;
   5513   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
   5514     if( iId==pCsr->iId ) break;
   5515   }
   5516   return pCsr;
   5517 }
   5518 
   5519 static void zipfileFunctionCds(
   5520   sqlite3_context *context,
   5521   int argc,
   5522   sqlite3_value **argv
   5523 ){
   5524   ZipfileCsr *pCsr;
   5525   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
   5526   assert( argc>0 );
   5527 
   5528   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
   5529   if( pCsr ){
   5530     ZipfileCDS *p = &pCsr->cds;
   5531     char *zRes = sqlite3_mprintf("{"
   5532         "\"version-made-by\" : %u, "
   5533         "\"version-to-extract\" : %u, "
   5534         "\"flags\" : %u, "
   5535         "\"compression\" : %u, "
   5536         "\"time\" : %u, "
   5537         "\"date\" : %u, "
   5538         "\"crc32\" : %u, "
   5539         "\"compressed-size\" : %u, "
   5540         "\"uncompressed-size\" : %u, "
   5541         "\"file-name-length\" : %u, "
   5542         "\"extra-field-length\" : %u, "
   5543         "\"file-comment-length\" : %u, "
   5544         "\"disk-number-start\" : %u, "
   5545         "\"internal-attr\" : %u, "
   5546         "\"external-attr\" : %u, "
   5547         "\"offset\" : %u }",
   5548         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
   5549         (u32)p->flags, (u32)p->iCompression,
   5550         (u32)p->mTime, (u32)p->mDate,
   5551         (u32)p->crc32, (u32)p->szCompressed,
   5552         (u32)p->szUncompressed, (u32)p->nFile,
   5553         (u32)p->nExtra, (u32)p->nComment,
   5554         (u32)p->iDiskStart, (u32)p->iInternalAttr,
   5555         (u32)p->iExternalAttr, (u32)p->iOffset
   5556     );
   5557 
   5558     if( zRes==0 ){
   5559       sqlite3_result_error_nomem(context);
   5560     }else{
   5561       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
   5562       sqlite3_free(zRes);
   5563     }
   5564   }
   5565 }
   5566 
   5567 
   5568 /*
   5569 ** xFindFunction method.
   5570 */
   5571 static int zipfileFindFunction(
   5572   sqlite3_vtab *pVtab,            /* Virtual table handle */
   5573   int nArg,                       /* Number of SQL function arguments */
   5574   const char *zName,              /* Name of SQL function */
   5575   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   5576   void **ppArg                    /* OUT: User data for *pxFunc */
   5577 ){
   5578   if( nArg>0 ){
   5579     if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
   5580       *pxFunc = zipfileFunctionCds;
   5581       *ppArg = (void*)pVtab;
   5582       return 1;
   5583     }
   5584   }
   5585 
   5586   return 0;
   5587 }
   5588 
   5589 /*
   5590 ** Register the "zipfile" virtual table.
   5591 */
   5592 static int zipfileRegister(sqlite3 *db){
   5593   static sqlite3_module zipfileModule = {
   5594     1,                         /* iVersion */
   5595     zipfileConnect,            /* xCreate */
   5596     zipfileConnect,            /* xConnect */
   5597     zipfileBestIndex,          /* xBestIndex */
   5598     zipfileDisconnect,         /* xDisconnect */
   5599     zipfileDisconnect,         /* xDestroy */
   5600     zipfileOpen,               /* xOpen - open a cursor */
   5601     zipfileClose,              /* xClose - close a cursor */
   5602     zipfileFilter,             /* xFilter - configure scan constraints */
   5603     zipfileNext,               /* xNext - advance a cursor */
   5604     zipfileEof,                /* xEof - check for end of scan */
   5605     zipfileColumn,             /* xColumn - read data */
   5606     zipfileRowid,              /* xRowid - read data */
   5607     zipfileUpdate,             /* xUpdate */
   5608     zipfileBegin,              /* xBegin */
   5609     0,                         /* xSync */
   5610     zipfileCommit,             /* xCommit */
   5611     zipfileRollback,           /* xRollback */
   5612     zipfileFindFunction,       /* xFindMethod */
   5613     0,                         /* xRename */
   5614   };
   5615 
   5616   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
   5617   if( rc==SQLITE_OK ){
   5618     rc = sqlite3_overload_function(db, "zipfile_cds", -1);
   5619   }
   5620   return rc;
   5621 }
   5622 #else         /* SQLITE_OMIT_VIRTUALTABLE */
   5623 # define zipfileRegister(x) SQLITE_OK
   5624 #endif
   5625 
   5626 #ifdef _WIN32
   5627 
   5628 #endif
   5629 int sqlite3_zipfile_init(
   5630   sqlite3 *db,
   5631   char **pzErrMsg,
   5632   const sqlite3_api_routines *pApi
   5633 ){
   5634   SQLITE_EXTENSION_INIT2(pApi);
   5635   (void)pzErrMsg;  /* Unused parameter */
   5636   return zipfileRegister(db);
   5637 }
   5638 
   5639 /************************* End ../ext/misc/zipfile.c ********************/
   5640 /************************* Begin ../ext/misc/sqlar.c ******************/
   5641 /*
   5642 ** 2017-12-17
   5643 **
   5644 ** The author disclaims copyright to this source code.  In place of
   5645 ** a legal notice, here is a blessing:
   5646 **
   5647 **    May you do good and not evil.
   5648 **    May you find forgiveness for yourself and forgive others.
   5649 **    May you share freely, never taking more than you give.
   5650 **
   5651 ******************************************************************************
   5652 **
   5653 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
   5654 ** for working with sqlar archives and used by the shell tool's built-in
   5655 ** sqlar support.
   5656 */
   5657 SQLITE_EXTENSION_INIT1
   5658 #include <zlib.h>
   5659 
   5660 /*
   5661 ** Implementation of the "sqlar_compress(X)" SQL function.
   5662 **
   5663 ** If the type of X is SQLITE_BLOB, and compressing that blob using
   5664 ** zlib utility function compress() yields a smaller blob, return the
   5665 ** compressed blob. Otherwise, return a copy of X.
   5666 **
   5667 ** SQLar uses the "zlib format" for compressed content.  The zlib format
   5668 ** contains a two-byte identification header and a four-byte checksum at
   5669 ** the end.  This is different from ZIP which uses the raw deflate format.
   5670 **
   5671 ** Future enhancements to SQLar might add support for new compression formats.
   5672 ** If so, those new formats will be identified by alternative headers in the
   5673 ** compressed data.
   5674 */
   5675 static void sqlarCompressFunc(
   5676   sqlite3_context *context,
   5677   int argc,
   5678   sqlite3_value **argv
   5679 ){
   5680   assert( argc==1 );
   5681   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
   5682     const Bytef *pData = sqlite3_value_blob(argv[0]);
   5683     uLong nData = sqlite3_value_bytes(argv[0]);
   5684     uLongf nOut = compressBound(nData);
   5685     Bytef *pOut;
   5686 
   5687     pOut = (Bytef*)sqlite3_malloc(nOut);
   5688     if( pOut==0 ){
   5689       sqlite3_result_error_nomem(context);
   5690       return;
   5691     }else{
   5692       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
   5693         sqlite3_result_error(context, "error in compress()", -1);
   5694       }else if( nOut<nData ){
   5695         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
   5696       }else{
   5697         sqlite3_result_value(context, argv[0]);
   5698       }
   5699       sqlite3_free(pOut);
   5700     }
   5701   }else{
   5702     sqlite3_result_value(context, argv[0]);
   5703   }
   5704 }
   5705 
   5706 /*
   5707 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
   5708 **
   5709 ** Parameter SZ is interpreted as an integer. If it is less than or
   5710 ** equal to zero, then this function returns a copy of X. Or, if
   5711 ** SZ is equal to the size of X when interpreted as a blob, also
   5712 ** return a copy of X. Otherwise, decompress blob X using zlib
   5713 ** utility function uncompress() and return the results (another
   5714 ** blob).
   5715 */
   5716 static void sqlarUncompressFunc(
   5717   sqlite3_context *context,
   5718   int argc,
   5719   sqlite3_value **argv
   5720 ){
   5721   uLong nData;
   5722   uLongf sz;
   5723 
   5724   assert( argc==2 );
   5725   sz = sqlite3_value_int(argv[1]);
   5726 
   5727   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
   5728     sqlite3_result_value(context, argv[0]);
   5729   }else{
   5730     const Bytef *pData= sqlite3_value_blob(argv[0]);
   5731     Bytef *pOut = sqlite3_malloc(sz);
   5732     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
   5733       sqlite3_result_error(context, "error in uncompress()", -1);
   5734     }else{
   5735       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
   5736     }
   5737     sqlite3_free(pOut);
   5738   }
   5739 }
   5740 
   5741 
   5742 #ifdef _WIN32
   5743 
   5744 #endif
   5745 int sqlite3_sqlar_init(
   5746   sqlite3 *db,
   5747   char **pzErrMsg,
   5748   const sqlite3_api_routines *pApi
   5749 ){
   5750   int rc = SQLITE_OK;
   5751   SQLITE_EXTENSION_INIT2(pApi);
   5752   (void)pzErrMsg;  /* Unused parameter */
   5753   rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
   5754                                sqlarCompressFunc, 0, 0);
   5755   if( rc==SQLITE_OK ){
   5756     rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
   5757                                  sqlarUncompressFunc, 0, 0);
   5758   }
   5759   return rc;
   5760 }
   5761 
   5762 /************************* End ../ext/misc/sqlar.c ********************/
   5763 #endif
   5764 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
   5765 /*
   5766 ** 2017 April 07
   5767 **
   5768 ** The author disclaims copyright to this source code.  In place of
   5769 ** a legal notice, here is a blessing:
   5770 **
   5771 **    May you do good and not evil.
   5772 **    May you find forgiveness for yourself and forgive others.
   5773 **    May you share freely, never taking more than you give.
   5774 **
   5775 *************************************************************************
   5776 */
   5777 
   5778 
   5779 
   5780 typedef struct sqlite3expert sqlite3expert;
   5781 
   5782 /*
   5783 ** Create a new sqlite3expert object.
   5784 **
   5785 ** If successful, a pointer to the new object is returned and (*pzErr) set
   5786 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
   5787 ** an English-language error message. In this case it is the responsibility
   5788 ** of the caller to eventually free the error message buffer using
   5789 ** sqlite3_free().
   5790 */
   5791 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
   5792 
   5793 /*
   5794 ** Configure an sqlite3expert object.
   5795 **
   5796 ** EXPERT_CONFIG_SAMPLE:
   5797 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
   5798 **   each candidate index. This involves scanning and sorting the entire
   5799 **   contents of each user database table once for each candidate index
   5800 **   associated with the table. For large databases, this can be
   5801 **   prohibitively slow. This option allows the sqlite3expert object to
   5802 **   be configured so that sqlite_stat1 data is instead generated based on a
   5803 **   subset of each table, or so that no sqlite_stat1 data is used at all.
   5804 **
   5805 **   A single integer argument is passed to this option. If the value is less
   5806 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
   5807 **   the analysis - indexes are recommended based on the database schema only.
   5808 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
   5809 **   generated for each candidate index (this is the default). Finally, if the
   5810 **   value falls between 0 and 100, then it represents the percentage of user
   5811 **   table rows that should be considered when generating sqlite_stat1 data.
   5812 **
   5813 **   Examples:
   5814 **
   5815 **     // Do not generate any sqlite_stat1 data
   5816 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
   5817 **
   5818 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
   5819 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
   5820 */
   5821 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
   5822 
   5823 #define EXPERT_CONFIG_SAMPLE 1    /* int */
   5824 
   5825 /*
   5826 ** Specify zero or more SQL statements to be included in the analysis.
   5827 **
   5828 ** Buffer zSql must contain zero or more complete SQL statements. This
   5829 ** function parses all statements contained in the buffer and adds them
   5830 ** to the internal list of statements to analyze. If successful, SQLITE_OK
   5831 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
   5832 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
   5833 ** may be set to point to an English language error message. In this case
   5834 ** the caller is responsible for eventually freeing the error message buffer
   5835 ** using sqlite3_free().
   5836 **
   5837 ** If an error does occur while processing one of the statements in the
   5838 ** buffer passed as the second argument, none of the statements in the
   5839 ** buffer are added to the analysis.
   5840 **
   5841 ** This function must be called before sqlite3_expert_analyze(). If a call
   5842 ** to this function is made on an sqlite3expert object that has already
   5843 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
   5844 ** immediately and no statements are added to the analysis.
   5845 */
   5846 int sqlite3_expert_sql(
   5847   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
   5848   const char *zSql,               /* SQL statement(s) to add */
   5849   char **pzErr                    /* OUT: Error message (if any) */
   5850 );
   5851 
   5852 
   5853 /*
   5854 ** This function is called after the sqlite3expert object has been configured
   5855 ** with all SQL statements using sqlite3_expert_sql() to actually perform
   5856 ** the analysis. Once this function has been called, it is not possible to
   5857 ** add further SQL statements to the analysis.
   5858 **
   5859 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
   5860 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
   5861 ** point to a buffer containing an English language error message. In this
   5862 ** case it is the responsibility of the caller to eventually free the buffer
   5863 ** using sqlite3_free().
   5864 **
   5865 ** If an error does occur within this function, the sqlite3expert object
   5866 ** is no longer useful for any purpose. At that point it is no longer
   5867 ** possible to add further SQL statements to the object or to re-attempt
   5868 ** the analysis. The sqlite3expert object must still be freed using a call
   5869 ** sqlite3_expert_destroy().
   5870 */
   5871 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
   5872 
   5873 /*
   5874 ** Return the total number of statements loaded using sqlite3_expert_sql().
   5875 ** The total number of SQL statements may be different from the total number
   5876 ** to calls to sqlite3_expert_sql().
   5877 */
   5878 int sqlite3_expert_count(sqlite3expert*);
   5879 
   5880 /*
   5881 ** Return a component of the report.
   5882 **
   5883 ** This function is called after sqlite3_expert_analyze() to extract the
   5884 ** results of the analysis. Each call to this function returns either a
   5885 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
   5886 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
   5887 ** #define constants defined below.
   5888 **
   5889 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
   5890 ** information relating to a specific SQL statement. In these cases that
   5891 ** SQL statement is identified by the value passed as the second argument.
   5892 ** SQL statements are numbered from 0 in the order in which they are parsed.
   5893 ** If an out-of-range value (less than zero or equal to or greater than the
   5894 ** value returned by sqlite3_expert_count()) is passed as the second argument
   5895 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
   5896 **
   5897 ** EXPERT_REPORT_SQL:
   5898 **   Return the text of SQL statement iStmt.
   5899 **
   5900 ** EXPERT_REPORT_INDEXES:
   5901 **   Return a buffer containing the CREATE INDEX statements for all recommended
   5902 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
   5903 **   is returned.
   5904 **
   5905 ** EXPERT_REPORT_PLAN:
   5906 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
   5907 **   iStmt after the proposed indexes have been added to the database schema.
   5908 **
   5909 ** EXPERT_REPORT_CANDIDATES:
   5910 **   Return a pointer to a buffer containing the CREATE INDEX statements
   5911 **   for all indexes that were tested (for all SQL statements). The iStmt
   5912 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
   5913 */
   5914 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
   5915 
   5916 /*
   5917 ** Values for the third argument passed to sqlite3_expert_report().
   5918 */
   5919 #define EXPERT_REPORT_SQL        1
   5920 #define EXPERT_REPORT_INDEXES    2
   5921 #define EXPERT_REPORT_PLAN       3
   5922 #define EXPERT_REPORT_CANDIDATES 4
   5923 
   5924 /*
   5925 ** Free an (sqlite3expert*) handle and all associated resources. There
   5926 ** should be one call to this function for each successful call to
   5927 ** sqlite3-expert_new().
   5928 */
   5929 void sqlite3_expert_destroy(sqlite3expert*);
   5930 
   5931 
   5932 
   5933 /************************* End ../ext/expert/sqlite3expert.h ********************/
   5934 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
   5935 /*
   5936 ** 2017 April 09
   5937 **
   5938 ** The author disclaims copyright to this source code.  In place of
   5939 ** a legal notice, here is a blessing:
   5940 **
   5941 **    May you do good and not evil.
   5942 **    May you find forgiveness for yourself and forgive others.
   5943 **    May you share freely, never taking more than you give.
   5944 **
   5945 *************************************************************************
   5946 */
   5947 #include <assert.h>
   5948 #include <string.h>
   5949 #include <stdio.h>
   5950 
   5951 #ifndef SQLITE_OMIT_VIRTUALTABLE
   5952 
   5953 /* typedef sqlite3_int64 i64; */
   5954 /* typedef sqlite3_uint64 u64; */
   5955 
   5956 typedef struct IdxColumn IdxColumn;
   5957 typedef struct IdxConstraint IdxConstraint;
   5958 typedef struct IdxScan IdxScan;
   5959 typedef struct IdxStatement IdxStatement;
   5960 typedef struct IdxTable IdxTable;
   5961 typedef struct IdxWrite IdxWrite;
   5962 
   5963 #define STRLEN  (int)strlen
   5964 
   5965 /*
   5966 ** A temp table name that we assume no user database will actually use.
   5967 ** If this assumption proves incorrect triggers on the table with the
   5968 ** conflicting name will be ignored.
   5969 */
   5970 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
   5971 
   5972 /*
   5973 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
   5974 ** any other type of single-ended range constraint on a column).
   5975 **
   5976 ** pLink:
   5977 **   Used to temporarily link IdxConstraint objects into lists while
   5978 **   creating candidate indexes.
   5979 */
   5980 struct IdxConstraint {
   5981   char *zColl;                    /* Collation sequence */
   5982   int bRange;                     /* True for range, false for eq */
   5983   int iCol;                       /* Constrained table column */
   5984   int bFlag;                      /* Used by idxFindCompatible() */
   5985   int bDesc;                      /* True if ORDER BY <expr> DESC */
   5986   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
   5987   IdxConstraint *pLink;           /* See above */
   5988 };
   5989 
   5990 /*
   5991 ** A single scan of a single table.
   5992 */
   5993 struct IdxScan {
   5994   IdxTable *pTab;                 /* Associated table object */
   5995   int iDb;                        /* Database containing table zTable */
   5996   i64 covering;                   /* Mask of columns required for cov. index */
   5997   IdxConstraint *pOrder;          /* ORDER BY columns */
   5998   IdxConstraint *pEq;             /* List of == constraints */
   5999   IdxConstraint *pRange;          /* List of < constraints */
   6000   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
   6001 };
   6002 
   6003 /*
   6004 ** Information regarding a single database table. Extracted from
   6005 ** "PRAGMA table_info" by function idxGetTableInfo().
   6006 */
   6007 struct IdxColumn {
   6008   char *zName;
   6009   char *zColl;
   6010   int iPk;
   6011 };
   6012 struct IdxTable {
   6013   int nCol;
   6014   char *zName;                    /* Table name */
   6015   IdxColumn *aCol;
   6016   IdxTable *pNext;                /* Next table in linked list of all tables */
   6017 };
   6018 
   6019 /*
   6020 ** An object of the following type is created for each unique table/write-op
   6021 ** seen. The objects are stored in a singly-linked list beginning at
   6022 ** sqlite3expert.pWrite.
   6023 */
   6024 struct IdxWrite {
   6025   IdxTable *pTab;
   6026   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
   6027   IdxWrite *pNext;
   6028 };
   6029 
   6030 /*
   6031 ** Each statement being analyzed is represented by an instance of this
   6032 ** structure.
   6033 */
   6034 struct IdxStatement {
   6035   int iId;                        /* Statement number */
   6036   char *zSql;                     /* SQL statement */
   6037   char *zIdx;                     /* Indexes */
   6038   char *zEQP;                     /* Plan */
   6039   IdxStatement *pNext;
   6040 };
   6041 
   6042 
   6043 /*
   6044 ** A hash table for storing strings. With space for a payload string
   6045 ** with each entry. Methods are:
   6046 **
   6047 **   idxHashInit()
   6048 **   idxHashClear()
   6049 **   idxHashAdd()
   6050 **   idxHashSearch()
   6051 */
   6052 #define IDX_HASH_SIZE 1023
   6053 typedef struct IdxHashEntry IdxHashEntry;
   6054 typedef struct IdxHash IdxHash;
   6055 struct IdxHashEntry {
   6056   char *zKey;                     /* nul-terminated key */
   6057   char *zVal;                     /* nul-terminated value string */
   6058   char *zVal2;                    /* nul-terminated value string 2 */
   6059   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
   6060   IdxHashEntry *pNext;            /* Next entry in hash */
   6061 };
   6062 struct IdxHash {
   6063   IdxHashEntry *pFirst;
   6064   IdxHashEntry *aHash[IDX_HASH_SIZE];
   6065 };
   6066 
   6067 /*
   6068 ** sqlite3expert object.
   6069 */
   6070 struct sqlite3expert {
   6071   int iSample;                    /* Percentage of tables to sample for stat1 */
   6072   sqlite3 *db;                    /* User database */
   6073   sqlite3 *dbm;                   /* In-memory db for this analysis */
   6074   sqlite3 *dbv;                   /* Vtab schema for this analysis */
   6075   IdxTable *pTable;               /* List of all IdxTable objects */
   6076   IdxScan *pScan;                 /* List of scan objects */
   6077   IdxWrite *pWrite;               /* List of write objects */
   6078   IdxStatement *pStatement;       /* List of IdxStatement objects */
   6079   int bRun;                       /* True once analysis has run */
   6080   char **pzErrmsg;
   6081   int rc;                         /* Error code from whereinfo hook */
   6082   IdxHash hIdx;                   /* Hash containing all candidate indexes */
   6083   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
   6084 };
   6085 
   6086 
   6087 /*
   6088 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
   6089 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
   6090 */
   6091 static void *idxMalloc(int *pRc, int nByte){
   6092   void *pRet;
   6093   assert( *pRc==SQLITE_OK );
   6094   assert( nByte>0 );
   6095   pRet = sqlite3_malloc(nByte);
   6096   if( pRet ){
   6097     memset(pRet, 0, nByte);
   6098   }else{
   6099     *pRc = SQLITE_NOMEM;
   6100   }
   6101   return pRet;
   6102 }
   6103 
   6104 /*
   6105 ** Initialize an IdxHash hash table.
   6106 */
   6107 static void idxHashInit(IdxHash *pHash){
   6108   memset(pHash, 0, sizeof(IdxHash));
   6109 }
   6110 
   6111 /*
   6112 ** Reset an IdxHash hash table.
   6113 */
   6114 static void idxHashClear(IdxHash *pHash){
   6115   int i;
   6116   for(i=0; i<IDX_HASH_SIZE; i++){
   6117     IdxHashEntry *pEntry;
   6118     IdxHashEntry *pNext;
   6119     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
   6120       pNext = pEntry->pHashNext;
   6121       sqlite3_free(pEntry->zVal2);
   6122       sqlite3_free(pEntry);
   6123     }
   6124   }
   6125   memset(pHash, 0, sizeof(IdxHash));
   6126 }
   6127 
   6128 /*
   6129 ** Return the index of the hash bucket that the string specified by the
   6130 ** arguments to this function belongs.
   6131 */
   6132 static int idxHashString(const char *z, int n){
   6133   unsigned int ret = 0;
   6134   int i;
   6135   for(i=0; i<n; i++){
   6136     ret += (ret<<3) + (unsigned char)(z[i]);
   6137   }
   6138   return (int)(ret % IDX_HASH_SIZE);
   6139 }
   6140 
   6141 /*
   6142 ** If zKey is already present in the hash table, return non-zero and do
   6143 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
   6144 ** the hash table passed as the second argument.
   6145 */
   6146 static int idxHashAdd(
   6147   int *pRc,
   6148   IdxHash *pHash,
   6149   const char *zKey,
   6150   const char *zVal
   6151 ){
   6152   int nKey = STRLEN(zKey);
   6153   int iHash = idxHashString(zKey, nKey);
   6154   int nVal = (zVal ? STRLEN(zVal) : 0);
   6155   IdxHashEntry *pEntry;
   6156   assert( iHash>=0 );
   6157   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
   6158     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
   6159       return 1;
   6160     }
   6161   }
   6162   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
   6163   if( pEntry ){
   6164     pEntry->zKey = (char*)&pEntry[1];
   6165     memcpy(pEntry->zKey, zKey, nKey);
   6166     if( zVal ){
   6167       pEntry->zVal = &pEntry->zKey[nKey+1];
   6168       memcpy(pEntry->zVal, zVal, nVal);
   6169     }
   6170     pEntry->pHashNext = pHash->aHash[iHash];
   6171     pHash->aHash[iHash] = pEntry;
   6172 
   6173     pEntry->pNext = pHash->pFirst;
   6174     pHash->pFirst = pEntry;
   6175   }
   6176   return 0;
   6177 }
   6178 
   6179 /*
   6180 ** If zKey/nKey is present in the hash table, return a pointer to the
   6181 ** hash-entry object.
   6182 */
   6183 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
   6184   int iHash;
   6185   IdxHashEntry *pEntry;
   6186   if( nKey<0 ) nKey = STRLEN(zKey);
   6187   iHash = idxHashString(zKey, nKey);
   6188   assert( iHash>=0 );
   6189   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
   6190     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
   6191       return pEntry;
   6192     }
   6193   }
   6194   return 0;
   6195 }
   6196 
   6197 /*
   6198 ** If the hash table contains an entry with a key equal to the string
   6199 ** passed as the final two arguments to this function, return a pointer
   6200 ** to the payload string. Otherwise, if zKey/nKey is not present in the
   6201 ** hash table, return NULL.
   6202 */
   6203 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
   6204   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
   6205   if( pEntry ) return pEntry->zVal;
   6206   return 0;
   6207 }
   6208 
   6209 /*
   6210 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
   6211 ** variable to point to a copy of nul-terminated string zColl.
   6212 */
   6213 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
   6214   IdxConstraint *pNew;
   6215   int nColl = STRLEN(zColl);
   6216 
   6217   assert( *pRc==SQLITE_OK );
   6218   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
   6219   if( pNew ){
   6220     pNew->zColl = (char*)&pNew[1];
   6221     memcpy(pNew->zColl, zColl, nColl+1);
   6222   }
   6223   return pNew;
   6224 }
   6225 
   6226 /*
   6227 ** An error associated with database handle db has just occurred. Pass
   6228 ** the error message to callback function xOut.
   6229 */
   6230 static void idxDatabaseError(
   6231   sqlite3 *db,                    /* Database handle */
   6232   char **pzErrmsg                 /* Write error here */
   6233 ){
   6234   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   6235 }
   6236 
   6237 /*
   6238 ** Prepare an SQL statement.
   6239 */
   6240 static int idxPrepareStmt(
   6241   sqlite3 *db,                    /* Database handle to compile against */
   6242   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
   6243   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
   6244   const char *zSql                /* SQL statement to compile */
   6245 ){
   6246   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
   6247   if( rc!=SQLITE_OK ){
   6248     *ppStmt = 0;
   6249     idxDatabaseError(db, pzErrmsg);
   6250   }
   6251   return rc;
   6252 }
   6253 
   6254 /*
   6255 ** Prepare an SQL statement using the results of a printf() formatting.
   6256 */
   6257 static int idxPrintfPrepareStmt(
   6258   sqlite3 *db,                    /* Database handle to compile against */
   6259   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
   6260   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
   6261   const char *zFmt,               /* printf() format of SQL statement */
   6262   ...                             /* Trailing printf() arguments */
   6263 ){
   6264   va_list ap;
   6265   int rc;
   6266   char *zSql;
   6267   va_start(ap, zFmt);
   6268   zSql = sqlite3_vmprintf(zFmt, ap);
   6269   if( zSql==0 ){
   6270     rc = SQLITE_NOMEM;
   6271   }else{
   6272     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
   6273     sqlite3_free(zSql);
   6274   }
   6275   va_end(ap);
   6276   return rc;
   6277 }
   6278 
   6279 
   6280 /*************************************************************************
   6281 ** Beginning of virtual table implementation.
   6282 */
   6283 typedef struct ExpertVtab ExpertVtab;
   6284 struct ExpertVtab {
   6285   sqlite3_vtab base;
   6286   IdxTable *pTab;
   6287   sqlite3expert *pExpert;
   6288 };
   6289 
   6290 typedef struct ExpertCsr ExpertCsr;
   6291 struct ExpertCsr {
   6292   sqlite3_vtab_cursor base;
   6293   sqlite3_stmt *pData;
   6294 };
   6295 
   6296 static char *expertDequote(const char *zIn){
   6297   int n = STRLEN(zIn);
   6298   char *zRet = sqlite3_malloc(n);
   6299 
   6300   assert( zIn[0]=='\'' );
   6301   assert( zIn[n-1]=='\'' );
   6302 
   6303   if( zRet ){
   6304     int iOut = 0;
   6305     int iIn = 0;
   6306     for(iIn=1; iIn<(n-1); iIn++){
   6307       if( zIn[iIn]=='\'' ){
   6308         assert( zIn[iIn+1]=='\'' );
   6309         iIn++;
   6310       }
   6311       zRet[iOut++] = zIn[iIn];
   6312     }
   6313     zRet[iOut] = '\0';
   6314   }
   6315 
   6316   return zRet;
   6317 }
   6318 
   6319 /*
   6320 ** This function is the implementation of both the xConnect and xCreate
   6321 ** methods of the r-tree virtual table.
   6322 **
   6323 **   argv[0]   -> module name
   6324 **   argv[1]   -> database name
   6325 **   argv[2]   -> table name
   6326 **   argv[...] -> column names...
   6327 */
   6328 static int expertConnect(
   6329   sqlite3 *db,
   6330   void *pAux,
   6331   int argc, const char *const*argv,
   6332   sqlite3_vtab **ppVtab,
   6333   char **pzErr
   6334 ){
   6335   sqlite3expert *pExpert = (sqlite3expert*)pAux;
   6336   ExpertVtab *p = 0;
   6337   int rc;
   6338 
   6339   if( argc!=4 ){
   6340     *pzErr = sqlite3_mprintf("internal error!");
   6341     rc = SQLITE_ERROR;
   6342   }else{
   6343     char *zCreateTable = expertDequote(argv[3]);
   6344     if( zCreateTable ){
   6345       rc = sqlite3_declare_vtab(db, zCreateTable);
   6346       if( rc==SQLITE_OK ){
   6347         p = idxMalloc(&rc, sizeof(ExpertVtab));
   6348       }
   6349       if( rc==SQLITE_OK ){
   6350         p->pExpert = pExpert;
   6351         p->pTab = pExpert->pTable;
   6352         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
   6353       }
   6354       sqlite3_free(zCreateTable);
   6355     }else{
   6356       rc = SQLITE_NOMEM;
   6357     }
   6358   }
   6359 
   6360   *ppVtab = (sqlite3_vtab*)p;
   6361   return rc;
   6362 }
   6363 
   6364 static int expertDisconnect(sqlite3_vtab *pVtab){
   6365   ExpertVtab *p = (ExpertVtab*)pVtab;
   6366   sqlite3_free(p);
   6367   return SQLITE_OK;
   6368 }
   6369 
   6370 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
   6371   ExpertVtab *p = (ExpertVtab*)pVtab;
   6372   int rc = SQLITE_OK;
   6373   int n = 0;
   6374   IdxScan *pScan;
   6375   const int opmask =
   6376     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
   6377     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
   6378     SQLITE_INDEX_CONSTRAINT_LE;
   6379 
   6380   pScan = idxMalloc(&rc, sizeof(IdxScan));
   6381   if( pScan ){
   6382     int i;
   6383 
   6384     /* Link the new scan object into the list */
   6385     pScan->pTab = p->pTab;
   6386     pScan->pNextScan = p->pExpert->pScan;
   6387     p->pExpert->pScan = pScan;
   6388 
   6389     /* Add the constraints to the IdxScan object */
   6390     for(i=0; i<pIdxInfo->nConstraint; i++){
   6391       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
   6392       if( pCons->usable
   6393        && pCons->iColumn>=0
   6394        && p->pTab->aCol[pCons->iColumn].iPk==0
   6395        && (pCons->op & opmask)
   6396       ){
   6397         IdxConstraint *pNew;
   6398         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
   6399         pNew = idxNewConstraint(&rc, zColl);
   6400         if( pNew ){
   6401           pNew->iCol = pCons->iColumn;
   6402           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   6403             pNew->pNext = pScan->pEq;
   6404             pScan->pEq = pNew;
   6405           }else{
   6406             pNew->bRange = 1;
   6407             pNew->pNext = pScan->pRange;
   6408             pScan->pRange = pNew;
   6409           }
   6410         }
   6411         n++;
   6412         pIdxInfo->aConstraintUsage[i].argvIndex = n;
   6413       }
   6414     }
   6415 
   6416     /* Add the ORDER BY to the IdxScan object */
   6417     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
   6418       int iCol = pIdxInfo->aOrderBy[i].iColumn;
   6419       if( iCol>=0 ){
   6420         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
   6421         if( pNew ){
   6422           pNew->iCol = iCol;
   6423           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
   6424           pNew->pNext = pScan->pOrder;
   6425           pNew->pLink = pScan->pOrder;
   6426           pScan->pOrder = pNew;
   6427           n++;
   6428         }
   6429       }
   6430     }
   6431   }
   6432 
   6433   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
   6434   return rc;
   6435 }
   6436 
   6437 static int expertUpdate(
   6438   sqlite3_vtab *pVtab,
   6439   int nData,
   6440   sqlite3_value **azData,
   6441   sqlite_int64 *pRowid
   6442 ){
   6443   (void)pVtab;
   6444   (void)nData;
   6445   (void)azData;
   6446   (void)pRowid;
   6447   return SQLITE_OK;
   6448 }
   6449 
   6450 /*
   6451 ** Virtual table module xOpen method.
   6452 */
   6453 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   6454   int rc = SQLITE_OK;
   6455   ExpertCsr *pCsr;
   6456   (void)pVTab;
   6457   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
   6458   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
   6459   return rc;
   6460 }
   6461 
   6462 /*
   6463 ** Virtual table module xClose method.
   6464 */
   6465 static int expertClose(sqlite3_vtab_cursor *cur){
   6466   ExpertCsr *pCsr = (ExpertCsr*)cur;
   6467   sqlite3_finalize(pCsr->pData);
   6468   sqlite3_free(pCsr);
   6469   return SQLITE_OK;
   6470 }
   6471 
   6472 /*
   6473 ** Virtual table module xEof method.
   6474 **
   6475 ** Return non-zero if the cursor does not currently point to a valid
   6476 ** record (i.e if the scan has finished), or zero otherwise.
   6477 */
   6478 static int expertEof(sqlite3_vtab_cursor *cur){
   6479   ExpertCsr *pCsr = (ExpertCsr*)cur;
   6480   return pCsr->pData==0;
   6481 }
   6482 
   6483 /*
   6484 ** Virtual table module xNext method.
   6485 */
   6486 static int expertNext(sqlite3_vtab_cursor *cur){
   6487   ExpertCsr *pCsr = (ExpertCsr*)cur;
   6488   int rc = SQLITE_OK;
   6489 
   6490   assert( pCsr->pData );
   6491   rc = sqlite3_step(pCsr->pData);
   6492   if( rc!=SQLITE_ROW ){
   6493     rc = sqlite3_finalize(pCsr->pData);
   6494     pCsr->pData = 0;
   6495   }else{
   6496     rc = SQLITE_OK;
   6497   }
   6498 
   6499   return rc;
   6500 }
   6501 
   6502 /*
   6503 ** Virtual table module xRowid method.
   6504 */
   6505 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   6506   (void)cur;
   6507   *pRowid = 0;
   6508   return SQLITE_OK;
   6509 }
   6510 
   6511 /*
   6512 ** Virtual table module xColumn method.
   6513 */
   6514 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   6515   ExpertCsr *pCsr = (ExpertCsr*)cur;
   6516   sqlite3_value *pVal;
   6517   pVal = sqlite3_column_value(pCsr->pData, i);
   6518   if( pVal ){
   6519     sqlite3_result_value(ctx, pVal);
   6520   }
   6521   return SQLITE_OK;
   6522 }
   6523 
   6524 /*
   6525 ** Virtual table module xFilter method.
   6526 */
   6527 static int expertFilter(
   6528   sqlite3_vtab_cursor *cur,
   6529   int idxNum, const char *idxStr,
   6530   int argc, sqlite3_value **argv
   6531 ){
   6532   ExpertCsr *pCsr = (ExpertCsr*)cur;
   6533   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
   6534   sqlite3expert *pExpert = pVtab->pExpert;
   6535   int rc;
   6536 
   6537   (void)idxNum;
   6538   (void)idxStr;
   6539   (void)argc;
   6540   (void)argv;
   6541   rc = sqlite3_finalize(pCsr->pData);
   6542   pCsr->pData = 0;
   6543   if( rc==SQLITE_OK ){
   6544     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
   6545         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
   6546     );
   6547   }
   6548 
   6549   if( rc==SQLITE_OK ){
   6550     rc = expertNext(cur);
   6551   }
   6552   return rc;
   6553 }
   6554 
   6555 static int idxRegisterVtab(sqlite3expert *p){
   6556   static sqlite3_module expertModule = {
   6557     2,                            /* iVersion */
   6558     expertConnect,                /* xCreate - create a table */
   6559     expertConnect,                /* xConnect - connect to an existing table */
   6560     expertBestIndex,              /* xBestIndex - Determine search strategy */
   6561     expertDisconnect,             /* xDisconnect - Disconnect from a table */
   6562     expertDisconnect,             /* xDestroy - Drop a table */
   6563     expertOpen,                   /* xOpen - open a cursor */
   6564     expertClose,                  /* xClose - close a cursor */
   6565     expertFilter,                 /* xFilter - configure scan constraints */
   6566     expertNext,                   /* xNext - advance a cursor */
   6567     expertEof,                    /* xEof */
   6568     expertColumn,                 /* xColumn - read data */
   6569     expertRowid,                  /* xRowid - read data */
   6570     expertUpdate,                 /* xUpdate - write data */
   6571     0,                            /* xBegin - begin transaction */
   6572     0,                            /* xSync - sync transaction */
   6573     0,                            /* xCommit - commit transaction */
   6574     0,                            /* xRollback - rollback transaction */
   6575     0,                            /* xFindFunction - function overloading */
   6576     0,                            /* xRename - rename the table */
   6577     0,                            /* xSavepoint */
   6578     0,                            /* xRelease */
   6579     0,                            /* xRollbackTo */
   6580   };
   6581 
   6582   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
   6583 }
   6584 /*
   6585 ** End of virtual table implementation.
   6586 *************************************************************************/
   6587 /*
   6588 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
   6589 ** is called, set it to the return value of sqlite3_finalize() before
   6590 ** returning. Otherwise, discard the sqlite3_finalize() return value.
   6591 */
   6592 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
   6593   int rc = sqlite3_finalize(pStmt);
   6594   if( *pRc==SQLITE_OK ) *pRc = rc;
   6595 }
   6596 
   6597 /*
   6598 ** Attempt to allocate an IdxTable structure corresponding to table zTab
   6599 ** in the main database of connection db. If successful, set (*ppOut) to
   6600 ** point to the new object and return SQLITE_OK. Otherwise, return an
   6601 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
   6602 ** set to point to an error string.
   6603 **
   6604 ** It is the responsibility of the caller to eventually free either the
   6605 ** IdxTable object or error message using sqlite3_free().
   6606 */
   6607 static int idxGetTableInfo(
   6608   sqlite3 *db,                    /* Database connection to read details from */
   6609   const char *zTab,               /* Table name */
   6610   IdxTable **ppOut,               /* OUT: New object (if successful) */
   6611   char **pzErrmsg                 /* OUT: Error message (if not) */
   6612 ){
   6613   sqlite3_stmt *p1 = 0;
   6614   int nCol = 0;
   6615   int nTab = STRLEN(zTab);
   6616   int nByte = sizeof(IdxTable) + nTab + 1;
   6617   IdxTable *pNew = 0;
   6618   int rc, rc2;
   6619   char *pCsr = 0;
   6620 
   6621   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
   6622   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
   6623     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
   6624     nByte += 1 + STRLEN(zCol);
   6625     rc = sqlite3_table_column_metadata(
   6626         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
   6627     );
   6628     nByte += 1 + STRLEN(zCol);
   6629     nCol++;
   6630   }
   6631   rc2 = sqlite3_reset(p1);
   6632   if( rc==SQLITE_OK ) rc = rc2;
   6633 
   6634   nByte += sizeof(IdxColumn) * nCol;
   6635   if( rc==SQLITE_OK ){
   6636     pNew = idxMalloc(&rc, nByte);
   6637   }
   6638   if( rc==SQLITE_OK ){
   6639     pNew->aCol = (IdxColumn*)&pNew[1];
   6640     pNew->nCol = nCol;
   6641     pCsr = (char*)&pNew->aCol[nCol];
   6642   }
   6643 
   6644   nCol = 0;
   6645   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
   6646     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
   6647     int nCopy = STRLEN(zCol) + 1;
   6648     pNew->aCol[nCol].zName = pCsr;
   6649     pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
   6650     memcpy(pCsr, zCol, nCopy);
   6651     pCsr += nCopy;
   6652 
   6653     rc = sqlite3_table_column_metadata(
   6654         db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
   6655     );
   6656     if( rc==SQLITE_OK ){
   6657       nCopy = STRLEN(zCol) + 1;
   6658       pNew->aCol[nCol].zColl = pCsr;
   6659       memcpy(pCsr, zCol, nCopy);
   6660       pCsr += nCopy;
   6661     }
   6662 
   6663     nCol++;
   6664   }
   6665   idxFinalize(&rc, p1);
   6666 
   6667   if( rc!=SQLITE_OK ){
   6668     sqlite3_free(pNew);
   6669     pNew = 0;
   6670   }else{
   6671     pNew->zName = pCsr;
   6672     memcpy(pNew->zName, zTab, nTab+1);
   6673   }
   6674 
   6675   *ppOut = pNew;
   6676   return rc;
   6677 }
   6678 
   6679 /*
   6680 ** This function is a no-op if *pRc is set to anything other than
   6681 ** SQLITE_OK when it is called.
   6682 **
   6683 ** If *pRc is initially set to SQLITE_OK, then the text specified by
   6684 ** the printf() style arguments is appended to zIn and the result returned
   6685 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
   6686 ** zIn before returning.
   6687 */
   6688 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
   6689   va_list ap;
   6690   char *zAppend = 0;
   6691   char *zRet = 0;
   6692   int nIn = zIn ? STRLEN(zIn) : 0;
   6693   int nAppend = 0;
   6694   va_start(ap, zFmt);
   6695   if( *pRc==SQLITE_OK ){
   6696     zAppend = sqlite3_vmprintf(zFmt, ap);
   6697     if( zAppend ){
   6698       nAppend = STRLEN(zAppend);
   6699       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
   6700     }
   6701     if( zAppend && zRet ){
   6702       if( nIn ) memcpy(zRet, zIn, nIn);
   6703       memcpy(&zRet[nIn], zAppend, nAppend+1);
   6704     }else{
   6705       sqlite3_free(zRet);
   6706       zRet = 0;
   6707       *pRc = SQLITE_NOMEM;
   6708     }
   6709     sqlite3_free(zAppend);
   6710     sqlite3_free(zIn);
   6711   }
   6712   va_end(ap);
   6713   return zRet;
   6714 }
   6715 
   6716 /*
   6717 ** Return true if zId must be quoted in order to use it as an SQL
   6718 ** identifier, or false otherwise.
   6719 */
   6720 static int idxIdentifierRequiresQuotes(const char *zId){
   6721   int i;
   6722   for(i=0; zId[i]; i++){
   6723     if( !(zId[i]=='_')
   6724      && !(zId[i]>='0' && zId[i]<='9')
   6725      && !(zId[i]>='a' && zId[i]<='z')
   6726      && !(zId[i]>='A' && zId[i]<='Z')
   6727     ){
   6728       return 1;
   6729     }
   6730   }
   6731   return 0;
   6732 }
   6733 
   6734 /*
   6735 ** This function appends an index column definition suitable for constraint
   6736 ** pCons to the string passed as zIn and returns the result.
   6737 */
   6738 static char *idxAppendColDefn(
   6739   int *pRc,                       /* IN/OUT: Error code */
   6740   char *zIn,                      /* Column defn accumulated so far */
   6741   IdxTable *pTab,                 /* Table index will be created on */
   6742   IdxConstraint *pCons
   6743 ){
   6744   char *zRet = zIn;
   6745   IdxColumn *p = &pTab->aCol[pCons->iCol];
   6746   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
   6747 
   6748   if( idxIdentifierRequiresQuotes(p->zName) ){
   6749     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
   6750   }else{
   6751     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
   6752   }
   6753 
   6754   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
   6755     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
   6756       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
   6757     }else{
   6758       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
   6759     }
   6760   }
   6761 
   6762   if( pCons->bDesc ){
   6763     zRet = idxAppendText(pRc, zRet, " DESC");
   6764   }
   6765   return zRet;
   6766 }
   6767 
   6768 /*
   6769 ** Search database dbm for an index compatible with the one idxCreateFromCons()
   6770 ** would create from arguments pScan, pEq and pTail. If no error occurs and
   6771 ** such an index is found, return non-zero. Or, if no such index is found,
   6772 ** return zero.
   6773 **
   6774 ** If an error occurs, set *pRc to an SQLite error code and return zero.
   6775 */
   6776 static int idxFindCompatible(
   6777   int *pRc,                       /* OUT: Error code */
   6778   sqlite3* dbm,                   /* Database to search */
   6779   IdxScan *pScan,                 /* Scan for table to search for index on */
   6780   IdxConstraint *pEq,             /* List of == constraints */
   6781   IdxConstraint *pTail            /* List of range constraints */
   6782 ){
   6783   const char *zTbl = pScan->pTab->zName;
   6784   sqlite3_stmt *pIdxList = 0;
   6785   IdxConstraint *pIter;
   6786   int nEq = 0;                    /* Number of elements in pEq */
   6787   int rc;
   6788 
   6789   /* Count the elements in list pEq */
   6790   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
   6791 
   6792   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
   6793   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
   6794     int bMatch = 1;
   6795     IdxConstraint *pT = pTail;
   6796     sqlite3_stmt *pInfo = 0;
   6797     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
   6798 
   6799     /* Zero the IdxConstraint.bFlag values in the pEq list */
   6800     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
   6801 
   6802     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
   6803     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
   6804       int iIdx = sqlite3_column_int(pInfo, 0);
   6805       int iCol = sqlite3_column_int(pInfo, 1);
   6806       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
   6807 
   6808       if( iIdx<nEq ){
   6809         for(pIter=pEq; pIter; pIter=pIter->pLink){
   6810           if( pIter->bFlag ) continue;
   6811           if( pIter->iCol!=iCol ) continue;
   6812           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
   6813           pIter->bFlag = 1;
   6814           break;
   6815         }
   6816         if( pIter==0 ){
   6817           bMatch = 0;
   6818           break;
   6819         }
   6820       }else{
   6821         if( pT ){
   6822           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
   6823             bMatch = 0;
   6824             break;
   6825           }
   6826           pT = pT->pLink;
   6827         }
   6828       }
   6829     }
   6830     idxFinalize(&rc, pInfo);
   6831 
   6832     if( rc==SQLITE_OK && bMatch ){
   6833       sqlite3_finalize(pIdxList);
   6834       return 1;
   6835     }
   6836   }
   6837   idxFinalize(&rc, pIdxList);
   6838 
   6839   *pRc = rc;
   6840   return 0;
   6841 }
   6842 
   6843 static int idxCreateFromCons(
   6844   sqlite3expert *p,
   6845   IdxScan *pScan,
   6846   IdxConstraint *pEq,
   6847   IdxConstraint *pTail
   6848 ){
   6849   sqlite3 *dbm = p->dbm;
   6850   int rc = SQLITE_OK;
   6851   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
   6852     IdxTable *pTab = pScan->pTab;
   6853     char *zCols = 0;
   6854     char *zIdx = 0;
   6855     IdxConstraint *pCons;
   6856     unsigned int h = 0;
   6857     const char *zFmt;
   6858 
   6859     for(pCons=pEq; pCons; pCons=pCons->pLink){
   6860       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
   6861     }
   6862     for(pCons=pTail; pCons; pCons=pCons->pLink){
   6863       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
   6864     }
   6865 
   6866     if( rc==SQLITE_OK ){
   6867       /* Hash the list of columns to come up with a name for the index */
   6868       const char *zTable = pScan->pTab->zName;
   6869       char *zName;                /* Index name */
   6870       int i;
   6871       for(i=0; zCols[i]; i++){
   6872         h += ((h<<3) + zCols[i]);
   6873       }
   6874       zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
   6875       if( zName==0 ){
   6876         rc = SQLITE_NOMEM;
   6877       }else{
   6878         if( idxIdentifierRequiresQuotes(zTable) ){
   6879           zFmt = "CREATE INDEX '%q' ON %Q(%s)";
   6880         }else{
   6881           zFmt = "CREATE INDEX %s ON %s(%s)";
   6882         }
   6883         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
   6884         if( !zIdx ){
   6885           rc = SQLITE_NOMEM;
   6886         }else{
   6887           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
   6888           idxHashAdd(&rc, &p->hIdx, zName, zIdx);
   6889         }
   6890         sqlite3_free(zName);
   6891         sqlite3_free(zIdx);
   6892       }
   6893     }
   6894 
   6895     sqlite3_free(zCols);
   6896   }
   6897   return rc;
   6898 }
   6899 
   6900 /*
   6901 ** Return true if list pList (linked by IdxConstraint.pLink) contains
   6902 ** a constraint compatible with *p. Otherwise return false.
   6903 */
   6904 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
   6905   IdxConstraint *pCmp;
   6906   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
   6907     if( p->iCol==pCmp->iCol ) return 1;
   6908   }
   6909   return 0;
   6910 }
   6911 
   6912 static int idxCreateFromWhere(
   6913   sqlite3expert *p,
   6914   IdxScan *pScan,                 /* Create indexes for this scan */
   6915   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
   6916 ){
   6917   IdxConstraint *p1 = 0;
   6918   IdxConstraint *pCon;
   6919   int rc;
   6920 
   6921   /* Gather up all the == constraints. */
   6922   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
   6923     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
   6924       pCon->pLink = p1;
   6925       p1 = pCon;
   6926     }
   6927   }
   6928 
   6929   /* Create an index using the == constraints collected above. And the
   6930   ** range constraint/ORDER BY terms passed in by the caller, if any. */
   6931   rc = idxCreateFromCons(p, pScan, p1, pTail);
   6932 
   6933   /* If no range/ORDER BY passed by the caller, create a version of the
   6934   ** index for each range constraint.  */
   6935   if( pTail==0 ){
   6936     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
   6937       assert( pCon->pLink==0 );
   6938       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
   6939         rc = idxCreateFromCons(p, pScan, p1, pCon);
   6940       }
   6941     }
   6942   }
   6943 
   6944   return rc;
   6945 }
   6946 
   6947 /*
   6948 ** Create candidate indexes in database [dbm] based on the data in
   6949 ** linked-list pScan.
   6950 */
   6951 static int idxCreateCandidates(sqlite3expert *p){
   6952   int rc = SQLITE_OK;
   6953   IdxScan *pIter;
   6954 
   6955   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
   6956     rc = idxCreateFromWhere(p, pIter, 0);
   6957     if( rc==SQLITE_OK && pIter->pOrder ){
   6958       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
   6959     }
   6960   }
   6961 
   6962   return rc;
   6963 }
   6964 
   6965 /*
   6966 ** Free all elements of the linked list starting at pConstraint.
   6967 */
   6968 static void idxConstraintFree(IdxConstraint *pConstraint){
   6969   IdxConstraint *pNext;
   6970   IdxConstraint *p;
   6971 
   6972   for(p=pConstraint; p; p=pNext){
   6973     pNext = p->pNext;
   6974     sqlite3_free(p);
   6975   }
   6976 }
   6977 
   6978 /*
   6979 ** Free all elements of the linked list starting from pScan up until pLast
   6980 ** (pLast is not freed).
   6981 */
   6982 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
   6983   IdxScan *p;
   6984   IdxScan *pNext;
   6985   for(p=pScan; p!=pLast; p=pNext){
   6986     pNext = p->pNextScan;
   6987     idxConstraintFree(p->pOrder);
   6988     idxConstraintFree(p->pEq);
   6989     idxConstraintFree(p->pRange);
   6990     sqlite3_free(p);
   6991   }
   6992 }
   6993 
   6994 /*
   6995 ** Free all elements of the linked list starting from pStatement up
   6996 ** until pLast (pLast is not freed).
   6997 */
   6998 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
   6999   IdxStatement *p;
   7000   IdxStatement *pNext;
   7001   for(p=pStatement; p!=pLast; p=pNext){
   7002     pNext = p->pNext;
   7003     sqlite3_free(p->zEQP);
   7004     sqlite3_free(p->zIdx);
   7005     sqlite3_free(p);
   7006   }
   7007 }
   7008 
   7009 /*
   7010 ** Free the linked list of IdxTable objects starting at pTab.
   7011 */
   7012 static void idxTableFree(IdxTable *pTab){
   7013   IdxTable *pIter;
   7014   IdxTable *pNext;
   7015   for(pIter=pTab; pIter; pIter=pNext){
   7016     pNext = pIter->pNext;
   7017     sqlite3_free(pIter);
   7018   }
   7019 }
   7020 
   7021 /*
   7022 ** Free the linked list of IdxWrite objects starting at pTab.
   7023 */
   7024 static void idxWriteFree(IdxWrite *pTab){
   7025   IdxWrite *pIter;
   7026   IdxWrite *pNext;
   7027   for(pIter=pTab; pIter; pIter=pNext){
   7028     pNext = pIter->pNext;
   7029     sqlite3_free(pIter);
   7030   }
   7031 }
   7032 
   7033 
   7034 
   7035 /*
   7036 ** This function is called after candidate indexes have been created. It
   7037 ** runs all the queries to see which indexes they prefer, and populates
   7038 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
   7039 */
   7040 int idxFindIndexes(
   7041   sqlite3expert *p,
   7042   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
   7043 ){
   7044   IdxStatement *pStmt;
   7045   sqlite3 *dbm = p->dbm;
   7046   int rc = SQLITE_OK;
   7047 
   7048   IdxHash hIdx;
   7049   idxHashInit(&hIdx);
   7050 
   7051   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
   7052     IdxHashEntry *pEntry;
   7053     sqlite3_stmt *pExplain = 0;
   7054     idxHashClear(&hIdx);
   7055     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
   7056         "EXPLAIN QUERY PLAN %s", pStmt->zSql
   7057     );
   7058     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
   7059       int iSelectid = sqlite3_column_int(pExplain, 0);
   7060       int iOrder = sqlite3_column_int(pExplain, 1);
   7061       int iFrom = sqlite3_column_int(pExplain, 2);
   7062       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
   7063       int nDetail = STRLEN(zDetail);
   7064       int i;
   7065 
   7066       for(i=0; i<nDetail; i++){
   7067         const char *zIdx = 0;
   7068         if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
   7069           zIdx = &zDetail[i+13];
   7070         }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
   7071           zIdx = &zDetail[i+22];
   7072         }
   7073         if( zIdx ){
   7074           const char *zSql;
   7075           int nIdx = 0;
   7076           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
   7077             nIdx++;
   7078           }
   7079           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
   7080           if( zSql ){
   7081             idxHashAdd(&rc, &hIdx, zSql, 0);
   7082             if( rc ) goto find_indexes_out;
   7083           }
   7084           break;
   7085         }
   7086       }
   7087 
   7088       pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%d|%d|%d|%s\n",
   7089           iSelectid, iOrder, iFrom, zDetail
   7090       );
   7091     }
   7092 
   7093     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
   7094       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
   7095     }
   7096 
   7097     idxFinalize(&rc, pExplain);
   7098   }
   7099 
   7100  find_indexes_out:
   7101   idxHashClear(&hIdx);
   7102   return rc;
   7103 }
   7104 
   7105 static int idxAuthCallback(
   7106   void *pCtx,
   7107   int eOp,
   7108   const char *z3,
   7109   const char *z4,
   7110   const char *zDb,
   7111   const char *zTrigger
   7112 ){
   7113   int rc = SQLITE_OK;
   7114   (void)z4;
   7115   (void)zTrigger;
   7116   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
   7117     if( sqlite3_stricmp(zDb, "main")==0 ){
   7118       sqlite3expert *p = (sqlite3expert*)pCtx;
   7119       IdxTable *pTab;
   7120       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
   7121         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
   7122       }
   7123       if( pTab ){
   7124         IdxWrite *pWrite;
   7125         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
   7126           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
   7127         }
   7128         if( pWrite==0 ){
   7129           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
   7130           if( rc==SQLITE_OK ){
   7131             pWrite->pTab = pTab;
   7132             pWrite->eOp = eOp;
   7133             pWrite->pNext = p->pWrite;
   7134             p->pWrite = pWrite;
   7135           }
   7136         }
   7137       }
   7138     }
   7139   }
   7140   return rc;
   7141 }
   7142 
   7143 static int idxProcessOneTrigger(
   7144   sqlite3expert *p,
   7145   IdxWrite *pWrite,
   7146   char **pzErr
   7147 ){
   7148   static const char *zInt = UNIQUE_TABLE_NAME;
   7149   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
   7150   IdxTable *pTab = pWrite->pTab;
   7151   const char *zTab = pTab->zName;
   7152   const char *zSql =
   7153     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
   7154     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
   7155     "ORDER BY type;";
   7156   sqlite3_stmt *pSelect = 0;
   7157   int rc = SQLITE_OK;
   7158   char *zWrite = 0;
   7159 
   7160   /* Create the table and its triggers in the temp schema */
   7161   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
   7162   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
   7163     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
   7164     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
   7165   }
   7166   idxFinalize(&rc, pSelect);
   7167 
   7168   /* Rename the table in the temp schema to zInt */
   7169   if( rc==SQLITE_OK ){
   7170     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
   7171     if( z==0 ){
   7172       rc = SQLITE_NOMEM;
   7173     }else{
   7174       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
   7175       sqlite3_free(z);
   7176     }
   7177   }
   7178 
   7179   switch( pWrite->eOp ){
   7180     case SQLITE_INSERT: {
   7181       int i;
   7182       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
   7183       for(i=0; i<pTab->nCol; i++){
   7184         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
   7185       }
   7186       zWrite = idxAppendText(&rc, zWrite, ")");
   7187       break;
   7188     }
   7189     case SQLITE_UPDATE: {
   7190       int i;
   7191       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
   7192       for(i=0; i<pTab->nCol; i++){
   7193         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
   7194             pTab->aCol[i].zName
   7195         );
   7196       }
   7197       break;
   7198     }
   7199     default: {
   7200       assert( pWrite->eOp==SQLITE_DELETE );
   7201       if( rc==SQLITE_OK ){
   7202         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
   7203         if( zWrite==0 ) rc = SQLITE_NOMEM;
   7204       }
   7205     }
   7206   }
   7207 
   7208   if( rc==SQLITE_OK ){
   7209     sqlite3_stmt *pX = 0;
   7210     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
   7211     idxFinalize(&rc, pX);
   7212     if( rc!=SQLITE_OK ){
   7213       idxDatabaseError(p->dbv, pzErr);
   7214     }
   7215   }
   7216   sqlite3_free(zWrite);
   7217 
   7218   if( rc==SQLITE_OK ){
   7219     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
   7220   }
   7221 
   7222   return rc;
   7223 }
   7224 
   7225 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
   7226   int rc = SQLITE_OK;
   7227   IdxWrite *pEnd = 0;
   7228   IdxWrite *pFirst = p->pWrite;
   7229 
   7230   while( rc==SQLITE_OK && pFirst!=pEnd ){
   7231     IdxWrite *pIter;
   7232     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
   7233       rc = idxProcessOneTrigger(p, pIter, pzErr);
   7234     }
   7235     pEnd = pFirst;
   7236     pFirst = p->pWrite;
   7237   }
   7238 
   7239   return rc;
   7240 }
   7241 
   7242 
   7243 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
   7244   int rc = idxRegisterVtab(p);
   7245   sqlite3_stmt *pSchema = 0;
   7246 
   7247   /* For each table in the main db schema:
   7248   **
   7249   **   1) Add an entry to the p->pTable list, and
   7250   **   2) Create the equivalent virtual table in dbv.
   7251   */
   7252   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
   7253       "SELECT type, name, sql, 1 FROM sqlite_master "
   7254       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
   7255       " UNION ALL "
   7256       "SELECT type, name, sql, 2 FROM sqlite_master "
   7257       "WHERE type = 'trigger'"
   7258       "  AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
   7259       "ORDER BY 4, 1"
   7260   );
   7261   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
   7262     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
   7263     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
   7264     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
   7265 
   7266     if( zType[0]=='v' || zType[1]=='r' ){
   7267       rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
   7268     }else{
   7269       IdxTable *pTab;
   7270       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
   7271       if( rc==SQLITE_OK ){
   7272         int i;
   7273         char *zInner = 0;
   7274         char *zOuter = 0;
   7275         pTab->pNext = p->pTable;
   7276         p->pTable = pTab;
   7277 
   7278         /* The statement the vtab will pass to sqlite3_declare_vtab() */
   7279         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
   7280         for(i=0; i<pTab->nCol; i++){
   7281           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
   7282               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
   7283           );
   7284         }
   7285         zInner = idxAppendText(&rc, zInner, ")");
   7286 
   7287         /* The CVT statement to create the vtab */
   7288         zOuter = idxAppendText(&rc, 0,
   7289             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
   7290         );
   7291         if( rc==SQLITE_OK ){
   7292           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
   7293         }
   7294         sqlite3_free(zInner);
   7295         sqlite3_free(zOuter);
   7296       }
   7297     }
   7298   }
   7299   idxFinalize(&rc, pSchema);
   7300   return rc;
   7301 }
   7302 
   7303 struct IdxSampleCtx {
   7304   int iTarget;
   7305   double target;                  /* Target nRet/nRow value */
   7306   double nRow;                    /* Number of rows seen */
   7307   double nRet;                    /* Number of rows returned */
   7308 };
   7309 
   7310 static void idxSampleFunc(
   7311   sqlite3_context *pCtx,
   7312   int argc,
   7313   sqlite3_value **argv
   7314 ){
   7315   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
   7316   int bRet;
   7317 
   7318   (void)argv;
   7319   assert( argc==0 );
   7320   if( p->nRow==0.0 ){
   7321     bRet = 1;
   7322   }else{
   7323     bRet = (p->nRet / p->nRow) <= p->target;
   7324     if( bRet==0 ){
   7325       unsigned short rnd;
   7326       sqlite3_randomness(2, (void*)&rnd);
   7327       bRet = ((int)rnd % 100) <= p->iTarget;
   7328     }
   7329   }
   7330 
   7331   sqlite3_result_int(pCtx, bRet);
   7332   p->nRow += 1.0;
   7333   p->nRet += (double)bRet;
   7334 }
   7335 
   7336 struct IdxRemCtx {
   7337   int nSlot;
   7338   struct IdxRemSlot {
   7339     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
   7340     i64 iVal;                     /* SQLITE_INTEGER value */
   7341     double rVal;                  /* SQLITE_FLOAT value */
   7342     int nByte;                    /* Bytes of space allocated at z */
   7343     int n;                        /* Size of buffer z */
   7344     char *z;                      /* SQLITE_TEXT/BLOB value */
   7345   } aSlot[1];
   7346 };
   7347 
   7348 /*
   7349 ** Implementation of scalar function rem().
   7350 */
   7351 static void idxRemFunc(
   7352   sqlite3_context *pCtx,
   7353   int argc,
   7354   sqlite3_value **argv
   7355 ){
   7356   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
   7357   struct IdxRemSlot *pSlot;
   7358   int iSlot;
   7359   assert( argc==2 );
   7360 
   7361   iSlot = sqlite3_value_int(argv[0]);
   7362   assert( iSlot<=p->nSlot );
   7363   pSlot = &p->aSlot[iSlot];
   7364 
   7365   switch( pSlot->eType ){
   7366     case SQLITE_NULL:
   7367       /* no-op */
   7368       break;
   7369 
   7370     case SQLITE_INTEGER:
   7371       sqlite3_result_int64(pCtx, pSlot->iVal);
   7372       break;
   7373 
   7374     case SQLITE_FLOAT:
   7375       sqlite3_result_double(pCtx, pSlot->rVal);
   7376       break;
   7377 
   7378     case SQLITE_BLOB:
   7379       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
   7380       break;
   7381 
   7382     case SQLITE_TEXT:
   7383       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
   7384       break;
   7385   }
   7386 
   7387   pSlot->eType = sqlite3_value_type(argv[1]);
   7388   switch( pSlot->eType ){
   7389     case SQLITE_NULL:
   7390       /* no-op */
   7391       break;
   7392 
   7393     case SQLITE_INTEGER:
   7394       pSlot->iVal = sqlite3_value_int64(argv[1]);
   7395       break;
   7396 
   7397     case SQLITE_FLOAT:
   7398       pSlot->rVal = sqlite3_value_double(argv[1]);
   7399       break;
   7400 
   7401     case SQLITE_BLOB:
   7402     case SQLITE_TEXT: {
   7403       int nByte = sqlite3_value_bytes(argv[1]);
   7404       if( nByte>pSlot->nByte ){
   7405         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
   7406         if( zNew==0 ){
   7407           sqlite3_result_error_nomem(pCtx);
   7408           return;
   7409         }
   7410         pSlot->nByte = nByte*2;
   7411         pSlot->z = zNew;
   7412       }
   7413       pSlot->n = nByte;
   7414       if( pSlot->eType==SQLITE_BLOB ){
   7415         memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
   7416       }else{
   7417         memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
   7418       }
   7419       break;
   7420     }
   7421   }
   7422 }
   7423 
   7424 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
   7425   int rc = SQLITE_OK;
   7426   const char *zMax =
   7427     "SELECT max(i.seqno) FROM "
   7428     "  sqlite_master AS s, "
   7429     "  pragma_index_list(s.name) AS l, "
   7430     "  pragma_index_info(l.name) AS i "
   7431     "WHERE s.type = 'table'";
   7432   sqlite3_stmt *pMax = 0;
   7433 
   7434   *pnMax = 0;
   7435   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
   7436   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
   7437     *pnMax = sqlite3_column_int(pMax, 0) + 1;
   7438   }
   7439   idxFinalize(&rc, pMax);
   7440 
   7441   return rc;
   7442 }
   7443 
   7444 static int idxPopulateOneStat1(
   7445   sqlite3expert *p,
   7446   sqlite3_stmt *pIndexXInfo,
   7447   sqlite3_stmt *pWriteStat,
   7448   const char *zTab,
   7449   const char *zIdx,
   7450   char **pzErr
   7451 ){
   7452   char *zCols = 0;
   7453   char *zOrder = 0;
   7454   char *zQuery = 0;
   7455   int nCol = 0;
   7456   int i;
   7457   sqlite3_stmt *pQuery = 0;
   7458   int *aStat = 0;
   7459   int rc = SQLITE_OK;
   7460 
   7461   assert( p->iSample>0 );
   7462 
   7463   /* Formulate the query text */
   7464   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
   7465   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
   7466     const char *zComma = zCols==0 ? "" : ", ";
   7467     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
   7468     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
   7469     zCols = idxAppendText(&rc, zCols,
   7470         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
   7471     );
   7472     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
   7473   }
   7474   sqlite3_reset(pIndexXInfo);
   7475   if( rc==SQLITE_OK ){
   7476     if( p->iSample==100 ){
   7477       zQuery = sqlite3_mprintf(
   7478           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
   7479       );
   7480     }else{
   7481       zQuery = sqlite3_mprintf(
   7482           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
   7483       );
   7484     }
   7485   }
   7486   sqlite3_free(zCols);
   7487   sqlite3_free(zOrder);
   7488 
   7489   /* Formulate the query text */
   7490   if( rc==SQLITE_OK ){
   7491     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
   7492     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
   7493   }
   7494   sqlite3_free(zQuery);
   7495 
   7496   if( rc==SQLITE_OK ){
   7497     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
   7498   }
   7499   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
   7500     IdxHashEntry *pEntry;
   7501     char *zStat = 0;
   7502     for(i=0; i<=nCol; i++) aStat[i] = 1;
   7503     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
   7504       aStat[0]++;
   7505       for(i=0; i<nCol; i++){
   7506         if( sqlite3_column_int(pQuery, i)==0 ) break;
   7507       }
   7508       for(/*no-op*/; i<nCol; i++){
   7509         aStat[i+1]++;
   7510       }
   7511     }
   7512 
   7513     if( rc==SQLITE_OK ){
   7514       int s0 = aStat[0];
   7515       zStat = sqlite3_mprintf("%d", s0);
   7516       if( zStat==0 ) rc = SQLITE_NOMEM;
   7517       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
   7518         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
   7519       }
   7520     }
   7521 
   7522     if( rc==SQLITE_OK ){
   7523       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
   7524       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
   7525       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
   7526       sqlite3_step(pWriteStat);
   7527       rc = sqlite3_reset(pWriteStat);
   7528     }
   7529 
   7530     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
   7531     if( pEntry ){
   7532       assert( pEntry->zVal2==0 );
   7533       pEntry->zVal2 = zStat;
   7534     }else{
   7535       sqlite3_free(zStat);
   7536     }
   7537   }
   7538   sqlite3_free(aStat);
   7539   idxFinalize(&rc, pQuery);
   7540 
   7541   return rc;
   7542 }
   7543 
   7544 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
   7545   int rc;
   7546   char *zSql;
   7547 
   7548   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
   7549   if( rc!=SQLITE_OK ) return rc;
   7550 
   7551   zSql = sqlite3_mprintf(
   7552       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
   7553   );
   7554   if( zSql==0 ) return SQLITE_NOMEM;
   7555   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
   7556   sqlite3_free(zSql);
   7557 
   7558   return rc;
   7559 }
   7560 
   7561 /*
   7562 ** This function is called as part of sqlite3_expert_analyze(). Candidate
   7563 ** indexes have already been created in database sqlite3expert.dbm, this
   7564 ** function populates sqlite_stat1 table in the same database.
   7565 **
   7566 ** The stat1 data is generated by querying the
   7567 */
   7568 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
   7569   int rc = SQLITE_OK;
   7570   int nMax =0;
   7571   struct IdxRemCtx *pCtx = 0;
   7572   struct IdxSampleCtx samplectx;
   7573   int i;
   7574   i64 iPrev = -100000;
   7575   sqlite3_stmt *pAllIndex = 0;
   7576   sqlite3_stmt *pIndexXInfo = 0;
   7577   sqlite3_stmt *pWrite = 0;
   7578 
   7579   const char *zAllIndex =
   7580     "SELECT s.rowid, s.name, l.name FROM "
   7581     "  sqlite_master AS s, "
   7582     "  pragma_index_list(s.name) AS l "
   7583     "WHERE s.type = 'table'";
   7584   const char *zIndexXInfo =
   7585     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
   7586   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
   7587 
   7588   /* If iSample==0, no sqlite_stat1 data is required. */
   7589   if( p->iSample==0 ) return SQLITE_OK;
   7590 
   7591   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
   7592   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
   7593 
   7594   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
   7595 
   7596   if( rc==SQLITE_OK ){
   7597     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
   7598     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
   7599   }
   7600 
   7601   if( rc==SQLITE_OK ){
   7602     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
   7603     rc = sqlite3_create_function(
   7604         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
   7605     );
   7606   }
   7607   if( rc==SQLITE_OK ){
   7608     rc = sqlite3_create_function(
   7609         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
   7610     );
   7611   }
   7612 
   7613   if( rc==SQLITE_OK ){
   7614     pCtx->nSlot = nMax+1;
   7615     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
   7616   }
   7617   if( rc==SQLITE_OK ){
   7618     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
   7619   }
   7620   if( rc==SQLITE_OK ){
   7621     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
   7622   }
   7623 
   7624   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
   7625     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
   7626     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
   7627     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
   7628     if( p->iSample<100 && iPrev!=iRowid ){
   7629       samplectx.target = (double)p->iSample / 100.0;
   7630       samplectx.iTarget = p->iSample;
   7631       samplectx.nRow = 0.0;
   7632       samplectx.nRet = 0.0;
   7633       rc = idxBuildSampleTable(p, zTab);
   7634       if( rc!=SQLITE_OK ) break;
   7635     }
   7636     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
   7637     iPrev = iRowid;
   7638   }
   7639   if( rc==SQLITE_OK && p->iSample<100 ){
   7640     rc = sqlite3_exec(p->dbv,
   7641         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
   7642     );
   7643   }
   7644 
   7645   idxFinalize(&rc, pAllIndex);
   7646   idxFinalize(&rc, pIndexXInfo);
   7647   idxFinalize(&rc, pWrite);
   7648 
   7649   for(i=0; i<pCtx->nSlot; i++){
   7650     sqlite3_free(pCtx->aSlot[i].z);
   7651   }
   7652   sqlite3_free(pCtx);
   7653 
   7654   if( rc==SQLITE_OK ){
   7655     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
   7656   }
   7657 
   7658   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
   7659   return rc;
   7660 }
   7661 
   7662 /*
   7663 ** Allocate a new sqlite3expert object.
   7664 */
   7665 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
   7666   int rc = SQLITE_OK;
   7667   sqlite3expert *pNew;
   7668 
   7669   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
   7670 
   7671   /* Open two in-memory databases to work with. The "vtab database" (dbv)
   7672   ** will contain a virtual table corresponding to each real table in
   7673   ** the user database schema, and a copy of each view. It is used to
   7674   ** collect information regarding the WHERE, ORDER BY and other clauses
   7675   ** of the user's query.
   7676   */
   7677   if( rc==SQLITE_OK ){
   7678     pNew->db = db;
   7679     pNew->iSample = 100;
   7680     rc = sqlite3_open(":memory:", &pNew->dbv);
   7681   }
   7682   if( rc==SQLITE_OK ){
   7683     rc = sqlite3_open(":memory:", &pNew->dbm);
   7684     if( rc==SQLITE_OK ){
   7685       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
   7686     }
   7687   }
   7688 
   7689 
   7690   /* Copy the entire schema of database [db] into [dbm]. */
   7691   if( rc==SQLITE_OK ){
   7692     sqlite3_stmt *pSql;
   7693     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
   7694         "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
   7695         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
   7696     );
   7697     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
   7698       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
   7699       rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
   7700     }
   7701     idxFinalize(&rc, pSql);
   7702   }
   7703 
   7704   /* Create the vtab schema */
   7705   if( rc==SQLITE_OK ){
   7706     rc = idxCreateVtabSchema(pNew, pzErrmsg);
   7707   }
   7708 
   7709   /* Register the auth callback with dbv */
   7710   if( rc==SQLITE_OK ){
   7711     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
   7712   }
   7713 
   7714   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
   7715   ** return the new sqlite3expert handle.  */
   7716   if( rc!=SQLITE_OK ){
   7717     sqlite3_expert_destroy(pNew);
   7718     pNew = 0;
   7719   }
   7720   return pNew;
   7721 }
   7722 
   7723 /*
   7724 ** Configure an sqlite3expert object.
   7725 */
   7726 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
   7727   int rc = SQLITE_OK;
   7728   va_list ap;
   7729   va_start(ap, op);
   7730   switch( op ){
   7731     case EXPERT_CONFIG_SAMPLE: {
   7732       int iVal = va_arg(ap, int);
   7733       if( iVal<0 ) iVal = 0;
   7734       if( iVal>100 ) iVal = 100;
   7735       p->iSample = iVal;
   7736       break;
   7737     }
   7738     default:
   7739       rc = SQLITE_NOTFOUND;
   7740       break;
   7741   }
   7742 
   7743   va_end(ap);
   7744   return rc;
   7745 }
   7746 
   7747 /*
   7748 ** Add an SQL statement to the analysis.
   7749 */
   7750 int sqlite3_expert_sql(
   7751   sqlite3expert *p,               /* From sqlite3_expert_new() */
   7752   const char *zSql,               /* SQL statement to add */
   7753   char **pzErr                    /* OUT: Error message (if any) */
   7754 ){
   7755   IdxScan *pScanOrig = p->pScan;
   7756   IdxStatement *pStmtOrig = p->pStatement;
   7757   int rc = SQLITE_OK;
   7758   const char *zStmt = zSql;
   7759 
   7760   if( p->bRun ) return SQLITE_MISUSE;
   7761 
   7762   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
   7763     sqlite3_stmt *pStmt = 0;
   7764     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
   7765     if( rc==SQLITE_OK ){
   7766       if( pStmt ){
   7767         IdxStatement *pNew;
   7768         const char *z = sqlite3_sql(pStmt);
   7769         int n = STRLEN(z);
   7770         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
   7771         if( rc==SQLITE_OK ){
   7772           pNew->zSql = (char*)&pNew[1];
   7773           memcpy(pNew->zSql, z, n+1);
   7774           pNew->pNext = p->pStatement;
   7775           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
   7776           p->pStatement = pNew;
   7777         }
   7778         sqlite3_finalize(pStmt);
   7779       }
   7780     }else{
   7781       idxDatabaseError(p->dbv, pzErr);
   7782     }
   7783   }
   7784 
   7785   if( rc!=SQLITE_OK ){
   7786     idxScanFree(p->pScan, pScanOrig);
   7787     idxStatementFree(p->pStatement, pStmtOrig);
   7788     p->pScan = pScanOrig;
   7789     p->pStatement = pStmtOrig;
   7790   }
   7791 
   7792   return rc;
   7793 }
   7794 
   7795 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
   7796   int rc;
   7797   IdxHashEntry *pEntry;
   7798 
   7799   /* Do trigger processing to collect any extra IdxScan structures */
   7800   rc = idxProcessTriggers(p, pzErr);
   7801 
   7802   /* Create candidate indexes within the in-memory database file */
   7803   if( rc==SQLITE_OK ){
   7804     rc = idxCreateCandidates(p);
   7805   }
   7806 
   7807   /* Generate the stat1 data */
   7808   if( rc==SQLITE_OK ){
   7809     rc = idxPopulateStat1(p, pzErr);
   7810   }
   7811 
   7812   /* Formulate the EXPERT_REPORT_CANDIDATES text */
   7813   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
   7814     p->zCandidates = idxAppendText(&rc, p->zCandidates,
   7815         "%s;%s%s\n", pEntry->zVal,
   7816         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
   7817     );
   7818   }
   7819 
   7820   /* Figure out which of the candidate indexes are preferred by the query
   7821   ** planner and report the results to the user.  */
   7822   if( rc==SQLITE_OK ){
   7823     rc = idxFindIndexes(p, pzErr);
   7824   }
   7825 
   7826   if( rc==SQLITE_OK ){
   7827     p->bRun = 1;
   7828   }
   7829   return rc;
   7830 }
   7831 
   7832 /*
   7833 ** Return the total number of statements that have been added to this
   7834 ** sqlite3expert using sqlite3_expert_sql().
   7835 */
   7836 int sqlite3_expert_count(sqlite3expert *p){
   7837   int nRet = 0;
   7838   if( p->pStatement ) nRet = p->pStatement->iId+1;
   7839   return nRet;
   7840 }
   7841 
   7842 /*
   7843 ** Return a component of the report.
   7844 */
   7845 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
   7846   const char *zRet = 0;
   7847   IdxStatement *pStmt;
   7848 
   7849   if( p->bRun==0 ) return 0;
   7850   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
   7851   switch( eReport ){
   7852     case EXPERT_REPORT_SQL:
   7853       if( pStmt ) zRet = pStmt->zSql;
   7854       break;
   7855     case EXPERT_REPORT_INDEXES:
   7856       if( pStmt ) zRet = pStmt->zIdx;
   7857       break;
   7858     case EXPERT_REPORT_PLAN:
   7859       if( pStmt ) zRet = pStmt->zEQP;
   7860       break;
   7861     case EXPERT_REPORT_CANDIDATES:
   7862       zRet = p->zCandidates;
   7863       break;
   7864   }
   7865   return zRet;
   7866 }
   7867 
   7868 /*
   7869 ** Free an sqlite3expert object.
   7870 */
   7871 void sqlite3_expert_destroy(sqlite3expert *p){
   7872   if( p ){
   7873     sqlite3_close(p->dbm);
   7874     sqlite3_close(p->dbv);
   7875     idxScanFree(p->pScan, 0);
   7876     idxStatementFree(p->pStatement, 0);
   7877     idxTableFree(p->pTable);
   7878     idxWriteFree(p->pWrite);
   7879     idxHashClear(&p->hIdx);
   7880     sqlite3_free(p->zCandidates);
   7881     sqlite3_free(p);
   7882   }
   7883 }
   7884 
   7885 #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
   7886 
   7887 /************************* End ../ext/expert/sqlite3expert.c ********************/
   7888 
   7889 #if defined(SQLITE_ENABLE_SESSION)
   7890 /*
   7891 ** State information for a single open session
   7892 */
   7893 typedef struct OpenSession OpenSession;
   7894 struct OpenSession {
   7895   char *zName;             /* Symbolic name for this session */
   7896   int nFilter;             /* Number of xFilter rejection GLOB patterns */
   7897   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
   7898   sqlite3_session *p;      /* The open session */
   7899 };
   7900 #endif
   7901 
   7902 /*
   7903 ** Shell output mode information from before ".explain on",
   7904 ** saved so that it can be restored by ".explain off"
   7905 */
   7906 typedef struct SavedModeInfo SavedModeInfo;
   7907 struct SavedModeInfo {
   7908   int valid;          /* Is there legit data in here? */
   7909   int mode;           /* Mode prior to ".explain on" */
   7910   int showHeader;     /* The ".header" setting prior to ".explain on" */
   7911   int colWidth[100];  /* Column widths prior to ".explain on" */
   7912 };
   7913 
   7914 typedef struct ExpertInfo ExpertInfo;
   7915 struct ExpertInfo {
   7916   sqlite3expert *pExpert;
   7917   int bVerbose;
   7918 };
   7919 
   7920 /*
   7921 ** State information about the database connection is contained in an
   7922 ** instance of the following structure.
   7923 */
   7924 typedef struct ShellState ShellState;
   7925 struct ShellState {
   7926   sqlite3 *db;           /* The database */
   7927   u8 autoExplain;        /* Automatically turn on .explain mode */
   7928   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
   7929   u8 statsOn;            /* True to display memory stats before each finalize */
   7930   u8 scanstatsOn;        /* True to display scan stats before each finalize */
   7931   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
   7932   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
   7933   int outCount;          /* Revert to stdout when reaching zero */
   7934   int cnt;               /* Number of records displayed so far */
   7935   FILE *out;             /* Write results here */
   7936   FILE *traceOut;        /* Output for sqlite3_trace() */
   7937   int nErr;              /* Number of errors seen */
   7938   int mode;              /* An output mode setting */
   7939   int modePrior;         /* Saved mode */
   7940   int cMode;             /* temporary output mode for the current query */
   7941   int normalMode;        /* Output mode before ".explain on" */
   7942   int writableSchema;    /* True if PRAGMA writable_schema=ON */
   7943   int showHeader;        /* True to show column names in List or Column mode */
   7944   int nCheck;            /* Number of ".check" commands run */
   7945   unsigned shellFlgs;    /* Various flags */
   7946   char *zDestTable;      /* Name of destination table when MODE_Insert */
   7947   char *zTempFile;       /* Temporary file that might need deleting */
   7948   char zTestcase[30];    /* Name of current test case */
   7949   char colSeparator[20]; /* Column separator character for several modes */
   7950   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
   7951   char colSepPrior[20];  /* Saved column separator */
   7952   char rowSepPrior[20];  /* Saved row separator */
   7953   int colWidth[100];     /* Requested width of each column when in column mode*/
   7954   int actualWidth[100];  /* Actual width of each column */
   7955   char nullValue[20];    /* The text to print when a NULL comes back from
   7956                          ** the database */
   7957   char outfile[FILENAME_MAX]; /* Filename for *out */
   7958   const char *zDbFilename;    /* name of the database file */
   7959   char *zFreeOnClose;         /* Filename to free when closing */
   7960   const char *zVfs;           /* Name of VFS to use */
   7961   sqlite3_stmt *pStmt;   /* Current statement if any. */
   7962   FILE *pLog;            /* Write log output here */
   7963   int *aiIndent;         /* Array of indents used in MODE_Explain */
   7964   int nIndent;           /* Size of array aiIndent[] */
   7965   int iIndent;           /* Index of current op in aiIndent[] */
   7966 #if defined(SQLITE_ENABLE_SESSION)
   7967   int nSession;             /* Number of active sessions */
   7968   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
   7969 #endif
   7970   ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
   7971 };
   7972 
   7973 
   7974 /* Allowed values for ShellState.autoEQP
   7975 */
   7976 #define AUTOEQP_off      0
   7977 #define AUTOEQP_on       1
   7978 #define AUTOEQP_trigger  2
   7979 #define AUTOEQP_full     3
   7980 
   7981 /* Allowed values for ShellState.openMode
   7982 */
   7983 #define SHELL_OPEN_UNSPEC     0      /* No open-mode specified */
   7984 #define SHELL_OPEN_NORMAL     1      /* Normal database file */
   7985 #define SHELL_OPEN_APPENDVFS  2      /* Use appendvfs */
   7986 #define SHELL_OPEN_ZIPFILE    3      /* Use the zipfile virtual table */
   7987 
   7988 /*
   7989 ** These are the allowed shellFlgs values
   7990 */
   7991 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
   7992 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
   7993 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
   7994 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
   7995 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
   7996 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
   7997 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
   7998 
   7999 /*
   8000 ** Macros for testing and setting shellFlgs
   8001 */
   8002 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
   8003 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
   8004 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
   8005 
   8006 /*
   8007 ** These are the allowed modes.
   8008 */
   8009 #define MODE_Line     0  /* One column per line.  Blank line between records */
   8010 #define MODE_Column   1  /* One record per line in neat columns */
   8011 #define MODE_List     2  /* One record per line with a separator */
   8012 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
   8013 #define MODE_Html     4  /* Generate an XHTML table */
   8014 #define MODE_Insert   5  /* Generate SQL "insert" statements */
   8015 #define MODE_Quote    6  /* Quote values as for SQL */
   8016 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
   8017 #define MODE_Csv      8  /* Quote strings, numbers are plain */
   8018 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
   8019 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
   8020 #define MODE_Pretty  11  /* Pretty-print schemas */
   8021 
   8022 static const char *modeDescr[] = {
   8023   "line",
   8024   "column",
   8025   "list",
   8026   "semi",
   8027   "html",
   8028   "insert",
   8029   "quote",
   8030   "tcl",
   8031   "csv",
   8032   "explain",
   8033   "ascii",
   8034   "prettyprint",
   8035 };
   8036 
   8037 /*
   8038 ** These are the column/row/line separators used by the various
   8039 ** import/export modes.
   8040 */
   8041 #define SEP_Column    "|"
   8042 #define SEP_Row       "\n"
   8043 #define SEP_Tab       "\t"
   8044 #define SEP_Space     " "
   8045 #define SEP_Comma     ","
   8046 #define SEP_CrLf      "\r\n"
   8047 #define SEP_Unit      "\x1F"
   8048 #define SEP_Record    "\x1E"
   8049 
   8050 /*
   8051 ** A callback for the sqlite3_log() interface.
   8052 */
   8053 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
   8054   ShellState *p = (ShellState*)pArg;
   8055   if( p->pLog==0 ) return;
   8056   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
   8057   fflush(p->pLog);
   8058 }
   8059 
   8060 /*
   8061 ** SQL function:  shell_putsnl(X)
   8062 **
   8063 ** Write the text X to the screen (or whatever output is being directed)
   8064 ** adding a newline at the end, and then return X.
   8065 */
   8066 static void shellPutsFunc(
   8067   sqlite3_context *pCtx,
   8068   int nVal,
   8069   sqlite3_value **apVal
   8070 ){
   8071   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
   8072   (void)nVal;
   8073   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
   8074   sqlite3_result_value(pCtx, apVal[0]);
   8075 }
   8076 
   8077 /*
   8078 ** SQL function:   edit(VALUE)
   8079 **                 edit(VALUE,EDITOR)
   8080 **
   8081 ** These steps:
   8082 **
   8083 **     (1) Write VALUE into a temporary file.
   8084 **     (2) Run program EDITOR on that temporary file.
   8085 **     (3) Read the temporary file back and return its content as the result.
   8086 **     (4) Delete the temporary file
   8087 **
   8088 ** If the EDITOR argument is omitted, use the value in the VISUAL
   8089 ** environment variable.  If still there is no EDITOR, through an error.
   8090 **
   8091 ** Also throw an error if the EDITOR program returns a non-zero exit code.
   8092 */
   8093 static void editFunc(
   8094   sqlite3_context *context,
   8095   int argc,
   8096   sqlite3_value **argv
   8097 ){
   8098   const char *zEditor;
   8099   char *zTempFile = 0;
   8100   sqlite3 *db;
   8101   char *zCmd = 0;
   8102   int bBin;
   8103   int rc;
   8104   FILE *f = 0;
   8105   sqlite3_int64 sz;
   8106   sqlite3_int64 x;
   8107   unsigned char *p = 0;
   8108 
   8109   if( argc==2 ){
   8110     zEditor = (const char*)sqlite3_value_text(argv[1]);
   8111   }else{
   8112     zEditor = getenv("VISUAL");
   8113   }
   8114   if( zEditor==0 ){
   8115     sqlite3_result_error(context, "no editor for edit()", -1);
   8116     return;
   8117   }
   8118   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   8119     sqlite3_result_error(context, "NULL input to edit()", -1);
   8120     return;
   8121   }
   8122   db = sqlite3_context_db_handle(context);
   8123   zTempFile = 0;
   8124   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
   8125   if( zTempFile==0 ){
   8126     sqlite3_uint64 r = 0;
   8127     sqlite3_randomness(sizeof(r), &r);
   8128     zTempFile = sqlite3_mprintf("temp%llx", r);
   8129     if( zTempFile==0 ){
   8130       sqlite3_result_error_nomem(context);
   8131       return;
   8132     }
   8133   }
   8134   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
   8135   f = fopen(zTempFile, bBin ? "wb" : "w");
   8136   if( f==0 ){
   8137     sqlite3_result_error(context, "edit() cannot open temp file", -1);
   8138     goto edit_func_end;
   8139   }
   8140   sz = sqlite3_value_bytes(argv[0]);
   8141   if( bBin ){
   8142     x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
   8143   }else{
   8144     x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
   8145   }
   8146   fclose(f);
   8147   f = 0;
   8148   if( x!=sz ){
   8149     sqlite3_result_error(context, "edit() could not write the whole file", -1);
   8150     goto edit_func_end;
   8151   }
   8152   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
   8153   if( zCmd==0 ){
   8154     sqlite3_result_error_nomem(context);
   8155     goto edit_func_end;
   8156   }
   8157   rc = system(zCmd);
   8158   sqlite3_free(zCmd);
   8159   if( rc ){
   8160     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
   8161     goto edit_func_end;
   8162   }
   8163   f = fopen(zTempFile, bBin ? "rb" : "r");
   8164   if( f==0 ){
   8165     sqlite3_result_error(context,
   8166       "edit() cannot reopen temp file after edit", -1);
   8167     goto edit_func_end;
   8168   }
   8169   fseek(f, 0, SEEK_END);
   8170   sz = ftell(f);
   8171   rewind(f);
   8172   p = sqlite3_malloc64( sz+(bBin==0) );
   8173   if( p==0 ){
   8174     sqlite3_result_error_nomem(context);
   8175     goto edit_func_end;
   8176   }
   8177   if( bBin ){
   8178     x = fread(p, 1, sz, f);
   8179   }else{
   8180     x = fread(p, 1, sz, f);
   8181     p[sz] = 0;
   8182   }
   8183   fclose(f);
   8184   f = 0;
   8185   if( x!=sz ){
   8186     sqlite3_result_error(context, "could not read back the whole file", -1);
   8187     goto edit_func_end;
   8188   }
   8189   if( bBin ){
   8190     sqlite3_result_blob(context, p, sz, sqlite3_free);
   8191   }else{
   8192     sqlite3_result_text(context, (const char*)p, sz, sqlite3_free);
   8193   }
   8194   p = 0;
   8195 
   8196 edit_func_end:
   8197   if( f ) fclose(f);
   8198   unlink(zTempFile);
   8199   sqlite3_free(zTempFile);
   8200   sqlite3_free(p);
   8201 }
   8202 
   8203 /*
   8204 ** Save or restore the current output mode
   8205 */
   8206 static void outputModePush(ShellState *p){
   8207   p->modePrior = p->mode;
   8208   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
   8209   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
   8210 }
   8211 static void outputModePop(ShellState *p){
   8212   p->mode = p->modePrior;
   8213   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
   8214   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
   8215 }
   8216 
   8217 /*
   8218 ** Output the given string as a hex-encoded blob (eg. X'1234' )
   8219 */
   8220 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
   8221   int i;
   8222   char *zBlob = (char *)pBlob;
   8223   raw_printf(out,"X'");
   8224   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
   8225   raw_printf(out,"'");
   8226 }
   8227 
   8228 /*
   8229 ** Find a string that is not found anywhere in z[].  Return a pointer
   8230 ** to that string.
   8231 **
   8232 ** Try to use zA and zB first.  If both of those are already found in z[]
   8233 ** then make up some string and store it in the buffer zBuf.
   8234 */
   8235 static const char *unused_string(
   8236   const char *z,                    /* Result must not appear anywhere in z */
   8237   const char *zA, const char *zB,   /* Try these first */
   8238   char *zBuf                        /* Space to store a generated string */
   8239 ){
   8240   unsigned i = 0;
   8241   if( strstr(z, zA)==0 ) return zA;
   8242   if( strstr(z, zB)==0 ) return zB;
   8243   do{
   8244     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
   8245   }while( strstr(z,zBuf)!=0 );
   8246   return zBuf;
   8247 }
   8248 
   8249 /*
   8250 ** Output the given string as a quoted string using SQL quoting conventions.
   8251 **
   8252 ** See also: output_quoted_escaped_string()
   8253 */
   8254 static void output_quoted_string(FILE *out, const char *z){
   8255   int i;
   8256   char c;
   8257   setBinaryMode(out, 1);
   8258   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
   8259   if( c==0 ){
   8260     utf8_printf(out,"'%s'",z);
   8261   }else{
   8262     raw_printf(out, "'");
   8263     while( *z ){
   8264       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
   8265       if( c=='\'' ) i++;
   8266       if( i ){
   8267         utf8_printf(out, "%.*s", i, z);
   8268         z += i;
   8269       }
   8270       if( c=='\'' ){
   8271         raw_printf(out, "'");
   8272         continue;
   8273       }
   8274       if( c==0 ){
   8275         break;
   8276       }
   8277       z++;
   8278     }
   8279     raw_printf(out, "'");
   8280   }
   8281   setTextMode(out, 1);
   8282 }
   8283 
   8284 /*
   8285 ** Output the given string as a quoted string using SQL quoting conventions.
   8286 ** Additionallly , escape the "\n" and "\r" characters so that they do not
   8287 ** get corrupted by end-of-line translation facilities in some operating
   8288 ** systems.
   8289 **
   8290 ** This is like output_quoted_string() but with the addition of the \r\n
   8291 ** escape mechanism.
   8292 */
   8293 static void output_quoted_escaped_string(FILE *out, const char *z){
   8294   int i;
   8295   char c;
   8296   setBinaryMode(out, 1);
   8297   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
   8298   if( c==0 ){
   8299     utf8_printf(out,"'%s'",z);
   8300   }else{
   8301     const char *zNL = 0;
   8302     const char *zCR = 0;
   8303     int nNL = 0;
   8304     int nCR = 0;
   8305     char zBuf1[20], zBuf2[20];
   8306     for(i=0; z[i]; i++){
   8307       if( z[i]=='\n' ) nNL++;
   8308       if( z[i]=='\r' ) nCR++;
   8309     }
   8310     if( nNL ){
   8311       raw_printf(out, "replace(");
   8312       zNL = unused_string(z, "\\n", "\\012", zBuf1);
   8313     }
   8314     if( nCR ){
   8315       raw_printf(out, "replace(");
   8316       zCR = unused_string(z, "\\r", "\\015", zBuf2);
   8317     }
   8318     raw_printf(out, "'");
   8319     while( *z ){
   8320       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
   8321       if( c=='\'' ) i++;
   8322       if( i ){
   8323         utf8_printf(out, "%.*s", i, z);
   8324         z += i;
   8325       }
   8326       if( c=='\'' ){
   8327         raw_printf(out, "'");
   8328         continue;
   8329       }
   8330       if( c==0 ){
   8331         break;
   8332       }
   8333       z++;
   8334       if( c=='\n' ){
   8335         raw_printf(out, "%s", zNL);
   8336         continue;
   8337       }
   8338       raw_printf(out, "%s", zCR);
   8339     }
   8340     raw_printf(out, "'");
   8341     if( nCR ){
   8342       raw_printf(out, ",'%s',char(13))", zCR);
   8343     }
   8344     if( nNL ){
   8345       raw_printf(out, ",'%s',char(10))", zNL);
   8346     }
   8347   }
   8348   setTextMode(out, 1);
   8349 }
   8350 
   8351 /*
   8352 ** Output the given string as a quoted according to C or TCL quoting rules.
   8353 */
   8354 static void output_c_string(FILE *out, const char *z){
   8355   unsigned int c;
   8356   fputc('"', out);
   8357   while( (c = *(z++))!=0 ){
   8358     if( c=='\\' ){
   8359       fputc(c, out);
   8360       fputc(c, out);
   8361     }else if( c=='"' ){
   8362       fputc('\\', out);
   8363       fputc('"', out);
   8364     }else if( c=='\t' ){
   8365       fputc('\\', out);
   8366       fputc('t', out);
   8367     }else if( c=='\n' ){
   8368       fputc('\\', out);
   8369       fputc('n', out);
   8370     }else if( c=='\r' ){
   8371       fputc('\\', out);
   8372       fputc('r', out);
   8373     }else if( !isprint(c&0xff) ){
   8374       raw_printf(out, "\\%03o", c&0xff);
   8375     }else{
   8376       fputc(c, out);
   8377     }
   8378   }
   8379   fputc('"', out);
   8380 }
   8381 
   8382 /*
   8383 ** Output the given string with characters that are special to
   8384 ** HTML escaped.
   8385 */
   8386 static void output_html_string(FILE *out, const char *z){
   8387   int i;
   8388   if( z==0 ) z = "";
   8389   while( *z ){
   8390     for(i=0;   z[i]
   8391             && z[i]!='<'
   8392             && z[i]!='&'
   8393             && z[i]!='>'
   8394             && z[i]!='\"'
   8395             && z[i]!='\'';
   8396         i++){}
   8397     if( i>0 ){
   8398       utf8_printf(out,"%.*s",i,z);
   8399     }
   8400     if( z[i]=='<' ){
   8401       raw_printf(out,"&lt;");
   8402     }else if( z[i]=='&' ){
   8403       raw_printf(out,"&amp;");
   8404     }else if( z[i]=='>' ){
   8405       raw_printf(out,"&gt;");
   8406     }else if( z[i]=='\"' ){
   8407       raw_printf(out,"&quot;");
   8408     }else if( z[i]=='\'' ){
   8409       raw_printf(out,"&#39;");
   8410     }else{
   8411       break;
   8412     }
   8413     z += i + 1;
   8414   }
   8415 }
   8416 
   8417 /*
   8418 ** If a field contains any character identified by a 1 in the following
   8419 ** array, then the string must be quoted for CSV.
   8420 */
   8421 static const char needCsvQuote[] = {
   8422   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8423   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8424   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
   8425   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   8426   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   8427   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   8428   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   8429   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
   8430   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8431   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8432   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8433   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8434   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8435   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8436   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8437   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   8438 };
   8439 
   8440 /*
   8441 ** Output a single term of CSV.  Actually, p->colSeparator is used for
   8442 ** the separator, which may or may not be a comma.  p->nullValue is
   8443 ** the null value.  Strings are quoted if necessary.  The separator
   8444 ** is only issued if bSep is true.
   8445 */
   8446 static void output_csv(ShellState *p, const char *z, int bSep){
   8447   FILE *out = p->out;
   8448   if( z==0 ){
   8449     utf8_printf(out,"%s",p->nullValue);
   8450   }else{
   8451     int i;
   8452     int nSep = strlen30(p->colSeparator);
   8453     for(i=0; z[i]; i++){
   8454       if( needCsvQuote[((unsigned char*)z)[i]]
   8455          || (z[i]==p->colSeparator[0] &&
   8456              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
   8457         i = 0;
   8458         break;
   8459       }
   8460     }
   8461     if( i==0 ){
   8462       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
   8463       utf8_printf(out, "%s", zQuoted);
   8464       sqlite3_free(zQuoted);
   8465     }else{
   8466       utf8_printf(out, "%s", z);
   8467     }
   8468   }
   8469   if( bSep ){
   8470     utf8_printf(p->out, "%s", p->colSeparator);
   8471   }
   8472 }
   8473 
   8474 /*
   8475 ** This routine runs when the user presses Ctrl-C
   8476 */
   8477 static void interrupt_handler(int NotUsed){
   8478   UNUSED_PARAMETER(NotUsed);
   8479   seenInterrupt++;
   8480   if( seenInterrupt>2 ) exit(1);
   8481   if( globalDb ) sqlite3_interrupt(globalDb);
   8482 }
   8483 
   8484 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
   8485 /*
   8486 ** This routine runs for console events (e.g. Ctrl-C) on Win32
   8487 */
   8488 static BOOL WINAPI ConsoleCtrlHandler(
   8489   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
   8490 ){
   8491   if( dwCtrlType==CTRL_C_EVENT ){
   8492     interrupt_handler(0);
   8493     return TRUE;
   8494   }
   8495   return FALSE;
   8496 }
   8497 #endif
   8498 
   8499 #ifndef SQLITE_OMIT_AUTHORIZATION
   8500 /*
   8501 ** When the ".auth ON" is set, the following authorizer callback is
   8502 ** invoked.  It always returns SQLITE_OK.
   8503 */
   8504 static int shellAuth(
   8505   void *pClientData,
   8506   int op,
   8507   const char *zA1,
   8508   const char *zA2,
   8509   const char *zA3,
   8510   const char *zA4
   8511 ){
   8512   ShellState *p = (ShellState*)pClientData;
   8513   static const char *azAction[] = { 0,
   8514      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
   8515      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
   8516      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
   8517      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
   8518      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
   8519      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
   8520      "PRAGMA",               "READ",                 "SELECT",
   8521      "TRANSACTION",          "UPDATE",               "ATTACH",
   8522      "DETACH",               "ALTER_TABLE",          "REINDEX",
   8523      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
   8524      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
   8525   };
   8526   int i;
   8527   const char *az[4];
   8528   az[0] = zA1;
   8529   az[1] = zA2;
   8530   az[2] = zA3;
   8531   az[3] = zA4;
   8532   utf8_printf(p->out, "authorizer: %s", azAction[op]);
   8533   for(i=0; i<4; i++){
   8534     raw_printf(p->out, " ");
   8535     if( az[i] ){
   8536       output_c_string(p->out, az[i]);
   8537     }else{
   8538       raw_printf(p->out, "NULL");
   8539     }
   8540   }
   8541   raw_printf(p->out, "\n");
   8542   return SQLITE_OK;
   8543 }
   8544 #endif
   8545 
   8546 /*
   8547 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
   8548 **
   8549 ** This routine converts some CREATE TABLE statements for shadow tables
   8550 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
   8551 */
   8552 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
   8553   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
   8554     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
   8555   }else{
   8556     utf8_printf(out, "%s%s", z, zTail);
   8557   }
   8558 }
   8559 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
   8560   char c = z[n];
   8561   z[n] = 0;
   8562   printSchemaLine(out, z, zTail);
   8563   z[n] = c;
   8564 }
   8565 
   8566 /*
   8567 ** Return true if string z[] has nothing but whitespace and comments to the
   8568 ** end of the first line.
   8569 */
   8570 static int wsToEol(const char *z){
   8571   int i;
   8572   for(i=0; z[i]; i++){
   8573     if( z[i]=='\n' ) return 1;
   8574     if( IsSpace(z[i]) ) continue;
   8575     if( z[i]=='-' && z[i+1]=='-' ) return 1;
   8576     return 0;
   8577   }
   8578   return 1;
   8579 }
   8580 
   8581 
   8582 /*
   8583 ** This is the callback routine that the shell
   8584 ** invokes for each row of a query result.
   8585 */
   8586 static int shell_callback(
   8587   void *pArg,
   8588   int nArg,        /* Number of result columns */
   8589   char **azArg,    /* Text of each result column */
   8590   char **azCol,    /* Column names */
   8591   int *aiType      /* Column types */
   8592 ){
   8593   int i;
   8594   ShellState *p = (ShellState*)pArg;
   8595 
   8596   if( azArg==0 ) return 0;
   8597   switch( p->cMode ){
   8598     case MODE_Line: {
   8599       int w = 5;
   8600       if( azArg==0 ) break;
   8601       for(i=0; i<nArg; i++){
   8602         int len = strlen30(azCol[i] ? azCol[i] : "");
   8603         if( len>w ) w = len;
   8604       }
   8605       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
   8606       for(i=0; i<nArg; i++){
   8607         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
   8608                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
   8609       }
   8610       break;
   8611     }
   8612     case MODE_Explain:
   8613     case MODE_Column: {
   8614       static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
   8615       const int *colWidth;
   8616       int showHdr;
   8617       char *rowSep;
   8618       if( p->cMode==MODE_Column ){
   8619         colWidth = p->colWidth;
   8620         showHdr = p->showHeader;
   8621         rowSep = p->rowSeparator;
   8622       }else{
   8623         colWidth = aExplainWidths;
   8624         showHdr = 1;
   8625         rowSep = SEP_Row;
   8626       }
   8627       if( p->cnt++==0 ){
   8628         for(i=0; i<nArg; i++){
   8629           int w, n;
   8630           if( i<ArraySize(p->colWidth) ){
   8631             w = colWidth[i];
   8632           }else{
   8633             w = 0;
   8634           }
   8635           if( w==0 ){
   8636             w = strlenChar(azCol[i] ? azCol[i] : "");
   8637             if( w<10 ) w = 10;
   8638             n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
   8639             if( w<n ) w = n;
   8640           }
   8641           if( i<ArraySize(p->actualWidth) ){
   8642             p->actualWidth[i] = w;
   8643           }
   8644           if( showHdr ){
   8645             utf8_width_print(p->out, w, azCol[i]);
   8646             utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
   8647           }
   8648         }
   8649         if( showHdr ){
   8650           for(i=0; i<nArg; i++){
   8651             int w;
   8652             if( i<ArraySize(p->actualWidth) ){
   8653                w = p->actualWidth[i];
   8654                if( w<0 ) w = -w;
   8655             }else{
   8656                w = 10;
   8657             }
   8658             utf8_printf(p->out,"%-*.*s%s",w,w,
   8659                    "----------------------------------------------------------"
   8660                    "----------------------------------------------------------",
   8661                     i==nArg-1 ? rowSep : "  ");
   8662           }
   8663         }
   8664       }
   8665       if( azArg==0 ) break;
   8666       for(i=0; i<nArg; i++){
   8667         int w;
   8668         if( i<ArraySize(p->actualWidth) ){
   8669            w = p->actualWidth[i];
   8670         }else{
   8671            w = 10;
   8672         }
   8673         if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
   8674           w = strlenChar(azArg[i]);
   8675         }
   8676         if( i==1 && p->aiIndent && p->pStmt ){
   8677           if( p->iIndent<p->nIndent ){
   8678             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
   8679           }
   8680           p->iIndent++;
   8681         }
   8682         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
   8683         utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
   8684       }
   8685       break;
   8686     }
   8687     case MODE_Semi: {   /* .schema and .fullschema output */
   8688       printSchemaLine(p->out, azArg[0], ";\n");
   8689       break;
   8690     }
   8691     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
   8692       char *z;
   8693       int j;
   8694       int nParen = 0;
   8695       char cEnd = 0;
   8696       char c;
   8697       int nLine = 0;
   8698       assert( nArg==1 );
   8699       if( azArg[0]==0 ) break;
   8700       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
   8701        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
   8702       ){
   8703         utf8_printf(p->out, "%s;\n", azArg[0]);
   8704         break;
   8705       }
   8706       z = sqlite3_mprintf("%s", azArg[0]);
   8707       j = 0;
   8708       for(i=0; IsSpace(z[i]); i++){}
   8709       for(; (c = z[i])!=0; i++){
   8710         if( IsSpace(c) ){
   8711           if( z[j-1]=='\r' ) z[j-1] = '\n';
   8712           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
   8713         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
   8714           j--;
   8715         }
   8716         z[j++] = c;
   8717       }
   8718       while( j>0 && IsSpace(z[j-1]) ){ j--; }
   8719       z[j] = 0;
   8720       if( strlen30(z)>=79 ){
   8721         for(i=j=0; (c = z[i])!=0; i++){  /* Copy changes from z[i] back to z[j] */
   8722           if( c==cEnd ){
   8723             cEnd = 0;
   8724           }else if( c=='"' || c=='\'' || c=='`' ){
   8725             cEnd = c;
   8726           }else if( c=='[' ){
   8727             cEnd = ']';
   8728           }else if( c=='-' && z[i+1]=='-' ){
   8729             cEnd = '\n';
   8730           }else if( c=='(' ){
   8731             nParen++;
   8732           }else if( c==')' ){
   8733             nParen--;
   8734             if( nLine>0 && nParen==0 && j>0 ){
   8735               printSchemaLineN(p->out, z, j, "\n");
   8736               j = 0;
   8737             }
   8738           }
   8739           z[j++] = c;
   8740           if( nParen==1 && cEnd==0
   8741            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
   8742           ){
   8743             if( c=='\n' ) j--;
   8744             printSchemaLineN(p->out, z, j, "\n  ");
   8745             j = 0;
   8746             nLine++;
   8747             while( IsSpace(z[i+1]) ){ i++; }
   8748           }
   8749         }
   8750         z[j] = 0;
   8751       }
   8752       printSchemaLine(p->out, z, ";\n");
   8753       sqlite3_free(z);
   8754       break;
   8755     }
   8756     case MODE_List: {
   8757       if( p->cnt++==0 && p->showHeader ){
   8758         for(i=0; i<nArg; i++){
   8759           utf8_printf(p->out,"%s%s",azCol[i],
   8760                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
   8761         }
   8762       }
   8763       if( azArg==0 ) break;
   8764       for(i=0; i<nArg; i++){
   8765         char *z = azArg[i];
   8766         if( z==0 ) z = p->nullValue;
   8767         utf8_printf(p->out, "%s", z);
   8768         if( i<nArg-1 ){
   8769           utf8_printf(p->out, "%s", p->colSeparator);
   8770         }else{
   8771           utf8_printf(p->out, "%s", p->rowSeparator);
   8772         }
   8773       }
   8774       break;
   8775     }
   8776     case MODE_Html: {
   8777       if( p->cnt++==0 && p->showHeader ){
   8778         raw_printf(p->out,"<TR>");
   8779         for(i=0; i<nArg; i++){
   8780           raw_printf(p->out,"<TH>");
   8781           output_html_string(p->out, azCol[i]);
   8782           raw_printf(p->out,"</TH>\n");
   8783         }
   8784         raw_printf(p->out,"</TR>\n");
   8785       }
   8786       if( azArg==0 ) break;
   8787       raw_printf(p->out,"<TR>");
   8788       for(i=0; i<nArg; i++){
   8789         raw_printf(p->out,"<TD>");
   8790         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
   8791         raw_printf(p->out,"</TD>\n");
   8792       }
   8793       raw_printf(p->out,"</TR>\n");
   8794       break;
   8795     }
   8796     case MODE_Tcl: {
   8797       if( p->cnt++==0 && p->showHeader ){
   8798         for(i=0; i<nArg; i++){
   8799           output_c_string(p->out,azCol[i] ? azCol[i] : "");
   8800           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
   8801         }
   8802         utf8_printf(p->out, "%s", p->rowSeparator);
   8803       }
   8804       if( azArg==0 ) break;
   8805       for(i=0; i<nArg; i++){
   8806         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
   8807         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
   8808       }
   8809       utf8_printf(p->out, "%s", p->rowSeparator);
   8810       break;
   8811     }
   8812     case MODE_Csv: {
   8813       setBinaryMode(p->out, 1);
   8814       if( p->cnt++==0 && p->showHeader ){
   8815         for(i=0; i<nArg; i++){
   8816           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
   8817         }
   8818         utf8_printf(p->out, "%s", p->rowSeparator);
   8819       }
   8820       if( nArg>0 ){
   8821         for(i=0; i<nArg; i++){
   8822           output_csv(p, azArg[i], i<nArg-1);
   8823         }
   8824         utf8_printf(p->out, "%s", p->rowSeparator);
   8825       }
   8826       setTextMode(p->out, 1);
   8827       break;
   8828     }
   8829     case MODE_Insert: {
   8830       if( azArg==0 ) break;
   8831       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
   8832       if( p->showHeader ){
   8833         raw_printf(p->out,"(");
   8834         for(i=0; i<nArg; i++){
   8835           if( i>0 ) raw_printf(p->out, ",");
   8836           if( quoteChar(azCol[i]) ){
   8837             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
   8838             utf8_printf(p->out, "%s", z);
   8839             sqlite3_free(z);
   8840           }else{
   8841             raw_printf(p->out, "%s", azCol[i]);
   8842           }
   8843         }
   8844         raw_printf(p->out,")");
   8845       }
   8846       p->cnt++;
   8847       for(i=0; i<nArg; i++){
   8848         raw_printf(p->out, i>0 ? "," : " VALUES(");
   8849         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
   8850           utf8_printf(p->out,"NULL");
   8851         }else if( aiType && aiType[i]==SQLITE_TEXT ){
   8852           if( ShellHasFlag(p, SHFLG_Newlines) ){
   8853             output_quoted_string(p->out, azArg[i]);
   8854           }else{
   8855             output_quoted_escaped_string(p->out, azArg[i]);
   8856           }
   8857         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
   8858           utf8_printf(p->out,"%s", azArg[i]);
   8859         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
   8860           char z[50];
   8861           double r = sqlite3_column_double(p->pStmt, i);
   8862           sqlite3_snprintf(50,z,"%!.20g", r);
   8863           raw_printf(p->out, "%s", z);
   8864         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
   8865           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
   8866           int nBlob = sqlite3_column_bytes(p->pStmt, i);
   8867           output_hex_blob(p->out, pBlob, nBlob);
   8868         }else if( isNumber(azArg[i], 0) ){
   8869           utf8_printf(p->out,"%s", azArg[i]);
   8870         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
   8871           output_quoted_string(p->out, azArg[i]);
   8872         }else{
   8873           output_quoted_escaped_string(p->out, azArg[i]);
   8874         }
   8875       }
   8876       raw_printf(p->out,");\n");
   8877       break;
   8878     }
   8879     case MODE_Quote: {
   8880       if( azArg==0 ) break;
   8881       if( p->cnt==0 && p->showHeader ){
   8882         for(i=0; i<nArg; i++){
   8883           if( i>0 ) raw_printf(p->out, ",");
   8884           output_quoted_string(p->out, azCol[i]);
   8885         }
   8886         raw_printf(p->out,"\n");
   8887       }
   8888       p->cnt++;
   8889       for(i=0; i<nArg; i++){
   8890         if( i>0 ) raw_printf(p->out, ",");
   8891         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
   8892           utf8_printf(p->out,"NULL");
   8893         }else if( aiType && aiType[i]==SQLITE_TEXT ){
   8894           output_quoted_string(p->out, azArg[i]);
   8895         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
   8896           utf8_printf(p->out,"%s", azArg[i]);
   8897         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
   8898           char z[50];
   8899           double r = sqlite3_column_double(p->pStmt, i);
   8900           sqlite3_snprintf(50,z,"%!.20g", r);
   8901           raw_printf(p->out, "%s", z);
   8902         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
   8903           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
   8904           int nBlob = sqlite3_column_bytes(p->pStmt, i);
   8905           output_hex_blob(p->out, pBlob, nBlob);
   8906         }else if( isNumber(azArg[i], 0) ){
   8907           utf8_printf(p->out,"%s", azArg[i]);
   8908         }else{
   8909           output_quoted_string(p->out, azArg[i]);
   8910         }
   8911       }
   8912       raw_printf(p->out,"\n");
   8913       break;
   8914     }
   8915     case MODE_Ascii: {
   8916       if( p->cnt++==0 && p->showHeader ){
   8917         for(i=0; i<nArg; i++){
   8918           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
   8919           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
   8920         }
   8921         utf8_printf(p->out, "%s", p->rowSeparator);
   8922       }
   8923       if( azArg==0 ) break;
   8924       for(i=0; i<nArg; i++){
   8925         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
   8926         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
   8927       }
   8928       utf8_printf(p->out, "%s", p->rowSeparator);
   8929       break;
   8930     }
   8931   }
   8932   return 0;
   8933 }
   8934 
   8935 /*
   8936 ** This is the callback routine that the SQLite library
   8937 ** invokes for each row of a query result.
   8938 */
   8939 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
   8940   /* since we don't have type info, call the shell_callback with a NULL value */
   8941   return shell_callback(pArg, nArg, azArg, azCol, NULL);
   8942 }
   8943 
   8944 /*
   8945 ** This is the callback routine from sqlite3_exec() that appends all
   8946 ** output onto the end of a ShellText object.
   8947 */
   8948 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
   8949   ShellText *p = (ShellText*)pArg;
   8950   int i;
   8951   UNUSED_PARAMETER(az);
   8952   if( azArg==0 ) return 0;
   8953   if( p->n ) appendText(p, "|", 0);
   8954   for(i=0; i<nArg; i++){
   8955     if( i ) appendText(p, ",", 0);
   8956     if( azArg[i] ) appendText(p, azArg[i], 0);
   8957   }
   8958   return 0;
   8959 }
   8960 
   8961 /*
   8962 ** Generate an appropriate SELFTEST table in the main database.
   8963 */
   8964 static void createSelftestTable(ShellState *p){
   8965   char *zErrMsg = 0;
   8966   sqlite3_exec(p->db,
   8967     "SAVEPOINT selftest_init;\n"
   8968     "CREATE TABLE IF NOT EXISTS selftest(\n"
   8969     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
   8970     "  op TEXT,\n"                   /* Operator:  memo run */
   8971     "  cmd TEXT,\n"                  /* Command text */
   8972     "  ans TEXT\n"                   /* Desired answer */
   8973     ");"
   8974     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
   8975     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
   8976     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
   8977     "         'memo','Tests generated by --init');\n"
   8978     "INSERT INTO [_shell$self]\n"
   8979     "  SELECT 'run',\n"
   8980     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
   8981                                  "FROM sqlite_master ORDER BY 2'',224))',\n"
   8982     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
   8983                           "FROM sqlite_master ORDER BY 2',224));\n"
   8984     "INSERT INTO [_shell$self]\n"
   8985     "  SELECT 'run',"
   8986     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
   8987     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
   8988     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
   8989     "  FROM (\n"
   8990     "    SELECT name FROM sqlite_master\n"
   8991     "     WHERE type='table'\n"
   8992     "       AND name<>'selftest'\n"
   8993     "       AND coalesce(rootpage,0)>0\n"
   8994     "  )\n"
   8995     " ORDER BY name;\n"
   8996     "INSERT INTO [_shell$self]\n"
   8997     "  VALUES('run','PRAGMA integrity_check','ok');\n"
   8998     "INSERT INTO selftest(tno,op,cmd,ans)"
   8999     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
   9000     "DROP TABLE [_shell$self];"
   9001     ,0,0,&zErrMsg);
   9002   if( zErrMsg ){
   9003     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
   9004     sqlite3_free(zErrMsg);
   9005   }
   9006   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
   9007 }
   9008 
   9009 
   9010 /*
   9011 ** Set the destination table field of the ShellState structure to
   9012 ** the name of the table given.  Escape any quote characters in the
   9013 ** table name.
   9014 */
   9015 static void set_table_name(ShellState *p, const char *zName){
   9016   int i, n;
   9017   char cQuote;
   9018   char *z;
   9019 
   9020   if( p->zDestTable ){
   9021     free(p->zDestTable);
   9022     p->zDestTable = 0;
   9023   }
   9024   if( zName==0 ) return;
   9025   cQuote = quoteChar(zName);
   9026   n = strlen30(zName);
   9027   if( cQuote ) n += n+2;
   9028   z = p->zDestTable = malloc( n+1 );
   9029   if( z==0 ){
   9030     raw_printf(stderr,"Error: out of memory\n");
   9031     exit(1);
   9032   }
   9033   n = 0;
   9034   if( cQuote ) z[n++] = cQuote;
   9035   for(i=0; zName[i]; i++){
   9036     z[n++] = zName[i];
   9037     if( zName[i]==cQuote ) z[n++] = cQuote;
   9038   }
   9039   if( cQuote ) z[n++] = cQuote;
   9040   z[n] = 0;
   9041 }
   9042 
   9043 
   9044 /*
   9045 ** Execute a query statement that will generate SQL output.  Print
   9046 ** the result columns, comma-separated, on a line and then add a
   9047 ** semicolon terminator to the end of that line.
   9048 **
   9049 ** If the number of columns is 1 and that column contains text "--"
   9050 ** then write the semicolon on a separate line.  That way, if a
   9051 ** "--" comment occurs at the end of the statement, the comment
   9052 ** won't consume the semicolon terminator.
   9053 */
   9054 static int run_table_dump_query(
   9055   ShellState *p,           /* Query context */
   9056   const char *zSelect,     /* SELECT statement to extract content */
   9057   const char *zFirstRow    /* Print before first row, if not NULL */
   9058 ){
   9059   sqlite3_stmt *pSelect;
   9060   int rc;
   9061   int nResult;
   9062   int i;
   9063   const char *z;
   9064   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
   9065   if( rc!=SQLITE_OK || !pSelect ){
   9066     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
   9067                 sqlite3_errmsg(p->db));
   9068     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
   9069     return rc;
   9070   }
   9071   rc = sqlite3_step(pSelect);
   9072   nResult = sqlite3_column_count(pSelect);
   9073   while( rc==SQLITE_ROW ){
   9074     if( zFirstRow ){
   9075       utf8_printf(p->out, "%s", zFirstRow);
   9076       zFirstRow = 0;
   9077     }
   9078     z = (const char*)sqlite3_column_text(pSelect, 0);
   9079     utf8_printf(p->out, "%s", z);
   9080     for(i=1; i<nResult; i++){
   9081       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
   9082     }
   9083     if( z==0 ) z = "";
   9084     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
   9085     if( z[0] ){
   9086       raw_printf(p->out, "\n;\n");
   9087     }else{
   9088       raw_printf(p->out, ";\n");
   9089     }
   9090     rc = sqlite3_step(pSelect);
   9091   }
   9092   rc = sqlite3_finalize(pSelect);
   9093   if( rc!=SQLITE_OK ){
   9094     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
   9095                 sqlite3_errmsg(p->db));
   9096     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
   9097   }
   9098   return rc;
   9099 }
   9100 
   9101 /*
   9102 ** Allocate space and save off current error string.
   9103 */
   9104 static char *save_err_msg(
   9105   sqlite3 *db            /* Database to query */
   9106 ){
   9107   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
   9108   char *zErrMsg = sqlite3_malloc64(nErrMsg);
   9109   if( zErrMsg ){
   9110     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
   9111   }
   9112   return zErrMsg;
   9113 }
   9114 
   9115 #ifdef __linux__
   9116 /*
   9117 ** Attempt to display I/O stats on Linux using /proc/PID/io
   9118 */
   9119 static void displayLinuxIoStats(FILE *out){
   9120   FILE *in;
   9121   char z[200];
   9122   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
   9123   in = fopen(z, "rb");
   9124   if( in==0 ) return;
   9125   while( fgets(z, sizeof(z), in)!=0 ){
   9126     static const struct {
   9127       const char *zPattern;
   9128       const char *zDesc;
   9129     } aTrans[] = {
   9130       { "rchar: ",                  "Bytes received by read():" },
   9131       { "wchar: ",                  "Bytes sent to write():"    },
   9132       { "syscr: ",                  "Read() system calls:"      },
   9133       { "syscw: ",                  "Write() system calls:"     },
   9134       { "read_bytes: ",             "Bytes read from storage:"  },
   9135       { "write_bytes: ",            "Bytes written to storage:" },
   9136       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
   9137     };
   9138     int i;
   9139     for(i=0; i<ArraySize(aTrans); i++){
   9140       int n = strlen30(aTrans[i].zPattern);
   9141       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
   9142         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
   9143         break;
   9144       }
   9145     }
   9146   }
   9147   fclose(in);
   9148 }
   9149 #endif
   9150 
   9151 /*
   9152 ** Display a single line of status using 64-bit values.
   9153 */
   9154 static void displayStatLine(
   9155   ShellState *p,            /* The shell context */
   9156   char *zLabel,             /* Label for this one line */
   9157   char *zFormat,            /* Format for the result */
   9158   int iStatusCtrl,          /* Which status to display */
   9159   int bReset                /* True to reset the stats */
   9160 ){
   9161   sqlite3_int64 iCur = -1;
   9162   sqlite3_int64 iHiwtr = -1;
   9163   int i, nPercent;
   9164   char zLine[200];
   9165   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
   9166   for(i=0, nPercent=0; zFormat[i]; i++){
   9167     if( zFormat[i]=='%' ) nPercent++;
   9168   }
   9169   if( nPercent>1 ){
   9170     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
   9171   }else{
   9172     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
   9173   }
   9174   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
   9175 }
   9176 
   9177 /*
   9178 ** Display memory stats.
   9179 */
   9180 static int display_stats(
   9181   sqlite3 *db,                /* Database to query */
   9182   ShellState *pArg,           /* Pointer to ShellState */
   9183   int bReset                  /* True to reset the stats */
   9184 ){
   9185   int iCur;
   9186   int iHiwtr;
   9187 
   9188   if( pArg && pArg->out ){
   9189     displayStatLine(pArg, "Memory Used:",
   9190        "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
   9191     displayStatLine(pArg, "Number of Outstanding Allocations:",
   9192        "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
   9193     if( pArg->shellFlgs & SHFLG_Pagecache ){
   9194       displayStatLine(pArg, "Number of Pcache Pages Used:",
   9195          "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
   9196     }
   9197     displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
   9198        "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
   9199     displayStatLine(pArg, "Largest Allocation:",
   9200        "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
   9201     displayStatLine(pArg, "Largest Pcache Allocation:",
   9202        "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
   9203 #ifdef YYTRACKMAXSTACKDEPTH
   9204     displayStatLine(pArg, "Deepest Parser Stack:",
   9205        "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
   9206 #endif
   9207   }
   9208 
   9209   if( pArg && pArg->out && db ){
   9210     if( pArg->shellFlgs & SHFLG_Lookaside ){
   9211       iHiwtr = iCur = -1;
   9212       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
   9213                         &iCur, &iHiwtr, bReset);
   9214       raw_printf(pArg->out,
   9215               "Lookaside Slots Used:                %d (max %d)\n",
   9216               iCur, iHiwtr);
   9217       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
   9218                         &iCur, &iHiwtr, bReset);
   9219       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
   9220               iHiwtr);
   9221       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
   9222                         &iCur, &iHiwtr, bReset);
   9223       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
   9224               iHiwtr);
   9225       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
   9226                         &iCur, &iHiwtr, bReset);
   9227       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
   9228               iHiwtr);
   9229     }
   9230     iHiwtr = iCur = -1;
   9231     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
   9232     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
   9233             iCur);
   9234     iHiwtr = iCur = -1;
   9235     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
   9236     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
   9237     iHiwtr = iCur = -1;
   9238     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
   9239     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
   9240     iHiwtr = iCur = -1;
   9241     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
   9242     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
   9243     iHiwtr = iCur = -1;
   9244     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
   9245     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
   9246             iCur);
   9247     iHiwtr = iCur = -1;
   9248     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
   9249     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
   9250             iCur);
   9251   }
   9252 
   9253   if( pArg && pArg->out && db && pArg->pStmt ){
   9254     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
   9255                                bReset);
   9256     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
   9257     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
   9258     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
   9259     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
   9260     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
   9261     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
   9262     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
   9263   }
   9264 
   9265 #ifdef __linux__
   9266   displayLinuxIoStats(pArg->out);
   9267 #endif
   9268 
   9269   /* Do not remove this machine readable comment: extra-stats-output-here */
   9270 
   9271   return 0;
   9272 }
   9273 
   9274 /*
   9275 ** Display scan stats.
   9276 */
   9277 static void display_scanstats(
   9278   sqlite3 *db,                    /* Database to query */
   9279   ShellState *pArg                /* Pointer to ShellState */
   9280 ){
   9281 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
   9282   UNUSED_PARAMETER(db);
   9283   UNUSED_PARAMETER(pArg);
   9284 #else
   9285   int i, k, n, mx;
   9286   raw_printf(pArg->out, "-------- scanstats --------\n");
   9287   mx = 0;
   9288   for(k=0; k<=mx; k++){
   9289     double rEstLoop = 1.0;
   9290     for(i=n=0; 1; i++){
   9291       sqlite3_stmt *p = pArg->pStmt;
   9292       sqlite3_int64 nLoop, nVisit;
   9293       double rEst;
   9294       int iSid;
   9295       const char *zExplain;
   9296       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
   9297         break;
   9298       }
   9299       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
   9300       if( iSid>mx ) mx = iSid;
   9301       if( iSid!=k ) continue;
   9302       if( n==0 ){
   9303         rEstLoop = (double)nLoop;
   9304         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
   9305       }
   9306       n++;
   9307       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
   9308       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
   9309       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
   9310       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
   9311       rEstLoop *= rEst;
   9312       raw_printf(pArg->out,
   9313           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
   9314           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
   9315       );
   9316     }
   9317   }
   9318   raw_printf(pArg->out, "---------------------------\n");
   9319 #endif
   9320 }
   9321 
   9322 /*
   9323 ** Parameter azArray points to a zero-terminated array of strings. zStr
   9324 ** points to a single nul-terminated string. Return non-zero if zStr
   9325 ** is equal, according to strcmp(), to any of the strings in the array.
   9326 ** Otherwise, return zero.
   9327 */
   9328 static int str_in_array(const char *zStr, const char **azArray){
   9329   int i;
   9330   for(i=0; azArray[i]; i++){
   9331     if( 0==strcmp(zStr, azArray[i]) ) return 1;
   9332   }
   9333   return 0;
   9334 }
   9335 
   9336 /*
   9337 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
   9338 ** and populate the ShellState.aiIndent[] array with the number of
   9339 ** spaces each opcode should be indented before it is output.
   9340 **
   9341 ** The indenting rules are:
   9342 **
   9343 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
   9344 **       all opcodes that occur between the p2 jump destination and the opcode
   9345 **       itself by 2 spaces.
   9346 **
   9347 **     * For each "Goto", if the jump destination is earlier in the program
   9348 **       and ends on one of:
   9349 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
   9350 **       or if the P1 parameter is one instead of zero,
   9351 **       then indent all opcodes between the earlier instruction
   9352 **       and "Goto" by 2 spaces.
   9353 */
   9354 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
   9355   const char *zSql;               /* The text of the SQL statement */
   9356   const char *z;                  /* Used to check if this is an EXPLAIN */
   9357   int *abYield = 0;               /* True if op is an OP_Yield */
   9358   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
   9359   int iOp;                        /* Index of operation in p->aiIndent[] */
   9360 
   9361   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
   9362                            "NextIfOpen", "PrevIfOpen", 0 };
   9363   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
   9364                             "Rewind", 0 };
   9365   const char *azGoto[] = { "Goto", 0 };
   9366 
   9367   /* Try to figure out if this is really an EXPLAIN statement. If this
   9368   ** cannot be verified, return early.  */
   9369   if( sqlite3_column_count(pSql)!=8 ){
   9370     p->cMode = p->mode;
   9371     return;
   9372   }
   9373   zSql = sqlite3_sql(pSql);
   9374   if( zSql==0 ) return;
   9375   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
   9376   if( sqlite3_strnicmp(z, "explain", 7) ){
   9377     p->cMode = p->mode;
   9378     return;
   9379   }
   9380 
   9381   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
   9382     int i;
   9383     int iAddr = sqlite3_column_int(pSql, 0);
   9384     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
   9385 
   9386     /* Set p2 to the P2 field of the current opcode. Then, assuming that
   9387     ** p2 is an instruction address, set variable p2op to the index of that
   9388     ** instruction in the aiIndent[] array. p2 and p2op may be different if
   9389     ** the current instruction is part of a sub-program generated by an
   9390     ** SQL trigger or foreign key.  */
   9391     int p2 = sqlite3_column_int(pSql, 3);
   9392     int p2op = (p2 + (iOp-iAddr));
   9393 
   9394     /* Grow the p->aiIndent array as required */
   9395     if( iOp>=nAlloc ){
   9396       if( iOp==0 ){
   9397         /* Do further verfication that this is explain output.  Abort if
   9398         ** it is not */
   9399         static const char *explainCols[] = {
   9400            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
   9401         int jj;
   9402         for(jj=0; jj<ArraySize(explainCols); jj++){
   9403           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
   9404             p->cMode = p->mode;
   9405             sqlite3_reset(pSql);
   9406             return;
   9407           }
   9408         }
   9409       }
   9410       nAlloc += 100;
   9411       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
   9412       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
   9413     }
   9414     abYield[iOp] = str_in_array(zOp, azYield);
   9415     p->aiIndent[iOp] = 0;
   9416     p->nIndent = iOp+1;
   9417 
   9418     if( str_in_array(zOp, azNext) ){
   9419       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
   9420     }
   9421     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
   9422      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
   9423     ){
   9424       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
   9425     }
   9426   }
   9427 
   9428   p->iIndent = 0;
   9429   sqlite3_free(abYield);
   9430   sqlite3_reset(pSql);
   9431 }
   9432 
   9433 /*
   9434 ** Free the array allocated by explain_data_prepare().
   9435 */
   9436 static void explain_data_delete(ShellState *p){
   9437   sqlite3_free(p->aiIndent);
   9438   p->aiIndent = 0;
   9439   p->nIndent = 0;
   9440   p->iIndent = 0;
   9441 }
   9442 
   9443 /*
   9444 ** Disable and restore .wheretrace and .selecttrace settings.
   9445 */
   9446 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
   9447 extern int sqlite3SelectTrace;
   9448 static int savedSelectTrace;
   9449 #endif
   9450 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
   9451 extern int sqlite3WhereTrace;
   9452 static int savedWhereTrace;
   9453 #endif
   9454 static void disable_debug_trace_modes(void){
   9455 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
   9456   savedSelectTrace = sqlite3SelectTrace;
   9457   sqlite3SelectTrace = 0;
   9458 #endif
   9459 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
   9460   savedWhereTrace = sqlite3WhereTrace;
   9461   sqlite3WhereTrace = 0;
   9462 #endif
   9463 }
   9464 static void restore_debug_trace_modes(void){
   9465 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
   9466   sqlite3SelectTrace = savedSelectTrace;
   9467 #endif
   9468 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
   9469   sqlite3WhereTrace = savedWhereTrace;
   9470 #endif
   9471 }
   9472 
   9473 /*
   9474 ** Run a prepared statement
   9475 */
   9476 static void exec_prepared_stmt(
   9477   ShellState *pArg,                                /* Pointer to ShellState */
   9478   sqlite3_stmt *pStmt,                             /* Statment to run */
   9479   int (*xCallback)(void*,int,char**,char**,int*)   /* Callback function */
   9480 ){
   9481   int rc;
   9482 
   9483   /* perform the first step.  this will tell us if we
   9484   ** have a result set or not and how wide it is.
   9485   */
   9486   rc = sqlite3_step(pStmt);
   9487   /* if we have a result set... */
   9488   if( SQLITE_ROW == rc ){
   9489     /* if we have a callback... */
   9490     if( xCallback ){
   9491       /* allocate space for col name ptr, value ptr, and type */
   9492       int nCol = sqlite3_column_count(pStmt);
   9493       void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
   9494       if( !pData ){
   9495         rc = SQLITE_NOMEM;
   9496       }else{
   9497         char **azCols = (char **)pData;      /* Names of result columns */
   9498         char **azVals = &azCols[nCol];       /* Results */
   9499         int *aiTypes = (int *)&azVals[nCol]; /* Result types */
   9500         int i, x;
   9501         assert(sizeof(int) <= sizeof(char *));
   9502         /* save off ptrs to column names */
   9503         for(i=0; i<nCol; i++){
   9504           azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   9505         }
   9506         do{
   9507           /* extract the data and data types */
   9508           for(i=0; i<nCol; i++){
   9509             aiTypes[i] = x = sqlite3_column_type(pStmt, i);
   9510             if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
   9511               azVals[i] = "";
   9512             }else{
   9513               azVals[i] = (char*)sqlite3_column_text(pStmt, i);
   9514             }
   9515             if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
   9516               rc = SQLITE_NOMEM;
   9517               break; /* from for */
   9518             }
   9519           } /* end for */
   9520 
   9521           /* if data and types extracted successfully... */
   9522           if( SQLITE_ROW == rc ){
   9523             /* call the supplied callback with the result row data */
   9524             if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
   9525               rc = SQLITE_ABORT;
   9526             }else{
   9527               rc = sqlite3_step(pStmt);
   9528             }
   9529           }
   9530         } while( SQLITE_ROW == rc );
   9531         sqlite3_free(pData);
   9532       }
   9533     }else{
   9534       do{
   9535         rc = sqlite3_step(pStmt);
   9536       } while( rc == SQLITE_ROW );
   9537     }
   9538   }
   9539 }
   9540 
   9541 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9542 /*
   9543 ** This function is called to process SQL if the previous shell command
   9544 ** was ".expert". It passes the SQL in the second argument directly to
   9545 ** the sqlite3expert object.
   9546 **
   9547 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
   9548 ** code. In this case, (*pzErr) may be set to point to a buffer containing
   9549 ** an English language error message. It is the responsibility of the
   9550 ** caller to eventually free this buffer using sqlite3_free().
   9551 */
   9552 static int expertHandleSQL(
   9553   ShellState *pState,
   9554   const char *zSql,
   9555   char **pzErr
   9556 ){
   9557   assert( pState->expert.pExpert );
   9558   assert( pzErr==0 || *pzErr==0 );
   9559   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
   9560 }
   9561 
   9562 /*
   9563 ** This function is called either to silently clean up the object
   9564 ** created by the ".expert" command (if bCancel==1), or to generate a
   9565 ** report from it and then clean it up (if bCancel==0).
   9566 **
   9567 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
   9568 ** code. In this case, (*pzErr) may be set to point to a buffer containing
   9569 ** an English language error message. It is the responsibility of the
   9570 ** caller to eventually free this buffer using sqlite3_free().
   9571 */
   9572 static int expertFinish(
   9573   ShellState *pState,
   9574   int bCancel,
   9575   char **pzErr
   9576 ){
   9577   int rc = SQLITE_OK;
   9578   sqlite3expert *p = pState->expert.pExpert;
   9579   assert( p );
   9580   assert( bCancel || pzErr==0 || *pzErr==0 );
   9581   if( bCancel==0 ){
   9582     FILE *out = pState->out;
   9583     int bVerbose = pState->expert.bVerbose;
   9584 
   9585     rc = sqlite3_expert_analyze(p, pzErr);
   9586     if( rc==SQLITE_OK ){
   9587       int nQuery = sqlite3_expert_count(p);
   9588       int i;
   9589 
   9590       if( bVerbose ){
   9591         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
   9592         raw_printf(out, "-- Candidates -----------------------------\n");
   9593         raw_printf(out, "%s\n", zCand);
   9594       }
   9595       for(i=0; i<nQuery; i++){
   9596         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
   9597         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
   9598         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
   9599         if( zIdx==0 ) zIdx = "(no new indexes)\n";
   9600         if( bVerbose ){
   9601           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
   9602           raw_printf(out, "%s\n\n", zSql);
   9603         }
   9604         raw_printf(out, "%s\n", zIdx);
   9605         raw_printf(out, "%s\n", zEQP);
   9606       }
   9607     }
   9608   }
   9609   sqlite3_expert_destroy(p);
   9610   pState->expert.pExpert = 0;
   9611   return rc;
   9612 }
   9613 
   9614 /*
   9615 ** Implementation of ".expert" dot command.
   9616 */
   9617 static int expertDotCommand(
   9618   ShellState *pState,             /* Current shell tool state */
   9619   char **azArg,                   /* Array of arguments passed to dot command */
   9620   int nArg                        /* Number of entries in azArg[] */
   9621 ){
   9622   int rc = SQLITE_OK;
   9623   char *zErr = 0;
   9624   int i;
   9625   int iSample = 0;
   9626 
   9627   assert( pState->expert.pExpert==0 );
   9628   memset(&pState->expert, 0, sizeof(ExpertInfo));
   9629 
   9630   for(i=1; rc==SQLITE_OK && i<nArg; i++){
   9631     char *z = azArg[i];
   9632     int n;
   9633     if( z[0]=='-' && z[1]=='-' ) z++;
   9634     n = strlen30(z);
   9635     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
   9636       pState->expert.bVerbose = 1;
   9637     }
   9638     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
   9639       if( i==(nArg-1) ){
   9640         raw_printf(stderr, "option requires an argument: %s\n", z);
   9641         rc = SQLITE_ERROR;
   9642       }else{
   9643         iSample = (int)integerValue(azArg[++i]);
   9644         if( iSample<0 || iSample>100 ){
   9645           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
   9646           rc = SQLITE_ERROR;
   9647         }
   9648       }
   9649     }
   9650     else{
   9651       raw_printf(stderr, "unknown option: %s\n", z);
   9652       rc = SQLITE_ERROR;
   9653     }
   9654   }
   9655 
   9656   if( rc==SQLITE_OK ){
   9657     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
   9658     if( pState->expert.pExpert==0 ){
   9659       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
   9660       rc = SQLITE_ERROR;
   9661     }else{
   9662       sqlite3_expert_config(
   9663           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
   9664       );
   9665     }
   9666   }
   9667 
   9668   return rc;
   9669 }
   9670 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
   9671 
   9672 /*
   9673 ** Execute a statement or set of statements.  Print
   9674 ** any result rows/columns depending on the current mode
   9675 ** set via the supplied callback.
   9676 **
   9677 ** This is very similar to SQLite's built-in sqlite3_exec()
   9678 ** function except it takes a slightly different callback
   9679 ** and callback data argument.
   9680 */
   9681 static int shell_exec(
   9682   sqlite3 *db,                              /* An open database */
   9683   const char *zSql,                         /* SQL to be evaluated */
   9684   int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
   9685                                             /* (not the same as sqlite3_exec) */
   9686   ShellState *pArg,                         /* Pointer to ShellState */
   9687   char **pzErrMsg                           /* Error msg written here */
   9688 ){
   9689   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
   9690   int rc = SQLITE_OK;             /* Return Code */
   9691   int rc2;
   9692   const char *zLeftover;          /* Tail of unprocessed SQL */
   9693 
   9694   if( pzErrMsg ){
   9695     *pzErrMsg = NULL;
   9696   }
   9697 
   9698 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9699   if( pArg->expert.pExpert ){
   9700     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
   9701     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
   9702   }
   9703 #endif
   9704 
   9705   while( zSql[0] && (SQLITE_OK == rc) ){
   9706     static const char *zStmtSql;
   9707     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
   9708     if( SQLITE_OK != rc ){
   9709       if( pzErrMsg ){
   9710         *pzErrMsg = save_err_msg(db);
   9711       }
   9712     }else{
   9713       if( !pStmt ){
   9714         /* this happens for a comment or white-space */
   9715         zSql = zLeftover;
   9716         while( IsSpace(zSql[0]) ) zSql++;
   9717         continue;
   9718       }
   9719       zStmtSql = sqlite3_sql(pStmt);
   9720       if( zStmtSql==0 ) zStmtSql = "";
   9721       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
   9722 
   9723       /* save off the prepared statment handle and reset row count */
   9724       if( pArg ){
   9725         pArg->pStmt = pStmt;
   9726         pArg->cnt = 0;
   9727       }
   9728 
   9729       /* echo the sql statement if echo on */
   9730       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
   9731         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
   9732       }
   9733 
   9734       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
   9735       if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
   9736         sqlite3_stmt *pExplain;
   9737         char *zEQP;
   9738         int triggerEQP = 0;
   9739         disable_debug_trace_modes();
   9740         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
   9741         if( pArg->autoEQP>=AUTOEQP_trigger ){
   9742           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
   9743         }
   9744         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
   9745         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
   9746         if( rc==SQLITE_OK ){
   9747           while( sqlite3_step(pExplain)==SQLITE_ROW ){
   9748             raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
   9749             raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
   9750             raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
   9751             utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
   9752           }
   9753         }
   9754         sqlite3_finalize(pExplain);
   9755         sqlite3_free(zEQP);
   9756         if( pArg->autoEQP>=AUTOEQP_full ){
   9757           /* Also do an EXPLAIN for ".eqp full" mode */
   9758           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
   9759           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
   9760           if( rc==SQLITE_OK ){
   9761             pArg->cMode = MODE_Explain;
   9762             explain_data_prepare(pArg, pExplain);
   9763             exec_prepared_stmt(pArg, pExplain, xCallback);
   9764             explain_data_delete(pArg);
   9765           }
   9766           sqlite3_finalize(pExplain);
   9767           sqlite3_free(zEQP);
   9768         }
   9769         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
   9770         restore_debug_trace_modes();
   9771       }
   9772 
   9773       if( pArg ){
   9774         pArg->cMode = pArg->mode;
   9775         if( pArg->autoExplain
   9776          && sqlite3_column_count(pStmt)==8
   9777          && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
   9778         ){
   9779           pArg->cMode = MODE_Explain;
   9780         }
   9781 
   9782         /* If the shell is currently in ".explain" mode, gather the extra
   9783         ** data required to add indents to the output.*/
   9784         if( pArg->cMode==MODE_Explain ){
   9785           explain_data_prepare(pArg, pStmt);
   9786         }
   9787       }
   9788 
   9789       exec_prepared_stmt(pArg, pStmt, xCallback);
   9790       explain_data_delete(pArg);
   9791 
   9792       /* print usage stats if stats on */
   9793       if( pArg && pArg->statsOn ){
   9794         display_stats(db, pArg, 0);
   9795       }
   9796 
   9797       /* print loop-counters if required */
   9798       if( pArg && pArg->scanstatsOn ){
   9799         display_scanstats(db, pArg);
   9800       }
   9801 
   9802       /* Finalize the statement just executed. If this fails, save a
   9803       ** copy of the error message. Otherwise, set zSql to point to the
   9804       ** next statement to execute. */
   9805       rc2 = sqlite3_finalize(pStmt);
   9806       if( rc!=SQLITE_NOMEM ) rc = rc2;
   9807       if( rc==SQLITE_OK ){
   9808         zSql = zLeftover;
   9809         while( IsSpace(zSql[0]) ) zSql++;
   9810       }else if( pzErrMsg ){
   9811         *pzErrMsg = save_err_msg(db);
   9812       }
   9813 
   9814       /* clear saved stmt handle */
   9815       if( pArg ){
   9816         pArg->pStmt = NULL;
   9817       }
   9818     }
   9819   } /* end while */
   9820 
   9821   return rc;
   9822 }
   9823 
   9824 /*
   9825 ** Release memory previously allocated by tableColumnList().
   9826 */
   9827 static void freeColumnList(char **azCol){
   9828   int i;
   9829   for(i=1; azCol[i]; i++){
   9830     sqlite3_free(azCol[i]);
   9831   }
   9832   /* azCol[0] is a static string */
   9833   sqlite3_free(azCol);
   9834 }
   9835 
   9836 /*
   9837 ** Return a list of pointers to strings which are the names of all
   9838 ** columns in table zTab.   The memory to hold the names is dynamically
   9839 ** allocated and must be released by the caller using a subsequent call
   9840 ** to freeColumnList().
   9841 **
   9842 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
   9843 ** value that needs to be preserved, then azCol[0] is filled in with the
   9844 ** name of the rowid column.
   9845 **
   9846 ** The first regular column in the table is azCol[1].  The list is terminated
   9847 ** by an entry with azCol[i]==0.
   9848 */
   9849 static char **tableColumnList(ShellState *p, const char *zTab){
   9850   char **azCol = 0;
   9851   sqlite3_stmt *pStmt;
   9852   char *zSql;
   9853   int nCol = 0;
   9854   int nAlloc = 0;
   9855   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
   9856   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
   9857   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
   9858   int rc;
   9859 
   9860   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
   9861   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   9862   sqlite3_free(zSql);
   9863   if( rc ) return 0;
   9864   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   9865     if( nCol>=nAlloc-2 ){
   9866       nAlloc = nAlloc*2 + nCol + 10;
   9867       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
   9868       if( azCol==0 ){
   9869         raw_printf(stderr, "Error: out of memory\n");
   9870         exit(1);
   9871       }
   9872     }
   9873     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
   9874     if( sqlite3_column_int(pStmt, 5) ){
   9875       nPK++;
   9876       if( nPK==1
   9877        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
   9878                           "INTEGER")==0
   9879       ){
   9880         isIPK = 1;
   9881       }else{
   9882         isIPK = 0;
   9883       }
   9884     }
   9885   }
   9886   sqlite3_finalize(pStmt);
   9887   if( azCol==0 ) return 0;
   9888   azCol[0] = 0;
   9889   azCol[nCol+1] = 0;
   9890 
   9891   /* The decision of whether or not a rowid really needs to be preserved
   9892   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
   9893   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
   9894   ** rowids on tables where the rowid is inaccessible because there are other
   9895   ** columns in the table named "rowid", "_rowid_", and "oid".
   9896   */
   9897   if( preserveRowid && isIPK ){
   9898     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
   9899     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
   9900     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
   9901     ** ROWID aliases.  To distinguish these cases, check to see if
   9902     ** there is a "pk" entry in "PRAGMA index_list".  There will be
   9903     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
   9904     */
   9905     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
   9906                            " WHERE origin='pk'", zTab);
   9907     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   9908     sqlite3_free(zSql);
   9909     if( rc ){
   9910       freeColumnList(azCol);
   9911       return 0;
   9912     }
   9913     rc = sqlite3_step(pStmt);
   9914     sqlite3_finalize(pStmt);
   9915     preserveRowid = rc==SQLITE_ROW;
   9916   }
   9917   if( preserveRowid ){
   9918     /* Only preserve the rowid if we can find a name to use for the
   9919     ** rowid */
   9920     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
   9921     int i, j;
   9922     for(j=0; j<3; j++){
   9923       for(i=1; i<=nCol; i++){
   9924         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
   9925       }
   9926       if( i>nCol ){
   9927         /* At this point, we know that azRowid[j] is not the name of any
   9928         ** ordinary column in the table.  Verify that azRowid[j] is a valid
   9929         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
   9930         ** tables will fail this last check */
   9931         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
   9932         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
   9933         break;
   9934       }
   9935     }
   9936   }
   9937   return azCol;
   9938 }
   9939 
   9940 /*
   9941 ** Toggle the reverse_unordered_selects setting.
   9942 */
   9943 static void toggleSelectOrder(sqlite3 *db){
   9944   sqlite3_stmt *pStmt = 0;
   9945   int iSetting = 0;
   9946   char zStmt[100];
   9947   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
   9948   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   9949     iSetting = sqlite3_column_int(pStmt, 0);
   9950   }
   9951   sqlite3_finalize(pStmt);
   9952   sqlite3_snprintf(sizeof(zStmt), zStmt,
   9953        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
   9954   sqlite3_exec(db, zStmt, 0, 0, 0);
   9955 }
   9956 
   9957 /*
   9958 ** This is a different callback routine used for dumping the database.
   9959 ** Each row received by this callback consists of a table name,
   9960 ** the table type ("index" or "table") and SQL to create the table.
   9961 ** This routine should print text sufficient to recreate the table.
   9962 */
   9963 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
   9964   int rc;
   9965   const char *zTable;
   9966   const char *zType;
   9967   const char *zSql;
   9968   ShellState *p = (ShellState *)pArg;
   9969 
   9970   UNUSED_PARAMETER(azNotUsed);
   9971   if( nArg!=3 || azArg==0 ) return 0;
   9972   zTable = azArg[0];
   9973   zType = azArg[1];
   9974   zSql = azArg[2];
   9975 
   9976   if( strcmp(zTable, "sqlite_sequence")==0 ){
   9977     raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
   9978   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
   9979     raw_printf(p->out, "ANALYZE sqlite_master;\n");
   9980   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
   9981     return 0;
   9982   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
   9983     char *zIns;
   9984     if( !p->writableSchema ){
   9985       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
   9986       p->writableSchema = 1;
   9987     }
   9988     zIns = sqlite3_mprintf(
   9989        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
   9990        "VALUES('table','%q','%q',0,'%q');",
   9991        zTable, zTable, zSql);
   9992     utf8_printf(p->out, "%s\n", zIns);
   9993     sqlite3_free(zIns);
   9994     return 0;
   9995   }else{
   9996     printSchemaLine(p->out, zSql, ";\n");
   9997   }
   9998 
   9999   if( strcmp(zType, "table")==0 ){
   10000     ShellText sSelect;
   10001     ShellText sTable;
   10002     char **azCol;
   10003     int i;
   10004     char *savedDestTable;
   10005     int savedMode;
   10006 
   10007     azCol = tableColumnList(p, zTable);
   10008     if( azCol==0 ){
   10009       p->nErr++;
   10010       return 0;
   10011     }
   10012 
   10013     /* Always quote the table name, even if it appears to be pure ascii,
   10014     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
   10015     initText(&sTable);
   10016     appendText(&sTable, zTable, quoteChar(zTable));
   10017     /* If preserving the rowid, add a column list after the table name.
   10018     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
   10019     ** instead of the usual "INSERT INTO tab VALUES(...)".
   10020     */
   10021     if( azCol[0] ){
   10022       appendText(&sTable, "(", 0);
   10023       appendText(&sTable, azCol[0], 0);
   10024       for(i=1; azCol[i]; i++){
   10025         appendText(&sTable, ",", 0);
   10026         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
   10027       }
   10028       appendText(&sTable, ")", 0);
   10029     }
   10030 
   10031     /* Build an appropriate SELECT statement */
   10032     initText(&sSelect);
   10033     appendText(&sSelect, "SELECT ", 0);
   10034     if( azCol[0] ){
   10035       appendText(&sSelect, azCol[0], 0);
   10036       appendText(&sSelect, ",", 0);
   10037     }
   10038     for(i=1; azCol[i]; i++){
   10039       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
   10040       if( azCol[i+1] ){
   10041         appendText(&sSelect, ",", 0);
   10042       }
   10043     }
   10044     freeColumnList(azCol);
   10045     appendText(&sSelect, " FROM ", 0);
   10046     appendText(&sSelect, zTable, quoteChar(zTable));
   10047 
   10048     savedDestTable = p->zDestTable;
   10049     savedMode = p->mode;
   10050     p->zDestTable = sTable.z;
   10051     p->mode = p->cMode = MODE_Insert;
   10052     rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
   10053     if( (rc&0xff)==SQLITE_CORRUPT ){
   10054       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
   10055       toggleSelectOrder(p->db);
   10056       shell_exec(p->db, sSelect.z, shell_callback, p, 0);
   10057       toggleSelectOrder(p->db);
   10058     }
   10059     p->zDestTable = savedDestTable;
   10060     p->mode = savedMode;
   10061     freeText(&sTable);
   10062     freeText(&sSelect);
   10063     if( rc ) p->nErr++;
   10064   }
   10065   return 0;
   10066 }
   10067 
   10068 /*
   10069 ** Run zQuery.  Use dump_callback() as the callback routine so that
   10070 ** the contents of the query are output as SQL statements.
   10071 **
   10072 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
   10073 ** "ORDER BY rowid DESC" to the end.
   10074 */
   10075 static int run_schema_dump_query(
   10076   ShellState *p,
   10077   const char *zQuery
   10078 ){
   10079   int rc;
   10080   char *zErr = 0;
   10081   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
   10082   if( rc==SQLITE_CORRUPT ){
   10083     char *zQ2;
   10084     int len = strlen30(zQuery);
   10085     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
   10086     if( zErr ){
   10087       utf8_printf(p->out, "/****** %s ******/\n", zErr);
   10088       sqlite3_free(zErr);
   10089       zErr = 0;
   10090     }
   10091     zQ2 = malloc( len+100 );
   10092     if( zQ2==0 ) return rc;
   10093     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
   10094     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
   10095     if( rc ){
   10096       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
   10097     }else{
   10098       rc = SQLITE_CORRUPT;
   10099     }
   10100     sqlite3_free(zErr);
   10101     free(zQ2);
   10102   }
   10103   return rc;
   10104 }
   10105 
   10106 /*
   10107 ** Text of a help message
   10108 */
   10109 static char zHelp[] =
   10110 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
   10111   ".archive ...           Manage SQL archives: \".archive --help\" for details\n"
   10112 #endif
   10113 #ifndef SQLITE_OMIT_AUTHORIZATION
   10114   ".auth ON|OFF           Show authorizer callbacks\n"
   10115 #endif
   10116   ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
   10117   ".bail on|off           Stop after hitting an error.  Default OFF\n"
   10118   ".binary on|off         Turn binary output on or off.  Default OFF\n"
   10119   ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
   10120   ".changes on|off        Show number of rows changed by SQL\n"
   10121   ".check GLOB            Fail if output since .testcase does not match\n"
   10122   ".clone NEWDB           Clone data into NEWDB from the existing database\n"
   10123   ".databases             List names and files of attached databases\n"
   10124   ".dbinfo ?DB?           Show status information about the database\n"
   10125   ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
   10126   "                         If TABLE specified, only dump tables matching\n"
   10127   "                         LIKE pattern TABLE.\n"
   10128   ".echo on|off           Turn command echo on or off\n"
   10129   ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
   10130   ".excel                 Display the output of next command in a spreadsheet\n"
   10131   ".exit                  Exit this program\n"
   10132   ".expert                EXPERIMENTAL. Suggest indexes for specified queries\n"
   10133 /* Because explain mode comes on automatically now, the ".explain" mode
   10134 ** is removed from the help screen.  It is still supported for legacy, however */
   10135 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
   10136   ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
   10137   ".headers on|off        Turn display of headers on or off\n"
   10138   ".help                  Show this message\n"
   10139   ".import FILE TABLE     Import data from FILE into TABLE\n"
   10140 #ifndef SQLITE_OMIT_TEST_CONTROL
   10141   ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
   10142 #endif
   10143   ".indexes ?TABLE?       Show names of all indexes\n"
   10144   "                         If TABLE specified, only show indexes for tables\n"
   10145   "                         matching LIKE pattern TABLE.\n"
   10146 #ifdef SQLITE_ENABLE_IOTRACE
   10147   ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
   10148 #endif
   10149   ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
   10150   ".lint OPTIONS          Report potential schema issues. Options:\n"
   10151   "                         fkey-indexes     Find missing foreign key indexes\n"
   10152 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   10153   ".load FILE ?ENTRY?     Load an extension library\n"
   10154 #endif
   10155   ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
   10156   ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
   10157   "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
   10158   "                         csv      Comma-separated values\n"
   10159   "                         column   Left-aligned columns.  (See .width)\n"
   10160   "                         html     HTML <table> code\n"
   10161   "                         insert   SQL insert statements for TABLE\n"
   10162   "                         line     One value per line\n"
   10163   "                         list     Values delimited by \"|\"\n"
   10164   "                         quote    Escape answers as for SQL\n"
   10165   "                         tabs     Tab-separated values\n"
   10166   "                         tcl      TCL list elements\n"
   10167   ".nullvalue STRING      Use STRING in place of NULL values\n"
   10168   ".once (-e|-x|FILE)     Output for the next SQL command only to FILE\n"
   10169   "                         or invoke system text editor (-e) or spreadsheet (-x)\n"
   10170   "                         on the output.\n"
   10171   ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
   10172   "                         The --new option starts with an empty file\n"
   10173   ".output ?FILE?         Send output to FILE or stdout\n"
   10174   ".print STRING...       Print literal STRING\n"
   10175   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
   10176   ".quit                  Exit this program\n"
   10177   ".read FILENAME         Execute SQL in FILENAME\n"
   10178   ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
   10179   ".save FILE             Write in-memory database into FILE\n"
   10180   ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
   10181   ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
   10182   "                          Add --indent for pretty-printing\n"
   10183   ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
   10184   ".separator COL ?ROW?   Change the column separator and optionally the row\n"
   10185   "                         separator for both the output mode and .import\n"
   10186 #if defined(SQLITE_ENABLE_SESSION)
   10187   ".session CMD ...       Create or control sessions\n"
   10188 #endif
   10189   ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
   10190   ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
   10191   ".show                  Show the current values for various settings\n"
   10192   ".stats ?on|off?        Show stats or turn stats on or off\n"
   10193   ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
   10194   ".tables ?TABLE?        List names of tables\n"
   10195   "                         If TABLE specified, only list tables matching\n"
   10196   "                         LIKE pattern TABLE.\n"
   10197   ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
   10198   ".timeout MS            Try opening locked tables for MS milliseconds\n"
   10199   ".timer on|off          Turn SQL timer on or off\n"
   10200   ".trace FILE|off        Output each SQL statement as it is run\n"
   10201   ".vfsinfo ?AUX?         Information about the top-level VFS\n"
   10202   ".vfslist               List all available VFSes\n"
   10203   ".vfsname ?AUX?         Print the name of the VFS stack\n"
   10204   ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
   10205   "                         Negative values right-justify\n"
   10206 ;
   10207 
   10208 #if defined(SQLITE_ENABLE_SESSION)
   10209 /*
   10210 ** Print help information for the ".sessions" command
   10211 */
   10212 void session_help(ShellState *p){
   10213   raw_printf(p->out,
   10214     ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
   10215     "If ?NAME? is omitted, the first defined session is used.\n"
   10216     "Subcommands:\n"
   10217     "   attach TABLE             Attach TABLE\n"
   10218     "   changeset FILE           Write a changeset into FILE\n"
   10219     "   close                    Close one session\n"
   10220     "   enable ?BOOLEAN?         Set or query the enable bit\n"
   10221     "   filter GLOB...           Reject tables matching GLOBs\n"
   10222     "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
   10223     "   isempty                  Query whether the session is empty\n"
   10224     "   list                     List currently open session names\n"
   10225     "   open DB NAME             Open a new session on DB\n"
   10226     "   patchset FILE            Write a patchset into FILE\n"
   10227   );
   10228 }
   10229 #endif
   10230 
   10231 
   10232 /* Forward reference */
   10233 static int process_input(ShellState *p, FILE *in);
   10234 
   10235 /*
   10236 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
   10237 ** and return a pointer to the buffer. The caller is responsible for freeing
   10238 ** the memory.
   10239 **
   10240 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
   10241 ** read.
   10242 **
   10243 ** For convenience, a nul-terminator byte is always appended to the data read
   10244 ** from the file before the buffer is returned. This byte is not included in
   10245 ** the final value of (*pnByte), if applicable.
   10246 **
   10247 ** NULL is returned if any error is encountered. The final value of *pnByte
   10248 ** is undefined in this case.
   10249 */
   10250 static char *readFile(const char *zName, int *pnByte){
   10251   FILE *in = fopen(zName, "rb");
   10252   long nIn;
   10253   size_t nRead;
   10254   char *pBuf;
   10255   if( in==0 ) return 0;
   10256   fseek(in, 0, SEEK_END);
   10257   nIn = ftell(in);
   10258   rewind(in);
   10259   pBuf = sqlite3_malloc64( nIn+1 );
   10260   if( pBuf==0 ) return 0;
   10261   nRead = fread(pBuf, nIn, 1, in);
   10262   fclose(in);
   10263   if( nRead!=1 ){
   10264     sqlite3_free(pBuf);
   10265     return 0;
   10266   }
   10267   pBuf[nIn] = 0;
   10268   if( pnByte ) *pnByte = nIn;
   10269   return pBuf;
   10270 }
   10271 
   10272 #if defined(SQLITE_ENABLE_SESSION)
   10273 /*
   10274 ** Close a single OpenSession object and release all of its associated
   10275 ** resources.
   10276 */
   10277 static void session_close(OpenSession *pSession){
   10278   int i;
   10279   sqlite3session_delete(pSession->p);
   10280   sqlite3_free(pSession->zName);
   10281   for(i=0; i<pSession->nFilter; i++){
   10282     sqlite3_free(pSession->azFilter[i]);
   10283   }
   10284   sqlite3_free(pSession->azFilter);
   10285   memset(pSession, 0, sizeof(OpenSession));
   10286 }
   10287 #endif
   10288 
   10289 /*
   10290 ** Close all OpenSession objects and release all associated resources.
   10291 */
   10292 #if defined(SQLITE_ENABLE_SESSION)
   10293 static void session_close_all(ShellState *p){
   10294   int i;
   10295   for(i=0; i<p->nSession; i++){
   10296     session_close(&p->aSession[i]);
   10297   }
   10298   p->nSession = 0;
   10299 }
   10300 #else
   10301 # define session_close_all(X)
   10302 #endif
   10303 
   10304 /*
   10305 ** Implementation of the xFilter function for an open session.  Omit
   10306 ** any tables named by ".session filter" but let all other table through.
   10307 */
   10308 #if defined(SQLITE_ENABLE_SESSION)
   10309 static int session_filter(void *pCtx, const char *zTab){
   10310   OpenSession *pSession = (OpenSession*)pCtx;
   10311   int i;
   10312   for(i=0; i<pSession->nFilter; i++){
   10313     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
   10314   }
   10315   return 1;
   10316 }
   10317 #endif
   10318 
   10319 /*
   10320 ** Try to deduce the type of file for zName based on its content.  Return
   10321 ** one of the SHELL_OPEN_* constants.
   10322 */
   10323 static int deduceDatabaseType(const char *zName){
   10324   FILE *f = fopen(zName, "rb");
   10325   size_t n;
   10326   int rc = SHELL_OPEN_UNSPEC;
   10327   char zBuf[100];
   10328   if( f==0 ) return SHELL_OPEN_NORMAL;
   10329   fseek(f, -25, SEEK_END);
   10330   n = fread(zBuf, 25, 1, f);
   10331   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
   10332     rc = SHELL_OPEN_APPENDVFS;
   10333   }else{
   10334     fseek(f, -22, SEEK_END);
   10335     n = fread(zBuf, 22, 1, f);
   10336     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
   10337        && zBuf[3]==0x06 ){
   10338       rc = SHELL_OPEN_ZIPFILE;
   10339     }
   10340   }
   10341   fclose(f);
   10342   return rc;
   10343 }
   10344 
   10345 /*
   10346 ** Make sure the database is open.  If it is not, then open it.  If
   10347 ** the database fails to open, print an error message and exit.
   10348 */
   10349 static void open_db(ShellState *p, int keepAlive){
   10350   if( p->db==0 ){
   10351     sqlite3_initialize();
   10352     if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){
   10353       p->openMode = deduceDatabaseType(p->zDbFilename);
   10354     }
   10355     switch( p->openMode ){
   10356       case SHELL_OPEN_APPENDVFS: {
   10357         sqlite3_open_v2(p->zDbFilename, &p->db,
   10358            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
   10359         break;
   10360       }
   10361       case SHELL_OPEN_ZIPFILE: {
   10362         sqlite3_open(":memory:", &p->db);
   10363         break;
   10364       }
   10365       case SHELL_OPEN_UNSPEC:
   10366       case SHELL_OPEN_NORMAL: {
   10367         sqlite3_open(p->zDbFilename, &p->db);
   10368         break;
   10369       }
   10370     }
   10371     globalDb = p->db;
   10372     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
   10373       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
   10374           p->zDbFilename, sqlite3_errmsg(p->db));
   10375       if( keepAlive ) return;
   10376       exit(1);
   10377     }
   10378 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   10379     sqlite3_enable_load_extension(p->db, 1);
   10380 #endif
   10381     sqlite3_fileio_init(p->db, 0, 0);
   10382     sqlite3_shathree_init(p->db, 0, 0);
   10383     sqlite3_completion_init(p->db, 0, 0);
   10384 #ifdef SQLITE_HAVE_ZLIB
   10385     sqlite3_zipfile_init(p->db, 0, 0);
   10386     sqlite3_sqlar_init(p->db, 0, 0);
   10387 #endif
   10388     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
   10389                             shellAddSchemaName, 0, 0);
   10390     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
   10391                             shellModuleSchema, 0, 0);
   10392     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
   10393                             shellPutsFunc, 0, 0);
   10394     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
   10395                             editFunc, 0, 0);
   10396     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
   10397                             editFunc, 0, 0);
   10398 
   10399     // Begin Android Add
   10400     #ifndef NO_ANDROID_FUNCS
   10401         InitializeIcuOrDie();
   10402         int err = register_localized_collators(p->db, "en_US", 0);
   10403         if (err != SQLITE_OK) {
   10404           fprintf(stderr, "register_localized_collators() failed\n");
   10405           exit(1);
   10406         }
   10407         err = register_android_functions(p->db, 0);
   10408         if (err != SQLITE_OK) {
   10409           fprintf(stderr, "register_android_functions() failed\n");
   10410           exit(1);
   10411         }
   10412     #endif
   10413     // End Android Add
   10414 
   10415     if( p->openMode==SHELL_OPEN_ZIPFILE ){
   10416       char *zSql = sqlite3_mprintf(
   10417          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
   10418       sqlite3_exec(p->db, zSql, 0, 0, 0);
   10419       sqlite3_free(zSql);
   10420     }
   10421   }
   10422 }
   10423 
   10424 #if HAVE_READLINE || HAVE_EDITLINE
   10425 /*
   10426 ** Readline completion callbacks
   10427 */
   10428 static char *readline_completion_generator(const char *text, int state){
   10429   static sqlite3_stmt *pStmt = 0;
   10430   char *zRet;
   10431   if( state==0 ){
   10432     char *zSql;
   10433     sqlite3_finalize(pStmt);
   10434     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
   10435                            "  FROM completion(%Q) ORDER BY 1", text);
   10436     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
   10437     sqlite3_free(zSql);
   10438   }
   10439   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   10440     zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
   10441   }else{
   10442     sqlite3_finalize(pStmt);
   10443     pStmt = 0;
   10444     zRet = 0;
   10445   }
   10446   return zRet;
   10447 }
   10448 static char **readline_completion(const char *zText, int iStart, int iEnd){
   10449   rl_attempted_completion_over = 1;
   10450   return rl_completion_matches(zText, readline_completion_generator);
   10451 }
   10452 
   10453 #elif HAVE_LINENOISE
   10454 /*
   10455 ** Linenoise completion callback
   10456 */
   10457 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
   10458   int nLine = strlen30(zLine);
   10459   int i, iStart;
   10460   sqlite3_stmt *pStmt = 0;
   10461   char *zSql;
   10462   char zBuf[1000];
   10463 
   10464   if( nLine>sizeof(zBuf)-30 ) return;
   10465   if( zLine[0]=='.' ) return;
   10466   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
   10467   if( i==nLine-1 ) return;
   10468   iStart = i+1;
   10469   memcpy(zBuf, zLine, iStart);
   10470   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
   10471                          "  FROM completion(%Q,%Q) ORDER BY 1",
   10472                          &zLine[iStart], zLine);
   10473   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
   10474   sqlite3_free(zSql);
   10475   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
   10476   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   10477     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
   10478     int nCompletion = sqlite3_column_bytes(pStmt, 0);
   10479     if( iStart+nCompletion < sizeof(zBuf)-1 ){
   10480       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
   10481       linenoiseAddCompletion(lc, zBuf);
   10482     }
   10483   }
   10484   sqlite3_finalize(pStmt);
   10485 }
   10486 #endif
   10487 
   10488 /*
   10489 ** Do C-language style dequoting.
   10490 **
   10491 **    \a    -> alarm
   10492 **    \b    -> backspace
   10493 **    \t    -> tab
   10494 **    \n    -> newline
   10495 **    \v    -> vertical tab
   10496 **    \f    -> form feed
   10497 **    \r    -> carriage return
   10498 **    \s    -> space
   10499 **    \"    -> "
   10500 **    \'    -> '
   10501 **    \\    -> backslash
   10502 **    \NNN  -> ascii character NNN in octal
   10503 */
   10504 static void resolve_backslashes(char *z){
   10505   int i, j;
   10506   char c;
   10507   while( *z && *z!='\\' ) z++;
   10508   for(i=j=0; (c = z[i])!=0; i++, j++){
   10509     if( c=='\\' && z[i+1]!=0 ){
   10510       c = z[++i];
   10511       if( c=='a' ){
   10512         c = '\a';
   10513       }else if( c=='b' ){
   10514         c = '\b';
   10515       }else if( c=='t' ){
   10516         c = '\t';
   10517       }else if( c=='n' ){
   10518         c = '\n';
   10519       }else if( c=='v' ){
   10520         c = '\v';
   10521       }else if( c=='f' ){
   10522         c = '\f';
   10523       }else if( c=='r' ){
   10524         c = '\r';
   10525       }else if( c=='"' ){
   10526         c = '"';
   10527       }else if( c=='\'' ){
   10528         c = '\'';
   10529       }else if( c=='\\' ){
   10530         c = '\\';
   10531       }else if( c>='0' && c<='7' ){
   10532         c -= '0';
   10533         if( z[i+1]>='0' && z[i+1]<='7' ){
   10534           i++;
   10535           c = (c<<3) + z[i] - '0';
   10536           if( z[i+1]>='0' && z[i+1]<='7' ){
   10537             i++;
   10538             c = (c<<3) + z[i] - '0';
   10539           }
   10540         }
   10541       }
   10542     }
   10543     z[j] = c;
   10544   }
   10545   if( j<i ) z[j] = 0;
   10546 }
   10547 
   10548 /*
   10549 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
   10550 ** for TRUE and FALSE.  Return the integer value if appropriate.
   10551 */
   10552 static int booleanValue(const char *zArg){
   10553   int i;
   10554   if( zArg[0]=='0' && zArg[1]=='x' ){
   10555     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
   10556   }else{
   10557     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
   10558   }
   10559   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
   10560   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
   10561     return 1;
   10562   }
   10563   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
   10564     return 0;
   10565   }
   10566   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
   10567           zArg);
   10568   return 0;
   10569 }
   10570 
   10571 /*
   10572 ** Set or clear a shell flag according to a boolean value.
   10573 */
   10574 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
   10575   if( booleanValue(zArg) ){
   10576     ShellSetFlag(p, mFlag);
   10577   }else{
   10578     ShellClearFlag(p, mFlag);
   10579   }
   10580 }
   10581 
   10582 /*
   10583 ** Close an output file, assuming it is not stderr or stdout
   10584 */
   10585 static void output_file_close(FILE *f){
   10586   if( f && f!=stdout && f!=stderr ) fclose(f);
   10587 }
   10588 
   10589 /*
   10590 ** Try to open an output file.   The names "stdout" and "stderr" are
   10591 ** recognized and do the right thing.  NULL is returned if the output
   10592 ** filename is "off".
   10593 */
   10594 static FILE *output_file_open(const char *zFile, int bTextMode){
   10595   FILE *f;
   10596   if( strcmp(zFile,"stdout")==0 ){
   10597     f = stdout;
   10598   }else if( strcmp(zFile, "stderr")==0 ){
   10599     f = stderr;
   10600   }else if( strcmp(zFile, "off")==0 ){
   10601     f = 0;
   10602   }else{
   10603     f = fopen(zFile, bTextMode ? "w" : "wb");
   10604     if( f==0 ){
   10605       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
   10606     }
   10607   }
   10608   return f;
   10609 }
   10610 
   10611 #if !defined(SQLITE_UNTESTABLE)
   10612 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
   10613 /*
   10614 ** A routine for handling output from sqlite3_trace().
   10615 */
   10616 static int sql_trace_callback(
   10617   unsigned mType,
   10618   void *pArg,
   10619   void *pP,
   10620   void *pX
   10621 ){
   10622   FILE *f = (FILE*)pArg;
   10623   UNUSED_PARAMETER(mType);
   10624   UNUSED_PARAMETER(pP);
   10625   if( f ){
   10626     const char *z = (const char*)pX;
   10627     int i = strlen30(z);
   10628     while( i>0 && z[i-1]==';' ){ i--; }
   10629     utf8_printf(f, "%.*s;\n", i, z);
   10630   }
   10631   return 0;
   10632 }
   10633 #endif
   10634 #endif
   10635 
   10636 /*
   10637 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
   10638 ** a useful spot to set a debugger breakpoint.
   10639 */
   10640 static void test_breakpoint(void){
   10641   static int nCall = 0;
   10642   nCall++;
   10643 }
   10644 
   10645 /*
   10646 ** An object used to read a CSV and other files for import.
   10647 */
   10648 typedef struct ImportCtx ImportCtx;
   10649 struct ImportCtx {
   10650   const char *zFile;  /* Name of the input file */
   10651   FILE *in;           /* Read the CSV text from this input stream */
   10652   char *z;            /* Accumulated text for a field */
   10653   int n;              /* Number of bytes in z */
   10654   int nAlloc;         /* Space allocated for z[] */
   10655   int nLine;          /* Current line number */
   10656   int bNotFirst;      /* True if one or more bytes already read */
   10657   int cTerm;          /* Character that terminated the most recent field */
   10658   int cColSep;        /* The column separator character.  (Usually ",") */
   10659   int cRowSep;        /* The row separator character.  (Usually "\n") */
   10660 };
   10661 
   10662 /* Append a single byte to z[] */
   10663 static void import_append_char(ImportCtx *p, int c){
   10664   if( p->n+1>=p->nAlloc ){
   10665     p->nAlloc += p->nAlloc + 100;
   10666     p->z = sqlite3_realloc64(p->z, p->nAlloc);
   10667     if( p->z==0 ){
   10668       raw_printf(stderr, "out of memory\n");
   10669       exit(1);
   10670     }
   10671   }
   10672   p->z[p->n++] = (char)c;
   10673 }
   10674 
   10675 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
   10676 ** with the option of having a separator other than ",".
   10677 **
   10678 **   +  Input comes from p->in.
   10679 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
   10680 **      from sqlite3_malloc64().
   10681 **   +  Use p->cSep as the column separator.  The default is ",".
   10682 **   +  Use p->rSep as the row separator.  The default is "\n".
   10683 **   +  Keep track of the line number in p->nLine.
   10684 **   +  Store the character that terminates the field in p->cTerm.  Store
   10685 **      EOF on end-of-file.
   10686 **   +  Report syntax errors on stderr
   10687 */
   10688 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
   10689   int c;
   10690   int cSep = p->cColSep;
   10691   int rSep = p->cRowSep;
   10692   p->n = 0;
   10693   c = fgetc(p->in);
   10694   if( c==EOF || seenInterrupt ){
   10695     p->cTerm = EOF;
   10696     return 0;
   10697   }
   10698   if( c=='"' ){
   10699     int pc, ppc;
   10700     int startLine = p->nLine;
   10701     int cQuote = c;
   10702     pc = ppc = 0;
   10703     while( 1 ){
   10704       c = fgetc(p->in);
   10705       if( c==rSep ) p->nLine++;
   10706       if( c==cQuote ){
   10707         if( pc==cQuote ){
   10708           pc = 0;
   10709           continue;
   10710         }
   10711       }
   10712       if( (c==cSep && pc==cQuote)
   10713        || (c==rSep && pc==cQuote)
   10714        || (c==rSep && pc=='\r' && ppc==cQuote)
   10715        || (c==EOF && pc==cQuote)
   10716       ){
   10717         do{ p->n--; }while( p->z[p->n]!=cQuote );
   10718         p->cTerm = c;
   10719         break;
   10720       }
   10721       if( pc==cQuote && c!='\r' ){
   10722         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
   10723                 p->zFile, p->nLine, cQuote);
   10724       }
   10725       if( c==EOF ){
   10726         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
   10727                 p->zFile, startLine, cQuote);
   10728         p->cTerm = c;
   10729         break;
   10730       }
   10731       import_append_char(p, c);
   10732       ppc = pc;
   10733       pc = c;
   10734     }
   10735   }else{
   10736     /* If this is the first field being parsed and it begins with the
   10737     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
   10738     if( (c&0xff)==0xef && p->bNotFirst==0 ){
   10739       import_append_char(p, c);
   10740       c = fgetc(p->in);
   10741       if( (c&0xff)==0xbb ){
   10742         import_append_char(p, c);
   10743         c = fgetc(p->in);
   10744         if( (c&0xff)==0xbf ){
   10745           p->bNotFirst = 1;
   10746           p->n = 0;
   10747           return csv_read_one_field(p);
   10748         }
   10749       }
   10750     }
   10751     while( c!=EOF && c!=cSep && c!=rSep ){
   10752       import_append_char(p, c);
   10753       c = fgetc(p->in);
   10754     }
   10755     if( c==rSep ){
   10756       p->nLine++;
   10757       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
   10758     }
   10759     p->cTerm = c;
   10760   }
   10761   if( p->z ) p->z[p->n] = 0;
   10762   p->bNotFirst = 1;
   10763   return p->z;
   10764 }
   10765 
   10766 /* Read a single field of ASCII delimited text.
   10767 **
   10768 **   +  Input comes from p->in.
   10769 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
   10770 **      from sqlite3_malloc64().
   10771 **   +  Use p->cSep as the column separator.  The default is "\x1F".
   10772 **   +  Use p->rSep as the row separator.  The default is "\x1E".
   10773 **   +  Keep track of the row number in p->nLine.
   10774 **   +  Store the character that terminates the field in p->cTerm.  Store
   10775 **      EOF on end-of-file.
   10776 **   +  Report syntax errors on stderr
   10777 */
   10778 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
   10779   int c;
   10780   int cSep = p->cColSep;
   10781   int rSep = p->cRowSep;
   10782   p->n = 0;
   10783   c = fgetc(p->in);
   10784   if( c==EOF || seenInterrupt ){
   10785     p->cTerm = EOF;
   10786     return 0;
   10787   }
   10788   while( c!=EOF && c!=cSep && c!=rSep ){
   10789     import_append_char(p, c);
   10790     c = fgetc(p->in);
   10791   }
   10792   if( c==rSep ){
   10793     p->nLine++;
   10794   }
   10795   p->cTerm = c;
   10796   if( p->z ) p->z[p->n] = 0;
   10797   return p->z;
   10798 }
   10799 
   10800 /*
   10801 ** Try to transfer data for table zTable.  If an error is seen while
   10802 ** moving forward, try to go backwards.  The backwards movement won't
   10803 ** work for WITHOUT ROWID tables.
   10804 */
   10805 static void tryToCloneData(
   10806   ShellState *p,
   10807   sqlite3 *newDb,
   10808   const char *zTable
   10809 ){
   10810   sqlite3_stmt *pQuery = 0;
   10811   sqlite3_stmt *pInsert = 0;
   10812   char *zQuery = 0;
   10813   char *zInsert = 0;
   10814   int rc;
   10815   int i, j, n;
   10816   int nTable = strlen30(zTable);
   10817   int k = 0;
   10818   int cnt = 0;
   10819   const int spinRate = 10000;
   10820 
   10821   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
   10822   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   10823   if( rc ){
   10824     utf8_printf(stderr, "Error %d: %s on [%s]\n",
   10825             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
   10826             zQuery);
   10827     goto end_data_xfer;
   10828   }
   10829   n = sqlite3_column_count(pQuery);
   10830   zInsert = sqlite3_malloc64(200 + nTable + n*3);
   10831   if( zInsert==0 ){
   10832     raw_printf(stderr, "out of memory\n");
   10833     goto end_data_xfer;
   10834   }
   10835   sqlite3_snprintf(200+nTable,zInsert,
   10836                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
   10837   i = strlen30(zInsert);
   10838   for(j=1; j<n; j++){
   10839     memcpy(zInsert+i, ",?", 2);
   10840     i += 2;
   10841   }
   10842   memcpy(zInsert+i, ");", 3);
   10843   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
   10844   if( rc ){
   10845     utf8_printf(stderr, "Error %d: %s on [%s]\n",
   10846             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
   10847             zQuery);
   10848     goto end_data_xfer;
   10849   }
   10850   for(k=0; k<2; k++){
   10851     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
   10852       for(i=0; i<n; i++){
   10853         switch( sqlite3_column_type(pQuery, i) ){
   10854           case SQLITE_NULL: {
   10855             sqlite3_bind_null(pInsert, i+1);
   10856             break;
   10857           }
   10858           case SQLITE_INTEGER: {
   10859             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
   10860             break;
   10861           }
   10862           case SQLITE_FLOAT: {
   10863             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
   10864             break;
   10865           }
   10866           case SQLITE_TEXT: {
   10867             sqlite3_bind_text(pInsert, i+1,
   10868                              (const char*)sqlite3_column_text(pQuery,i),
   10869                              -1, SQLITE_STATIC);
   10870             break;
   10871           }
   10872           case SQLITE_BLOB: {
   10873             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
   10874                                             sqlite3_column_bytes(pQuery,i),
   10875                                             SQLITE_STATIC);
   10876             break;
   10877           }
   10878         }
   10879       } /* End for */
   10880       rc = sqlite3_step(pInsert);
   10881       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   10882         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
   10883                         sqlite3_errmsg(newDb));
   10884       }
   10885       sqlite3_reset(pInsert);
   10886       cnt++;
   10887       if( (cnt%spinRate)==0 ){
   10888         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
   10889         fflush(stdout);
   10890       }
   10891     } /* End while */
   10892     if( rc==SQLITE_DONE ) break;
   10893     sqlite3_finalize(pQuery);
   10894     sqlite3_free(zQuery);
   10895     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
   10896                              zTable);
   10897     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   10898     if( rc ){
   10899       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
   10900       break;
   10901     }
   10902   } /* End for(k=0...) */
   10903 
   10904 end_data_xfer:
   10905   sqlite3_finalize(pQuery);
   10906   sqlite3_finalize(pInsert);
   10907   sqlite3_free(zQuery);
   10908   sqlite3_free(zInsert);
   10909 }
   10910 
   10911 
   10912 /*
   10913 ** Try to transfer all rows of the schema that match zWhere.  For
   10914 ** each row, invoke xForEach() on the object defined by that row.
   10915 ** If an error is encountered while moving forward through the
   10916 ** sqlite_master table, try again moving backwards.
   10917 */
   10918 static void tryToCloneSchema(
   10919   ShellState *p,
   10920   sqlite3 *newDb,
   10921   const char *zWhere,
   10922   void (*xForEach)(ShellState*,sqlite3*,const char*)
   10923 ){
   10924   sqlite3_stmt *pQuery = 0;
   10925   char *zQuery = 0;
   10926   int rc;
   10927   const unsigned char *zName;
   10928   const unsigned char *zSql;
   10929   char *zErrMsg = 0;
   10930 
   10931   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
   10932                            " WHERE %s", zWhere);
   10933   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   10934   if( rc ){
   10935     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
   10936                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
   10937                     zQuery);
   10938     goto end_schema_xfer;
   10939   }
   10940   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
   10941     zName = sqlite3_column_text(pQuery, 0);
   10942     zSql = sqlite3_column_text(pQuery, 1);
   10943     printf("%s... ", zName); fflush(stdout);
   10944     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
   10945     if( zErrMsg ){
   10946       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
   10947       sqlite3_free(zErrMsg);
   10948       zErrMsg = 0;
   10949     }
   10950     if( xForEach ){
   10951       xForEach(p, newDb, (const char*)zName);
   10952     }
   10953     printf("done\n");
   10954   }
   10955   if( rc!=SQLITE_DONE ){
   10956     sqlite3_finalize(pQuery);
   10957     sqlite3_free(zQuery);
   10958     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
   10959                              " WHERE %s ORDER BY rowid DESC", zWhere);
   10960     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   10961     if( rc ){
   10962       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
   10963                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
   10964                       zQuery);
   10965       goto end_schema_xfer;
   10966     }
   10967     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
   10968       zName = sqlite3_column_text(pQuery, 0);
   10969       zSql = sqlite3_column_text(pQuery, 1);
   10970       printf("%s... ", zName); fflush(stdout);
   10971       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
   10972       if( zErrMsg ){
   10973         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
   10974         sqlite3_free(zErrMsg);
   10975         zErrMsg = 0;
   10976       }
   10977       if( xForEach ){
   10978         xForEach(p, newDb, (const char*)zName);
   10979       }
   10980       printf("done\n");
   10981     }
   10982   }
   10983 end_schema_xfer:
   10984   sqlite3_finalize(pQuery);
   10985   sqlite3_free(zQuery);
   10986 }
   10987 
   10988 /*
   10989 ** Open a new database file named "zNewDb".  Try to recover as much information
   10990 ** as possible out of the main database (which might be corrupt) and write it
   10991 ** into zNewDb.
   10992 */
   10993 static void tryToClone(ShellState *p, const char *zNewDb){
   10994   int rc;
   10995   sqlite3 *newDb = 0;
   10996   if( access(zNewDb,0)==0 ){
   10997     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
   10998     return;
   10999   }
   11000   rc = sqlite3_open(zNewDb, &newDb);
   11001   if( rc ){
   11002     utf8_printf(stderr, "Cannot create output database: %s\n",
   11003             sqlite3_errmsg(newDb));
   11004   }else{
   11005     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
   11006     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
   11007     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
   11008     tryToCloneSchema(p, newDb, "type!='table'", 0);
   11009     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
   11010     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
   11011   }
   11012   sqlite3_close(newDb);
   11013 }
   11014 
   11015 /*
   11016 ** Change the output file back to stdout.
   11017 **
   11018 ** If the p->doXdgOpen flag is set, that means the output was being
   11019 ** redirected to a temporary file named by p->zTempFile.  In that case,
   11020 ** launch start/open/xdg-open on that temporary file.
   11021 */
   11022 static void output_reset(ShellState *p){
   11023   if( p->outfile[0]=='|' ){
   11024 #ifndef SQLITE_OMIT_POPEN
   11025     pclose(p->out);
   11026 #endif
   11027   }else{
   11028     output_file_close(p->out);
   11029     if( p->doXdgOpen ){
   11030       const char *zXdgOpenCmd =
   11031 #if defined(_WIN32)
   11032       "start";
   11033 #elif defined(__APPLE__)
   11034       "open";
   11035 #else
   11036       "xdg-open";
   11037 #endif
   11038       char *zCmd;
   11039       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
   11040       if( system(zCmd) ){
   11041         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
   11042       }
   11043       sqlite3_free(zCmd);
   11044       outputModePop(p);
   11045       p->doXdgOpen = 0;
   11046     }
   11047   }
   11048   p->outfile[0] = 0;
   11049   p->out = stdout;
   11050 }
   11051 
   11052 /*
   11053 ** Run an SQL command and return the single integer result.
   11054 */
   11055 static int db_int(ShellState *p, const char *zSql){
   11056   sqlite3_stmt *pStmt;
   11057   int res = 0;
   11058   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   11059   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
   11060     res = sqlite3_column_int(pStmt,0);
   11061   }
   11062   sqlite3_finalize(pStmt);
   11063   return res;
   11064 }
   11065 
   11066 /*
   11067 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
   11068 */
   11069 static unsigned int get2byteInt(unsigned char *a){
   11070   return (a[0]<<8) + a[1];
   11071 }
   11072 static unsigned int get4byteInt(unsigned char *a){
   11073   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
   11074 }
   11075 
   11076 /*
   11077 ** Implementation of the ".info" command.
   11078 **
   11079 ** Return 1 on error, 2 to exit, and 0 otherwise.
   11080 */
   11081 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
   11082   static const struct { const char *zName; int ofst; } aField[] = {
   11083      { "file change counter:",  24  },
   11084      { "database page count:",  28  },
   11085      { "freelist page count:",  36  },
   11086      { "schema cookie:",        40  },
   11087      { "schema format:",        44  },
   11088      { "default cache size:",   48  },
   11089      { "autovacuum top root:",  52  },
   11090      { "incremental vacuum:",   64  },
   11091      { "text encoding:",        56  },
   11092      { "user version:",         60  },
   11093      { "application id:",       68  },
   11094      { "software version:",     96  },
   11095   };
   11096   static const struct { const char *zName; const char *zSql; } aQuery[] = {
   11097      { "number of tables:",
   11098        "SELECT count(*) FROM %s WHERE type='table'" },
   11099      { "number of indexes:",
   11100        "SELECT count(*) FROM %s WHERE type='index'" },
   11101      { "number of triggers:",
   11102        "SELECT count(*) FROM %s WHERE type='trigger'" },
   11103      { "number of views:",
   11104        "SELECT count(*) FROM %s WHERE type='view'" },
   11105      { "schema size:",
   11106        "SELECT total(length(sql)) FROM %s" },
   11107   };
   11108   int i;
   11109   char *zSchemaTab;
   11110   char *zDb = nArg>=2 ? azArg[1] : "main";
   11111   sqlite3_stmt *pStmt = 0;
   11112   unsigned char aHdr[100];
   11113   open_db(p, 0);
   11114   if( p->db==0 ) return 1;
   11115   sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
   11116                      -1, &pStmt, 0);
   11117   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
   11118   if( sqlite3_step(pStmt)==SQLITE_ROW
   11119    && sqlite3_column_bytes(pStmt,0)>100
   11120   ){
   11121     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
   11122     sqlite3_finalize(pStmt);
   11123   }else{
   11124     raw_printf(stderr, "unable to read database header\n");
   11125     sqlite3_finalize(pStmt);
   11126     return 1;
   11127   }
   11128   i = get2byteInt(aHdr+16);
   11129   if( i==1 ) i = 65536;
   11130   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
   11131   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
   11132   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
   11133   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
   11134   for(i=0; i<ArraySize(aField); i++){
   11135     int ofst = aField[i].ofst;
   11136     unsigned int val = get4byteInt(aHdr + ofst);
   11137     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
   11138     switch( ofst ){
   11139       case 56: {
   11140         if( val==1 ) raw_printf(p->out, " (utf8)");
   11141         if( val==2 ) raw_printf(p->out, " (utf16le)");
   11142         if( val==3 ) raw_printf(p->out, " (utf16be)");
   11143       }
   11144     }
   11145     raw_printf(p->out, "\n");
   11146   }
   11147   if( zDb==0 ){
   11148     zSchemaTab = sqlite3_mprintf("main.sqlite_master");
   11149   }else if( strcmp(zDb,"temp")==0 ){
   11150     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
   11151   }else{
   11152     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
   11153   }
   11154   for(i=0; i<ArraySize(aQuery); i++){
   11155     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
   11156     int val = db_int(p, zSql);
   11157     sqlite3_free(zSql);
   11158     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
   11159   }
   11160   sqlite3_free(zSchemaTab);
   11161   return 0;
   11162 }
   11163 
   11164 /*
   11165 ** Print the current sqlite3_errmsg() value to stderr and return 1.
   11166 */
   11167 static int shellDatabaseError(sqlite3 *db){
   11168   const char *zErr = sqlite3_errmsg(db);
   11169   utf8_printf(stderr, "Error: %s\n", zErr);
   11170   return 1;
   11171 }
   11172 
   11173 /*
   11174 ** Print an out-of-memory message to stderr and return 1.
   11175 */
   11176 static int shellNomemError(void){
   11177   raw_printf(stderr, "Error: out of memory\n");
   11178   return 1;
   11179 }
   11180 
   11181 /*
   11182 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
   11183 ** if they match and FALSE (0) if they do not match.
   11184 **
   11185 ** Globbing rules:
   11186 **
   11187 **      '*'       Matches any sequence of zero or more characters.
   11188 **
   11189 **      '?'       Matches exactly one character.
   11190 **
   11191 **     [...]      Matches one character from the enclosed list of
   11192 **                characters.
   11193 **
   11194 **     [^...]     Matches one character not in the enclosed list.
   11195 **
   11196 **      '#'       Matches any sequence of one or more digits with an
   11197 **                optional + or - sign in front
   11198 **
   11199 **      ' '       Any span of whitespace matches any other span of
   11200 **                whitespace.
   11201 **
   11202 ** Extra whitespace at the end of z[] is ignored.
   11203 */
   11204 static int testcase_glob(const char *zGlob, const char *z){
   11205   int c, c2;
   11206   int invert;
   11207   int seen;
   11208 
   11209   while( (c = (*(zGlob++)))!=0 ){
   11210     if( IsSpace(c) ){
   11211       if( !IsSpace(*z) ) return 0;
   11212       while( IsSpace(*zGlob) ) zGlob++;
   11213       while( IsSpace(*z) ) z++;
   11214     }else if( c=='*' ){
   11215       while( (c=(*(zGlob++))) == '*' || c=='?' ){
   11216         if( c=='?' && (*(z++))==0 ) return 0;
   11217       }
   11218       if( c==0 ){
   11219         return 1;
   11220       }else if( c=='[' ){
   11221         while( *z && testcase_glob(zGlob-1,z)==0 ){
   11222           z++;
   11223         }
   11224         return (*z)!=0;
   11225       }
   11226       while( (c2 = (*(z++)))!=0 ){
   11227         while( c2!=c ){
   11228           c2 = *(z++);
   11229           if( c2==0 ) return 0;
   11230         }
   11231         if( testcase_glob(zGlob,z) ) return 1;
   11232       }
   11233       return 0;
   11234     }else if( c=='?' ){
   11235       if( (*(z++))==0 ) return 0;
   11236     }else if( c=='[' ){
   11237       int prior_c = 0;
   11238       seen = 0;
   11239       invert = 0;
   11240       c = *(z++);
   11241       if( c==0 ) return 0;
   11242       c2 = *(zGlob++);
   11243       if( c2=='^' ){
   11244         invert = 1;
   11245         c2 = *(zGlob++);
   11246       }
   11247       if( c2==']' ){
   11248         if( c==']' ) seen = 1;
   11249         c2 = *(zGlob++);
   11250       }
   11251       while( c2 && c2!=']' ){
   11252         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
   11253           c2 = *(zGlob++);
   11254           if( c>=prior_c && c<=c2 ) seen = 1;
   11255           prior_c = 0;
   11256         }else{
   11257           if( c==c2 ){
   11258             seen = 1;
   11259           }
   11260           prior_c = c2;
   11261         }
   11262         c2 = *(zGlob++);
   11263       }
   11264       if( c2==0 || (seen ^ invert)==0 ) return 0;
   11265     }else if( c=='#' ){
   11266       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
   11267       if( !IsDigit(z[0]) ) return 0;
   11268       z++;
   11269       while( IsDigit(z[0]) ){ z++; }
   11270     }else{
   11271       if( c!=(*(z++)) ) return 0;
   11272     }
   11273   }
   11274   while( IsSpace(*z) ){ z++; }
   11275   return *z==0;
   11276 }
   11277 
   11278 
   11279 /*
   11280 ** Compare the string as a command-line option with either one or two
   11281 ** initial "-" characters.
   11282 */
   11283 static int optionMatch(const char *zStr, const char *zOpt){
   11284   if( zStr[0]!='-' ) return 0;
   11285   zStr++;
   11286   if( zStr[0]=='-' ) zStr++;
   11287   return strcmp(zStr, zOpt)==0;
   11288 }
   11289 
   11290 /*
   11291 ** Delete a file.
   11292 */
   11293 int shellDeleteFile(const char *zFilename){
   11294   int rc;
   11295 #ifdef _WIN32
   11296   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
   11297   rc = _wunlink(z);
   11298   sqlite3_free(z);
   11299 #else
   11300   rc = unlink(zFilename);
   11301 #endif
   11302   return rc;
   11303 }
   11304 
   11305 /*
   11306 ** Try to delete the temporary file (if there is one) and free the
   11307 ** memory used to hold the name of the temp file.
   11308 */
   11309 static void clearTempFile(ShellState *p){
   11310   if( p->zTempFile==0 ) return;
   11311   if( p->doXdgOpen ) return;
   11312   if( shellDeleteFile(p->zTempFile) ) return;
   11313   sqlite3_free(p->zTempFile);
   11314   p->zTempFile = 0;
   11315 }
   11316 
   11317 /*
   11318 ** Create a new temp file name with the given suffix.
   11319 */
   11320 static void newTempFile(ShellState *p, const char *zSuffix){
   11321   clearTempFile(p);
   11322   sqlite3_free(p->zTempFile);
   11323   p->zTempFile = 0;
   11324   if( p->db ){
   11325     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
   11326   }
   11327   if( p->zTempFile==0 ){
   11328     sqlite3_uint64 r;
   11329     sqlite3_randomness(sizeof(r), &r);
   11330     p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
   11331   }else{
   11332     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
   11333   }
   11334   if( p->zTempFile==0 ){
   11335     raw_printf(stderr, "out of memory\n");
   11336     exit(1);
   11337   }
   11338 }
   11339 
   11340 
   11341 /*
   11342 ** The implementation of SQL scalar function fkey_collate_clause(), used
   11343 ** by the ".lint fkey-indexes" command. This scalar function is always
   11344 ** called with four arguments - the parent table name, the parent column name,
   11345 ** the child table name and the child column name.
   11346 **
   11347 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
   11348 **
   11349 ** If either of the named tables or columns do not exist, this function
   11350 ** returns an empty string. An empty string is also returned if both tables
   11351 ** and columns exist but have the same default collation sequence. Or,
   11352 ** if both exist but the default collation sequences are different, this
   11353 ** function returns the string " COLLATE <parent-collation>", where
   11354 ** <parent-collation> is the default collation sequence of the parent column.
   11355 */
   11356 static void shellFkeyCollateClause(
   11357   sqlite3_context *pCtx,
   11358   int nVal,
   11359   sqlite3_value **apVal
   11360 ){
   11361   sqlite3 *db = sqlite3_context_db_handle(pCtx);
   11362   const char *zParent;
   11363   const char *zParentCol;
   11364   const char *zParentSeq;
   11365   const char *zChild;
   11366   const char *zChildCol;
   11367   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
   11368   int rc;
   11369 
   11370   assert( nVal==4 );
   11371   zParent = (const char*)sqlite3_value_text(apVal[0]);
   11372   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
   11373   zChild = (const char*)sqlite3_value_text(apVal[2]);
   11374   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
   11375 
   11376   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
   11377   rc = sqlite3_table_column_metadata(
   11378       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
   11379   );
   11380   if( rc==SQLITE_OK ){
   11381     rc = sqlite3_table_column_metadata(
   11382         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
   11383     );
   11384   }
   11385 
   11386   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
   11387     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
   11388     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
   11389     sqlite3_free(z);
   11390   }
   11391 }
   11392 
   11393 
   11394 /*
   11395 ** The implementation of dot-command ".lint fkey-indexes".
   11396 */
   11397 static int lintFkeyIndexes(
   11398   ShellState *pState,             /* Current shell tool state */
   11399   char **azArg,                   /* Array of arguments passed to dot command */
   11400   int nArg                        /* Number of entries in azArg[] */
   11401 ){
   11402   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
   11403   FILE *out = pState->out;        /* Stream to write non-error output to */
   11404   int bVerbose = 0;               /* If -verbose is present */
   11405   int bGroupByParent = 0;         /* If -groupbyparent is present */
   11406   int i;                          /* To iterate through azArg[] */
   11407   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
   11408   int rc;                         /* Return code */
   11409   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
   11410 
   11411   /*
   11412   ** This SELECT statement returns one row for each foreign key constraint
   11413   ** in the schema of the main database. The column values are:
   11414   **
   11415   ** 0. The text of an SQL statement similar to:
   11416   **
   11417   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
   11418   **
   11419   **    This SELECT is similar to the one that the foreign keys implementation
   11420   **    needs to run internally on child tables. If there is an index that can
   11421   **    be used to optimize this query, then it can also be used by the FK
   11422   **    implementation to optimize DELETE or UPDATE statements on the parent
   11423   **    table.
   11424   **
   11425   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
   11426   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
   11427   **    contains an index that can be used to optimize the query.
   11428   **
   11429   ** 2. Human readable text that describes the child table and columns. e.g.
   11430   **
   11431   **       "child_table(child_key1, child_key2)"
   11432   **
   11433   ** 3. Human readable text that describes the parent table and columns. e.g.
   11434   **
   11435   **       "parent_table(parent_key1, parent_key2)"
   11436   **
   11437   ** 4. A full CREATE INDEX statement for an index that could be used to
   11438   **    optimize DELETE or UPDATE statements on the parent table. e.g.
   11439   **
   11440   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
   11441   **
   11442   ** 5. The name of the parent table.
   11443   **
   11444   ** These six values are used by the C logic below to generate the report.
   11445   */
   11446   const char *zSql =
   11447   "SELECT "
   11448     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
   11449     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
   11450     "  || fkey_collate_clause("
   11451     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
   11452     ", "
   11453     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
   11454     "  || group_concat('*=?', ' AND ') || ')'"
   11455     ", "
   11456     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
   11457     ", "
   11458     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
   11459     ", "
   11460     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
   11461     "  || ' ON ' || quote(s.name) || '('"
   11462     "  || group_concat(quote(f.[from]) ||"
   11463     "        fkey_collate_clause("
   11464     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
   11465     "  || ');'"
   11466     ", "
   11467     "     f.[table] "
   11468     "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
   11469     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
   11470     "GROUP BY s.name, f.id "
   11471     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
   11472   ;
   11473   const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
   11474 
   11475   for(i=2; i<nArg; i++){
   11476     int n = strlen30(azArg[i]);
   11477     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
   11478       bVerbose = 1;
   11479     }
   11480     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
   11481       bGroupByParent = 1;
   11482       zIndent = "    ";
   11483     }
   11484     else{
   11485       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
   11486           azArg[0], azArg[1]
   11487       );
   11488       return SQLITE_ERROR;
   11489     }
   11490   }
   11491 
   11492   /* Register the fkey_collate_clause() SQL function */
   11493   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
   11494       0, shellFkeyCollateClause, 0, 0
   11495   );
   11496 
   11497 
   11498   if( rc==SQLITE_OK ){
   11499     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
   11500   }
   11501   if( rc==SQLITE_OK ){
   11502     sqlite3_bind_int(pSql, 1, bGroupByParent);
   11503   }
   11504 
   11505   if( rc==SQLITE_OK ){
   11506     int rc2;
   11507     char *zPrev = 0;
   11508     while( SQLITE_ROW==sqlite3_step(pSql) ){
   11509       int res = -1;
   11510       sqlite3_stmt *pExplain = 0;
   11511       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
   11512       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
   11513       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
   11514       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
   11515       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
   11516       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
   11517 
   11518       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
   11519       if( rc!=SQLITE_OK ) break;
   11520       if( SQLITE_ROW==sqlite3_step(pExplain) ){
   11521         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
   11522         res = (
   11523               0==sqlite3_strglob(zGlob, zPlan)
   11524            || 0==sqlite3_strglob(zGlobIPK, zPlan)
   11525         );
   11526       }
   11527       rc = sqlite3_finalize(pExplain);
   11528       if( rc!=SQLITE_OK ) break;
   11529 
   11530       if( res<0 ){
   11531         raw_printf(stderr, "Error: internal error");
   11532         break;
   11533       }else{
   11534         if( bGroupByParent
   11535         && (bVerbose || res==0)
   11536         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
   11537         ){
   11538           raw_printf(out, "-- Parent table %s\n", zParent);
   11539           sqlite3_free(zPrev);
   11540           zPrev = sqlite3_mprintf("%s", zParent);
   11541         }
   11542 
   11543         if( res==0 ){
   11544           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
   11545         }else if( bVerbose ){
   11546           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
   11547               zIndent, zFrom, zTarget
   11548           );
   11549         }
   11550       }
   11551     }
   11552     sqlite3_free(zPrev);
   11553 
   11554     if( rc!=SQLITE_OK ){
   11555       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
   11556     }
   11557 
   11558     rc2 = sqlite3_finalize(pSql);
   11559     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
   11560       rc = rc2;
   11561       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
   11562     }
   11563   }else{
   11564     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
   11565   }
   11566 
   11567   return rc;
   11568 }
   11569 
   11570 /*
   11571 ** Implementation of ".lint" dot command.
   11572 */
   11573 static int lintDotCommand(
   11574   ShellState *pState,             /* Current shell tool state */
   11575   char **azArg,                   /* Array of arguments passed to dot command */
   11576   int nArg                        /* Number of entries in azArg[] */
   11577 ){
   11578   int n;
   11579   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
   11580   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
   11581   return lintFkeyIndexes(pState, azArg, nArg);
   11582 
   11583  usage:
   11584   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
   11585   raw_printf(stderr, "Where sub-commands are:\n");
   11586   raw_printf(stderr, "    fkey-indexes\n");
   11587   return SQLITE_ERROR;
   11588 }
   11589 
   11590 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
   11591 /*********************************************************************************
   11592 ** The ".archive" or ".ar" command.
   11593 */
   11594 static void shellPrepare(
   11595   sqlite3 *db,
   11596   int *pRc,
   11597   const char *zSql,
   11598   sqlite3_stmt **ppStmt
   11599 ){
   11600   *ppStmt = 0;
   11601   if( *pRc==SQLITE_OK ){
   11602     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
   11603     if( rc!=SQLITE_OK ){
   11604       raw_printf(stderr, "sql error: %s (%d)\n",
   11605           sqlite3_errmsg(db), sqlite3_errcode(db)
   11606       );
   11607       *pRc = rc;
   11608     }
   11609   }
   11610 }
   11611 
   11612 static void shellPreparePrintf(
   11613   sqlite3 *db,
   11614   int *pRc,
   11615   sqlite3_stmt **ppStmt,
   11616   const char *zFmt,
   11617   ...
   11618 ){
   11619   *ppStmt = 0;
   11620   if( *pRc==SQLITE_OK ){
   11621     va_list ap;
   11622     char *z;
   11623     va_start(ap, zFmt);
   11624     z = sqlite3_vmprintf(zFmt, ap);
   11625     if( z==0 ){
   11626       *pRc = SQLITE_NOMEM;
   11627     }else{
   11628       shellPrepare(db, pRc, z, ppStmt);
   11629       sqlite3_free(z);
   11630     }
   11631   }
   11632 }
   11633 
   11634 static void shellFinalize(
   11635   int *pRc,
   11636   sqlite3_stmt *pStmt
   11637 ){
   11638   if( pStmt ){
   11639     sqlite3 *db = sqlite3_db_handle(pStmt);
   11640     int rc = sqlite3_finalize(pStmt);
   11641     if( *pRc==SQLITE_OK ){
   11642       if( rc!=SQLITE_OK ){
   11643         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
   11644       }
   11645       *pRc = rc;
   11646     }
   11647   }
   11648 }
   11649 
   11650 static void shellReset(
   11651   int *pRc,
   11652   sqlite3_stmt *pStmt
   11653 ){
   11654   int rc = sqlite3_reset(pStmt);
   11655   if( *pRc==SQLITE_OK ){
   11656     if( rc!=SQLITE_OK ){
   11657       sqlite3 *db = sqlite3_db_handle(pStmt);
   11658       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
   11659     }
   11660     *pRc = rc;
   11661   }
   11662 }
   11663 /*
   11664 ** Structure representing a single ".ar" command.
   11665 */
   11666 typedef struct ArCommand ArCommand;
   11667 struct ArCommand {
   11668   u8 eCmd;                        /* An AR_CMD_* value */
   11669   u8 bVerbose;                    /* True if --verbose */
   11670   u8 bZip;                        /* True if the archive is a ZIP */
   11671   u8 bDryRun;                     /* True if --dry-run */
   11672   u8 bAppend;                     /* True if --append */
   11673   int nArg;                       /* Number of command arguments */
   11674   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
   11675   const char *zFile;              /* --file argument, or NULL */
   11676   const char *zDir;               /* --directory argument, or NULL */
   11677   char **azArg;                   /* Array of command arguments */
   11678   ShellState *p;                  /* Shell state */
   11679   sqlite3 *db;                    /* Database containing the archive */
   11680 };
   11681 
   11682 /*
   11683 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
   11684 */
   11685 static int arUsage(FILE *f){
   11686   raw_printf(f,
   11687 "\n"
   11688 "Usage: .ar [OPTION...] [FILE...]\n"
   11689 "The .ar command manages sqlar archives.\n"
   11690 "\n"
   11691 "Examples:\n"
   11692 "  .ar -cf archive.sar foo bar    # Create archive.sar from files foo and bar\n"
   11693 "  .ar -tf archive.sar            # List members of archive.sar\n"
   11694 "  .ar -xvf archive.sar           # Verbosely extract files from archive.sar\n"
   11695 "\n"
   11696 "Each command line must feature exactly one command option:\n"
   11697 "  -c, --create               Create a new archive\n"
   11698 "  -u, --update               Update or add files to an existing archive\n"
   11699 "  -t, --list                 List contents of archive\n"
   11700 "  -x, --extract              Extract files from archive\n"
   11701 "\n"
   11702 "And zero or more optional options:\n"
   11703 "  -v, --verbose              Print each filename as it is processed\n"
   11704 "  -f FILE, --file FILE       Operate on archive FILE (default is current db)\n"
   11705 "  -a FILE, --append FILE     Operate on FILE opened using the apndvfs VFS\n"
   11706 "  -C DIR, --directory DIR    Change to directory DIR to read/extract files\n"
   11707 "  -n, --dryrun               Show the SQL that would have occurred\n"
   11708 "\n"
   11709 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
   11710 "\n"
   11711 );
   11712   return SQLITE_ERROR;
   11713 }
   11714 
   11715 /*
   11716 ** Print an error message for the .ar command to stderr and return
   11717 ** SQLITE_ERROR.
   11718 */
   11719 static int arErrorMsg(const char *zFmt, ...){
   11720   va_list ap;
   11721   char *z;
   11722   va_start(ap, zFmt);
   11723   z = sqlite3_vmprintf(zFmt, ap);
   11724   va_end(ap);
   11725   raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
   11726   sqlite3_free(z);
   11727   return SQLITE_ERROR;
   11728 }
   11729 
   11730 /*
   11731 ** Values for ArCommand.eCmd.
   11732 */
   11733 #define AR_CMD_CREATE       1
   11734 #define AR_CMD_EXTRACT      2
   11735 #define AR_CMD_LIST         3
   11736 #define AR_CMD_UPDATE       4
   11737 #define AR_CMD_HELP         5
   11738 
   11739 /*
   11740 ** Other (non-command) switches.
   11741 */
   11742 #define AR_SWITCH_VERBOSE     6
   11743 #define AR_SWITCH_FILE        7
   11744 #define AR_SWITCH_DIRECTORY   8
   11745 #define AR_SWITCH_APPEND      9
   11746 #define AR_SWITCH_DRYRUN     10
   11747 
   11748 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
   11749   switch( eSwitch ){
   11750     case AR_CMD_CREATE:
   11751     case AR_CMD_EXTRACT:
   11752     case AR_CMD_LIST:
   11753     case AR_CMD_UPDATE:
   11754     case AR_CMD_HELP:
   11755       if( pAr->eCmd ){
   11756         return arErrorMsg("multiple command options");
   11757       }
   11758       pAr->eCmd = eSwitch;
   11759       break;
   11760 
   11761     case AR_SWITCH_DRYRUN:
   11762       pAr->bDryRun = 1;
   11763       break;
   11764     case AR_SWITCH_VERBOSE:
   11765       pAr->bVerbose = 1;
   11766       break;
   11767     case AR_SWITCH_APPEND:
   11768       pAr->bAppend = 1;
   11769       /* Fall thru into --file */
   11770     case AR_SWITCH_FILE:
   11771       pAr->zFile = zArg;
   11772       break;
   11773     case AR_SWITCH_DIRECTORY:
   11774       pAr->zDir = zArg;
   11775       break;
   11776   }
   11777 
   11778   return SQLITE_OK;
   11779 }
   11780 
   11781 /*
   11782 ** Parse the command line for an ".ar" command. The results are written into
   11783 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
   11784 ** successfully, otherwise an error message is written to stderr and
   11785 ** SQLITE_ERROR returned.
   11786 */
   11787 static int arParseCommand(
   11788   char **azArg,                   /* Array of arguments passed to dot command */
   11789   int nArg,                       /* Number of entries in azArg[] */
   11790   ArCommand *pAr                  /* Populate this object */
   11791 ){
   11792   struct ArSwitch {
   11793     const char *zLong;
   11794     char cShort;
   11795     u8 eSwitch;
   11796     u8 bArg;
   11797   } aSwitch[] = {
   11798     { "create",    'c', AR_CMD_CREATE,       0 },
   11799     { "extract",   'x', AR_CMD_EXTRACT,      0 },
   11800     { "list",      't', AR_CMD_LIST,         0 },
   11801     { "update",    'u', AR_CMD_UPDATE,       0 },
   11802     { "help",      'h', AR_CMD_HELP,         0 },
   11803     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
   11804     { "file",      'f', AR_SWITCH_FILE,      1 },
   11805     { "append",    'a', AR_SWITCH_APPEND,    1 },
   11806     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
   11807     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
   11808   };
   11809   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
   11810   struct ArSwitch *pEnd = &aSwitch[nSwitch];
   11811 
   11812   if( nArg<=1 ){
   11813     return arUsage(stderr);
   11814   }else{
   11815     char *z = azArg[1];
   11816     memset(pAr, 0, sizeof(ArCommand));
   11817 
   11818     if( z[0]!='-' ){
   11819       /* Traditional style [tar] invocation */
   11820       int i;
   11821       int iArg = 2;
   11822       for(i=0; z[i]; i++){
   11823         const char *zArg = 0;
   11824         struct ArSwitch *pOpt;
   11825         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
   11826           if( z[i]==pOpt->cShort ) break;
   11827         }
   11828         if( pOpt==pEnd ){
   11829           return arErrorMsg("unrecognized option: %c", z[i]);
   11830         }
   11831         if( pOpt->bArg ){
   11832           if( iArg>=nArg ){
   11833             return arErrorMsg("option requires an argument: %c",z[i]);
   11834           }
   11835           zArg = azArg[iArg++];
   11836         }
   11837         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
   11838       }
   11839       pAr->nArg = nArg-iArg;
   11840       if( pAr->nArg>0 ){
   11841         pAr->azArg = &azArg[iArg];
   11842       }
   11843     }else{
   11844       /* Non-traditional invocation */
   11845       int iArg;
   11846       for(iArg=1; iArg<nArg; iArg++){
   11847         int n;
   11848         z = azArg[iArg];
   11849         if( z[0]!='-' ){
   11850           /* All remaining command line words are command arguments. */
   11851           pAr->azArg = &azArg[iArg];
   11852           pAr->nArg = nArg-iArg;
   11853           break;
   11854         }
   11855         n = strlen30(z);
   11856 
   11857         if( z[1]!='-' ){
   11858           int i;
   11859           /* One or more short options */
   11860           for(i=1; i<n; i++){
   11861             const char *zArg = 0;
   11862             struct ArSwitch *pOpt;
   11863             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
   11864               if( z[i]==pOpt->cShort ) break;
   11865             }
   11866             if( pOpt==pEnd ){
   11867               return arErrorMsg("unrecognized option: %c\n", z[i]);
   11868             }
   11869             if( pOpt->bArg ){
   11870               if( i<(n-1) ){
   11871                 zArg = &z[i+1];
   11872                 i = n;
   11873               }else{
   11874                 if( iArg>=(nArg-1) ){
   11875                   return arErrorMsg("option requires an argument: %c\n",z[i]);
   11876                 }
   11877                 zArg = azArg[++iArg];
   11878               }
   11879             }
   11880             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
   11881           }
   11882         }else if( z[2]=='\0' ){
   11883           /* A -- option, indicating that all remaining command line words
   11884           ** are command arguments.  */
   11885           pAr->azArg = &azArg[iArg+1];
   11886           pAr->nArg = nArg-iArg-1;
   11887           break;
   11888         }else{
   11889           /* A long option */
   11890           const char *zArg = 0;             /* Argument for option, if any */
   11891           struct ArSwitch *pMatch = 0;      /* Matching option */
   11892           struct ArSwitch *pOpt;            /* Iterator */
   11893           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
   11894             const char *zLong = pOpt->zLong;
   11895             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
   11896               if( pMatch ){
   11897                 return arErrorMsg("ambiguous option: %s",z);
   11898               }else{
   11899                 pMatch = pOpt;
   11900               }
   11901             }
   11902           }
   11903 
   11904           if( pMatch==0 ){
   11905             return arErrorMsg("unrecognized option: %s", z);
   11906           }
   11907           if( pMatch->bArg ){
   11908             if( iArg>=(nArg-1) ){
   11909               return arErrorMsg("option requires an argument: %s", z);
   11910             }
   11911             zArg = azArg[++iArg];
   11912           }
   11913           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
   11914         }
   11915       }
   11916     }
   11917   }
   11918 
   11919   return SQLITE_OK;
   11920 }
   11921 
   11922 /*
   11923 ** This function assumes that all arguments within the ArCommand.azArg[]
   11924 ** array refer to archive members, as for the --extract or --list commands.
   11925 ** It checks that each of them are present. If any specified file is not
   11926 ** present in the archive, an error is printed to stderr and an error
   11927 ** code returned. Otherwise, if all specified arguments are present in
   11928 ** the archive, SQLITE_OK is returned.
   11929 **
   11930 ** This function strips any trailing '/' characters from each argument.
   11931 ** This is consistent with the way the [tar] command seems to work on
   11932 ** Linux.
   11933 */
   11934 static int arCheckEntries(ArCommand *pAr){
   11935   int rc = SQLITE_OK;
   11936   if( pAr->nArg ){
   11937     int i, j;
   11938     sqlite3_stmt *pTest = 0;
   11939 
   11940     shellPreparePrintf(pAr->db, &rc, &pTest,
   11941         "SELECT name FROM %s WHERE name=$name",
   11942         pAr->zSrcTable
   11943     );
   11944     j = sqlite3_bind_parameter_index(pTest, "$name");
   11945     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
   11946       char *z = pAr->azArg[i];
   11947       int n = strlen30(z);
   11948       int bOk = 0;
   11949       while( n>0 && z[n-1]=='/' ) n--;
   11950       z[n] = '\0';
   11951       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
   11952       if( SQLITE_ROW==sqlite3_step(pTest) ){
   11953         bOk = 1;
   11954       }
   11955       shellReset(&rc, pTest);
   11956       if( rc==SQLITE_OK && bOk==0 ){
   11957         utf8_printf(stderr, "not found in archive: %s\n", z);
   11958         rc = SQLITE_ERROR;
   11959       }
   11960     }
   11961     shellFinalize(&rc, pTest);
   11962   }
   11963   return rc;
   11964 }
   11965 
   11966 /*
   11967 ** Format a WHERE clause that can be used against the "sqlar" table to
   11968 ** identify all archive members that match the command arguments held
   11969 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
   11970 ** The caller is responsible for eventually calling sqlite3_free() on
   11971 ** any non-NULL (*pzWhere) value.
   11972 */
   11973 static void arWhereClause(
   11974   int *pRc,
   11975   ArCommand *pAr,
   11976   char **pzWhere                  /* OUT: New WHERE clause */
   11977 ){
   11978   char *zWhere = 0;
   11979   if( *pRc==SQLITE_OK ){
   11980     if( pAr->nArg==0 ){
   11981       zWhere = sqlite3_mprintf("1");
   11982     }else{
   11983       int i;
   11984       const char *zSep = "";
   11985       for(i=0; i<pAr->nArg; i++){
   11986         const char *z = pAr->azArg[i];
   11987         zWhere = sqlite3_mprintf(
   11988           "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
   11989           zWhere, zSep, z, strlen30(z)+1, z
   11990         );
   11991         if( zWhere==0 ){
   11992           *pRc = SQLITE_NOMEM;
   11993           break;
   11994         }
   11995         zSep = " OR ";
   11996       }
   11997     }
   11998   }
   11999   *pzWhere = zWhere;
   12000 }
   12001 
   12002 /*
   12003 ** Implementation of .ar "lisT" command.
   12004 */
   12005 static int arListCommand(ArCommand *pAr){
   12006   const char *zSql = "SELECT %s FROM %s WHERE %s";
   12007   const char *azCols[] = {
   12008     "name",
   12009     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
   12010   };
   12011 
   12012   char *zWhere = 0;
   12013   sqlite3_stmt *pSql = 0;
   12014   int rc;
   12015 
   12016   rc = arCheckEntries(pAr);
   12017   arWhereClause(&rc, pAr, &zWhere);
   12018 
   12019   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
   12020                      pAr->zSrcTable, zWhere);
   12021   if( pAr->bDryRun ){
   12022     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
   12023   }else{
   12024     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
   12025       if( pAr->bVerbose ){
   12026         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
   12027             sqlite3_column_text(pSql, 0),
   12028             sqlite3_column_int(pSql, 1),
   12029             sqlite3_column_text(pSql, 2),
   12030             sqlite3_column_text(pSql, 3)
   12031         );
   12032       }else{
   12033         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
   12034       }
   12035     }
   12036   }
   12037   shellFinalize(&rc, pSql);
   12038   return rc;
   12039 }
   12040 
   12041 
   12042 /*
   12043 ** Implementation of .ar "eXtract" command.
   12044 */
   12045 static int arExtractCommand(ArCommand *pAr){
   12046   const char *zSql1 =
   12047     "SELECT "
   12048     " ($dir || name),"
   12049     " writefile(($dir || name), %s, mode, mtime) "
   12050     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
   12051 
   12052   const char *azExtraArg[] = {
   12053     "sqlar_uncompress(data, sz)",
   12054     "data"
   12055   };
   12056 
   12057   sqlite3_stmt *pSql = 0;
   12058   int rc = SQLITE_OK;
   12059   char *zDir = 0;
   12060   char *zWhere = 0;
   12061   int i, j;
   12062 
   12063   /* If arguments are specified, check that they actually exist within
   12064   ** the archive before proceeding. And formulate a WHERE clause to
   12065   ** match them.  */
   12066   rc = arCheckEntries(pAr);
   12067   arWhereClause(&rc, pAr, &zWhere);
   12068 
   12069   if( rc==SQLITE_OK ){
   12070     if( pAr->zDir ){
   12071       zDir = sqlite3_mprintf("%s/", pAr->zDir);
   12072     }else{
   12073       zDir = sqlite3_mprintf("");
   12074     }
   12075     if( zDir==0 ) rc = SQLITE_NOMEM;
   12076   }
   12077 
   12078   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
   12079       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
   12080   );
   12081 
   12082   if( rc==SQLITE_OK ){
   12083     j = sqlite3_bind_parameter_index(pSql, "$dir");
   12084     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
   12085 
   12086     /* Run the SELECT statement twice. The first time, writefile() is called
   12087     ** for all archive members that should be extracted. The second time,
   12088     ** only for the directories. This is because the timestamps for
   12089     ** extracted directories must be reset after they are populated (as
   12090     ** populating them changes the timestamp).  */
   12091     for(i=0; i<2; i++){
   12092       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
   12093       sqlite3_bind_int(pSql, j, i);
   12094       if( pAr->bDryRun ){
   12095         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
   12096       }else{
   12097         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
   12098           if( i==0 && pAr->bVerbose ){
   12099             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
   12100           }
   12101         }
   12102       }
   12103       shellReset(&rc, pSql);
   12104     }
   12105     shellFinalize(&rc, pSql);
   12106   }
   12107 
   12108   sqlite3_free(zDir);
   12109   sqlite3_free(zWhere);
   12110   return rc;
   12111 }
   12112 
   12113 /*
   12114 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
   12115 */
   12116 static int arExecSql(ArCommand *pAr, const char *zSql){
   12117   int rc;
   12118   if( pAr->bDryRun ){
   12119     utf8_printf(pAr->p->out, "%s\n", zSql);
   12120     rc = SQLITE_OK;
   12121   }else{
   12122     char *zErr = 0;
   12123     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
   12124     if( zErr ){
   12125       utf8_printf(stdout, "ERROR: %s\n", zErr);
   12126       sqlite3_free(zErr);
   12127     }
   12128   }
   12129   return rc;
   12130 }
   12131 
   12132 
   12133 /*
   12134 ** Implementation of .ar "create" and "update" commands.
   12135 **
   12136 ** Create the "sqlar" table in the database if it does not already exist.
   12137 ** Then add each file in the azFile[] array to the archive. Directories
   12138 ** are added recursively. If argument bVerbose is non-zero, a message is
   12139 ** printed on stdout for each file archived.
   12140 **
   12141 ** The create command is the same as update, except that it drops
   12142 ** any existing "sqlar" table before beginning.
   12143 */
   12144 static int arCreateOrUpdateCommand(
   12145   ArCommand *pAr,                 /* Command arguments and options */
   12146   int bUpdate                     /* true for a --create.  false for --update */
   12147 ){
   12148   const char *zCreate =
   12149       "CREATE TABLE IF NOT EXISTS sqlar(\n"
   12150       "  name TEXT PRIMARY KEY,  -- name of the file\n"
   12151       "  mode INT,               -- access permissions\n"
   12152       "  mtime INT,              -- last modification time\n"
   12153       "  sz INT,                 -- original file size\n"
   12154       "  data BLOB               -- compressed content\n"
   12155       ")";
   12156   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
   12157   const char *zInsertFmt =
   12158      "REPLACE INTO sqlar(name,mode,mtime,sz,data)\n"
   12159      "  SELECT\n"
   12160      "    %s,\n"
   12161      "    mode,\n"
   12162      "    mtime,\n"
   12163      "    CASE substr(lsmode(mode),1,1)\n"
   12164      "      WHEN '-' THEN length(data)\n"
   12165      "      WHEN 'd' THEN 0\n"
   12166      "      ELSE -1 END,\n"
   12167      "    CASE WHEN lsmode(mode) LIKE 'd%%' THEN NULL else data END\n"
   12168      "  FROM fsdir(%Q,%Q)\n"
   12169      "  WHERE lsmode(mode) NOT LIKE '?%%';";
   12170   int i;                          /* For iterating through azFile[] */
   12171   int rc;                         /* Return code */
   12172 
   12173   rc = arExecSql(pAr, "SAVEPOINT ar;");
   12174   if( rc!=SQLITE_OK ) return rc;
   12175   if( bUpdate==0 ){
   12176     rc = arExecSql(pAr, zDrop);
   12177     if( rc!=SQLITE_OK ) return rc;
   12178   }
   12179   rc = arExecSql(pAr, zCreate);
   12180   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
   12181     char *zSql = sqlite3_mprintf(zInsertFmt,
   12182         pAr->bVerbose ? "shell_putsnl(name)" : "name",
   12183         pAr->azArg[i], pAr->zDir);
   12184     rc = arExecSql(pAr, zSql);
   12185     sqlite3_free(zSql);
   12186   }
   12187   if( rc!=SQLITE_OK ){
   12188     arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
   12189   }else{
   12190     rc = arExecSql(pAr, "RELEASE ar;");
   12191   }
   12192   return rc;
   12193 }
   12194 
   12195 /*
   12196 ** Implementation of ".ar" dot command.
   12197 */
   12198 static int arDotCommand(
   12199   ShellState *pState,             /* Current shell tool state */
   12200   char **azArg,                   /* Array of arguments passed to dot command */
   12201   int nArg                        /* Number of entries in azArg[] */
   12202 ){
   12203   ArCommand cmd;
   12204   int rc;
   12205   memset(&cmd, 0, sizeof(cmd));
   12206   rc = arParseCommand(azArg, nArg, &cmd);
   12207   if( rc==SQLITE_OK ){
   12208     int eDbType = SHELL_OPEN_UNSPEC;
   12209     cmd.p = pState;
   12210     cmd.db = pState->db;
   12211     if( cmd.zFile ){
   12212       eDbType = deduceDatabaseType(cmd.zFile);
   12213     }else{
   12214       eDbType = pState->openMode;
   12215     }
   12216     if( eDbType==SHELL_OPEN_ZIPFILE ){
   12217       if( cmd.zFile==0 ){
   12218         cmd.zSrcTable = sqlite3_mprintf("zip");
   12219       }else{
   12220         cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
   12221       }
   12222       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
   12223         utf8_printf(stderr, "zip archives are read-only\n");
   12224         rc = SQLITE_ERROR;
   12225         goto end_ar_command;
   12226       }
   12227       cmd.bZip = 1;
   12228     }else if( cmd.zFile ){
   12229       int flags;
   12230       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
   12231       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
   12232         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
   12233       }else{
   12234         flags = SQLITE_OPEN_READONLY;
   12235       }
   12236       cmd.db = 0;
   12237       if( cmd.bDryRun ){
   12238         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
   12239              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
   12240       }
   12241       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
   12242              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
   12243       if( rc!=SQLITE_OK ){
   12244         utf8_printf(stderr, "cannot open file: %s (%s)\n",
   12245             cmd.zFile, sqlite3_errmsg(cmd.db)
   12246         );
   12247         goto end_ar_command;
   12248       }
   12249       sqlite3_fileio_init(cmd.db, 0, 0);
   12250 #ifdef SQLITE_HAVE_ZLIB
   12251       sqlite3_sqlar_init(cmd.db, 0, 0);
   12252 #endif
   12253       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
   12254                               shellPutsFunc, 0, 0);
   12255 
   12256     }
   12257     if( cmd.zSrcTable==0 ){
   12258       if( cmd.eCmd!=AR_CMD_CREATE
   12259        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
   12260       ){
   12261         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
   12262         rc = SQLITE_ERROR;
   12263         goto end_ar_command;
   12264       }
   12265       cmd.zSrcTable = sqlite3_mprintf("sqlar");
   12266     }
   12267 
   12268     switch( cmd.eCmd ){
   12269       case AR_CMD_CREATE:
   12270         rc = arCreateOrUpdateCommand(&cmd, 0);
   12271         break;
   12272 
   12273       case AR_CMD_EXTRACT:
   12274         rc = arExtractCommand(&cmd);
   12275         break;
   12276 
   12277       case AR_CMD_LIST:
   12278         rc = arListCommand(&cmd);
   12279         break;
   12280 
   12281       case AR_CMD_HELP:
   12282         arUsage(pState->out);
   12283         break;
   12284 
   12285       default:
   12286         assert( cmd.eCmd==AR_CMD_UPDATE );
   12287         rc = arCreateOrUpdateCommand(&cmd, 1);
   12288         break;
   12289     }
   12290   }
   12291 end_ar_command:
   12292   if( cmd.db!=pState->db ){
   12293     sqlite3_close(cmd.db);
   12294   }
   12295   sqlite3_free(cmd.zSrcTable);
   12296 
   12297   return rc;
   12298 }
   12299 /* End of the ".archive" or ".ar" command logic
   12300 **********************************************************************************/
   12301 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
   12302 
   12303 
   12304 /*
   12305 ** If an input line begins with "." then invoke this routine to
   12306 ** process that line.
   12307 **
   12308 ** Return 1 on error, 2 to exit, and 0 otherwise.
   12309 */
   12310 static int do_meta_command(char *zLine, ShellState *p){
   12311   int h = 1;
   12312   int nArg = 0;
   12313   int n, c;
   12314   int rc = 0;
   12315   char *azArg[50];
   12316 
   12317 #ifndef SQLITE_OMIT_VIRTUALTABLE
   12318   if( p->expert.pExpert ){
   12319     expertFinish(p, 1, 0);
   12320   }
   12321 #endif
   12322 
   12323   /* Parse the input line into tokens.
   12324   */
   12325   while( zLine[h] && nArg<ArraySize(azArg) ){
   12326     while( IsSpace(zLine[h]) ){ h++; }
   12327     if( zLine[h]==0 ) break;
   12328     if( zLine[h]=='\'' || zLine[h]=='"' ){
   12329       int delim = zLine[h++];
   12330       azArg[nArg++] = &zLine[h];
   12331       while( zLine[h] && zLine[h]!=delim ){
   12332         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
   12333         h++;
   12334       }
   12335       if( zLine[h]==delim ){
   12336         zLine[h++] = 0;
   12337       }
   12338       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
   12339     }else{
   12340       azArg[nArg++] = &zLine[h];
   12341       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
   12342       if( zLine[h] ) zLine[h++] = 0;
   12343       resolve_backslashes(azArg[nArg-1]);
   12344     }
   12345   }
   12346 
   12347   /* Process the input line.
   12348   */
   12349   if( nArg==0 ) return 0; /* no tokens, no error */
   12350   n = strlen30(azArg[0]);
   12351   c = azArg[0][0];
   12352   clearTempFile(p);
   12353 
   12354 #ifndef SQLITE_OMIT_AUTHORIZATION
   12355   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
   12356     if( nArg!=2 ){
   12357       raw_printf(stderr, "Usage: .auth ON|OFF\n");
   12358       rc = 1;
   12359       goto meta_command_exit;
   12360     }
   12361     open_db(p, 0);
   12362     if( booleanValue(azArg[1]) ){
   12363       sqlite3_set_authorizer(p->db, shellAuth, p);
   12364     }else{
   12365       sqlite3_set_authorizer(p->db, 0, 0);
   12366     }
   12367   }else
   12368 #endif
   12369 
   12370 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
   12371   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
   12372     open_db(p, 0);
   12373     rc = arDotCommand(p, azArg, nArg);
   12374   }else
   12375 #endif
   12376 
   12377   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
   12378    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
   12379   ){
   12380     const char *zDestFile = 0;
   12381     const char *zDb = 0;
   12382     sqlite3 *pDest;
   12383     sqlite3_backup *pBackup;
   12384     int j;
   12385     for(j=1; j<nArg; j++){
   12386       const char *z = azArg[j];
   12387       if( z[0]=='-' ){
   12388         while( z[0]=='-' ) z++;
   12389         /* No options to process at this time */
   12390         {
   12391           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
   12392           return 1;
   12393         }
   12394       }else if( zDestFile==0 ){
   12395         zDestFile = azArg[j];
   12396       }else if( zDb==0 ){
   12397         zDb = zDestFile;
   12398         zDestFile = azArg[j];
   12399       }else{
   12400         raw_printf(stderr, "too many arguments to .backup\n");
   12401         return 1;
   12402       }
   12403     }
   12404     if( zDestFile==0 ){
   12405       raw_printf(stderr, "missing FILENAME argument on .backup\n");
   12406       return 1;
   12407     }
   12408     if( zDb==0 ) zDb = "main";
   12409     rc = sqlite3_open(zDestFile, &pDest);
   12410     if( rc!=SQLITE_OK ){
   12411       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
   12412       sqlite3_close(pDest);
   12413       return 1;
   12414     }
   12415     open_db(p, 0);
   12416     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
   12417     if( pBackup==0 ){
   12418       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
   12419       sqlite3_close(pDest);
   12420       return 1;
   12421     }
   12422     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
   12423     sqlite3_backup_finish(pBackup);
   12424     if( rc==SQLITE_DONE ){
   12425       rc = 0;
   12426     }else{
   12427       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
   12428       rc = 1;
   12429     }
   12430     sqlite3_close(pDest);
   12431   }else
   12432 
   12433   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
   12434     if( nArg==2 ){
   12435       bail_on_error = booleanValue(azArg[1]);
   12436     }else{
   12437       raw_printf(stderr, "Usage: .bail on|off\n");
   12438       rc = 1;
   12439     }
   12440   }else
   12441 
   12442   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
   12443     if( nArg==2 ){
   12444       if( booleanValue(azArg[1]) ){
   12445         setBinaryMode(p->out, 1);
   12446       }else{
   12447         setTextMode(p->out, 1);
   12448       }
   12449     }else{
   12450       raw_printf(stderr, "Usage: .binary on|off\n");
   12451       rc = 1;
   12452     }
   12453   }else
   12454 
   12455   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
   12456     if( nArg==2 ){
   12457 #if defined(_WIN32) || defined(WIN32)
   12458       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
   12459       rc = !SetCurrentDirectoryW(z);
   12460       sqlite3_free(z);
   12461 #else
   12462       rc = chdir(azArg[1]);
   12463 #endif
   12464       if( rc ){
   12465         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
   12466         rc = 1;
   12467       }
   12468     }else{
   12469       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
   12470       rc = 1;
   12471     }
   12472   }else
   12473 
   12474   /* The undocumented ".breakpoint" command causes a call to the no-op
   12475   ** routine named test_breakpoint().
   12476   */
   12477   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
   12478     test_breakpoint();
   12479   }else
   12480 
   12481   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
   12482     if( nArg==2 ){
   12483       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
   12484     }else{
   12485       raw_printf(stderr, "Usage: .changes on|off\n");
   12486       rc = 1;
   12487     }
   12488   }else
   12489 
   12490   /* Cancel output redirection, if it is currently set (by .testcase)
   12491   ** Then read the content of the testcase-out.txt file and compare against
   12492   ** azArg[1].  If there are differences, report an error and exit.
   12493   */
   12494   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
   12495     char *zRes = 0;
   12496     output_reset(p);
   12497     if( nArg!=2 ){
   12498       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
   12499       rc = 2;
   12500     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
   12501       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
   12502       rc = 2;
   12503     }else if( testcase_glob(azArg[1],zRes)==0 ){
   12504       utf8_printf(stderr,
   12505                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
   12506                  p->zTestcase, azArg[1], zRes);
   12507       rc = 1;
   12508     }else{
   12509       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
   12510       p->nCheck++;
   12511     }
   12512     sqlite3_free(zRes);
   12513   }else
   12514 
   12515   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
   12516     if( nArg==2 ){
   12517       tryToClone(p, azArg[1]);
   12518     }else{
   12519       raw_printf(stderr, "Usage: .clone FILENAME\n");
   12520       rc = 1;
   12521     }
   12522   }else
   12523 
   12524   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
   12525     ShellState data;
   12526     char *zErrMsg = 0;
   12527     open_db(p, 0);
   12528     memcpy(&data, p, sizeof(data));
   12529     data.showHeader = 0;
   12530     data.cMode = data.mode = MODE_List;
   12531     sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
   12532     data.cnt = 0;
   12533     sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
   12534                  callback, &data, &zErrMsg);
   12535     if( zErrMsg ){
   12536       utf8_printf(stderr,"Error: %s\n", zErrMsg);
   12537       sqlite3_free(zErrMsg);
   12538       rc = 1;
   12539     }
   12540   }else
   12541 
   12542   if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
   12543     rc = shell_dbinfo_command(p, nArg, azArg);
   12544   }else
   12545 
   12546   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
   12547     const char *zLike = 0;
   12548     int i;
   12549     int savedShowHeader = p->showHeader;
   12550     ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
   12551     for(i=1; i<nArg; i++){
   12552       if( azArg[i][0]=='-' ){
   12553         const char *z = azArg[i]+1;
   12554         if( z[0]=='-' ) z++;
   12555         if( strcmp(z,"preserve-rowids")==0 ){
   12556 #ifdef SQLITE_OMIT_VIRTUALTABLE
   12557           raw_printf(stderr, "The --preserve-rowids option is not compatible"
   12558                              " with SQLITE_OMIT_VIRTUALTABLE\n");
   12559           rc = 1;
   12560           goto meta_command_exit;
   12561 #else
   12562           ShellSetFlag(p, SHFLG_PreserveRowid);
   12563 #endif
   12564         }else
   12565         if( strcmp(z,"newlines")==0 ){
   12566           ShellSetFlag(p, SHFLG_Newlines);
   12567         }else
   12568         {
   12569           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
   12570           rc = 1;
   12571           goto meta_command_exit;
   12572         }
   12573       }else if( zLike ){
   12574         raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
   12575                            "?--newlines? ?LIKE-PATTERN?\n");
   12576         rc = 1;
   12577         goto meta_command_exit;
   12578       }else{
   12579         zLike = azArg[i];
   12580       }
   12581     }
   12582     open_db(p, 0);
   12583     /* When playing back a "dump", the content might appear in an order
   12584     ** which causes immediate foreign key constraints to be violated.
   12585     ** So disable foreign-key constraint enforcement to prevent problems. */
   12586     raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
   12587     raw_printf(p->out, "BEGIN TRANSACTION;\n");
   12588     p->writableSchema = 0;
   12589     p->showHeader = 0;
   12590     /* Set writable_schema=ON since doing so forces SQLite to initialize
   12591     ** as much of the schema as it can even if the sqlite_master table is
   12592     ** corrupt. */
   12593     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
   12594     p->nErr = 0;
   12595     if( zLike==0 ){
   12596       run_schema_dump_query(p,
   12597         "SELECT name, type, sql FROM sqlite_master "
   12598         "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
   12599       );
   12600       run_schema_dump_query(p,
   12601         "SELECT name, type, sql FROM sqlite_master "
   12602         "WHERE name=='sqlite_sequence'"
   12603       );
   12604       run_table_dump_query(p,
   12605         "SELECT sql FROM sqlite_master "
   12606         "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
   12607       );
   12608     }else{
   12609       char *zSql;
   12610       zSql = sqlite3_mprintf(
   12611         "SELECT name, type, sql FROM sqlite_master "
   12612         "WHERE tbl_name LIKE %Q AND type=='table'"
   12613         "  AND sql NOT NULL", zLike);
   12614       run_schema_dump_query(p,zSql);
   12615       sqlite3_free(zSql);
   12616       zSql = sqlite3_mprintf(
   12617         "SELECT sql FROM sqlite_master "
   12618         "WHERE sql NOT NULL"
   12619         "  AND type IN ('index','trigger','view')"
   12620         "  AND tbl_name LIKE %Q", zLike);
   12621       run_table_dump_query(p, zSql, 0);
   12622       sqlite3_free(zSql);
   12623     }
   12624     if( p->writableSchema ){
   12625       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
   12626       p->writableSchema = 0;
   12627     }
   12628     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
   12629     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
   12630     raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
   12631     p->showHeader = savedShowHeader;
   12632   }else
   12633 
   12634   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
   12635     if( nArg==2 ){
   12636       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
   12637     }else{
   12638       raw_printf(stderr, "Usage: .echo on|off\n");
   12639       rc = 1;
   12640     }
   12641   }else
   12642 
   12643   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
   12644     if( nArg==2 ){
   12645       if( strcmp(azArg[1],"full")==0 ){
   12646         p->autoEQP = AUTOEQP_full;
   12647       }else if( strcmp(azArg[1],"trigger")==0 ){
   12648         p->autoEQP = AUTOEQP_trigger;
   12649       }else{
   12650         p->autoEQP = booleanValue(azArg[1]);
   12651       }
   12652     }else{
   12653       raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
   12654       rc = 1;
   12655     }
   12656   }else
   12657 
   12658   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
   12659     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
   12660     rc = 2;
   12661   }else
   12662 
   12663   /* The ".explain" command is automatic now.  It is largely pointless.  It
   12664   ** retained purely for backwards compatibility */
   12665   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
   12666     int val = 1;
   12667     if( nArg>=2 ){
   12668       if( strcmp(azArg[1],"auto")==0 ){
   12669         val = 99;
   12670       }else{
   12671         val =  booleanValue(azArg[1]);
   12672       }
   12673     }
   12674     if( val==1 && p->mode!=MODE_Explain ){
   12675       p->normalMode = p->mode;
   12676       p->mode = MODE_Explain;
   12677       p->autoExplain = 0;
   12678     }else if( val==0 ){
   12679       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
   12680       p->autoExplain = 0;
   12681     }else if( val==99 ){
   12682       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
   12683       p->autoExplain = 1;
   12684     }
   12685   }else
   12686 
   12687 #ifndef SQLITE_OMIT_VIRTUALTABLE
   12688   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
   12689     open_db(p, 0);
   12690     expertDotCommand(p, azArg, nArg);
   12691   }else
   12692 #endif
   12693 
   12694   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
   12695     ShellState data;
   12696     char *zErrMsg = 0;
   12697     int doStats = 0;
   12698     memcpy(&data, p, sizeof(data));
   12699     data.showHeader = 0;
   12700     data.cMode = data.mode = MODE_Semi;
   12701     if( nArg==2 && optionMatch(azArg[1], "indent") ){
   12702       data.cMode = data.mode = MODE_Pretty;
   12703       nArg = 1;
   12704     }
   12705     if( nArg!=1 ){
   12706       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
   12707       rc = 1;
   12708       goto meta_command_exit;
   12709     }
   12710     open_db(p, 0);
   12711     rc = sqlite3_exec(p->db,
   12712        "SELECT sql FROM"
   12713        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
   12714        "     FROM sqlite_master UNION ALL"
   12715        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
   12716        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
   12717        "ORDER BY rowid",
   12718        callback, &data, &zErrMsg
   12719     );
   12720     if( rc==SQLITE_OK ){
   12721       sqlite3_stmt *pStmt;
   12722       rc = sqlite3_prepare_v2(p->db,
   12723                "SELECT rowid FROM sqlite_master"
   12724                " WHERE name GLOB 'sqlite_stat[134]'",
   12725                -1, &pStmt, 0);
   12726       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
   12727       sqlite3_finalize(pStmt);
   12728     }
   12729     if( doStats==0 ){
   12730       raw_printf(p->out, "/* No STAT tables available */\n");
   12731     }else{
   12732       raw_printf(p->out, "ANALYZE sqlite_master;\n");
   12733       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
   12734                    callback, &data, &zErrMsg);
   12735       data.cMode = data.mode = MODE_Insert;
   12736       data.zDestTable = "sqlite_stat1";
   12737       shell_exec(p->db, "SELECT * FROM sqlite_stat1",
   12738                  shell_callback, &data,&zErrMsg);
   12739       data.zDestTable = "sqlite_stat3";
   12740       shell_exec(p->db, "SELECT * FROM sqlite_stat3",
   12741                  shell_callback, &data,&zErrMsg);
   12742       data.zDestTable = "sqlite_stat4";
   12743       shell_exec(p->db, "SELECT * FROM sqlite_stat4",
   12744                  shell_callback, &data, &zErrMsg);
   12745       raw_printf(p->out, "ANALYZE sqlite_master;\n");
   12746     }
   12747   }else
   12748 
   12749   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
   12750     if( nArg==2 ){
   12751       p->showHeader = booleanValue(azArg[1]);
   12752     }else{
   12753       raw_printf(stderr, "Usage: .headers on|off\n");
   12754       rc = 1;
   12755     }
   12756   }else
   12757 
   12758   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
   12759     utf8_printf(p->out, "%s", zHelp);
   12760   }else
   12761 
   12762   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
   12763     char *zTable;               /* Insert data into this table */
   12764     char *zFile;                /* Name of file to extra content from */
   12765     sqlite3_stmt *pStmt = NULL; /* A statement */
   12766     int nCol;                   /* Number of columns in the table */
   12767     int nByte;                  /* Number of bytes in an SQL string */
   12768     int i, j;                   /* Loop counters */
   12769     int needCommit;             /* True to COMMIT or ROLLBACK at end */
   12770     int nSep;                   /* Number of bytes in p->colSeparator[] */
   12771     char *zSql;                 /* An SQL statement */
   12772     ImportCtx sCtx;             /* Reader context */
   12773     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
   12774     int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
   12775 
   12776     if( nArg!=3 ){
   12777       raw_printf(stderr, "Usage: .import FILE TABLE\n");
   12778       goto meta_command_exit;
   12779     }
   12780     zFile = azArg[1];
   12781     zTable = azArg[2];
   12782     seenInterrupt = 0;
   12783     memset(&sCtx, 0, sizeof(sCtx));
   12784     open_db(p, 0);
   12785     nSep = strlen30(p->colSeparator);
   12786     if( nSep==0 ){
   12787       raw_printf(stderr,
   12788                  "Error: non-null column separator required for import\n");
   12789       return 1;
   12790     }
   12791     if( nSep>1 ){
   12792       raw_printf(stderr, "Error: multi-character column separators not allowed"
   12793                       " for import\n");
   12794       return 1;
   12795     }
   12796     nSep = strlen30(p->rowSeparator);
   12797     if( nSep==0 ){
   12798       raw_printf(stderr, "Error: non-null row separator required for import\n");
   12799       return 1;
   12800     }
   12801     if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
   12802       /* When importing CSV (only), if the row separator is set to the
   12803       ** default output row separator, change it to the default input
   12804       ** row separator.  This avoids having to maintain different input
   12805       ** and output row separators. */
   12806       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
   12807       nSep = strlen30(p->rowSeparator);
   12808     }
   12809     if( nSep>1 ){
   12810       raw_printf(stderr, "Error: multi-character row separators not allowed"
   12811                       " for import\n");
   12812       return 1;
   12813     }
   12814     sCtx.zFile = zFile;
   12815     sCtx.nLine = 1;
   12816     if( sCtx.zFile[0]=='|' ){
   12817 #ifdef SQLITE_OMIT_POPEN
   12818       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
   12819       return 1;
   12820 #else
   12821       sCtx.in = popen(sCtx.zFile+1, "r");
   12822       sCtx.zFile = "<pipe>";
   12823       xCloser = pclose;
   12824 #endif
   12825     }else{
   12826       sCtx.in = fopen(sCtx.zFile, "rb");
   12827       xCloser = fclose;
   12828     }
   12829     if( p->mode==MODE_Ascii ){
   12830       xRead = ascii_read_one_field;
   12831     }else{
   12832       xRead = csv_read_one_field;
   12833     }
   12834     if( sCtx.in==0 ){
   12835       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
   12836       return 1;
   12837     }
   12838     sCtx.cColSep = p->colSeparator[0];
   12839     sCtx.cRowSep = p->rowSeparator[0];
   12840     zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
   12841     if( zSql==0 ){
   12842       raw_printf(stderr, "Error: out of memory\n");
   12843       xCloser(sCtx.in);
   12844       return 1;
   12845     }
   12846     nByte = strlen30(zSql);
   12847     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   12848     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
   12849     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
   12850       char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
   12851       char cSep = '(';
   12852       while( xRead(&sCtx) ){
   12853         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
   12854         cSep = ',';
   12855         if( sCtx.cTerm!=sCtx.cColSep ) break;
   12856       }
   12857       if( cSep=='(' ){
   12858         sqlite3_free(zCreate);
   12859         sqlite3_free(sCtx.z);
   12860         xCloser(sCtx.in);
   12861         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
   12862         return 1;
   12863       }
   12864       zCreate = sqlite3_mprintf("%z\n)", zCreate);
   12865       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
   12866       sqlite3_free(zCreate);
   12867       if( rc ){
   12868         utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
   12869                 sqlite3_errmsg(p->db));
   12870         sqlite3_free(sCtx.z);
   12871         xCloser(sCtx.in);
   12872         return 1;
   12873       }
   12874       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   12875     }
   12876     sqlite3_free(zSql);
   12877     if( rc ){
   12878       if (pStmt) sqlite3_finalize(pStmt);
   12879       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
   12880       xCloser(sCtx.in);
   12881       return 1;
   12882     }
   12883     nCol = sqlite3_column_count(pStmt);
   12884     sqlite3_finalize(pStmt);
   12885     pStmt = 0;
   12886     if( nCol==0 ) return 0; /* no columns, no error */
   12887     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
   12888     if( zSql==0 ){
   12889       raw_printf(stderr, "Error: out of memory\n");
   12890       xCloser(sCtx.in);
   12891       return 1;
   12892     }
   12893     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
   12894     j = strlen30(zSql);
   12895     for(i=1; i<nCol; i++){
   12896       zSql[j++] = ',';
   12897       zSql[j++] = '?';
   12898     }
   12899     zSql[j++] = ')';
   12900     zSql[j] = 0;
   12901     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   12902     sqlite3_free(zSql);
   12903     if( rc ){
   12904       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
   12905       if (pStmt) sqlite3_finalize(pStmt);
   12906       xCloser(sCtx.in);
   12907       return 1;
   12908     }
   12909     needCommit = sqlite3_get_autocommit(p->db);
   12910     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
   12911     do{
   12912       int startLine = sCtx.nLine;
   12913       for(i=0; i<nCol; i++){
   12914         char *z = xRead(&sCtx);
   12915         /*
   12916         ** Did we reach end-of-file before finding any columns?
   12917         ** If so, stop instead of NULL filling the remaining columns.
   12918         */
   12919         if( z==0 && i==0 ) break;
   12920         /*
   12921         ** Did we reach end-of-file OR end-of-line before finding any
   12922         ** columns in ASCII mode?  If so, stop instead of NULL filling
   12923         ** the remaining columns.
   12924         */
   12925         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
   12926         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
   12927         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
   12928           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
   12929                           "filling the rest with NULL\n",
   12930                           sCtx.zFile, startLine, nCol, i+1);
   12931           i += 2;
   12932           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
   12933         }
   12934       }
   12935       if( sCtx.cTerm==sCtx.cColSep ){
   12936         do{
   12937           xRead(&sCtx);
   12938           i++;
   12939         }while( sCtx.cTerm==sCtx.cColSep );
   12940         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
   12941                         "extras ignored\n",
   12942                         sCtx.zFile, startLine, nCol, i);
   12943       }
   12944       if( i>=nCol ){
   12945         sqlite3_step(pStmt);
   12946         rc = sqlite3_reset(pStmt);
   12947         if( rc!=SQLITE_OK ){
   12948           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
   12949                       startLine, sqlite3_errmsg(p->db));
   12950         }
   12951       }
   12952     }while( sCtx.cTerm!=EOF );
   12953 
   12954     xCloser(sCtx.in);
   12955     sqlite3_free(sCtx.z);
   12956     sqlite3_finalize(pStmt);
   12957     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
   12958   }else
   12959 
   12960 #ifndef SQLITE_UNTESTABLE
   12961   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
   12962     char *zSql;
   12963     char *zCollist = 0;
   12964     sqlite3_stmt *pStmt;
   12965     int tnum = 0;
   12966     int i;
   12967     if( nArg!=3 ){
   12968       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
   12969       rc = 1;
   12970       goto meta_command_exit;
   12971     }
   12972     open_db(p, 0);
   12973     zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
   12974                            " WHERE name='%q' AND type='index'", azArg[1]);
   12975     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   12976     sqlite3_free(zSql);
   12977     if( sqlite3_step(pStmt)==SQLITE_ROW ){
   12978       tnum = sqlite3_column_int(pStmt, 0);
   12979     }
   12980     sqlite3_finalize(pStmt);
   12981     if( tnum==0 ){
   12982       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
   12983       rc = 1;
   12984       goto meta_command_exit;
   12985     }
   12986     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
   12987     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   12988     sqlite3_free(zSql);
   12989     i = 0;
   12990     while( sqlite3_step(pStmt)==SQLITE_ROW ){
   12991       char zLabel[20];
   12992       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
   12993       i++;
   12994       if( zCol==0 ){
   12995         if( sqlite3_column_int(pStmt,1)==-1 ){
   12996           zCol = "_ROWID_";
   12997         }else{
   12998           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
   12999           zCol = zLabel;
   13000         }
   13001       }
   13002       if( zCollist==0 ){
   13003         zCollist = sqlite3_mprintf("\"%w\"", zCol);
   13004       }else{
   13005         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
   13006       }
   13007     }
   13008     sqlite3_finalize(pStmt);
   13009     zSql = sqlite3_mprintf(
   13010           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
   13011           azArg[2], zCollist, zCollist);
   13012     sqlite3_free(zCollist);
   13013     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
   13014     if( rc==SQLITE_OK ){
   13015       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
   13016       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
   13017       if( rc ){
   13018         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
   13019       }else{
   13020         utf8_printf(stdout, "%s;\n", zSql);
   13021         raw_printf(stdout,
   13022            "WARNING: writing to an imposter table will corrupt the index!\n"
   13023         );
   13024       }
   13025     }else{
   13026       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
   13027       rc = 1;
   13028     }
   13029     sqlite3_free(zSql);
   13030   }else
   13031 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
   13032 
   13033 #ifdef SQLITE_ENABLE_IOTRACE
   13034   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
   13035     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
   13036     if( iotrace && iotrace!=stdout ) fclose(iotrace);
   13037     iotrace = 0;
   13038     if( nArg<2 ){
   13039       sqlite3IoTrace = 0;
   13040     }else if( strcmp(azArg[1], "-")==0 ){
   13041       sqlite3IoTrace = iotracePrintf;
   13042       iotrace = stdout;
   13043     }else{
   13044       iotrace = fopen(azArg[1], "w");
   13045       if( iotrace==0 ){
   13046         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
   13047         sqlite3IoTrace = 0;
   13048         rc = 1;
   13049       }else{
   13050         sqlite3IoTrace = iotracePrintf;
   13051       }
   13052     }
   13053   }else
   13054 #endif
   13055 
   13056   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
   13057     static const struct {
   13058        const char *zLimitName;   /* Name of a limit */
   13059        int limitCode;            /* Integer code for that limit */
   13060     } aLimit[] = {
   13061       { "length",                SQLITE_LIMIT_LENGTH                    },
   13062       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
   13063       { "column",                SQLITE_LIMIT_COLUMN                    },
   13064       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
   13065       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
   13066       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
   13067       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
   13068       { "attached",              SQLITE_LIMIT_ATTACHED                  },
   13069       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
   13070       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
   13071       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
   13072       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
   13073     };
   13074     int i, n2;
   13075     open_db(p, 0);
   13076     if( nArg==1 ){
   13077       for(i=0; i<ArraySize(aLimit); i++){
   13078         printf("%20s %d\n", aLimit[i].zLimitName,
   13079                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
   13080       }
   13081     }else if( nArg>3 ){
   13082       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
   13083       rc = 1;
   13084       goto meta_command_exit;
   13085     }else{
   13086       int iLimit = -1;
   13087       n2 = strlen30(azArg[1]);
   13088       for(i=0; i<ArraySize(aLimit); i++){
   13089         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
   13090           if( iLimit<0 ){
   13091             iLimit = i;
   13092           }else{
   13093             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
   13094             rc = 1;
   13095             goto meta_command_exit;
   13096           }
   13097         }
   13098       }
   13099       if( iLimit<0 ){
   13100         utf8_printf(stderr, "unknown limit: \"%s\"\n"
   13101                         "enter \".limits\" with no arguments for a list.\n",
   13102                          azArg[1]);
   13103         rc = 1;
   13104         goto meta_command_exit;
   13105       }
   13106       if( nArg==3 ){
   13107         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
   13108                       (int)integerValue(azArg[2]));
   13109       }
   13110       printf("%20s %d\n", aLimit[iLimit].zLimitName,
   13111              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
   13112     }
   13113   }else
   13114 
   13115   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
   13116     open_db(p, 0);
   13117     lintDotCommand(p, azArg, nArg);
   13118   }else
   13119 
   13120 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   13121   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
   13122     const char *zFile, *zProc;
   13123     char *zErrMsg = 0;
   13124     if( nArg<2 ){
   13125       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
   13126       rc = 1;
   13127       goto meta_command_exit;
   13128     }
   13129     zFile = azArg[1];
   13130     zProc = nArg>=3 ? azArg[2] : 0;
   13131     open_db(p, 0);
   13132     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
   13133     if( rc!=SQLITE_OK ){
   13134       utf8_printf(stderr, "Error: %s\n", zErrMsg);
   13135       sqlite3_free(zErrMsg);
   13136       rc = 1;
   13137     }
   13138   }else
   13139 #endif
   13140 
   13141   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
   13142     if( nArg!=2 ){
   13143       raw_printf(stderr, "Usage: .log FILENAME\n");
   13144       rc = 1;
   13145     }else{
   13146       const char *zFile = azArg[1];
   13147       output_file_close(p->pLog);
   13148       p->pLog = output_file_open(zFile, 0);
   13149     }
   13150   }else
   13151 
   13152   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
   13153     const char *zMode = nArg>=2 ? azArg[1] : "";
   13154     int n2 = strlen30(zMode);
   13155     int c2 = zMode[0];
   13156     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
   13157       p->mode = MODE_Line;
   13158       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
   13159     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
   13160       p->mode = MODE_Column;
   13161       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
   13162     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
   13163       p->mode = MODE_List;
   13164       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
   13165       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
   13166     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
   13167       p->mode = MODE_Html;
   13168     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
   13169       p->mode = MODE_Tcl;
   13170       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
   13171       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
   13172     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
   13173       p->mode = MODE_Csv;
   13174       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
   13175       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
   13176     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
   13177       p->mode = MODE_List;
   13178       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
   13179     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
   13180       p->mode = MODE_Insert;
   13181       set_table_name(p, nArg>=3 ? azArg[2] : "table");
   13182     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
   13183       p->mode = MODE_Quote;
   13184     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
   13185       p->mode = MODE_Ascii;
   13186       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
   13187       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
   13188     }else if( nArg==1 ){
   13189       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
   13190     }else{
   13191       raw_printf(stderr, "Error: mode should be one of: "
   13192          "ascii column csv html insert line list quote tabs tcl\n");
   13193       rc = 1;
   13194     }
   13195     p->cMode = p->mode;
   13196   }else
   13197 
   13198   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
   13199     if( nArg==2 ){
   13200       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
   13201                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
   13202     }else{
   13203       raw_printf(stderr, "Usage: .nullvalue STRING\n");
   13204       rc = 1;
   13205     }
   13206   }else
   13207 
   13208   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
   13209     char *zNewFilename;  /* Name of the database file to open */
   13210     int iName = 1;       /* Index in azArg[] of the filename */
   13211     int newFlag = 0;     /* True to delete file before opening */
   13212     /* Close the existing database */
   13213     session_close_all(p);
   13214     sqlite3_close(p->db);
   13215     p->db = 0;
   13216     p->zDbFilename = 0;
   13217     sqlite3_free(p->zFreeOnClose);
   13218     p->zFreeOnClose = 0;
   13219     p->openMode = SHELL_OPEN_UNSPEC;
   13220     /* Check for command-line arguments */
   13221     for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
   13222       const char *z = azArg[iName];
   13223       if( optionMatch(z,"new") ){
   13224         newFlag = 1;
   13225 #ifdef SQLITE_HAVE_ZIP
   13226       }else if( optionMatch(z, "zip") ){
   13227         p->openMode = SHELL_OPEN_ZIPFILE;
   13228 #endif
   13229       }else if( optionMatch(z, "append") ){
   13230         p->openMode = SHELL_OPEN_APPENDVFS;
   13231       }else if( z[0]=='-' ){
   13232         utf8_printf(stderr, "unknown option: %s\n", z);
   13233         rc = 1;
   13234         goto meta_command_exit;
   13235       }
   13236     }
   13237     /* If a filename is specified, try to open it first */
   13238     zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
   13239     if( zNewFilename ){
   13240       if( newFlag ) shellDeleteFile(zNewFilename);
   13241       p->zDbFilename = zNewFilename;
   13242       open_db(p, 1);
   13243       if( p->db==0 ){
   13244         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
   13245         sqlite3_free(zNewFilename);
   13246       }else{
   13247         p->zFreeOnClose = zNewFilename;
   13248       }
   13249     }
   13250     if( p->db==0 ){
   13251       /* As a fall-back open a TEMP database */
   13252       p->zDbFilename = 0;
   13253       open_db(p, 0);
   13254     }
   13255   }else
   13256 
   13257   if( (c=='o'
   13258         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
   13259    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
   13260   ){
   13261     const char *zFile = nArg>=2 ? azArg[1] : "stdout";
   13262     int bTxtMode = 0;
   13263     if( azArg[0][0]=='e' ){
   13264       /* Transform the ".excel" command into ".once -x" */
   13265       nArg = 2;
   13266       azArg[0] = "once";
   13267       zFile = azArg[1] = "-x";
   13268       n = 4;
   13269     }
   13270     if( nArg>2 ){
   13271       utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
   13272       rc = 1;
   13273       goto meta_command_exit;
   13274     }
   13275     if( n>1 && strncmp(azArg[0], "once", n)==0 ){
   13276       if( nArg<2 ){
   13277         raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
   13278         rc = 1;
   13279         goto meta_command_exit;
   13280       }
   13281       p->outCount = 2;
   13282     }else{
   13283       p->outCount = 0;
   13284     }
   13285     output_reset(p);
   13286     if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
   13287     if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
   13288       p->doXdgOpen = 1;
   13289       outputModePush(p);
   13290       if( zFile[1]=='x' ){
   13291         newTempFile(p, "csv");
   13292         p->mode = MODE_Csv;
   13293         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
   13294         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
   13295       }else{
   13296         newTempFile(p, "txt");
   13297         bTxtMode = 1;
   13298       }
   13299       zFile = p->zTempFile;
   13300     }
   13301     if( zFile[0]=='|' ){
   13302 #ifdef SQLITE_OMIT_POPEN
   13303       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
   13304       rc = 1;
   13305       p->out = stdout;
   13306 #else
   13307       p->out = popen(zFile + 1, "w");
   13308       if( p->out==0 ){
   13309         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
   13310         p->out = stdout;
   13311         rc = 1;
   13312       }else{
   13313         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
   13314       }
   13315 #endif
   13316     }else{
   13317       p->out = output_file_open(zFile, bTxtMode);
   13318       if( p->out==0 ){
   13319         if( strcmp(zFile,"off")!=0 ){
   13320           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
   13321         }
   13322         p->out = stdout;
   13323         rc = 1;
   13324       } else {
   13325         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
   13326       }
   13327     }
   13328   }else
   13329 
   13330   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
   13331     int i;
   13332     for(i=1; i<nArg; i++){
   13333       if( i>1 ) raw_printf(p->out, " ");
   13334       utf8_printf(p->out, "%s", azArg[i]);
   13335     }
   13336     raw_printf(p->out, "\n");
   13337   }else
   13338 
   13339   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
   13340     if( nArg >= 2) {
   13341       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
   13342     }
   13343     if( nArg >= 3) {
   13344       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
   13345     }
   13346   }else
   13347 
   13348   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
   13349     rc = 2;
   13350   }else
   13351 
   13352   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
   13353     FILE *alt;
   13354     if( nArg!=2 ){
   13355       raw_printf(stderr, "Usage: .read FILE\n");
   13356       rc = 1;
   13357       goto meta_command_exit;
   13358     }
   13359     alt = fopen(azArg[1], "rb");
   13360     if( alt==0 ){
   13361       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
   13362       rc = 1;
   13363     }else{
   13364       rc = process_input(p, alt);
   13365       fclose(alt);
   13366     }
   13367   }else
   13368 
   13369   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
   13370     const char *zSrcFile;
   13371     const char *zDb;
   13372     sqlite3 *pSrc;
   13373     sqlite3_backup *pBackup;
   13374     int nTimeout = 0;
   13375 
   13376     if( nArg==2 ){
   13377       zSrcFile = azArg[1];
   13378       zDb = "main";
   13379     }else if( nArg==3 ){
   13380       zSrcFile = azArg[2];
   13381       zDb = azArg[1];
   13382     }else{
   13383       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
   13384       rc = 1;
   13385       goto meta_command_exit;
   13386     }
   13387     rc = sqlite3_open(zSrcFile, &pSrc);
   13388     if( rc!=SQLITE_OK ){
   13389       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
   13390       sqlite3_close(pSrc);
   13391       return 1;
   13392     }
   13393     open_db(p, 0);
   13394     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
   13395     if( pBackup==0 ){
   13396       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
   13397       sqlite3_close(pSrc);
   13398       return 1;
   13399     }
   13400     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
   13401           || rc==SQLITE_BUSY  ){
   13402       if( rc==SQLITE_BUSY ){
   13403         if( nTimeout++ >= 3 ) break;
   13404         sqlite3_sleep(100);
   13405       }
   13406     }
   13407     sqlite3_backup_finish(pBackup);
   13408     if( rc==SQLITE_DONE ){
   13409       rc = 0;
   13410     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
   13411       raw_printf(stderr, "Error: source database is busy\n");
   13412       rc = 1;
   13413     }else{
   13414       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
   13415       rc = 1;
   13416     }
   13417     sqlite3_close(pSrc);
   13418   }else
   13419 
   13420 
   13421   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
   13422     if( nArg==2 ){
   13423       p->scanstatsOn = booleanValue(azArg[1]);
   13424 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
   13425       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
   13426 #endif
   13427     }else{
   13428       raw_printf(stderr, "Usage: .scanstats on|off\n");
   13429       rc = 1;
   13430     }
   13431   }else
   13432 
   13433   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
   13434     ShellText sSelect;
   13435     ShellState data;
   13436     char *zErrMsg = 0;
   13437     const char *zDiv = "(";
   13438     const char *zName = 0;
   13439     int iSchema = 0;
   13440     int bDebug = 0;
   13441     int ii;
   13442 
   13443     open_db(p, 0);
   13444     memcpy(&data, p, sizeof(data));
   13445     data.showHeader = 0;
   13446     data.cMode = data.mode = MODE_Semi;
   13447     initText(&sSelect);
   13448     for(ii=1; ii<nArg; ii++){
   13449       if( optionMatch(azArg[ii],"indent") ){
   13450         data.cMode = data.mode = MODE_Pretty;
   13451       }else if( optionMatch(azArg[ii],"debug") ){
   13452         bDebug = 1;
   13453       }else if( zName==0 ){
   13454         zName = azArg[ii];
   13455       }else{
   13456         raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
   13457         rc = 1;
   13458         goto meta_command_exit;
   13459       }
   13460     }
   13461     if( zName!=0 ){
   13462       int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
   13463       if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
   13464         char *new_argv[2], *new_colv[2];
   13465         new_argv[0] = sqlite3_mprintf(
   13466                       "CREATE TABLE %s (\n"
   13467                       "  type text,\n"
   13468                       "  name text,\n"
   13469                       "  tbl_name text,\n"
   13470                       "  rootpage integer,\n"
   13471                       "  sql text\n"
   13472                       ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
   13473         new_argv[1] = 0;
   13474         new_colv[0] = "sql";
   13475         new_colv[1] = 0;
   13476         callback(&data, 1, new_argv, new_colv);
   13477         sqlite3_free(new_argv[0]);
   13478       }
   13479     }
   13480     if( zDiv ){
   13481       sqlite3_stmt *pStmt = 0;
   13482       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
   13483                               -1, &pStmt, 0);
   13484       if( rc ){
   13485         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
   13486         sqlite3_finalize(pStmt);
   13487         rc = 1;
   13488         goto meta_command_exit;
   13489       }
   13490       appendText(&sSelect, "SELECT sql FROM", 0);
   13491       iSchema = 0;
   13492       while( sqlite3_step(pStmt)==SQLITE_ROW ){
   13493         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
   13494         char zScNum[30];
   13495         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
   13496         appendText(&sSelect, zDiv, 0);
   13497         zDiv = " UNION ALL ";
   13498         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
   13499         if( sqlite3_stricmp(zDb, "main")!=0 ){
   13500           appendText(&sSelect, zDb, '"');
   13501         }else{
   13502           appendText(&sSelect, "NULL", 0);
   13503         }
   13504         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
   13505         appendText(&sSelect, zScNum, 0);
   13506         appendText(&sSelect, " AS snum, ", 0);
   13507         appendText(&sSelect, zDb, '\'');
   13508         appendText(&sSelect, " AS sname FROM ", 0);
   13509         appendText(&sSelect, zDb, '"');
   13510         appendText(&sSelect, ".sqlite_master", 0);
   13511       }
   13512       sqlite3_finalize(pStmt);
   13513 #ifdef SQLITE_INTROSPECTION_PRAGMAS
   13514       if( zName ){
   13515         appendText(&sSelect,
   13516            " UNION ALL SELECT shell_module_schema(name),"
   13517            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
   13518       }
   13519 #endif
   13520       appendText(&sSelect, ") WHERE ", 0);
   13521       if( zName ){
   13522         char *zQarg = sqlite3_mprintf("%Q", zName);
   13523         if( strchr(zName, '.') ){
   13524           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
   13525         }else{
   13526           appendText(&sSelect, "lower(tbl_name)", 0);
   13527         }
   13528         appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
   13529         appendText(&sSelect, zQarg, 0);
   13530         appendText(&sSelect, " AND ", 0);
   13531         sqlite3_free(zQarg);
   13532       }
   13533       appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
   13534                            " ORDER BY snum, rowid", 0);
   13535       if( bDebug ){
   13536         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
   13537       }else{
   13538         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
   13539       }
   13540       freeText(&sSelect);
   13541     }
   13542     if( zErrMsg ){
   13543       utf8_printf(stderr,"Error: %s\n", zErrMsg);
   13544       sqlite3_free(zErrMsg);
   13545       rc = 1;
   13546     }else if( rc != SQLITE_OK ){
   13547       raw_printf(stderr,"Error: querying schema information\n");
   13548       rc = 1;
   13549     }else{
   13550       rc = 0;
   13551     }
   13552   }else
   13553 
   13554 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
   13555   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
   13556     sqlite3SelectTrace = (int)integerValue(azArg[1]);
   13557   }else
   13558 #endif
   13559 
   13560 #if defined(SQLITE_ENABLE_SESSION)
   13561   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
   13562     OpenSession *pSession = &p->aSession[0];
   13563     char **azCmd = &azArg[1];
   13564     int iSes = 0;
   13565     int nCmd = nArg - 1;
   13566     int i;
   13567     if( nArg<=1 ) goto session_syntax_error;
   13568     open_db(p, 0);
   13569     if( nArg>=3 ){
   13570       for(iSes=0; iSes<p->nSession; iSes++){
   13571         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
   13572       }
   13573       if( iSes<p->nSession ){
   13574         pSession = &p->aSession[iSes];
   13575         azCmd++;
   13576         nCmd--;
   13577       }else{
   13578         pSession = &p->aSession[0];
   13579         iSes = 0;
   13580       }
   13581     }
   13582 
   13583     /* .session attach TABLE
   13584     ** Invoke the sqlite3session_attach() interface to attach a particular
   13585     ** table so that it is never filtered.
   13586     */
   13587     if( strcmp(azCmd[0],"attach")==0 ){
   13588       if( nCmd!=2 ) goto session_syntax_error;
   13589       if( pSession->p==0 ){
   13590         session_not_open:
   13591         raw_printf(stderr, "ERROR: No sessions are open\n");
   13592       }else{
   13593         rc = sqlite3session_attach(pSession->p, azCmd[1]);
   13594         if( rc ){
   13595           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
   13596           rc = 0;
   13597         }
   13598       }
   13599     }else
   13600 
   13601     /* .session changeset FILE
   13602     ** .session patchset FILE
   13603     ** Write a changeset or patchset into a file.  The file is overwritten.
   13604     */
   13605     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
   13606       FILE *out = 0;
   13607       if( nCmd!=2 ) goto session_syntax_error;
   13608       if( pSession->p==0 ) goto session_not_open;
   13609       out = fopen(azCmd[1], "wb");
   13610       if( out==0 ){
   13611         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
   13612       }else{
   13613         int szChng;
   13614         void *pChng;
   13615         if( azCmd[0][0]=='c' ){
   13616           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
   13617         }else{
   13618           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
   13619         }
   13620         if( rc ){
   13621           printf("Error: error code %d\n", rc);
   13622           rc = 0;
   13623         }
   13624         if( pChng
   13625           && fwrite(pChng, szChng, 1, out)!=1 ){
   13626           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
   13627                   szChng);
   13628         }
   13629         sqlite3_free(pChng);
   13630         fclose(out);
   13631       }
   13632     }else
   13633 
   13634     /* .session close
   13635     ** Close the identified session
   13636     */
   13637     if( strcmp(azCmd[0], "close")==0 ){
   13638       if( nCmd!=1 ) goto session_syntax_error;
   13639       if( p->nSession ){
   13640         session_close(pSession);
   13641         p->aSession[iSes] = p->aSession[--p->nSession];
   13642       }
   13643     }else
   13644 
   13645     /* .session enable ?BOOLEAN?
   13646     ** Query or set the enable flag
   13647     */
   13648     if( strcmp(azCmd[0], "enable")==0 ){
   13649       int ii;
   13650       if( nCmd>2 ) goto session_syntax_error;
   13651       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
   13652       if( p->nSession ){
   13653         ii = sqlite3session_enable(pSession->p, ii);
   13654         utf8_printf(p->out, "session %s enable flag = %d\n",
   13655                     pSession->zName, ii);
   13656       }
   13657     }else
   13658 
   13659     /* .session filter GLOB ....
   13660     ** Set a list of GLOB patterns of table names to be excluded.
   13661     */
   13662     if( strcmp(azCmd[0], "filter")==0 ){
   13663       int ii, nByte;
   13664       if( nCmd<2 ) goto session_syntax_error;
   13665       if( p->nSession ){
   13666         for(ii=0; ii<pSession->nFilter; ii++){
   13667           sqlite3_free(pSession->azFilter[ii]);
   13668         }
   13669         sqlite3_free(pSession->azFilter);
   13670         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
   13671         pSession->azFilter = sqlite3_malloc( nByte );
   13672         if( pSession->azFilter==0 ){
   13673           raw_printf(stderr, "Error: out or memory\n");
   13674           exit(1);
   13675         }
   13676         for(ii=1; ii<nCmd; ii++){
   13677           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
   13678         }
   13679         pSession->nFilter = ii-1;
   13680       }
   13681     }else
   13682 
   13683     /* .session indirect ?BOOLEAN?
   13684     ** Query or set the indirect flag
   13685     */
   13686     if( strcmp(azCmd[0], "indirect")==0 ){
   13687       int ii;
   13688       if( nCmd>2 ) goto session_syntax_error;
   13689       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
   13690       if( p->nSession ){
   13691         ii = sqlite3session_indirect(pSession->p, ii);
   13692         utf8_printf(p->out, "session %s indirect flag = %d\n",
   13693                     pSession->zName, ii);
   13694       }
   13695     }else
   13696 
   13697     /* .session isempty
   13698     ** Determine if the session is empty
   13699     */
   13700     if( strcmp(azCmd[0], "isempty")==0 ){
   13701       int ii;
   13702       if( nCmd!=1 ) goto session_syntax_error;
   13703       if( p->nSession ){
   13704         ii = sqlite3session_isempty(pSession->p);
   13705         utf8_printf(p->out, "session %s isempty flag = %d\n",
   13706                     pSession->zName, ii);
   13707       }
   13708     }else
   13709 
   13710     /* .session list
   13711     ** List all currently open sessions
   13712     */
   13713     if( strcmp(azCmd[0],"list")==0 ){
   13714       for(i=0; i<p->nSession; i++){
   13715         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
   13716       }
   13717     }else
   13718 
   13719     /* .session open DB NAME
   13720     ** Open a new session called NAME on the attached database DB.
   13721     ** DB is normally "main".
   13722     */
   13723     if( strcmp(azCmd[0],"open")==0 ){
   13724       char *zName;
   13725       if( nCmd!=3 ) goto session_syntax_error;
   13726       zName = azCmd[2];
   13727       if( zName[0]==0 ) goto session_syntax_error;
   13728       for(i=0; i<p->nSession; i++){
   13729         if( strcmp(p->aSession[i].zName,zName)==0 ){
   13730           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
   13731           goto meta_command_exit;
   13732         }
   13733       }
   13734       if( p->nSession>=ArraySize(p->aSession) ){
   13735         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
   13736         goto meta_command_exit;
   13737       }
   13738       pSession = &p->aSession[p->nSession];
   13739       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
   13740       if( rc ){
   13741         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
   13742         rc = 0;
   13743         goto meta_command_exit;
   13744       }
   13745       pSession->nFilter = 0;
   13746       sqlite3session_table_filter(pSession->p, session_filter, pSession);
   13747       p->nSession++;
   13748       pSession->zName = sqlite3_mprintf("%s", zName);
   13749     }else
   13750     /* If no command name matches, show a syntax error */
   13751     session_syntax_error:
   13752     session_help(p);
   13753   }else
   13754 #endif
   13755 
   13756 #ifdef SQLITE_DEBUG
   13757   /* Undocumented commands for internal testing.  Subject to change
   13758   ** without notice. */
   13759   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
   13760     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
   13761       int i, v;
   13762       for(i=1; i<nArg; i++){
   13763         v = booleanValue(azArg[i]);
   13764         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
   13765       }
   13766     }
   13767     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
   13768       int i; sqlite3_int64 v;
   13769       for(i=1; i<nArg; i++){
   13770         char zBuf[200];
   13771         v = integerValue(azArg[i]);
   13772         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
   13773         utf8_printf(p->out, "%s", zBuf);
   13774       }
   13775     }
   13776   }else
   13777 #endif
   13778 
   13779   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
   13780     int bIsInit = 0;         /* True to initialize the SELFTEST table */
   13781     int bVerbose = 0;        /* Verbose output */
   13782     int bSelftestExists;     /* True if SELFTEST already exists */
   13783     int i, k;                /* Loop counters */
   13784     int nTest = 0;           /* Number of tests runs */
   13785     int nErr = 0;            /* Number of errors seen */
   13786     ShellText str;           /* Answer for a query */
   13787     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
   13788 
   13789     open_db(p,0);
   13790     for(i=1; i<nArg; i++){
   13791       const char *z = azArg[i];
   13792       if( z[0]=='-' && z[1]=='-' ) z++;
   13793       if( strcmp(z,"-init")==0 ){
   13794         bIsInit = 1;
   13795       }else
   13796       if( strcmp(z,"-v")==0 ){
   13797         bVerbose++;
   13798       }else
   13799       {
   13800         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
   13801                     azArg[i], azArg[0]);
   13802         raw_printf(stderr, "Should be one of: --init -v\n");
   13803         rc = 1;
   13804         goto meta_command_exit;
   13805       }
   13806     }
   13807     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
   13808            != SQLITE_OK ){
   13809       bSelftestExists = 0;
   13810     }else{
   13811       bSelftestExists = 1;
   13812     }
   13813     if( bIsInit ){
   13814       createSelftestTable(p);
   13815       bSelftestExists = 1;
   13816     }
   13817     initText(&str);
   13818     appendText(&str, "x", 0);
   13819     for(k=bSelftestExists; k>=0; k--){
   13820       if( k==1 ){
   13821         rc = sqlite3_prepare_v2(p->db,
   13822             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
   13823             -1, &pStmt, 0);
   13824       }else{
   13825         rc = sqlite3_prepare_v2(p->db,
   13826           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
   13827           "      (1,'run','PRAGMA integrity_check','ok')",
   13828           -1, &pStmt, 0);
   13829       }
   13830       if( rc ){
   13831         raw_printf(stderr, "Error querying the selftest table\n");
   13832         rc = 1;
   13833         sqlite3_finalize(pStmt);
   13834         goto meta_command_exit;
   13835       }
   13836       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
   13837         int tno = sqlite3_column_int(pStmt, 0);
   13838         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
   13839         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
   13840         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
   13841 
   13842         k = 0;
   13843         if( bVerbose>0 ){
   13844           char *zQuote = sqlite3_mprintf("%q", zSql);
   13845           printf("%d: %s %s\n", tno, zOp, zSql);
   13846           sqlite3_free(zQuote);
   13847         }
   13848         if( strcmp(zOp,"memo")==0 ){
   13849           utf8_printf(p->out, "%s\n", zSql);
   13850         }else
   13851         if( strcmp(zOp,"run")==0 ){
   13852           char *zErrMsg = 0;
   13853           str.n = 0;
   13854           str.z[0] = 0;
   13855           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
   13856           nTest++;
   13857           if( bVerbose ){
   13858             utf8_printf(p->out, "Result: %s\n", str.z);
   13859           }
   13860           if( rc || zErrMsg ){
   13861             nErr++;
   13862             rc = 1;
   13863             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
   13864             sqlite3_free(zErrMsg);
   13865           }else if( strcmp(zAns,str.z)!=0 ){
   13866             nErr++;
   13867             rc = 1;
   13868             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
   13869             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
   13870           }
   13871         }else
   13872         {
   13873           utf8_printf(stderr,
   13874             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
   13875           rc = 1;
   13876           break;
   13877         }
   13878       } /* End loop over rows of content from SELFTEST */
   13879       sqlite3_finalize(pStmt);
   13880     } /* End loop over k */
   13881     freeText(&str);
   13882     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
   13883   }else
   13884 
   13885   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
   13886     if( nArg<2 || nArg>3 ){
   13887       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
   13888       rc = 1;
   13889     }
   13890     if( nArg>=2 ){
   13891       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
   13892                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
   13893     }
   13894     if( nArg>=3 ){
   13895       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
   13896                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
   13897     }
   13898   }else
   13899 
   13900   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
   13901     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
   13902     int i;                   /* Loop counter */
   13903     int bSchema = 0;         /* Also hash the schema */
   13904     int bSeparate = 0;       /* Hash each table separately */
   13905     int iSize = 224;         /* Hash algorithm to use */
   13906     int bDebug = 0;          /* Only show the query that would have run */
   13907     sqlite3_stmt *pStmt;     /* For querying tables names */
   13908     char *zSql;              /* SQL to be run */
   13909     char *zSep;              /* Separator */
   13910     ShellText sSql;          /* Complete SQL for the query to run the hash */
   13911     ShellText sQuery;        /* Set of queries used to read all content */
   13912     open_db(p, 0);
   13913     for(i=1; i<nArg; i++){
   13914       const char *z = azArg[i];
   13915       if( z[0]=='-' ){
   13916         z++;
   13917         if( z[0]=='-' ) z++;
   13918         if( strcmp(z,"schema")==0 ){
   13919           bSchema = 1;
   13920         }else
   13921         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
   13922          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
   13923         ){
   13924           iSize = atoi(&z[5]);
   13925         }else
   13926         if( strcmp(z,"debug")==0 ){
   13927           bDebug = 1;
   13928         }else
   13929         {
   13930           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
   13931                       azArg[i], azArg[0]);
   13932           raw_printf(stderr, "Should be one of: --schema"
   13933                              " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
   13934           rc = 1;
   13935           goto meta_command_exit;
   13936         }
   13937       }else if( zLike ){
   13938         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
   13939         rc = 1;
   13940         goto meta_command_exit;
   13941       }else{
   13942         zLike = z;
   13943         bSeparate = 1;
   13944         if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
   13945       }
   13946     }
   13947     if( bSchema ){
   13948       zSql = "SELECT lower(name) FROM sqlite_master"
   13949              " WHERE type='table' AND coalesce(rootpage,0)>1"
   13950              " UNION ALL SELECT 'sqlite_master'"
   13951              " ORDER BY 1 collate nocase";
   13952     }else{
   13953       zSql = "SELECT lower(name) FROM sqlite_master"
   13954              " WHERE type='table' AND coalesce(rootpage,0)>1"
   13955              " AND name NOT LIKE 'sqlite_%'"
   13956              " ORDER BY 1 collate nocase";
   13957     }
   13958     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   13959     initText(&sQuery);
   13960     initText(&sSql);
   13961     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
   13962     zSep = "VALUES(";
   13963     while( SQLITE_ROW==sqlite3_step(pStmt) ){
   13964       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
   13965       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
   13966       if( strncmp(zTab, "sqlite_",7)!=0 ){
   13967         appendText(&sQuery,"SELECT * FROM ", 0);
   13968         appendText(&sQuery,zTab,'"');
   13969         appendText(&sQuery," NOT INDEXED;", 0);
   13970       }else if( strcmp(zTab, "sqlite_master")==0 ){
   13971         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
   13972                            " ORDER BY name;", 0);
   13973       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
   13974         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
   13975                            " ORDER BY name;", 0);
   13976       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
   13977         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
   13978                            " ORDER BY tbl,idx;", 0);
   13979       }else if( strcmp(zTab, "sqlite_stat3")==0
   13980              || strcmp(zTab, "sqlite_stat4")==0 ){
   13981         appendText(&sQuery, "SELECT * FROM ", 0);
   13982         appendText(&sQuery, zTab, 0);
   13983         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
   13984       }
   13985       appendText(&sSql, zSep, 0);
   13986       appendText(&sSql, sQuery.z, '\'');
   13987       sQuery.n = 0;
   13988       appendText(&sSql, ",", 0);
   13989       appendText(&sSql, zTab, '\'');
   13990       zSep = "),(";
   13991     }
   13992     sqlite3_finalize(pStmt);
   13993     if( bSeparate ){
   13994       zSql = sqlite3_mprintf(
   13995           "%s))"
   13996           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
   13997           "   FROM [sha3sum$query]",
   13998           sSql.z, iSize);
   13999     }else{
   14000       zSql = sqlite3_mprintf(
   14001           "%s))"
   14002           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
   14003           "   FROM [sha3sum$query]",
   14004           sSql.z, iSize);
   14005     }
   14006     freeText(&sQuery);
   14007     freeText(&sSql);
   14008     if( bDebug ){
   14009       utf8_printf(p->out, "%s\n", zSql);
   14010     }else{
   14011       shell_exec(p->db, zSql, shell_callback, p, 0);
   14012     }
   14013     sqlite3_free(zSql);
   14014   }else
   14015 
   14016   if( c=='s'
   14017    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
   14018   ){
   14019     char *zCmd;
   14020     int i, x;
   14021     if( nArg<2 ){
   14022       raw_printf(stderr, "Usage: .system COMMAND\n");
   14023       rc = 1;
   14024       goto meta_command_exit;
   14025     }
   14026     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
   14027     for(i=2; i<nArg; i++){
   14028       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
   14029                              zCmd, azArg[i]);
   14030     }
   14031     x = system(zCmd);
   14032     sqlite3_free(zCmd);
   14033     if( x ) raw_printf(stderr, "System command returns %d\n", x);
   14034   }else
   14035 
   14036   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
   14037     static const char *azBool[] = { "off", "on", "trigger", "full"};
   14038     int i;
   14039     if( nArg!=1 ){
   14040       raw_printf(stderr, "Usage: .show\n");
   14041       rc = 1;
   14042       goto meta_command_exit;
   14043     }
   14044     utf8_printf(p->out, "%12.12s: %s\n","echo",
   14045                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
   14046     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
   14047     utf8_printf(p->out, "%12.12s: %s\n","explain",
   14048          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
   14049     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
   14050     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
   14051     utf8_printf(p->out, "%12.12s: ", "nullvalue");
   14052       output_c_string(p->out, p->nullValue);
   14053       raw_printf(p->out, "\n");
   14054     utf8_printf(p->out,"%12.12s: %s\n","output",
   14055             strlen30(p->outfile) ? p->outfile : "stdout");
   14056     utf8_printf(p->out,"%12.12s: ", "colseparator");
   14057       output_c_string(p->out, p->colSeparator);
   14058       raw_printf(p->out, "\n");
   14059     utf8_printf(p->out,"%12.12s: ", "rowseparator");
   14060       output_c_string(p->out, p->rowSeparator);
   14061       raw_printf(p->out, "\n");
   14062     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
   14063     utf8_printf(p->out, "%12.12s: ", "width");
   14064     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
   14065       raw_printf(p->out, "%d ", p->colWidth[i]);
   14066     }
   14067     raw_printf(p->out, "\n");
   14068     utf8_printf(p->out, "%12.12s: %s\n", "filename",
   14069                 p->zDbFilename ? p->zDbFilename : "");
   14070   }else
   14071 
   14072   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
   14073     if( nArg==2 ){
   14074       p->statsOn = booleanValue(azArg[1]);
   14075     }else if( nArg==1 ){
   14076       display_stats(p->db, p, 0);
   14077     }else{
   14078       raw_printf(stderr, "Usage: .stats ?on|off?\n");
   14079       rc = 1;
   14080     }
   14081   }else
   14082 
   14083   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
   14084    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
   14085                  || strncmp(azArg[0], "indexes", n)==0) )
   14086   ){
   14087     sqlite3_stmt *pStmt;
   14088     char **azResult;
   14089     int nRow, nAlloc;
   14090     int ii;
   14091     ShellText s;
   14092     initText(&s);
   14093     open_db(p, 0);
   14094     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
   14095     if( rc ) return shellDatabaseError(p->db);
   14096 
   14097     if( nArg>2 && c=='i' ){
   14098       /* It is an historical accident that the .indexes command shows an error
   14099       ** when called with the wrong number of arguments whereas the .tables
   14100       ** command does not. */
   14101       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
   14102       rc = 1;
   14103       goto meta_command_exit;
   14104     }
   14105     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
   14106       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
   14107       if( zDbName==0 ) continue;
   14108       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
   14109       if( sqlite3_stricmp(zDbName, "main")==0 ){
   14110         appendText(&s, "SELECT name FROM ", 0);
   14111       }else{
   14112         appendText(&s, "SELECT ", 0);
   14113         appendText(&s, zDbName, '\'');
   14114         appendText(&s, "||'.'||name FROM ", 0);
   14115       }
   14116       appendText(&s, zDbName, '"');
   14117       appendText(&s, ".sqlite_master ", 0);
   14118       if( c=='t' ){
   14119         appendText(&s," WHERE type IN ('table','view')"
   14120                       "   AND name NOT LIKE 'sqlite_%'"
   14121                       "   AND name LIKE ?1", 0);
   14122       }else{
   14123         appendText(&s," WHERE type='index'"
   14124                       "   AND tbl_name LIKE ?1", 0);
   14125       }
   14126     }
   14127     rc = sqlite3_finalize(pStmt);
   14128     appendText(&s, " ORDER BY 1", 0);
   14129     rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
   14130     freeText(&s);
   14131     if( rc ) return shellDatabaseError(p->db);
   14132 
   14133     /* Run the SQL statement prepared by the above block. Store the results
   14134     ** as an array of nul-terminated strings in azResult[].  */
   14135     nRow = nAlloc = 0;
   14136     azResult = 0;
   14137     if( nArg>1 ){
   14138       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
   14139     }else{
   14140       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
   14141     }
   14142     while( sqlite3_step(pStmt)==SQLITE_ROW ){
   14143       if( nRow>=nAlloc ){
   14144         char **azNew;
   14145         int n2 = nAlloc*2 + 10;
   14146         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
   14147         if( azNew==0 ){
   14148           rc = shellNomemError();
   14149           break;
   14150         }
   14151         nAlloc = n2;
   14152         azResult = azNew;
   14153       }
   14154       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
   14155       if( 0==azResult[nRow] ){
   14156         rc = shellNomemError();
   14157         break;
   14158       }
   14159       nRow++;
   14160     }
   14161     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
   14162       rc = shellDatabaseError(p->db);
   14163     }
   14164 
   14165     /* Pretty-print the contents of array azResult[] to the output */
   14166     if( rc==0 && nRow>0 ){
   14167       int len, maxlen = 0;
   14168       int i, j;
   14169       int nPrintCol, nPrintRow;
   14170       for(i=0; i<nRow; i++){
   14171         len = strlen30(azResult[i]);
   14172         if( len>maxlen ) maxlen = len;
   14173       }
   14174       nPrintCol = 80/(maxlen+2);
   14175       if( nPrintCol<1 ) nPrintCol = 1;
   14176       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
   14177       for(i=0; i<nPrintRow; i++){
   14178         for(j=i; j<nRow; j+=nPrintRow){
   14179           char *zSp = j<nPrintRow ? "" : "  ";
   14180           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
   14181                       azResult[j] ? azResult[j]:"");
   14182         }
   14183         raw_printf(p->out, "\n");
   14184       }
   14185     }
   14186 
   14187     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
   14188     sqlite3_free(azResult);
   14189   }else
   14190 
   14191   /* Begin redirecting output to the file "testcase-out.txt" */
   14192   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
   14193     output_reset(p);
   14194     p->out = output_file_open("testcase-out.txt", 0);
   14195     if( p->out==0 ){
   14196       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
   14197     }
   14198     if( nArg>=2 ){
   14199       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
   14200     }else{
   14201       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
   14202     }
   14203   }else
   14204 
   14205 #ifndef SQLITE_UNTESTABLE
   14206   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
   14207     static const struct {
   14208        const char *zCtrlName;   /* Name of a test-control option */
   14209        int ctrlCode;            /* Integer code for that option */
   14210        const char *zUsage;      /* Usage notes */
   14211     } aCtrl[] = {
   14212       { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"            },
   14213       { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"            },
   14214     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""          },*/
   14215     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""                },*/
   14216       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""                   },
   14217     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""                }, */
   14218       { "imposter",           SQLITE_TESTCTRL_IMPOSTER,   "SCHEMA ON/OFF ROOTPAGE"},
   14219 #ifdef SQLITE_N_KEYWORD
   14220       { "iskeyword",          SQLITE_TESTCTRL_ISKEYWORD,     "IDENTIFIER"         },
   14221 #endif
   14222       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"           },
   14223       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"            },
   14224       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"       },
   14225 #ifdef YYCOVERAGE
   14226       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""                 },
   14227 #endif
   14228       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "           },
   14229       { "prng_reset",         SQLITE_TESTCTRL_PRNG_RESET,    ""                   },
   14230       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""                   },
   14231       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""                   },
   14232       { "reserve",            SQLITE_TESTCTRL_RESERVE,       "BYTES-OF-RESERVE"   },
   14233     };
   14234     int testctrl = -1;
   14235     int iCtrl = -1;
   14236     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
   14237     int isOk = 0;
   14238     int i, n2;
   14239     const char *zCmd = 0;
   14240 
   14241     open_db(p, 0);
   14242     zCmd = nArg>=2 ? azArg[1] : "help";
   14243 
   14244     /* The argument can optionally begin with "-" or "--" */
   14245     if( zCmd[0]=='-' && zCmd[1] ){
   14246       zCmd++;
   14247       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
   14248     }
   14249 
   14250     /* --help lists all test-controls */
   14251     if( strcmp(zCmd,"help")==0 ){
   14252       utf8_printf(p->out, "Available test-controls:\n");
   14253       for(i=0; i<ArraySize(aCtrl); i++){
   14254         utf8_printf(p->out, "  .testctrl %s %s\n",
   14255                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
   14256       }
   14257       rc = 1;
   14258       goto meta_command_exit;
   14259     }
   14260 
   14261     /* convert testctrl text option to value. allow any unique prefix
   14262     ** of the option name, or a numerical value. */
   14263     n2 = strlen30(zCmd);
   14264     for(i=0; i<ArraySize(aCtrl); i++){
   14265       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
   14266         if( testctrl<0 ){
   14267           testctrl = aCtrl[i].ctrlCode;
   14268           iCtrl = i;
   14269         }else{
   14270           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
   14271                               "Use \".testctrl --help\" for help\n", zCmd);
   14272           rc = 1;
   14273           goto meta_command_exit;
   14274         }
   14275       }
   14276     }
   14277     if( testctrl<0 ){
   14278       utf8_printf(stderr,"Error: unknown test-control: %s\n"
   14279                          "Use \".testctrl --help\" for help\n", zCmd);
   14280     }else{
   14281       switch(testctrl){
   14282 
   14283         /* sqlite3_test_control(int, db, int) */
   14284         case SQLITE_TESTCTRL_OPTIMIZATIONS:
   14285         case SQLITE_TESTCTRL_RESERVE:
   14286           if( nArg==3 ){
   14287             int opt = (int)strtol(azArg[2], 0, 0);
   14288             rc2 = sqlite3_test_control(testctrl, p->db, opt);
   14289             isOk = 3;
   14290           }
   14291           break;
   14292 
   14293         /* sqlite3_test_control(int) */
   14294         case SQLITE_TESTCTRL_PRNG_SAVE:
   14295         case SQLITE_TESTCTRL_PRNG_RESTORE:
   14296         case SQLITE_TESTCTRL_PRNG_RESET:
   14297         case SQLITE_TESTCTRL_BYTEORDER:
   14298           if( nArg==2 ){
   14299             rc2 = sqlite3_test_control(testctrl);
   14300             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
   14301           }
   14302           break;
   14303 
   14304         /* sqlite3_test_control(int, uint) */
   14305         case SQLITE_TESTCTRL_PENDING_BYTE:
   14306           if( nArg==3 ){
   14307             unsigned int opt = (unsigned int)integerValue(azArg[2]);
   14308             rc2 = sqlite3_test_control(testctrl, opt);
   14309             isOk = 3;
   14310           }
   14311           break;
   14312 
   14313         /* sqlite3_test_control(int, int) */
   14314         case SQLITE_TESTCTRL_ASSERT:
   14315         case SQLITE_TESTCTRL_ALWAYS:
   14316           if( nArg==3 ){
   14317             int opt = booleanValue(azArg[2]);
   14318             rc2 = sqlite3_test_control(testctrl, opt);
   14319             isOk = 1;
   14320           }
   14321           break;
   14322 
   14323         /* sqlite3_test_control(int, int) */
   14324         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
   14325         case SQLITE_TESTCTRL_NEVER_CORRUPT:
   14326           if( nArg==3 ){
   14327             int opt = booleanValue(azArg[2]);
   14328             rc2 = sqlite3_test_control(testctrl, opt);
   14329             isOk = 3;
   14330           }
   14331           break;
   14332 
   14333         /* sqlite3_test_control(int, char *) */
   14334 #ifdef SQLITE_N_KEYWORD
   14335         case SQLITE_TESTCTRL_ISKEYWORD:
   14336           if( nArg==3 ){
   14337             const char *opt = azArg[2];
   14338             rc2 = sqlite3_test_control(testctrl, opt);
   14339             isOk = 1;
   14340           }
   14341           break;
   14342 #endif
   14343 
   14344         case SQLITE_TESTCTRL_IMPOSTER:
   14345           if( nArg==5 ){
   14346             rc2 = sqlite3_test_control(testctrl, p->db,
   14347                           azArg[2],
   14348                           integerValue(azArg[3]),
   14349                           integerValue(azArg[4]));
   14350             isOk = 3;
   14351           }
   14352           break;
   14353 
   14354 #ifdef YYCOVERAGE
   14355         case SQLITE_TESTCTRL_PARSER_COVERAGE:
   14356           if( nArg==2 ){
   14357             sqlite3_test_control(testctrl, p->out);
   14358             isOk = 3;
   14359           }
   14360 #endif
   14361       }
   14362     }
   14363     if( isOk==0 && iCtrl>=0 ){
   14364       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
   14365       rc = 1;
   14366     }else if( isOk==1 ){
   14367       raw_printf(p->out, "%d\n", rc2);
   14368     }else if( isOk==2 ){
   14369       raw_printf(p->out, "0x%08x\n", rc2);
   14370     }
   14371   }else
   14372 #endif /* !defined(SQLITE_UNTESTABLE) */
   14373 
   14374   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
   14375     open_db(p, 0);
   14376     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
   14377   }else
   14378 
   14379   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
   14380     if( nArg==2 ){
   14381       enableTimer = booleanValue(azArg[1]);
   14382       if( enableTimer && !HAS_TIMER ){
   14383         raw_printf(stderr, "Error: timer not available on this system.\n");
   14384         enableTimer = 0;
   14385       }
   14386     }else{
   14387       raw_printf(stderr, "Usage: .timer on|off\n");
   14388       rc = 1;
   14389     }
   14390   }else
   14391 
   14392   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
   14393     open_db(p, 0);
   14394     if( nArg!=2 ){
   14395       raw_printf(stderr, "Usage: .trace FILE|off\n");
   14396       rc = 1;
   14397       goto meta_command_exit;
   14398     }
   14399     output_file_close(p->traceOut);
   14400     p->traceOut = output_file_open(azArg[1], 0);
   14401 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
   14402     if( p->traceOut==0 ){
   14403       sqlite3_trace_v2(p->db, 0, 0, 0);
   14404     }else{
   14405       sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
   14406     }
   14407 #endif
   14408   }else
   14409 
   14410 #if SQLITE_USER_AUTHENTICATION
   14411   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
   14412     if( nArg<2 ){
   14413       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
   14414       rc = 1;
   14415       goto meta_command_exit;
   14416     }
   14417     open_db(p, 0);
   14418     if( strcmp(azArg[1],"login")==0 ){
   14419       if( nArg!=4 ){
   14420         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
   14421         rc = 1;
   14422         goto meta_command_exit;
   14423       }
   14424       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
   14425       if( rc ){
   14426         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
   14427         rc = 1;
   14428       }
   14429     }else if( strcmp(azArg[1],"add")==0 ){
   14430       if( nArg!=5 ){
   14431         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
   14432         rc = 1;
   14433         goto meta_command_exit;
   14434       }
   14435       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
   14436                             booleanValue(azArg[4]));
   14437       if( rc ){
   14438         raw_printf(stderr, "User-Add failed: %d\n", rc);
   14439         rc = 1;
   14440       }
   14441     }else if( strcmp(azArg[1],"edit")==0 ){
   14442       if( nArg!=5 ){
   14443         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
   14444         rc = 1;
   14445         goto meta_command_exit;
   14446       }
   14447       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
   14448                               booleanValue(azArg[4]));
   14449       if( rc ){
   14450         raw_printf(stderr, "User-Edit failed: %d\n", rc);
   14451         rc = 1;
   14452       }
   14453     }else if( strcmp(azArg[1],"delete")==0 ){
   14454       if( nArg!=3 ){
   14455         raw_printf(stderr, "Usage: .user delete USER\n");
   14456         rc = 1;
   14457         goto meta_command_exit;
   14458       }
   14459       rc = sqlite3_user_delete(p->db, azArg[2]);
   14460       if( rc ){
   14461         raw_printf(stderr, "User-Delete failed: %d\n", rc);
   14462         rc = 1;
   14463       }
   14464     }else{
   14465       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
   14466       rc = 1;
   14467       goto meta_command_exit;
   14468     }
   14469   }else
   14470 #endif /* SQLITE_USER_AUTHENTICATION */
   14471 
   14472   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
   14473     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
   14474         sqlite3_libversion(), sqlite3_sourceid());
   14475 #if SQLITE_HAVE_ZLIB
   14476     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
   14477 #endif
   14478 #define CTIMEOPT_VAL_(opt) #opt
   14479 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
   14480 #if defined(__clang__) && defined(__clang_major__)
   14481     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
   14482                     CTIMEOPT_VAL(__clang_minor__) "."
   14483                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
   14484 #elif defined(_MSC_VER)
   14485     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
   14486 #elif defined(__GNUC__) && defined(__VERSION__)
   14487     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
   14488 #endif
   14489   }else
   14490 
   14491   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
   14492     const char *zDbName = nArg==2 ? azArg[1] : "main";
   14493     sqlite3_vfs *pVfs = 0;
   14494     if( p->db ){
   14495       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
   14496       if( pVfs ){
   14497         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
   14498         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
   14499         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
   14500         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
   14501       }
   14502     }
   14503   }else
   14504 
   14505   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
   14506     sqlite3_vfs *pVfs;
   14507     sqlite3_vfs *pCurrent = 0;
   14508     if( p->db ){
   14509       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
   14510     }
   14511     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
   14512       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
   14513            pVfs==pCurrent ? "  <--- CURRENT" : "");
   14514       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
   14515       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
   14516       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
   14517       if( pVfs->pNext ){
   14518         raw_printf(p->out, "-----------------------------------\n");
   14519       }
   14520     }
   14521   }else
   14522 
   14523   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
   14524     const char *zDbName = nArg==2 ? azArg[1] : "main";
   14525     char *zVfsName = 0;
   14526     if( p->db ){
   14527       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
   14528       if( zVfsName ){
   14529         utf8_printf(p->out, "%s\n", zVfsName);
   14530         sqlite3_free(zVfsName);
   14531       }
   14532     }
   14533   }else
   14534 
   14535 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
   14536   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
   14537     sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
   14538   }else
   14539 #endif
   14540 
   14541   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
   14542     int j;
   14543     assert( nArg<=ArraySize(azArg) );
   14544     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
   14545       p->colWidth[j-1] = (int)integerValue(azArg[j]);
   14546     }
   14547   }else
   14548 
   14549   {
   14550     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
   14551       " \"%s\". Enter \".help\" for help\n", azArg[0]);
   14552     rc = 1;
   14553   }
   14554 
   14555 meta_command_exit:
   14556   if( p->outCount ){
   14557     p->outCount--;
   14558     if( p->outCount==0 ) output_reset(p);
   14559   }
   14560   return rc;
   14561 }
   14562 
   14563 /*
   14564 ** Return TRUE if a semicolon occurs anywhere in the first N characters
   14565 ** of string z[].
   14566 */
   14567 static int line_contains_semicolon(const char *z, int N){
   14568   int i;
   14569   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
   14570   return 0;
   14571 }
   14572 
   14573 /*
   14574 ** Test to see if a line consists entirely of whitespace.
   14575 */
   14576 static int _all_whitespace(const char *z){
   14577   for(; *z; z++){
   14578     if( IsSpace(z[0]) ) continue;
   14579     if( *z=='/' && z[1]=='*' ){
   14580       z += 2;
   14581       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
   14582       if( *z==0 ) return 0;
   14583       z++;
   14584       continue;
   14585     }
   14586     if( *z=='-' && z[1]=='-' ){
   14587       z += 2;
   14588       while( *z && *z!='\n' ){ z++; }
   14589       if( *z==0 ) return 1;
   14590       continue;
   14591     }
   14592     return 0;
   14593   }
   14594   return 1;
   14595 }
   14596 
   14597 /*
   14598 ** Return TRUE if the line typed in is an SQL command terminator other
   14599 ** than a semi-colon.  The SQL Server style "go" command is understood
   14600 ** as is the Oracle "/".
   14601 */
   14602 static int line_is_command_terminator(const char *zLine){
   14603   while( IsSpace(zLine[0]) ){ zLine++; };
   14604   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
   14605     return 1;  /* Oracle */
   14606   }
   14607   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
   14608          && _all_whitespace(&zLine[2]) ){
   14609     return 1;  /* SQL Server */
   14610   }
   14611   return 0;
   14612 }
   14613 
   14614 /*
   14615 ** Return true if zSql is a complete SQL statement.  Return false if it
   14616 ** ends in the middle of a string literal or C-style comment.
   14617 */
   14618 static int line_is_complete(char *zSql, int nSql){
   14619   int rc;
   14620   if( zSql==0 ) return 1;
   14621   zSql[nSql] = ';';
   14622   zSql[nSql+1] = 0;
   14623   rc = sqlite3_complete(zSql);
   14624   zSql[nSql] = 0;
   14625   return rc;
   14626 }
   14627 
   14628 /*
   14629 ** Run a single line of SQL
   14630 */
   14631 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
   14632   int rc;
   14633   char *zErrMsg = 0;
   14634 
   14635   open_db(p, 0);
   14636   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
   14637   BEGIN_TIMER;
   14638   rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
   14639   END_TIMER;
   14640   if( rc || zErrMsg ){
   14641     char zPrefix[100];
   14642     if( in!=0 || !stdin_is_interactive ){
   14643       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
   14644                        "Error: near line %d:", startline);
   14645     }else{
   14646       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
   14647     }
   14648     if( zErrMsg!=0 ){
   14649       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
   14650       sqlite3_free(zErrMsg);
   14651       zErrMsg = 0;
   14652     }else{
   14653       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
   14654     }
   14655     return 1;
   14656   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
   14657     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
   14658             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
   14659   }
   14660   return 0;
   14661 }
   14662 
   14663 
   14664 /*
   14665 ** Read input from *in and process it.  If *in==0 then input
   14666 ** is interactive - the user is typing it it.  Otherwise, input
   14667 ** is coming from a file or device.  A prompt is issued and history
   14668 ** is saved only if input is interactive.  An interrupt signal will
   14669 ** cause this routine to exit immediately, unless input is interactive.
   14670 **
   14671 ** Return the number of errors.
   14672 */
   14673 static int process_input(ShellState *p, FILE *in){
   14674   char *zLine = 0;          /* A single input line */
   14675   char *zSql = 0;           /* Accumulated SQL text */
   14676   int nLine;                /* Length of current line */
   14677   int nSql = 0;             /* Bytes of zSql[] used */
   14678   int nAlloc = 0;           /* Allocated zSql[] space */
   14679   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
   14680   int rc;                   /* Error code */
   14681   int errCnt = 0;           /* Number of errors seen */
   14682   int lineno = 0;           /* Current line number */
   14683   int startline = 0;        /* Line number for start of current input */
   14684 
   14685   while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
   14686     fflush(p->out);
   14687     zLine = one_input_line(in, zLine, nSql>0);
   14688     if( zLine==0 ){
   14689       /* End of input */
   14690       if( in==0 && stdin_is_interactive ) printf("\n");
   14691       break;
   14692     }
   14693     if( seenInterrupt ){
   14694       if( in!=0 ) break;
   14695       seenInterrupt = 0;
   14696     }
   14697     lineno++;
   14698     if( nSql==0 && _all_whitespace(zLine) ){
   14699       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
   14700       continue;
   14701     }
   14702     if( zLine && zLine[0]=='.' && nSql==0 ){
   14703       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
   14704       rc = do_meta_command(zLine, p);
   14705       if( rc==2 ){ /* exit requested */
   14706         break;
   14707       }else if( rc ){
   14708         errCnt++;
   14709       }
   14710       continue;
   14711     }
   14712     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
   14713       memcpy(zLine,";",2);
   14714     }
   14715     nLine = strlen30(zLine);
   14716     if( nSql+nLine+2>=nAlloc ){
   14717       nAlloc = nSql+nLine+100;
   14718       zSql = realloc(zSql, nAlloc);
   14719       if( zSql==0 ){
   14720         raw_printf(stderr, "Error: out of memory\n");
   14721         exit(1);
   14722       }
   14723     }
   14724     nSqlPrior = nSql;
   14725     if( nSql==0 ){
   14726       int i;
   14727       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
   14728       assert( nAlloc>0 && zSql!=0 );
   14729       memcpy(zSql, zLine+i, nLine+1-i);
   14730       startline = lineno;
   14731       nSql = nLine-i;
   14732     }else{
   14733       zSql[nSql++] = '\n';
   14734       memcpy(zSql+nSql, zLine, nLine+1);
   14735       nSql += nLine;
   14736     }
   14737     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
   14738                 && sqlite3_complete(zSql) ){
   14739       errCnt += runOneSqlLine(p, zSql, in, startline);
   14740       nSql = 0;
   14741       if( p->outCount ){
   14742         output_reset(p);
   14743         p->outCount = 0;
   14744       }else{
   14745         clearTempFile(p);
   14746       }
   14747     }else if( nSql && _all_whitespace(zSql) ){
   14748       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
   14749       nSql = 0;
   14750     }
   14751   }
   14752   if( nSql && !_all_whitespace(zSql) ){
   14753     runOneSqlLine(p, zSql, in, startline);
   14754   }
   14755   free(zSql);
   14756   free(zLine);
   14757   return errCnt>0;
   14758 }
   14759 
   14760 /*
   14761 ** Return a pathname which is the user's home directory.  A
   14762 ** 0 return indicates an error of some kind.
   14763 */
   14764 static char *find_home_dir(int clearFlag){
   14765   static char *home_dir = NULL;
   14766   if( clearFlag ){
   14767     free(home_dir);
   14768     home_dir = 0;
   14769     return 0;
   14770   }
   14771   if( home_dir ) return home_dir;
   14772 
   14773 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
   14774      && !defined(__RTP__) && !defined(_WRS_KERNEL)
   14775   {
   14776     struct passwd *pwent;
   14777     uid_t uid = getuid();
   14778     if( (pwent=getpwuid(uid)) != NULL) {
   14779       home_dir = pwent->pw_dir;
   14780     }
   14781   }
   14782 #endif
   14783 
   14784 #if defined(_WIN32_WCE)
   14785   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
   14786    */
   14787   home_dir = "/";
   14788 #else
   14789 
   14790 #if defined(_WIN32) || defined(WIN32)
   14791   if (!home_dir) {
   14792     home_dir = getenv("USERPROFILE");
   14793   }
   14794 #endif
   14795 
   14796   if (!home_dir) {
   14797     home_dir = getenv("HOME");
   14798   }
   14799 
   14800 #if defined(_WIN32) || defined(WIN32)
   14801   if (!home_dir) {
   14802     char *zDrive, *zPath;
   14803     int n;
   14804     zDrive = getenv("HOMEDRIVE");
   14805     zPath = getenv("HOMEPATH");
   14806     if( zDrive && zPath ){
   14807       n = strlen30(zDrive) + strlen30(zPath) + 1;
   14808       home_dir = malloc( n );
   14809       if( home_dir==0 ) return 0;
   14810       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
   14811       return home_dir;
   14812     }
   14813     home_dir = "c:\\";
   14814   }
   14815 #endif
   14816 
   14817 #endif /* !_WIN32_WCE */
   14818 
   14819   if( home_dir ){
   14820     int n = strlen30(home_dir) + 1;
   14821     char *z = malloc( n );
   14822     if( z ) memcpy(z, home_dir, n);
   14823     home_dir = z;
   14824   }
   14825 
   14826   return home_dir;
   14827 }
   14828 
   14829 /*
   14830 ** Read input from the file given by sqliterc_override.  Or if that
   14831 ** parameter is NULL, take input from ~/.sqliterc
   14832 **
   14833 ** Returns the number of errors.
   14834 */
   14835 static void process_sqliterc(
   14836   ShellState *p,                  /* Configuration data */
   14837   const char *sqliterc_override   /* Name of config file. NULL to use default */
   14838 ){
   14839   char *home_dir = NULL;
   14840   const char *sqliterc = sqliterc_override;
   14841   char *zBuf = 0;
   14842   FILE *in = NULL;
   14843 
   14844   if (sqliterc == NULL) {
   14845     home_dir = find_home_dir(0);
   14846     if( home_dir==0 ){
   14847       raw_printf(stderr, "-- warning: cannot find home directory;"
   14848                       " cannot read ~/.sqliterc\n");
   14849       return;
   14850     }
   14851     sqlite3_initialize();
   14852     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
   14853     sqliterc = zBuf;
   14854   }
   14855   in = fopen(sqliterc,"rb");
   14856   if( in ){
   14857     if( stdin_is_interactive ){
   14858       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
   14859     }
   14860     process_input(p,in);
   14861     fclose(in);
   14862   }
   14863   sqlite3_free(zBuf);
   14864 }
   14865 
   14866 /*
   14867 ** Show available command line options
   14868 */
   14869 static const char zOptions[] =
   14870   "   -ascii               set output mode to 'ascii'\n"
   14871   "   -bail                stop after hitting an error\n"
   14872   "   -batch               force batch I/O\n"
   14873   "   -column              set output mode to 'column'\n"
   14874   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
   14875   "   -csv                 set output mode to 'csv'\n"
   14876   "   -echo                print commands before execution\n"
   14877   "   -init FILENAME       read/process named file\n"
   14878   "   -[no]header          turn headers on or off\n"
   14879 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   14880   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
   14881 #endif
   14882   "   -help                show this message\n"
   14883   "   -html                set output mode to HTML\n"
   14884   "   -interactive         force interactive I/O\n"
   14885   "   -line                set output mode to 'line'\n"
   14886   "   -list                set output mode to 'list'\n"
   14887   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
   14888   "   -mmap N              default mmap size set to N\n"
   14889 #ifdef SQLITE_ENABLE_MULTIPLEX
   14890   "   -multiplex           enable the multiplexor VFS\n"
   14891 #endif
   14892   "   -newline SEP         set output row separator. Default: '\\n'\n"
   14893   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
   14894   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
   14895   "   -quote               set output mode to 'quote'\n"
   14896   "   -separator SEP       set output column separator. Default: '|'\n"
   14897   "   -stats               print memory stats before each finalize\n"
   14898   "   -version             show SQLite version\n"
   14899   "   -vfs NAME            use NAME as the default VFS\n"
   14900 #ifdef SQLITE_ENABLE_VFSTRACE
   14901   "   -vfstrace            enable tracing of all VFS calls\n"
   14902 #endif
   14903 ;
   14904 static void usage(int showDetail){
   14905   utf8_printf(stderr,
   14906       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
   14907       "FILENAME is the name of an SQLite database. A new database is created\n"
   14908       "if the file does not previously exist.\n", Argv0);
   14909   if( showDetail ){
   14910     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
   14911   }else{
   14912     raw_printf(stderr, "Use the -help option for additional information\n");
   14913   }
   14914   exit(1);
   14915 }
   14916 
   14917 /*
   14918 ** Initialize the state information in data
   14919 */
   14920 static void main_init(ShellState *data) {
   14921   memset(data, 0, sizeof(*data));
   14922   data->normalMode = data->cMode = data->mode = MODE_List;
   14923   data->autoExplain = 1;
   14924   memcpy(data->colSeparator,SEP_Column, 2);
   14925   memcpy(data->rowSeparator,SEP_Row, 2);
   14926   data->showHeader = 0;
   14927   data->shellFlgs = SHFLG_Lookaside;
   14928   sqlite3_config(SQLITE_CONFIG_URI, 1);
   14929   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
   14930   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
   14931   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
   14932   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
   14933 }
   14934 
   14935 /*
   14936 ** Output text to the console in a font that attracts extra attention.
   14937 */
   14938 #ifdef _WIN32
   14939 static void printBold(const char *zText){
   14940   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
   14941   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
   14942   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
   14943   SetConsoleTextAttribute(out,
   14944          FOREGROUND_RED|FOREGROUND_INTENSITY
   14945   );
   14946   printf("%s", zText);
   14947   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
   14948 }
   14949 #else
   14950 static void printBold(const char *zText){
   14951   printf("\033[1m%s\033[0m", zText);
   14952 }
   14953 #endif
   14954 
   14955 /*
   14956 ** Get the argument to an --option.  Throw an error and die if no argument
   14957 ** is available.
   14958 */
   14959 static char *cmdline_option_value(int argc, char **argv, int i){
   14960   if( i==argc ){
   14961     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
   14962             argv[0], argv[argc-1]);
   14963     exit(1);
   14964   }
   14965   return argv[i];
   14966 }
   14967 
   14968 #ifndef SQLITE_SHELL_IS_UTF8
   14969 #  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
   14970 #    define SQLITE_SHELL_IS_UTF8          (0)
   14971 #  else
   14972 #    define SQLITE_SHELL_IS_UTF8          (1)
   14973 #  endif
   14974 #endif
   14975 
   14976 #if SQLITE_SHELL_IS_UTF8
   14977 int SQLITE_CDECL main(int argc, char **argv){
   14978 #else
   14979 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
   14980   char **argv;
   14981 #endif
   14982   char *zErrMsg = 0;
   14983   ShellState data;
   14984   const char *zInitFile = 0;
   14985   int i;
   14986   int rc = 0;
   14987   int warnInmemoryDb = 0;
   14988   int readStdin = 1;
   14989   int nCmd = 0;
   14990   char **azCmd = 0;
   14991 
   14992   setBinaryMode(stdin, 0);
   14993   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
   14994   stdin_is_interactive = isatty(0);
   14995   stdout_is_console = isatty(1);
   14996 
   14997 #if USE_SYSTEM_SQLITE+0!=1
   14998   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
   14999     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
   15000             sqlite3_sourceid(), SQLITE_SOURCE_ID);
   15001     exit(1);
   15002   }
   15003 #endif
   15004   main_init(&data);
   15005 #if !SQLITE_SHELL_IS_UTF8
   15006   sqlite3_initialize();
   15007   argv = sqlite3_malloc64(sizeof(argv[0])*argc);
   15008   if( argv==0 ){
   15009     raw_printf(stderr, "out of memory\n");
   15010     exit(1);
   15011   }
   15012   for(i=0; i<argc; i++){
   15013     argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
   15014     if( argv[i]==0 ){
   15015       raw_printf(stderr, "out of memory\n");
   15016       exit(1);
   15017     }
   15018   }
   15019 #endif
   15020   assert( argc>=1 && argv && argv[0] );
   15021   Argv0 = argv[0];
   15022 
   15023   /* Make sure we have a valid signal handler early, before anything
   15024   ** else is done.
   15025   */
   15026 #ifdef SIGINT
   15027   signal(SIGINT, interrupt_handler);
   15028 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
   15029   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
   15030 #endif
   15031 
   15032 #ifdef SQLITE_SHELL_DBNAME_PROC
   15033   {
   15034     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
   15035     ** of a C-function that will provide the name of the database file.  Use
   15036     ** this compile-time option to embed this shell program in larger
   15037     ** applications. */
   15038     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
   15039     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
   15040     warnInmemoryDb = 0;
   15041   }
   15042 #endif
   15043 
   15044   /* Do an initial pass through the command-line argument to locate
   15045   ** the name of the database file, the name of the initialization file,
   15046   ** the size of the alternative malloc heap,
   15047   ** and the first command to execute.
   15048   */
   15049   for(i=1; i<argc; i++){
   15050     char *z;
   15051     z = argv[i];
   15052     if( z[0]!='-' ){
   15053       if( data.zDbFilename==0 ){
   15054         data.zDbFilename = z;
   15055       }else{
   15056         /* Excesss arguments are interpreted as SQL (or dot-commands) and
   15057         ** mean that nothing is read from stdin */
   15058         readStdin = 0;
   15059         nCmd++;
   15060         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
   15061         if( azCmd==0 ){
   15062           raw_printf(stderr, "out of memory\n");
   15063           exit(1);
   15064         }
   15065         azCmd[nCmd-1] = z;
   15066       }
   15067     }
   15068     if( z[1]=='-' ) z++;
   15069     if( strcmp(z,"-separator")==0
   15070      || strcmp(z,"-nullvalue")==0
   15071      || strcmp(z,"-newline")==0
   15072      || strcmp(z,"-cmd")==0
   15073     ){
   15074       (void)cmdline_option_value(argc, argv, ++i);
   15075     }else if( strcmp(z,"-init")==0 ){
   15076       zInitFile = cmdline_option_value(argc, argv, ++i);
   15077     }else if( strcmp(z,"-batch")==0 ){
   15078       /* Need to check for batch mode here to so we can avoid printing
   15079       ** informational messages (like from process_sqliterc) before
   15080       ** we do the actual processing of arguments later in a second pass.
   15081       */
   15082       stdin_is_interactive = 0;
   15083     }else if( strcmp(z,"-heap")==0 ){
   15084 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   15085       const char *zSize;
   15086       sqlite3_int64 szHeap;
   15087 
   15088       zSize = cmdline_option_value(argc, argv, ++i);
   15089       szHeap = integerValue(zSize);
   15090       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
   15091       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
   15092 #else
   15093       (void)cmdline_option_value(argc, argv, ++i);
   15094 #endif
   15095     }else if( strcmp(z,"-pagecache")==0 ){
   15096       int n, sz;
   15097       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
   15098       if( sz>70000 ) sz = 70000;
   15099       if( sz<0 ) sz = 0;
   15100       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
   15101       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
   15102                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
   15103       data.shellFlgs |= SHFLG_Pagecache;
   15104     }else if( strcmp(z,"-lookaside")==0 ){
   15105       int n, sz;
   15106       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
   15107       if( sz<0 ) sz = 0;
   15108       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
   15109       if( n<0 ) n = 0;
   15110       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
   15111       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
   15112 #ifdef SQLITE_ENABLE_VFSTRACE
   15113     }else if( strcmp(z,"-vfstrace")==0 ){
   15114       extern int vfstrace_register(
   15115          const char *zTraceName,
   15116          const char *zOldVfsName,
   15117          int (*xOut)(const char*,void*),
   15118          void *pOutArg,
   15119          int makeDefault
   15120       );
   15121       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
   15122 #endif
   15123 #ifdef SQLITE_ENABLE_MULTIPLEX
   15124     }else if( strcmp(z,"-multiplex")==0 ){
   15125       extern int sqlite3_multiple_initialize(const char*,int);
   15126       sqlite3_multiplex_initialize(0, 1);
   15127 #endif
   15128     }else if( strcmp(z,"-mmap")==0 ){
   15129       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
   15130       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
   15131     }else if( strcmp(z,"-vfs")==0 ){
   15132       sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
   15133       if( pVfs ){
   15134         sqlite3_vfs_register(pVfs, 1);
   15135       }else{
   15136         utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
   15137         exit(1);
   15138       }
   15139 #ifdef SQLITE_HAVE_ZIP
   15140     }else if( strcmp(z,"-zip")==0 ){
   15141       data.openMode = SHELL_OPEN_ZIPFILE;
   15142 #endif
   15143     }else if( strcmp(z,"-append")==0 ){
   15144       data.openMode = SHELL_OPEN_APPENDVFS;
   15145     }
   15146   }
   15147   if( data.zDbFilename==0 ){
   15148 #ifndef SQLITE_OMIT_MEMORYDB
   15149     data.zDbFilename = ":memory:";
   15150     warnInmemoryDb = argc==1;
   15151 #else
   15152     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
   15153     return 1;
   15154 #endif
   15155   }
   15156   data.out = stdout;
   15157   sqlite3_appendvfs_init(0,0,0);
   15158 
   15159   /* Go ahead and open the database file if it already exists.  If the
   15160   ** file does not exist, delay opening it.  This prevents empty database
   15161   ** files from being created if a user mistypes the database name argument
   15162   ** to the sqlite command-line tool.
   15163   */
   15164   if( access(data.zDbFilename, 0)==0 ){
   15165     open_db(&data, 0);
   15166   }
   15167 
   15168   /* Process the initialization file if there is one.  If no -init option
   15169   ** is given on the command line, look for a file named ~/.sqliterc and
   15170   ** try to process it.
   15171   */
   15172   process_sqliterc(&data,zInitFile);
   15173 
   15174   /* Make a second pass through the command-line argument and set
   15175   ** options.  This second pass is delayed until after the initialization
   15176   ** file is processed so that the command-line arguments will override
   15177   ** settings in the initialization file.
   15178   */
   15179   for(i=1; i<argc; i++){
   15180     char *z = argv[i];
   15181     if( z[0]!='-' ) continue;
   15182     if( z[1]=='-' ){ z++; }
   15183     if( strcmp(z,"-init")==0 ){
   15184       i++;
   15185     }else if( strcmp(z,"-html")==0 ){
   15186       data.mode = MODE_Html;
   15187     }else if( strcmp(z,"-list")==0 ){
   15188       data.mode = MODE_List;
   15189     }else if( strcmp(z,"-quote")==0 ){
   15190       data.mode = MODE_Quote;
   15191     }else if( strcmp(z,"-line")==0 ){
   15192       data.mode = MODE_Line;
   15193     }else if( strcmp(z,"-column")==0 ){
   15194       data.mode = MODE_Column;
   15195     }else if( strcmp(z,"-csv")==0 ){
   15196       data.mode = MODE_Csv;
   15197       memcpy(data.colSeparator,",",2);
   15198 #ifdef SQLITE_HAVE_ZIP
   15199     }else if( strcmp(z,"-zip")==0 ){
   15200       data.openMode = SHELL_OPEN_ZIPFILE;
   15201 #endif
   15202     }else if( strcmp(z,"-append")==0 ){
   15203       data.openMode = SHELL_OPEN_APPENDVFS;
   15204     }else if( strcmp(z,"-ascii")==0 ){
   15205       data.mode = MODE_Ascii;
   15206       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
   15207                        SEP_Unit);
   15208       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
   15209                        SEP_Record);
   15210     }else if( strcmp(z,"-separator")==0 ){
   15211       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
   15212                        "%s",cmdline_option_value(argc,argv,++i));
   15213     }else if( strcmp(z,"-newline")==0 ){
   15214       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
   15215                        "%s",cmdline_option_value(argc,argv,++i));
   15216     }else if( strcmp(z,"-nullvalue")==0 ){
   15217       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
   15218                        "%s",cmdline_option_value(argc,argv,++i));
   15219     }else if( strcmp(z,"-header")==0 ){
   15220       data.showHeader = 1;
   15221     }else if( strcmp(z,"-noheader")==0 ){
   15222       data.showHeader = 0;
   15223     }else if( strcmp(z,"-echo")==0 ){
   15224       ShellSetFlag(&data, SHFLG_Echo);
   15225     }else if( strcmp(z,"-eqp")==0 ){
   15226       data.autoEQP = AUTOEQP_on;
   15227     }else if( strcmp(z,"-eqpfull")==0 ){
   15228       data.autoEQP = AUTOEQP_full;
   15229     }else if( strcmp(z,"-stats")==0 ){
   15230       data.statsOn = 1;
   15231     }else if( strcmp(z,"-scanstats")==0 ){
   15232       data.scanstatsOn = 1;
   15233     }else if( strcmp(z,"-backslash")==0 ){
   15234       /* Undocumented command-line option: -backslash
   15235       ** Causes C-style backslash escapes to be evaluated in SQL statements
   15236       ** prior to sending the SQL into SQLite.  Useful for injecting
   15237       ** crazy bytes in the middle of SQL statements for testing and debugging.
   15238       */
   15239       ShellSetFlag(&data, SHFLG_Backslash);
   15240     }else if( strcmp(z,"-bail")==0 ){
   15241       bail_on_error = 1;
   15242     }else if( strcmp(z,"-version")==0 ){
   15243       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
   15244       return 0;
   15245     }else if( strcmp(z,"-interactive")==0 ){
   15246       stdin_is_interactive = 1;
   15247     }else if( strcmp(z,"-batch")==0 ){
   15248       stdin_is_interactive = 0;
   15249     }else if( strcmp(z,"-heap")==0 ){
   15250       i++;
   15251     }else if( strcmp(z,"-pagecache")==0 ){
   15252       i+=2;
   15253     }else if( strcmp(z,"-lookaside")==0 ){
   15254       i+=2;
   15255     }else if( strcmp(z,"-mmap")==0 ){
   15256       i++;
   15257     }else if( strcmp(z,"-vfs")==0 ){
   15258       i++;
   15259 #ifdef SQLITE_ENABLE_VFSTRACE
   15260     }else if( strcmp(z,"-vfstrace")==0 ){
   15261       i++;
   15262 #endif
   15263 #ifdef SQLITE_ENABLE_MULTIPLEX
   15264     }else if( strcmp(z,"-multiplex")==0 ){
   15265       i++;
   15266 #endif
   15267     }else if( strcmp(z,"-help")==0 ){
   15268       usage(1);
   15269     }else if( strcmp(z,"-cmd")==0 ){
   15270       /* Run commands that follow -cmd first and separately from commands
   15271       ** that simply appear on the command-line.  This seems goofy.  It would
   15272       ** be better if all commands ran in the order that they appear.  But
   15273       ** we retain the goofy behavior for historical compatibility. */
   15274       if( i==argc-1 ) break;
   15275       z = cmdline_option_value(argc,argv,++i);
   15276       if( z[0]=='.' ){
   15277         rc = do_meta_command(z, &data);
   15278         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
   15279       }else{
   15280         open_db(&data, 0);
   15281         rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
   15282         if( zErrMsg!=0 ){
   15283           utf8_printf(stderr,"Error: %s\n", zErrMsg);
   15284           if( bail_on_error ) return rc!=0 ? rc : 1;
   15285         }else if( rc!=0 ){
   15286           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
   15287           if( bail_on_error ) return rc;
   15288         }
   15289       }
   15290     }else{
   15291       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
   15292       raw_printf(stderr,"Use -help for a list of options.\n");
   15293       return 1;
   15294     }
   15295     data.cMode = data.mode;
   15296   }
   15297 
   15298   if( !readStdin ){
   15299     /* Run all arguments that do not begin with '-' as if they were separate
   15300     ** command-line inputs, except for the argToSkip argument which contains
   15301     ** the database filename.
   15302     */
   15303     for(i=0; i<nCmd; i++){
   15304       if( azCmd[i][0]=='.' ){
   15305         rc = do_meta_command(azCmd[i], &data);
   15306         if( rc ) return rc==2 ? 0 : rc;
   15307       }else{
   15308         open_db(&data, 0);
   15309         rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
   15310         if( zErrMsg!=0 ){
   15311           utf8_printf(stderr,"Error: %s\n", zErrMsg);
   15312           return rc!=0 ? rc : 1;
   15313         }else if( rc!=0 ){
   15314           utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
   15315           return rc;
   15316         }
   15317       }
   15318     }
   15319     free(azCmd);
   15320   }else{
   15321     /* Run commands received from standard input
   15322     */
   15323     if( stdin_is_interactive ){
   15324       char *zHome;
   15325       char *zHistory = 0;
   15326       int nHistory;
   15327       printf(
   15328         "SQLite version %s %.19s\n" /*extra-version-info*/
   15329         "Enter \".help\" for usage hints.\n",
   15330         sqlite3_libversion(), sqlite3_sourceid()
   15331       );
   15332       if( warnInmemoryDb ){
   15333         printf("Connected to a ");
   15334         printBold("transient in-memory database");
   15335         printf(".\nUse \".open FILENAME\" to reopen on a "
   15336                "persistent database.\n");
   15337       }
   15338       zHome = find_home_dir(0);
   15339       if( zHome ){
   15340         nHistory = strlen30(zHome) + 20;
   15341         if( (zHistory = malloc(nHistory))!=0 ){
   15342           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
   15343         }
   15344       }
   15345       if( zHistory ){ shell_read_history(zHistory); }
   15346 #if HAVE_READLINE || HAVE_EDITLINE
   15347       rl_attempted_completion_function = readline_completion;
   15348 #elif HAVE_LINENOISE
   15349       linenoiseSetCompletionCallback(linenoise_completion);
   15350 #endif
   15351       rc = process_input(&data, 0);
   15352       if( zHistory ){
   15353         shell_stifle_history(2000);
   15354         shell_write_history(zHistory);
   15355         free(zHistory);
   15356       }
   15357     }else{
   15358       rc = process_input(&data, stdin);
   15359     }
   15360   }
   15361   set_table_name(&data, 0);
   15362   if( data.db ){
   15363     session_close_all(&data);
   15364     sqlite3_close(data.db);
   15365   }
   15366   sqlite3_free(data.zFreeOnClose);
   15367   find_home_dir(1);
   15368   output_reset(&data);
   15369   data.doXdgOpen = 0;
   15370   clearTempFile(&data);
   15371 #if !SQLITE_SHELL_IS_UTF8
   15372   for(i=0; i<argc; i++) sqlite3_free(argv[i]);
   15373   sqlite3_free(argv);
   15374 #endif
   15375   return rc;
   15376 }
   15377