Home | History | Annotate | Line # | Download | only in dist
      1 /*
      2 ** This is the amalgamated source code to the "sqlite3" or "sqlite3.exe"
      3 ** command-line shell (CLI) for SQLite.  This file is automatically
      4 ** generated by the tool/mkshellc.tcl script from the following sources:
      5 **
      6 **   ext/expert/sqlite3expert.c
      7 **   ext/expert/sqlite3expert.h
      8 **   ext/intck/sqlite3intck.c
      9 **   ext/intck/sqlite3intck.h
     10 **   ext/misc/appendvfs.c
     11 **   ext/misc/base64.c
     12 **   ext/misc/base85.c
     13 **   ext/misc/completion.c
     14 **   ext/misc/decimal.c
     15 **   ext/misc/fileio.c
     16 **   ext/misc/ieee754.c
     17 **   ext/misc/memtrace.c
     18 **   ext/misc/pcachetrace.c
     19 **   ext/misc/regexp.c
     20 **   ext/misc/series.c
     21 **   ext/misc/sha1.c
     22 **   ext/misc/shathree.c
     23 **   ext/misc/sqlar.c
     24 **   ext/misc/sqlite3_stdio.c
     25 **   ext/misc/sqlite3_stdio.h
     26 **   ext/misc/stmtrand.c
     27 **   ext/misc/uint.c
     28 **   ext/misc/vfstrace.c
     29 **   ext/misc/windirent.h
     30 **   ext/misc/zipfile.c
     31 **   ext/qrf/qrf.c
     32 **   ext/qrf/qrf.h
     33 **   ext/recover/dbdata.c
     34 **   ext/recover/sqlite3recover.c
     35 **   ext/recover/sqlite3recover.h
     36 **   src/shell.c.in
     37 **
     38 ** To modify this program, get a copy of the canonical SQLite source tree,
     39 ** edit the src/shell.c.in file and/or some of the other files that are
     40 ** listed above, then rerun the command "make shell.c".
     41 */
     42 /************************* Begin src/shell.c.in ******************/
     43 /*
     44 ** 2001 September 15
     45 **
     46 ** The author disclaims copyright to this source code.  In place of
     47 ** a legal notice, here is a blessing:
     48 **
     49 **    May you do good and not evil.
     50 **    May you find forgiveness for yourself and forgive others.
     51 **    May you share freely, never taking more than you give.
     52 **
     53 *************************************************************************
     54 ** This file contains code to implement the "sqlite3" command line
     55 ** utility for accessing SQLite databases.
     56 */
     57 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
     58 /* This needs to come before any includes for MSVC compiler */
     59 #define _CRT_SECURE_NO_WARNINGS
     60 #endif
     61 typedef unsigned int u32;
     62 typedef unsigned short int u16;
     63 
     64 /*
     65 ** Limit input nesting via .read or any other input redirect.
     66 ** It's not too expensive, so a generous allowance can be made.
     67 */
     68 #define MAX_INPUT_NESTING 25
     69 
     70 /*
     71 ** Used to prevent warnings about unused parameters
     72 */
     73 #define UNUSED_PARAMETER(x) (void)(x)
     74 
     75 /*
     76 ** Number of elements in an array
     77 */
     78 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
     79 
     80 /*
     81 ** Optionally #include a user-defined header, whereby compilation options
     82 ** may be set prior to where they take effect, but after platform setup.
     83 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
     84 ** file. Note that this macro has a like effect on sqlite3.c compilation.
     85 */
     86 # define SHELL_STRINGIFY_(f) #f
     87 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
     88 #ifdef SQLITE_CUSTOM_INCLUDE
     89 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
     90 #endif
     91 
     92 /*
     93 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
     94 ** somewhat for use as a WASM module in a web browser. This flag
     95 ** should only be used when building the "fiddle" web application, as
     96 ** the browser-mode build has much different user input requirements
     97 ** and this build mode rewires the user input subsystem to account for
     98 ** that.
     99 */
    100 #if defined(SQLITE_SHELL_FIDDLE)
    101 # undef SQLITE_OMIT_LOAD_EXTENSION
    102 # define SQLITE_OMIT_LOAD_EXTENSION 1
    103 #endif
    104 
    105 /*
    106 ** Warning pragmas copied from msvc.h in the core.
    107 */
    108 #if defined(_MSC_VER)
    109 #pragma warning(disable : 4054)
    110 #pragma warning(disable : 4055)
    111 #pragma warning(disable : 4100)
    112 #pragma warning(disable : 4127)
    113 #pragma warning(disable : 4130)
    114 #pragma warning(disable : 4152)
    115 #pragma warning(disable : 4189)
    116 #pragma warning(disable : 4206)
    117 #pragma warning(disable : 4210)
    118 #pragma warning(disable : 4232)
    119 #pragma warning(disable : 4244)
    120 #pragma warning(disable : 4305)
    121 #pragma warning(disable : 4306)
    122 #pragma warning(disable : 4702)
    123 #pragma warning(disable : 4706)
    124 #endif /* defined(_MSC_VER) */
    125 
    126 /*
    127 ** No support for loadable extensions in VxWorks.
    128 */
    129 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
    130 # define SQLITE_OMIT_LOAD_EXTENSION 1
    131 #endif
    132 
    133 /*
    134 ** Enable large-file support for fopen() and friends on unix.
    135 */
    136 #ifndef SQLITE_DISABLE_LFS
    137 # define _LARGE_FILE       1
    138 # ifndef _FILE_OFFSET_BITS
    139 #   define _FILE_OFFSET_BITS 64
    140 # endif
    141 # define _LARGEFILE_SOURCE 1
    142 #endif
    143 
    144 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
    145 /*
    146 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
    147 ** to expose strdup().
    148 */
    149 # define _POSIX_SOURCE
    150 #endif
    151 
    152 #include <stdlib.h>
    153 #include <string.h>
    154 #include <stdio.h>
    155 #include <assert.h>
    156 #include <math.h>
    157 #include <stdint.h>
    158 #include "sqlite3.h"
    159 typedef sqlite3_int64 i64;
    160 typedef sqlite3_uint64 u64;
    161 typedef unsigned char u8;
    162 #include <ctype.h>
    163 #include <stdarg.h>
    164 #ifndef _WIN32
    165 # include <sys/time.h>
    166 # include <sys/ioctl.h>
    167 #endif
    168 
    169 #if !defined(_WIN32) && !defined(WIN32)
    170 # include <signal.h>
    171 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
    172 #  include <pwd.h>
    173 # endif
    174 #endif
    175 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
    176 # include <unistd.h>
    177 # include <dirent.h>
    178 # define GETPID getpid
    179 # if defined(__MINGW32__)
    180 #  define DIRENT dirent
    181 #  ifndef S_ISLNK
    182 #   define S_ISLNK(mode) (0)
    183 #  endif
    184 # endif
    185 #else
    186 # define GETPID (int)GetCurrentProcessId
    187 #endif
    188 #include <sys/types.h>
    189 #include <sys/stat.h>
    190 
    191 #if HAVE_READLINE
    192 # include <readline/readline.h>
    193 # include <readline/history.h>
    194 #endif
    195 
    196 #if HAVE_EDITLINE
    197 # include <editline/readline.h>
    198 #endif
    199 
    200 #if HAVE_EDITLINE || HAVE_READLINE
    201 
    202 # define shell_add_history(X) add_history(X)
    203 # define shell_read_history(X) read_history(X)
    204 # define shell_write_history(X) write_history(X)
    205 # define shell_stifle_history(X) stifle_history(X)
    206 # define shell_readline(X) readline(X)
    207 
    208 #elif HAVE_LINENOISE
    209 
    210 # include "linenoise.h"
    211 # define shell_add_history(X) linenoiseHistoryAdd(X)
    212 # define shell_read_history(X) linenoiseHistoryLoad(X)
    213 # define shell_write_history(X) linenoiseHistorySave(X)
    214 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
    215 # define shell_readline(X) linenoise(X)
    216 
    217 #else
    218 
    219 # define shell_read_history(X)
    220 # define shell_write_history(X)
    221 # define shell_stifle_history(X)
    222 
    223 # define SHELL_USE_LOCAL_GETLINE 1
    224 #endif
    225 
    226 #ifndef deliberate_fall_through
    227 /* Quiet some compilers about some of our intentional code. */
    228 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
    229 #  define deliberate_fall_through __attribute__((fallthrough));
    230 # else
    231 #  define deliberate_fall_through
    232 # endif
    233 #endif
    234 
    235 #if defined(_WIN32) || defined(WIN32)
    236 #  include <io.h>
    237 #  include <fcntl.h>
    238 #  define isatty(h) _isatty(h)
    239 #  ifndef access
    240 #   define access(f,m) _access((f),(m))
    241 #  endif
    242 #  ifndef unlink
    243 #   define unlink _unlink
    244 #  endif
    245 #  ifndef strdup
    246 #   define strdup _strdup
    247 #  endif
    248 #  undef pclose
    249 #  define pclose _pclose
    250 #else
    251  /* Make sure isatty() has a prototype. */
    252  extern int isatty(int);
    253 
    254 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
    255   /* popen and pclose are not C89 functions and so are
    256   ** sometimes omitted from the <stdio.h> header */
    257    extern FILE *popen(const char*,const char*);
    258    extern int pclose(FILE*);
    259 # else
    260 #  define SQLITE_OMIT_POPEN 1
    261 # endif
    262 #endif
    263 
    264 #if defined(_WIN32_WCE)
    265 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
    266  * thus we always assume that we have a console. That can be
    267  * overridden with the -batch command line option.
    268  */
    269 #define isatty(x) 1
    270 #endif
    271 
    272 /* ctype macros that work with signed characters */
    273 #define IsSpace(X)  isspace((unsigned char)X)
    274 #define IsDigit(X)  isdigit((unsigned char)X)
    275 #define ToLower(X)  (char)tolower((unsigned char)X)
    276 #define IsAlnum(X)  isalnum((unsigned char)X)
    277 #define IsAlpha(X)  isalpha((unsigned char)X)
    278 
    279 #if defined(_WIN32) || defined(WIN32)
    280 #undef WIN32_LEAN_AND_MEAN
    281 #define WIN32_LEAN_AND_MEAN
    282 #include <windows.h>
    283 
    284 /* string conversion routines only needed on Win32 */
    285 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
    286 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
    287 #endif
    288 
    289 /************************* Begin ext/misc/sqlite3_stdio.h ******************/
    290 /*
    291 ** 2024-09-24
    292 **
    293 ** The author disclaims copyright to this source code.  In place of
    294 ** a legal notice, here is a blessing:
    295 **
    296 **    May you do good and not evil.
    297 **    May you find forgiveness for yourself and forgive others.
    298 **    May you share freely, never taking more than you give.
    299 **
    300 *************************************************************************
    301 **
    302 ** This header file contains definitions of interfaces that provide
    303 ** cross-platform I/O for UTF-8 content.
    304 **
    305 ** On most platforms, the interfaces definitions in this file are
    306 ** just #defines.  For example sqlite3_fopen() is a macro that resolves
    307 ** to the standard fopen() in the C-library.
    308 **
    309 ** But Windows does not have a standard C-library, at least not one that
    310 ** can handle UTF-8.  So for windows build, the interfaces resolve to new
    311 ** C-language routines contained in the separate sqlite3_stdio.c source file.
    312 **
    313 ** So on all non-Windows platforms, simply #include this header file and
    314 ** use the interfaces defined herein.  Then to run your application on Windows,
    315 ** also link in the accompanying sqlite3_stdio.c source file when compiling
    316 ** to get compatible interfaces.
    317 */
    318 #ifndef _SQLITE3_STDIO_H_
    319 #define _SQLITE3_STDIO_H_ 1
    320 #ifdef _WIN32
    321 /**** Definitions For Windows ****/
    322 #include <stdio.h>
    323 #include <stdarg.h>
    324 #include <windows.h>
    325 
    326 FILE *sqlite3_fopen(const char *zFilename, const char *zMode);
    327 FILE *sqlite3_popen(const char *zCommand, const char *type);
    328 char *sqlite3_fgets(char *s, int size, FILE *stream);
    329 int sqlite3_fputs(const char *s, FILE *stream);
    330 int sqlite3_fprintf(FILE *stream, const char *format, ...);
    331 int sqlite3_vfprintf(FILE *stream, const char *format, va_list);
    332 void sqlite3_fsetmode(FILE *stream, int mode);
    333 
    334 
    335 #else
    336 /**** Definitions For All Other Platforms ****/
    337 #include <stdio.h>
    338 #define sqlite3_fopen     fopen
    339 #define sqlite3_popen     popen
    340 #define sqlite3_fgets     fgets
    341 #define sqlite3_fputs     fputs
    342 #define sqlite3_fprintf   fprintf
    343 #define sqlite3_vfprintf  vfprintf
    344 #define sqlite3_fsetmode(F,X)   /*no-op*/
    345 
    346 #endif
    347 #endif /* _SQLITE3_STDIO_H_ */
    348 
    349 /************************* End ext/misc/sqlite3_stdio.h ********************/
    350 /************************* Begin ext/misc/sqlite3_stdio.c ******************/
    351 /*
    352 ** 2024-09-24
    353 **
    354 ** The author disclaims copyright to this source code.  In place of
    355 ** a legal notice, here is a blessing:
    356 **
    357 **    May you do good and not evil.
    358 **    May you find forgiveness for yourself and forgive others.
    359 **    May you share freely, never taking more than you give.
    360 **
    361 *************************************************************************
    362 **
    363 ** Implementation of standard I/O interfaces for UTF-8 that are missing
    364 ** on Windows.
    365 */
    366 #ifdef _WIN32  /* This file is a no-op on all platforms except Windows */
    367 #ifndef _SQLITE3_STDIO_H_
    368 /* #include "sqlite3_stdio.h" */
    369 #endif
    370 #undef WIN32_LEAN_AND_MEAN
    371 #define WIN32_LEAN_AND_MEAN
    372 #include <windows.h>
    373 #include <stdlib.h>
    374 #include <string.h>
    375 #include <stdio.h>
    376 #include <assert.h>
    377 /* #include "sqlite3.h" */
    378 #include <ctype.h>
    379 #include <stdarg.h>
    380 #include <io.h>
    381 #include <fcntl.h>
    382 
    383 /*
    384 ** If the SQLITE_U8TEXT_ONLY option is defined, then use O_U8TEXT
    385 ** when appropriate on all output.  (Sometimes use O_BINARY when
    386 ** rendering ASCII text in cases where NL-to-CRLF expansion would
    387 ** not be correct.)
    388 **
    389 ** If the SQLITE_U8TEXT_STDIO option is defined, then use O_U8TEXT
    390 ** when appropriate when writing to stdout or stderr.  Use O_BINARY
    391 ** or O_TEXT (depending on things like the .mode and the .crlf setting
    392 ** in the CLI, or other context clues in other applications) for all
    393 ** other output channels.
    394 **
    395 ** The default behavior, if neither of the above is defined is to
    396 ** use O_U8TEXT when writing to the Windows console (or anything
    397 ** else for which _isatty() returns true) and to use O_BINARY or O_TEXT
    398 ** for all other output channels.
    399 **
    400 ** The SQLITE_USE_W32_FOR_CONSOLE_IO macro is also available.  If
    401 ** defined, it forces the use of Win32 APIs for all console I/O, both
    402 ** input and output.  This is necessary for some non-Microsoft run-times
    403 ** that implement stdio differently from Microsoft/Visual-Studio.
    404 */
    405 #if defined(SQLITE_U8TEXT_ONLY)
    406 # define UseWtextForOutput(fd) 1
    407 # define UseWtextForInput(fd)  1
    408 # define IsConsole(fd)         _isatty(_fileno(fd))
    409 #elif defined(SQLITE_U8TEXT_STDIO)
    410 # define UseWtextForOutput(fd) ((fd)==stdout || (fd)==stderr)
    411 # define UseWtextForInput(fd)  ((fd)==stdin)
    412 # define IsConsole(fd)         _isatty(_fileno(fd))
    413 #else
    414 # define UseWtextForOutput(fd) _isatty(_fileno(fd))
    415 # define UseWtextForInput(fd)  _isatty(_fileno(fd))
    416 # define IsConsole(fd)         1
    417 #endif
    418 
    419 /*
    420 ** Global variables determine if simulated O_BINARY mode is to be
    421 ** used for stdout or other, respectively.  Simulated O_BINARY mode
    422 ** means the mode is usually O_BINARY, but switches to O_U8TEXT for
    423 ** unicode characters U+0080 or greater (any character that has a
    424 ** multi-byte representation in UTF-8).  This is the only way we
    425 ** have found to render Unicode characters on a Windows console while
    426 ** at the same time avoiding undesirable \n to \r\n translation.
    427 */
    428 static int simBinaryStdout = 0;
    429 static int simBinaryOther = 0;
    430 
    431 
    432 /*
    433 ** Determine if simulated binary mode should be used for output to fd
    434 */
    435 static int UseBinaryWText(FILE *fd){
    436   if( fd==stdout || fd==stderr ){
    437     return simBinaryStdout;
    438   }else{
    439     return simBinaryOther;
    440   }
    441 }
    442 
    443 
    444 /*
    445 ** Work-alike for the fopen() routine from the standard C library.
    446 */
    447 FILE *sqlite3_fopen(const char *zFilename, const char *zMode){
    448   FILE *fp = 0;
    449   wchar_t *b1, *b2;
    450   int sz1, sz2;
    451 
    452   sz1 = (int)strlen(zFilename);
    453   sz2 = (int)strlen(zMode);
    454   b1 = sqlite3_malloc64( (sz1+1)*sizeof(b1[0]) );
    455   b2 = sqlite3_malloc64( (sz2+1)*sizeof(b1[0]) );
    456   if( b1 && b2 ){
    457     sz1 = MultiByteToWideChar(CP_UTF8, 0, zFilename, sz1, b1, sz1);
    458     b1[sz1] = 0;
    459     sz2 = MultiByteToWideChar(CP_UTF8, 0, zMode, sz2, b2, sz2);
    460     b2[sz2] = 0;
    461     fp = _wfopen(b1, b2);
    462   }
    463   sqlite3_free(b1);
    464   sqlite3_free(b2);
    465   simBinaryOther = 0;
    466   return fp;
    467 }
    468 
    469 
    470 /*
    471 ** Work-alike for the popen() routine from the standard C library.
    472 */
    473 FILE *sqlite3_popen(const char *zCommand, const char *zMode){
    474   FILE *fp = 0;
    475   wchar_t *b1, *b2;
    476   int sz1, sz2;
    477 
    478   sz1 = (int)strlen(zCommand);
    479   sz2 = (int)strlen(zMode);
    480   b1 = sqlite3_malloc64( (sz1+1)*sizeof(b1[0]) );
    481   b2 = sqlite3_malloc64( (sz2+1)*sizeof(b1[0]) );
    482   if( b1 && b2 ){
    483     sz1 = MultiByteToWideChar(CP_UTF8, 0, zCommand, sz1, b1, sz1);
    484     b1[sz1] = 0;
    485     sz2 = MultiByteToWideChar(CP_UTF8, 0, zMode, sz2, b2, sz2);
    486     b2[sz2] = 0;
    487     fp = _wpopen(b1, b2);
    488   }
    489   sqlite3_free(b1);
    490   sqlite3_free(b2);
    491   return fp;
    492 }
    493 
    494 /*
    495 ** Work-alike for fgets() from the standard C library.
    496 */
    497 char *sqlite3_fgets(char *buf, int sz, FILE *in){
    498   if( UseWtextForInput(in) ){
    499     /* When reading from the command-prompt in Windows, it is necessary
    500     ** to use _O_WTEXT input mode to read UTF-16 characters, then translate
    501     ** that into UTF-8.  Otherwise, non-ASCII characters all get translated
    502     ** into '?'.
    503     */
    504     wchar_t *b1 = sqlite3_malloc64( sz*sizeof(wchar_t) );
    505     if( b1==0 ) return 0;
    506 #ifdef SQLITE_USE_W32_FOR_CONSOLE_IO
    507     DWORD nRead = 0;
    508     if( IsConsole(in)
    509      && ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), b1, sz-1, &nRead, 0)
    510     ){
    511       b1[nRead] = 0;
    512     }else
    513 #endif
    514     {
    515       _setmode(_fileno(in), IsConsole(in) ? _O_WTEXT : _O_U8TEXT);
    516       if( fgetws(b1, sz/4, in)==0 ){
    517         sqlite3_free(b1);
    518         return 0;
    519       }
    520     }
    521     WideCharToMultiByte(CP_UTF8, 0, b1, -1, buf, sz, 0, 0);
    522     sqlite3_free(b1);
    523     return buf;
    524   }else{
    525     /* Reading from a file or other input source, just read bytes without
    526     ** any translation. */
    527     return fgets(buf, sz, in);
    528   }
    529 }
    530 
    531 /*
    532 ** Send ASCII text as O_BINARY.  But for Unicode characters U+0080 and
    533 ** greater, switch to O_U8TEXT.
    534 */
    535 static void piecemealOutput(wchar_t *b1, int sz, FILE *out){
    536   int i;
    537   wchar_t c;
    538   while( sz>0 ){
    539     for(i=0; i<sz && b1[i]>=0x80; i++){}
    540     if( i>0 ){
    541       c = b1[i];
    542       b1[i] = 0;
    543       fflush(out);
    544       _setmode(_fileno(out), _O_U8TEXT);
    545       fputws(b1, out);
    546       fflush(out);
    547       b1 += i;
    548       b1[0] = c;
    549       sz -= i;
    550     }else{
    551       fflush(out);
    552       _setmode(_fileno(out), _O_TEXT);
    553       _setmode(_fileno(out), _O_BINARY);
    554       fwrite(&b1[0], 1, 1, out);
    555       for(i=1; i<sz && b1[i]<0x80; i++){
    556         fwrite(&b1[i], 1, 1, out);
    557       }
    558       fflush(out);
    559       _setmode(_fileno(out), _O_U8TEXT);
    560       b1 += i;
    561       sz -= i;
    562     }
    563   }
    564 }
    565 
    566 /*
    567 ** Work-alike for fputs() from the standard C library.
    568 */
    569 int sqlite3_fputs(const char *z, FILE *out){
    570   if( !UseWtextForOutput(out) ){
    571     /* Writing to a file or other destination, just write bytes without
    572     ** any translation. */
    573     return fputs(z, out);
    574   }else{
    575     /* One must use UTF16 in order to get unicode support when writing
    576     ** to the console on Windows.
    577     */
    578     int sz = (int)strlen(z);
    579     wchar_t *b1 = sqlite3_malloc64( (sz+1)*sizeof(wchar_t) );
    580     if( b1==0 ) return 0;
    581     sz = MultiByteToWideChar(CP_UTF8, 0, z, sz, b1, sz);
    582     b1[sz] = 0;
    583 
    584 #ifdef SQLITE_USE_W32_FOR_CONSOLE_IO
    585     DWORD nWr = 0;
    586     if( IsConsole(out)
    587       && WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),b1,sz,&nWr,0)
    588     ){
    589       /* If writing to the console, then the WriteConsoleW() is all we
    590       ** need to do. */
    591     }else
    592 #endif
    593     {
    594       /* As long as SQLITE_USE_W32_FOR_CONSOLE_IO is not defined, or for
    595       ** non-console I/O even if that macro is defined, write using the
    596       ** standard library. */
    597       _setmode(_fileno(out), _O_U8TEXT);
    598       if( UseBinaryWText(out) ){
    599         piecemealOutput(b1, sz, out);
    600       }else{
    601         fputws(b1, out);
    602       }
    603     }
    604     sqlite3_free(b1);
    605     return 0;
    606   }
    607 }
    608 
    609 
    610 /*
    611 ** Work-alikes for fprintf() and vfprintf() from the standard C library.
    612 */
    613 int sqlite3_fprintf(FILE *out, const char *zFormat, ...){
    614   int rc;
    615   if( UseWtextForOutput(out) ){
    616     /* When writing to the command-prompt in Windows, it is necessary
    617     ** to use _O_WTEXT input mode and write UTF-16 characters.
    618     */
    619     char *z;
    620     va_list ap;
    621 
    622     va_start(ap, zFormat);
    623     z = sqlite3_vmprintf(zFormat, ap);
    624     va_end(ap);
    625     sqlite3_fputs(z, out);
    626     rc = (int)strlen(z);
    627     sqlite3_free(z);
    628   }else{
    629     /* Writing to a file or other destination, just write bytes without
    630     ** any translation. */
    631     va_list ap;
    632     va_start(ap, zFormat);
    633     rc = vfprintf(out, zFormat, ap);
    634     va_end(ap);
    635   }
    636   return rc;
    637 }
    638 int sqlite3_vfprintf(FILE *out, const char *zFormat, va_list ap){
    639   int rc;
    640   if( UseWtextForOutput(out) ){
    641     /* When writing to the command-prompt in Windows, it is necessary
    642     ** to use _O_WTEXT input mode and write UTF-16 characters.
    643     */
    644     char *z;
    645     z = sqlite3_vmprintf(zFormat, ap);
    646     sqlite3_fputs(z, out);
    647     rc = (int)strlen(z);
    648     sqlite3_free(z);
    649   }else{
    650     /* Writing to a file or other destination, just write bytes without
    651     ** any translation. */
    652     rc = vfprintf(out, zFormat, ap);
    653   }
    654   return rc;
    655 }
    656 
    657 /*
    658 ** Set the mode for an output stream.  mode argument is typically _O_BINARY or
    659 ** _O_TEXT.
    660 */
    661 void sqlite3_fsetmode(FILE *fp, int mode){
    662   if( !UseWtextForOutput(fp) ){
    663     fflush(fp);
    664     _setmode(_fileno(fp), mode);
    665   }else if( fp==stdout || fp==stderr ){
    666     simBinaryStdout = (mode==_O_BINARY);
    667   }else{
    668     simBinaryOther = (mode==_O_BINARY);
    669   }
    670 }
    671 
    672 #endif /* defined(_WIN32) */
    673 
    674 /************************* End ext/misc/sqlite3_stdio.c ********************/
    675 /************************* Begin ext/qrf/qrf.h ******************/
    676 /*
    677 ** 2025-10-20
    678 **
    679 ** The author disclaims copyright to this source code.  In place of
    680 ** a legal notice, here is a blessing:
    681 **
    682 **    May you do good and not evil.
    683 **    May you find forgiveness for yourself and forgive others.
    684 **    May you share freely, never taking more than you give.
    685 **
    686 *************************************************************************
    687 ** Header file for the Query Result-Format or "qrf" utility library for
    688 ** SQLite.  See the README.md documentation for additional information.
    689 */
    690 #ifndef SQLITE_QRF_H
    691 #define SQLITE_QRF_H
    692 #ifdef __cplusplus
    693 extern "C" {
    694 #endif
    695 #include <stdlib.h>
    696 /* #include "sqlite3.h" */
    697 
    698 /*
    699 ** Specification used by clients to define the output format they want
    700 */
    701 typedef struct sqlite3_qrf_spec sqlite3_qrf_spec;
    702 struct sqlite3_qrf_spec {
    703   unsigned char iVersion;     /* Version number of this structure */
    704   unsigned char eStyle;       /* Formatting style.  "box", "csv", etc... */
    705   unsigned char eEsc;         /* How to escape control characters in text */
    706   unsigned char eText;        /* Quoting style for text */
    707   unsigned char eTitle;       /* Quating style for the text of column names */
    708   unsigned char eBlob;        /* Quoting style for BLOBs */
    709   unsigned char bTitles;      /* True to show column names */
    710   unsigned char bWordWrap;    /* Try to wrap on word boundaries */
    711   unsigned char bTextJsonb;   /* Render JSONB blobs as JSON text */
    712   unsigned char eDfltAlign;   /* Default alignment, no covered by aAlignment */
    713   unsigned char eTitleAlign;  /* Alignment for column headers */
    714   unsigned char bSplitColumn; /* Wrap single-column output into many columns */
    715   unsigned char bBorder;      /* Show outer border in Box and Table styles */
    716   short int nWrap;            /* Wrap columns wider than this */
    717   short int nScreenWidth;     /* Maximum overall table width */
    718   short int nLineLimit;       /* Maximum number of lines for any row */
    719   short int nTitleLimit;      /* Maximum number of characters in a title */
    720   unsigned int nMultiInsert;  /* Add rows to one INSERT until size exceeds */
    721   int nCharLimit;             /* Maximum number of characters in a cell */
    722   int nWidth;                 /* Number of entries in aWidth[] */
    723   int nAlign;                 /* Number of entries in aAlignment[] */
    724   short int *aWidth;          /* Column widths */
    725   unsigned char *aAlign;      /* Column alignments */
    726   char *zColumnSep;           /* Alternative column separator */
    727   char *zRowSep;              /* Alternative row separator */
    728   char *zTableName;           /* Output table name */
    729   char *zNull;                /* Rendering of NULL */
    730   char *(*xRender)(void*,sqlite3_value*);           /* Render a value */
    731   int (*xWrite)(void*,const char*,sqlite3_int64);   /* Write output */
    732   void *pRenderArg;           /* First argument to the xRender callback */
    733   void *pWriteArg;            /* First argument to the xWrite callback */
    734   char **pzOutput;            /* Storage location for output string */
    735   /* Additional fields may be added in the future */
    736 };
    737 
    738 /*
    739 ** Interfaces
    740 */
    741 int sqlite3_format_query_result(
    742   sqlite3_stmt *pStmt,             /* SQL statement to run */
    743   const sqlite3_qrf_spec *pSpec,   /* Result format specification */
    744   char **pzErr                     /* OUT: Write error message here */
    745 );
    746 
    747 /*
    748 ** Range of values for sqlite3_qrf_spec.aWidth[] entries and for
    749 ** sqlite3_qrf_spec.mxColWidth and .nScreenWidth
    750 */
    751 #define QRF_MAX_WIDTH    10000
    752 #define QRF_MIN_WIDTH    0
    753 
    754 /*
    755 ** Output styles:
    756 */
    757 #define QRF_STYLE_Auto      0 /* Choose a style automatically */
    758 #define QRF_STYLE_Box       1 /* Unicode box-drawing characters */
    759 #define QRF_STYLE_Column    2 /* One record per line in neat columns */
    760 #define QRF_STYLE_Count     3 /* Output only a count of the rows of output */
    761 #define QRF_STYLE_Csv       4 /* Comma-separated-value */
    762 #define QRF_STYLE_Eqp       5 /* Format EXPLAIN QUERY PLAN output */
    763 #define QRF_STYLE_Explain   6 /* EXPLAIN output */
    764 #define QRF_STYLE_Html      7 /* Generate an XHTML table */
    765 #define QRF_STYLE_Insert    8 /* Generate SQL "insert" statements */
    766 #define QRF_STYLE_Json      9 /* Output is a list of JSON objects */
    767 #define QRF_STYLE_JObject  10 /* Independent JSON objects for each row */
    768 #define QRF_STYLE_Line     11 /* One column per line. */
    769 #define QRF_STYLE_List     12 /* One record per line with a separator */
    770 #define QRF_STYLE_Markdown 13 /* Markdown formatting */
    771 #define QRF_STYLE_Off      14 /* No query output shown */
    772 #define QRF_STYLE_Quote    15 /* SQL-quoted, comma-separated */
    773 #define QRF_STYLE_Stats    16 /* EQP-like output but with performance stats */
    774 #define QRF_STYLE_StatsEst 17 /* EQP-like output with planner estimates */
    775 #define QRF_STYLE_StatsVm  18 /* EXPLAIN-like output with performance stats */
    776 #define QRF_STYLE_Table    19 /* MySQL-style table formatting */
    777 
    778 /*
    779 ** Quoting styles for text.
    780 ** Allowed values for sqlite3_qrf_spec.eText
    781 */
    782 #define QRF_TEXT_Auto    0 /* Choose text encoding automatically */
    783 #define QRF_TEXT_Plain   1 /* Literal text */
    784 #define QRF_TEXT_Sql     2 /* Quote as an SQL literal */
    785 #define QRF_TEXT_Csv     3 /* CSV-style quoting */
    786 #define QRF_TEXT_Html    4 /* HTML-style quoting */
    787 #define QRF_TEXT_Tcl     5 /* C/Tcl quoting */
    788 #define QRF_TEXT_Json    6 /* JSON quoting */
    789 #define QRF_TEXT_Relaxed 7 /* Relaxed SQL quoting */
    790 
    791 /*
    792 ** Quoting styles for BLOBs
    793 ** Allowed values for sqlite3_qrf_spec.eBlob
    794 */
    795 #define QRF_BLOB_Auto    0 /* Determine BLOB quoting using eText */
    796 #define QRF_BLOB_Text    1 /* Display content exactly as it is */
    797 #define QRF_BLOB_Sql     2 /* Quote as an SQL literal */
    798 #define QRF_BLOB_Hex     3 /* Hexadecimal representation */
    799 #define QRF_BLOB_Tcl     4 /* "\000" notation */
    800 #define QRF_BLOB_Json    5 /* A JSON string */
    801 #define QRF_BLOB_Size    6 /* Display the blob size only */
    802 
    803 /*
    804 ** Control-character escape modes.
    805 ** Allowed values for sqlite3_qrf_spec.eEsc
    806 */
    807 #define QRF_ESC_Auto    0 /* Choose the ctrl-char escape automatically */
    808 #define QRF_ESC_Off     1 /* Do not escape control characters */
    809 #define QRF_ESC_Ascii   2 /* Unix-style escapes.  Ex: U+0007 shows ^G */
    810 #define QRF_ESC_Symbol  3 /* Unicode escapes. Ex: U+0007 shows U+2407 */
    811 
    812 /*
    813 ** Allowed values for "boolean" fields, such as "bColumnNames", "bWordWrap",
    814 ** and "bTextJsonb".  There is an extra "auto" variants so these are actually
    815 ** tri-state settings, not booleans.
    816 */
    817 #define QRF_SW_Auto     0 /* Let QRF choose the best value */
    818 #define QRF_SW_Off      1 /* This setting is forced off */
    819 #define QRF_SW_On       2 /* This setting is forced on */
    820 #define QRF_Auto        0 /* Alternate spelling for QRF_*_Auto */
    821 #define QRF_No          1 /* Alternate spelling for QRF_SW_Off */
    822 #define QRF_Yes         2 /* Alternate spelling for QRF_SW_On */
    823 
    824 /*
    825 ** Possible alignment values alignment settings
    826 **
    827 **                             Horizontal   Vertial
    828 **                             ----------   --------  */
    829 #define QRF_ALIGN_Auto    0 /*   auto        auto     */
    830 #define QRF_ALIGN_Left    1 /*   left        auto     */
    831 #define QRF_ALIGN_Center  2 /*   center      auto     */
    832 #define QRF_ALIGN_Right   3 /*   right       auto     */
    833 #define QRF_ALIGN_Top     4 /*   auto        top      */
    834 #define QRF_ALIGN_NW      5 /*   left        top      */
    835 #define QRF_ALIGN_N       6 /*   center      top      */
    836 #define QRF_ALIGN_NE      7 /*   right       top      */
    837 #define QRF_ALIGN_Middle  8 /*   auto        middle   */
    838 #define QRF_ALIGN_W       9 /*   left        middle   */
    839 #define QRF_ALIGN_C      10 /*   center      middle   */
    840 #define QRF_ALIGN_E      11 /*   right       middle   */
    841 #define QRF_ALIGN_Bottom 12 /*   auto        bottom   */
    842 #define QRF_ALIGN_SW     13 /*   left        bottom   */
    843 #define QRF_ALIGN_S      14 /*   center      bottom   */
    844 #define QRF_ALIGN_SE     15 /*   right       bottom   */
    845 #define QRF_ALIGN_HMASK   3 /* Horizontal alignment mask */
    846 #define QRF_ALIGN_VMASK  12 /* Vertical alignment mask */
    847 
    848 /*
    849 ** Auxiliary routines contined within this module that might be useful
    850 ** in other contexts, and which are therefore exported.
    851 */
    852 /*
    853 ** Return an estimate of the width, in columns, for the single Unicode
    854 ** character c.  For normal characters, the answer is always 1.  But the
    855 ** estimate might be 0 or 2 for zero-width and double-width characters.
    856 **
    857 ** Different devices display unicode using different widths.  So
    858 ** it is impossible to know that true display width with 100% accuracy.
    859 ** Inaccuracies in the width estimates might cause columns to be misaligned.
    860 ** Unfortunately, there is nothing we can do about that.
    861 */
    862 int sqlite3_qrf_wcwidth(int c);
    863 
    864 /*
    865 ** Return an estimate of the number of display columns used by the
    866 ** string in the argument.  The width of individual characters is
    867 ** determined as for sqlite3_qrf_wcwidth().  VT100 escape code sequences
    868 ** are assigned a width of zero.
    869 */
    870 size_t sqlite3_qrf_wcswidth(const char*);
    871 
    872 
    873 #ifdef __cplusplus
    874 }
    875 #endif
    876 #endif /* !defined(SQLITE_QRF_H) */
    877 
    878 /************************* End ext/qrf/qrf.h ********************/
    879 /************************* Begin ext/qrf/qrf.c ******************/
    880 /*
    881 ** 2025-10-20
    882 **
    883 ** The author disclaims copyright to this source code.  In place of
    884 ** a legal notice, here is a blessing:
    885 **
    886 **    May you do good and not evil.
    887 **    May you find forgiveness for yourself and forgive others.
    888 **    May you share freely, never taking more than you give.
    889 **
    890 *************************************************************************
    891 ** Implementation of the Query Result-Format or "qrf" utility library for
    892 ** SQLite.  See the README.md documentation for additional information.
    893 */
    894 #ifndef SQLITE_QRF_H
    895 #include "qrf.h"
    896 #endif
    897 #include <string.h>
    898 #include <assert.h>
    899 #include <stdint.h>
    900 
    901 #ifndef SQLITE_AMALGAMATION
    902 /* typedef sqlite3_int64 i64; */
    903 #endif
    904 
    905 /* A single line in the EQP output */
    906 typedef struct qrfEQPGraphRow qrfEQPGraphRow;
    907 struct qrfEQPGraphRow {
    908   int iEqpId;            /* ID for this row */
    909   int iParentId;         /* ID of the parent row */
    910   qrfEQPGraphRow *pNext; /* Next row in sequence */
    911   char zText[1];         /* Text to display for this row */
    912 };
    913 
    914 /* All EQP output is collected into an instance of the following */
    915 typedef struct qrfEQPGraph qrfEQPGraph;
    916 struct qrfEQPGraph {
    917   qrfEQPGraphRow *pRow;  /* Linked list of all rows of the EQP output */
    918   qrfEQPGraphRow *pLast; /* Last element of the pRow list */
    919   int nWidth;            /* Width of the graph */
    920   char zPrefix[400];     /* Graph prefix */
    921 };
    922 
    923 /*
    924 ** Private state information.  Subject to change from one release to the
    925 ** next.
    926 */
    927 typedef struct Qrf Qrf;
    928 struct Qrf {
    929   sqlite3_stmt *pStmt;        /* The statement whose output is to be rendered */
    930   sqlite3 *db;                /* The corresponding database connection */
    931   sqlite3_stmt *pJTrans;      /* JSONB to JSON translator statement */
    932   char **pzErr;               /* Write error message here, if not NULL */
    933   sqlite3_str *pOut;          /* Accumulated output */
    934   int iErr;                   /* Error code */
    935   int nCol;                   /* Number of output columns */
    936   int expMode;                /* Original sqlite3_stmt_isexplain() plus 1 */
    937   int mxWidth;                /* Screen width */
    938   int mxHeight;               /* nLineLimit */
    939   union {
    940     struct {                  /* Content for QRF_STYLE_Line */
    941       int mxColWth;             /* Maximum display width of any column */
    942       char **azCol;             /* Names of output columns (MODE_Line) */
    943     } sLine;
    944     qrfEQPGraph *pGraph;      /* EQP graph (Eqp, Stats, and StatsEst) */
    945     struct {                  /* Content for QRF_STYLE_Explain */
    946       int nIndent;              /* Slots allocated for aiIndent */
    947       int iIndent;              /* Current slot */
    948       int *aiIndent;            /* Indentation for each opcode */
    949     } sExpln;
    950     unsigned int nIns;        /* Bytes used for current INSERT stmt */
    951   } u;
    952   sqlite3_int64 nRow;         /* Number of rows handled so far */
    953   int *actualWidth;           /* Actual width of each column */
    954   sqlite3_qrf_spec spec;      /* Copy of the original spec */
    955 };
    956 
    957 /*
    958 ** Data for substitute ctype.h functions.  Used for x-platform
    959 ** consistency and so that '_' is counted as an alphabetic
    960 ** character.
    961 **
    962 **    0x01 -  space
    963 **    0x02 -  digit
    964 **    0x04 -  alphabetic, including '_'
    965 */
    966 static const char qrfCType[] = {
    967   0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0,
    968   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    969   1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    970   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
    971   0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
    972   4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4,
    973   0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
    974   4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0,
    975   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    976   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    977   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    978   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    979   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    980   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    981   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    982   0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    983 };
    984 #define qrfSpace(x) ((qrfCType[(unsigned char)x]&1)!=0)
    985 #define qrfDigit(x) ((qrfCType[(unsigned char)x]&2)!=0)
    986 #define qrfAlpha(x) ((qrfCType[(unsigned char)x]&4)!=0)
    987 #define qrfAlnum(x) ((qrfCType[(unsigned char)x]&6)!=0)
    988 
    989 #ifndef deliberate_fall_through
    990 /* Quiet some compilers about some of our intentional code. */
    991 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
    992 #  define deliberate_fall_through __attribute__((fallthrough));
    993 # else
    994 #  define deliberate_fall_through
    995 # endif
    996 #endif
    997 
    998 /*
    999 ** Set an error code and error message.
   1000 */
   1001 static void qrfError(
   1002   Qrf *p,                /* Query result state */
   1003   int iCode,             /* Error code */
   1004   const char *zFormat,   /* Message format (or NULL) */
   1005   ...
   1006 ){
   1007   p->iErr = iCode;
   1008   if( p->pzErr!=0 ){
   1009     sqlite3_free(*p->pzErr);
   1010     *p->pzErr = 0;
   1011     if( zFormat ){
   1012       va_list ap;
   1013       va_start(ap, zFormat);
   1014       *p->pzErr = sqlite3_vmprintf(zFormat, ap);
   1015       va_end(ap);
   1016     }
   1017   }
   1018 }
   1019 
   1020 /*
   1021 ** Out-of-memory error.
   1022 */
   1023 static void qrfOom(Qrf *p){
   1024   qrfError(p, SQLITE_NOMEM, "out of memory");
   1025 }
   1026 
   1027 /*
   1028 ** Transfer any error in pStr over into p.
   1029 */
   1030 static void qrfStrErr(Qrf *p, sqlite3_str *pStr){
   1031   int rc = pStr ? sqlite3_str_errcode(pStr) : 0;
   1032   if( rc ){
   1033     qrfError(p, rc, sqlite3_errstr(rc));
   1034   }
   1035 }
   1036 
   1037 
   1038 /*
   1039 ** Add a new entry to the EXPLAIN QUERY PLAN data
   1040 */
   1041 static void qrfEqpAppend(Qrf *p, int iEqpId, int p2, const char *zText){
   1042   qrfEQPGraphRow *pNew;
   1043   sqlite3_int64 nText;
   1044   if( zText==0 ) return;
   1045   if( p->u.pGraph==0 ){
   1046     p->u.pGraph = sqlite3_malloc64( sizeof(qrfEQPGraph) );
   1047     if( p->u.pGraph==0 ){
   1048       qrfOom(p);
   1049       return;
   1050     }
   1051     memset(p->u.pGraph, 0, sizeof(qrfEQPGraph) );
   1052   }
   1053   nText = strlen(zText);
   1054   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
   1055   if( pNew==0 ){
   1056     qrfOom(p);
   1057     return;
   1058   }
   1059   pNew->iEqpId = iEqpId;
   1060   pNew->iParentId = p2;
   1061   memcpy(pNew->zText, zText, nText+1);
   1062   pNew->pNext = 0;
   1063   if( p->u.pGraph->pLast ){
   1064     p->u.pGraph->pLast->pNext = pNew;
   1065   }else{
   1066     p->u.pGraph->pRow = pNew;
   1067   }
   1068   p->u.pGraph->pLast = pNew;
   1069 }
   1070 
   1071 /*
   1072 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
   1073 ** in p->u.pGraph.
   1074 */
   1075 static void qrfEqpReset(Qrf *p){
   1076   qrfEQPGraphRow *pRow, *pNext;
   1077   if( p->u.pGraph ){
   1078     for(pRow = p->u.pGraph->pRow; pRow; pRow = pNext){
   1079       pNext = pRow->pNext;
   1080       sqlite3_free(pRow);
   1081     }
   1082     sqlite3_free(p->u.pGraph);
   1083     p->u.pGraph = 0;
   1084   }
   1085 }
   1086 
   1087 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
   1088 ** pOld, or return the first such line if pOld is NULL
   1089 */
   1090 static qrfEQPGraphRow *qrfEqpNextRow(Qrf *p, int iEqpId, qrfEQPGraphRow *pOld){
   1091   qrfEQPGraphRow *pRow = pOld ? pOld->pNext : p->u.pGraph->pRow;
   1092   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
   1093   return pRow;
   1094 }
   1095 
   1096 /* Render a single level of the graph that has iEqpId as its parent.  Called
   1097 ** recursively to render sublevels.
   1098 */
   1099 static void qrfEqpRenderLevel(Qrf *p, int iEqpId){
   1100   qrfEQPGraphRow *pRow, *pNext;
   1101   i64 n = strlen(p->u.pGraph->zPrefix);
   1102   char *z;
   1103   for(pRow = qrfEqpNextRow(p, iEqpId, 0); pRow; pRow = pNext){
   1104     pNext = qrfEqpNextRow(p, iEqpId, pRow);
   1105     z = pRow->zText;
   1106     sqlite3_str_appendf(p->pOut, "%s%s%s\n", p->u.pGraph->zPrefix,
   1107                             pNext ? "|--" : "`--", z);
   1108     if( n<(i64)sizeof(p->u.pGraph->zPrefix)-7 ){
   1109       memcpy(&p->u.pGraph->zPrefix[n], pNext ? "|  " : "   ", 4);
   1110       qrfEqpRenderLevel(p, pRow->iEqpId);
   1111       p->u.pGraph->zPrefix[n] = 0;
   1112     }
   1113   }
   1114 }
   1115 
   1116 /*
   1117 ** Render the 64-bit value N in a more human-readable format into
   1118 ** pOut.
   1119 **
   1120 **   +  Only show the first three significant digits.
   1121 **   +  Append suffixes K, M, G, T, P, and E for 1e3, 1e6, ... 1e18
   1122 */
   1123 static void qrfApproxInt64(sqlite3_str *pOut, i64 N){
   1124   static const char aSuffix[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
   1125   int i;
   1126   if( N<0 ){
   1127     N = N==INT64_MIN ? INT64_MAX : -N;
   1128     sqlite3_str_append(pOut, "-", 1);
   1129   }
   1130   if( N<10000 ){
   1131     sqlite3_str_appendf(pOut, "%4lld ", N);
   1132     return;
   1133   }
   1134   for(i=1; i<=18; i++){
   1135     N = (N+5)/10;
   1136     if( N<10000 ){
   1137       int n = (int)N;
   1138       switch( i%3 ){
   1139         case 0:
   1140           sqlite3_str_appendf(pOut, "%d.%02d", n/1000, (n%1000)/10);
   1141           break;
   1142         case 1:
   1143           sqlite3_str_appendf(pOut, "%2d.%d", n/100, (n%100)/10);
   1144           break;
   1145         case 2:
   1146           sqlite3_str_appendf(pOut, "%4d", n/10);
   1147           break;
   1148       }
   1149       sqlite3_str_append(pOut, &aSuffix[i/3], 1);
   1150       break;
   1151     }
   1152   }
   1153 }
   1154 
   1155 /*
   1156 ** Display and reset the EXPLAIN QUERY PLAN data
   1157 */
   1158 static void qrfEqpRender(Qrf *p, i64 nCycle){
   1159   qrfEQPGraphRow *pRow;
   1160   if( p->u.pGraph!=0 && (pRow = p->u.pGraph->pRow)!=0 ){
   1161     if( pRow->zText[0]=='-' ){
   1162       if( pRow->pNext==0 ){
   1163         qrfEqpReset(p);
   1164         return;
   1165       }
   1166       sqlite3_str_appendf(p->pOut, "%s\n", pRow->zText+3);
   1167       p->u.pGraph->pRow = pRow->pNext;
   1168       sqlite3_free(pRow);
   1169     }else if( nCycle>0 ){
   1170       int nSp = p->u.pGraph->nWidth - 2;
   1171       if( p->spec.eStyle==QRF_STYLE_StatsEst ){
   1172         sqlite3_str_appendchar(p->pOut, nSp, ' ');
   1173         sqlite3_str_appendall(p->pOut,
   1174                                 "Cycles      Loops  (est)  Rows   (est)\n");
   1175         sqlite3_str_appendchar(p->pOut, nSp, ' ');
   1176         sqlite3_str_appendall(p->pOut,
   1177                                 "----------  ------------  ------------\n");
   1178       }else{
   1179         sqlite3_str_appendchar(p->pOut, nSp, ' ');
   1180         sqlite3_str_appendall(p->pOut,
   1181                                 "Cycles      Loops  Rows \n");
   1182         sqlite3_str_appendchar(p->pOut, nSp, ' ');
   1183         sqlite3_str_appendall(p->pOut,
   1184                                 "----------  -----  -----\n");
   1185       }
   1186       sqlite3_str_appendall(p->pOut, "QUERY PLAN");
   1187       sqlite3_str_appendchar(p->pOut, nSp - 10, ' ');
   1188       qrfApproxInt64(p->pOut, nCycle);
   1189       sqlite3_str_appendall(p->pOut, " 100%\n");
   1190     }else{
   1191       sqlite3_str_appendall(p->pOut, "QUERY PLAN\n");
   1192     }
   1193     p->u.pGraph->zPrefix[0] = 0;
   1194     qrfEqpRenderLevel(p, 0);
   1195     qrfEqpReset(p);
   1196   }
   1197 }
   1198 
   1199 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   1200 /*
   1201 ** Helper function for qrfExpStats().
   1202 **
   1203 */
   1204 static int qrfStatsHeight(sqlite3_stmt *p, int iEntry){
   1205   int iPid = 0;
   1206   int ret = 1;
   1207   sqlite3_stmt_scanstatus_v2(p, iEntry,
   1208       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
   1209   );
   1210   while( iPid!=0 ){
   1211     int ii;
   1212     for(ii=0; 1; ii++){
   1213       int iId;
   1214       int res;
   1215       res = sqlite3_stmt_scanstatus_v2(p, ii,
   1216           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
   1217       );
   1218       if( res ) break;
   1219       if( iId==iPid ){
   1220         sqlite3_stmt_scanstatus_v2(p, ii,
   1221             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
   1222         );
   1223       }
   1224     }
   1225     ret++;
   1226   }
   1227   return ret;
   1228 }
   1229 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
   1230 
   1231 
   1232 /*
   1233 ** Generate ".scanstatus est" style of EQP output.
   1234 */
   1235 static void qrfEqpStats(Qrf *p){
   1236 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
   1237   qrfError(p, SQLITE_ERROR, "not available in this build");
   1238 #else
   1239   static const int f = SQLITE_SCANSTAT_COMPLEX;
   1240   sqlite3_stmt *pS = p->pStmt;
   1241   int i = 0;
   1242   i64 nTotal = 0;
   1243   int nWidth = 0;
   1244   int prevPid = -1;             /* Previous iPid */
   1245   double rEstCum = 1.0;         /* Cumulative row estimate */
   1246   sqlite3_str *pLine = sqlite3_str_new(p->db);
   1247   sqlite3_str *pStats = sqlite3_str_new(p->db);
   1248   qrfEqpReset(p);
   1249 
   1250   for(i=0; 1; i++){
   1251     const char *z = 0;
   1252     int n = 0;
   1253     if( sqlite3_stmt_scanstatus_v2(pS,i,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
   1254       break;
   1255     }
   1256     n = (int)strlen(z) + qrfStatsHeight(pS,i)*3;
   1257     if( n>nWidth ) nWidth = n;
   1258   }
   1259   nWidth += 2;
   1260 
   1261   sqlite3_stmt_scanstatus_v2(pS,-1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
   1262   for(i=0; 1; i++){
   1263     i64 nLoop = 0;
   1264     i64 nRow = 0;
   1265     i64 nCycle = 0;
   1266     int iId = 0;
   1267     int iPid = 0;
   1268     const char *zo = 0;
   1269     const char *zName = 0;
   1270     double rEst = 0.0;
   1271 
   1272     if( sqlite3_stmt_scanstatus_v2(pS,i,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
   1273       break;
   1274     }
   1275     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
   1276     if( iPid!=prevPid ){
   1277       prevPid = iPid;
   1278       rEstCum = 1.0;
   1279     }
   1280     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
   1281     rEstCum *= rEst;
   1282     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
   1283     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
   1284     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
   1285     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
   1286     sqlite3_stmt_scanstatus_v2(pS,i, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
   1287 
   1288     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
   1289       int nSp = 0;
   1290       sqlite3_str_reset(pStats);
   1291       if( nCycle>=0 && nTotal>0 ){
   1292         qrfApproxInt64(pStats, nCycle);
   1293         sqlite3_str_appendf(pStats, " %3d%%",
   1294             ((nCycle*100)+nTotal/2) / nTotal
   1295         );
   1296         nSp = 2;
   1297       }
   1298       if( nLoop>=0 ){
   1299         if( nSp ) sqlite3_str_appendchar(pStats, nSp, ' ');
   1300         qrfApproxInt64(pStats, nLoop);
   1301         nSp = 2;
   1302         if( p->spec.eStyle==QRF_STYLE_StatsEst ){
   1303           sqlite3_str_appendf(pStats, "  ");
   1304           qrfApproxInt64(pStats, (i64)(rEstCum/rEst));
   1305         }
   1306       }
   1307       if( nRow>=0 ){
   1308         if( nSp ) sqlite3_str_appendchar(pStats, nSp, ' ');
   1309         qrfApproxInt64(pStats, nRow);
   1310         nSp = 2;
   1311         if( p->spec.eStyle==QRF_STYLE_StatsEst ){
   1312           sqlite3_str_appendf(pStats, "  ");
   1313           qrfApproxInt64(pStats, (i64)rEstCum);
   1314         }
   1315       }
   1316       sqlite3_str_appendf(pLine,
   1317           "% *s %s", -1*(nWidth-qrfStatsHeight(pS,i)*3), zo,
   1318           sqlite3_str_value(pStats)
   1319       );
   1320       sqlite3_str_reset(pStats);
   1321       qrfEqpAppend(p, iId, iPid, sqlite3_str_value(pLine));
   1322       sqlite3_str_reset(pLine);
   1323     }else{
   1324       qrfEqpAppend(p, iId, iPid, zo);
   1325     }
   1326   }
   1327   if( p->u.pGraph ) p->u.pGraph->nWidth = nWidth;
   1328   qrfStrErr(p, pLine);
   1329   sqlite3_free(sqlite3_str_finish(pLine));
   1330   qrfStrErr(p, pStats);
   1331   sqlite3_free(sqlite3_str_finish(pStats));
   1332 #endif
   1333 }
   1334 
   1335 
   1336 /*
   1337 ** Reset the prepared statement.
   1338 */
   1339 static void qrfResetStmt(Qrf *p){
   1340   int rc = sqlite3_reset(p->pStmt);
   1341   if( rc!=SQLITE_OK && p->iErr==SQLITE_OK ){
   1342     qrfError(p, rc, "%s", sqlite3_errmsg(p->db));
   1343   }
   1344 }
   1345 
   1346 /*
   1347 ** If xWrite is defined, send all content of pOut to xWrite and
   1348 ** reset pOut.
   1349 */
   1350 static void qrfWrite(Qrf *p){
   1351   int n;
   1352   if( p->spec.xWrite && (n = sqlite3_str_length(p->pOut))>0 ){
   1353     int rc = p->spec.xWrite(p->spec.pWriteArg,
   1354                  sqlite3_str_value(p->pOut),
   1355                  (sqlite3_int64)n);
   1356     sqlite3_str_reset(p->pOut);
   1357     if( rc ){
   1358       qrfError(p, rc, "Failed to write %d bytes of output", n);
   1359     }
   1360   }
   1361 }
   1362 
   1363 /* Lookup table to estimate the number of columns consumed by a Unicode
   1364 ** character.
   1365 */
   1366 static const struct {
   1367   unsigned char w;    /* Width of the character in columns */
   1368   int iFirst;         /* First character in a span having this width */
   1369 } aQrfUWidth[] = {
   1370    /* {1, 0x00000}, */
   1371   {0, 0x00300},  {1, 0x00370},  {0, 0x00483},  {1, 0x00487},  {0, 0x00488},
   1372   {1, 0x0048a},  {0, 0x00591},  {1, 0x005be},  {0, 0x005bf},  {1, 0x005c0},
   1373   {0, 0x005c1},  {1, 0x005c3},  {0, 0x005c4},  {1, 0x005c6},  {0, 0x005c7},
   1374   {1, 0x005c8},  {0, 0x00600},  {1, 0x00604},  {0, 0x00610},  {1, 0x00616},
   1375   {0, 0x0064b},  {1, 0x0065f},  {0, 0x00670},  {1, 0x00671},  {0, 0x006d6},
   1376   {1, 0x006e5},  {0, 0x006e7},  {1, 0x006e9},  {0, 0x006ea},  {1, 0x006ee},
   1377   {0, 0x0070f},  {1, 0x00710},  {0, 0x00711},  {1, 0x00712},  {0, 0x00730},
   1378   {1, 0x0074b},  {0, 0x007a6},  {1, 0x007b1},  {0, 0x007eb},  {1, 0x007f4},
   1379   {0, 0x00901},  {1, 0x00903},  {0, 0x0093c},  {1, 0x0093d},  {0, 0x00941},
   1380   {1, 0x00949},  {0, 0x0094d},  {1, 0x0094e},  {0, 0x00951},  {1, 0x00955},
   1381   {0, 0x00962},  {1, 0x00964},  {0, 0x00981},  {1, 0x00982},  {0, 0x009bc},
   1382   {1, 0x009bd},  {0, 0x009c1},  {1, 0x009c5},  {0, 0x009cd},  {1, 0x009ce},
   1383   {0, 0x009e2},  {1, 0x009e4},  {0, 0x00a01},  {1, 0x00a03},  {0, 0x00a3c},
   1384   {1, 0x00a3d},  {0, 0x00a41},  {1, 0x00a43},  {0, 0x00a47},  {1, 0x00a49},
   1385   {0, 0x00a4b},  {1, 0x00a4e},  {0, 0x00a70},  {1, 0x00a72},  {0, 0x00a81},
   1386   {1, 0x00a83},  {0, 0x00abc},  {1, 0x00abd},  {0, 0x00ac1},  {1, 0x00ac6},
   1387   {0, 0x00ac7},  {1, 0x00ac9},  {0, 0x00acd},  {1, 0x00ace},  {0, 0x00ae2},
   1388   {1, 0x00ae4},  {0, 0x00b01},  {1, 0x00b02},  {0, 0x00b3c},  {1, 0x00b3d},
   1389   {0, 0x00b3f},  {1, 0x00b40},  {0, 0x00b41},  {1, 0x00b44},  {0, 0x00b4d},
   1390   {1, 0x00b4e},  {0, 0x00b56},  {1, 0x00b57},  {0, 0x00b82},  {1, 0x00b83},
   1391   {0, 0x00bc0},  {1, 0x00bc1},  {0, 0x00bcd},  {1, 0x00bce},  {0, 0x00c3e},
   1392   {1, 0x00c41},  {0, 0x00c46},  {1, 0x00c49},  {0, 0x00c4a},  {1, 0x00c4e},
   1393   {0, 0x00c55},  {1, 0x00c57},  {0, 0x00cbc},  {1, 0x00cbd},  {0, 0x00cbf},
   1394   {1, 0x00cc0},  {0, 0x00cc6},  {1, 0x00cc7},  {0, 0x00ccc},  {1, 0x00cce},
   1395   {0, 0x00ce2},  {1, 0x00ce4},  {0, 0x00d41},  {1, 0x00d44},  {0, 0x00d4d},
   1396   {1, 0x00d4e},  {0, 0x00dca},  {1, 0x00dcb},  {0, 0x00dd2},  {1, 0x00dd5},
   1397   {0, 0x00dd6},  {1, 0x00dd7},  {0, 0x00e31},  {1, 0x00e32},  {0, 0x00e34},
   1398   {1, 0x00e3b},  {0, 0x00e47},  {1, 0x00e4f},  {0, 0x00eb1},  {1, 0x00eb2},
   1399   {0, 0x00eb4},  {1, 0x00eba},  {0, 0x00ebb},  {1, 0x00ebd},  {0, 0x00ec8},
   1400   {1, 0x00ece},  {0, 0x00f18},  {1, 0x00f1a},  {0, 0x00f35},  {1, 0x00f36},
   1401   {0, 0x00f37},  {1, 0x00f38},  {0, 0x00f39},  {1, 0x00f3a},  {0, 0x00f71},
   1402   {1, 0x00f7f},  {0, 0x00f80},  {1, 0x00f85},  {0, 0x00f86},  {1, 0x00f88},
   1403   {0, 0x00f90},  {1, 0x00f98},  {0, 0x00f99},  {1, 0x00fbd},  {0, 0x00fc6},
   1404   {1, 0x00fc7},  {0, 0x0102d},  {1, 0x01031},  {0, 0x01032},  {1, 0x01033},
   1405   {0, 0x01036},  {1, 0x0103b},  {0, 0x01058},
   1406   {1, 0x0105a},  {2, 0x01100},  {0, 0x01160},  {1, 0x01200},  {0, 0x0135f},
   1407   {1, 0x01360},  {0, 0x01712},  {1, 0x01715},  {0, 0x01732},  {1, 0x01735},
   1408   {0, 0x01752},  {1, 0x01754},  {0, 0x01772},  {1, 0x01774},  {0, 0x017b4},
   1409   {1, 0x017b6},  {0, 0x017b7},  {1, 0x017be},  {0, 0x017c6},  {1, 0x017c7},
   1410   {0, 0x017c9},  {1, 0x017d4},  {0, 0x017dd},  {1, 0x017de},  {0, 0x0180b},
   1411   {1, 0x0180e},  {0, 0x018a9},  {1, 0x018aa},  {0, 0x01920},  {1, 0x01923},
   1412   {0, 0x01927},  {1, 0x01929},  {0, 0x01932},  {1, 0x01933},  {0, 0x01939},
   1413   {1, 0x0193c},  {0, 0x01a17},  {1, 0x01a19},  {0, 0x01b00},  {1, 0x01b04},
   1414   {0, 0x01b34},  {1, 0x01b35},  {0, 0x01b36},  {1, 0x01b3b},  {0, 0x01b3c},
   1415   {1, 0x01b3d},  {0, 0x01b42},  {1, 0x01b43},  {0, 0x01b6b},  {1, 0x01b74},
   1416   {0, 0x01dc0},  {1, 0x01dcb},  {0, 0x01dfe},  {1, 0x01e00},  {0, 0x0200b},
   1417   {1, 0x02010},  {0, 0x0202a},  {1, 0x0202f},  {0, 0x02060},  {1, 0x02064},
   1418   {0, 0x0206a},  {1, 0x02070},  {0, 0x020d0},  {1, 0x020f0},  {2, 0x02329},
   1419   {1, 0x0232b},  {2, 0x02e80},  {0, 0x0302a},  {2, 0x03030},  {1, 0x0303f},
   1420   {2, 0x03040},  {0, 0x03099},  {2, 0x0309b},  {1, 0x0a4d0},  {0, 0x0a806},
   1421   {1, 0x0a807},  {0, 0x0a80b},  {1, 0x0a80c},  {0, 0x0a825},  {1, 0x0a827},
   1422   {2, 0x0ac00},  {1, 0x0d7a4},  {2, 0x0f900},  {1, 0x0fb00},  {0, 0x0fb1e},
   1423   {1, 0x0fb1f},  {0, 0x0fe00},  {2, 0x0fe10},  {1, 0x0fe1a},  {0, 0x0fe20},
   1424   {1, 0x0fe24},  {2, 0x0fe30},  {1, 0x0fe70},  {0, 0x0feff},  {2, 0x0ff00},
   1425   {1, 0x0ff61},  {2, 0x0ffe0},  {1, 0x0ffe7},  {0, 0x0fff9},  {1, 0x0fffc},
   1426   {0, 0x10a01},  {1, 0x10a04},  {0, 0x10a05},  {1, 0x10a07},  {0, 0x10a0c},
   1427   {1, 0x10a10},  {0, 0x10a38},  {1, 0x10a3b},  {0, 0x10a3f},  {1, 0x10a40},
   1428   {0, 0x1d167},  {1, 0x1d16a},  {0, 0x1d173},  {1, 0x1d183},  {0, 0x1d185},
   1429   {1, 0x1d18c},  {0, 0x1d1aa},  {1, 0x1d1ae},  {0, 0x1d242},  {1, 0x1d245},
   1430   {2, 0x20000},  {1, 0x2fffe},  {2, 0x30000},  {1, 0x3fffe},  {0, 0xe0001},
   1431   {1, 0xe0002},  {0, 0xe0020},  {1, 0xe0080},  {0, 0xe0100},  {1, 0xe01f0}
   1432 };
   1433 
   1434 /*
   1435 ** Return an estimate of the width, in columns, for the single Unicode
   1436 ** character c.  For normal characters, the answer is always 1.  But the
   1437 ** estimate might be 0 or 2 for zero-width and double-width characters.
   1438 **
   1439 ** Different display devices display unicode using different widths.  So
   1440 ** it is impossible to know that true display width with 100% accuracy.
   1441 ** Inaccuracies in the width estimates might cause columns to be misaligned.
   1442 ** Unfortunately, there is nothing we can do about that.
   1443 */
   1444 int sqlite3_qrf_wcwidth(int c){
   1445   int iFirst, iLast;
   1446 
   1447   /* Fast path for common characters */
   1448   if( c<0x300 ) return 1;
   1449 
   1450   /* The general case */
   1451   iFirst = 0;
   1452   iLast = sizeof(aQrfUWidth)/sizeof(aQrfUWidth[0]) - 1;
   1453   while( iFirst<iLast-1 ){
   1454     int iMid = (iFirst+iLast)/2;
   1455     int cMid = aQrfUWidth[iMid].iFirst;
   1456     if( cMid < c ){
   1457       iFirst = iMid;
   1458     }else if( cMid > c ){
   1459       iLast = iMid - 1;
   1460     }else{
   1461       return aQrfUWidth[iMid].w;
   1462     }
   1463   }
   1464   if( aQrfUWidth[iLast].iFirst > c ) return aQrfUWidth[iFirst].w;
   1465   return aQrfUWidth[iLast].w;
   1466 }
   1467 
   1468 /*
   1469 ** Compute the value and length of a multi-byte UTF-8 character that
   1470 ** begins at z[0]. Return the length.  Write the Unicode value into *pU.
   1471 **
   1472 ** This routine only works for *multi-byte* UTF-8 characters.  It does
   1473 ** not attempt to detect illegal characters.
   1474 */
   1475 static int sqlite3_qrf_decode_utf8(const unsigned char *z, int *pU){
   1476   if( (z[0] & 0xe0)==0xc0 && (z[1] & 0xc0)==0x80 ){
   1477     *pU = ((z[0] & 0x1f)<<6) | (z[1] & 0x3f);
   1478     return 2;
   1479   }
   1480   if( (z[0] & 0xf0)==0xe0 && (z[1] & 0xc0)==0x80 && (z[2] & 0xc0)==0x80 ){
   1481     *pU = ((z[0] & 0x0f)<<12) | ((z[1] & 0x3f)<<6) | (z[2] & 0x3f);
   1482     return 3;
   1483   }
   1484   if( (z[0] & 0xf8)==0xf0 && (z[1] & 0xc0)==0x80 && (z[2] & 0xc0)==0x80
   1485    && (z[3] & 0xc0)==0x80
   1486   ){
   1487     *pU = ((z[0] & 0x0f)<<18) | ((z[1] & 0x3f)<<12) | ((z[2] & 0x3f))<<6
   1488                               | (z[3] & 0x3f);
   1489     return 4;
   1490   }
   1491   *pU = 0;
   1492   return 1;
   1493 }
   1494 
   1495 /*
   1496 ** Check to see if z[] is a valid VT100 escape.  If it is, then
   1497 ** return the number of bytes in the escape sequence.  Return 0 if
   1498 ** z[] is not a VT100 escape.
   1499 **
   1500 ** This routine assumes that z[0] is \033 (ESC).
   1501 */
   1502 static int qrfIsVt100(const unsigned char *z){
   1503   int i;
   1504   if( z[1]!='[' ) return 0;
   1505   i = 2;
   1506   while( z[i]>=0x30 && z[i]<=0x3f ){ i++; }
   1507   while( z[i]>=0x20 && z[i]<=0x2f ){ i++; }
   1508   if( z[i]<0x40 || z[i]>0x7e ) return 0;
   1509   return i+1;
   1510 }
   1511 
   1512 /*
   1513 ** Return the length of a string in display characters.
   1514 **
   1515 ** Most characters of the input string count as 1, including
   1516 ** multi-byte UTF8 characters.  However, zero-width unicode
   1517 ** characters and VT100 escape sequences count as zero, and
   1518 ** double-width characters count as two.
   1519 **
   1520 ** The definition of "zero-width" and "double-width" characters
   1521 ** is not precise.  It depends on the output device, to some extent,
   1522 ** and it varies according to the Unicode version.  This routine
   1523 ** makes the best guess that it can.
   1524 */
   1525 size_t sqlite3_qrf_wcswidth(const char *zIn){
   1526   const unsigned char *z = (const unsigned char*)zIn;
   1527   size_t n = 0;
   1528   while( *z ){
   1529     if( z[0]<' ' ){
   1530       int k;
   1531       if( z[0]=='\033' && (k = qrfIsVt100(z))>0 ){
   1532         z += k;
   1533       }else{
   1534         z++;
   1535       }
   1536     }else if( (0x80&z[0])==0 ){
   1537       n++;
   1538       z++;
   1539     }else{
   1540       int u = 0;
   1541       int len = sqlite3_qrf_decode_utf8(z, &u);
   1542       z += len;
   1543       n += sqlite3_qrf_wcwidth(u);
   1544     }
   1545   }
   1546   return n;
   1547 }
   1548 
   1549 /*
   1550 ** Return the display width of the longest line of text
   1551 ** in the (possibly) multi-line input string zIn[0..nByte].
   1552 ** zIn[] is not necessarily zero-terminated.  Take
   1553 ** into account tab characters, zero- and double-width
   1554 ** characters, CR and NL, and VT100 escape codes.
   1555 **
   1556 ** Write the number of newlines into *pnNL.  So, *pnNL will
   1557 ** return 0 if everything fits on one line, or positive it
   1558 ** it will need to be split.
   1559 */
   1560 static int qrfDisplayWidth(const char *zIn, sqlite3_int64 nByte, int *pnNL){
   1561   const unsigned char *z;
   1562   const unsigned char *zEnd;
   1563   int mx = 0;
   1564   int n = 0;
   1565   int nNL = 0;
   1566   if( zIn==0 ) zIn = "";
   1567   z = (const unsigned char*)zIn;
   1568   zEnd = &z[nByte];
   1569   while( z<zEnd ){
   1570     if( z[0]<' ' ){
   1571       int k;
   1572       if( z[0]=='\033' && (k = qrfIsVt100(z))>0 ){
   1573         z += k;
   1574       }else{
   1575         if( z[0]=='\t' ){
   1576           n = (n+8)&~7;
   1577         }else if( z[0]=='\n' || z[0]=='\r' ){
   1578           nNL++;
   1579           if( n>mx ) mx = n;
   1580           n = 0;
   1581         }
   1582         z++;
   1583       }
   1584     }else if( (0x80&z[0])==0 ){
   1585       n++;
   1586       z++;
   1587     }else{
   1588       int u = 0;
   1589       int len = sqlite3_qrf_decode_utf8(z, &u);
   1590       z += len;
   1591       n += sqlite3_qrf_wcwidth(u);
   1592     }
   1593   }
   1594   if( mx>n ) n = mx;
   1595   if( pnNL ) *pnNL = nNL;
   1596   return n;
   1597 }
   1598 
   1599 /*
   1600 ** Escape the input string if it is needed and in accordance with
   1601 ** eEsc, which is either QRF_ESC_Ascii or QRF_ESC_Symbol.
   1602 **
   1603 ** Escaping is needed if the string contains any control characters
   1604 ** other than \t, \n, and \r\n
   1605 **
   1606 ** If no escaping is needed (the common case) then set *ppOut to NULL
   1607 ** and return 0.  If escaping is needed, write the escaped string into
   1608 ** memory obtained from sqlite3_malloc64() and make *ppOut point to that
   1609 ** memory and return 0.  If an error occurs, return non-zero.
   1610 **
   1611 ** The caller is responsible for freeing *ppFree if it is non-NULL in order
   1612 ** to reclaim memory.
   1613 */
   1614 static void qrfEscape(
   1615   int eEsc,            /* QRF_ESC_Ascii or QRF_ESC_Symbol */
   1616   sqlite3_str *pStr,      /* String to be escaped */
   1617   int iStart              /* Begin escapding on this byte of pStr */
   1618 ){
   1619   sqlite3_int64 i, j;     /* Loop counters */
   1620   sqlite3_int64 sz;       /* Size of the string prior to escaping */
   1621   sqlite3_int64 nCtrl = 0;/* Number of control characters to escape */
   1622   unsigned char *zIn;     /* Text to be escaped */
   1623   unsigned char c;        /* A single character of the text */
   1624   unsigned char *zOut;    /* Where to write the results */
   1625 
   1626   /* Find the text to be escaped */
   1627   zIn = (unsigned char*)sqlite3_str_value(pStr);
   1628   if( zIn==0 ) return;
   1629   zIn += iStart;
   1630 
   1631   /* Count the control characters */
   1632   for(i=0; (c = zIn[i])!=0; i++){
   1633     if( c<=0x1f
   1634      && c!='\t'
   1635      && c!='\n'
   1636      && (c!='\r' || zIn[i+1]!='\n')
   1637     ){
   1638       nCtrl++;
   1639     }
   1640   }
   1641   if( nCtrl==0 ) return;  /* Early out if no control characters */
   1642 
   1643   /* Make space to hold the escapes.  Copy the original text to the end
   1644   ** of the available space. */
   1645   sz = sqlite3_str_length(pStr) - iStart;
   1646   if( eEsc==QRF_ESC_Symbol ) nCtrl *= 2;
   1647   sqlite3_str_appendchar(pStr, nCtrl, ' ');
   1648   zOut = (unsigned char*)sqlite3_str_value(pStr);
   1649   if( zOut==0 ) return;
   1650   zOut += iStart;
   1651   zIn = zOut + nCtrl;
   1652   memmove(zIn,zOut,sz);
   1653 
   1654   /* Convert the control characters */
   1655   for(i=j=0; (c = zIn[i])!=0; i++){
   1656     if( c>0x1f
   1657      || c=='\t'
   1658      || c=='\n'
   1659      || (c=='\r' && zIn[i+1]=='\n')
   1660     ){
   1661       continue;
   1662     }
   1663     if( i>0 ){
   1664       memmove(&zOut[j], zIn, i);
   1665       j += i;
   1666     }
   1667     zIn += i+1;
   1668     i = -1;
   1669     if( eEsc==QRF_ESC_Symbol ){
   1670       zOut[j++] = 0xe2;
   1671       zOut[j++] = 0x90;
   1672       zOut[j++] = 0x80+c;
   1673     }else{
   1674       zOut[j++] = '^';
   1675       zOut[j++] = 0x40+c;
   1676     }
   1677   }
   1678 }
   1679 
   1680 /*
   1681 ** Determine if the string z[] can be shown as plain text.  Return true
   1682 ** if z[] is unambiguously text.  Return false if z[] needs to be
   1683 ** quoted.
   1684 **
   1685 ** All of the following must be true in order for z[] to be relaxable:
   1686 **
   1687 **    (1) z[] does not begin or end with ' or whitespace
   1688 **    (2) z[] is not the same as the NULL rendering
   1689 **    (3) z[] does not looks like a numeric literal
   1690 */
   1691 static int qrfRelaxable(Qrf *p, const char *z){
   1692   size_t i, n;
   1693   if( z[0]=='\'' || qrfSpace(z[0]) ) return 0;
   1694   if( z[0]==0 ){
   1695     return (p->spec.zNull!=0 && p->spec.zNull[0]!=0);
   1696   }
   1697   n = strlen(z);
   1698   if( n==0 || z[n-1]=='\'' || qrfSpace(z[n-1]) ) return 0;
   1699   if( p->spec.zNull && strcmp(p->spec.zNull,z)==0 ) return 0;
   1700   i = (z[0]=='-' || z[0]=='+');
   1701   if( strcmp(z+i,"Inf")==0 ) return 0;
   1702   if( !qrfDigit(z[i]) ) return 1;
   1703   i++;
   1704   while( qrfDigit(z[i]) ){ i++; }
   1705   if( z[i]==0 ) return 0;
   1706   if( z[i]=='.' ){
   1707     i++;
   1708     while( qrfDigit(z[i]) ){ i++; }
   1709     if( z[i]==0 ) return 0;
   1710   }
   1711   if( z[i]=='e' || z[i]=='E' ){
   1712     i++;
   1713     if( z[i]=='+' || z[i]=='-' ){ i++; }
   1714     if( !qrfDigit(z[i]) ) return 1;
   1715     i++;
   1716     while( qrfDigit(z[i]) ){ i++; }
   1717   }
   1718   return z[i]!=0;
   1719 }
   1720 
   1721 /*
   1722 ** If a field contains any character identified by a 1 in the following
   1723 ** array, then the string must be quoted for CSV.
   1724 */
   1725 static const char qrfCsvQuote[] = {
   1726   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1727   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1728   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
   1729   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   1730   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   1731   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   1732   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   1733   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
   1734   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1735   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1736   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1737   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1738   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1739   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1740   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1741   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   1742 };
   1743 
   1744 /*
   1745 ** Encode text appropriately and append it to pOut.
   1746 */
   1747 static void qrfEncodeText(Qrf *p, sqlite3_str *pOut, const char *zTxt){
   1748   int iStart = sqlite3_str_length(pOut);
   1749   switch( p->spec.eText ){
   1750     case QRF_TEXT_Relaxed:
   1751       if( qrfRelaxable(p, zTxt) ){
   1752         sqlite3_str_appendall(pOut, zTxt);
   1753         break;
   1754       }
   1755       deliberate_fall_through; /* FALLTHRU */
   1756     case QRF_TEXT_Sql: {
   1757       if( p->spec.eEsc==QRF_ESC_Off ){
   1758         sqlite3_str_appendf(pOut, "%Q", zTxt);
   1759       }else{
   1760         sqlite3_str_appendf(pOut, "%#Q", zTxt);
   1761       }
   1762       break;
   1763     }
   1764     case QRF_TEXT_Csv: {
   1765       unsigned int i;
   1766       for(i=0; zTxt[i]; i++){
   1767         if( qrfCsvQuote[((const unsigned char*)zTxt)[i]] ){
   1768           i = 0;
   1769           break;
   1770         }
   1771       }
   1772       if( i==0 || strstr(zTxt, p->spec.zColumnSep)!=0 ){
   1773         sqlite3_str_appendf(pOut, "\"%w\"", zTxt);
   1774       }else{
   1775         sqlite3_str_appendall(pOut, zTxt);
   1776       }
   1777       break;
   1778     }
   1779     case QRF_TEXT_Html: {
   1780       const unsigned char *z = (const unsigned char*)zTxt;
   1781       while( *z ){
   1782         unsigned int i = 0;
   1783         unsigned char c;
   1784         while( (c=z[i])>'>'
   1785             || (c && c!='<' && c!='>' && c!='&' && c!='\"' && c!='\'')
   1786         ){
   1787           i++;
   1788         }
   1789         if( i>0 ){
   1790           sqlite3_str_append(pOut, (const char*)z, i);
   1791         }
   1792         switch( z[i] ){
   1793           case '>':   sqlite3_str_append(pOut, "&lt;", 4);   break;
   1794           case '&':   sqlite3_str_append(pOut, "&amp;", 5);  break;
   1795           case '<':   sqlite3_str_append(pOut, "&lt;", 4);   break;
   1796           case '"':   sqlite3_str_append(pOut, "&quot;", 6); break;
   1797           case '\'':  sqlite3_str_append(pOut, "&#39;", 5);  break;
   1798           default:    i--;
   1799         }
   1800         z += i + 1;
   1801       }
   1802       break;
   1803     }
   1804     case QRF_TEXT_Tcl:
   1805     case QRF_TEXT_Json: {
   1806       const unsigned char *z = (const unsigned char*)zTxt;
   1807       sqlite3_str_append(pOut, "\"", 1);
   1808       while( *z ){
   1809         unsigned int i;
   1810         for(i=0; z[i]>=0x20 && z[i]!='\\' && z[i]!='"'; i++){}
   1811         if( i>0 ){
   1812           sqlite3_str_append(pOut, (const char*)z, i);
   1813         }
   1814         if( z[i]==0 ) break;
   1815         switch( z[i] ){
   1816           case '"':   sqlite3_str_append(pOut, "\\\"", 2);  break;
   1817           case '\\':  sqlite3_str_append(pOut, "\\\\", 2);  break;
   1818           case '\b':  sqlite3_str_append(pOut, "\\b", 2);   break;
   1819           case '\f':  sqlite3_str_append(pOut, "\\f", 2);   break;
   1820           case '\n':  sqlite3_str_append(pOut, "\\n", 2);   break;
   1821           case '\r':  sqlite3_str_append(pOut, "\\r", 2);   break;
   1822           case '\t':  sqlite3_str_append(pOut, "\\t", 2);   break;
   1823           default: {
   1824             if( p->spec.eText==QRF_TEXT_Json ){
   1825               sqlite3_str_appendf(pOut, "\\u%04x", z[i]);
   1826             }else{
   1827               sqlite3_str_appendf(pOut, "\\%03o", z[i]);
   1828             }
   1829             break;
   1830           }
   1831         }
   1832         z += i + 1;
   1833       }
   1834       sqlite3_str_append(pOut, "\"", 1);
   1835       break;
   1836     }
   1837     default: {
   1838       sqlite3_str_appendall(pOut, zTxt);
   1839       break;
   1840     }
   1841   }
   1842   if( p->spec.eEsc!=QRF_ESC_Off ){
   1843     qrfEscape(p->spec.eEsc, pOut, iStart);
   1844   }
   1845 }
   1846 
   1847 /*
   1848 ** Do a quick sanity check to see aBlob[0..nBlob-1] is valid JSONB
   1849 ** return true if it is and false if it is not.
   1850 **
   1851 ** False positives are possible, but not false negatives.
   1852 */
   1853 static int qrfJsonbQuickCheck(unsigned char *aBlob, int nBlob){
   1854   unsigned char x;   /* Payload size half-byte */
   1855   int i;             /* Loop counter */
   1856   int n;             /* Bytes in the payload size integer */
   1857   sqlite3_uint64 sz; /* value of the payload size integer */
   1858 
   1859   if( nBlob==0 ) return 0;
   1860   x = aBlob[0]>>4;
   1861   if( x<=11 ) return nBlob==(1+x);
   1862   n = x<14 ? x-11 : 4*(x-13);
   1863   if( nBlob<1+n ) return 0;
   1864   sz = aBlob[1];
   1865   for(i=1; i<n; i++) sz = (sz<<8) + aBlob[i+1];
   1866   return sz+n+1==(sqlite3_uint64)nBlob;
   1867 }
   1868 
   1869 /*
   1870 ** The current iCol-th column of p->pStmt is known to be a BLOB.  Check
   1871 ** to see if that BLOB is really a JSONB blob.  If it is, then translate
   1872 ** it into a text JSON representation and return a pointer to that text JSON.
   1873 ** If the BLOB is not JSONB, then return a NULL pointer.
   1874 **
   1875 ** The memory used to hold the JSON text is managed internally by the
   1876 ** "p" object and is overwritten and/or deallocated upon the next call
   1877 ** to this routine (with the same p argument) or when the p object is
   1878 ** finailized.
   1879 */
   1880 static const char *qrfJsonbToJson(Qrf *p, int iCol){
   1881   int nByte;
   1882   const void *pBlob;
   1883   int rc;
   1884   nByte = sqlite3_column_bytes(p->pStmt, iCol);
   1885   pBlob = sqlite3_column_blob(p->pStmt, iCol);
   1886   if( qrfJsonbQuickCheck((unsigned char*)pBlob, nByte)==0 ){
   1887     return 0;
   1888   }
   1889   if( p->pJTrans==0 ){
   1890     sqlite3 *db;
   1891     rc = sqlite3_open(":memory:",&db);
   1892     if( rc ){
   1893       sqlite3_close(db);
   1894       return 0;
   1895     }
   1896     rc = sqlite3_prepare_v2(db, "SELECT json(?1)", -1, &p->pJTrans, 0);
   1897     if( rc ){
   1898       sqlite3_finalize(p->pJTrans);
   1899       p->pJTrans = 0;
   1900       sqlite3_close(db);
   1901       return 0;
   1902     }
   1903   }else{
   1904     sqlite3_reset(p->pJTrans);
   1905   }
   1906   sqlite3_bind_blob(p->pJTrans, 1, (void*)pBlob, nByte, SQLITE_STATIC);
   1907   rc = sqlite3_step(p->pJTrans);
   1908   if( rc==SQLITE_ROW ){
   1909     return (const char*)sqlite3_column_text(p->pJTrans, 0);
   1910   }else{
   1911     return 0;
   1912   }
   1913 }
   1914 
   1915 /*
   1916 ** Adjust the input string zIn[] such that it is no more than N display
   1917 ** characters wide.  If it is wider than that, then truncate and add
   1918 ** ellipsis.  Or if zIn[] contains a \r or \n, truncate at that point,
   1919 ** adding ellipsis.  Embedded tabs in zIn[] are converted into ordinary
   1920 ** spaces.
   1921 **
   1922 ** Return this display width of the modified title string.
   1923 */
   1924 static int qrfTitleLimit(char *zIn, int N){
   1925   unsigned char *z = (unsigned char*)zIn;
   1926   int n = 0;
   1927   unsigned char *zEllipsis = 0;
   1928   while( 1 /*exit-by-break*/ ){
   1929     if( z[0]<' ' ){
   1930       int k;
   1931       if( z[0]==0 ){
   1932         zEllipsis = 0;
   1933         break;
   1934       }else if( z[0]=='\033' && (k = qrfIsVt100(z))>0 ){
   1935         z += k;
   1936       }else if( z[0]=='\t' ){
   1937         z[0] = ' ';
   1938       }else if( z[0]=='\n' || z[0]=='\r' ){
   1939         z[0] = ' ';
   1940       }else{
   1941         z++;
   1942       }
   1943     }else if( (0x80&z[0])==0 ){
   1944       if( n>=(N-3) && zEllipsis==0 ) zEllipsis = z;
   1945       if( n==N ){ z[0] = 0; break; }
   1946       n++;
   1947       z++;
   1948     }else{
   1949       int u = 0;
   1950       int len = sqlite3_qrf_decode_utf8(z, &u);
   1951       if( n+len>(N-3) && zEllipsis==0 ) zEllipsis = z;
   1952       if( n+len>N ){ z[0] = 0; break; }
   1953       z += len;
   1954       n += sqlite3_qrf_wcwidth(u);
   1955     }
   1956   }
   1957   if( zEllipsis && N>=3 ) memcpy(zEllipsis,"...",4);
   1958   return n;
   1959 }
   1960 
   1961 
   1962 /*
   1963 ** Render value pVal into pOut
   1964 */
   1965 static void qrfRenderValue(Qrf *p, sqlite3_str *pOut, int iCol){
   1966 #if SQLITE_VERSION_NUMBER>=3052000
   1967   int iStartLen = sqlite3_str_length(pOut);
   1968 #endif
   1969   if( p->spec.xRender ){
   1970     sqlite3_value *pVal;
   1971     char *z;
   1972     pVal = sqlite3_value_dup(sqlite3_column_value(p->pStmt,iCol));
   1973     z = p->spec.xRender(p->spec.pRenderArg, pVal);
   1974     sqlite3_value_free(pVal);
   1975     if( z ){
   1976       sqlite3_str_appendall(pOut, z);
   1977       sqlite3_free(z);
   1978       return;
   1979     }
   1980   }
   1981   switch( sqlite3_column_type(p->pStmt,iCol) ){
   1982     case SQLITE_INTEGER: {
   1983       sqlite3_str_appendf(pOut, "%lld", sqlite3_column_int64(p->pStmt,iCol));
   1984       break;
   1985     }
   1986     case SQLITE_FLOAT: {
   1987       const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
   1988       sqlite3_str_appendall(pOut, zTxt);
   1989       break;
   1990     }
   1991     case SQLITE_BLOB: {
   1992       if( p->spec.bTextJsonb==QRF_Yes ){
   1993         const char *zJson = qrfJsonbToJson(p, iCol);
   1994         if( zJson ){
   1995           if( p->spec.eText==QRF_TEXT_Sql ){
   1996             sqlite3_str_append(pOut,"jsonb(",6);
   1997             qrfEncodeText(p, pOut, zJson);
   1998             sqlite3_str_append(pOut,")",1);
   1999           }else{
   2000             qrfEncodeText(p, pOut, zJson);
   2001           }
   2002           break;
   2003         }
   2004       }
   2005       switch( p->spec.eBlob ){
   2006         case QRF_BLOB_Hex:
   2007         case QRF_BLOB_Sql: {
   2008           int iStart;
   2009           int nBlob = sqlite3_column_bytes(p->pStmt,iCol);
   2010           int i, j;
   2011           char *zVal;
   2012           const unsigned char *a = sqlite3_column_blob(p->pStmt,iCol);
   2013           if( p->spec.eBlob==QRF_BLOB_Sql ){
   2014             sqlite3_str_append(pOut, "x'", 2);
   2015           }
   2016           iStart = sqlite3_str_length(pOut);
   2017           sqlite3_str_appendchar(pOut, nBlob, ' ');
   2018           sqlite3_str_appendchar(pOut, nBlob, ' ');
   2019           if( p->spec.eBlob==QRF_BLOB_Sql ){
   2020             sqlite3_str_appendchar(pOut, 1, '\'');
   2021           }
   2022           if( sqlite3_str_errcode(pOut) ) return;
   2023           zVal = sqlite3_str_value(pOut);
   2024           for(i=0, j=iStart; i<nBlob; i++, j+=2){
   2025             unsigned char c = a[i];
   2026             zVal[j] = "0123456789abcdef"[(c>>4)&0xf];
   2027             zVal[j+1] = "0123456789abcdef"[(c)&0xf];
   2028           }
   2029           break;
   2030         }
   2031         case QRF_BLOB_Tcl:
   2032         case QRF_BLOB_Json: {
   2033           int iStart;
   2034           int nBlob = sqlite3_column_bytes(p->pStmt,iCol);
   2035           int i, j;
   2036           char *zVal;
   2037           const unsigned char *a = sqlite3_column_blob(p->pStmt,iCol);
   2038           int szC = p->spec.eBlob==QRF_BLOB_Json ? 6 : 4;
   2039           sqlite3_str_append(pOut, "\"", 1);
   2040           iStart = sqlite3_str_length(pOut);
   2041           for(i=szC; i>0; i--){
   2042             sqlite3_str_appendchar(pOut, nBlob, ' ');
   2043           }
   2044           sqlite3_str_appendchar(pOut, 1, '"');
   2045           if( sqlite3_str_errcode(pOut) ) return;
   2046           zVal = sqlite3_str_value(pOut);
   2047           for(i=0, j=iStart; i<nBlob; i++, j+=szC){
   2048             unsigned char c = a[i];
   2049             zVal[j] = '\\';
   2050             if( szC==4 ){
   2051               zVal[j+1] = '0' + ((c>>6)&3);
   2052               zVal[j+2] = '0' + ((c>>3)&7);
   2053               zVal[j+3] = '0' + (c&7);
   2054             }else{
   2055               zVal[j+1] = 'u';
   2056               zVal[j+2] = '0';
   2057               zVal[j+3] = '0';
   2058               zVal[j+4] = "0123456789abcdef"[(c>>4)&0xf];
   2059               zVal[j+5] = "0123456789abcdef"[(c)&0xf];
   2060             }
   2061           }
   2062           break;
   2063         }
   2064         case QRF_BLOB_Size: {
   2065           int nBlob = sqlite3_column_bytes(p->pStmt,iCol);
   2066           sqlite3_str_appendf(pOut, "(%d-byte blob)", nBlob);
   2067           break;
   2068         }
   2069         default: {
   2070           const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
   2071           qrfEncodeText(p, pOut, zTxt);
   2072         }
   2073       }
   2074       break;
   2075     }
   2076     case SQLITE_NULL: {
   2077       sqlite3_str_appendall(pOut, p->spec.zNull);
   2078       break;
   2079     }
   2080     case SQLITE_TEXT: {
   2081       const char *zTxt = (const char*)sqlite3_column_text(p->pStmt,iCol);
   2082       qrfEncodeText(p, pOut, zTxt);
   2083       break;
   2084     }
   2085   }
   2086 #if SQLITE_VERSION_NUMBER>=3052000
   2087   if( p->spec.nCharLimit>0
   2088    && (sqlite3_str_length(pOut) - iStartLen) > p->spec.nCharLimit
   2089   ){
   2090     const unsigned char *z;
   2091     int ii = 0, w = 0, limit = p->spec.nCharLimit;
   2092     z = (const unsigned char*)sqlite3_str_value(pOut) + iStartLen;
   2093     if( limit<4 ) limit = 4;
   2094     while( 1 ){
   2095       if( z[ii]<' ' ){
   2096         int k;
   2097         if( z[ii]=='\033' && (k = qrfIsVt100(z+ii))>0 ){
   2098           ii += k;
   2099         }else if( z[ii]==0 ){
   2100           break;
   2101         }else{
   2102           ii++;
   2103         }
   2104       }else if( (0x80&z[ii])==0 ){
   2105         w++;
   2106         if( w>limit ) break;
   2107         ii++;
   2108       }else{
   2109         int u = 0;
   2110         int len = sqlite3_qrf_decode_utf8(&z[ii], &u);
   2111         w += sqlite3_qrf_wcwidth(u);
   2112         if( w>limit ) break;
   2113         ii += len;
   2114       }
   2115     }
   2116     if( w>limit ){
   2117       sqlite3_str_truncate(pOut, iStartLen+ii);
   2118       sqlite3_str_append(pOut, "...", 3);
   2119     }
   2120   }
   2121 #endif
   2122 }
   2123 
   2124 /* Trim spaces of the end if pOut
   2125 */
   2126 static void qrfRTrim(sqlite3_str *pOut){
   2127 #if SQLITE_VERSION_NUMBER>=3052000
   2128   int nByte = sqlite3_str_length(pOut);
   2129   const char *zOut = sqlite3_str_value(pOut);
   2130   while( nByte>0 && zOut[nByte-1]==' ' ){ nByte--; }
   2131   sqlite3_str_truncate(pOut, nByte);
   2132 #endif
   2133 }
   2134 
   2135 /*
   2136 ** Store string zUtf to pOut as w characters.  If w is negative,
   2137 ** then right-justify the text.  W is the width in display characters, not
   2138 ** in bytes.  Double-width unicode characters count as two characters.
   2139 ** VT100 escape sequences count as zero.  And so forth.
   2140 */
   2141 static void qrfWidthPrint(Qrf *p, sqlite3_str *pOut, int w, const char *zUtf){
   2142   const unsigned char *a = (const unsigned char*)zUtf;
   2143   static const int mxW = 10000000;
   2144   unsigned char c;
   2145   int i = 0;
   2146   int n = 0;
   2147   int k;
   2148   int aw;
   2149   (void)p;
   2150   if( w<-mxW ){
   2151     w = -mxW;
   2152   }else if( w>mxW ){
   2153     w= mxW;
   2154   }
   2155   aw = w<0 ? -w : w;
   2156   if( a==0 ) a = (const unsigned char*)"";
   2157   while( (c = a[i])!=0 ){
   2158     if( (c&0xc0)==0xc0 ){
   2159       int u;
   2160       int len = sqlite3_qrf_decode_utf8(a+i, &u);
   2161       int x = sqlite3_qrf_wcwidth(u);
   2162       if( x+n>aw ){
   2163         break;
   2164       }
   2165       i += len;
   2166       n += x;
   2167     }else if( c==0x1b && (k = qrfIsVt100(&a[i]))>0 ){
   2168       i += k;
   2169     }else if( n>=aw ){
   2170       break;
   2171     }else{
   2172       n++;
   2173       i++;
   2174     }
   2175   }
   2176   if( n>=aw ){
   2177     sqlite3_str_append(pOut, zUtf, i);
   2178   }else if( w<0 ){
   2179     if( aw>n ) sqlite3_str_appendchar(pOut, aw-n, ' ');
   2180     sqlite3_str_append(pOut, zUtf, i);
   2181   }else{
   2182     sqlite3_str_append(pOut, zUtf, i);
   2183     if( aw>n ) sqlite3_str_appendchar(pOut, aw-n, ' ');
   2184   }
   2185 }
   2186 
   2187 /*
   2188 ** (*pz)[] is a line of text that is to be displayed the box or table or
   2189 ** similar tabular formats.  z[] contain newlines or might be too wide
   2190 ** to fit in the columns so will need to be split into multiple line.
   2191 **
   2192 ** This routine determines:
   2193 **
   2194 **    *  How many bytes of z[] should be shown on the current line.
   2195 **    *  How many character positions those bytes will cover.
   2196 **    *  The byte offset to the start of the next line.
   2197 */
   2198 static void qrfWrapLine(
   2199   const char *zIn,   /* Input text to be displayed */
   2200   int w,             /* Column width in characters (not bytes) */
   2201   int bWrap,         /* True if we should do word-wrapping */
   2202   int *pnThis,       /* OUT: How many bytes of z[] for the current line */
   2203   int *pnWide,       /* OUT: How wide is the text of this line */
   2204   int *piNext        /* OUT: Offset into z[] to start of the next line */
   2205 ){
   2206   int i;                 /* Input bytes consumed */
   2207   int k;                 /* Bytes in a VT100 code */
   2208   int n;                 /* Output column number */
   2209   const unsigned char *z = (const unsigned char*)zIn;
   2210   unsigned char c = 0;
   2211 
   2212   if( z[0]==0 ){
   2213     *pnThis = 0;
   2214     *pnWide = 0;
   2215     *piNext = 0;
   2216     return;
   2217   }
   2218   n = 0;
   2219   for(i=0; n<=w; i++){
   2220     c = z[i];
   2221     if( c>=0xc0 ){
   2222       int u;
   2223       int len = sqlite3_qrf_decode_utf8(&z[i], &u);
   2224       int wcw = sqlite3_qrf_wcwidth(u);
   2225       if( wcw+n>w ) break;
   2226       i += len-1;
   2227       n += wcw;
   2228       continue;
   2229     }
   2230     if( c>=' ' ){
   2231       if( n==w ) break;
   2232       n++;
   2233       continue;
   2234     }
   2235     if( c==0 || c=='\n' ) break;
   2236     if( c=='\r' && z[i+1]=='\n' ){ c = z[++i]; break; }
   2237     if( c=='\t' ){
   2238       int wcw = 8 - (n&7);
   2239       if( n+wcw>w ) break;
   2240       n += wcw;
   2241       continue;
   2242     }
   2243     if( c==0x1b && (k = qrfIsVt100(&z[i]))>0 ){
   2244       i += k-1;
   2245     }else if( n==w ){
   2246       break;
   2247     }else{
   2248       n++;
   2249     }
   2250   }
   2251   if( c==0 ){
   2252     *pnThis = i;
   2253     *pnWide = n;
   2254     *piNext = i;
   2255     return;
   2256   }
   2257   if( c=='\n' ){
   2258     *pnThis = i;
   2259     *pnWide = n;
   2260     *piNext = i+1;
   2261     return;
   2262   }
   2263 
   2264   /* If we get this far, that means the current line will end at some
   2265   ** point that is neither a "\n" or a 0x00.  Figure out where that
   2266   ** split should occur
   2267   */
   2268   if( bWrap && z[i]!=0 && !qrfSpace(z[i]) && qrfAlnum(c)==qrfAlnum(z[i]) ){
   2269     /* Perhaps try to back up to a better place to break the line */
   2270     for(k=i-1; k>=i/2; k--){
   2271       if( qrfSpace(z[k]) ) break;
   2272     }
   2273     if( k<i/2 ){
   2274       for(k=i; k>=i/2; k--){
   2275         if( qrfAlnum(z[k-1])!=qrfAlnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
   2276       }
   2277     }
   2278     if( k>=i/2 ){
   2279       i = k;
   2280       n = qrfDisplayWidth((const char*)z, k, 0);
   2281     }
   2282   }
   2283   *pnThis = i;
   2284   *pnWide = n;
   2285   while( zIn[i]==' ' || zIn[i]=='\t' || zIn[i]=='\r' ){ i++; }
   2286   *piNext = i;
   2287 }
   2288 
   2289 /*
   2290 ** Append nVal bytes of text from zVal onto the end of pOut.
   2291 ** Convert tab characters in zVal to the appropriate number of
   2292 ** spaces.
   2293 */
   2294 static void qrfAppendWithTabs(
   2295   sqlite3_str *pOut,       /* Append text here */
   2296   const char *zVal,        /* Text to append */
   2297   int nVal                 /* Use only the first nVal bytes of zVal[] */
   2298 ){
   2299   int i = 0;
   2300   unsigned int col = 0;
   2301   unsigned char *z = (unsigned char *)zVal;
   2302   while( i<nVal ){
   2303     unsigned char c = z[i];
   2304     if( c<' ' ){
   2305       int k;
   2306       sqlite3_str_append(pOut, (const char*)z, i);
   2307       nVal -= i;
   2308       z += i;
   2309       i = 0;
   2310       if( c=='\033' && (k = qrfIsVt100(z))>0 ){
   2311         sqlite3_str_append(pOut, (const char*)z, k);
   2312         z += k;
   2313         nVal -= k;
   2314       }else if( c=='\t' ){
   2315         k = 8 - (col&7);
   2316         sqlite3_str_appendchar(pOut, k, ' ');
   2317         col += k;
   2318         z++;
   2319         nVal--;
   2320       }else if( c=='\r' && nVal==1 ){
   2321         z++;
   2322         nVal--;
   2323       }else{
   2324         char zCtrlPik[4];
   2325         col++;
   2326         zCtrlPik[0] = 0xe2;
   2327         zCtrlPik[1] = 0x90;
   2328         zCtrlPik[2] = 0x80+c;
   2329         sqlite3_str_append(pOut, zCtrlPik, 3);
   2330         z++;
   2331         nVal--;
   2332       }
   2333     }else if( (0x80&c)==0 ){
   2334       i++;
   2335       col++;
   2336     }else{
   2337       int u = 0;
   2338       int len = sqlite3_qrf_decode_utf8(&z[i], &u);
   2339       i += len;
   2340       col += sqlite3_qrf_wcwidth(u);
   2341     }
   2342   }
   2343   sqlite3_str_append(pOut, (const char*)z, i);
   2344 }
   2345 
   2346 /*
   2347 ** GCC does not define the offsetof() macro so we'll have to do it
   2348 ** ourselves.
   2349 */
   2350 #ifndef offsetof
   2351 # define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))
   2352 #endif
   2353 
   2354 /*
   2355 ** Data for columnar layout, collected into a single object so
   2356 ** that it can be more easily passed into subroutines.
   2357 */
   2358 typedef struct qrfColData qrfColData;
   2359 struct qrfColData {
   2360   Qrf *p;                  /* The QRF instance */
   2361   int nCol;                /* Number of columns in the table */
   2362   unsigned char bMultiRow; /* One or more cells will span multiple lines */
   2363   unsigned char nMargin;   /* Width of column margins */
   2364   sqlite3_int64 nRow;      /* Number of rows */
   2365   sqlite3_int64 nAlloc;    /* Number of cells allocated */
   2366   sqlite3_int64 n;         /* Number of cells.  nCol*nRow */
   2367   char **az;               /* Content of all cells */
   2368   int *aiWth;              /* Width of each cell */
   2369   unsigned char *abNum;    /* True for each numeric cell */
   2370   struct qrfPerCol {       /* Per-column data */
   2371     char *z;                 /* Cache of text for current row */
   2372     int w;                   /* Computed width of this column */
   2373     int mxW;                 /* Maximum natural (unwrapped) width */
   2374     unsigned char e;         /* Alignment */
   2375     unsigned char fx;        /* Width is fixed */
   2376     unsigned char bNum;      /* True if is numeric */
   2377   } *a;                    /* One per column */
   2378 };
   2379 
   2380 /*
   2381 ** Output horizontally justified text into pOut.  The text is the
   2382 ** first nVal bytes of zVal.  Include nWS bytes of whitespace, either
   2383 ** split between both sides, or on the left, or on the right, depending
   2384 ** on eAlign.
   2385 */
   2386 static void qrfPrintAligned(
   2387   sqlite3_str *pOut,       /* Append text here */
   2388   struct qrfPerCol *pCol,  /* Information about the text to print */
   2389   int nVal,                /* Use only the first nVal bytes of zVal[] */
   2390   int nWS                 /* Whitespace for horizonal alignment */
   2391 ){
   2392   unsigned char eAlign = pCol->e & QRF_ALIGN_HMASK;
   2393   if( eAlign==QRF_Auto && pCol->bNum ) eAlign = QRF_ALIGN_Right;
   2394   if( eAlign==QRF_ALIGN_Center ){
   2395     /* Center the text */
   2396     sqlite3_str_appendchar(pOut, nWS/2, ' ');
   2397     qrfAppendWithTabs(pOut, pCol->z, nVal);
   2398     sqlite3_str_appendchar(pOut, nWS - nWS/2, ' ');
   2399   }else if( eAlign==QRF_ALIGN_Right ){
   2400     /* Right justify the text */
   2401     sqlite3_str_appendchar(pOut, nWS, ' ');
   2402     qrfAppendWithTabs(pOut, pCol->z, nVal);
   2403   }else{
   2404     /* Left justify the text */
   2405     qrfAppendWithTabs(pOut, pCol->z, nVal);
   2406     sqlite3_str_appendchar(pOut, nWS, ' ');
   2407   }
   2408 }
   2409 
   2410 /*
   2411 ** Free all the memory allocates in the qrfColData object
   2412 */
   2413 static void qrfColDataFree(qrfColData *p){
   2414   sqlite3_int64 i;
   2415   for(i=0; i<p->n; i++) sqlite3_free(p->az[i]);
   2416   sqlite3_free(p->az);
   2417   sqlite3_free(p->aiWth);
   2418   sqlite3_free(p->abNum);
   2419   sqlite3_free(p->a);
   2420   memset(p, 0, sizeof(*p));
   2421 }
   2422 
   2423 /*
   2424 ** Allocate space for more cells in the qrfColData object.
   2425 ** Return non-zero if a memory allocation fails.
   2426 */
   2427 static int qrfColDataEnlarge(qrfColData *p){
   2428   char **azData;
   2429   int *aiWth;
   2430   unsigned char *abNum;
   2431   p->nAlloc = 2*p->nAlloc + 10*p->nCol;
   2432   azData = sqlite3_realloc64(p->az, p->nAlloc*sizeof(char*));
   2433   if( azData==0 ){
   2434     qrfOom(p->p);
   2435     qrfColDataFree(p);
   2436     return 1;
   2437   }
   2438   p->az = azData;
   2439   aiWth = sqlite3_realloc64(p->aiWth, p->nAlloc*sizeof(int));
   2440   if( aiWth==0 ){
   2441     qrfOom(p->p);
   2442     qrfColDataFree(p);
   2443     return 1;
   2444   }
   2445   p->aiWth = aiWth;
   2446   abNum = sqlite3_realloc64(p->abNum, p->nAlloc);
   2447   if( abNum==0 ){
   2448     qrfOom(p->p);
   2449     qrfColDataFree(p);
   2450     return 1;
   2451   }
   2452   p->abNum = abNum;
   2453   return 0;
   2454 }
   2455 
   2456 /*
   2457 ** Print a markdown or table-style row separator using ascii-art
   2458 */
   2459 static void qrfRowSeparator(sqlite3_str *pOut, qrfColData *p, char cSep){
   2460   int i;
   2461   if( p->nCol>0 ){
   2462     int useBorder = p->p->spec.bBorder!=QRF_No;
   2463     if( useBorder ){
   2464       sqlite3_str_append(pOut, &cSep, 1);
   2465     }
   2466     sqlite3_str_appendchar(pOut, p->a[0].w+p->nMargin, '-');
   2467     for(i=1; i<p->nCol; i++){
   2468       sqlite3_str_append(pOut, &cSep, 1);
   2469       sqlite3_str_appendchar(pOut, p->a[i].w+p->nMargin, '-');
   2470     }
   2471     if( useBorder ){
   2472       sqlite3_str_append(pOut, &cSep, 1);
   2473     }
   2474   }
   2475   sqlite3_str_append(pOut, "\n", 1);
   2476 }
   2477 
   2478 /*
   2479 ** UTF8 box-drawing characters.  Imagine box lines like this:
   2480 **
   2481 **           1
   2482 **           |
   2483 **       4 --+-- 2
   2484 **           |
   2485 **           3
   2486 **
   2487 ** Each box characters has between 2 and 4 of the lines leading from
   2488 ** the center.  The characters are here identified by the numbers of
   2489 ** their corresponding lines.
   2490 */
   2491 #define BOX_24   "\342\224\200"  /* U+2500 --- */
   2492 #define BOX_13   "\342\224\202"  /* U+2502  |  */
   2493 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
   2494 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
   2495 #define BOX_12   "\342\224\224"  /* U+2514  '- */
   2496 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
   2497 #define BOX_123  "\342\224\234"  /* U+251c  |- */
   2498 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
   2499 #define BOX_234  "\342\224\254"  /* U+252c -,- */
   2500 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
   2501 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
   2502 
   2503 /* Rounded corners: */
   2504 #define BOX_R12  "\342\225\260"  /* U+2570  '- */
   2505 #define BOX_R23  "\342\225\255"  /* U+256d  ,- */
   2506 #define BOX_R34  "\342\225\256"  /* U+256e -,  */
   2507 #define BOX_R14  "\342\225\257"  /* U+256f -'  */
   2508 
   2509 /* Doubled horizontal lines: */
   2510 #define DBL_24   "\342\225\220"  /* U+2550 === */
   2511 #define DBL_123  "\342\225\236"  /* U+255e  |= */
   2512 #define DBL_134  "\342\225\241"  /* U+2561 =|  */
   2513 #define DBL_1234 "\342\225\252"  /* U+256a =|= */
   2514 
   2515 /* Draw horizontal line N characters long using unicode box
   2516 ** characters
   2517 */
   2518 static void qrfBoxLine(sqlite3_str *pOut, int N, int bDbl){
   2519   const char *azDash[2] = {
   2520       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24   BOX_24 BOX_24 BOX_24 BOX_24 BOX_24,
   2521       DBL_24 DBL_24 DBL_24 DBL_24 DBL_24   DBL_24 DBL_24 DBL_24 DBL_24 DBL_24
   2522   };/*  0       1      2     3      4        5      6      7      8      9   */
   2523   const int nDash = 30;
   2524   N *= 3;
   2525   while( N>nDash ){
   2526     sqlite3_str_append(pOut, azDash[bDbl], nDash);
   2527     N -= nDash;
   2528   }
   2529   sqlite3_str_append(pOut, azDash[bDbl], N);
   2530 }
   2531 
   2532 /*
   2533 ** Draw a horizontal separator for a QRF_STYLE_Box table.
   2534 */
   2535 static void qrfBoxSeparator(
   2536   sqlite3_str *pOut,
   2537   qrfColData *p,
   2538   const char *zSep1,
   2539   const char *zSep2,
   2540   const char *zSep3,
   2541   int bDbl
   2542 ){
   2543   int i;
   2544   if( p->nCol>0 ){
   2545     int useBorder = p->p->spec.bBorder!=QRF_No;
   2546     if( useBorder ){
   2547       sqlite3_str_appendall(pOut, zSep1);
   2548     }
   2549     qrfBoxLine(pOut, p->a[0].w+p->nMargin, bDbl);
   2550     for(i=1; i<p->nCol; i++){
   2551       sqlite3_str_appendall(pOut, zSep2);
   2552       qrfBoxLine(pOut, p->a[i].w+p->nMargin, bDbl);
   2553     }
   2554     if( useBorder ){
   2555       sqlite3_str_appendall(pOut, zSep3);
   2556     }
   2557   }
   2558   sqlite3_str_append(pOut, "\n", 1);
   2559 }
   2560 
   2561 /*
   2562 ** Load into pData the default alignment for the body of a table.
   2563 */
   2564 static void qrfLoadAlignment(qrfColData *pData, Qrf *p){
   2565   sqlite3_int64 i;
   2566   for(i=0; i<pData->nCol; i++){
   2567     pData->a[i].e = p->spec.eDfltAlign;
   2568     if( i<p->spec.nAlign ){
   2569       unsigned char ax = p->spec.aAlign[i];
   2570       if( (ax & QRF_ALIGN_HMASK)!=0 ){
   2571         pData->a[i].e = (ax & QRF_ALIGN_HMASK) |
   2572                             (pData->a[i].e & QRF_ALIGN_VMASK);
   2573       }
   2574     }else if( i<p->spec.nWidth ){
   2575       if( p->spec.aWidth[i]<0 ){
   2576          pData->a[i].e = QRF_ALIGN_Right |
   2577                                (pData->a[i].e & QRF_ALIGN_VMASK);
   2578       }
   2579     }
   2580   }
   2581 }
   2582 
   2583 /*
   2584 ** If the single column in pData->a[] with pData->n entries can be
   2585 ** laid out as nCol columns with a 2-space gap between each such
   2586 ** that all columns fit within nSW, then return a pointer to an array
   2587 ** of integers which is the width of each column from left to right.
   2588 **
   2589 ** If the layout is not possible, return a NULL pointer.
   2590 **
   2591 ** Space to hold the returned array is from sqlite_malloc64().
   2592 */
   2593 static int *qrfValidLayout(
   2594   qrfColData *pData,   /* Collected query results */
   2595   Qrf *p,              /* On which to report an OOM */
   2596   int nCol,            /* Attempt this many columns */
   2597   int nSW              /* Screen width */
   2598 ){
   2599   int i;        /* Loop counter */
   2600   int nr;       /* Number of rows */
   2601   int w = 0;    /* Width of the current column */
   2602   int t;        /* Total width of all columns */
   2603   int *aw;      /* Array of individual column widths */
   2604 
   2605   aw = sqlite3_malloc64( sizeof(int)*nCol );
   2606   if( aw==0 ){
   2607     qrfOom(p);
   2608     return 0;
   2609   }
   2610   nr = (pData->n + nCol - 1)/nCol;
   2611   for(i=0; i<pData->n; i++){
   2612     if( (i%nr)==0 ){
   2613       if( i>0 ) aw[i/nr-1] = w;
   2614       w = pData->aiWth[i];
   2615     }else if( pData->aiWth[i]>w ){
   2616       w = pData->aiWth[i];
   2617     }
   2618   }
   2619   aw[nCol-1] = w;
   2620   for(t=i=0; i<nCol; i++) t += aw[i];
   2621   t += 2*(nCol-1);
   2622   if( t>nSW ){
   2623     sqlite3_free(aw);
   2624     return 0;
   2625   }
   2626   return aw;
   2627 }
   2628 
   2629 /*
   2630 ** The output is single-column and the bSplitColumn flag is set.
   2631 ** Check to see if the single-column output can be split into multiple
   2632 ** columns that appear side-by-side.  Adjust pData appropriately.
   2633 */
   2634 static void qrfSplitColumn(qrfColData *pData, Qrf *p){
   2635   int nCol = 1;
   2636   int *aw = 0;
   2637   char **az = 0;
   2638   int *aiWth = 0;
   2639   unsigned char *abNum = 0;
   2640   int nColNext = 2;
   2641   int w;
   2642   struct qrfPerCol *a = 0;
   2643   sqlite3_int64 nRow = 1;
   2644   sqlite3_int64 i;
   2645   while( 1/*exit-by-break*/ ){
   2646     int *awNew = qrfValidLayout(pData, p, nColNext, p->spec.nScreenWidth);
   2647     if( awNew==0 ) break;
   2648     sqlite3_free(aw);
   2649     aw = awNew;
   2650     nCol = nColNext;
   2651     nRow = (pData->n + nCol - 1)/nCol;
   2652     if( nRow==1 ) break;
   2653     nColNext++;
   2654     while( (pData->n + nColNext - 1)/nColNext == nRow ) nColNext++;
   2655   }
   2656   if( nCol==1 ){
   2657     sqlite3_free(aw);
   2658     return;  /* Cannot do better than 1 column */
   2659   }
   2660   az = sqlite3_malloc64( nRow*nCol*sizeof(char*) );
   2661   if( az==0 ){
   2662     qrfOom(p);
   2663     return;
   2664   }
   2665   aiWth = sqlite3_malloc64( nRow*nCol*sizeof(int) );
   2666   if( aiWth==0 ){
   2667     sqlite3_free(az);
   2668     qrfOom(p);
   2669     return;
   2670   }
   2671   a = sqlite3_malloc64( nCol*sizeof(struct qrfPerCol) );
   2672   if( a==0 ){
   2673     sqlite3_free(az);
   2674     sqlite3_free(aiWth);
   2675     qrfOom(p);
   2676     return;
   2677   }
   2678   abNum = sqlite3_malloc64( nRow*nCol );
   2679   if( abNum==0 ){
   2680     sqlite3_free(az);
   2681     sqlite3_free(aiWth);
   2682     sqlite3_free(a);
   2683     qrfOom(p);
   2684     return;
   2685   }
   2686   for(i=0; i<pData->n; i++){
   2687     sqlite3_int64 j = (i%nRow)*nCol + (i/nRow);
   2688     az[j] = pData->az[i];
   2689     abNum[j]= pData->abNum[i];
   2690     pData->az[i] = 0;
   2691     aiWth[j] = pData->aiWth[i];
   2692   }
   2693   while( i<nRow*nCol ){
   2694     sqlite3_int64 j = (i%nRow)*nCol + (i/nRow);
   2695     az[j] = sqlite3_mprintf("");
   2696     if( az[j]==0 ) qrfOom(p);
   2697     aiWth[j] = 0;
   2698     abNum[j] = 0;
   2699     i++;
   2700   }
   2701   for(i=0; i<nCol; i++){
   2702     a[i].fx = a[i].mxW = a[i].w = aw[i];
   2703     a[i].e = pData->a[0].e;
   2704   }
   2705   sqlite3_free(pData->az);
   2706   sqlite3_free(pData->aiWth);
   2707   sqlite3_free(pData->a);
   2708   sqlite3_free(pData->abNum);
   2709   sqlite3_free(aw);
   2710   pData->az = az;
   2711   pData->aiWth = aiWth;
   2712   pData->a = a;
   2713   pData->abNum = abNum;
   2714   pData->nCol = nCol;
   2715   pData->n = pData->nAlloc = nRow*nCol;
   2716   for(i=w=0; i<nCol; i++) w += a[i].w;
   2717   pData->nMargin = (p->spec.nScreenWidth - w)/(nCol - 1);
   2718   if( pData->nMargin>5 ) pData->nMargin = 5;
   2719 }
   2720 
   2721 /*
   2722 ** Adjust the layout for the screen width restriction
   2723 */
   2724 static void qrfRestrictScreenWidth(qrfColData *pData, Qrf *p){
   2725   int sepW;             /* Width of all box separators and margins */
   2726   int sumW;             /* Total width of data area over all columns */
   2727   int targetW;          /* Desired total data area */
   2728   int i;                /* Loop counters */
   2729   int nCol;             /* Number of columns */
   2730 
   2731   pData->nMargin = 2;   /* Default to normal margins */
   2732   if( p->spec.nScreenWidth==0 ) return;
   2733   if( p->spec.eStyle==QRF_STYLE_Column ){
   2734     sepW = pData->nCol*2 - 2;
   2735   }else{
   2736     sepW = pData->nCol*3 + 1;
   2737     if( p->spec.bBorder==QRF_No ) sepW -= 2;
   2738   }
   2739   nCol = pData->nCol;
   2740   for(i=sumW=0; i<nCol; i++) sumW += pData->a[i].w;
   2741   if( p->spec.nScreenWidth >= sumW+sepW ) return;
   2742 
   2743   /* First thing to do is reduce the separation between columns */
   2744   pData->nMargin = 0;
   2745   if( p->spec.eStyle==QRF_STYLE_Column ){
   2746     sepW = pData->nCol - 1;
   2747   }else{
   2748     sepW = pData->nCol + 1;
   2749     if( p->spec.bBorder==QRF_No ) sepW -= 2;
   2750   }
   2751   targetW = p->spec.nScreenWidth - sepW;
   2752 
   2753 #define MIN_SQUOZE    8
   2754 #define MIN_EX_SQUOZE 16
   2755   /* Reduce the width of the widest eligible column.  A column is
   2756   ** eligible for narrowing if:
   2757   **
   2758   **    *  It is not a fixed-width column  (a[0].fx is false)
   2759   **    *  The current width is more than MIN_SQUOZE
   2760   **    *  Either:
   2761   **         +  The current width is more then MIN_EX_SQUOZE, or
   2762   **         +  The current width is more than half the max width (a[].mxW)
   2763   **
   2764   ** Keep making reductions until either no more reductions are
   2765   ** possible or until the size target is reached.
   2766   */
   2767   while( sumW > targetW ){
   2768     int gain, w;
   2769     int ix = -1;
   2770     int mx = 0;
   2771     for(i=0; i<nCol; i++){
   2772       if( pData->a[i].fx==0
   2773        && (w = pData->a[i].w)>mx
   2774        && w>MIN_SQUOZE
   2775        && (w>MIN_EX_SQUOZE || w*2>pData->a[i].mxW)
   2776       ){
   2777         ix = i;
   2778         mx = w;
   2779       }
   2780     }
   2781     if( ix<0 ) break;
   2782     if( mx>=MIN_SQUOZE*2 ){
   2783       gain = mx/2;
   2784     }else{
   2785       gain = mx - MIN_SQUOZE;
   2786     }
   2787     if( sumW - gain < targetW ){
   2788       gain = sumW - targetW;
   2789     }
   2790     sumW -= gain;
   2791     pData->a[ix].w -= gain;
   2792     pData->bMultiRow = 1;
   2793   }
   2794 }
   2795 
   2796 /*
   2797 ** Columnar modes require that the entire query be evaluated first, with
   2798 ** results written into memory, so that we can compute appropriate column
   2799 ** widths.
   2800 */
   2801 static void qrfColumnar(Qrf *p){
   2802   sqlite3_int64 i, j;                     /* Loop counters */
   2803   const char *colSep = 0;                 /* Column separator text */
   2804   const char *rowSep = 0;                 /* Row terminator text */
   2805   const char *rowStart = 0;               /* Row start text */
   2806   int szColSep, szRowSep, szRowStart;     /* Size in bytes of previous 3 */
   2807   int rc;                                 /* Result code */
   2808   int nColumn = p->nCol;                  /* Number of columns */
   2809   int bWW;                                /* True to do word-wrap */
   2810   sqlite3_str *pStr;                      /* Temporary rendering */
   2811   qrfColData data;                        /* Columnar layout data */
   2812   int bRTrim;                             /* Trim trailing space */
   2813 
   2814   rc = sqlite3_step(p->pStmt);
   2815   if( rc!=SQLITE_ROW || nColumn==0 ){
   2816     return;   /* No output */
   2817   }
   2818 
   2819   /* Initialize the data container */
   2820   memset(&data, 0, sizeof(data));
   2821   data.nCol = p->nCol;
   2822   data.p = p;
   2823   data.a = sqlite3_malloc64( nColumn*sizeof(struct qrfPerCol) );
   2824   if( data.a==0 ){
   2825     qrfOom(p);
   2826     return;
   2827   }
   2828   memset(data.a, 0, nColumn*sizeof(struct qrfPerCol) );
   2829   if( qrfColDataEnlarge(&data) ) return;
   2830   assert( data.az!=0 );
   2831 
   2832   /* Load the column header names and all cell content into data */
   2833   if( p->spec.bTitles==QRF_Yes ){
   2834     unsigned char saved_eText = p->spec.eText;
   2835     p->spec.eText = p->spec.eTitle;
   2836     memset(data.abNum, 0, nColumn);
   2837     for(i=0; i<nColumn; i++){
   2838       const char *z = (const char*)sqlite3_column_name(p->pStmt,i);
   2839       int nNL = 0;
   2840       int n, w;
   2841       pStr = sqlite3_str_new(p->db);
   2842       qrfEncodeText(p, pStr, z ? z : "");
   2843       n = sqlite3_str_length(pStr);
   2844       qrfStrErr(p, pStr);
   2845       z = data.az[data.n] = sqlite3_str_finish(pStr);
   2846       if( p->spec.nTitleLimit ){
   2847         nNL = 0;
   2848         data.aiWth[data.n] = w = qrfTitleLimit(data.az[data.n],
   2849                                                p->spec.nTitleLimit );
   2850       }else{
   2851         data.aiWth[data.n] = w = qrfDisplayWidth(z, n, &nNL);
   2852       }
   2853       data.n++;
   2854       if( w>data.a[i].mxW ) data.a[i].mxW = w;
   2855       if( nNL ) data.bMultiRow = 1;
   2856     }
   2857     p->spec.eText = saved_eText;
   2858     p->nRow++;
   2859   }
   2860   do{
   2861     if( data.n+nColumn > data.nAlloc ){
   2862       if( qrfColDataEnlarge(&data) ) return;
   2863     }
   2864     for(i=0; i<nColumn; i++){
   2865       char *z;
   2866       int nNL = 0;
   2867       int n, w;
   2868       int eType = sqlite3_column_type(p->pStmt,i);
   2869       pStr = sqlite3_str_new(p->db);
   2870       qrfRenderValue(p, pStr, i);
   2871       n = sqlite3_str_length(pStr);
   2872       qrfStrErr(p, pStr);
   2873       z = data.az[data.n] = sqlite3_str_finish(pStr);
   2874       data.abNum[data.n] = eType==SQLITE_INTEGER || eType==SQLITE_FLOAT;
   2875       data.aiWth[data.n] = w = qrfDisplayWidth(z, n, &nNL);
   2876       data.n++;
   2877       if( w>data.a[i].mxW ) data.a[i].mxW = w;
   2878       if( nNL ) data.bMultiRow = 1;
   2879     }
   2880     p->nRow++;
   2881   }while( sqlite3_step(p->pStmt)==SQLITE_ROW && p->iErr==SQLITE_OK );
   2882   if( p->iErr ){
   2883     qrfColDataFree(&data);
   2884     return;
   2885   }
   2886 
   2887   /* Compute the width and alignment of every column */
   2888   if( p->spec.bTitles==QRF_No ){
   2889     qrfLoadAlignment(&data, p);
   2890   }else{
   2891     unsigned char e;
   2892     if( p->spec.eTitleAlign==QRF_Auto ){
   2893       e = QRF_ALIGN_Center;
   2894     }else{
   2895       e = p->spec.eTitleAlign;
   2896     }
   2897     for(i=0; i<nColumn; i++) data.a[i].e = e;
   2898   }
   2899 
   2900   for(i=0; i<nColumn; i++){
   2901     int w = 0;
   2902     if( i<p->spec.nWidth ){
   2903       w = p->spec.aWidth[i];
   2904       if( w==(-32768) ){
   2905         w = 0;
   2906         if( p->spec.nAlign>i && (p->spec.aAlign[i] & QRF_ALIGN_HMASK)==0 ){
   2907           data.a[i].e |= QRF_ALIGN_Right;
   2908         }
   2909       }else if( w<0 ){
   2910         w = -w;
   2911         if( p->spec.nAlign>i && (p->spec.aAlign[i] & QRF_ALIGN_HMASK)==0 ){
   2912           data.a[i].e |= QRF_ALIGN_Right;
   2913         }
   2914       }
   2915       if( w ) data.a[i].fx = 1;
   2916     }
   2917     if( w==0 ){
   2918       w = data.a[i].mxW;
   2919       if( p->spec.nWrap>0 && w>p->spec.nWrap ){
   2920         w = p->spec.nWrap;
   2921         data.bMultiRow = 1;
   2922       }
   2923     }else if( (data.bMultiRow==0 || w==1) && data.a[i].mxW>w ){
   2924       data.bMultiRow = 1;
   2925       if( w==1 ){
   2926         /* If aiWth[j] is 2 or more, then there might be a double-wide
   2927         ** character somewhere.  So make the column width at least 2. */
   2928         w = 2;
   2929       }
   2930     }
   2931     data.a[i].w = w;
   2932   }
   2933 
   2934   if( nColumn==1
   2935    && data.n>1
   2936    && p->spec.bSplitColumn==QRF_Yes
   2937    && p->spec.eStyle==QRF_STYLE_Column
   2938    && p->spec.bTitles==QRF_No
   2939    && p->spec.nScreenWidth>data.a[0].w+3
   2940   ){
   2941     /* Attempt to convert single-column tables into multi-column by
   2942     ** verticle wrapping, if the screen is wide enough and if the
   2943     ** bSplitColumn flag is set. */
   2944     qrfSplitColumn(&data, p);
   2945     nColumn = data.nCol;
   2946   }else{
   2947     /* Adjust the column widths due to screen width restrictions */
   2948     qrfRestrictScreenWidth(&data, p);
   2949   }
   2950 
   2951   /* Draw the line across the top of the table.  Also initialize
   2952   ** the row boundary and column separator texts. */
   2953   switch( p->spec.eStyle ){
   2954     case QRF_STYLE_Box:
   2955       if( data.nMargin ){
   2956         rowStart = BOX_13 " ";
   2957         colSep = " " BOX_13 " ";
   2958         rowSep = " " BOX_13 "\n";
   2959       }else{
   2960         rowStart = BOX_13;
   2961         colSep = BOX_13;
   2962         rowSep = BOX_13 "\n";
   2963       }
   2964       if( p->spec.bBorder==QRF_No){
   2965         rowStart += 3;
   2966         rowSep = "\n";
   2967       }else{
   2968         qrfBoxSeparator(p->pOut, &data, BOX_R23, BOX_234, BOX_R34, 0);
   2969       }
   2970       break;
   2971     case QRF_STYLE_Table:
   2972       if( data.nMargin ){
   2973         rowStart = "| ";
   2974         colSep = " | ";
   2975         rowSep = " |\n";
   2976       }else{
   2977         rowStart = "|";
   2978         colSep = "|";
   2979         rowSep = "|\n";
   2980       }
   2981       if( p->spec.bBorder==QRF_No ){
   2982         rowStart += 1;
   2983         rowSep = "\n";
   2984       }else{
   2985         qrfRowSeparator(p->pOut, &data, '+');
   2986       }
   2987       break;
   2988     case QRF_STYLE_Column: {
   2989       static const char zSpace[] = "     ";
   2990       rowStart = "";
   2991       if( data.nMargin<2 ){
   2992         colSep = " ";
   2993       }else if( data.nMargin<=5 ){
   2994         colSep = &zSpace[5-data.nMargin];
   2995       }else{
   2996         colSep = zSpace;
   2997       }
   2998       rowSep = "\n";
   2999       break;
   3000     }
   3001     default:  /*case QRF_STYLE_Markdown:*/
   3002       if( data.nMargin ){
   3003         rowStart = "| ";
   3004         colSep = " | ";
   3005         rowSep = " |\n";
   3006       }else{
   3007         rowStart = "|";
   3008         colSep = "|";
   3009         rowSep = "|\n";
   3010       }
   3011       break;
   3012   }
   3013   szRowStart = (int)strlen(rowStart);
   3014   szRowSep = (int)strlen(rowSep);
   3015   szColSep = (int)strlen(colSep);
   3016 
   3017   bWW = (p->spec.bWordWrap==QRF_Yes && data.bMultiRow);
   3018   if( p->spec.eStyle==QRF_STYLE_Column
   3019    || (p->spec.bBorder==QRF_No
   3020        && (p->spec.eStyle==QRF_STYLE_Box || p->spec.eStyle==QRF_STYLE_Table)
   3021       )
   3022   ){
   3023     bRTrim = 1;
   3024   }else{
   3025     bRTrim = 0;
   3026   }
   3027   for(i=0; i<data.n && sqlite3_str_errcode(p->pOut)==SQLITE_OK; i+=nColumn){
   3028     int bMore;
   3029     int nRow = 0;
   3030 
   3031     /* Draw a single row of the table.  This might be the title line
   3032     ** (if there is a title line) or a row in the body of the table.
   3033     ** The column number will be j.  The row number is i/nColumn.
   3034     */
   3035     for(j=0; j<nColumn; j++){
   3036       data.a[j].z = data.az[i+j];
   3037       if( data.a[j].z==0 ) data.a[j].z = "";
   3038       data.a[j].bNum = data.abNum[i+j];
   3039     }
   3040     do{
   3041       sqlite3_str_append(p->pOut, rowStart, szRowStart);
   3042       bMore = 0;
   3043       for(j=0; j<nColumn; j++){
   3044         int nThis = 0;
   3045         int nWide = 0;
   3046         int iNext = 0;
   3047         int nWS;
   3048         qrfWrapLine(data.a[j].z, data.a[j].w, bWW, &nThis, &nWide, &iNext);
   3049         nWS = data.a[j].w - nWide;
   3050         qrfPrintAligned(p->pOut, &data.a[j], nThis, nWS);
   3051         data.a[j].z += iNext;
   3052         if( data.a[j].z[0]!=0 ){
   3053           bMore = 1;
   3054         }
   3055         if( j<nColumn-1 ){
   3056           sqlite3_str_append(p->pOut, colSep, szColSep);
   3057         }else{
   3058           if( bRTrim ) qrfRTrim(p->pOut);
   3059           sqlite3_str_append(p->pOut, rowSep, szRowSep);
   3060         }
   3061       }
   3062     }while( bMore && ++nRow < p->mxHeight );
   3063     if( bMore ){
   3064       /* This row was terminated by nLineLimit.  Show ellipsis. */
   3065       sqlite3_str_append(p->pOut, rowStart, szRowStart);
   3066       for(j=0; j<nColumn; j++){
   3067         if( data.a[j].z[0]==0 ){
   3068           sqlite3_str_appendchar(p->pOut, data.a[j].w, ' ');
   3069         }else{
   3070           int nE = 3;
   3071           if( nE>data.a[j].w ) nE = data.a[j].w;
   3072           data.a[j].z = "...";
   3073           qrfPrintAligned(p->pOut, &data.a[j], nE, data.a[j].w-nE);
   3074         }
   3075         if( j<nColumn-1 ){
   3076           sqlite3_str_append(p->pOut, colSep, szColSep);
   3077         }else{
   3078           if( bRTrim ) qrfRTrim(p->pOut);
   3079           sqlite3_str_append(p->pOut, rowSep, szRowSep);
   3080         }
   3081       }
   3082     }
   3083 
   3084     /* Draw either (1) the separator between the title line and the body
   3085     ** of the table, or (2) separators between individual rows of the table
   3086     ** body.  isTitleDataSeparator will be true if we are doing (1).
   3087     */
   3088     if( (i==0 || data.bMultiRow) && i+nColumn<data.n ){
   3089       int isTitleDataSeparator = (i==0 && p->spec.bTitles==QRF_Yes);
   3090       if( isTitleDataSeparator ){
   3091         qrfLoadAlignment(&data, p);
   3092       }
   3093       switch( p->spec.eStyle ){
   3094         case QRF_STYLE_Table: {
   3095           if( isTitleDataSeparator || data.bMultiRow ){
   3096             qrfRowSeparator(p->pOut, &data, '+');
   3097           }
   3098           break;
   3099         }
   3100         case QRF_STYLE_Box: {
   3101           if( isTitleDataSeparator ){
   3102             qrfBoxSeparator(p->pOut, &data, DBL_123, DBL_1234, DBL_134, 1);
   3103           }else if( data.bMultiRow ){
   3104             qrfBoxSeparator(p->pOut, &data, BOX_123, BOX_1234, BOX_134, 0);
   3105           }
   3106           break;
   3107         }
   3108         case QRF_STYLE_Markdown: {
   3109           if( isTitleDataSeparator ){
   3110             qrfRowSeparator(p->pOut, &data, '|');
   3111           }
   3112           break;
   3113         }
   3114         case QRF_STYLE_Column: {
   3115           if( isTitleDataSeparator ){
   3116             for(j=0; j<nColumn; j++){
   3117               sqlite3_str_appendchar(p->pOut, data.a[j].w, '-');
   3118               if( j<nColumn-1 ){
   3119                 sqlite3_str_append(p->pOut, colSep, szColSep);
   3120               }else{
   3121                 qrfRTrim(p->pOut);
   3122                 sqlite3_str_append(p->pOut, rowSep, szRowSep);
   3123               }
   3124             }
   3125           }else if( data.bMultiRow ){
   3126             qrfRTrim(p->pOut);
   3127             sqlite3_str_append(p->pOut, "\n", 1);
   3128           }
   3129           break;
   3130         }
   3131       }
   3132     }
   3133   }
   3134 
   3135   /* Draw the line across the bottom of the table */
   3136   if( p->spec.bBorder!=QRF_No ){
   3137     switch( p->spec.eStyle ){
   3138       case QRF_STYLE_Box:
   3139         qrfBoxSeparator(p->pOut, &data, BOX_R12, BOX_124, BOX_R14, 0);
   3140         break;
   3141       case QRF_STYLE_Table:
   3142         qrfRowSeparator(p->pOut, &data, '+');
   3143         break;
   3144     }
   3145   }
   3146   qrfWrite(p);
   3147 
   3148   qrfColDataFree(&data);
   3149   return;
   3150 }
   3151 
   3152 /*
   3153 ** Parameter azArray points to a zero-terminated array of strings. zStr
   3154 ** points to a single nul-terminated string. Return non-zero if zStr
   3155 ** is equal, according to strcmp(), to any of the strings in the array.
   3156 ** Otherwise, return zero.
   3157 */
   3158 static int qrfStringInArray(const char *zStr, const char **azArray){
   3159   int i;
   3160   if( zStr==0 ) return 0;
   3161   for(i=0; azArray[i]; i++){
   3162     if( 0==strcmp(zStr, azArray[i]) ) return 1;
   3163   }
   3164   return 0;
   3165 }
   3166 
   3167 /*
   3168 ** Print out an EXPLAIN with indentation.  This is a two-pass algorithm.
   3169 **
   3170 ** On the first pass, we compute aiIndent[iOp] which is the amount of
   3171 ** indentation to apply to the iOp-th opcode.  The output actually occurs
   3172 ** on the second pass.
   3173 **
   3174 ** The indenting rules are:
   3175 **
   3176 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
   3177 **       all opcodes that occur between the p2 jump destination and the opcode
   3178 **       itself by 2 spaces.
   3179 **
   3180 **     * Do the previous for "Return" instructions for when P2 is positive.
   3181 **       See tag-20220407a in wherecode.c and vdbe.c.
   3182 **
   3183 **     * For each "Goto", if the jump destination is earlier in the program
   3184 **       and ends on one of:
   3185 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
   3186 **       or if the P1 parameter is one instead of zero,
   3187 **       then indent all opcodes between the earlier instruction
   3188 **       and "Goto" by 2 spaces.
   3189 */
   3190 static void qrfExplain(Qrf *p){
   3191   int *abYield = 0;     /* abYield[iOp] is rue if opcode iOp is an OP_Yield */
   3192   int *aiIndent = 0;    /* Indent the iOp-th opcode by aiIndent[iOp] */
   3193   i64 nAlloc = 0;       /* Allocated size of aiIndent[], abYield */
   3194   int nIndent = 0;      /* Number of entries in aiIndent[] */
   3195   int iOp;              /* Opcode number */
   3196   int i;                /* Column loop counter */
   3197 
   3198   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
   3199                            "Return", 0 };
   3200   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
   3201                             "Rewind", 0 };
   3202   const char *azGoto[] = { "Goto", 0 };
   3203 
   3204   /* The caller guarantees that the leftmost 4 columns of the statement
   3205   ** passed to this function are equivalent to the leftmost 4 columns
   3206   ** of EXPLAIN statement output. In practice the statement may be
   3207   ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
   3208   assert( sqlite3_column_count(p->pStmt)>=4 );
   3209   assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 0), "addr" ) );
   3210   assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 1), "opcode" ) );
   3211   assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 2), "p1" ) );
   3212   assert( 0==sqlite3_stricmp( sqlite3_column_name(p->pStmt, 3), "p2" ) );
   3213 
   3214   for(iOp=0; SQLITE_ROW==sqlite3_step(p->pStmt) && !p->iErr; iOp++){
   3215     int iAddr = sqlite3_column_int(p->pStmt, 0);
   3216     const char *zOp = (const char*)sqlite3_column_text(p->pStmt, 1);
   3217     int p1 = sqlite3_column_int(p->pStmt, 2);
   3218     int p2 = sqlite3_column_int(p->pStmt, 3);
   3219 
   3220     /* Assuming that p2 is an instruction address, set variable p2op to the
   3221     ** index of that instruction in the aiIndent[] array. p2 and p2op may be
   3222     ** different if the current instruction is part of a sub-program generated
   3223     ** by an SQL trigger or foreign key.  */
   3224     int p2op = (p2 + (iOp-iAddr));
   3225 
   3226     /* Grow the aiIndent array as required */
   3227     if( iOp>=nAlloc ){
   3228       nAlloc += 100;
   3229       aiIndent = (int*)sqlite3_realloc64(aiIndent, nAlloc*sizeof(int));
   3230       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
   3231       if( aiIndent==0 || abYield==0 ){
   3232         qrfOom(p);
   3233         sqlite3_free(aiIndent);
   3234         sqlite3_free(abYield);
   3235         return;
   3236       }
   3237     }
   3238 
   3239     abYield[iOp] = qrfStringInArray(zOp, azYield);
   3240     aiIndent[iOp] = 0;
   3241     nIndent = iOp+1;
   3242     if( qrfStringInArray(zOp, azNext) && p2op>0 ){
   3243       for(i=p2op; i<iOp; i++) aiIndent[i] += 2;
   3244     }
   3245     if( qrfStringInArray(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
   3246       for(i=p2op; i<iOp; i++) aiIndent[i] += 2;
   3247     }
   3248   }
   3249   sqlite3_free(abYield);
   3250 
   3251   /* Second pass.  Actually generate output */
   3252   sqlite3_reset(p->pStmt);
   3253   if( p->iErr==SQLITE_OK ){
   3254     static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
   3255     static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
   3256     static const int aScanExpWidth[] = {4,15, 6, 13, 4, 4, 4, 13, 2, 13};
   3257     static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
   3258     const int *aWidth = aExplainWidth;
   3259     const int *aMap = aExplainMap;
   3260     int nWidth = sizeof(aExplainWidth)/sizeof(int);
   3261     int iIndent = 1;
   3262     int nArg = p->nCol;
   3263     if( p->spec.eStyle==QRF_STYLE_StatsVm ){
   3264       aWidth = aScanExpWidth;
   3265       aMap = aScanExpMap;
   3266       nWidth = sizeof(aScanExpWidth)/sizeof(int);
   3267       iIndent = 3;
   3268     }
   3269     if( nArg>nWidth ) nArg = nWidth;
   3270 
   3271     for(iOp=0; sqlite3_step(p->pStmt)==SQLITE_ROW && !p->iErr; iOp++){
   3272       /* If this is the first row seen, print out the headers */
   3273       if( iOp==0 ){
   3274         for(i=0; i<nArg; i++){
   3275           const char *zCol = sqlite3_column_name(p->pStmt, aMap[i]);
   3276           qrfWidthPrint(p,p->pOut, aWidth[i], zCol);
   3277           if( i==nArg-1 ){
   3278             sqlite3_str_append(p->pOut, "\n", 1);
   3279           }else{
   3280             sqlite3_str_append(p->pOut, "  ", 2);
   3281           }
   3282         }
   3283         for(i=0; i<nArg; i++){
   3284           sqlite3_str_appendf(p->pOut, "%.*c", aWidth[i], '-');
   3285           if( i==nArg-1 ){
   3286             sqlite3_str_append(p->pOut, "\n", 1);
   3287           }else{
   3288             sqlite3_str_append(p->pOut, "  ", 2);
   3289           }
   3290         }
   3291       }
   3292 
   3293       for(i=0; i<nArg; i++){
   3294         const char *zSep = "  ";
   3295         int w = aWidth[i];
   3296         const char *zVal = (const char*)sqlite3_column_text(p->pStmt, aMap[i]);
   3297         int len;
   3298         if( i==nArg-1 ) w = 0;
   3299         if( zVal==0 ) zVal = "";
   3300         len = (int)sqlite3_qrf_wcswidth(zVal);
   3301         if( len>w ){
   3302           w = len;
   3303           zSep = " ";
   3304         }
   3305         if( i==iIndent && aiIndent && iOp<nIndent ){
   3306           sqlite3_str_appendchar(p->pOut, aiIndent[iOp], ' ');
   3307         }
   3308         qrfWidthPrint(p, p->pOut, w, zVal);
   3309         if( i==nArg-1 ){
   3310           sqlite3_str_append(p->pOut, "\n", 1);
   3311         }else{
   3312           sqlite3_str_appendall(p->pOut, zSep);
   3313         }
   3314       }
   3315       p->nRow++;
   3316     }
   3317     qrfWrite(p);
   3318   }
   3319   sqlite3_free(aiIndent);
   3320 }
   3321 
   3322 /*
   3323 ** Do a "scanstatus vm" style EXPLAIN listing on p->pStmt.
   3324 **
   3325 ** p->pStmt is probably not an EXPLAIN query.  Instead, construct a
   3326 ** new query that is a bytecode() rendering of p->pStmt with extra
   3327 ** columns for the "scanstatus vm" outputs, and run the results of
   3328 ** that new query through the normal EXPLAIN formatting.
   3329 */
   3330 static void qrfScanStatusVm(Qrf *p){
   3331   sqlite3_stmt *pOrigStmt = p->pStmt;
   3332   sqlite3_stmt *pExplain;
   3333   int rc;
   3334   static const char *zSql =
   3335       "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
   3336       "   format('% 6s (%.2f%%)',"
   3337       "      CASE WHEN ncycle<100_000 THEN ncycle || ' '"
   3338       "         WHEN ncycle<100_000_000 THEN (ncycle/1_000) || 'K'"
   3339       "         WHEN ncycle<100_000_000_000 THEN (ncycle/1_000_000) || 'M'"
   3340       "         ELSE (ncycle/1000_000_000) || 'G' END,"
   3341       "       ncycle*100.0/(sum(ncycle) OVER ())"
   3342       "   )  AS cycles"
   3343       "   FROM bytecode(?1)";
   3344   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pExplain, 0);
   3345   if( rc ){
   3346     qrfError(p, rc, "%s", sqlite3_errmsg(p->db));
   3347     sqlite3_finalize(pExplain);
   3348     return;
   3349   }
   3350   sqlite3_bind_pointer(pExplain, 1, pOrigStmt, "stmt-pointer", 0);
   3351   p->pStmt = pExplain;
   3352   p->nCol = 10;
   3353   qrfExplain(p);
   3354   sqlite3_finalize(pExplain);
   3355   p->pStmt = pOrigStmt;
   3356 }
   3357 
   3358 /*
   3359 ** Attempt to determine if identifier zName needs to be quoted, either
   3360 ** because it contains non-alphanumeric characters, or because it is an
   3361 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
   3362 ** that quoting is required.
   3363 **
   3364 ** Return 1 if quoting is required.  Return 0 if no quoting is required.
   3365 */
   3366 
   3367 static int qrf_need_quote(const char *zName){
   3368   int i;
   3369   const unsigned char *z = (const unsigned char*)zName;
   3370   if( z==0 ) return 1;
   3371   if( !qrfAlpha(z[0]) ) return 1;
   3372   for(i=0; z[i]; i++){
   3373     if( !qrfAlnum(z[i]) ) return 1;
   3374   }
   3375   return sqlite3_keyword_check(zName, i)!=0;
   3376 }
   3377 
   3378 /*
   3379 ** Helper function for QRF_STYLE_Json and QRF_STYLE_JObject.
   3380 ** The initial "{" for a JSON object that will contain row content
   3381 ** has been output.  Now output all the content.
   3382 */
   3383 static void qrfOneJsonRow(Qrf *p){
   3384   int i, nItem;
   3385   for(nItem=i=0; i<p->nCol; i++){
   3386     const char *zCName;
   3387     zCName = sqlite3_column_name(p->pStmt, i);
   3388     if( nItem>0 ) sqlite3_str_append(p->pOut, ",", 1);
   3389     nItem++;
   3390     qrfEncodeText(p, p->pOut, zCName);
   3391     sqlite3_str_append(p->pOut, ":", 1);
   3392     qrfRenderValue(p, p->pOut, i);
   3393   }
   3394   qrfWrite(p);
   3395 }
   3396 
   3397 /*
   3398 ** Render a single row of output for non-columnar styles - any
   3399 ** style that lets us render row by row as the content is received
   3400 ** from the query.
   3401 */
   3402 static void qrfOneSimpleRow(Qrf *p){
   3403   int i;
   3404   switch( p->spec.eStyle ){
   3405     case QRF_STYLE_Off:
   3406     case QRF_STYLE_Count: {
   3407       /* No-op */
   3408       break;
   3409     }
   3410     case QRF_STYLE_Json: {
   3411       if( p->nRow==0 ){
   3412         sqlite3_str_append(p->pOut, "[{", 2);
   3413       }else{
   3414         sqlite3_str_append(p->pOut, "},\n{", 4);
   3415       }
   3416       qrfOneJsonRow(p);
   3417       break;
   3418     }
   3419     case QRF_STYLE_JObject: {
   3420       if( p->nRow==0 ){
   3421         sqlite3_str_append(p->pOut, "{", 1);
   3422       }else{
   3423         sqlite3_str_append(p->pOut, "}\n{", 3);
   3424       }
   3425       qrfOneJsonRow(p);
   3426       break;
   3427     }
   3428     case QRF_STYLE_Html: {
   3429       if( p->nRow==0 && p->spec.bTitles==QRF_Yes ){
   3430         sqlite3_str_append(p->pOut, "<TR>", 4);
   3431         for(i=0; i<p->nCol; i++){
   3432           const char *zCName = sqlite3_column_name(p->pStmt, i);
   3433           sqlite3_str_append(p->pOut, "\n<TH>", 5);
   3434           qrfEncodeText(p, p->pOut, zCName);
   3435         }
   3436         sqlite3_str_append(p->pOut, "\n</TR>\n", 7);
   3437       }
   3438       sqlite3_str_append(p->pOut, "<TR>", 4);
   3439       for(i=0; i<p->nCol; i++){
   3440         sqlite3_str_append(p->pOut, "\n<TD>", 5);
   3441         qrfRenderValue(p, p->pOut, i);
   3442       }
   3443       sqlite3_str_append(p->pOut, "\n</TR>\n", 7);
   3444       qrfWrite(p);
   3445       break;
   3446     }
   3447     case QRF_STYLE_Insert: {
   3448       unsigned int mxIns = p->spec.nMultiInsert;
   3449       int szStart = sqlite3_str_length(p->pOut);
   3450       if( p->u.nIns==0 || p->u.nIns>=mxIns ){
   3451         if( p->u.nIns ){
   3452           sqlite3_str_append(p->pOut, ";\n", 2);
   3453           p->u.nIns = 0;
   3454         }
   3455         if( qrf_need_quote(p->spec.zTableName) ){
   3456           sqlite3_str_appendf(p->pOut,"INSERT INTO \"%w\"",p->spec.zTableName);
   3457         }else{
   3458           sqlite3_str_appendf(p->pOut,"INSERT INTO %s",p->spec.zTableName);
   3459         }
   3460         if( p->spec.bTitles==QRF_Yes ){
   3461           for(i=0; i<p->nCol; i++){
   3462             const char *zCName = sqlite3_column_name(p->pStmt, i);
   3463             if( qrf_need_quote(zCName) ){
   3464               sqlite3_str_appendf(p->pOut, "%c\"%w\"",
   3465                                   i==0 ? '(' : ',', zCName);
   3466             }else{
   3467               sqlite3_str_appendf(p->pOut, "%c%s",
   3468                                   i==0 ? '(' : ',', zCName);
   3469             }
   3470           }
   3471           sqlite3_str_append(p->pOut, ")", 1);
   3472         }
   3473         sqlite3_str_append(p->pOut," VALUES(", 8);
   3474       }else{
   3475         sqlite3_str_append(p->pOut,",\n  (", 5);
   3476       }
   3477       for(i=0; i<p->nCol; i++){
   3478         if( i>0 ) sqlite3_str_append(p->pOut, ",", 1);
   3479         qrfRenderValue(p, p->pOut, i);
   3480       }
   3481       p->u.nIns += sqlite3_str_length(p->pOut) + 2 - szStart;
   3482       if( p->u.nIns>=mxIns ){
   3483         sqlite3_str_append(p->pOut, ");\n", 3);
   3484         p->u.nIns = 0;
   3485       }else{
   3486         sqlite3_str_append(p->pOut, ")", 1);
   3487       }
   3488       qrfWrite(p);
   3489       break;
   3490     }
   3491     case QRF_STYLE_Line: {
   3492       sqlite3_str *pVal;
   3493       int mxW;
   3494       int bWW;
   3495       int nSep;
   3496       if( p->u.sLine.azCol==0 ){
   3497         p->u.sLine.azCol = sqlite3_malloc64( p->nCol*sizeof(char*) );
   3498         if( p->u.sLine.azCol==0 ){
   3499           qrfOom(p);
   3500           break;
   3501         }
   3502         p->u.sLine.mxColWth = 0;
   3503         for(i=0; i<p->nCol; i++){
   3504           int sz;
   3505           const char *zCName = sqlite3_column_name(p->pStmt, i);
   3506           if( zCName==0 ) zCName = "unknown";
   3507           p->u.sLine.azCol[i] = sqlite3_mprintf("%s", zCName);
   3508           if( p->spec.nTitleLimit>0 ){
   3509             (void)qrfTitleLimit(p->u.sLine.azCol[i], p->spec.nTitleLimit);
   3510           }
   3511           sz = (int)sqlite3_qrf_wcswidth(p->u.sLine.azCol[i]);
   3512           if( sz > p->u.sLine.mxColWth ) p->u.sLine.mxColWth = sz;
   3513         }
   3514       }
   3515       if( p->nRow ) sqlite3_str_append(p->pOut, "\n", 1);
   3516       pVal = sqlite3_str_new(p->db);
   3517       nSep = (int)strlen(p->spec.zColumnSep);
   3518       mxW = p->mxWidth - (nSep + p->u.sLine.mxColWth);
   3519       bWW = p->spec.bWordWrap==QRF_Yes;
   3520       for(i=0; i<p->nCol; i++){
   3521         const char *zVal;
   3522         int cnt = 0;
   3523         qrfWidthPrint(p, p->pOut, -p->u.sLine.mxColWth, p->u.sLine.azCol[i]);
   3524         sqlite3_str_append(p->pOut, p->spec.zColumnSep, nSep);
   3525         qrfRenderValue(p, pVal, i);
   3526         zVal = sqlite3_str_value(pVal);
   3527         if( zVal==0 ) zVal = "";
   3528         do{
   3529           int nThis, nWide, iNext;
   3530           qrfWrapLine(zVal, mxW, bWW, &nThis, &nWide, &iNext);
   3531           if( cnt ){
   3532             sqlite3_str_appendchar(p->pOut,p->u.sLine.mxColWth+nSep,' ');
   3533           }
   3534           cnt++;
   3535           if( cnt>p->mxHeight ){
   3536             zVal = "...";
   3537             nThis = iNext = 3;
   3538           }
   3539           sqlite3_str_append(p->pOut, zVal, nThis);
   3540           sqlite3_str_append(p->pOut, "\n", 1);
   3541           zVal += iNext;
   3542         }while( zVal[0] );
   3543         sqlite3_str_reset(pVal);
   3544       }
   3545       qrfStrErr(p, pVal);
   3546       sqlite3_free(sqlite3_str_finish(pVal));
   3547       qrfWrite(p);
   3548       break;
   3549     }
   3550     case QRF_STYLE_Eqp: {
   3551       const char *zEqpLine = (const char*)sqlite3_column_text(p->pStmt,3);
   3552       int iEqpId = sqlite3_column_int(p->pStmt, 0);
   3553       int iParentId = sqlite3_column_int(p->pStmt, 1);
   3554       if( zEqpLine==0 ) zEqpLine = "";
   3555       if( zEqpLine[0]=='-' ) qrfEqpRender(p, 0);
   3556       qrfEqpAppend(p, iEqpId, iParentId, zEqpLine);
   3557       break;
   3558     }
   3559     default: {  /* QRF_STYLE_List */
   3560       if( p->nRow==0 && p->spec.bTitles==QRF_Yes ){
   3561         int saved_eText = p->spec.eText;
   3562         p->spec.eText = p->spec.eTitle;
   3563         for(i=0; i<p->nCol; i++){
   3564           const char *zCName = sqlite3_column_name(p->pStmt, i);
   3565           if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
   3566           qrfEncodeText(p, p->pOut, zCName);
   3567         }
   3568         sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
   3569         qrfWrite(p);
   3570         p->spec.eText = saved_eText;
   3571       }
   3572       for(i=0; i<p->nCol; i++){
   3573         if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
   3574         qrfRenderValue(p, p->pOut, i);
   3575       }
   3576       sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
   3577       qrfWrite(p);
   3578       break;
   3579     }
   3580   }
   3581   p->nRow++;
   3582 }
   3583 
   3584 /*
   3585 ** Initialize the internal Qrf object.
   3586 */
   3587 static void qrfInitialize(
   3588   Qrf *p,                        /* State object to be initialized */
   3589   sqlite3_stmt *pStmt,           /* Query whose output to be formatted */
   3590   const sqlite3_qrf_spec *pSpec, /* Format specification */
   3591   char **pzErr                   /* Write errors here */
   3592 ){
   3593   size_t sz;                     /* Size of pSpec[], based on pSpec->iVersion */
   3594   memset(p, 0, sizeof(*p));
   3595   p->pzErr = pzErr;
   3596   if( pSpec->iVersion>1 ){
   3597     qrfError(p, SQLITE_ERROR,
   3598        "unusable sqlite3_qrf_spec.iVersion (%d)",
   3599        pSpec->iVersion);
   3600     return;
   3601   }
   3602   p->pStmt = pStmt;
   3603   p->db = sqlite3_db_handle(pStmt);
   3604   p->pOut = sqlite3_str_new(p->db);
   3605   if( p->pOut==0 ){
   3606     qrfOom(p);
   3607     return;
   3608   }
   3609   p->iErr = SQLITE_OK;
   3610   p->nCol = sqlite3_column_count(p->pStmt);
   3611   p->nRow = 0;
   3612   sz = sizeof(sqlite3_qrf_spec);
   3613   memcpy(&p->spec, pSpec, sz);
   3614   if( p->spec.zNull==0 ) p->spec.zNull = "";
   3615   p->mxWidth = p->spec.nScreenWidth;
   3616   if( p->mxWidth<=0 ) p->mxWidth = QRF_MAX_WIDTH;
   3617   p->mxHeight = p->spec.nLineLimit;
   3618   if( p->mxHeight<=0 ) p->mxHeight = 2147483647;
   3619   if( p->spec.eStyle>QRF_STYLE_Table ) p->spec.eStyle = QRF_Auto;
   3620   if( p->spec.eEsc>QRF_ESC_Symbol ) p->spec.eEsc = QRF_Auto;
   3621   if( p->spec.eText>QRF_TEXT_Relaxed ) p->spec.eText = QRF_Auto;
   3622   if( p->spec.eTitle>QRF_TEXT_Relaxed ) p->spec.eTitle = QRF_Auto;
   3623   if( p->spec.eBlob>QRF_BLOB_Size ) p->spec.eBlob = QRF_Auto;
   3624 qrf_reinit:
   3625   switch( p->spec.eStyle ){
   3626     case QRF_Auto: {
   3627       switch( sqlite3_stmt_isexplain(pStmt) ){
   3628         case 0:  p->spec.eStyle = QRF_STYLE_Box;      break;
   3629         case 1:  p->spec.eStyle = QRF_STYLE_Explain;  break;
   3630         default: p->spec.eStyle = QRF_STYLE_Eqp;      break;
   3631       }
   3632       goto qrf_reinit;
   3633     }
   3634     case QRF_STYLE_List: {
   3635       if( p->spec.zColumnSep==0 ) p->spec.zColumnSep = "|";
   3636       if( p->spec.zRowSep==0 ) p->spec.zRowSep = "\n";
   3637       break;
   3638     }
   3639     case QRF_STYLE_JObject:
   3640     case QRF_STYLE_Json: {
   3641       p->spec.eText = QRF_TEXT_Json;
   3642       p->spec.zNull = "null";
   3643       break;
   3644     }
   3645     case QRF_STYLE_Html: {
   3646       p->spec.eText = QRF_TEXT_Html;
   3647       p->spec.zNull = "null";
   3648       break;
   3649     }
   3650     case QRF_STYLE_Insert: {
   3651       p->spec.eText = QRF_TEXT_Sql;
   3652       p->spec.zNull = "NULL";
   3653       if( p->spec.zTableName==0 || p->spec.zTableName[0]==0 ){
   3654         p->spec.zTableName = "tab";
   3655       }
   3656       p->u.nIns = 0;
   3657       break;
   3658     }
   3659     case QRF_STYLE_Line: {
   3660       if( p->spec.zColumnSep==0 ){
   3661         p->spec.zColumnSep = ": ";
   3662       }
   3663       break;
   3664     }
   3665     case QRF_STYLE_Csv: {
   3666       p->spec.eStyle = QRF_STYLE_List;
   3667       p->spec.eText = QRF_TEXT_Csv;
   3668       p->spec.zColumnSep = ",";
   3669       p->spec.zRowSep = "\r\n";
   3670       p->spec.zNull = "";
   3671       break;
   3672     }
   3673     case QRF_STYLE_Quote: {
   3674       p->spec.eText = QRF_TEXT_Sql;
   3675       p->spec.zNull = "NULL";
   3676       p->spec.zColumnSep = ",";
   3677       p->spec.zRowSep = "\n";
   3678       break;
   3679     }
   3680     case QRF_STYLE_Eqp: {
   3681       int expMode = sqlite3_stmt_isexplain(p->pStmt);
   3682       if( expMode!=2 ){
   3683         sqlite3_stmt_explain(p->pStmt, 2);
   3684         p->expMode = expMode+1;
   3685       }
   3686       break;
   3687     }
   3688     case QRF_STYLE_Explain: {
   3689       int expMode = sqlite3_stmt_isexplain(p->pStmt);
   3690       if( expMode!=1 ){
   3691         sqlite3_stmt_explain(p->pStmt, 1);
   3692         p->expMode = expMode+1;
   3693       }
   3694       break;
   3695     }
   3696   }
   3697   if( p->spec.eEsc==QRF_Auto ){
   3698     p->spec.eEsc = QRF_ESC_Ascii;
   3699   }
   3700   if( p->spec.eText==QRF_Auto ){
   3701     p->spec.eText = QRF_TEXT_Plain;
   3702   }
   3703   if( p->spec.eTitle==QRF_Auto ){
   3704     switch( p->spec.eStyle ){
   3705       case QRF_STYLE_Box:
   3706       case QRF_STYLE_Column:
   3707       case QRF_STYLE_Table:
   3708         p->spec.eTitle = QRF_TEXT_Plain;
   3709         break;
   3710       default:
   3711         p->spec.eTitle = p->spec.eText;
   3712         break;
   3713     }
   3714   }
   3715   if( p->spec.eBlob==QRF_Auto ){
   3716     switch( p->spec.eText ){
   3717       case QRF_TEXT_Sql:  p->spec.eBlob = QRF_BLOB_Sql;  break;
   3718       case QRF_TEXT_Csv:  p->spec.eBlob = QRF_BLOB_Tcl;  break;
   3719       case QRF_TEXT_Tcl:  p->spec.eBlob = QRF_BLOB_Tcl;  break;
   3720       case QRF_TEXT_Json: p->spec.eBlob = QRF_BLOB_Json; break;
   3721       default:            p->spec.eBlob = QRF_BLOB_Text; break;
   3722     }
   3723   }
   3724   if( p->spec.bTitles==QRF_Auto ){
   3725     switch( p->spec.eStyle ){
   3726       case QRF_STYLE_Box:
   3727       case QRF_STYLE_Csv:
   3728       case QRF_STYLE_Column:
   3729       case QRF_STYLE_Table:
   3730       case QRF_STYLE_Markdown:
   3731         p->spec.bTitles = QRF_Yes;
   3732         break;
   3733       default:
   3734         p->spec.bTitles = QRF_No;
   3735         break;
   3736     }
   3737   }
   3738   if( p->spec.bWordWrap==QRF_Auto ){
   3739     p->spec.bWordWrap = QRF_Yes;
   3740   }
   3741   if( p->spec.bTextJsonb==QRF_Auto ){
   3742     p->spec.bTextJsonb = QRF_No;
   3743   }
   3744   if( p->spec.zColumnSep==0 ) p->spec.zColumnSep = ",";
   3745   if( p->spec.zRowSep==0 ) p->spec.zRowSep = "\n";
   3746 }
   3747 
   3748 /*
   3749 ** Finish rendering the results
   3750 */
   3751 static void qrfFinalize(Qrf *p){
   3752   switch( p->spec.eStyle ){
   3753     case QRF_STYLE_Count: {
   3754       sqlite3_str_appendf(p->pOut, "%lld\n", p->nRow);
   3755       break;
   3756     }
   3757     case QRF_STYLE_Json: {
   3758       if( p->nRow>0 ){
   3759         sqlite3_str_append(p->pOut, "}]\n", 3);
   3760       }
   3761       break;
   3762     }
   3763     case QRF_STYLE_JObject: {
   3764       if( p->nRow>0 ){
   3765         sqlite3_str_append(p->pOut, "}\n", 2);
   3766       }
   3767       break;
   3768     }
   3769     case QRF_STYLE_Insert: {
   3770       if( p->u.nIns ){
   3771         sqlite3_str_append(p->pOut, ";\n", 2);
   3772       }
   3773       break;
   3774     }
   3775     case QRF_STYLE_Line: {
   3776       if( p->u.sLine.azCol ){
   3777         int i;
   3778         for(i=0; i<p->nCol; i++) sqlite3_free(p->u.sLine.azCol[i]);
   3779         sqlite3_free(p->u.sLine.azCol);
   3780       }
   3781       break;
   3782     }
   3783     case QRF_STYLE_Stats:
   3784     case QRF_STYLE_StatsEst: {
   3785       i64 nCycle = 0;
   3786 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   3787       sqlite3_stmt_scanstatus_v2(p->pStmt, -1, SQLITE_SCANSTAT_NCYCLE,
   3788                                  SQLITE_SCANSTAT_COMPLEX, (void*)&nCycle);
   3789 #endif
   3790       qrfEqpRender(p, nCycle);
   3791       break;
   3792     }
   3793     case QRF_STYLE_Eqp: {
   3794       qrfEqpRender(p, 0);
   3795       break;
   3796     }
   3797   }
   3798   qrfWrite(p);
   3799   qrfStrErr(p, p->pOut);
   3800   if( p->spec.pzOutput ){
   3801     if( p->spec.pzOutput[0] ){
   3802       sqlite3_int64 n, sz;
   3803       char *zCombined;
   3804       sz = strlen(p->spec.pzOutput[0]);
   3805       n = sqlite3_str_length(p->pOut);
   3806       zCombined = sqlite3_realloc64(p->spec.pzOutput[0], sz+n+1);
   3807       if( zCombined==0 ){
   3808         sqlite3_free(p->spec.pzOutput[0]);
   3809         p->spec.pzOutput[0] = 0;
   3810         qrfOom(p);
   3811       }else{
   3812         p->spec.pzOutput[0] = zCombined;
   3813         memcpy(zCombined+sz, sqlite3_str_value(p->pOut), n+1);
   3814       }
   3815       sqlite3_free(sqlite3_str_finish(p->pOut));
   3816     }else{
   3817       p->spec.pzOutput[0] = sqlite3_str_finish(p->pOut);
   3818     }
   3819   }else if( p->pOut ){
   3820     sqlite3_free(sqlite3_str_finish(p->pOut));
   3821   }
   3822   if( p->expMode>0 ){
   3823     sqlite3_stmt_explain(p->pStmt, p->expMode-1);
   3824   }
   3825   if( p->actualWidth ){
   3826     sqlite3_free(p->actualWidth);
   3827   }
   3828   if( p->pJTrans ){
   3829     sqlite3 *db = sqlite3_db_handle(p->pJTrans);
   3830     sqlite3_finalize(p->pJTrans);
   3831     sqlite3_close(db);
   3832   }
   3833 }
   3834 
   3835 /*
   3836 ** Run the prepared statement pStmt and format the results according
   3837 ** to the specification provided in pSpec.  Return an error code.
   3838 ** If pzErr is not NULL and if an error occurs, write an error message
   3839 ** into *pzErr.
   3840 */
   3841 int sqlite3_format_query_result(
   3842   sqlite3_stmt *pStmt,                 /* Statement to evaluate */
   3843   const sqlite3_qrf_spec *pSpec,       /* Format specification */
   3844   char **pzErr                         /* Write error message here */
   3845 ){
   3846   Qrf qrf;         /* The new Qrf being created */
   3847 
   3848   if( pStmt==0 ) return SQLITE_OK;       /* No-op */
   3849   if( pSpec==0 ) return SQLITE_MISUSE;
   3850   qrfInitialize(&qrf, pStmt, pSpec, pzErr);
   3851   switch( qrf.spec.eStyle ){
   3852     case QRF_STYLE_Box:
   3853     case QRF_STYLE_Column:
   3854     case QRF_STYLE_Markdown:
   3855     case QRF_STYLE_Table: {
   3856       /* Columnar modes require that the entire query be evaluated and the
   3857       ** results stored in memory, so that we can compute column widths */
   3858       qrfColumnar(&qrf);
   3859       break;
   3860     }
   3861     case QRF_STYLE_Explain: {
   3862       qrfExplain(&qrf);
   3863       break;
   3864     }
   3865     case QRF_STYLE_StatsVm: {
   3866       qrfScanStatusVm(&qrf);
   3867       break;
   3868     }
   3869     case QRF_STYLE_Stats:
   3870     case QRF_STYLE_StatsEst: {
   3871       qrfEqpStats(&qrf);
   3872       break;
   3873     }
   3874     default: {
   3875       /* Non-columnar modes where the output can occur after each row
   3876       ** of result is received */
   3877       while( qrf.iErr==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   3878         qrfOneSimpleRow(&qrf);
   3879       }
   3880       break;
   3881     }
   3882   }
   3883   qrfResetStmt(&qrf);
   3884   qrfFinalize(&qrf);
   3885   return qrf.iErr;
   3886 }
   3887 
   3888 /************************* End ext/qrf/qrf.c ********************/
   3889 
   3890 /* Use console I/O package as a direct INCLUDE. */
   3891 #define SQLITE_INTERNAL_LINKAGE static
   3892 
   3893 #ifdef SQLITE_SHELL_FIDDLE
   3894 /* Deselect most features from the console I/O package for Fiddle. */
   3895 # define SQLITE_CIO_NO_REDIRECT
   3896 # define SQLITE_CIO_NO_CLASSIFY
   3897 # define SQLITE_CIO_NO_TRANSLATE
   3898 # define SQLITE_CIO_NO_SETMODE
   3899 # define SQLITE_CIO_NO_FLUSH
   3900 #endif
   3901 
   3902 /*
   3903 ** The source code for several run-time loadable extensions is inserted
   3904 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
   3905 ** code, we need to override some macros to make the included program code
   3906 ** work here in the middle of this regular program.
   3907 */
   3908 #define SQLITE_EXTENSION_INIT1
   3909 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
   3910 
   3911 /************************* Begin ext/misc/windirent.h ******************/
   3912 /*
   3913 ** 2025-06-05
   3914 **
   3915 ** The author disclaims copyright to this source code.  In place of
   3916 ** a legal notice, here is a blessing:
   3917 **
   3918 **    May you do good and not evil.
   3919 **    May you find forgiveness for yourself and forgive others.
   3920 **    May you share freely, never taking more than you give.
   3921 **
   3922 *************************************************************************
   3923 **
   3924 ** An implementation of opendir(), readdir(), and closedir() for Windows,
   3925 ** based on the FindFirstFile(), FindNextFile(), and FindClose() APIs
   3926 ** of Win32.
   3927 **
   3928 ** #include this file inside any C-code module that needs to use
   3929 ** opendir()/readdir()/closedir().  This file is a no-op on non-Windows
   3930 ** machines.  On Windows, static functions are defined that implement
   3931 ** those standard interfaces.
   3932 */
   3933 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
   3934 #define SQLITE_WINDIRENT_H
   3935 
   3936 #ifndef WIN32_LEAN_AND_MEAN
   3937 #define WIN32_LEAN_AND_MEAN
   3938 #endif
   3939 #include <windows.h>
   3940 #include <io.h>
   3941 #include <stdio.h>
   3942 #include <stdlib.h>
   3943 #include <errno.h>
   3944 #include <limits.h>
   3945 #include <sys/types.h>
   3946 #include <sys/stat.h>
   3947 #include <string.h>
   3948 #ifndef FILENAME_MAX
   3949 # define FILENAME_MAX (260)
   3950 #endif
   3951 #ifndef S_ISREG
   3952 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
   3953 #endif
   3954 #ifndef S_ISDIR
   3955 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
   3956 #endif
   3957 #ifndef S_ISLNK
   3958 #define S_ISLNK(m) (0)
   3959 #endif
   3960 typedef unsigned short mode_t;
   3961 
   3962 /* The dirent object for Windows is abbreviated.  The only field really
   3963 ** usable by applications is d_name[].
   3964 */
   3965 struct dirent {
   3966  int d_ino;                  /* Inode number (synthesized) */
   3967  unsigned d_attributes;      /* File attributes */
   3968  char d_name[FILENAME_MAX];  /* Null-terminated filename */
   3969 };
   3970 
   3971 /* The internals of DIR are opaque according to standards.  So it
   3972 ** does not matter what we put here. */
   3973 typedef struct DIR DIR;
   3974 struct DIR {
   3975   intptr_t d_handle;         /* Handle for findfirst()/findnext() */
   3976   struct dirent cur;         /* Current entry */
   3977 };
   3978 
   3979 /* Ignore hidden and system files */
   3980 #define WindowsFileToIgnore(a) \
   3981     ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
   3982 
   3983 /*
   3984 ** Close a previously opened directory
   3985 */
   3986 static int closedir(DIR *pDir){
   3987   int rc = 0;
   3988   if( pDir==0 ){
   3989     return EINVAL;
   3990   }
   3991   if( pDir->d_handle!=0 && pDir->d_handle!=(-1) ){
   3992     rc = _findclose(pDir->d_handle);
   3993   }
   3994   sqlite3_free(pDir);
   3995   return rc;
   3996 }
   3997 
   3998 /*
   3999 ** Open a new directory.  The directory name should be UTF-8 encoded.
   4000 ** appropriate translations happen automatically.
   4001 */
   4002 static DIR *opendir(const char *zDirName){
   4003   DIR *pDir;
   4004   wchar_t *b1;
   4005   sqlite3_int64 sz;
   4006   struct _wfinddata_t data;
   4007 
   4008   pDir = sqlite3_malloc64( sizeof(DIR) );
   4009   if( pDir==0 ) return 0;
   4010   memset(pDir, 0, sizeof(DIR));
   4011   memset(&data, 0, sizeof(data));
   4012   sz = strlen(zDirName);
   4013   b1 = sqlite3_malloc64( (sz+3)*sizeof(b1[0]) );
   4014   if( b1==0 ){
   4015     closedir(pDir);
   4016     return NULL;
   4017   }
   4018   sz = MultiByteToWideChar(CP_UTF8, 0, zDirName, sz, b1, sz);
   4019   b1[sz++] = '\\';
   4020   b1[sz++] = '*';
   4021   b1[sz] = 0;
   4022   if( sz+1>sizeof(data.name)/sizeof(data.name[0]) ){
   4023     closedir(pDir);
   4024     sqlite3_free(b1);
   4025     return NULL;
   4026   }
   4027   memcpy(data.name, b1, (sz+1)*sizeof(b1[0]));
   4028   sqlite3_free(b1);
   4029   pDir->d_handle = _wfindfirst(data.name, &data);
   4030   if( pDir->d_handle<0 ){
   4031     closedir(pDir);
   4032     return NULL;
   4033   }
   4034   while( WindowsFileToIgnore(data) ){
   4035     memset(&data, 0, sizeof(data));
   4036     if( _wfindnext(pDir->d_handle, &data)==-1 ){
   4037       closedir(pDir);
   4038       return NULL;
   4039     }
   4040   }
   4041   pDir->cur.d_ino = 0;
   4042   pDir->cur.d_attributes = data.attrib;
   4043   WideCharToMultiByte(CP_UTF8, 0, data.name, -1,
   4044                       pDir->cur.d_name, FILENAME_MAX, 0, 0);
   4045   return pDir;
   4046 }
   4047 
   4048 /*
   4049 ** Read the next entry from a directory.
   4050 **
   4051 ** The returned struct-dirent object is managed by DIR.  It is only
   4052 ** valid until the next readdir() or closedir() call.  Only the
   4053 ** d_name[] field is meaningful.  The d_name[] value has been
   4054 ** translated into UTF8.
   4055 */
   4056 static struct dirent *readdir(DIR *pDir){
   4057   struct _wfinddata_t data;
   4058   if( pDir==0 ) return 0;
   4059   if( (pDir->cur.d_ino++)==0 ){
   4060     return &pDir->cur;
   4061   }
   4062   do{
   4063     memset(&data, 0, sizeof(data));
   4064     if( _wfindnext(pDir->d_handle, &data)==-1 ){
   4065       return NULL;
   4066     }
   4067   }while( WindowsFileToIgnore(data) );
   4068   pDir->cur.d_attributes = data.attrib;
   4069   WideCharToMultiByte(CP_UTF8, 0, data.name, -1,
   4070                       pDir->cur.d_name, FILENAME_MAX, 0, 0);
   4071   return &pDir->cur;
   4072 }
   4073 
   4074 #endif /* defined(_WIN32) && defined(_MSC_VER) */
   4075 
   4076 /************************* End ext/misc/windirent.h ********************/
   4077 /************************* Begin ext/misc/memtrace.c ******************/
   4078 /*
   4079 ** 2019-01-21
   4080 **
   4081 ** The author disclaims copyright to this source code.  In place of
   4082 ** a legal notice, here is a blessing:
   4083 **
   4084 **    May you do good and not evil.
   4085 **    May you find forgiveness for yourself and forgive others.
   4086 **    May you share freely, never taking more than you give.
   4087 **
   4088 *************************************************************************
   4089 **
   4090 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
   4091 ** mechanism to add a tracing layer on top of SQLite.  If this extension
   4092 ** is registered prior to sqlite3_initialize(), it will cause all memory
   4093 ** allocation activities to be logged on standard output, or to some other
   4094 ** FILE specified by the initializer.
   4095 **
   4096 ** This file needs to be compiled into the application that uses it.
   4097 **
   4098 ** This extension is used to implement the --memtrace option of the
   4099 ** command-line shell.
   4100 */
   4101 #include <assert.h>
   4102 #include <string.h>
   4103 #include <stdio.h>
   4104 
   4105 /* The original memory allocation routines */
   4106 static sqlite3_mem_methods memtraceBase;
   4107 static FILE *memtraceOut;
   4108 
   4109 /* Methods that trace memory allocations */
   4110 static void *memtraceMalloc(int n){
   4111   if( memtraceOut ){
   4112     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
   4113             memtraceBase.xRoundup(n));
   4114   }
   4115   return memtraceBase.xMalloc(n);
   4116 }
   4117 static void memtraceFree(void *p){
   4118   if( p==0 ) return;
   4119   if( memtraceOut ){
   4120     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
   4121   }
   4122   memtraceBase.xFree(p);
   4123 }
   4124 static void *memtraceRealloc(void *p, int n){
   4125   if( p==0 ) return memtraceMalloc(n);
   4126   if( n==0 ){
   4127     memtraceFree(p);
   4128     return 0;
   4129   }
   4130   if( memtraceOut ){
   4131     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
   4132             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
   4133   }
   4134   return memtraceBase.xRealloc(p, n);
   4135 }
   4136 static int memtraceSize(void *p){
   4137   return memtraceBase.xSize(p);
   4138 }
   4139 static int memtraceRoundup(int n){
   4140   return memtraceBase.xRoundup(n);
   4141 }
   4142 static int memtraceInit(void *p){
   4143   return memtraceBase.xInit(p);
   4144 }
   4145 static void memtraceShutdown(void *p){
   4146   memtraceBase.xShutdown(p);
   4147 }
   4148 
   4149 /* The substitute memory allocator */
   4150 static sqlite3_mem_methods ersaztMethods = {
   4151   memtraceMalloc,
   4152   memtraceFree,
   4153   memtraceRealloc,
   4154   memtraceSize,
   4155   memtraceRoundup,
   4156   memtraceInit,
   4157   memtraceShutdown,
   4158   0
   4159 };
   4160 
   4161 /* Begin tracing memory allocations to out. */
   4162 static int sqlite3MemTraceActivate(FILE *out){
   4163   int rc = SQLITE_OK;
   4164   if( memtraceBase.xMalloc==0 ){
   4165     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
   4166     if( rc==SQLITE_OK ){
   4167       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
   4168     }
   4169   }
   4170   memtraceOut = out;
   4171   return rc;
   4172 }
   4173 
   4174 /* Deactivate memory tracing */
   4175 static int sqlite3MemTraceDeactivate(void){
   4176   int rc = SQLITE_OK;
   4177   if( memtraceBase.xMalloc!=0 ){
   4178     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
   4179     if( rc==SQLITE_OK ){
   4180       memset(&memtraceBase, 0, sizeof(memtraceBase));
   4181     }
   4182   }
   4183   memtraceOut = 0;
   4184   return rc;
   4185 }
   4186 
   4187 /************************* End ext/misc/memtrace.c ********************/
   4188 /************************* Begin ext/misc/pcachetrace.c ******************/
   4189 /*
   4190 ** 2023-06-21
   4191 **
   4192 ** The author disclaims copyright to this source code.  In place of
   4193 ** a legal notice, here is a blessing:
   4194 **
   4195 **    May you do good and not evil.
   4196 **    May you find forgiveness for yourself and forgive others.
   4197 **    May you share freely, never taking more than you give.
   4198 **
   4199 *************************************************************************
   4200 **
   4201 ** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
   4202 ** mechanism to add a tracing layer on top of pluggable page cache of
   4203 ** SQLite.  If this extension is registered prior to sqlite3_initialize(),
   4204 ** it will cause all page cache activities to be logged on standard output,
   4205 ** or to some other FILE specified by the initializer.
   4206 **
   4207 ** This file needs to be compiled into the application that uses it.
   4208 **
   4209 ** This extension is used to implement the --pcachetrace option of the
   4210 ** command-line shell.
   4211 */
   4212 #include <assert.h>
   4213 #include <string.h>
   4214 #include <stdio.h>
   4215 
   4216 /* The original page cache routines */
   4217 static sqlite3_pcache_methods2 pcacheBase;
   4218 static FILE *pcachetraceOut;
   4219 
   4220 /* Methods that trace pcache activity */
   4221 static int pcachetraceInit(void *pArg){
   4222   int nRes;
   4223   if( pcachetraceOut ){
   4224     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
   4225   }
   4226   nRes = pcacheBase.xInit(pArg);
   4227   if( pcachetraceOut ){
   4228     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
   4229   }
   4230   return nRes;
   4231 }
   4232 static void pcachetraceShutdown(void *pArg){
   4233   if( pcachetraceOut ){
   4234     fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
   4235   }
   4236   pcacheBase.xShutdown(pArg);
   4237 }
   4238 static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
   4239   sqlite3_pcache *pRes;
   4240   if( pcachetraceOut ){
   4241     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
   4242             szPage, szExtra, bPurge);
   4243   }
   4244   pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
   4245   if( pcachetraceOut ){
   4246     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
   4247             szPage, szExtra, bPurge, pRes);
   4248   }
   4249   return pRes;
   4250 }
   4251 static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
   4252   if( pcachetraceOut ){
   4253     fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
   4254   }
   4255   pcacheBase.xCachesize(p, nCachesize);
   4256 }
   4257 static int pcachetracePagecount(sqlite3_pcache *p){
   4258   int nRes;
   4259   if( pcachetraceOut ){
   4260     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
   4261   }
   4262   nRes = pcacheBase.xPagecount(p);
   4263   if( pcachetraceOut ){
   4264     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
   4265   }
   4266   return nRes;
   4267 }
   4268 static sqlite3_pcache_page *pcachetraceFetch(
   4269   sqlite3_pcache *p,
   4270   unsigned key,
   4271   int crFg
   4272 ){
   4273   sqlite3_pcache_page *pRes;
   4274   if( pcachetraceOut ){
   4275     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
   4276   }
   4277   pRes = pcacheBase.xFetch(p, key, crFg);
   4278   if( pcachetraceOut ){
   4279     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
   4280             p, key, crFg, pRes);
   4281   }
   4282   return pRes;
   4283 }
   4284 static void pcachetraceUnpin(
   4285   sqlite3_pcache *p,
   4286   sqlite3_pcache_page *pPg,
   4287   int bDiscard
   4288 ){
   4289   if( pcachetraceOut ){
   4290     fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
   4291             p, pPg, bDiscard);
   4292   }
   4293   pcacheBase.xUnpin(p, pPg, bDiscard);
   4294 }
   4295 static void pcachetraceRekey(
   4296   sqlite3_pcache *p,
   4297   sqlite3_pcache_page *pPg,
   4298   unsigned oldKey,
   4299   unsigned newKey
   4300 ){
   4301   if( pcachetraceOut ){
   4302     fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
   4303         p, pPg, oldKey, newKey);
   4304   }
   4305   pcacheBase.xRekey(p, pPg, oldKey, newKey);
   4306 }
   4307 static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
   4308   if( pcachetraceOut ){
   4309     fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
   4310   }
   4311   pcacheBase.xTruncate(p, n);
   4312 }
   4313 static void pcachetraceDestroy(sqlite3_pcache *p){
   4314   if( pcachetraceOut ){
   4315     fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
   4316   }
   4317   pcacheBase.xDestroy(p);
   4318 }
   4319 static void pcachetraceShrink(sqlite3_pcache *p){
   4320   if( pcachetraceOut ){
   4321     fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
   4322   }
   4323   pcacheBase.xShrink(p);
   4324 }
   4325 
   4326 /* The substitute pcache methods */
   4327 static sqlite3_pcache_methods2 ersaztPcacheMethods = {
   4328   0,
   4329   0,
   4330   pcachetraceInit,
   4331   pcachetraceShutdown,
   4332   pcachetraceCreate,
   4333   pcachetraceCachesize,
   4334   pcachetracePagecount,
   4335   pcachetraceFetch,
   4336   pcachetraceUnpin,
   4337   pcachetraceRekey,
   4338   pcachetraceTruncate,
   4339   pcachetraceDestroy,
   4340   pcachetraceShrink
   4341 };
   4342 
   4343 /* Begin tracing memory allocations to out. */
   4344 static int sqlite3PcacheTraceActivate(FILE *out){
   4345   int rc = SQLITE_OK;
   4346   if( pcacheBase.xFetch==0 ){
   4347     rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
   4348     if( rc==SQLITE_OK ){
   4349       rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
   4350     }
   4351   }
   4352   pcachetraceOut = out;
   4353   return rc;
   4354 }
   4355 
   4356 /* Deactivate memory tracing */
   4357 static int sqlite3PcacheTraceDeactivate(void){
   4358   int rc = SQLITE_OK;
   4359   if( pcacheBase.xFetch!=0 ){
   4360     rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
   4361     if( rc==SQLITE_OK ){
   4362       memset(&pcacheBase, 0, sizeof(pcacheBase));
   4363     }
   4364   }
   4365   pcachetraceOut = 0;
   4366   return rc;
   4367 }
   4368 
   4369 /************************* End ext/misc/pcachetrace.c ********************/
   4370 /************************* Begin ext/misc/shathree.c ******************/
   4371 /*
   4372 ** 2017-03-08
   4373 **
   4374 ** The author disclaims copyright to this source code.  In place of
   4375 ** a legal notice, here is a blessing:
   4376 **
   4377 **    May you do good and not evil.
   4378 **    May you find forgiveness for yourself and forgive others.
   4379 **    May you share freely, never taking more than you give.
   4380 **
   4381 ******************************************************************************
   4382 **
   4383 ** This SQLite extension implements functions that compute SHA3 hashes
   4384 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
   4385 ** Three SQL functions are implemented:
   4386 **
   4387 **     sha3(X,SIZE)
   4388 **     sha3_agg(Y,SIZE)
   4389 **     sha3_query(Z,SIZE)
   4390 **
   4391 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
   4392 ** X is NULL.  If inputs X is text, the UTF-8 rendering of that text is
   4393 ** used to compute the hash.  If X is a BLOB, then the binary data of the
   4394 ** blob is used to compute the hash.  If X is an integer or real number,
   4395 ** then that number if converted into UTF-8 text and the hash is computed
   4396 ** over the text.
   4397 **
   4398 ** The sha3_agg(Y) function computes the SHA3 hash of all Y inputs.  Since
   4399 ** order is important for the hash, it is recommended that the Y expression
   4400 ** by followed by an ORDER BY clause to guarantee that the inputs occur
   4401 ** in the desired order.
   4402 **
   4403 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
   4404 ** and returns a hash of their results.
   4405 **
   4406 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
   4407 ** is used.  If SIZE is included it must be one of the integers 224, 256,
   4408 ** 384, or 512, to determine SHA3 hash variant that is computed.
   4409 **
   4410 ** Because the sha3_agg() and sha3_query() functions compute a hash over
   4411 ** multiple values, the values are encode to use include type information.
   4412 **
   4413 ** In sha3_agg(), the sequence of bytes that gets hashed for each input
   4414 ** Y depends on the datatype of Y:
   4415 **
   4416 **    typeof(Y)='null'         A single "N" is hashed.  (One byte)
   4417 **
   4418 **    typeof(Y)='integer'      The data hash is the character "I" followed
   4419 **                             by an 8-byte big-endian binary of the
   4420 **                             64-bit signed integer.  (Nine bytes total.)
   4421 **
   4422 **    typeof(Y)='real'         The character "F" followed by an 8-byte
   4423 **                             big-ending binary of the double.  (Nine
   4424 **                             bytes total.)
   4425 **
   4426 **    typeof(Y)='text'         The hash is over prefix "Tnnn:" followed
   4427 **                             by the UTF8 encoding of the text.  The "nnn"
   4428 **                             in the prefix is the minimum-length decimal
   4429 **                             representation of the octet_length of the text.
   4430 **                             Notice the ":" at the end of the prefix, which
   4431 **                             is needed to separate the prefix from the
   4432 **                             content in cases where the content starts
   4433 **                             with a digit.
   4434 **
   4435 **    typeof(Y)='blob'         The hash is taken over prefix "Bnnn:" followed
   4436 **                             by the binary content of the blob.  The "nnn"
   4437 **                             in the prefix is the minimum-length decimal
   4438 **                             representation of the byte-length of the blob.
   4439 **
   4440 ** According to the rules above, all of the following SELECT statements
   4441 ** should return TRUE:
   4442 **
   4443 **    SELECT sha3(1) = sha3('1');
   4444 **
   4445 **    SELECT sha3('hello') = sha3(x'68656c6c6f');
   4446 **
   4447 **    WITH a(x) AS (VALUES('xyzzy'))
   4448 **      SELECT sha3_agg(x) = sha3('T5:xyzzy')            FROM a;
   4449 **
   4450 **    WITH a(x) AS (VALUES(x'010203'))
   4451 **      SELECT sha3_agg(x) = sha3(x'42333a010203')       FROM a;
   4452 **
   4453 **    WITH a(x) AS (VALUES(0x123456))
   4454 **      SELECT sha3_agg(x) = sha3(x'490000000000123456') FROM a;
   4455 **
   4456 **    WITH a(x) AS (VALUES(100.015625))
   4457 **      SELECT sha3_agg(x) = sha3(x'464059010000000000') FROM a;
   4458 **
   4459 **    WITH a(x) AS (VALUES(NULL))
   4460 **      SELECT sha3_agg(x) = sha3('N') FROM a;
   4461 **
   4462 **
   4463 ** In sha3_query(), individual column values are encoded as with
   4464 ** sha3_agg(), but with the addition that a single "R" character is
   4465 ** inserted at the start of each row.
   4466 **
   4467 ** Note that sha3_agg() hashes rows for which Y is NULL.  Add a FILTER
   4468 ** clause if NULL rows should be excluded:
   4469 **
   4470 **    SELECT sha3_agg(x ORDER BY rowid) FILTER(WHERE x NOT NULL) FROM t1;
   4471 */
   4472 /* #include "sqlite3ext.h" */
   4473 SQLITE_EXTENSION_INIT1
   4474 #include <assert.h>
   4475 #include <string.h>
   4476 #include <stdarg.h>
   4477 
   4478 #ifndef SQLITE_AMALGAMATION
   4479 /* typedef sqlite3_uint64 u64; */
   4480 #endif /* SQLITE_AMALGAMATION */
   4481 
   4482 /******************************************************************************
   4483 ** The Hash Engine
   4484 */
   4485 /*
   4486 ** Macros to determine whether the machine is big or little endian,
   4487 ** and whether or not that determination is run-time or compile-time.
   4488 **
   4489 ** For best performance, an attempt is made to guess at the byte-order
   4490 ** using C-preprocessor macros.  If that is unsuccessful, or if
   4491 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
   4492 ** at run-time.
   4493 */
   4494 #ifndef SHA3_BYTEORDER
   4495 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
   4496      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
   4497      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
   4498      defined(__arm__)
   4499 #   define SHA3_BYTEORDER    1234
   4500 # elif defined(sparc)    || defined(__ppc__)
   4501 #   define SHA3_BYTEORDER    4321
   4502 # else
   4503 #   define SHA3_BYTEORDER 0
   4504 # endif
   4505 #endif
   4506 
   4507 
   4508 /*
   4509 ** State structure for a SHA3 hash in progress
   4510 */
   4511 typedef struct SHA3Context SHA3Context;
   4512 struct SHA3Context {
   4513   union {
   4514     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
   4515     unsigned char x[1600];    /* ... or 1600 bytes */
   4516   } u;
   4517   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
   4518   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
   4519   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
   4520   unsigned iSize;        /* 224, 256, 358, or 512 */
   4521 };
   4522 
   4523 /*
   4524 ** A single step of the Keccak mixing function for a 1600-bit state
   4525 */
   4526 static void KeccakF1600Step(SHA3Context *p){
   4527   int i;
   4528   u64 b0, b1, b2, b3, b4;
   4529   u64 c0, c1, c2, c3, c4;
   4530   u64 d0, d1, d2, d3, d4;
   4531   static const u64 RC[] = {
   4532     0x0000000000000001ULL,  0x0000000000008082ULL,
   4533     0x800000000000808aULL,  0x8000000080008000ULL,
   4534     0x000000000000808bULL,  0x0000000080000001ULL,
   4535     0x8000000080008081ULL,  0x8000000000008009ULL,
   4536     0x000000000000008aULL,  0x0000000000000088ULL,
   4537     0x0000000080008009ULL,  0x000000008000000aULL,
   4538     0x000000008000808bULL,  0x800000000000008bULL,
   4539     0x8000000000008089ULL,  0x8000000000008003ULL,
   4540     0x8000000000008002ULL,  0x8000000000000080ULL,
   4541     0x000000000000800aULL,  0x800000008000000aULL,
   4542     0x8000000080008081ULL,  0x8000000000008080ULL,
   4543     0x0000000080000001ULL,  0x8000000080008008ULL
   4544   };
   4545 # define a00 (p->u.s[0])
   4546 # define a01 (p->u.s[1])
   4547 # define a02 (p->u.s[2])
   4548 # define a03 (p->u.s[3])
   4549 # define a04 (p->u.s[4])
   4550 # define a10 (p->u.s[5])
   4551 # define a11 (p->u.s[6])
   4552 # define a12 (p->u.s[7])
   4553 # define a13 (p->u.s[8])
   4554 # define a14 (p->u.s[9])
   4555 # define a20 (p->u.s[10])
   4556 # define a21 (p->u.s[11])
   4557 # define a22 (p->u.s[12])
   4558 # define a23 (p->u.s[13])
   4559 # define a24 (p->u.s[14])
   4560 # define a30 (p->u.s[15])
   4561 # define a31 (p->u.s[16])
   4562 # define a32 (p->u.s[17])
   4563 # define a33 (p->u.s[18])
   4564 # define a34 (p->u.s[19])
   4565 # define a40 (p->u.s[20])
   4566 # define a41 (p->u.s[21])
   4567 # define a42 (p->u.s[22])
   4568 # define a43 (p->u.s[23])
   4569 # define a44 (p->u.s[24])
   4570 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
   4571 
   4572   for(i=0; i<24; i+=4){
   4573     c0 = a00^a10^a20^a30^a40;
   4574     c1 = a01^a11^a21^a31^a41;
   4575     c2 = a02^a12^a22^a32^a42;
   4576     c3 = a03^a13^a23^a33^a43;
   4577     c4 = a04^a14^a24^a34^a44;
   4578     d0 = c4^ROL64(c1, 1);
   4579     d1 = c0^ROL64(c2, 1);
   4580     d2 = c1^ROL64(c3, 1);
   4581     d3 = c2^ROL64(c4, 1);
   4582     d4 = c3^ROL64(c0, 1);
   4583 
   4584     b0 = (a00^d0);
   4585     b1 = ROL64((a11^d1), 44);
   4586     b2 = ROL64((a22^d2), 43);
   4587     b3 = ROL64((a33^d3), 21);
   4588     b4 = ROL64((a44^d4), 14);
   4589     a00 =   b0 ^((~b1)&  b2 );
   4590     a00 ^= RC[i];
   4591     a11 =   b1 ^((~b2)&  b3 );
   4592     a22 =   b2 ^((~b3)&  b4 );
   4593     a33 =   b3 ^((~b4)&  b0 );
   4594     a44 =   b4 ^((~b0)&  b1 );
   4595 
   4596     b2 = ROL64((a20^d0), 3);
   4597     b3 = ROL64((a31^d1), 45);
   4598     b4 = ROL64((a42^d2), 61);
   4599     b0 = ROL64((a03^d3), 28);
   4600     b1 = ROL64((a14^d4), 20);
   4601     a20 =   b0 ^((~b1)&  b2 );
   4602     a31 =   b1 ^((~b2)&  b3 );
   4603     a42 =   b2 ^((~b3)&  b4 );
   4604     a03 =   b3 ^((~b4)&  b0 );
   4605     a14 =   b4 ^((~b0)&  b1 );
   4606 
   4607     b4 = ROL64((a40^d0), 18);
   4608     b0 = ROL64((a01^d1), 1);
   4609     b1 = ROL64((a12^d2), 6);
   4610     b2 = ROL64((a23^d3), 25);
   4611     b3 = ROL64((a34^d4), 8);
   4612     a40 =   b0 ^((~b1)&  b2 );
   4613     a01 =   b1 ^((~b2)&  b3 );
   4614     a12 =   b2 ^((~b3)&  b4 );
   4615     a23 =   b3 ^((~b4)&  b0 );
   4616     a34 =   b4 ^((~b0)&  b1 );
   4617 
   4618     b1 = ROL64((a10^d0), 36);
   4619     b2 = ROL64((a21^d1), 10);
   4620     b3 = ROL64((a32^d2), 15);
   4621     b4 = ROL64((a43^d3), 56);
   4622     b0 = ROL64((a04^d4), 27);
   4623     a10 =   b0 ^((~b1)&  b2 );
   4624     a21 =   b1 ^((~b2)&  b3 );
   4625     a32 =   b2 ^((~b3)&  b4 );
   4626     a43 =   b3 ^((~b4)&  b0 );
   4627     a04 =   b4 ^((~b0)&  b1 );
   4628 
   4629     b3 = ROL64((a30^d0), 41);
   4630     b4 = ROL64((a41^d1), 2);
   4631     b0 = ROL64((a02^d2), 62);
   4632     b1 = ROL64((a13^d3), 55);
   4633     b2 = ROL64((a24^d4), 39);
   4634     a30 =   b0 ^((~b1)&  b2 );
   4635     a41 =   b1 ^((~b2)&  b3 );
   4636     a02 =   b2 ^((~b3)&  b4 );
   4637     a13 =   b3 ^((~b4)&  b0 );
   4638     a24 =   b4 ^((~b0)&  b1 );
   4639 
   4640     c0 = a00^a20^a40^a10^a30;
   4641     c1 = a11^a31^a01^a21^a41;
   4642     c2 = a22^a42^a12^a32^a02;
   4643     c3 = a33^a03^a23^a43^a13;
   4644     c4 = a44^a14^a34^a04^a24;
   4645     d0 = c4^ROL64(c1, 1);
   4646     d1 = c0^ROL64(c2, 1);
   4647     d2 = c1^ROL64(c3, 1);
   4648     d3 = c2^ROL64(c4, 1);
   4649     d4 = c3^ROL64(c0, 1);
   4650 
   4651     b0 = (a00^d0);
   4652     b1 = ROL64((a31^d1), 44);
   4653     b2 = ROL64((a12^d2), 43);
   4654     b3 = ROL64((a43^d3), 21);
   4655     b4 = ROL64((a24^d4), 14);
   4656     a00 =   b0 ^((~b1)&  b2 );
   4657     a00 ^= RC[i+1];
   4658     a31 =   b1 ^((~b2)&  b3 );
   4659     a12 =   b2 ^((~b3)&  b4 );
   4660     a43 =   b3 ^((~b4)&  b0 );
   4661     a24 =   b4 ^((~b0)&  b1 );
   4662 
   4663     b2 = ROL64((a40^d0), 3);
   4664     b3 = ROL64((a21^d1), 45);
   4665     b4 = ROL64((a02^d2), 61);
   4666     b0 = ROL64((a33^d3), 28);
   4667     b1 = ROL64((a14^d4), 20);
   4668     a40 =   b0 ^((~b1)&  b2 );
   4669     a21 =   b1 ^((~b2)&  b3 );
   4670     a02 =   b2 ^((~b3)&  b4 );
   4671     a33 =   b3 ^((~b4)&  b0 );
   4672     a14 =   b4 ^((~b0)&  b1 );
   4673 
   4674     b4 = ROL64((a30^d0), 18);
   4675     b0 = ROL64((a11^d1), 1);
   4676     b1 = ROL64((a42^d2), 6);
   4677     b2 = ROL64((a23^d3), 25);
   4678     b3 = ROL64((a04^d4), 8);
   4679     a30 =   b0 ^((~b1)&  b2 );
   4680     a11 =   b1 ^((~b2)&  b3 );
   4681     a42 =   b2 ^((~b3)&  b4 );
   4682     a23 =   b3 ^((~b4)&  b0 );
   4683     a04 =   b4 ^((~b0)&  b1 );
   4684 
   4685     b1 = ROL64((a20^d0), 36);
   4686     b2 = ROL64((a01^d1), 10);
   4687     b3 = ROL64((a32^d2), 15);
   4688     b4 = ROL64((a13^d3), 56);
   4689     b0 = ROL64((a44^d4), 27);
   4690     a20 =   b0 ^((~b1)&  b2 );
   4691     a01 =   b1 ^((~b2)&  b3 );
   4692     a32 =   b2 ^((~b3)&  b4 );
   4693     a13 =   b3 ^((~b4)&  b0 );
   4694     a44 =   b4 ^((~b0)&  b1 );
   4695 
   4696     b3 = ROL64((a10^d0), 41);
   4697     b4 = ROL64((a41^d1), 2);
   4698     b0 = ROL64((a22^d2), 62);
   4699     b1 = ROL64((a03^d3), 55);
   4700     b2 = ROL64((a34^d4), 39);
   4701     a10 =   b0 ^((~b1)&  b2 );
   4702     a41 =   b1 ^((~b2)&  b3 );
   4703     a22 =   b2 ^((~b3)&  b4 );
   4704     a03 =   b3 ^((~b4)&  b0 );
   4705     a34 =   b4 ^((~b0)&  b1 );
   4706 
   4707     c0 = a00^a40^a30^a20^a10;
   4708     c1 = a31^a21^a11^a01^a41;
   4709     c2 = a12^a02^a42^a32^a22;
   4710     c3 = a43^a33^a23^a13^a03;
   4711     c4 = a24^a14^a04^a44^a34;
   4712     d0 = c4^ROL64(c1, 1);
   4713     d1 = c0^ROL64(c2, 1);
   4714     d2 = c1^ROL64(c3, 1);
   4715     d3 = c2^ROL64(c4, 1);
   4716     d4 = c3^ROL64(c0, 1);
   4717 
   4718     b0 = (a00^d0);
   4719     b1 = ROL64((a21^d1), 44);
   4720     b2 = ROL64((a42^d2), 43);
   4721     b3 = ROL64((a13^d3), 21);
   4722     b4 = ROL64((a34^d4), 14);
   4723     a00 =   b0 ^((~b1)&  b2 );
   4724     a00 ^= RC[i+2];
   4725     a21 =   b1 ^((~b2)&  b3 );
   4726     a42 =   b2 ^((~b3)&  b4 );
   4727     a13 =   b3 ^((~b4)&  b0 );
   4728     a34 =   b4 ^((~b0)&  b1 );
   4729 
   4730     b2 = ROL64((a30^d0), 3);
   4731     b3 = ROL64((a01^d1), 45);
   4732     b4 = ROL64((a22^d2), 61);
   4733     b0 = ROL64((a43^d3), 28);
   4734     b1 = ROL64((a14^d4), 20);
   4735     a30 =   b0 ^((~b1)&  b2 );
   4736     a01 =   b1 ^((~b2)&  b3 );
   4737     a22 =   b2 ^((~b3)&  b4 );
   4738     a43 =   b3 ^((~b4)&  b0 );
   4739     a14 =   b4 ^((~b0)&  b1 );
   4740 
   4741     b4 = ROL64((a10^d0), 18);
   4742     b0 = ROL64((a31^d1), 1);
   4743     b1 = ROL64((a02^d2), 6);
   4744     b2 = ROL64((a23^d3), 25);
   4745     b3 = ROL64((a44^d4), 8);
   4746     a10 =   b0 ^((~b1)&  b2 );
   4747     a31 =   b1 ^((~b2)&  b3 );
   4748     a02 =   b2 ^((~b3)&  b4 );
   4749     a23 =   b3 ^((~b4)&  b0 );
   4750     a44 =   b4 ^((~b0)&  b1 );
   4751 
   4752     b1 = ROL64((a40^d0), 36);
   4753     b2 = ROL64((a11^d1), 10);
   4754     b3 = ROL64((a32^d2), 15);
   4755     b4 = ROL64((a03^d3), 56);
   4756     b0 = ROL64((a24^d4), 27);
   4757     a40 =   b0 ^((~b1)&  b2 );
   4758     a11 =   b1 ^((~b2)&  b3 );
   4759     a32 =   b2 ^((~b3)&  b4 );
   4760     a03 =   b3 ^((~b4)&  b0 );
   4761     a24 =   b4 ^((~b0)&  b1 );
   4762 
   4763     b3 = ROL64((a20^d0), 41);
   4764     b4 = ROL64((a41^d1), 2);
   4765     b0 = ROL64((a12^d2), 62);
   4766     b1 = ROL64((a33^d3), 55);
   4767     b2 = ROL64((a04^d4), 39);
   4768     a20 =   b0 ^((~b1)&  b2 );
   4769     a41 =   b1 ^((~b2)&  b3 );
   4770     a12 =   b2 ^((~b3)&  b4 );
   4771     a33 =   b3 ^((~b4)&  b0 );
   4772     a04 =   b4 ^((~b0)&  b1 );
   4773 
   4774     c0 = a00^a30^a10^a40^a20;
   4775     c1 = a21^a01^a31^a11^a41;
   4776     c2 = a42^a22^a02^a32^a12;
   4777     c3 = a13^a43^a23^a03^a33;
   4778     c4 = a34^a14^a44^a24^a04;
   4779     d0 = c4^ROL64(c1, 1);
   4780     d1 = c0^ROL64(c2, 1);
   4781     d2 = c1^ROL64(c3, 1);
   4782     d3 = c2^ROL64(c4, 1);
   4783     d4 = c3^ROL64(c0, 1);
   4784 
   4785     b0 = (a00^d0);
   4786     b1 = ROL64((a01^d1), 44);
   4787     b2 = ROL64((a02^d2), 43);
   4788     b3 = ROL64((a03^d3), 21);
   4789     b4 = ROL64((a04^d4), 14);
   4790     a00 =   b0 ^((~b1)&  b2 );
   4791     a00 ^= RC[i+3];
   4792     a01 =   b1 ^((~b2)&  b3 );
   4793     a02 =   b2 ^((~b3)&  b4 );
   4794     a03 =   b3 ^((~b4)&  b0 );
   4795     a04 =   b4 ^((~b0)&  b1 );
   4796 
   4797     b2 = ROL64((a10^d0), 3);
   4798     b3 = ROL64((a11^d1), 45);
   4799     b4 = ROL64((a12^d2), 61);
   4800     b0 = ROL64((a13^d3), 28);
   4801     b1 = ROL64((a14^d4), 20);
   4802     a10 =   b0 ^((~b1)&  b2 );
   4803     a11 =   b1 ^((~b2)&  b3 );
   4804     a12 =   b2 ^((~b3)&  b4 );
   4805     a13 =   b3 ^((~b4)&  b0 );
   4806     a14 =   b4 ^((~b0)&  b1 );
   4807 
   4808     b4 = ROL64((a20^d0), 18);
   4809     b0 = ROL64((a21^d1), 1);
   4810     b1 = ROL64((a22^d2), 6);
   4811     b2 = ROL64((a23^d3), 25);
   4812     b3 = ROL64((a24^d4), 8);
   4813     a20 =   b0 ^((~b1)&  b2 );
   4814     a21 =   b1 ^((~b2)&  b3 );
   4815     a22 =   b2 ^((~b3)&  b4 );
   4816     a23 =   b3 ^((~b4)&  b0 );
   4817     a24 =   b4 ^((~b0)&  b1 );
   4818 
   4819     b1 = ROL64((a30^d0), 36);
   4820     b2 = ROL64((a31^d1), 10);
   4821     b3 = ROL64((a32^d2), 15);
   4822     b4 = ROL64((a33^d3), 56);
   4823     b0 = ROL64((a34^d4), 27);
   4824     a30 =   b0 ^((~b1)&  b2 );
   4825     a31 =   b1 ^((~b2)&  b3 );
   4826     a32 =   b2 ^((~b3)&  b4 );
   4827     a33 =   b3 ^((~b4)&  b0 );
   4828     a34 =   b4 ^((~b0)&  b1 );
   4829 
   4830     b3 = ROL64((a40^d0), 41);
   4831     b4 = ROL64((a41^d1), 2);
   4832     b0 = ROL64((a42^d2), 62);
   4833     b1 = ROL64((a43^d3), 55);
   4834     b2 = ROL64((a44^d4), 39);
   4835     a40 =   b0 ^((~b1)&  b2 );
   4836     a41 =   b1 ^((~b2)&  b3 );
   4837     a42 =   b2 ^((~b3)&  b4 );
   4838     a43 =   b3 ^((~b4)&  b0 );
   4839     a44 =   b4 ^((~b0)&  b1 );
   4840   }
   4841 }
   4842 
   4843 /*
   4844 ** Initialize a new hash.  iSize determines the size of the hash
   4845 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
   4846 ** can be zero to use the default hash size of 256 bits.
   4847 */
   4848 static void SHA3Init(SHA3Context *p, int iSize){
   4849   memset(p, 0, sizeof(*p));
   4850   p->iSize = iSize;
   4851   if( iSize>=128 && iSize<=512 ){
   4852     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
   4853   }else{
   4854     p->nRate = (1600 - 2*256)/8;
   4855   }
   4856 #if SHA3_BYTEORDER==1234
   4857   /* Known to be little-endian at compile-time. No-op */
   4858 #elif SHA3_BYTEORDER==4321
   4859   p->ixMask = 7;  /* Big-endian */
   4860 #else
   4861   {
   4862     static unsigned int one = 1;
   4863     if( 1==*(unsigned char*)&one ){
   4864       /* Little endian.  No byte swapping. */
   4865       p->ixMask = 0;
   4866     }else{
   4867       /* Big endian.  Byte swap. */
   4868       p->ixMask = 7;
   4869     }
   4870   }
   4871 #endif
   4872 }
   4873 
   4874 /*
   4875 ** Make consecutive calls to the SHA3Update function to add new content
   4876 ** to the hash
   4877 */
   4878 static void SHA3Update(
   4879   SHA3Context *p,
   4880   const unsigned char *aData,
   4881   unsigned int nData
   4882 ){
   4883   unsigned int i = 0;
   4884   if( aData==0 ) return;
   4885 #if SHA3_BYTEORDER==1234
   4886   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
   4887     for(; i+7<nData; i+=8){
   4888       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
   4889       p->nLoaded += 8;
   4890       if( p->nLoaded>=p->nRate ){
   4891         KeccakF1600Step(p);
   4892         p->nLoaded = 0;
   4893       }
   4894     }
   4895   }
   4896 #endif
   4897   for(; i<nData; i++){
   4898 #if SHA3_BYTEORDER==1234
   4899     p->u.x[p->nLoaded] ^= aData[i];
   4900 #elif SHA3_BYTEORDER==4321
   4901     p->u.x[p->nLoaded^0x07] ^= aData[i];
   4902 #else
   4903     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
   4904 #endif
   4905     p->nLoaded++;
   4906     if( p->nLoaded==p->nRate ){
   4907       KeccakF1600Step(p);
   4908       p->nLoaded = 0;
   4909     }
   4910   }
   4911 }
   4912 
   4913 /*
   4914 ** After all content has been added, invoke SHA3Final() to compute
   4915 ** the final hash.  The function returns a pointer to the binary
   4916 ** hash value.
   4917 */
   4918 static unsigned char *SHA3Final(SHA3Context *p){
   4919   unsigned int i;
   4920   if( p->nLoaded==p->nRate-1 ){
   4921     const unsigned char c1 = 0x86;
   4922     SHA3Update(p, &c1, 1);
   4923   }else{
   4924     const unsigned char c2 = 0x06;
   4925     const unsigned char c3 = 0x80;
   4926     SHA3Update(p, &c2, 1);
   4927     p->nLoaded = p->nRate - 1;
   4928     SHA3Update(p, &c3, 1);
   4929   }
   4930   for(i=0; i<p->nRate; i++){
   4931     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
   4932   }
   4933   return &p->u.x[p->nRate];
   4934 }
   4935 /* End of the hashing logic
   4936 *****************************************************************************/
   4937 
   4938 /*
   4939 ** Implementation of the sha3(X,SIZE) function.
   4940 **
   4941 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
   4942 ** size is 256.  If X is a BLOB, it is hashed as is.
   4943 ** For all other non-NULL types of input, X is converted into a UTF-8 string
   4944 ** and the string is hashed without the trailing 0x00 terminator.  The hash
   4945 ** of a NULL value is NULL.
   4946 */
   4947 static void sha3Func(
   4948   sqlite3_context *context,
   4949   int argc,
   4950   sqlite3_value **argv
   4951 ){
   4952   SHA3Context cx;
   4953   int eType = sqlite3_value_type(argv[0]);
   4954   int nByte = sqlite3_value_bytes(argv[0]);
   4955   int iSize;
   4956   if( argc==1 ){
   4957     iSize = 256;
   4958   }else{
   4959     iSize = sqlite3_value_int(argv[1]);
   4960     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
   4961       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
   4962                                     "384 512", -1);
   4963       return;
   4964     }
   4965   }
   4966   if( eType==SQLITE_NULL ) return;
   4967   SHA3Init(&cx, iSize);
   4968   if( eType==SQLITE_BLOB ){
   4969     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
   4970   }else{
   4971     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
   4972   }
   4973   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
   4974 }
   4975 
   4976 /* Compute a string using sqlite3_vsnprintf() with a maximum length
   4977 ** of 50 bytes and add it to the hash.
   4978 */
   4979 static void sha3_step_vformat(
   4980   SHA3Context *p,                 /* Add content to this context */
   4981   const char *zFormat,
   4982   ...
   4983 ){
   4984   va_list ap;
   4985   int n;
   4986   char zBuf[50];
   4987   va_start(ap, zFormat);
   4988   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
   4989   va_end(ap);
   4990   n = (int)strlen(zBuf);
   4991   SHA3Update(p, (unsigned char*)zBuf, n);
   4992 }
   4993 
   4994 /*
   4995 ** Update a SHA3Context using a single sqlite3_value.
   4996 */
   4997 static void sha3UpdateFromValue(SHA3Context *p, sqlite3_value *pVal){
   4998   switch( sqlite3_value_type(pVal) ){
   4999     case SQLITE_NULL: {
   5000       SHA3Update(p, (const unsigned char*)"N",1);
   5001       break;
   5002     }
   5003     case SQLITE_INTEGER: {
   5004       sqlite3_uint64 u;
   5005       int j;
   5006       unsigned char x[9];
   5007       sqlite3_int64 v = sqlite3_value_int64(pVal);
   5008       memcpy(&u, &v, 8);
   5009       for(j=8; j>=1; j--){
   5010         x[j] = u & 0xff;
   5011         u >>= 8;
   5012       }
   5013       x[0] = 'I';
   5014       SHA3Update(p, x, 9);
   5015       break;
   5016     }
   5017     case SQLITE_FLOAT: {
   5018       sqlite3_uint64 u;
   5019       int j;
   5020       unsigned char x[9];
   5021       double r = sqlite3_value_double(pVal);
   5022       memcpy(&u, &r, 8);
   5023       for(j=8; j>=1; j--){
   5024         x[j] = u & 0xff;
   5025         u >>= 8;
   5026       }
   5027       x[0] = 'F';
   5028       SHA3Update(p,x,9);
   5029       break;
   5030     }
   5031     case SQLITE_TEXT: {
   5032       int n2 = sqlite3_value_bytes(pVal);
   5033       const unsigned char *z2 = sqlite3_value_text(pVal);
   5034       sha3_step_vformat(p,"T%d:",n2);
   5035       SHA3Update(p, z2, n2);
   5036       break;
   5037     }
   5038     case SQLITE_BLOB: {
   5039       int n2 = sqlite3_value_bytes(pVal);
   5040       const unsigned char *z2 = sqlite3_value_blob(pVal);
   5041       sha3_step_vformat(p,"B%d:",n2);
   5042       SHA3Update(p, z2, n2);
   5043       break;
   5044     }
   5045   }
   5046 }
   5047 
   5048 /*
   5049 ** Implementation of the sha3_query(SQL,SIZE) function.
   5050 **
   5051 ** This function compiles and runs the SQL statement(s) given in the
   5052 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
   5053 ** size is 256.
   5054 **
   5055 ** The format of the byte stream that is hashed is summarized as follows:
   5056 **
   5057 **       S<n>:<sql>
   5058 **       R
   5059 **       N
   5060 **       I<int>
   5061 **       F<ieee-float>
   5062 **       B<size>:<bytes>
   5063 **       T<size>:<text>
   5064 **
   5065 ** <sql> is the original SQL text for each statement run and <n> is
   5066 ** the size of that text.  The SQL text is UTF-8.  A single R character
   5067 ** occurs before the start of each row.  N means a NULL value.
   5068 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
   5069 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
   5070 ** B means blobs of <size> bytes.  T means text rendered as <size>
   5071 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
   5072 ** text integers.
   5073 **
   5074 ** For each SQL statement in the X input, there is one S segment.  Each
   5075 ** S segment is followed by zero or more R segments, one for each row in the
   5076 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
   5077 ** one for each column in the result set.  Segments are concatentated directly
   5078 ** with no delimiters of any kind.
   5079 */
   5080 static void sha3QueryFunc(
   5081   sqlite3_context *context,
   5082   int argc,
   5083   sqlite3_value **argv
   5084 ){
   5085   sqlite3 *db = sqlite3_context_db_handle(context);
   5086   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
   5087   sqlite3_stmt *pStmt = 0;
   5088   int nCol;                   /* Number of columns in the result set */
   5089   int i;                      /* Loop counter */
   5090   int rc;
   5091   int n;
   5092   const char *z;
   5093   SHA3Context cx;
   5094   int iSize;
   5095 
   5096   if( argc==1 ){
   5097     iSize = 256;
   5098   }else{
   5099     iSize = sqlite3_value_int(argv[1]);
   5100     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
   5101       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
   5102                                     "384 512", -1);
   5103       return;
   5104     }
   5105   }
   5106   if( zSql==0 ) return;
   5107   SHA3Init(&cx, iSize);
   5108   while( zSql[0] ){
   5109     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
   5110     if( rc ){
   5111       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
   5112                                    zSql, sqlite3_errmsg(db));
   5113       sqlite3_finalize(pStmt);
   5114       sqlite3_result_error(context, zMsg, -1);
   5115       sqlite3_free(zMsg);
   5116       return;
   5117     }
   5118     if( !sqlite3_stmt_readonly(pStmt) ){
   5119       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
   5120       sqlite3_finalize(pStmt);
   5121       sqlite3_result_error(context, zMsg, -1);
   5122       sqlite3_free(zMsg);
   5123       return;
   5124     }
   5125     nCol = sqlite3_column_count(pStmt);
   5126     z = sqlite3_sql(pStmt);
   5127     if( z ){
   5128       n = (int)strlen(z);
   5129       sha3_step_vformat(&cx,"S%d:",n);
   5130       SHA3Update(&cx,(unsigned char*)z,n);
   5131     }
   5132 
   5133     /* Compute a hash over the result of the query */
   5134     while( SQLITE_ROW==sqlite3_step(pStmt) ){
   5135       SHA3Update(&cx,(const unsigned char*)"R",1);
   5136       for(i=0; i<nCol; i++){
   5137         sha3UpdateFromValue(&cx, sqlite3_column_value(pStmt,i));
   5138       }
   5139     }
   5140     sqlite3_finalize(pStmt);
   5141   }
   5142   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
   5143 }
   5144 
   5145 /*
   5146 ** xStep function for sha3_agg().
   5147 */
   5148 static void sha3AggStep(
   5149   sqlite3_context *context,
   5150   int argc,
   5151   sqlite3_value **argv
   5152 ){
   5153   SHA3Context *p;
   5154   p = (SHA3Context*)sqlite3_aggregate_context(context, sizeof(*p));
   5155   if( p==0 ) return;
   5156   if( p->nRate==0 ){
   5157     int sz = 256;
   5158     if( argc==2 ){
   5159       sz = sqlite3_value_int(argv[1]);
   5160       if( sz!=224 && sz!=384 && sz!=512 ){
   5161         sz = 256;
   5162       }
   5163     }
   5164     SHA3Init(p, sz);
   5165   }
   5166   sha3UpdateFromValue(p, argv[0]);
   5167 }
   5168 
   5169 
   5170 /*
   5171 ** xFinal function for sha3_agg().
   5172 */
   5173 static void sha3AggFinal(sqlite3_context *context){
   5174   SHA3Context *p;
   5175   p = (SHA3Context*)sqlite3_aggregate_context(context, sizeof(*p));
   5176   if( p==0 ) return;
   5177   if( p->iSize ){
   5178     sqlite3_result_blob(context, SHA3Final(p), p->iSize/8, SQLITE_TRANSIENT);
   5179   }
   5180 }
   5181 
   5182 
   5183 
   5184 #ifdef _WIN32
   5185 
   5186 #endif
   5187 static int sqlite3_shathree_init(
   5188   sqlite3 *db,
   5189   char **pzErrMsg,
   5190   const sqlite3_api_routines *pApi
   5191 ){
   5192   int rc = SQLITE_OK;
   5193   SQLITE_EXTENSION_INIT2(pApi);
   5194   (void)pzErrMsg;  /* Unused parameter */
   5195   rc = sqlite3_create_function(db, "sha3", 1,
   5196                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
   5197                       0, sha3Func, 0, 0);
   5198   if( rc==SQLITE_OK ){
   5199     rc = sqlite3_create_function(db, "sha3", 2,
   5200                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
   5201                       0, sha3Func, 0, 0);
   5202   }
   5203   if( rc==SQLITE_OK ){
   5204     rc = sqlite3_create_function(db, "sha3_agg", 1,
   5205                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
   5206                       0, 0, sha3AggStep, sha3AggFinal);
   5207   }
   5208   if( rc==SQLITE_OK ){
   5209     rc = sqlite3_create_function(db, "sha3_agg", 2,
   5210                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
   5211                       0, 0, sha3AggStep, sha3AggFinal);
   5212   }
   5213   if( rc==SQLITE_OK ){
   5214     rc = sqlite3_create_function(db, "sha3_query", 1,
   5215                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
   5216                       0, sha3QueryFunc, 0, 0);
   5217   }
   5218   if( rc==SQLITE_OK ){
   5219     rc = sqlite3_create_function(db, "sha3_query", 2,
   5220                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
   5221                       0, sha3QueryFunc, 0, 0);
   5222   }
   5223   return rc;
   5224 }
   5225 
   5226 /************************* End ext/misc/shathree.c ********************/
   5227 /************************* Begin ext/misc/sha1.c ******************/
   5228 /*
   5229 ** 2017-01-27
   5230 **
   5231 ** The author disclaims copyright to this source code.  In place of
   5232 ** a legal notice, here is a blessing:
   5233 **
   5234 **    May you do good and not evil.
   5235 **    May you find forgiveness for yourself and forgive others.
   5236 **    May you share freely, never taking more than you give.
   5237 **
   5238 ******************************************************************************
   5239 **
   5240 ** This SQLite extension implements functions that compute SHA1 hashes.
   5241 ** Two SQL functions are implemented:
   5242 **
   5243 **     sha1(X)
   5244 **     sha1_query(Y)
   5245 **
   5246 ** The sha1(X) function computes the SHA1 hash of the input X, or NULL if
   5247 ** X is NULL.
   5248 **
   5249 ** The sha1_query(Y) function evalutes all queries in the SQL statements of Y
   5250 ** and returns a hash of their results.
   5251 */
   5252 /* #include "sqlite3ext.h" */
   5253 SQLITE_EXTENSION_INIT1
   5254 #include <assert.h>
   5255 #include <string.h>
   5256 #include <stdarg.h>
   5257 
   5258 /******************************************************************************
   5259 ** The Hash Engine
   5260 */
   5261 /* Context for the SHA1 hash */
   5262 typedef struct SHA1Context SHA1Context;
   5263 struct SHA1Context {
   5264   unsigned int state[5];
   5265   unsigned int count[2];
   5266   unsigned char buffer[64];
   5267 };
   5268 
   5269 #define SHA_ROT(x,l,r) ((x) << (l) | (x) >> (r))
   5270 #define rol(x,k) SHA_ROT(x,k,32-(k))
   5271 #define ror(x,k) SHA_ROT(x,32-(k),k)
   5272 
   5273 #define blk0le(i) (block[i] = (ror(block[i],8)&0xFF00FF00) \
   5274     |(rol(block[i],8)&0x00FF00FF))
   5275 #define blk0be(i) block[i]
   5276 #define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \
   5277     ^block[(i+2)&15]^block[i&15],1))
   5278 
   5279 /*
   5280  * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1
   5281  *
   5282  * Rl0() for little-endian and Rb0() for big-endian.  Endianness is
   5283  * determined at run-time.
   5284  */
   5285 #define Rl0(v,w,x,y,z,i) \
   5286     z+=((w&(x^y))^y)+blk0le(i)+0x5A827999+rol(v,5);w=ror(w,2);
   5287 #define Rb0(v,w,x,y,z,i) \
   5288     z+=((w&(x^y))^y)+blk0be(i)+0x5A827999+rol(v,5);w=ror(w,2);
   5289 #define R1(v,w,x,y,z,i) \
   5290     z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=ror(w,2);
   5291 #define R2(v,w,x,y,z,i) \
   5292     z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=ror(w,2);
   5293 #define R3(v,w,x,y,z,i) \
   5294     z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=ror(w,2);
   5295 #define R4(v,w,x,y,z,i) \
   5296     z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=ror(w,2);
   5297 
   5298 /*
   5299  * Hash a single 512-bit block. This is the core of the algorithm.
   5300  */
   5301 static void SHA1Transform(unsigned int state[5], const unsigned char buffer[64]){
   5302   unsigned int qq[5]; /* a, b, c, d, e; */
   5303   static int one = 1;
   5304   unsigned int block[16];
   5305   memcpy(block, buffer, 64);
   5306   memcpy(qq,state,5*sizeof(unsigned int));
   5307 
   5308 #define a qq[0]
   5309 #define b qq[1]
   5310 #define c qq[2]
   5311 #define d qq[3]
   5312 #define e qq[4]
   5313 
   5314   /* Copy p->state[] to working vars */
   5315   /*
   5316   a = state[0];
   5317   b = state[1];
   5318   c = state[2];
   5319   d = state[3];
   5320   e = state[4];
   5321   */
   5322 
   5323   /* 4 rounds of 20 operations each. Loop unrolled. */
   5324   if( 1 == *(unsigned char*)&one ){
   5325     Rl0(a,b,c,d,e, 0); Rl0(e,a,b,c,d, 1); Rl0(d,e,a,b,c, 2); Rl0(c,d,e,a,b, 3);
   5326     Rl0(b,c,d,e,a, 4); Rl0(a,b,c,d,e, 5); Rl0(e,a,b,c,d, 6); Rl0(d,e,a,b,c, 7);
   5327     Rl0(c,d,e,a,b, 8); Rl0(b,c,d,e,a, 9); Rl0(a,b,c,d,e,10); Rl0(e,a,b,c,d,11);
   5328     Rl0(d,e,a,b,c,12); Rl0(c,d,e,a,b,13); Rl0(b,c,d,e,a,14); Rl0(a,b,c,d,e,15);
   5329   }else{
   5330     Rb0(a,b,c,d,e, 0); Rb0(e,a,b,c,d, 1); Rb0(d,e,a,b,c, 2); Rb0(c,d,e,a,b, 3);
   5331     Rb0(b,c,d,e,a, 4); Rb0(a,b,c,d,e, 5); Rb0(e,a,b,c,d, 6); Rb0(d,e,a,b,c, 7);
   5332     Rb0(c,d,e,a,b, 8); Rb0(b,c,d,e,a, 9); Rb0(a,b,c,d,e,10); Rb0(e,a,b,c,d,11);
   5333     Rb0(d,e,a,b,c,12); Rb0(c,d,e,a,b,13); Rb0(b,c,d,e,a,14); Rb0(a,b,c,d,e,15);
   5334   }
   5335   R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
   5336   R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
   5337   R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
   5338   R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
   5339   R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
   5340   R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
   5341   R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
   5342   R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
   5343   R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
   5344   R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
   5345   R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
   5346   R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
   5347   R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
   5348   R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
   5349   R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
   5350   R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
   5351 
   5352   /* Add the working vars back into context.state[] */
   5353   state[0] += a;
   5354   state[1] += b;
   5355   state[2] += c;
   5356   state[3] += d;
   5357   state[4] += e;
   5358 
   5359 #undef a
   5360 #undef b
   5361 #undef c
   5362 #undef d
   5363 #undef e
   5364 }
   5365 
   5366 
   5367 /* Initialize a SHA1 context */
   5368 static void hash_init(SHA1Context *p){
   5369   /* SHA1 initialization constants */
   5370   p->state[0] = 0x67452301;
   5371   p->state[1] = 0xEFCDAB89;
   5372   p->state[2] = 0x98BADCFE;
   5373   p->state[3] = 0x10325476;
   5374   p->state[4] = 0xC3D2E1F0;
   5375   p->count[0] = p->count[1] = 0;
   5376 }
   5377 
   5378 /* Add new content to the SHA1 hash */
   5379 static void hash_step(
   5380   SHA1Context *p,                 /* Add content to this context */
   5381   const unsigned char *data,      /* Data to be added */
   5382   unsigned int len                /* Number of bytes in data */
   5383 ){
   5384   unsigned int i, j;
   5385 
   5386   j = p->count[0];
   5387   if( (p->count[0] += len << 3) < j ){
   5388     p->count[1] += (len>>29)+1;
   5389   }
   5390   j = (j >> 3) & 63;
   5391   if( (j + len) > 63 ){
   5392     (void)memcpy(&p->buffer[j], data, (i = 64-j));
   5393     SHA1Transform(p->state, p->buffer);
   5394     for(; i + 63 < len; i += 64){
   5395       SHA1Transform(p->state, &data[i]);
   5396     }
   5397     j = 0;
   5398   }else{
   5399     i = 0;
   5400   }
   5401   (void)memcpy(&p->buffer[j], &data[i], len - i);
   5402 }
   5403 
   5404 /* Compute a string using sqlite3_vsnprintf() and hash it */
   5405 static void hash_step_vformat(
   5406   SHA1Context *p,                 /* Add content to this context */
   5407   const char *zFormat,
   5408   ...
   5409 ){
   5410   va_list ap;
   5411   int n;
   5412   char zBuf[50];
   5413   va_start(ap, zFormat);
   5414   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
   5415   va_end(ap);
   5416   n = (int)strlen(zBuf);
   5417   hash_step(p, (unsigned char*)zBuf, n);
   5418 }
   5419 
   5420 
   5421 /* Add padding and compute the message digest.  Render the
   5422 ** message digest as lower-case hexadecimal and put it into
   5423 ** zOut[].  zOut[] must be at least 41 bytes long. */
   5424 static void hash_finish(
   5425   SHA1Context *p,           /* The SHA1 context to finish and render */
   5426   char *zOut,               /* Store hex or binary hash here */
   5427   int bAsBinary             /* 1 for binary hash, 0 for hex hash */
   5428 ){
   5429   unsigned int i;
   5430   unsigned char finalcount[8];
   5431   unsigned char digest[20];
   5432   static const char zEncode[] = "0123456789abcdef";
   5433 
   5434   for (i = 0; i < 8; i++){
   5435     finalcount[i] = (unsigned char)((p->count[(i >= 4 ? 0 : 1)]
   5436        >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
   5437   }
   5438   hash_step(p, (const unsigned char *)"\200", 1);
   5439   while ((p->count[0] & 504) != 448){
   5440     hash_step(p, (const unsigned char *)"\0", 1);
   5441   }
   5442   hash_step(p, finalcount, 8);  /* Should cause a SHA1Transform() */
   5443   for (i = 0; i < 20; i++){
   5444     digest[i] = (unsigned char)((p->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
   5445   }
   5446   if( bAsBinary ){
   5447     memcpy(zOut, digest, 20);
   5448   }else{
   5449     for(i=0; i<20; i++){
   5450       zOut[i*2] = zEncode[(digest[i]>>4)&0xf];
   5451       zOut[i*2+1] = zEncode[digest[i] & 0xf];
   5452     }
   5453     zOut[i*2]= 0;
   5454   }
   5455 }
   5456 /* End of the hashing logic
   5457 *****************************************************************************/
   5458 
   5459 /*
   5460 ** Two SQL functions:  sha1(X) and sha1b(X).
   5461 **
   5462 ** sha1(X) returns a lower-case hexadecimal rendering of the SHA1 hash
   5463 ** of the argument X.  If X is a BLOB, it is hashed as is.  For all other
   5464 ** types of input, X is converted into a UTF-8 string and the string
   5465 ** is hashed without the trailing 0x00 terminator.  The hash of a NULL
   5466 ** value is NULL.
   5467 **
   5468 ** sha1b(X) is the same except that it returns a 20-byte BLOB containing
   5469 ** the binary hash instead of a hexadecimal string.
   5470 */
   5471 static void sha1Func(
   5472   sqlite3_context *context,
   5473   int argc,
   5474   sqlite3_value **argv
   5475 ){
   5476   SHA1Context cx;
   5477   int eType = sqlite3_value_type(argv[0]);
   5478   int nByte = sqlite3_value_bytes(argv[0]);
   5479   const unsigned char *pData;
   5480   char zOut[44];
   5481 
   5482   assert( argc==1 );
   5483   if( eType==SQLITE_NULL ) return;
   5484   hash_init(&cx);
   5485   if( eType==SQLITE_BLOB ){
   5486     pData = (const unsigned char*)sqlite3_value_blob(argv[0]);
   5487   }else{
   5488     pData = (const unsigned char*)sqlite3_value_text(argv[0]);
   5489   }
   5490   if( pData==0 ) return;
   5491   hash_step(&cx, pData, nByte);
   5492   if( sqlite3_user_data(context)!=0 ){
   5493     /* sha1b() - binary result */
   5494     hash_finish(&cx, zOut, 1);
   5495     sqlite3_result_blob(context, zOut, 20, SQLITE_TRANSIENT);
   5496   }else{
   5497     /* sha1() - hexadecimal text result */
   5498     hash_finish(&cx, zOut, 0);
   5499     sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT);
   5500   }
   5501 }
   5502 
   5503 /*
   5504 ** Implementation of the sha1_query(SQL) function.
   5505 **
   5506 ** This function compiles and runs the SQL statement(s) given in the
   5507 ** argument. The results are hashed using SHA1 and that hash is returned.
   5508 **
   5509 ** The original SQL text is included as part of the hash.
   5510 **
   5511 ** The hash is not just a concatenation of the outputs.  Each query
   5512 ** is delimited and each row and value within the query is delimited,
   5513 ** with all values being marked with their datatypes.
   5514 */
   5515 static void sha1QueryFunc(
   5516   sqlite3_context *context,
   5517   int argc,
   5518   sqlite3_value **argv
   5519 ){
   5520   sqlite3 *db = sqlite3_context_db_handle(context);
   5521   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
   5522   sqlite3_stmt *pStmt = 0;
   5523   int nCol;                   /* Number of columns in the result set */
   5524   int i;                      /* Loop counter */
   5525   int rc;
   5526   int n;
   5527   const char *z;
   5528   SHA1Context cx;
   5529   char zOut[44];
   5530 
   5531   assert( argc==1 );
   5532   if( zSql==0 ) return;
   5533   hash_init(&cx);
   5534   while( zSql[0] ){
   5535     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
   5536     if( rc ){
   5537       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
   5538                                    zSql, sqlite3_errmsg(db));
   5539       sqlite3_finalize(pStmt);
   5540       sqlite3_result_error(context, zMsg, -1);
   5541       sqlite3_free(zMsg);
   5542       return;
   5543     }
   5544     if( !sqlite3_stmt_readonly(pStmt) ){
   5545       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
   5546       sqlite3_finalize(pStmt);
   5547       sqlite3_result_error(context, zMsg, -1);
   5548       sqlite3_free(zMsg);
   5549       return;
   5550     }
   5551     nCol = sqlite3_column_count(pStmt);
   5552     z = sqlite3_sql(pStmt);
   5553     if( z==0 ) z = "";
   5554     n = (int)strlen(z);
   5555     hash_step_vformat(&cx,"S%d:",n);
   5556     hash_step(&cx,(unsigned char*)z,n);
   5557 
   5558     /* Compute a hash over the result of the query */
   5559     while( SQLITE_ROW==sqlite3_step(pStmt) ){
   5560       hash_step(&cx,(const unsigned char*)"R",1);
   5561       for(i=0; i<nCol; i++){
   5562         switch( sqlite3_column_type(pStmt,i) ){
   5563           case SQLITE_NULL: {
   5564             hash_step(&cx, (const unsigned char*)"N",1);
   5565             break;
   5566           }
   5567           case SQLITE_INTEGER: {
   5568             sqlite3_uint64 u;
   5569             int j;
   5570             unsigned char x[9];
   5571             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
   5572             memcpy(&u, &v, 8);
   5573             for(j=8; j>=1; j--){
   5574               x[j] = u & 0xff;
   5575               u >>= 8;
   5576             }
   5577             x[0] = 'I';
   5578             hash_step(&cx, x, 9);
   5579             break;
   5580           }
   5581           case SQLITE_FLOAT: {
   5582             sqlite3_uint64 u;
   5583             int j;
   5584             unsigned char x[9];
   5585             double r = sqlite3_column_double(pStmt,i);
   5586             memcpy(&u, &r, 8);
   5587             for(j=8; j>=1; j--){
   5588               x[j] = u & 0xff;
   5589               u >>= 8;
   5590             }
   5591             x[0] = 'F';
   5592             hash_step(&cx,x,9);
   5593             break;
   5594           }
   5595           case SQLITE_TEXT: {
   5596             int n2 = sqlite3_column_bytes(pStmt, i);
   5597             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
   5598             hash_step_vformat(&cx,"T%d:",n2);
   5599             hash_step(&cx, z2, n2);
   5600             break;
   5601           }
   5602           case SQLITE_BLOB: {
   5603             int n2 = sqlite3_column_bytes(pStmt, i);
   5604             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
   5605             hash_step_vformat(&cx,"B%d:",n2);
   5606             hash_step(&cx, z2, n2);
   5607             break;
   5608           }
   5609         }
   5610       }
   5611     }
   5612     sqlite3_finalize(pStmt);
   5613   }
   5614   hash_finish(&cx, zOut, 0);
   5615   sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT);
   5616 }
   5617 
   5618 
   5619 #ifdef _WIN32
   5620 
   5621 #endif
   5622 static int sqlite3_sha_init(
   5623   sqlite3 *db,
   5624   char **pzErrMsg,
   5625   const sqlite3_api_routines *pApi
   5626 ){
   5627   int rc = SQLITE_OK;
   5628   static int one = 1;
   5629   SQLITE_EXTENSION_INIT2(pApi);
   5630   (void)pzErrMsg;  /* Unused parameter */
   5631   rc = sqlite3_create_function(db, "sha1", 1,
   5632                        SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
   5633                                 0, sha1Func, 0, 0);
   5634   if( rc==SQLITE_OK ){
   5635     rc = sqlite3_create_function(db, "sha1b", 1,
   5636                        SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
   5637                           (void*)&one, sha1Func, 0, 0);
   5638   }
   5639   if( rc==SQLITE_OK ){
   5640     rc = sqlite3_create_function(db, "sha1_query", 1,
   5641                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
   5642                                  sha1QueryFunc, 0, 0);
   5643   }
   5644   return rc;
   5645 }
   5646 
   5647 /************************* End ext/misc/sha1.c ********************/
   5648 /************************* Begin ext/misc/uint.c ******************/
   5649 /*
   5650 ** 2020-04-14
   5651 **
   5652 ** The author disclaims copyright to this source code.  In place of
   5653 ** a legal notice, here is a blessing:
   5654 **
   5655 **    May you do good and not evil.
   5656 **    May you find forgiveness for yourself and forgive others.
   5657 **    May you share freely, never taking more than you give.
   5658 **
   5659 ******************************************************************************
   5660 **
   5661 ** This SQLite extension implements the UINT collating sequence.
   5662 **
   5663 ** UINT works like BINARY for text, except that embedded strings
   5664 ** of digits compare in numeric order.
   5665 **
   5666 **     *   Leading zeros are handled properly, in the sense that
   5667 **         they do not mess of the magnitude comparison of embedded
   5668 **         strings of digits.  "x00123y" is equal to "x123y".
   5669 **
   5670 **     *   Only unsigned integers are recognized.  Plus and minus
   5671 **         signs are ignored.  Decimal points and exponential notation
   5672 **         are ignored.
   5673 **
   5674 **     *   Embedded integers can be of arbitrary length.  Comparison
   5675 **         is *not* limited integers that can be expressed as a
   5676 **         64-bit machine integer.
   5677 */
   5678 /* #include "sqlite3ext.h" */
   5679 SQLITE_EXTENSION_INIT1
   5680 #include <assert.h>
   5681 #include <string.h>
   5682 #include <ctype.h>
   5683 
   5684 /*
   5685 ** Compare text in lexicographic order, except strings of digits
   5686 ** compare in numeric order.
   5687 */
   5688 static int uintCollFunc(
   5689   void *notUsed,
   5690   int nKey1, const void *pKey1,
   5691   int nKey2, const void *pKey2
   5692 ){
   5693   const unsigned char *zA = (const unsigned char*)pKey1;
   5694   const unsigned char *zB = (const unsigned char*)pKey2;
   5695   int i=0, j=0, x;
   5696   (void)notUsed;
   5697   while( i<nKey1 && j<nKey2 ){
   5698     x = zA[i] - zB[j];
   5699     if( isdigit(zA[i]) ){
   5700       int k;
   5701       if( !isdigit(zB[j]) ) return x;
   5702       while( i<nKey1 && zA[i]=='0' ){ i++; }
   5703       while( j<nKey2 && zB[j]=='0' ){ j++; }
   5704       k = 0;
   5705       while( i+k<nKey1 && isdigit(zA[i+k])
   5706              && j+k<nKey2 && isdigit(zB[j+k]) ){
   5707         k++;
   5708       }
   5709       if( i+k<nKey1 && isdigit(zA[i+k]) ){
   5710         return +1;
   5711       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
   5712         return -1;
   5713       }else{
   5714         x = memcmp(zA+i, zB+j, k);
   5715         if( x ) return x;
   5716         i += k;
   5717         j += k;
   5718       }
   5719     }else if( x ){
   5720       return x;
   5721     }else{
   5722       i++;
   5723       j++;
   5724     }
   5725   }
   5726   return (nKey1 - i) - (nKey2 - j);
   5727 }
   5728 
   5729 #ifdef _WIN32
   5730 
   5731 #endif
   5732 static int sqlite3_uint_init(
   5733   sqlite3 *db,
   5734   char **pzErrMsg,
   5735   const sqlite3_api_routines *pApi
   5736 ){
   5737   SQLITE_EXTENSION_INIT2(pApi);
   5738   (void)pzErrMsg;  /* Unused parameter */
   5739   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
   5740 }
   5741 
   5742 /************************* End ext/misc/uint.c ********************/
   5743 /************************* Begin ext/misc/decimal.c ******************/
   5744 /*
   5745 ** 2020-06-22
   5746 **
   5747 ** The author disclaims copyright to this source code.  In place of
   5748 ** a legal notice, here is a blessing:
   5749 **
   5750 **    May you do good and not evil.
   5751 **    May you find forgiveness for yourself and forgive others.
   5752 **    May you share freely, never taking more than you give.
   5753 **
   5754 ******************************************************************************
   5755 **
   5756 ** Routines to implement arbitrary-precision decimal math.
   5757 **
   5758 ** The focus here is on simplicity and correctness, not performance.
   5759 */
   5760 /* #include "sqlite3ext.h" */
   5761 SQLITE_EXTENSION_INIT1
   5762 #include <assert.h>
   5763 #include <string.h>
   5764 #include <ctype.h>
   5765 #include <stdlib.h>
   5766 
   5767 /* Mark a function parameter as unused, to suppress nuisance compiler
   5768 ** warnings. */
   5769 #ifndef UNUSED_PARAMETER
   5770 # define UNUSED_PARAMETER(X)  (void)(X)
   5771 #endif
   5772 
   5773 #ifndef IsSpace
   5774 #define IsSpace(X)  isspace((unsigned char)X)
   5775 #endif
   5776 
   5777 #ifndef SQLITE_DECIMAL_MAX_DIGIT
   5778 # define SQLITE_DECIMAL_MAX_DIGIT 10000000
   5779 #endif
   5780 
   5781 /* A decimal object */
   5782 typedef struct Decimal Decimal;
   5783 struct Decimal {
   5784   char sign;        /* 0 for positive, 1 for negative */
   5785   char oom;         /* True if an OOM is encountered */
   5786   char isNull;      /* True if holds a NULL rather than a number */
   5787   char isInit;      /* True upon initialization */
   5788   int nDigit;       /* Total number of digits */
   5789   int nFrac;        /* Number of digits to the right of the decimal point */
   5790   signed char *a;   /* Array of digits.  Most significant first. */
   5791 };
   5792 
   5793 /*
   5794 ** Release memory held by a Decimal, but do not free the object itself.
   5795 */
   5796 static void decimal_clear(Decimal *p){
   5797   sqlite3_free(p->a);
   5798 }
   5799 
   5800 /*
   5801 ** Destroy a Decimal object
   5802 */
   5803 static void decimal_free(Decimal *p){
   5804   if( p ){
   5805     decimal_clear(p);
   5806     sqlite3_free(p);
   5807   }
   5808 }
   5809 
   5810 /*
   5811 ** Allocate a new Decimal object initialized to the text in zIn[].
   5812 ** Return NULL if any kind of error occurs.
   5813 */
   5814 static Decimal *decimalNewFromText(const char *zIn, int n){
   5815   Decimal *p = 0;
   5816   int i;
   5817   int iExp = 0;
   5818 
   5819   if( zIn==0 ) goto new_from_text_failed;
   5820   p = sqlite3_malloc64( sizeof(*p) );
   5821   if( p==0 ) goto new_from_text_failed;
   5822   p->sign = 0;
   5823   p->oom = 0;
   5824   p->isInit = 1;
   5825   p->isNull = 0;
   5826   p->nDigit = 0;
   5827   p->nFrac = 0;
   5828   p->a = sqlite3_malloc64( n+1 );
   5829   if( p->a==0 ) goto new_from_text_failed;
   5830   for(i=0; IsSpace(zIn[i]); i++){}
   5831   if( zIn[i]=='-' ){
   5832     p->sign = 1;
   5833     i++;
   5834   }else if( zIn[i]=='+' ){
   5835     i++;
   5836   }
   5837   while( i<n && zIn[i]=='0' ) i++;
   5838   while( i<n ){
   5839     char c = zIn[i];
   5840     if( c>='0' && c<='9' ){
   5841       p->a[p->nDigit++] = c - '0';
   5842     }else if( c=='.' ){
   5843       p->nFrac = p->nDigit + 1;
   5844     }else if( c=='e' || c=='E' ){
   5845       int j = i+1;
   5846       int neg = 0;
   5847       if( j>=n ) break;
   5848       if( zIn[j]=='-' ){
   5849         neg = 1;
   5850         j++;
   5851       }else if( zIn[j]=='+' ){
   5852         j++;
   5853       }
   5854       while( j<n && iExp<1000000 ){
   5855         if( zIn[j]>='0' && zIn[j]<='9' ){
   5856           iExp = iExp*10 + zIn[j] - '0';
   5857         }
   5858         j++;
   5859       }
   5860       if( neg ) iExp = -iExp;
   5861       break;
   5862     }
   5863     i++;
   5864   }
   5865   if( p->nFrac ){
   5866     p->nFrac = p->nDigit - (p->nFrac - 1);
   5867   }
   5868   if( iExp>0 ){
   5869     if( p->nFrac>0 ){
   5870       if( iExp<=p->nFrac ){
   5871         p->nFrac -= iExp;
   5872         iExp = 0;
   5873       }else{
   5874         iExp -= p->nFrac;
   5875         p->nFrac = 0;
   5876       }
   5877     }
   5878     if( iExp>0 ){
   5879       signed char *a = sqlite3_realloc64(p->a, (sqlite3_int64)p->nDigit
   5880                                      + (sqlite3_int64)iExp + 1 );
   5881       if( a==0 ) goto new_from_text_failed;
   5882       p->a = a;
   5883       memset(p->a+p->nDigit, 0, iExp);
   5884       p->nDigit += iExp;
   5885     }
   5886   }else if( iExp<0 ){
   5887     int nExtra;
   5888     iExp = -iExp;
   5889     nExtra = p->nDigit - p->nFrac - 1;
   5890     if( nExtra ){
   5891       if( nExtra>=iExp ){
   5892         p->nFrac += iExp;
   5893         iExp  = 0;
   5894       }else{
   5895         iExp -= nExtra;
   5896         p->nFrac = p->nDigit - 1;
   5897       }
   5898     }
   5899     if( iExp>0 ){
   5900       signed char *a = sqlite3_realloc64(p->a, (sqlite3_int64)p->nDigit
   5901                                      + (sqlite3_int64)iExp + 1 );
   5902       if( a==0 ) goto new_from_text_failed;
   5903       p->a = a;
   5904       memmove(p->a+iExp, p->a, p->nDigit);
   5905       memset(p->a, 0, iExp);
   5906       p->nDigit += iExp;
   5907       p->nFrac += iExp;
   5908     }
   5909   }
   5910   if( p->sign ){
   5911     for(i=0; i<p->nDigit && p->a[i]==0; i++){}
   5912     if( i>=p->nDigit ) p->sign = 0;
   5913   }
   5914   if( p->nDigit>SQLITE_DECIMAL_MAX_DIGIT ) goto new_from_text_failed;
   5915   return p;
   5916 
   5917 new_from_text_failed:
   5918   if( p ){
   5919     if( p->a ) sqlite3_free(p->a);
   5920     sqlite3_free(p);
   5921   }
   5922   return 0;
   5923 }
   5924 
   5925 /* Forward reference */
   5926 static Decimal *decimalFromDouble(double);
   5927 
   5928 /*
   5929 ** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
   5930 ** to the new object, or NULL if there is an error.  If the pCtx argument
   5931 ** is not NULL, then errors are reported on it as well.
   5932 **
   5933 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
   5934 ** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
   5935 ** 8 bytes, the resulting double value is expanded into its decimal equivalent.
   5936 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
   5937 ** then NULL is returned.
   5938 */
   5939 static Decimal *decimal_new(
   5940   sqlite3_context *pCtx,       /* Report error here, if not null */
   5941   sqlite3_value *pIn,          /* Construct the decimal object from this */
   5942   int bTextOnly                /* Always interpret pIn as text if true */
   5943 ){
   5944   Decimal *p = 0;
   5945   int eType = sqlite3_value_type(pIn);
   5946   if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
   5947     eType = SQLITE_TEXT;
   5948   }
   5949   switch( eType ){
   5950     case SQLITE_TEXT:
   5951     case SQLITE_INTEGER: {
   5952       const char *zIn = (const char*)sqlite3_value_text(pIn);
   5953       int n = sqlite3_value_bytes(pIn);
   5954       p = decimalNewFromText(zIn, n);
   5955       if( p==0 ) goto new_failed;
   5956       break;
   5957     }
   5958 
   5959     case SQLITE_FLOAT: {
   5960       p = decimalFromDouble(sqlite3_value_double(pIn));
   5961       break;
   5962     }
   5963 
   5964     case SQLITE_BLOB: {
   5965       const unsigned char *x;
   5966       unsigned int i;
   5967       sqlite3_uint64 v = 0;
   5968       double r;
   5969 
   5970       if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
   5971       x = sqlite3_value_blob(pIn);
   5972       for(i=0; i<sizeof(r); i++){
   5973         v = (v<<8) | x[i];
   5974       }
   5975       memcpy(&r, &v, sizeof(r));
   5976       p = decimalFromDouble(r);
   5977       break;
   5978     }
   5979 
   5980     case SQLITE_NULL: {
   5981       break;
   5982     }
   5983   }
   5984   return p;
   5985 
   5986 new_failed:
   5987   if( pCtx ) sqlite3_result_error_nomem(pCtx);
   5988   sqlite3_free(p);
   5989   return 0;
   5990 }
   5991 
   5992 /*
   5993 ** Make the given Decimal the result.
   5994 */
   5995 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
   5996   char *z;
   5997   int i, j;
   5998   int n;
   5999   if( p==0 || p->oom ){
   6000     sqlite3_result_error_nomem(pCtx);
   6001     return;
   6002   }
   6003   if( p->isNull ){
   6004     sqlite3_result_null(pCtx);
   6005     return;
   6006   }
   6007   z = sqlite3_malloc64( (sqlite3_int64)p->nDigit+4 );
   6008   if( z==0 ){
   6009     sqlite3_result_error_nomem(pCtx);
   6010     return;
   6011   }
   6012   i = 0;
   6013   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
   6014     p->sign = 0;
   6015   }
   6016   if( p->sign ){
   6017     z[0] = '-';
   6018     i = 1;
   6019   }
   6020   n = p->nDigit - p->nFrac;
   6021   if( n<=0 ){
   6022     z[i++] = '0';
   6023   }
   6024   j = 0;
   6025   while( n>1 && p->a[j]==0 ){
   6026     j++;
   6027     n--;
   6028   }
   6029   while( n>0  ){
   6030     z[i++] = p->a[j] + '0';
   6031     j++;
   6032     n--;
   6033   }
   6034   if( p->nFrac ){
   6035     z[i++] = '.';
   6036     do{
   6037       z[i++] = p->a[j] + '0';
   6038       j++;
   6039     }while( j<p->nDigit );
   6040   }
   6041   z[i] = 0;
   6042   sqlite3_result_text(pCtx, z, i, sqlite3_free);
   6043 }
   6044 
   6045 /*
   6046 ** Round a decimal value to N significant digits.  N must be positive.
   6047 */
   6048 static void decimal_round(Decimal *p, int N){
   6049   int i;
   6050   int nZero;
   6051   if( N<1 ) return;
   6052   if( p==0 ) return;
   6053   if( p->nDigit<=N ) return;
   6054   for(nZero=0; nZero<p->nDigit && p->a[nZero]==0; nZero++){}
   6055   N += nZero;
   6056   if( p->nDigit<=N ) return;
   6057   if( p->a[N]>4 ){
   6058     p->a[N-1]++;
   6059     for(i=N-1; i>0 && p->a[i]>9; i--){
   6060       p->a[i] = 0;
   6061       p->a[i-1]++;
   6062     }
   6063     if( p->a[0]>9 ){
   6064       p->a[0] = 1;
   6065       p->nFrac--;
   6066     }
   6067   }
   6068   memset(&p->a[N], 0, p->nDigit - N);
   6069 }
   6070 
   6071 /*
   6072 ** Make the given Decimal the result in an format similar to  '%+#e'.
   6073 ** In other words, show exponential notation with leading and trailing
   6074 ** zeros omitted.
   6075 */
   6076 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p, int N){
   6077   char *z;       /* The output buffer */
   6078   int i;         /* Loop counter */
   6079   int nZero;     /* Number of leading zeros */
   6080   int nDigit;    /* Number of digits not counting trailing zeros */
   6081   int nFrac;     /* Digits to the right of the decimal point */
   6082   int exp;       /* Exponent value */
   6083   signed char zero;     /* Zero value */
   6084   signed char *a;       /* Array of digits */
   6085 
   6086   if( p==0 || p->oom ){
   6087     sqlite3_result_error_nomem(pCtx);
   6088     return;
   6089   }
   6090   if( p->isNull ){
   6091     sqlite3_result_null(pCtx);
   6092     return;
   6093   }
   6094   if( N<1 ) N = 0;
   6095   for(nDigit=p->nDigit; nDigit>N && p->a[nDigit-1]==0; nDigit--){}
   6096   for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
   6097   nFrac = p->nFrac + (nDigit - p->nDigit);
   6098   nDigit -= nZero;
   6099   z = sqlite3_malloc64( (sqlite3_int64)nDigit+20 );
   6100   if( z==0 ){
   6101     sqlite3_result_error_nomem(pCtx);
   6102     return;
   6103   }
   6104   if( nDigit==0 ){
   6105     zero = 0;
   6106     a = &zero;
   6107     nDigit = 1;
   6108     nFrac = 0;
   6109   }else{
   6110     a = &p->a[nZero];
   6111   }
   6112   if( p->sign && nDigit>0 ){
   6113     z[0] = '-';
   6114   }else{
   6115     z[0] = '+';
   6116   }
   6117   z[1] = a[0]+'0';
   6118   z[2] = '.';
   6119   if( nDigit==1 ){
   6120     z[3] = '0';
   6121     i = 4;
   6122   }else{
   6123     for(i=1; i<nDigit; i++){
   6124       z[2+i] = a[i]+'0';
   6125     }
   6126     i = nDigit+2;
   6127   }
   6128   exp = nDigit - nFrac - 1;
   6129   sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
   6130   sqlite3_result_text(pCtx, z, -1, sqlite3_free);
   6131 }
   6132 
   6133 /*
   6134 ** Compare to Decimal objects.  Return negative, 0, or positive if the
   6135 ** first object is less than, equal to, or greater than the second.
   6136 **
   6137 ** Preconditions for this routine:
   6138 **
   6139 **    pA!=0
   6140 **    pA->isNull==0
   6141 **    pB!=0
   6142 **    pB->isNull==0
   6143 */
   6144 static int decimal_cmp(Decimal *pA, Decimal *pB){
   6145   int nASig, nBSig, rc, n;
   6146   while( pA->nFrac>0 && pA->a[pA->nDigit-1]==0 ){
   6147     pA->nDigit--;
   6148     pA->nFrac--;
   6149   }
   6150   while( pB->nFrac>0 && pB->a[pB->nDigit-1]==0 ){
   6151     pB->nDigit--;
   6152     pB->nFrac--;
   6153   }
   6154   if( pA->sign!=pB->sign ){
   6155     return pA->sign ? -1 : +1;
   6156   }
   6157   if( pA->sign ){
   6158     Decimal *pTemp = pA;
   6159     pA = pB;
   6160     pB = pTemp;
   6161   }
   6162   nASig = pA->nDigit - pA->nFrac;
   6163   nBSig = pB->nDigit - pB->nFrac;
   6164   if( nASig!=nBSig ){
   6165     return nASig - nBSig;
   6166   }
   6167   n = pA->nDigit;
   6168   if( n>pB->nDigit ) n = pB->nDigit;
   6169   rc = memcmp(pA->a, pB->a, n);
   6170   if( rc==0 ){
   6171     rc = pA->nDigit - pB->nDigit;
   6172   }
   6173   return rc;
   6174 }
   6175 
   6176 /*
   6177 ** SQL Function:   decimal_cmp(X, Y)
   6178 **
   6179 ** Return negative, zero, or positive if X is less then, equal to, or
   6180 ** greater than Y.
   6181 */
   6182 static void decimalCmpFunc(
   6183   sqlite3_context *context,
   6184   int argc,
   6185   sqlite3_value **argv
   6186 ){
   6187   Decimal *pA = 0, *pB = 0;
   6188   int rc;
   6189 
   6190   UNUSED_PARAMETER(argc);
   6191   pA = decimal_new(context, argv[0], 1);
   6192   if( pA==0 || pA->isNull ) goto cmp_done;
   6193   pB = decimal_new(context, argv[1], 1);
   6194   if( pB==0 || pB->isNull ) goto cmp_done;
   6195   rc = decimal_cmp(pA, pB);
   6196   if( rc<0 ) rc = -1;
   6197   else if( rc>0 ) rc = +1;
   6198   sqlite3_result_int(context, rc);
   6199 cmp_done:
   6200   decimal_free(pA);
   6201   decimal_free(pB);
   6202 }
   6203 
   6204 /*
   6205 ** Expand the Decimal so that it has a least nDigit digits and nFrac
   6206 ** digits to the right of the decimal point.
   6207 */
   6208 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
   6209   int nAddSig;
   6210   int nAddFrac;
   6211   signed char *a;
   6212   if( p==0 ) return;
   6213   nAddFrac = nFrac - p->nFrac;
   6214   nAddSig = (nDigit - p->nDigit) - nAddFrac;
   6215   if( nAddFrac==0 && nAddSig==0 ) return;
   6216   if( nDigit+1>SQLITE_DECIMAL_MAX_DIGIT ){ p->oom = 1; return; }
   6217   a = sqlite3_realloc64(p->a, nDigit+1);
   6218   if( a==0 ){
   6219     p->oom = 1;
   6220     return;
   6221   }
   6222   p->a = a;
   6223   if( nAddSig ){
   6224     memmove(p->a+nAddSig, p->a, p->nDigit);
   6225     memset(p->a, 0, nAddSig);
   6226     p->nDigit += nAddSig;
   6227   }
   6228   if( nAddFrac ){
   6229     memset(p->a+p->nDigit, 0, nAddFrac);
   6230     p->nDigit += nAddFrac;
   6231     p->nFrac += nAddFrac;
   6232   }
   6233 }
   6234 
   6235 /*
   6236 ** Add the value pB into pA.   A := A + B.
   6237 **
   6238 ** Both pA and pB might become denormalized by this routine.
   6239 */
   6240 static void decimal_add(Decimal *pA, Decimal *pB){
   6241   int nSig, nFrac, nDigit;
   6242   int i, rc;
   6243   if( pA==0 ){
   6244     return;
   6245   }
   6246   if( pA->oom || pB==0 || pB->oom ){
   6247     pA->oom = 1;
   6248     return;
   6249   }
   6250   if( pA->isNull || pB->isNull ){
   6251     pA->isNull = 1;
   6252     return;
   6253   }
   6254   nSig = pA->nDigit - pA->nFrac;
   6255   if( nSig && pA->a[0]==0 ) nSig--;
   6256   if( nSig<pB->nDigit-pB->nFrac ){
   6257     nSig = pB->nDigit - pB->nFrac;
   6258   }
   6259   nFrac = pA->nFrac;
   6260   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
   6261   nDigit = nSig + nFrac + 1;
   6262   decimal_expand(pA, nDigit, nFrac);
   6263   decimal_expand(pB, nDigit, nFrac);
   6264   if( pA->oom || pB->oom ){
   6265     pA->oom = 1;
   6266   }else{
   6267     if( pA->sign==pB->sign ){
   6268       int carry = 0;
   6269       for(i=nDigit-1; i>=0; i--){
   6270         int x = pA->a[i] + pB->a[i] + carry;
   6271         if( x>=10 ){
   6272           carry = 1;
   6273           pA->a[i] = x - 10;
   6274         }else{
   6275           carry = 0;
   6276           pA->a[i] = x;
   6277         }
   6278       }
   6279     }else{
   6280       signed char *aA, *aB;
   6281       int borrow = 0;
   6282       rc = memcmp(pA->a, pB->a, nDigit);
   6283       if( rc<0 ){
   6284         aA = pB->a;
   6285         aB = pA->a;
   6286         pA->sign = !pA->sign;
   6287       }else{
   6288         aA = pA->a;
   6289         aB = pB->a;
   6290       }
   6291       for(i=nDigit-1; i>=0; i--){
   6292         int x = aA[i] - aB[i] - borrow;
   6293         if( x<0 ){
   6294           pA->a[i] = x+10;
   6295           borrow = 1;
   6296         }else{
   6297           pA->a[i] = x;
   6298           borrow = 0;
   6299         }
   6300       }
   6301     }
   6302   }
   6303 }
   6304 
   6305 /*
   6306 ** Multiply A by B.   A := A * B
   6307 **
   6308 ** All significant digits after the decimal point are retained.
   6309 ** Trailing zeros after the decimal point are omitted as long as
   6310 ** the number of digits after the decimal point is no less than
   6311 ** either the number of digits in either input.
   6312 */
   6313 static void decimalMul(Decimal *pA, Decimal *pB){
   6314   signed char *acc = 0;
   6315   int i, j, k;
   6316   int minFrac;
   6317   sqlite3_int64 sumDigit;
   6318 
   6319   if( pA==0 || pA->oom || pA->isNull
   6320    || pB==0 || pB->oom || pB->isNull
   6321   ){
   6322     goto mul_end;
   6323   }
   6324   sumDigit = pA->nDigit;
   6325   sumDigit += pB->nDigit;
   6326   sumDigit += 2;
   6327   if( sumDigit>SQLITE_DECIMAL_MAX_DIGIT ){ pA->oom = 1; return; }
   6328   acc = sqlite3_malloc64( sumDigit );
   6329   if( acc==0 ){
   6330     pA->oom = 1;
   6331     goto mul_end;
   6332   }
   6333   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
   6334   minFrac = pA->nFrac;
   6335   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
   6336   for(i=pA->nDigit-1; i>=0; i--){
   6337     signed char f = pA->a[i];
   6338     int carry = 0, x;
   6339     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
   6340       x = acc[k] + f*pB->a[j] + carry;
   6341       acc[k] = x%10;
   6342       carry = x/10;
   6343     }
   6344     x = acc[k] + carry;
   6345     acc[k] = x%10;
   6346     acc[k-1] += x/10;
   6347   }
   6348   sqlite3_free(pA->a);
   6349   pA->a = acc;
   6350   acc = 0;
   6351   pA->nDigit += pB->nDigit + 2;
   6352   pA->nFrac += pB->nFrac;
   6353   pA->sign ^= pB->sign;
   6354   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
   6355     pA->nFrac--;
   6356     pA->nDigit--;
   6357   }
   6358 
   6359 mul_end:
   6360   sqlite3_free(acc);
   6361 }
   6362 
   6363 /*
   6364 ** Create a new Decimal object that contains an integer power of 2.
   6365 */
   6366 static Decimal *decimalPow2(int N){
   6367   Decimal *pA = 0;      /* The result to be returned */
   6368   Decimal *pX = 0;      /* Multiplier */
   6369   if( N<-20000 || N>20000 ) goto pow2_fault;
   6370   pA = decimalNewFromText("1.0", 3);
   6371   if( pA==0 || pA->oom ) goto pow2_fault;
   6372   if( N==0 ) return pA;
   6373   if( N>0 ){
   6374     pX = decimalNewFromText("2.0", 3);
   6375   }else{
   6376     N = -N;
   6377     pX = decimalNewFromText("0.5", 3);
   6378   }
   6379   if( pX==0 || pX->oom ) goto pow2_fault;
   6380   while( 1 /* Exit by break */ ){
   6381     if( N & 1 ){
   6382       decimalMul(pA, pX);
   6383       if( pA->oom ) goto pow2_fault;
   6384     }
   6385     N >>= 1;
   6386     if( N==0 ) break;
   6387     decimalMul(pX, pX);
   6388   }
   6389   decimal_free(pX);
   6390   return pA;
   6391 
   6392 pow2_fault:
   6393   decimal_free(pA);
   6394   decimal_free(pX);
   6395   return 0;
   6396 }
   6397 
   6398 /*
   6399 ** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
   6400 */
   6401 static Decimal *decimalFromDouble(double r){
   6402   sqlite3_int64 m, a;
   6403   int e;
   6404   int isNeg;
   6405   Decimal *pA;
   6406   Decimal *pX;
   6407   char zNum[100];
   6408   if( r<0.0 ){
   6409     isNeg = 1;
   6410     r = -r;
   6411   }else{
   6412     isNeg = 0;
   6413   }
   6414   memcpy(&a,&r,sizeof(a));
   6415   if( a==0 || a==(sqlite3_int64)0x8000000000000000LL){
   6416     e = 0;
   6417     m = 0;
   6418   }else{
   6419     e = a>>52;
   6420     m = a & ((((sqlite3_int64)1)<<52)-1);
   6421     if( e==0 ){
   6422       m <<= 1;
   6423     }else{
   6424       m |= ((sqlite3_int64)1)<<52;
   6425     }
   6426     while( e<1075 && m>0 && (m&1)==0 ){
   6427       m >>= 1;
   6428       e++;
   6429     }
   6430     if( isNeg ) m = -m;
   6431     e = e - 1075;
   6432     if( e>971 ){
   6433       return 0;  /* A NaN or an Infinity */
   6434     }
   6435   }
   6436 
   6437   /* At this point m is the integer significand and e is the exponent */
   6438   sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
   6439   pA = decimalNewFromText(zNum, (int)strlen(zNum));
   6440   pX = decimalPow2(e);
   6441   decimalMul(pA, pX);
   6442   decimal_free(pX);
   6443   return pA;
   6444 }
   6445 
   6446 /*
   6447 ** SQL Function:   decimal(X)
   6448 ** OR:             decimal_exp(X)
   6449 **
   6450 ** Convert input X into decimal and then back into text.
   6451 **
   6452 ** If X is originally a float, then a full decimal expansion of that floating
   6453 ** point value is done.  Or if X is an 8-byte blob, it is interpreted
   6454 ** as a float and similarly expanded.
   6455 **
   6456 ** The decimal_exp(X) function returns the result in exponential notation.
   6457 ** decimal(X) returns a complete decimal, without the e+NNN at the end.
   6458 */
   6459 static void decimalFunc(
   6460   sqlite3_context *context,
   6461   int argc,
   6462   sqlite3_value **argv
   6463 ){
   6464   Decimal *p =  decimal_new(context, argv[0], 0);
   6465   int N;
   6466   if( argc==2 ){
   6467     N = sqlite3_value_int(argv[1]);
   6468     if( N>0 ) decimal_round(p, N);
   6469   }else{
   6470     N = 0;
   6471   }
   6472   if( p ){
   6473     if( sqlite3_user_data(context)!=0 ){
   6474       decimal_result_sci(context, p, N);
   6475     }else{
   6476       decimal_result(context, p);
   6477     }
   6478     decimal_free(p);
   6479   }
   6480 }
   6481 
   6482 /*
   6483 ** Compare text in decimal order.
   6484 */
   6485 static int decimalCollFunc(
   6486   void *notUsed,
   6487   int nKey1, const void *pKey1,
   6488   int nKey2, const void *pKey2
   6489 ){
   6490   const unsigned char *zA = (const unsigned char*)pKey1;
   6491   const unsigned char *zB = (const unsigned char*)pKey2;
   6492   Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
   6493   Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
   6494   int rc;
   6495   UNUSED_PARAMETER(notUsed);
   6496   if( pA==0 || pB==0 ){
   6497     rc = 0;
   6498   }else{
   6499     rc = decimal_cmp(pA, pB);
   6500   }
   6501   decimal_free(pA);
   6502   decimal_free(pB);
   6503   return rc;
   6504 }
   6505 
   6506 
   6507 /*
   6508 ** SQL Function:   decimal_add(X, Y)
   6509 **                 decimal_sub(X, Y)
   6510 **
   6511 ** Return the sum or difference of X and Y.
   6512 */
   6513 static void decimalAddFunc(
   6514   sqlite3_context *context,
   6515   int argc,
   6516   sqlite3_value **argv
   6517 ){
   6518   Decimal *pA = decimal_new(context, argv[0], 1);
   6519   Decimal *pB = decimal_new(context, argv[1], 1);
   6520   UNUSED_PARAMETER(argc);
   6521   decimal_add(pA, pB);
   6522   decimal_result(context, pA);
   6523   decimal_free(pA);
   6524   decimal_free(pB);
   6525 }
   6526 static void decimalSubFunc(
   6527   sqlite3_context *context,
   6528   int argc,
   6529   sqlite3_value **argv
   6530 ){
   6531   Decimal *pA = decimal_new(context, argv[0], 1);
   6532   Decimal *pB = decimal_new(context, argv[1], 1);
   6533   UNUSED_PARAMETER(argc);
   6534   if( pB ){
   6535     pB->sign = !pB->sign;
   6536     decimal_add(pA, pB);
   6537     decimal_result(context, pA);
   6538   }
   6539   decimal_free(pA);
   6540   decimal_free(pB);
   6541 }
   6542 
   6543 /* Aggregate function:   decimal_sum(X)
   6544 **
   6545 ** Works like sum() except that it uses decimal arithmetic for unlimited
   6546 ** precision.
   6547 */
   6548 static void decimalSumStep(
   6549   sqlite3_context *context,
   6550   int argc,
   6551   sqlite3_value **argv
   6552 ){
   6553   Decimal *p;
   6554   Decimal *pArg;
   6555   UNUSED_PARAMETER(argc);
   6556   p = sqlite3_aggregate_context(context, sizeof(*p));
   6557   if( p==0 ) return;
   6558   if( !p->isInit ){
   6559     p->isInit = 1;
   6560     p->a = sqlite3_malloc64(2);
   6561     if( p->a==0 ){
   6562       p->oom = 1;
   6563     }else{
   6564       p->a[0] = 0;
   6565     }
   6566     p->nDigit = 1;
   6567     p->nFrac = 0;
   6568   }
   6569   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   6570   pArg = decimal_new(context, argv[0], 1);
   6571   decimal_add(p, pArg);
   6572   decimal_free(pArg);
   6573 }
   6574 static void decimalSumInverse(
   6575   sqlite3_context *context,
   6576   int argc,
   6577   sqlite3_value **argv
   6578 ){
   6579   Decimal *p;
   6580   Decimal *pArg;
   6581   UNUSED_PARAMETER(argc);
   6582   p = sqlite3_aggregate_context(context, sizeof(*p));
   6583   if( p==0 ) return;
   6584   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   6585   pArg = decimal_new(context, argv[0], 1);
   6586   if( pArg ) pArg->sign = !pArg->sign;
   6587   decimal_add(p, pArg);
   6588   decimal_free(pArg);
   6589 }
   6590 static void decimalSumValue(sqlite3_context *context){
   6591   Decimal *p = sqlite3_aggregate_context(context, 0);
   6592   if( p==0 ) return;
   6593   decimal_result(context, p);
   6594 }
   6595 static void decimalSumFinalize(sqlite3_context *context){
   6596   Decimal *p = sqlite3_aggregate_context(context, 0);
   6597   if( p==0 ) return;
   6598   decimal_result(context, p);
   6599   decimal_clear(p);
   6600 }
   6601 
   6602 /*
   6603 ** SQL Function:   decimal_mul(X, Y)
   6604 **
   6605 ** Return the product of X and Y.
   6606 */
   6607 static void decimalMulFunc(
   6608   sqlite3_context *context,
   6609   int argc,
   6610   sqlite3_value **argv
   6611 ){
   6612   Decimal *pA = decimal_new(context, argv[0], 1);
   6613   Decimal *pB = decimal_new(context, argv[1], 1);
   6614   UNUSED_PARAMETER(argc);
   6615   if( pA==0 || pA->oom || pA->isNull
   6616    || pB==0 || pB->oom || pB->isNull
   6617   ){
   6618     goto mul_end;
   6619   }
   6620   decimalMul(pA, pB);
   6621   if( pA->oom ){
   6622     goto mul_end;
   6623   }
   6624   decimal_result(context, pA);
   6625 
   6626 mul_end:
   6627   decimal_free(pA);
   6628   decimal_free(pB);
   6629 }
   6630 
   6631 /*
   6632 ** SQL Function:   decimal_pow2(N)
   6633 **
   6634 ** Return the N-th power of 2.  N must be an integer.
   6635 */
   6636 static void decimalPow2Func(
   6637   sqlite3_context *context,
   6638   int argc,
   6639   sqlite3_value **argv
   6640 ){
   6641   UNUSED_PARAMETER(argc);
   6642   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
   6643     Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
   6644     decimal_result_sci(context, pA, 0);
   6645     decimal_free(pA);
   6646   }
   6647 }
   6648 
   6649 #ifdef _WIN32
   6650 
   6651 #endif
   6652 static int sqlite3_decimal_init(
   6653   sqlite3 *db,
   6654   char **pzErrMsg,
   6655   const sqlite3_api_routines *pApi
   6656 ){
   6657   int rc = SQLITE_OK;
   6658   static const struct {
   6659     const char *zFuncName;
   6660     int nArg;
   6661     int iArg;
   6662     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   6663   } aFunc[] = {
   6664     { "decimal",       1, 0,  decimalFunc        },
   6665     { "decimal",       2, 0,  decimalFunc        },
   6666     { "decimal_exp",   1, 1,  decimalFunc        },
   6667     { "decimal_exp",   2, 1,  decimalFunc        },
   6668     { "decimal_cmp",   2, 0,  decimalCmpFunc     },
   6669     { "decimal_add",   2, 0,  decimalAddFunc     },
   6670     { "decimal_sub",   2, 0,  decimalSubFunc     },
   6671     { "decimal_mul",   2, 0,  decimalMulFunc     },
   6672     { "decimal_pow2",  1, 0,  decimalPow2Func    },
   6673   };
   6674   unsigned int i;
   6675   (void)pzErrMsg;  /* Unused parameter */
   6676 
   6677   SQLITE_EXTENSION_INIT2(pApi);
   6678 
   6679   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
   6680     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
   6681                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
   6682                    aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
   6683   }
   6684   if( rc==SQLITE_OK ){
   6685     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
   6686                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
   6687                    decimalSumStep, decimalSumFinalize,
   6688                    decimalSumValue, decimalSumInverse, 0);
   6689   }
   6690   if( rc==SQLITE_OK ){
   6691     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
   6692                                   0, decimalCollFunc);
   6693   }
   6694   return rc;
   6695 }
   6696 
   6697 /************************* End ext/misc/decimal.c ********************/
   6698 /************************* Begin ext/misc/base64.c ******************/
   6699 /*
   6700 ** 2022-11-18
   6701 **
   6702 ** The author disclaims copyright to this source code.  In place of
   6703 ** a legal notice, here is a blessing:
   6704 **
   6705 **    May you do good and not evil.
   6706 **    May you find forgiveness for yourself and forgive others.
   6707 **    May you share freely, never taking more than you give.
   6708 **
   6709 *************************************************************************
   6710 **
   6711 ** This is a SQLite extension for converting in either direction
   6712 ** between a (binary) blob and base64 text. Base64 can transit a
   6713 ** sane USASCII channel unmolested. It also plays nicely in CSV or
   6714 ** written as TCL brace-enclosed literals or SQL string literals,
   6715 ** and can be used unmodified in XML-like documents.
   6716 **
   6717 ** This is an independent implementation of conversions specified in
   6718 ** RFC 4648, done on the above date by the author (Larry Brasfield)
   6719 ** who thereby has the right to put this into the public domain.
   6720 **
   6721 ** The conversions meet RFC 4648 requirements, provided that this
   6722 ** C source specifies that line-feeds are included in the encoded
   6723 ** data to limit visible line lengths to 72 characters and to
   6724 ** terminate any encoded blob having non-zero length.
   6725 **
   6726 ** Length limitations are not imposed except that the runtime
   6727 ** SQLite string or blob length limits are respected. Otherwise,
   6728 ** any length binary sequence can be represented and recovered.
   6729 ** Generated base64 sequences, with their line-feeds included,
   6730 ** can be concatenated; the result converted back to binary will
   6731 ** be the concatenation of the represented binary sequences.
   6732 **
   6733 ** This SQLite3 extension creates a function, base64(x), which
   6734 ** either: converts text x containing base64 to a returned blob;
   6735 ** or converts a blob x to returned text containing base64. An
   6736 ** error will be thrown for other input argument types.
   6737 **
   6738 ** This code relies on UTF-8 encoding only with respect to the
   6739 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
   6740 ** It will fail miserably if somehow made to try to convert EBCDIC.
   6741 ** Because it is table-driven, it could be enhanced to handle that,
   6742 ** but the world and SQLite have moved on from that anachronism.
   6743 **
   6744 ** To build the extension:
   6745 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
   6746 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
   6747 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
   6748 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
   6749 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
   6750 */
   6751 
   6752 #include <assert.h>
   6753 
   6754 /* #include "sqlite3ext.h" */
   6755 
   6756 #ifndef deliberate_fall_through
   6757 /* Quiet some compilers about some of our intentional code. */
   6758 # if GCC_VERSION>=7000000
   6759 #  define deliberate_fall_through __attribute__((fallthrough));
   6760 # else
   6761 #  define deliberate_fall_through
   6762 # endif
   6763 #endif
   6764 
   6765 SQLITE_EXTENSION_INIT1;
   6766 
   6767 #define PC 0x80 /* pad character */
   6768 #define WS 0x81 /* whitespace */
   6769 #define ND 0x82 /* Not above or digit-value */
   6770 #define PAD_CHAR '='
   6771 
   6772 #ifndef U8_TYPEDEF
   6773 /* typedef unsigned char u8; */
   6774 #define U8_TYPEDEF
   6775 #endif
   6776 
   6777 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
   6778 static const u8 b64DigitValues[128] = {
   6779   /*                             HT LF VT  FF CR       */
   6780     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
   6781   /*                                                US */
   6782     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
   6783   /*sp                                  +            / */
   6784     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
   6785   /* 0  1            5            9            =       */
   6786     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
   6787   /*    A                                            O */
   6788     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
   6789   /* P                               Z                 */
   6790     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
   6791   /*    a                                            o */
   6792     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
   6793   /* p                               z                 */
   6794     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
   6795 };
   6796 
   6797 static const char b64Numerals[64+1]
   6798 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
   6799 
   6800 #define BX_DV_PROTO(c) \
   6801   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
   6802 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
   6803 #define IS_BX_WS(bdp) ((bdp)==WS)
   6804 #define IS_BX_PAD(bdp) ((bdp)==PC)
   6805 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
   6806 /* Width of base64 lines. Should be an integer multiple of 4. */
   6807 #define B64_DARK_MAX 72
   6808 
   6809 /* Encode a byte buffer into base64 text with linefeeds appended to limit
   6810 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
   6811 */
   6812 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
   6813   int nCol = 0;
   6814   while( nbIn >= 3 ){
   6815     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
   6816     pOut[0] = BX_NUMERAL(pIn[0]>>2);
   6817     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
   6818     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
   6819     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
   6820     pOut += 4;
   6821     nbIn -= 3;
   6822     pIn += 3;
   6823     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
   6824       *pOut++ = '\n';
   6825       nCol = 0;
   6826     }
   6827   }
   6828   if( nbIn > 0 ){
   6829     signed char nco = nbIn+1;
   6830     int nbe;
   6831     unsigned long qv = *pIn++;
   6832     for( nbe=1; nbe<3; ++nbe ){
   6833       qv <<= 8;
   6834       if( nbe<nbIn ) qv |= *pIn++;
   6835     }
   6836     for( nbe=3; nbe>=0; --nbe ){
   6837       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
   6838       qv >>= 6;
   6839       pOut[nbe] = ce;
   6840     }
   6841     pOut += 4;
   6842     *pOut++ = '\n';
   6843   }
   6844   *pOut = 0;
   6845   return pOut;
   6846 }
   6847 
   6848 /* Skip over text which is not base64 numeral(s). */
   6849 static char * skipNonB64( char *s, int nc ){
   6850   char c;
   6851   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
   6852   return s;
   6853 }
   6854 
   6855 /* Decode base64 text into a byte buffer. */
   6856 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
   6857   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
   6858   while( ncIn>0 && *pIn!=PAD_CHAR ){
   6859     static signed char nboi[] = { 0, 0, 1, 2, 3 };
   6860     char *pUse = skipNonB64(pIn, ncIn);
   6861     unsigned long qv = 0L;
   6862     int nti, nbo, nac;
   6863     ncIn -= (pUse - pIn);
   6864     pIn = pUse;
   6865     nti = (ncIn>4)? 4 : ncIn;
   6866     ncIn -= nti;
   6867     nbo = nboi[nti];
   6868     if( nbo==0 ) break;
   6869     for( nac=0; nac<4; ++nac ){
   6870       char c = (nac<nti)? *pIn++ : b64Numerals[0];
   6871       u8 bdp = BX_DV_PROTO(c);
   6872       switch( bdp ){
   6873       case ND:
   6874         /*  Treat dark non-digits as pad, but they terminate decode too. */
   6875         ncIn = 0;
   6876         deliberate_fall_through; /* FALLTHRU */
   6877       case WS:
   6878         /* Treat whitespace as pad and terminate this group.*/
   6879         nti = nac;
   6880         deliberate_fall_through; /* FALLTHRU */
   6881       case PC:
   6882         bdp = 0;
   6883         --nbo;
   6884         deliberate_fall_through; /* FALLTHRU */
   6885       default: /* bdp is the digit value. */
   6886         qv = qv<<6 | bdp;
   6887         break;
   6888       }
   6889     }
   6890     switch( nbo ){
   6891     case 3:
   6892       pOut[2] = (qv) & 0xff;
   6893       deliberate_fall_through; /* FALLTHRU */
   6894     case 2:
   6895       pOut[1] = (qv>>8) & 0xff;
   6896       deliberate_fall_through; /* FALLTHRU */
   6897     case 1:
   6898       pOut[0] = (qv>>16) & 0xff;
   6899       break;
   6900     }
   6901     pOut += nbo;
   6902   }
   6903   return pOut;
   6904 }
   6905 
   6906 /* This function does the work for the SQLite base64(x) UDF. */
   6907 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
   6908   sqlite3_int64 nb;
   6909   sqlite3_int64 nv = sqlite3_value_bytes(av[0]);
   6910   sqlite3_int64 nc;
   6911   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
   6912                             SQLITE_LIMIT_LENGTH, -1);
   6913   char *cBuf;
   6914   u8 *bBuf;
   6915   assert(na==1);
   6916   switch( sqlite3_value_type(av[0]) ){
   6917   case SQLITE_BLOB:
   6918     nb = nv;
   6919     nc = 4*((nv+2)/3); /* quads needed */
   6920     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
   6921     if( nvMax < nc ){
   6922       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
   6923       return;
   6924     }
   6925     bBuf = (u8*)sqlite3_value_blob(av[0]);
   6926     if( !bBuf ){
   6927       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
   6928         goto memFail;
   6929       }
   6930       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
   6931       break;
   6932     }
   6933     cBuf = sqlite3_malloc64(nc);
   6934     if( !cBuf ) goto memFail;
   6935     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
   6936     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
   6937     break;
   6938   case SQLITE_TEXT:
   6939     nc = nv;
   6940     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
   6941     if( nvMax < nb ){
   6942       sqlite3_result_error(context, "blob from base64 may be too big", -1);
   6943       return;
   6944     }else if( nb<1 ){
   6945       nb = 1;
   6946     }
   6947     cBuf = (char *)sqlite3_value_text(av[0]);
   6948     if( !cBuf ){
   6949       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
   6950         goto memFail;
   6951       }
   6952       sqlite3_result_zeroblob(context, 0);
   6953       break;
   6954     }
   6955     bBuf = sqlite3_malloc64(nb);
   6956     if( !bBuf ) goto memFail;
   6957     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
   6958     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
   6959     break;
   6960   default:
   6961     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
   6962     return;
   6963   }
   6964   return;
   6965  memFail:
   6966   sqlite3_result_error(context, "base64 OOM", -1);
   6967 }
   6968 
   6969 /*
   6970 ** Establish linkage to running SQLite library.
   6971 */
   6972 #ifndef SQLITE_SHELL_EXTFUNCS
   6973 #ifdef _WIN32
   6974 
   6975 #endif
   6976 static int sqlite3_base64_init
   6977 #else
   6978 static int sqlite3_base64_init
   6979 #endif
   6980 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
   6981   SQLITE_EXTENSION_INIT2(pApi);
   6982   (void)pzErr;
   6983   return sqlite3_create_function
   6984     (db, "base64", 1,
   6985      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
   6986      0, base64, 0, 0);
   6987 }
   6988 
   6989 /*
   6990 ** Define some macros to allow this extension to be built into the shell
   6991 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
   6992 ** allows shell.c, as distributed, to have this extension built in.
   6993 */
   6994 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
   6995 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
   6996 
   6997 /************************* End ext/misc/base64.c ********************/
   6998 /************************* Begin ext/misc/base85.c ******************/
   6999 /*
   7000 ** 2022-11-16
   7001 **
   7002 ** The author disclaims copyright to this source code.  In place of
   7003 ** a legal notice, here is a blessing:
   7004 **
   7005 **    May you do good and not evil.
   7006 **    May you find forgiveness for yourself and forgive others.
   7007 **    May you share freely, never taking more than you give.
   7008 **
   7009 *************************************************************************
   7010 **
   7011 ** This is a utility for converting binary to base85 or vice-versa.
   7012 ** It can be built as a standalone program or an SQLite3 extension.
   7013 **
   7014 ** Much like base64 representations, base85 can be sent through a
   7015 ** sane USASCII channel unmolested. It also plays nicely in CSV or
   7016 ** written as TCL brace-enclosed literals or SQL string literals.
   7017 ** It is not suited for unmodified use in XML-like documents.
   7018 **
   7019 ** The encoding used resembles Ascii85, but was devised by the author
   7020 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
   7021 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
   7022 ** Further, this is an independent implementation of a base85 system.
   7023 ** Hence, the author has rightfully put this into the public domain.
   7024 **
   7025 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
   7026 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
   7027 ** in code order representing digit values 0 to 84 (base 10.)
   7028 **
   7029 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
   7030 ** are represented as 5-digit base85 numbers with MS to LS digit
   7031 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
   7032 ** still big-endian but 8-24 bit values. (Using big-endian yields
   7033 ** the simplest transition to byte groups smaller than 4 bytes.
   7034 ** These byte groups can also be considered base-256 numbers.)
   7035 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
   7036 ** No pad characters are used; Encoded base85 numeral sequence
   7037 ** (aka "group") length maps 1-to-1 to the decoded binary length.
   7038 **
   7039 ** Any character not in the base85 numeral set delimits groups.
   7040 ** When base85 is streamed or stored in containers of indefinite
   7041 ** size, newline is used to separate it into sub-sequences of no
   7042 ** more than 80 digits so that fgets() can be used to read it.
   7043 **
   7044 ** Length limitations are not imposed except that the runtime
   7045 ** SQLite string or blob length limits are respected. Otherwise,
   7046 ** any length binary sequence can be represented and recovered.
   7047 ** Base85 sequences can be concatenated by separating them with
   7048 ** a non-base85 character; the conversion to binary will then
   7049 ** be the concatenation of the represented binary sequences.
   7050 
   7051 ** The standalone program either converts base85 on stdin to create
   7052 ** a binary file or converts a binary file to base85 on stdout.
   7053 ** Read or make it blurt its help for invocation details.
   7054 **
   7055 ** The SQLite3 extension creates a function, base85(x), which will
   7056 ** either convert text base85 to a blob or a blob to text base85
   7057 ** and return the result (or throw an error for other types.)
   7058 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
   7059 ** function, is_base85(t), which returns 1 iff the text t contains
   7060 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
   7061 **
   7062 ** To build the extension:
   7063 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
   7064 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
   7065 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
   7066 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
   7067 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
   7068 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
   7069 **
   7070 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
   7071 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
   7072 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
   7073 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
   7074 */
   7075 
   7076 #include <stdio.h>
   7077 #include <memory.h>
   7078 #include <string.h>
   7079 #include <assert.h>
   7080 #ifndef OMIT_BASE85_CHECKER
   7081 # include <ctype.h>
   7082 #endif
   7083 
   7084 #ifndef BASE85_STANDALONE
   7085 
   7086 /* # include "sqlite3ext.h" */
   7087 
   7088 SQLITE_EXTENSION_INIT1;
   7089 
   7090 #else
   7091 
   7092 # ifdef _WIN32
   7093 #  include <io.h>
   7094 #  include <fcntl.h>
   7095 # else
   7096 #  define setmode(fd,m)
   7097 # endif
   7098 
   7099 static char *zHelp =
   7100   "Usage: base85 <dirFlag> <binFile>\n"
   7101   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
   7102   "   content to be converted to/from base85 on stdout/stdin.\n"
   7103   " <binFile> names a binary file to be rendered or created.\n"
   7104   "   Or, the name '-' refers to the stdin or stdout stream.\n"
   7105   ;
   7106 
   7107 static void sayHelp(){
   7108   printf("%s", zHelp);
   7109 }
   7110 #endif
   7111 
   7112 #ifndef U8_TYPEDEF
   7113 /* typedef unsigned char u8; */
   7114 #define U8_TYPEDEF
   7115 #endif
   7116 
   7117 /* Classify c according to interval within USASCII set w.r.t. base85
   7118  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
   7119  */
   7120 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
   7121 
   7122 /* Provide digitValue to b85Numeral offset as a function of above class. */
   7123 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
   7124 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
   7125 
   7126 /* Say whether c is a base85 numeral. */
   7127 #define IS_B85( c ) (B85_CLASS(c) & 1)
   7128 
   7129 #if 0 /* Not used, */
   7130 static u8 base85DigitValue( char c ){
   7131   u8 dv = (u8)(c - '#');
   7132   if( dv>87 ) return 0xff;
   7133   return (dv > 3)? dv-3 : dv;
   7134 }
   7135 #endif
   7136 
   7137 /* Width of base64 lines. Should be an integer multiple of 5. */
   7138 #define B85_DARK_MAX 80
   7139 
   7140 
   7141 static char * skipNonB85( char *s, int nc ){
   7142   char c;
   7143   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
   7144   return s;
   7145 }
   7146 
   7147 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
   7148  * Do not use the macro form with argument expression having a side-effect.*/
   7149 #if 0
   7150 static char base85Numeral( u8 b ){
   7151   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
   7152 }
   7153 #else
   7154 # define base85Numeral( dn )\
   7155   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
   7156 #endif
   7157 
   7158 static char *putcs(char *pc, char *s){
   7159   char c;
   7160   while( (c = *s++)!=0 ) *pc++ = c;
   7161   return pc;
   7162 }
   7163 
   7164 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
   7165 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
   7166 ** or to terminate the last group (to aid concatenation.)
   7167 */
   7168 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
   7169   int nCol = 0;
   7170   while( nbIn >= 4 ){
   7171     int nco = 5;
   7172     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
   7173                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
   7174     while( nco > 0 ){
   7175       unsigned nqv = (unsigned)(qbv/85UL);
   7176       unsigned char dv = qbv - 85UL*nqv;
   7177       qbv = nqv;
   7178       pOut[--nco] = base85Numeral(dv);
   7179     }
   7180     nbIn -= 4;
   7181     pIn += 4;
   7182     pOut += 5;
   7183     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
   7184       pOut = putcs(pOut, pSep);
   7185       nCol = 0;
   7186     }
   7187   }
   7188   if( nbIn > 0 ){
   7189     int nco = nbIn + 1;
   7190     unsigned long qv = *pIn++;
   7191     int nbe = 1;
   7192     while( nbe++ < nbIn ){
   7193       qv = (qv<<8) | *pIn++;
   7194     }
   7195     nCol += nco;
   7196     while( nco > 0 ){
   7197       u8 dv = (u8)(qv % 85);
   7198       qv /= 85;
   7199       pOut[--nco] = base85Numeral(dv);
   7200     }
   7201     pOut += (nbIn+1);
   7202   }
   7203   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
   7204   *pOut = 0;
   7205   return pOut;
   7206 }
   7207 
   7208 /* Decode base85 text into a byte buffer. */
   7209 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
   7210   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
   7211   while( ncIn>0 ){
   7212     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
   7213     char *pUse = skipNonB85(pIn, ncIn);
   7214     unsigned long qv = 0L;
   7215     int nti, nbo;
   7216     ncIn -= (pUse - pIn);
   7217     pIn = pUse;
   7218     nti = (ncIn>5)? 5 : ncIn;
   7219     nbo = nboi[nti];
   7220     if( nbo==0 ) break;
   7221     while( nti>0 ){
   7222       char c = *pIn++;
   7223       u8 cdo = B85_DNOS(c);
   7224       --ncIn;
   7225       if( cdo==0 ) break;
   7226       qv = 85 * qv + (c - cdo);
   7227       --nti;
   7228     }
   7229     nbo -= nti; /* Adjust for early (non-digit) end of group. */
   7230     switch( nbo ){
   7231     case 4:
   7232       *pOut++ = (qv >> 24)&0xff;
   7233       /* FALLTHRU */
   7234     case 3:
   7235       *pOut++ = (qv >> 16)&0xff;
   7236       /* FALLTHRU */
   7237     case 2:
   7238       *pOut++ = (qv >> 8)&0xff;
   7239       /* FALLTHRU */
   7240     case 1:
   7241       *pOut++ = qv&0xff;
   7242       /* FALLTHRU */
   7243     case 0:
   7244       break;
   7245     }
   7246   }
   7247   return pOut;
   7248 }
   7249 
   7250 #ifndef OMIT_BASE85_CHECKER
   7251 /* Say whether input char sequence is all (base85 and/or whitespace).*/
   7252 static int allBase85( char *p, int len ){
   7253   char c;
   7254   while( len-- > 0 && (c = *p++) != 0 ){
   7255     if( !IS_B85(c) && !IsSpace(c) ) return 0;
   7256   }
   7257   return 1;
   7258 }
   7259 #endif
   7260 
   7261 #ifndef BASE85_STANDALONE
   7262 
   7263 #ifndef OMIT_BASE85_CHECKER
   7264 /* This function does the work for the SQLite is_base85(t) UDF. */
   7265 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
   7266   assert(na==1);
   7267   switch( sqlite3_value_type(av[0]) ){
   7268   case SQLITE_TEXT:
   7269     {
   7270       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
   7271                           sqlite3_value_bytes(av[0]) );
   7272       sqlite3_result_int(context, rv);
   7273     }
   7274     break;
   7275   case SQLITE_NULL:
   7276     sqlite3_result_null(context);
   7277     break;
   7278   default:
   7279     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
   7280     return;
   7281   }
   7282 }
   7283 #endif
   7284 
   7285 /* This function does the work for the SQLite base85(x) UDF. */
   7286 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
   7287   sqlite3_int64 nb, nc, nv = sqlite3_value_bytes(av[0]);
   7288   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
   7289                             SQLITE_LIMIT_LENGTH, -1);
   7290   char *cBuf;
   7291   u8 *bBuf;
   7292   assert(na==1);
   7293   switch( sqlite3_value_type(av[0]) ){
   7294   case SQLITE_BLOB:
   7295     nb = nv;
   7296     /*    ulongs    tail   newlines  tailenc+nul*/
   7297     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
   7298     if( nvMax < nc ){
   7299       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
   7300       return;
   7301     }
   7302     bBuf = (u8*)sqlite3_value_blob(av[0]);
   7303     if( !bBuf ){
   7304       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
   7305         goto memFail;
   7306       }
   7307       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
   7308       break;
   7309     }
   7310     cBuf = sqlite3_malloc64(nc);
   7311     if( !cBuf ) goto memFail;
   7312     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
   7313     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
   7314     break;
   7315   case SQLITE_TEXT:
   7316     nc = nv;
   7317     nb = 4*(nv/5) + nv%5; /* may overestimate */
   7318     if( nvMax < nb ){
   7319       sqlite3_result_error(context, "blob from base85 may be too big", -1);
   7320       return;
   7321     }else if( nb<1 ){
   7322       nb = 1;
   7323     }
   7324     cBuf = (char *)sqlite3_value_text(av[0]);
   7325     if( !cBuf ){
   7326       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
   7327         goto memFail;
   7328       }
   7329       sqlite3_result_zeroblob(context, 0);
   7330       break;
   7331     }
   7332     bBuf = sqlite3_malloc64(nb);
   7333     if( !bBuf ) goto memFail;
   7334     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
   7335     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
   7336     break;
   7337   default:
   7338     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
   7339     return;
   7340   }
   7341   return;
   7342  memFail:
   7343   sqlite3_result_error(context, "base85 OOM", -1);
   7344 }
   7345 
   7346 /*
   7347 ** Establish linkage to running SQLite library.
   7348 */
   7349 #ifndef SQLITE_SHELL_EXTFUNCS
   7350 #ifdef _WIN32
   7351 
   7352 #endif
   7353 static int sqlite3_base85_init
   7354 #else
   7355 static int sqlite3_base85_init
   7356 #endif
   7357 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
   7358   SQLITE_EXTENSION_INIT2(pApi);
   7359   (void)pzErr;
   7360 #ifndef OMIT_BASE85_CHECKER
   7361   {
   7362     int rc = sqlite3_create_function
   7363       (db, "is_base85", 1,
   7364        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
   7365        0, is_base85, 0, 0);
   7366     if( rc!=SQLITE_OK ) return rc;
   7367   }
   7368 #endif
   7369   return sqlite3_create_function
   7370     (db, "base85", 1,
   7371      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
   7372      0, base85, 0, 0);
   7373 }
   7374 
   7375 /*
   7376 ** Define some macros to allow this extension to be built into the shell
   7377 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
   7378 ** allows shell.c, as distributed, to have this extension built in.
   7379 */
   7380 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
   7381 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
   7382 
   7383 #else /* standalone program */
   7384 
   7385 int main(int na, char *av[]){
   7386   int cin;
   7387   int rc = 0;
   7388   u8 bBuf[4*(B85_DARK_MAX/5)];
   7389   char cBuf[5*(sizeof(bBuf)/4)+2];
   7390   size_t nio;
   7391 # ifndef OMIT_BASE85_CHECKER
   7392   int b85Clean = 1;
   7393 # endif
   7394   char rw;
   7395   FILE *fb = 0, *foc = 0;
   7396   char fmode[3] = "xb";
   7397   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
   7398     sayHelp();
   7399     return 0;
   7400   }
   7401   fmode[0] = rw;
   7402   if( av[2][0]=='-' && av[2][1]==0 ){
   7403     switch( rw ){
   7404     case 'r':
   7405       fb = stdin;
   7406       setmode(fileno(stdin), O_BINARY);
   7407       break;
   7408     case 'w':
   7409       fb = stdout;
   7410       setmode(fileno(stdout), O_BINARY);
   7411       break;
   7412     }
   7413   }else{
   7414     fb = fopen(av[2], fmode);
   7415     foc = fb;
   7416   }
   7417   if( !fb ){
   7418     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
   7419     rc = 1;
   7420   }else{
   7421     switch( rw ){
   7422     case 'r':
   7423       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
   7424         toBase85( bBuf, (int)nio, cBuf, 0 );
   7425         fprintf(stdout, "%s\n", cBuf);
   7426       }
   7427       break;
   7428     case 'w':
   7429       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
   7430         int nc = strlen(cBuf);
   7431         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
   7432         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
   7433 #ifndef OMIT_BASE85_CHECKER
   7434         b85Clean &= allBase85( cBuf, nc );
   7435 #endif
   7436       }
   7437       break;
   7438     default:
   7439       sayHelp();
   7440       rc = 1;
   7441     }
   7442     if( foc ) fclose(foc);
   7443   }
   7444 # ifndef OMIT_BASE85_CHECKER
   7445   if( !b85Clean ){
   7446     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
   7447   }
   7448 # endif
   7449   return rc;
   7450 }
   7451 
   7452 #endif
   7453 
   7454 /************************* End ext/misc/base85.c ********************/
   7455 /************************* Begin ext/misc/ieee754.c ******************/
   7456 /*
   7457 ** 2013-04-17
   7458 **
   7459 ** The author disclaims copyright to this source code.  In place of
   7460 ** a legal notice, here is a blessing:
   7461 **
   7462 **    May you do good and not evil.
   7463 **    May you find forgiveness for yourself and forgive others.
   7464 **    May you share freely, never taking more than you give.
   7465 **
   7466 ******************************************************************************
   7467 **
   7468 ** This SQLite extension implements functions for the exact display
   7469 ** and input of IEEE754 Binary64 floating-point numbers.
   7470 **
   7471 **   ieee754(X)
   7472 **   ieee754(Y,Z)
   7473 **
   7474 ** In the first form, the value X should be a floating-point number.
   7475 ** The function will return a string of the form 'ieee754(Y,Z)' where
   7476 ** Y and Z are integers such that X==Y*pow(2,Z).
   7477 **
   7478 ** In the second form, Y and Z are integers which are the mantissa and
   7479 ** base-2 exponent of a new floating point number.  The function returns
   7480 ** a floating-point value equal to Y*pow(2,Z).
   7481 **
   7482 ** Examples:
   7483 **
   7484 **     ieee754(2.0)             ->     'ieee754(2,0)'
   7485 **     ieee754(45.25)           ->     'ieee754(181,-2)'
   7486 **     ieee754(2, 0)            ->     2.0
   7487 **     ieee754(181, -2)         ->     45.25
   7488 **
   7489 ** Two additional functions break apart the one-argument ieee754()
   7490 ** result into separate integer values:
   7491 **
   7492 **     ieee754_mantissa(45.25)  ->     181
   7493 **     ieee754_exponent(45.25)  ->     -2
   7494 **
   7495 ** These functions convert binary64 numbers into blobs and back again.
   7496 **
   7497 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
   7498 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
   7499 **
   7500 ** In all single-argument functions, if the argument is an 8-byte blob
   7501 ** then that blob is interpreted as a big-endian binary64 value.
   7502 **
   7503 **
   7504 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
   7505 ** -----------------------------------------------
   7506 **
   7507 ** This extension in combination with the separate 'decimal' extension
   7508 ** can be used to compute the exact decimal representation of binary64
   7509 ** values.  To begin, first compute a table of exponent values:
   7510 **
   7511 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
   7512 **    WITH RECURSIVE c(x,v) AS (
   7513 **      VALUES(0,'1')
   7514 **      UNION ALL
   7515 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
   7516 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
   7517 **    WITH RECURSIVE c(x,v) AS (
   7518 **      VALUES(-1,'0.5')
   7519 **      UNION ALL
   7520 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
   7521 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
   7522 **
   7523 ** Then, to compute the exact decimal representation of a floating
   7524 ** point value (the value 47.49 is used in the example) do:
   7525 **
   7526 **    WITH c(n) AS (VALUES(47.49))
   7527 **          ---------------^^^^^---- Replace with whatever you want
   7528 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
   7529 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
   7530 **
   7531 ** Here is a query to show various boundry values for the binary64
   7532 ** number format:
   7533 **
   7534 **    WITH c(name,bin) AS (VALUES
   7535 **       ('minimum positive value',        x'0000000000000001'),
   7536 **       ('maximum subnormal value',       x'000fffffffffffff'),
   7537 **       ('minimum positive normal value', x'0010000000000000'),
   7538 **       ('maximum value',                 x'7fefffffffffffff'))
   7539 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
   7540 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
   7541 **
   7542 */
   7543 /* #include "sqlite3ext.h" */
   7544 SQLITE_EXTENSION_INIT1
   7545 #include <assert.h>
   7546 #include <string.h>
   7547 
   7548 /* Mark a function parameter as unused, to suppress nuisance compiler
   7549 ** warnings. */
   7550 #ifndef UNUSED_PARAMETER
   7551 # define UNUSED_PARAMETER(X)  (void)(X)
   7552 #endif
   7553 
   7554 /*
   7555 ** Implementation of the ieee754() function
   7556 */
   7557 static void ieee754func(
   7558   sqlite3_context *context,
   7559   int argc,
   7560   sqlite3_value **argv
   7561 ){
   7562   if( argc==1 ){
   7563     sqlite3_int64 m, a;
   7564     double r;
   7565     int e;
   7566     int isNeg;
   7567     char zResult[100];
   7568     assert( sizeof(m)==sizeof(r) );
   7569     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
   7570      && sqlite3_value_bytes(argv[0])==sizeof(r)
   7571     ){
   7572       const unsigned char *x = sqlite3_value_blob(argv[0]);
   7573       unsigned int i;
   7574       sqlite3_uint64 v = 0;
   7575       for(i=0; i<sizeof(r); i++){
   7576         v = (v<<8) | x[i];
   7577       }
   7578       memcpy(&r, &v, sizeof(r));
   7579     }else{
   7580       r = sqlite3_value_double(argv[0]);
   7581     }
   7582     if( r<0.0 ){
   7583       isNeg = 1;
   7584       r = -r;
   7585     }else{
   7586       isNeg = 0;
   7587     }
   7588     memcpy(&a,&r,sizeof(a));
   7589     if( a==0 ){
   7590       e = 0;
   7591       m = 0;
   7592     }else if( a==(sqlite3_int64)0x8000000000000000LL ){
   7593       e = -1996;
   7594       m = -1;
   7595     }else{
   7596       e = a>>52;
   7597       m = a & ((((sqlite3_int64)1)<<52)-1);
   7598       if( e==0 ){
   7599         m <<= 1;
   7600       }else{
   7601         m |= ((sqlite3_int64)1)<<52;
   7602       }
   7603       while( e<1075 && m>0 && (m&1)==0 ){
   7604         m >>= 1;
   7605         e++;
   7606       }
   7607       if( isNeg ) m = -m;
   7608     }
   7609     switch( *(int*)sqlite3_user_data(context) ){
   7610       case 0:
   7611         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
   7612                          m, e-1075);
   7613         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
   7614         break;
   7615       case 1:
   7616         sqlite3_result_int64(context, m);
   7617         break;
   7618       case 2:
   7619         sqlite3_result_int(context, e-1075);
   7620         break;
   7621     }
   7622   }else{
   7623     sqlite3_int64 m, e, a;
   7624     double r;
   7625     int isNeg = 0;
   7626     m = sqlite3_value_int64(argv[0]);
   7627     e = sqlite3_value_int64(argv[1]);
   7628 
   7629     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
   7630     if( e>10000 ){
   7631       e = 10000;
   7632     }else if( e<-10000 ){
   7633       e = -10000;
   7634     }
   7635 
   7636     if( m<0 ){
   7637       if( m<(-9223372036854775807LL) ) return;
   7638       isNeg = 1;
   7639       m = -m;
   7640     }else if( m==0 && e>-1000 && e<1000 ){
   7641       sqlite3_result_double(context, 0.0);
   7642       return;
   7643     }
   7644     while( (m>>32)&0xffe00000 ){
   7645       m >>= 1;
   7646       e++;
   7647     }
   7648     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
   7649       m <<= 1;
   7650       e--;
   7651     }
   7652     e += 1075;
   7653     if( e<=0 ){
   7654       /* Subnormal */
   7655       if( 1-e >= 64 ){
   7656         m = 0;
   7657       }else{
   7658         m >>= 1-e;
   7659       }
   7660       e = 0;
   7661     }else if( e>0x7ff ){
   7662       e = 0x7ff;
   7663     }
   7664     a = m & ((((sqlite3_int64)1)<<52)-1);
   7665     a |= e<<52;
   7666     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
   7667     memcpy(&r, &a, sizeof(r));
   7668     sqlite3_result_double(context, r);
   7669   }
   7670 }
   7671 
   7672 /*
   7673 ** Functions to convert between blobs and floats.
   7674 */
   7675 static void ieee754func_from_blob(
   7676   sqlite3_context *context,
   7677   int argc,
   7678   sqlite3_value **argv
   7679 ){
   7680   UNUSED_PARAMETER(argc);
   7681   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
   7682    && sqlite3_value_bytes(argv[0])==sizeof(double)
   7683   ){
   7684     double r;
   7685     const unsigned char *x = sqlite3_value_blob(argv[0]);
   7686     unsigned int i;
   7687     sqlite3_uint64 v = 0;
   7688     for(i=0; i<sizeof(r); i++){
   7689       v = (v<<8) | x[i];
   7690     }
   7691     memcpy(&r, &v, sizeof(r));
   7692     sqlite3_result_double(context, r);
   7693   }
   7694 }
   7695 static void ieee754func_to_blob(
   7696   sqlite3_context *context,
   7697   int argc,
   7698   sqlite3_value **argv
   7699 ){
   7700   UNUSED_PARAMETER(argc);
   7701   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
   7702    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
   7703   ){
   7704     double r = sqlite3_value_double(argv[0]);
   7705     sqlite3_uint64 v;
   7706     unsigned char a[sizeof(r)];
   7707     unsigned int i;
   7708     memcpy(&v, &r, sizeof(r));
   7709     for(i=1; i<=sizeof(r); i++){
   7710       a[sizeof(r)-i] = v&0xff;
   7711       v >>= 8;
   7712     }
   7713     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
   7714   }
   7715 }
   7716 
   7717 /*
   7718 ** Functions to convert between 64-bit integers and floats.
   7719 **
   7720 ** The bit patterns are copied.  The numeric values are different.
   7721 */
   7722 static void ieee754func_from_int(
   7723   sqlite3_context *context,
   7724   int argc,
   7725   sqlite3_value **argv
   7726 ){
   7727   UNUSED_PARAMETER(argc);
   7728   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
   7729     double r;
   7730     sqlite3_int64 v = sqlite3_value_int64(argv[0]);
   7731     memcpy(&r, &v, sizeof(r));
   7732     sqlite3_result_double(context, r);
   7733   }
   7734 }
   7735 static void ieee754func_to_int(
   7736   sqlite3_context *context,
   7737   int argc,
   7738   sqlite3_value **argv
   7739 ){
   7740   UNUSED_PARAMETER(argc);
   7741   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT ){
   7742     double r = sqlite3_value_double(argv[0]);
   7743     sqlite3_uint64 v;
   7744     memcpy(&v, &r, sizeof(v));
   7745     sqlite3_result_int64(context, v);
   7746   }
   7747 }
   7748 
   7749 /*
   7750 ** SQL Function:   ieee754_inc(r,N)
   7751 **
   7752 ** Move the floating point value r by N quantums and return the new
   7753 ** values.
   7754 **
   7755 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
   7756 ** integer, adds N, then casts the value back into float.
   7757 **
   7758 ** Example:  To find the smallest positive number:
   7759 **
   7760 **     SELECT ieee754_inc(0.0,+1);
   7761 */
   7762 static void ieee754inc(
   7763   sqlite3_context *context,
   7764   int argc,
   7765   sqlite3_value **argv
   7766 ){
   7767   double r;
   7768   sqlite3_int64 N;
   7769   sqlite3_uint64 m1, m2;
   7770   double r2;
   7771   UNUSED_PARAMETER(argc);
   7772   r = sqlite3_value_double(argv[0]);
   7773   N = sqlite3_value_int64(argv[1]);
   7774   memcpy(&m1, &r, 8);
   7775   m2 = m1 + N;
   7776   memcpy(&r2, &m2, 8);
   7777   sqlite3_result_double(context, r2);
   7778 }
   7779 
   7780 
   7781 #ifdef _WIN32
   7782 
   7783 #endif
   7784 static int sqlite3_ieee_init(
   7785   sqlite3 *db,
   7786   char **pzErrMsg,
   7787   const sqlite3_api_routines *pApi
   7788 ){
   7789   static const struct {
   7790     char *zFName;
   7791     int nArg;
   7792     int iAux;
   7793     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   7794   } aFunc[] = {
   7795     { "ieee754",           1,   0, ieee754func },
   7796     { "ieee754",           2,   0, ieee754func },
   7797     { "ieee754_mantissa",  1,   1, ieee754func },
   7798     { "ieee754_exponent",  1,   2, ieee754func },
   7799     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
   7800     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
   7801     { "ieee754_to_int",    1,   0, ieee754func_to_int },
   7802     { "ieee754_from_int",  1,   0, ieee754func_from_int },
   7803     { "ieee754_inc",       2,   0, ieee754inc  },
   7804   };
   7805   unsigned int i;
   7806   int rc = SQLITE_OK;
   7807   SQLITE_EXTENSION_INIT2(pApi);
   7808   (void)pzErrMsg;  /* Unused parameter */
   7809   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
   7810     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
   7811                                SQLITE_UTF8|SQLITE_INNOCUOUS,
   7812                                (void*)&aFunc[i].iAux,
   7813                                aFunc[i].xFunc, 0, 0);
   7814   }
   7815   return rc;
   7816 }
   7817 
   7818 /************************* End ext/misc/ieee754.c ********************/
   7819 /************************* Begin ext/misc/series.c ******************/
   7820 /*
   7821 ** 2015-08-18, 2023-04-28
   7822 **
   7823 ** The author disclaims copyright to this source code.  In place of
   7824 ** a legal notice, here is a blessing:
   7825 **
   7826 **    May you do good and not evil.
   7827 **    May you find forgiveness for yourself and forgive others.
   7828 **    May you share freely, never taking more than you give.
   7829 **
   7830 *************************************************************************
   7831 **
   7832 ** This file demonstrates how to create a table-valued-function using
   7833 ** a virtual table.  This demo implements the generate_series() function
   7834 ** which gives the same results as the eponymous function in PostgreSQL,
   7835 ** within the limitation that its arguments are signed 64-bit integers.
   7836 **
   7837 ** Considering its equivalents to generate_series(start,stop,step): A
   7838 ** value V[n] sequence is produced for integer n ascending from 0 where
   7839 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
   7840 ** for each produced value (independent of production time ordering.)
   7841 **
   7842 ** All parameters must be either integer or convertable to integer.
   7843 ** The start parameter is required.
   7844 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
   7845 ** The step parameter defaults to 1 and 0 is treated as 1.
   7846 **
   7847 ** Examples:
   7848 **
   7849 **      SELECT * FROM generate_series(0,100,5);
   7850 **
   7851 ** The query above returns integers from 0 through 100 counting by steps
   7852 ** of 5.  In other words, 0, 5, 10, 15, ..., 90, 95, 100.  There are a total
   7853 ** of 21 rows.
   7854 **
   7855 **      SELECT * FROM generate_series(0,100);
   7856 **
   7857 ** Integers from 0 through 100 with a step size of 1.  101 rows.
   7858 **
   7859 **      SELECT * FROM generate_series(20) LIMIT 10;
   7860 **
   7861 ** Integers 20 through 29.  10 rows.
   7862 **
   7863 **      SELECT * FROM generate_series(0,-100,-5);
   7864 **
   7865 ** Integers 0 -5 -10 ... -100.  21 rows.
   7866 **
   7867 **      SELECT * FROM generate_series(0,-1);
   7868 **
   7869 ** Empty sequence.
   7870 **
   7871 ** HOW IT WORKS
   7872 **
   7873 ** The generate_series "function" is really a virtual table with the
   7874 ** following schema:
   7875 **
   7876 **     CREATE TABLE generate_series(
   7877 **       value,
   7878 **       start HIDDEN,
   7879 **       stop HIDDEN,
   7880 **       step HIDDEN
   7881 **     );
   7882 **
   7883 ** The virtual table also has a rowid which is an alias for the value.
   7884 **
   7885 ** Function arguments in queries against this virtual table are translated
   7886 ** into equality constraints against successive hidden columns.  In other
   7887 ** words, the following pairs of queries are equivalent to each other:
   7888 **
   7889 **    SELECT * FROM generate_series(0,100,5);
   7890 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
   7891 **
   7892 **    SELECT * FROM generate_series(0,100);
   7893 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
   7894 **
   7895 **    SELECT * FROM generate_series(20) LIMIT 10;
   7896 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
   7897 **
   7898 ** The generate_series virtual table implementation leaves the xCreate method
   7899 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
   7900 ** TABLE command with "generate_series" as the USING argument.  Instead, there
   7901 ** is a single generate_series virtual table that is always available without
   7902 ** having to be created first.
   7903 **
   7904 ** The xBestIndex method looks for equality constraints against the hidden
   7905 ** start, stop, and step columns, and if present, it uses those constraints
   7906 ** to bound the sequence of generated values.  If the equality constraints
   7907 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
   7908 ** xBestIndex returns a small cost when both start and stop are available,
   7909 ** and a very large cost if either start or stop are unavailable.  This
   7910 ** encourages the query planner to order joins such that the bounds of the
   7911 ** series are well-defined.
   7912 **
   7913 ** Update on 2024-08-22:
   7914 ** xBestIndex now also looks for equality and inequality constraints against
   7915 ** the value column and uses those constraints as additional bounds against
   7916 ** the sequence range.  Thus, a query like this:
   7917 **
   7918 **     SELECT value FROM generate_series($SA,$EA)
   7919 **      WHERE value BETWEEN $SB AND $EB;
   7920 **
   7921 ** Is logically the same as:
   7922 **
   7923 **     SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB));
   7924 **
   7925 ** Constraints on the value column can server as substitutes for constraints
   7926 ** on the hidden start and stop columns.  So, the following two queries
   7927 ** are equivalent:
   7928 **
   7929 **     SELECT value FROM generate_series($S,$E);
   7930 **     SELECT value FROM generate_series WHERE value BETWEEN $S and $E;
   7931 **
   7932 */
   7933 /* #include "sqlite3ext.h" */
   7934 SQLITE_EXTENSION_INIT1
   7935 #include <assert.h>
   7936 #include <string.h>
   7937 #include <limits.h>
   7938 #include <math.h>
   7939 
   7940 #ifndef SQLITE_OMIT_VIRTUALTABLE
   7941 
   7942 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
   7943 ** serve as the underlying representation of a cursor that scans
   7944 ** over rows of the result.
   7945 **
   7946 ** iOBase, iOTerm, and iOStep are the original values of the
   7947 ** start=, stop=, and step= constraints on the query.  These are
   7948 ** the values reported by the start, stop, and step columns of the
   7949 ** virtual table.
   7950 **
   7951 ** iBase, iTerm, iStep, and bDescp are the actual values used to generate
   7952 ** the sequence.  These might be different from the iOxxxx values.
   7953 ** For example in
   7954 **
   7955 **   SELECT value FROM generate_series(1,11,2)
   7956 **    WHERE value BETWEEN 4 AND 8;
   7957 **
   7958 ** The iOBase is 1, but the iBase is 5.  iOTerm is 11 but iTerm is 7.
   7959 ** Another example:
   7960 **
   7961 **   SELECT value FROM generate_series(1,15,3) ORDER BY value DESC;
   7962 **
   7963 ** The cursor initialization for the above query is:
   7964 **
   7965 **   iOBase = 1        iBase = 13
   7966 **   iOTerm = 15       iTerm = 1
   7967 **   iOStep = 3        iStep = 3      bDesc = 1
   7968 **
   7969 ** The actual step size is unsigned so that can have a value of
   7970 ** +9223372036854775808 which is needed for querys like this:
   7971 **
   7972 **   SELECT value
   7973 **     FROM generate_series(9223372036854775807,
   7974 **                          -9223372036854775808,
   7975 **                          -9223372036854775808)
   7976 **    ORDER BY value ASC;
   7977 **
   7978 ** The setup for the previous query will be:
   7979 **
   7980 **   iOBase = 9223372036854775807    iBase = -1
   7981 **   iOTerm = -9223372036854775808   iTerm = 9223372036854775807
   7982 **   iOStep = -9223372036854775808   iStep = 9223372036854775808  bDesc = 0
   7983 */
   7984 /* typedef unsigned char u8; */
   7985 typedef struct series_cursor series_cursor;
   7986 struct series_cursor {
   7987   sqlite3_vtab_cursor base;  /* Base class - must be first */
   7988   sqlite3_int64 iOBase;      /* Original starting value ("start") */
   7989   sqlite3_int64 iOTerm;      /* Original terminal value ("stop") */
   7990   sqlite3_int64 iOStep;      /* Original step value */
   7991   sqlite3_int64 iBase;       /* Starting value to actually use */
   7992   sqlite3_int64 iTerm;       /* Terminal value to actually use */
   7993   sqlite3_uint64 iStep;      /* The step size */
   7994   sqlite3_int64 iValue;      /* Current value */
   7995   u8 bDesc;                  /* iStep is really negative */
   7996   u8 bDone;                  /* True if stepped past last element */
   7997 };
   7998 
   7999 /*
   8000 ** Computed the difference between two 64-bit signed integers using a
   8001 ** convoluted computation designed to work around the silly restriction
   8002 ** against signed integer overflow in C.
   8003 */
   8004 static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){
   8005   assert( a>=b );
   8006   return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b);
   8007 }
   8008 
   8009 /*
   8010 ** Add or substract an unsigned 64-bit integer from a signed 64-bit integer
   8011 ** and return the new signed 64-bit integer.
   8012 */
   8013 static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){
   8014   sqlite3_uint64 x = *(sqlite3_uint64*)&a;
   8015   x += b;
   8016   return *(sqlite3_int64*)&x;
   8017 }
   8018 static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){
   8019   sqlite3_uint64 x = *(sqlite3_uint64*)&a;
   8020   x -= b;
   8021   return *(sqlite3_int64*)&x;
   8022 }
   8023 
   8024 /*
   8025 ** The seriesConnect() method is invoked to create a new
   8026 ** series_vtab that describes the generate_series virtual table.
   8027 **
   8028 ** Think of this routine as the constructor for series_vtab objects.
   8029 **
   8030 ** All this routine needs to do is:
   8031 **
   8032 **    (1) Allocate the series_vtab object and initialize all fields.
   8033 **
   8034 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
   8035 **        result set of queries against generate_series will look like.
   8036 */
   8037 static int seriesConnect(
   8038   sqlite3 *db,
   8039   void *pUnused,
   8040   int argcUnused, const char *const*argvUnused,
   8041   sqlite3_vtab **ppVtab,
   8042   char **pzErrUnused
   8043 ){
   8044   sqlite3_vtab *pNew;
   8045   int rc;
   8046 
   8047 /* Column numbers */
   8048 #define SERIES_COLUMN_ROWID (-1)
   8049 #define SERIES_COLUMN_VALUE 0
   8050 #define SERIES_COLUMN_START 1
   8051 #define SERIES_COLUMN_STOP  2
   8052 #define SERIES_COLUMN_STEP  3
   8053 
   8054   (void)pUnused;
   8055   (void)argcUnused;
   8056   (void)argvUnused;
   8057   (void)pzErrUnused;
   8058   rc = sqlite3_declare_vtab(db,
   8059      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
   8060   if( rc==SQLITE_OK ){
   8061     pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) );
   8062     if( pNew==0 ) return SQLITE_NOMEM;
   8063     memset(pNew, 0, sizeof(*pNew));
   8064     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
   8065   }
   8066   return rc;
   8067 }
   8068 
   8069 /*
   8070 ** This method is the destructor for series_cursor objects.
   8071 */
   8072 static int seriesDisconnect(sqlite3_vtab *pVtab){
   8073   sqlite3_free(pVtab);
   8074   return SQLITE_OK;
   8075 }
   8076 
   8077 /*
   8078 ** Constructor for a new series_cursor object.
   8079 */
   8080 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
   8081   series_cursor *pCur;
   8082   (void)pUnused;
   8083   pCur = sqlite3_malloc64( sizeof(*pCur) );
   8084   if( pCur==0 ) return SQLITE_NOMEM;
   8085   memset(pCur, 0, sizeof(*pCur));
   8086   *ppCursor = &pCur->base;
   8087   return SQLITE_OK;
   8088 }
   8089 
   8090 /*
   8091 ** Destructor for a series_cursor.
   8092 */
   8093 static int seriesClose(sqlite3_vtab_cursor *cur){
   8094   sqlite3_free(cur);
   8095   return SQLITE_OK;
   8096 }
   8097 
   8098 
   8099 /*
   8100 ** Advance a series_cursor to its next row of output.
   8101 */
   8102 static int seriesNext(sqlite3_vtab_cursor *cur){
   8103   series_cursor *pCur = (series_cursor*)cur;
   8104   if( pCur->iValue==pCur->iTerm ){
   8105     pCur->bDone = 1;
   8106   }else if( pCur->bDesc ){
   8107     pCur->iValue = sub64(pCur->iValue, pCur->iStep);
   8108     assert( pCur->iValue>=pCur->iTerm );
   8109   }else{
   8110     pCur->iValue = add64(pCur->iValue, pCur->iStep);
   8111     assert( pCur->iValue<=pCur->iTerm );
   8112   }
   8113   return SQLITE_OK;
   8114 }
   8115 
   8116 /*
   8117 ** Return values of columns for the row at which the series_cursor
   8118 ** is currently pointing.
   8119 */
   8120 static int seriesColumn(
   8121   sqlite3_vtab_cursor *cur,   /* The cursor */
   8122   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   8123   int i                       /* Which column to return */
   8124 ){
   8125   series_cursor *pCur = (series_cursor*)cur;
   8126   sqlite3_int64 x = 0;
   8127   switch( i ){
   8128     case SERIES_COLUMN_START:  x = pCur->iOBase;     break;
   8129     case SERIES_COLUMN_STOP:   x = pCur->iOTerm;     break;
   8130     case SERIES_COLUMN_STEP:   x = pCur->iOStep;     break;
   8131     default:                   x = pCur->iValue;     break;
   8132   }
   8133   sqlite3_result_int64(ctx, x);
   8134   return SQLITE_OK;
   8135 }
   8136 
   8137 #ifndef LARGEST_UINT64
   8138 #define LARGEST_INT64  ((sqlite3_int64)0x7fffffffffffffffLL)
   8139 #define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL)
   8140 #define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL)
   8141 #endif
   8142 
   8143 /*
   8144 ** The rowid is the same as the value.
   8145 */
   8146 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   8147   series_cursor *pCur = (series_cursor*)cur;
   8148   *pRowid = pCur->iValue;
   8149   return SQLITE_OK;
   8150 }
   8151 
   8152 /*
   8153 ** Return TRUE if the cursor has been moved off of the last
   8154 ** row of output.
   8155 */
   8156 static int seriesEof(sqlite3_vtab_cursor *cur){
   8157   series_cursor *pCur = (series_cursor*)cur;
   8158   return pCur->bDone;
   8159 }
   8160 
   8161 /* True to cause run-time checking of the start=, stop=, and/or step=
   8162 ** parameters.  The only reason to do this is for testing the
   8163 ** constraint checking logic for virtual tables in the SQLite core.
   8164 */
   8165 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
   8166 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
   8167 #endif
   8168 
   8169 /*
   8170 ** Return the number of steps between pCur->iBase and pCur->iTerm if
   8171 ** the step width is pCur->iStep.
   8172 */
   8173 static sqlite3_uint64 seriesSteps(series_cursor *pCur){
   8174   if( pCur->bDesc ){
   8175     assert( pCur->iBase >= pCur->iTerm );
   8176     return span64(pCur->iBase, pCur->iTerm)/pCur->iStep;
   8177   }else{
   8178     assert( pCur->iBase <= pCur->iTerm );
   8179     return span64(pCur->iTerm, pCur->iBase)/pCur->iStep;
   8180   }
   8181 }
   8182 
   8183 #if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32)
   8184 /*
   8185 ** Case 1 (the most common case):
   8186 ** The standard math library is available so use ceil() and floor() from there.
   8187 */
   8188 static double seriesCeil(double r){ return ceil(r); }
   8189 static double seriesFloor(double r){ return floor(r); }
   8190 #elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
   8191 /*
   8192 ** Case 2 (2nd most common): Use GCC/Clang builtins
   8193 */
   8194 static double seriesCeil(double r){ return __builtin_ceil(r); }
   8195 static double seriesFloor(double r){ return __builtin_floor(r); }
   8196 #else
   8197 /*
   8198 ** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
   8199 */
   8200 static double seriesCeil(double r){
   8201   sqlite3_int64 x;
   8202   if( r!=r ) return r;
   8203   if( r<=(-4503599627370496.0) ) return r;
   8204   if( r>=(+4503599627370496.0) ) return r;
   8205   x = (sqlite3_int64)r;
   8206   if( r==(double)x ) return r;
   8207   if( r>(double)x ) x++;
   8208   return (double)x;
   8209 }
   8210 static double seriesFloor(double r){
   8211   sqlite3_int64 x;
   8212   if( r!=r ) return r;
   8213   if( r<=(-4503599627370496.0) ) return r;
   8214   if( r>=(+4503599627370496.0) ) return r;
   8215   x = (sqlite3_int64)r;
   8216   if( r==(double)x ) return r;
   8217   if( r<(double)x ) x--;
   8218   return (double)x;
   8219 }
   8220 #endif
   8221 
   8222 /*
   8223 ** This method is called to "rewind" the series_cursor object back
   8224 ** to the first row of output.  This method is always called at least
   8225 ** once prior to any call to seriesColumn() or seriesRowid() or
   8226 ** seriesEof().
   8227 **
   8228 ** The query plan selected by seriesBestIndex is passed in the idxNum
   8229 ** parameter.  (idxStr is not used in this implementation.)  idxNum
   8230 ** is a bitmask showing which constraints are available:
   8231 **
   8232 **   0x0001:    start=VALUE
   8233 **   0x0002:    stop=VALUE
   8234 **   0x0004:    step=VALUE
   8235 **   0x0008:    descending order
   8236 **   0x0010:    ascending order
   8237 **   0x0020:    LIMIT  VALUE
   8238 **   0x0040:    OFFSET  VALUE
   8239 **   0x0080:    value=VALUE
   8240 **   0x0100:    value>=VALUE
   8241 **   0x0200:    value>VALUE
   8242 **   0x1000:    value<=VALUE
   8243 **   0x2000:    value<VALUE
   8244 **
   8245 ** This routine should initialize the cursor and position it so that it
   8246 ** is pointing at the first row, or pointing off the end of the table
   8247 ** (so that seriesEof() will return true) if the table is empty.
   8248 */
   8249 static int seriesFilter(
   8250   sqlite3_vtab_cursor *pVtabCursor,
   8251   int idxNum, const char *idxStrUnused,
   8252   int argc, sqlite3_value **argv
   8253 ){
   8254   series_cursor *pCur = (series_cursor *)pVtabCursor;
   8255   int iArg = 0;                         /* Arguments used so far */
   8256   int i;                                /* Loop counter */
   8257   sqlite3_int64 iMin = SMALLEST_INT64;  /* Smallest allowed output value */
   8258   sqlite3_int64 iMax = LARGEST_INT64;   /* Largest allowed output value */
   8259   sqlite3_int64 iLimit = 0;             /* if >0, the value of the LIMIT */
   8260   sqlite3_int64 iOffset = 0;            /* if >0, the value of the OFFSET */
   8261 
   8262   (void)idxStrUnused;
   8263 
   8264   /* If any constraints have a NULL value, then return no rows.
   8265   ** See ticket https://sqlite.org/src/info/fac496b61722daf2
   8266   */
   8267   for(i=0; i<argc; i++){
   8268     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
   8269       goto series_no_rows;
   8270     }
   8271   }
   8272 
   8273   /* Capture the three HIDDEN parameters to the virtual table and insert
   8274   ** default values for any parameters that are omitted.
   8275   */
   8276   if( idxNum & 0x01 ){
   8277     pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
   8278   }else{
   8279     pCur->iOBase = 0;
   8280   }
   8281   if( idxNum & 0x02 ){
   8282     pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
   8283   }else{
   8284     pCur->iOTerm = 0xffffffff;
   8285   }
   8286   if( idxNum & 0x04 ){
   8287     pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
   8288     if( pCur->iOStep==0 ) pCur->iOStep = 1;
   8289   }else{
   8290     pCur->iOStep = 1;
   8291   }
   8292 
   8293   /* If there are constraints on the value column but there are
   8294   ** no constraints on  the start, stop, and step columns, then
   8295   ** initialize the default range to be the entire range of 64-bit signed
   8296   ** integers.  This range will contracted by the value column constraints
   8297   ** further below.
   8298   */
   8299   if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
   8300     pCur->iOBase = SMALLEST_INT64;
   8301   }
   8302   if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
   8303     pCur->iOTerm = LARGEST_INT64;
   8304   }
   8305   pCur->iBase = pCur->iOBase;
   8306   pCur->iTerm = pCur->iOTerm;
   8307   if( pCur->iOStep>0 ){
   8308     pCur->iStep = pCur->iOStep;
   8309   }else if( pCur->iOStep>SMALLEST_INT64 ){
   8310     pCur->iStep = -pCur->iOStep;
   8311   }else{
   8312     pCur->iStep = LARGEST_INT64;
   8313     pCur->iStep++;
   8314   }
   8315   pCur->bDesc = pCur->iOStep<0;
   8316   if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
   8317     goto series_no_rows;
   8318   }
   8319   if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
   8320     goto series_no_rows;
   8321   }
   8322 
   8323   /* Extract the LIMIT and OFFSET values, but do not apply them yet.
   8324   ** The range must first be constrained by the limits on value.
   8325   */
   8326   if( idxNum & 0x20 ){
   8327     iLimit = sqlite3_value_int64(argv[iArg++]);
   8328     if( idxNum & 0x40 ){
   8329       iOffset = sqlite3_value_int64(argv[iArg++]);
   8330     }
   8331   }
   8332 
   8333   /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
   8334   ** based on equality and inequality constraints on the "value" column.
   8335   */
   8336   if( idxNum & 0x3380 ){
   8337     if( idxNum & 0x0080 ){    /* value=X */
   8338       if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
   8339         double r = sqlite3_value_double(argv[iArg++]);
   8340         if( r==seriesCeil(r)
   8341          && r>=(double)SMALLEST_INT64
   8342          && r<=(double)LARGEST_INT64
   8343         ){
   8344           iMin = iMax = (sqlite3_int64)r;
   8345         }else{
   8346           goto series_no_rows;
   8347         }
   8348       }else{
   8349         iMin = iMax = sqlite3_value_int64(argv[iArg++]);
   8350       }
   8351     }else{
   8352       if( idxNum & 0x0300 ){  /* value>X or value>=X */
   8353         if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
   8354           double r = sqlite3_value_double(argv[iArg++]);
   8355           if( r<(double)SMALLEST_INT64 ){
   8356             iMin = SMALLEST_INT64;
   8357           }else if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
   8358             iMin = (sqlite3_int64)seriesCeil(r+1.0);
   8359           }else{
   8360             iMin = (sqlite3_int64)seriesCeil(r);
   8361           }
   8362         }else{
   8363           iMin = sqlite3_value_int64(argv[iArg++]);
   8364           if( (idxNum & 0x0200)!=0 ){
   8365             if( iMin==LARGEST_INT64 ){
   8366               goto series_no_rows;
   8367             }else{
   8368               iMin++;
   8369             }
   8370           }
   8371         }
   8372       }
   8373       if( idxNum & 0x3000 ){   /* value<X or value<=X */
   8374         if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
   8375           double r = sqlite3_value_double(argv[iArg++]);
   8376           if( r>(double)LARGEST_INT64 ){
   8377             iMax = LARGEST_INT64;
   8378           }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
   8379             iMax = (sqlite3_int64)(r-1.0);
   8380           }else{
   8381             iMax = (sqlite3_int64)seriesFloor(r);
   8382           }
   8383         }else{
   8384           iMax = sqlite3_value_int64(argv[iArg++]);
   8385           if( idxNum & 0x2000 ){
   8386             if( iMax==SMALLEST_INT64 ){
   8387               goto series_no_rows;
   8388             }else{
   8389               iMax--;
   8390             }
   8391           }
   8392         }
   8393       }
   8394       if( iMin>iMax ){
   8395         goto series_no_rows;
   8396       }
   8397     }
   8398 
   8399     /* Try to reduce the range of values to be generated based on
   8400     ** constraints on the "value" column.
   8401     */
   8402     if( pCur->bDesc==0 ){
   8403       if( pCur->iBase<iMin ){
   8404         sqlite3_uint64 span = span64(iMin,pCur->iBase);
   8405         pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
   8406         if( pCur->iBase<iMin ){
   8407           if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
   8408             goto series_no_rows;
   8409           }
   8410           pCur->iBase = add64(pCur->iBase, pCur->iStep);
   8411         }
   8412       }
   8413       if( pCur->iTerm>iMax ){
   8414         pCur->iTerm = iMax;
   8415       }
   8416     }else{
   8417       if( pCur->iBase>iMax ){
   8418         sqlite3_uint64 span = span64(pCur->iBase,iMax);
   8419         pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
   8420         if( pCur->iBase>iMax ){
   8421           if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
   8422             goto series_no_rows;
   8423           }
   8424           pCur->iBase = sub64(pCur->iBase, pCur->iStep);
   8425         }
   8426       }
   8427       if( pCur->iTerm<iMin ){
   8428         pCur->iTerm = iMin;
   8429       }
   8430     }
   8431   }
   8432 
   8433   /* Adjust iTerm so that it is exactly the last value of the series.
   8434   */
   8435   if( pCur->bDesc==0 ){
   8436     if( pCur->iBase>pCur->iTerm ){
   8437       goto series_no_rows;
   8438     }
   8439     pCur->iTerm = sub64(pCur->iTerm,
   8440                         span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
   8441   }else{
   8442     if( pCur->iBase<pCur->iTerm ){
   8443       goto series_no_rows;
   8444     }
   8445     pCur->iTerm = add64(pCur->iTerm,
   8446                         span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
   8447   }
   8448 
   8449   /* Transform the series generator to output values in the requested
   8450   ** order.
   8451   */
   8452   if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
   8453    || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
   8454   ){
   8455     sqlite3_int64 tmp = pCur->iBase;
   8456     pCur->iBase = pCur->iTerm;
   8457     pCur->iTerm = tmp;
   8458     pCur->bDesc = !pCur->bDesc;
   8459   }
   8460 
   8461   /* Apply LIMIT and OFFSET constraints, if any */
   8462   assert( pCur->iStep!=0 );
   8463   if( idxNum & 0x20 ){
   8464     if( iOffset>0 ){
   8465       if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
   8466         goto series_no_rows;
   8467       }else if( pCur->bDesc ){
   8468         pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
   8469       }else{
   8470         pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
   8471       }
   8472     }
   8473     if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
   8474       pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
   8475     }
   8476   }
   8477   pCur->iValue = pCur->iBase;
   8478   pCur->bDone = 0;
   8479   return SQLITE_OK;
   8480 
   8481 series_no_rows:
   8482   pCur->iBase = 0;
   8483   pCur->iTerm = 0;
   8484   pCur->iStep = 1;
   8485   pCur->bDesc = 0;
   8486   pCur->bDone = 1;
   8487   return SQLITE_OK;
   8488 }
   8489 
   8490 /*
   8491 ** SQLite will invoke this method one or more times while planning a query
   8492 ** that uses the generate_series virtual table.  This routine needs to create
   8493 ** a query plan for each invocation and compute an estimated cost for that
   8494 ** plan.
   8495 **
   8496 ** In this implementation idxNum is used to represent the
   8497 ** query plan.  idxStr is unused.
   8498 **
   8499 ** The query plan is represented by bits in idxNum:
   8500 **
   8501 **   0x0001  start = $num
   8502 **   0x0002  stop = $num
   8503 **   0x0004  step = $num
   8504 **   0x0008  output is in descending order
   8505 **   0x0010  output is in ascending order
   8506 **   0x0020  LIMIT $num
   8507 **   0x0040  OFFSET $num
   8508 **   0x0080  value = $num
   8509 **   0x0100  value >= $num
   8510 **   0x0200  value > $num
   8511 **   0x1000  value <= $num
   8512 **   0x2000  value < $num
   8513 **
   8514 ** Only one of 0x0100 or 0x0200 will be returned.  Similarly, only
   8515 ** one of 0x1000 or 0x2000 will be returned.  If the 0x0080 is set, then
   8516 ** none of the 0xff00 bits will be set.
   8517 **
   8518 ** The order of parameters passed to xFilter is as follows:
   8519 **
   8520 **    * The argument to start= if bit 0x0001 is in the idxNum mask
   8521 **    * The argument to stop= if bit 0x0002 is in the idxNum mask
   8522 **    * The argument to step= if bit 0x0004 is in the idxNum mask
   8523 **    * The argument to LIMIT if bit 0x0020 is in the idxNum mask
   8524 **    * The argument to OFFSET if bit 0x0040 is in the idxNum mask
   8525 **    * The argument to value=, or value>= or value> if any of
   8526 **      bits 0x0380 are in the idxNum mask
   8527 **    * The argument to value<= or value< if either of bits 0x3000
   8528 **      are in the mask
   8529 **
   8530 */
   8531 static int seriesBestIndex(
   8532   sqlite3_vtab *pVTab,
   8533   sqlite3_index_info *pIdxInfo
   8534 ){
   8535   int i, j;              /* Loop over constraints */
   8536   int idxNum = 0;        /* The query plan bitmask */
   8537 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
   8538   int bStartSeen = 0;    /* EQ constraint seen on the START column */
   8539 #endif
   8540   int unusableMask = 0;  /* Mask of unusable constraints */
   8541   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
   8542   int aIdx[7];           /* Constraints on start, stop, step, LIMIT, OFFSET,
   8543                          ** and value.  aIdx[5] covers value=, value>=, and
   8544                          ** value>,  aIdx[6] covers value<= and value< */
   8545   const struct sqlite3_index_constraint *pConstraint;
   8546 
   8547   /* This implementation assumes that the start, stop, and step columns
   8548   ** are the last three columns in the virtual table. */
   8549   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
   8550   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
   8551 
   8552   aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
   8553   pConstraint = pIdxInfo->aConstraint;
   8554   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   8555     int iCol;    /* 0 for start, 1 for stop, 2 for step */
   8556     int iMask;   /* bitmask for those column */
   8557     int op = pConstraint->op;
   8558     if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
   8559      && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
   8560     ){
   8561       if( pConstraint->usable==0 ){
   8562         /* do nothing */
   8563       }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
   8564         aIdx[3] = i;
   8565         idxNum |= 0x20;
   8566       }else{
   8567         assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
   8568         aIdx[4] = i;
   8569         idxNum |= 0x40;
   8570       }
   8571       continue;
   8572     }
   8573     if( pConstraint->iColumn<SERIES_COLUMN_START ){
   8574       if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
   8575            pConstraint->iColumn==SERIES_COLUMN_ROWID)
   8576        && pConstraint->usable
   8577       ){
   8578         switch( op ){
   8579           case SQLITE_INDEX_CONSTRAINT_EQ:
   8580           case SQLITE_INDEX_CONSTRAINT_IS: {
   8581             idxNum |=  0x0080;
   8582             idxNum &= ~0x3300;
   8583             aIdx[5] = i;
   8584             aIdx[6] = -1;
   8585 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
   8586             bStartSeen = 1;
   8587 #endif
   8588             break;
   8589           }
   8590           case SQLITE_INDEX_CONSTRAINT_GE: {
   8591             if( idxNum & 0x0080 ) break;
   8592             idxNum |=  0x0100;
   8593             idxNum &= ~0x0200;
   8594             aIdx[5] = i;
   8595 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
   8596             bStartSeen = 1;
   8597 #endif
   8598             break;
   8599           }
   8600           case SQLITE_INDEX_CONSTRAINT_GT: {
   8601             if( idxNum & 0x0080 ) break;
   8602             idxNum |=  0x0200;
   8603             idxNum &= ~0x0100;
   8604             aIdx[5] = i;
   8605 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
   8606             bStartSeen = 1;
   8607 #endif
   8608             break;
   8609           }
   8610           case SQLITE_INDEX_CONSTRAINT_LE: {
   8611             if( idxNum & 0x0080 ) break;
   8612             idxNum |=  0x1000;
   8613             idxNum &= ~0x2000;
   8614             aIdx[6] = i;
   8615             break;
   8616           }
   8617           case SQLITE_INDEX_CONSTRAINT_LT: {
   8618             if( idxNum & 0x0080 ) break;
   8619             idxNum |=  0x2000;
   8620             idxNum &= ~0x1000;
   8621             aIdx[6] = i;
   8622             break;
   8623           }
   8624         }
   8625       }
   8626       continue;
   8627     }
   8628     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
   8629     assert( iCol>=0 && iCol<=2 );
   8630     iMask = 1 << iCol;
   8631 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
   8632     if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
   8633       bStartSeen = 1;
   8634     }
   8635 #endif
   8636     if( pConstraint->usable==0 ){
   8637       unusableMask |=  iMask;
   8638       continue;
   8639     }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
   8640       idxNum |= iMask;
   8641       aIdx[iCol] = i;
   8642     }
   8643   }
   8644   if( aIdx[3]==0 ){
   8645     /* Ignore OFFSET if LIMIT is omitted */
   8646     idxNum &= ~0x60;
   8647     aIdx[4] = 0;
   8648   }
   8649   for(i=0; i<7; i++){
   8650     if( (j = aIdx[i])>=0 ){
   8651       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
   8652       pIdxInfo->aConstraintUsage[j].omit =
   8653          !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
   8654     }
   8655   }
   8656   /* The current generate_column() implementation requires at least one
   8657   ** argument (the START value).  Legacy versions assumed START=0 if the
   8658   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
   8659   ** to obtain the legacy behavior */
   8660 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
   8661   if( !bStartSeen ){
   8662     sqlite3_free(pVTab->zErrMsg);
   8663     pVTab->zErrMsg = sqlite3_mprintf(
   8664         "first argument to \"generate_series()\" missing or unusable");
   8665     return SQLITE_ERROR;
   8666   }
   8667 #endif
   8668   if( (unusableMask & ~idxNum)!=0 ){
   8669     /* The start, stop, and step columns are inputs.  Therefore if there
   8670     ** are unusable constraints on any of start, stop, or step then
   8671     ** this plan is unusable */
   8672     return SQLITE_CONSTRAINT;
   8673   }
   8674   if( (idxNum & 0x03)==0x03 ){
   8675     /* Both start= and stop= boundaries are available.  This is the
   8676     ** the preferred case */
   8677     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
   8678     pIdxInfo->estimatedRows = 1000;
   8679     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
   8680       if( pIdxInfo->aOrderBy[0].desc ){
   8681         idxNum |= 0x08;
   8682       }else{
   8683         idxNum |= 0x10;
   8684       }
   8685       pIdxInfo->orderByConsumed = 1;
   8686     }
   8687   }else if( (idxNum & 0x21)==0x21 ){
   8688     /* We have start= and LIMIT */
   8689     pIdxInfo->estimatedRows = 2500;
   8690   }else{
   8691     /* If either boundary is missing, we have to generate a huge span
   8692     ** of numbers.  Make this case very expensive so that the query
   8693     ** planner will work hard to avoid it. */
   8694     pIdxInfo->estimatedRows = 2147483647;
   8695   }
   8696   pIdxInfo->idxNum = idxNum;
   8697 #ifdef SQLITE_INDEX_SCAN_HEX
   8698   pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
   8699 #endif
   8700   return SQLITE_OK;
   8701 }
   8702 
   8703 /*
   8704 ** This following structure defines all the methods for the
   8705 ** generate_series virtual table.
   8706 */
   8707 static sqlite3_module seriesModule = {
   8708   0,                         /* iVersion */
   8709   0,                         /* xCreate */
   8710   seriesConnect,             /* xConnect */
   8711   seriesBestIndex,           /* xBestIndex */
   8712   seriesDisconnect,          /* xDisconnect */
   8713   0,                         /* xDestroy */
   8714   seriesOpen,                /* xOpen - open a cursor */
   8715   seriesClose,               /* xClose - close a cursor */
   8716   seriesFilter,              /* xFilter - configure scan constraints */
   8717   seriesNext,                /* xNext - advance a cursor */
   8718   seriesEof,                 /* xEof - check for end of scan */
   8719   seriesColumn,              /* xColumn - read data */
   8720   seriesRowid,               /* xRowid - read data */
   8721   0,                         /* xUpdate */
   8722   0,                         /* xBegin */
   8723   0,                         /* xSync */
   8724   0,                         /* xCommit */
   8725   0,                         /* xRollback */
   8726   0,                         /* xFindMethod */
   8727   0,                         /* xRename */
   8728   0,                         /* xSavepoint */
   8729   0,                         /* xRelease */
   8730   0,                         /* xRollbackTo */
   8731   0,                         /* xShadowName */
   8732   0                          /* xIntegrity */
   8733 };
   8734 
   8735 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   8736 
   8737 #ifdef _WIN32
   8738 
   8739 #endif
   8740 static int sqlite3_series_init(
   8741   sqlite3 *db,
   8742   char **pzErrMsg,
   8743   const sqlite3_api_routines *pApi
   8744 ){
   8745   int rc = SQLITE_OK;
   8746   SQLITE_EXTENSION_INIT2(pApi);
   8747 #ifndef SQLITE_OMIT_VIRTUALTABLE
   8748   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
   8749     *pzErrMsg = sqlite3_mprintf(
   8750         "generate_series() requires SQLite 3.8.12 or later");
   8751     return SQLITE_ERROR;
   8752   }
   8753   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
   8754 #endif
   8755   return rc;
   8756 }
   8757 
   8758 /************************* End ext/misc/series.c ********************/
   8759 /************************* Begin ext/misc/regexp.c ******************/
   8760 /*
   8761 ** 2012-11-13
   8762 **
   8763 ** The author disclaims copyright to this source code.  In place of
   8764 ** a legal notice, here is a blessing:
   8765 **
   8766 **    May you do good and not evil.
   8767 **    May you find forgiveness for yourself and forgive others.
   8768 **    May you share freely, never taking more than you give.
   8769 **
   8770 ******************************************************************************
   8771 **
   8772 ** The code in this file implements a compact but reasonably
   8773 ** efficient regular-expression matcher for posix extended regular
   8774 ** expressions against UTF8 text.
   8775 **
   8776 ** This file is an SQLite extension.  It registers a single function
   8777 ** named "regexp(A,B)" where A is the regular expression and B is the
   8778 ** string to be matched.  By registering this function, SQLite will also
   8779 ** then implement the "B regexp A" operator.  Note that with the function
   8780 ** the regular expression comes first, but with the operator it comes
   8781 ** second.
   8782 **
   8783 **  The following regular expression syntax is supported:
   8784 **
   8785 **     X*      zero or more occurrences of X
   8786 **     X+      one or more occurrences of X
   8787 **     X?      zero or one occurrences of X
   8788 **     X{p,q}  between p and q occurrences of X
   8789 **     (X)     match X
   8790 **     X|Y     X or Y
   8791 **     ^X      X occurring at the beginning of the string
   8792 **     X$      X occurring at the end of the string
   8793 **     .       Match any single character
   8794 **     \c      Character c where c is one of \{}()[]|*+?-.
   8795 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
   8796 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
   8797 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
   8798 **     [abc]   Any single character from the set abc
   8799 **     [^abc]  Any single character not in the set abc
   8800 **     [a-z]   Any single character in the range a-z
   8801 **     [^a-z]  Any single character not in the range a-z
   8802 **     \b      Word boundary
   8803 **     \w      Word character.  [A-Za-z0-9_]
   8804 **     \W      Non-word character
   8805 **     \d      Digit
   8806 **     \D      Non-digit
   8807 **     \s      Whitespace character
   8808 **     \S      Non-whitespace character
   8809 **
   8810 ** A nondeterministic finite automaton (NFA) is used for matching, so the
   8811 ** performance is bounded by O(N*M) where N is the size of the regular
   8812 ** expression and M is the size of the input string.  The matcher never
   8813 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
   8814 ** to p copies of X following by q-p copies of X? and that the size of the
   8815 ** regular expression in the O(N*M) performance bound is computed after
   8816 ** this expansion.
   8817 **
   8818 ** To help prevent DoS attacks, the maximum size of the NFA is restricted.
   8819 */
   8820 #include <string.h>
   8821 #include <stdlib.h>
   8822 /* #include "sqlite3ext.h" */
   8823 SQLITE_EXTENSION_INIT1
   8824 
   8825 /*
   8826 ** The following #defines change the names of some functions implemented in
   8827 ** this file to prevent name collisions with C-library functions of the
   8828 ** same name.
   8829 */
   8830 #define re_match   sqlite3re_match
   8831 #define re_compile sqlite3re_compile
   8832 #define re_free    sqlite3re_free
   8833 
   8834 /* The end-of-input character */
   8835 #define RE_EOF            0    /* End of input */
   8836 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
   8837 
   8838 /* The NFA is implemented as sequence of opcodes taken from the following
   8839 ** set.  Each opcode has a single integer argument.
   8840 */
   8841 #define RE_OP_MATCH       1    /* Match the one character in the argument */
   8842 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
   8843 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
   8844 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
   8845 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
   8846 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
   8847 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
   8848 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
   8849 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
   8850 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
   8851 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
   8852 #define RE_OP_NOTWORD    12    /* Not a perl word character */
   8853 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
   8854 #define RE_OP_NOTDIGIT   14    /* Not a digit */
   8855 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
   8856 #define RE_OP_NOTSPACE   16    /* Not a digit */
   8857 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
   8858 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
   8859 
   8860 /* Each opcode is a "state" in the NFA */
   8861 typedef unsigned short ReStateNumber;
   8862 
   8863 /* Because this is an NFA and not a DFA, multiple states can be active at
   8864 ** once.  An instance of the following object records all active states in
   8865 ** the NFA.  The implementation is optimized for the common case where the
   8866 ** number of actives states is small.
   8867 */
   8868 typedef struct ReStateSet {
   8869   unsigned nState;            /* Number of current states */
   8870   ReStateNumber *aState;      /* Current states */
   8871 } ReStateSet;
   8872 
   8873 /* An input string read one character at a time.
   8874 */
   8875 typedef struct ReInput ReInput;
   8876 struct ReInput {
   8877   const unsigned char *z;  /* All text */
   8878   int i;                   /* Next byte to read */
   8879   int mx;                  /* EOF when i>=mx */
   8880 };
   8881 
   8882 /* A compiled NFA (or an NFA that is in the process of being compiled) is
   8883 ** an instance of the following object.
   8884 */
   8885 typedef struct ReCompiled ReCompiled;
   8886 struct ReCompiled {
   8887   ReInput sIn;                /* Regular expression text */
   8888   const char *zErr;           /* Error message to return */
   8889   char *aOp;                  /* Operators for the virtual machine */
   8890   int *aArg;                  /* Arguments to each operator */
   8891   unsigned (*xNextChar)(ReInput*);  /* Next character function */
   8892   unsigned char zInit[12];    /* Initial text to match */
   8893   int nInit;                  /* Number of bytes in zInit */
   8894   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
   8895   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
   8896   unsigned mxAlloc;           /* Complexity limit */
   8897 };
   8898 
   8899 /* Add a state to the given state set if it is not already there */
   8900 static void re_add_state(ReStateSet *pSet, int newState){
   8901   unsigned i;
   8902   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
   8903   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
   8904 }
   8905 
   8906 /* Extract the next unicode character from *pzIn and return it.  Advance
   8907 ** *pzIn to the first byte past the end of the character returned.  To
   8908 ** be clear:  this routine converts utf8 to unicode.  This routine is
   8909 ** optimized for the common case where the next character is a single byte.
   8910 */
   8911 static unsigned re_next_char(ReInput *p){
   8912   unsigned c;
   8913   if( p->i>=p->mx ) return 0;
   8914   c = p->z[p->i++];
   8915   if( c>=0x80 ){
   8916     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
   8917       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
   8918       if( c<0x80 ) c = 0xfffd;
   8919     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
   8920            && (p->z[p->i+1]&0xc0)==0x80 ){
   8921       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
   8922       p->i += 2;
   8923       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
   8924     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
   8925            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
   8926       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
   8927                        | (p->z[p->i+2]&0x3f);
   8928       p->i += 3;
   8929       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
   8930     }else{
   8931       c = 0xfffd;
   8932     }
   8933   }
   8934   return c;
   8935 }
   8936 static unsigned re_next_char_nocase(ReInput *p){
   8937   unsigned c = re_next_char(p);
   8938   if( c>='A' && c<='Z' ) c += 'a' - 'A';
   8939   return c;
   8940 }
   8941 
   8942 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
   8943 static int re_word_char(int c){
   8944   return (c>='0' && c<='9') || (c>='a' && c<='z')
   8945       || (c>='A' && c<='Z') || c=='_';
   8946 }
   8947 
   8948 /* Return true if c is a "digit" character:  [0-9] */
   8949 static int re_digit_char(int c){
   8950   return (c>='0' && c<='9');
   8951 }
   8952 
   8953 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
   8954 static int re_space_char(int c){
   8955   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   8956 }
   8957 
   8958 /* Run a compiled regular expression on the zero-terminated input
   8959 ** string zIn[].  Return true on a match and false if there is no match.
   8960 */
   8961 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
   8962   ReStateSet aStateSet[2], *pThis, *pNext;
   8963   ReStateNumber aSpace[100];
   8964   ReStateNumber *pToFree;
   8965   unsigned int i = 0;
   8966   unsigned int iSwap = 0;
   8967   int c = RE_START;
   8968   int cPrev = 0;
   8969   int rc = 0;
   8970   ReInput in;
   8971 
   8972   in.z = zIn;
   8973   in.i = 0;
   8974   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
   8975 
   8976   /* Look for the initial prefix match, if there is one. */
   8977   if( pRe->nInit ){
   8978     unsigned char x = pRe->zInit[0];
   8979     while( in.i+pRe->nInit<=in.mx
   8980      && (zIn[in.i]!=x ||
   8981          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
   8982     ){
   8983       in.i++;
   8984     }
   8985     if( in.i+pRe->nInit>in.mx ) return 0;
   8986     c = RE_START-1;
   8987   }
   8988 
   8989   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
   8990     pToFree = 0;
   8991     aStateSet[0].aState = aSpace;
   8992   }else{
   8993     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
   8994     if( pToFree==0 ) return -1;
   8995     aStateSet[0].aState = pToFree;
   8996   }
   8997   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
   8998   pNext = &aStateSet[1];
   8999   pNext->nState = 0;
   9000   re_add_state(pNext, 0);
   9001   while( c!=RE_EOF && pNext->nState>0 ){
   9002     cPrev = c;
   9003     c = pRe->xNextChar(&in);
   9004     pThis = pNext;
   9005     pNext = &aStateSet[iSwap];
   9006     iSwap = 1 - iSwap;
   9007     pNext->nState = 0;
   9008     for(i=0; i<pThis->nState; i++){
   9009       int x = pThis->aState[i];
   9010       switch( pRe->aOp[x] ){
   9011         case RE_OP_MATCH: {
   9012           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
   9013           break;
   9014         }
   9015         case RE_OP_ATSTART: {
   9016           if( cPrev==RE_START ) re_add_state(pThis, x+1);
   9017           break;
   9018         }
   9019         case RE_OP_ANY: {
   9020           if( c!=0 ) re_add_state(pNext, x+1);
   9021           break;
   9022         }
   9023         case RE_OP_WORD: {
   9024           if( re_word_char(c) ) re_add_state(pNext, x+1);
   9025           break;
   9026         }
   9027         case RE_OP_NOTWORD: {
   9028           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
   9029           break;
   9030         }
   9031         case RE_OP_DIGIT: {
   9032           if( re_digit_char(c) ) re_add_state(pNext, x+1);
   9033           break;
   9034         }
   9035         case RE_OP_NOTDIGIT: {
   9036           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
   9037           break;
   9038         }
   9039         case RE_OP_SPACE: {
   9040           if( re_space_char(c) ) re_add_state(pNext, x+1);
   9041           break;
   9042         }
   9043         case RE_OP_NOTSPACE: {
   9044           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
   9045           break;
   9046         }
   9047         case RE_OP_BOUNDARY: {
   9048           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
   9049           break;
   9050         }
   9051         case RE_OP_ANYSTAR: {
   9052           re_add_state(pNext, x);
   9053           re_add_state(pThis, x+1);
   9054           break;
   9055         }
   9056         case RE_OP_FORK: {
   9057           re_add_state(pThis, x+pRe->aArg[x]);
   9058           re_add_state(pThis, x+1);
   9059           break;
   9060         }
   9061         case RE_OP_GOTO: {
   9062           re_add_state(pThis, x+pRe->aArg[x]);
   9063           break;
   9064         }
   9065         case RE_OP_ACCEPT: {
   9066           rc = 1;
   9067           goto re_match_end;
   9068         }
   9069         case RE_OP_CC_EXC: {
   9070           if( c==0 ) break;
   9071           /* fall-through */ goto re_op_cc_inc;
   9072         }
   9073         case RE_OP_CC_INC: re_op_cc_inc: {
   9074           int j = 1;
   9075           int n = pRe->aArg[x];
   9076           int hit = 0;
   9077           for(j=1; j>0 && j<n; j++){
   9078             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
   9079               if( pRe->aArg[x+j]==c ){
   9080                 hit = 1;
   9081                 j = -1;
   9082               }
   9083             }else{
   9084               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
   9085                 hit = 1;
   9086                 j = -1;
   9087               }else{
   9088                 j++;
   9089               }
   9090             }
   9091           }
   9092           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
   9093           if( hit ) re_add_state(pNext, x+n);
   9094           break;
   9095         }
   9096       }
   9097     }
   9098   }
   9099   for(i=0; i<pNext->nState; i++){
   9100     int x = pNext->aState[i];
   9101     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
   9102     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
   9103   }
   9104 re_match_end:
   9105   sqlite3_free(pToFree);
   9106   return rc;
   9107 }
   9108 
   9109 /* Resize the opcode and argument arrays for an RE under construction.
   9110 */
   9111 static int re_resize(ReCompiled *p, unsigned int N){
   9112   char *aOp;
   9113   int *aArg;
   9114   if( N>p->mxAlloc ){ p->zErr = "REGEXP pattern too big"; return 1; }
   9115   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
   9116   if( aOp==0 ){ p->zErr = "out of memory"; return 1; }
   9117   p->aOp = aOp;
   9118   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
   9119   if( aArg==0 ){ p->zErr = "out of memory"; return 1; }
   9120   p->aArg = aArg;
   9121   p->nAlloc = N;
   9122   return 0;
   9123 }
   9124 
   9125 /* Insert a new opcode and argument into an RE under construction.  The
   9126 ** insertion point is just prior to existing opcode iBefore.
   9127 */
   9128 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
   9129   int i;
   9130   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
   9131   for(i=p->nState; i>iBefore; i--){
   9132     p->aOp[i] = p->aOp[i-1];
   9133     p->aArg[i] = p->aArg[i-1];
   9134   }
   9135   p->nState++;
   9136   p->aOp[iBefore] = (char)op;
   9137   p->aArg[iBefore] = arg;
   9138   return iBefore;
   9139 }
   9140 
   9141 /* Append a new opcode and argument to the end of the RE under construction.
   9142 */
   9143 static int re_append(ReCompiled *p, int op, int arg){
   9144   return re_insert(p, p->nState, op, arg);
   9145 }
   9146 
   9147 /* Make a copy of N opcodes starting at iStart onto the end of the RE
   9148 ** under construction.
   9149 */
   9150 static void re_copy(ReCompiled *p, int iStart, unsigned int N){
   9151   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
   9152   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
   9153   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
   9154   p->nState += N;
   9155 }
   9156 
   9157 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
   9158 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
   9159 ** c is not a hex digit *pV is unchanged.
   9160 */
   9161 static int re_hex(int c, int *pV){
   9162   if( c>='0' && c<='9' ){
   9163     c -= '0';
   9164   }else if( c>='a' && c<='f' ){
   9165     c -= 'a' - 10;
   9166   }else if( c>='A' && c<='F' ){
   9167     c -= 'A' - 10;
   9168   }else{
   9169     return 0;
   9170   }
   9171   *pV = (*pV)*16 + (c & 0xff);
   9172   return 1;
   9173 }
   9174 
   9175 /* A backslash character has been seen, read the next character and
   9176 ** return its interpretation.
   9177 */
   9178 static unsigned re_esc_char(ReCompiled *p){
   9179   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]-";
   9180   static const char zTrans[] = "\a\f\n\r\t\v";
   9181   int i, v = 0;
   9182   char c;
   9183   if( p->sIn.i>=p->sIn.mx ) return 0;
   9184   c = p->sIn.z[p->sIn.i];
   9185   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
   9186     const unsigned char *zIn = p->sIn.z + p->sIn.i;
   9187     if( re_hex(zIn[1],&v)
   9188      && re_hex(zIn[2],&v)
   9189      && re_hex(zIn[3],&v)
   9190      && re_hex(zIn[4],&v)
   9191     ){
   9192       p->sIn.i += 5;
   9193       return v;
   9194     }
   9195   }
   9196   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
   9197     const unsigned char *zIn = p->sIn.z + p->sIn.i;
   9198     if( re_hex(zIn[1],&v)
   9199      && re_hex(zIn[2],&v)
   9200     ){
   9201       p->sIn.i += 3;
   9202       return v;
   9203     }
   9204   }
   9205   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
   9206   if( zEsc[i] ){
   9207     if( i<6 ) c = zTrans[i];
   9208     p->sIn.i++;
   9209   }else{
   9210     p->zErr = "unknown \\ escape";
   9211   }
   9212   return c;
   9213 }
   9214 
   9215 /* Forward declaration */
   9216 static const char *re_subcompile_string(ReCompiled*);
   9217 
   9218 /* Peek at the next byte of input */
   9219 static unsigned char rePeek(ReCompiled *p){
   9220   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
   9221 }
   9222 
   9223 /* Compile RE text into a sequence of opcodes.  Continue up to the
   9224 ** first unmatched ")" character, then return.  If an error is found,
   9225 ** return a pointer to the error message string.
   9226 */
   9227 static const char *re_subcompile_re(ReCompiled *p){
   9228   const char *zErr;
   9229   int iStart, iEnd, iGoto;
   9230   iStart = p->nState;
   9231   zErr = re_subcompile_string(p);
   9232   if( zErr ) return zErr;
   9233   while( rePeek(p)=='|' ){
   9234     iEnd = p->nState;
   9235     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
   9236     iGoto = re_append(p, RE_OP_GOTO, 0);
   9237     p->sIn.i++;
   9238     zErr = re_subcompile_string(p);
   9239     if( zErr ) return zErr;
   9240     p->aArg[iGoto] = p->nState - iGoto;
   9241   }
   9242   return 0;
   9243 }
   9244 
   9245 /* Compile an element of regular expression text (anything that can be
   9246 ** an operand to the "|" operator).  Return NULL on success or a pointer
   9247 ** to the error message if there is a problem.
   9248 */
   9249 static const char *re_subcompile_string(ReCompiled *p){
   9250   int iPrev = -1;
   9251   int iStart;
   9252   unsigned c;
   9253   const char *zErr;
   9254   while( (c = p->xNextChar(&p->sIn))!=0 ){
   9255     iStart = p->nState;
   9256     switch( c ){
   9257       case '|':
   9258       case ')': {
   9259         p->sIn.i--;
   9260         return 0;
   9261       }
   9262       case '(': {
   9263         zErr = re_subcompile_re(p);
   9264         if( zErr ) return zErr;
   9265         if( rePeek(p)!=')' ) return "unmatched '('";
   9266         p->sIn.i++;
   9267         break;
   9268       }
   9269       case '.': {
   9270         if( rePeek(p)=='*' ){
   9271           re_append(p, RE_OP_ANYSTAR, 0);
   9272           p->sIn.i++;
   9273         }else{
   9274           re_append(p, RE_OP_ANY, 0);
   9275         }
   9276         break;
   9277       }
   9278       case '*': {
   9279         if( iPrev<0 ) return "'*' without operand";
   9280         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
   9281         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
   9282         break;
   9283       }
   9284       case '+': {
   9285         if( iPrev<0 ) return "'+' without operand";
   9286         re_append(p, RE_OP_FORK, iPrev - p->nState);
   9287         break;
   9288       }
   9289       case '?': {
   9290         if( iPrev<0 ) return "'?' without operand";
   9291         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
   9292         break;
   9293       }
   9294       case '$': {
   9295         re_append(p, RE_OP_MATCH, RE_EOF);
   9296         break;
   9297       }
   9298       case '^': {
   9299         re_append(p, RE_OP_ATSTART, 0);
   9300         break;
   9301       }
   9302       case '{': {
   9303         unsigned int m = 0, n = 0;
   9304         unsigned int sz, j;
   9305         if( iPrev<0 ) return "'{m,n}' without operand";
   9306         while( (c=rePeek(p))>='0' && c<='9' ){
   9307           m = m*10 + c - '0';
   9308           if( m*2>p->mxAlloc ) return "REGEXP pattern too big";
   9309           p->sIn.i++;
   9310         }
   9311         n = m;
   9312         if( c==',' ){
   9313           p->sIn.i++;
   9314           n = 0;
   9315           while( (c=rePeek(p))>='0' && c<='9' ){
   9316             n = n*10 + c-'0';
   9317             if( n*2>p->mxAlloc ) return "REGEXP pattern too big";
   9318             p->sIn.i++;
   9319           }
   9320         }
   9321         if( c!='}' ) return "unmatched '{'";
   9322         if( n<m ) return "n less than m in '{m,n}'";
   9323         p->sIn.i++;
   9324         sz = p->nState - iPrev;
   9325         if( m==0 ){
   9326           if( n==0 ) return "both m and n are zero in '{m,n}'";
   9327           re_insert(p, iPrev, RE_OP_FORK, sz+1);
   9328           iPrev++;
   9329           n--;
   9330         }else{
   9331           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
   9332         }
   9333         for(j=m; j<n; j++){
   9334           re_append(p, RE_OP_FORK, sz+1);
   9335           re_copy(p, iPrev, sz);
   9336         }
   9337         if( n==0 && m>0 ){
   9338           re_append(p, RE_OP_FORK, -(int)sz);
   9339         }
   9340         break;
   9341       }
   9342       case '[': {
   9343         unsigned int iFirst = p->nState;
   9344         if( rePeek(p)=='^' ){
   9345           re_append(p, RE_OP_CC_EXC, 0);
   9346           p->sIn.i++;
   9347         }else{
   9348           re_append(p, RE_OP_CC_INC, 0);
   9349         }
   9350         while( (c = p->xNextChar(&p->sIn))!=0 ){
   9351           if( c=='[' && rePeek(p)==':' ){
   9352             return "POSIX character classes not supported";
   9353           }
   9354           if( c=='\\' ) c = re_esc_char(p);
   9355           if( rePeek(p)=='-' ){
   9356             re_append(p, RE_OP_CC_RANGE, c);
   9357             p->sIn.i++;
   9358             c = p->xNextChar(&p->sIn);
   9359             if( c=='\\' ) c = re_esc_char(p);
   9360             re_append(p, RE_OP_CC_RANGE, c);
   9361           }else{
   9362             re_append(p, RE_OP_CC_VALUE, c);
   9363           }
   9364           if( rePeek(p)==']' ){ p->sIn.i++; break; }
   9365         }
   9366         if( c==0 ) return "unclosed '['";
   9367         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
   9368         break;
   9369       }
   9370       case '\\': {
   9371         int specialOp = 0;
   9372         switch( rePeek(p) ){
   9373           case 'b': specialOp = RE_OP_BOUNDARY;   break;
   9374           case 'd': specialOp = RE_OP_DIGIT;      break;
   9375           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
   9376           case 's': specialOp = RE_OP_SPACE;      break;
   9377           case 'S': specialOp = RE_OP_NOTSPACE;   break;
   9378           case 'w': specialOp = RE_OP_WORD;       break;
   9379           case 'W': specialOp = RE_OP_NOTWORD;    break;
   9380         }
   9381         if( specialOp ){
   9382           p->sIn.i++;
   9383           re_append(p, specialOp, 0);
   9384         }else{
   9385           c = re_esc_char(p);
   9386           re_append(p, RE_OP_MATCH, c);
   9387         }
   9388         break;
   9389       }
   9390       default: {
   9391         re_append(p, RE_OP_MATCH, c);
   9392         break;
   9393       }
   9394     }
   9395     iPrev = iStart;
   9396   }
   9397   return 0;
   9398 }
   9399 
   9400 /* Free and reclaim all the memory used by a previously compiled
   9401 ** regular expression.  Applications should invoke this routine once
   9402 ** for every call to re_compile() to avoid memory leaks.
   9403 */
   9404 static void re_free(ReCompiled *pRe){
   9405   if( pRe ){
   9406     sqlite3_free(pRe->aOp);
   9407     sqlite3_free(pRe->aArg);
   9408     sqlite3_free(pRe);
   9409   }
   9410 }
   9411 
   9412 /*
   9413 ** Version of re_free() that accepts a pointer of type (void*). Required
   9414 ** to satisfy sanitizers when the re_free() function is called via a
   9415 ** function pointer.
   9416 */
   9417 static void re_free_voidptr(void *p){
   9418   re_free((ReCompiled*)p);
   9419 }
   9420 
   9421 /*
   9422 ** Compile a textual regular expression in zIn[] into a compiled regular
   9423 ** expression suitable for us by re_match() and return a pointer to the
   9424 ** compiled regular expression in *ppRe.  Return NULL on success or an
   9425 ** error message if something goes wrong.
   9426 */
   9427 static const char *re_compile(
   9428   ReCompiled **ppRe,      /* OUT: write compiled NFA here */
   9429   const char *zIn,        /* Input regular expression */
   9430   int mxRe,               /* Complexity limit */
   9431   int noCase              /* True for caseless comparisons */
   9432 ){
   9433   ReCompiled *pRe;
   9434   const char *zErr;
   9435   int i, j;
   9436 
   9437   *ppRe = 0;
   9438   pRe = sqlite3_malloc64( sizeof(*pRe) );
   9439   if( pRe==0 ){
   9440     return "out of memory";
   9441   }
   9442   memset(pRe, 0, sizeof(*pRe));
   9443   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
   9444   pRe->mxAlloc = mxRe;
   9445   if( re_resize(pRe, 30) ){
   9446     zErr = pRe->zErr;
   9447     re_free(pRe);
   9448     return zErr;
   9449   }
   9450   if( zIn[0]=='^' ){
   9451     zIn++;
   9452   }else{
   9453     re_append(pRe, RE_OP_ANYSTAR, 0);
   9454   }
   9455   pRe->sIn.z = (unsigned char*)zIn;
   9456   pRe->sIn.i = 0;
   9457   pRe->sIn.mx = (int)strlen(zIn);
   9458   zErr = re_subcompile_re(pRe);
   9459   if( zErr ){
   9460     re_free(pRe);
   9461     return zErr;
   9462   }
   9463   if( pRe->sIn.i>=pRe->sIn.mx ){
   9464     re_append(pRe, RE_OP_ACCEPT, 0);
   9465     *ppRe = pRe;
   9466   }else{
   9467     re_free(pRe);
   9468     return "unrecognized character";
   9469   }
   9470 
   9471   /* The following is a performance optimization.  If the regex begins with
   9472   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
   9473   ** one or more matching characters, enter those matching characters into
   9474   ** zInit[].  The re_match() routine can then search ahead in the input
   9475   ** string looking for the initial match without having to run the whole
   9476   ** regex engine over the string.  Do not worry about trying to match
   9477   ** unicode characters beyond plane 0 - those are very rare and this is
   9478   ** just an optimization. */
   9479   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
   9480     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
   9481       unsigned x = pRe->aArg[i];
   9482       if( x<=0x7f ){
   9483         pRe->zInit[j++] = (unsigned char)x;
   9484       }else if( x<=0x7ff ){
   9485         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
   9486         pRe->zInit[j++] = 0x80 | (x&0x3f);
   9487       }else if( x<=0xffff ){
   9488         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
   9489         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
   9490         pRe->zInit[j++] = 0x80 | (x&0x3f);
   9491       }else{
   9492         break;
   9493       }
   9494     }
   9495     if( j>0 && pRe->zInit[j-1]==0 ) j--;
   9496     pRe->nInit = j;
   9497   }
   9498   return pRe->zErr;
   9499 }
   9500 
   9501 /*
   9502 ** The value of LIMIT_MAX_PATTERN_LENGTH.
   9503 */
   9504 static int re_maxlen(sqlite3_context *context){
   9505   sqlite3 *db = sqlite3_context_db_handle(context);
   9506   return sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH,-1);
   9507 }
   9508 
   9509 /*
   9510 ** Maximum NFA size given a maximum pattern length.
   9511 */
   9512 static int re_maxnfa(int mxlen){
   9513   return 75+mxlen/2;
   9514 }
   9515 
   9516 /*
   9517 ** Implementation of the regexp() SQL function.  This function implements
   9518 ** the build-in REGEXP operator.  The first argument to the function is the
   9519 ** pattern and the second argument is the string.  So, the SQL statements:
   9520 **
   9521 **       A REGEXP B
   9522 **
   9523 ** is implemented as regexp(B,A).
   9524 */
   9525 static void re_sql_func(
   9526   sqlite3_context *context,
   9527   int argc,
   9528   sqlite3_value **argv
   9529 ){
   9530   ReCompiled *pRe;          /* Compiled regular expression */
   9531   const char *zPattern;     /* The regular expression */
   9532   const unsigned char *zStr;/* String being searched */
   9533   const char *zErr;         /* Compile error message */
   9534   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
   9535 
   9536   (void)argc;  /* Unused */
   9537   pRe = sqlite3_get_auxdata(context, 0);
   9538   if( pRe==0 ){
   9539     int mxLen = re_maxlen(context);
   9540     int nPattern;
   9541     zPattern = (const char*)sqlite3_value_text(argv[0]);
   9542     if( zPattern==0 ) return;
   9543     nPattern = sqlite3_value_bytes(argv[0]);
   9544     if( nPattern>mxLen ){
   9545       zErr = "REGEXP pattern too big";
   9546     }else{
   9547       zErr = re_compile(&pRe, zPattern, re_maxnfa(mxLen),
   9548                         sqlite3_user_data(context)!=0);
   9549     }
   9550     if( zErr ){
   9551       re_free(pRe);
   9552       sqlite3_result_error(context, zErr, -1);
   9553       return;
   9554     }
   9555     if( pRe==0 ){
   9556       sqlite3_result_error_nomem(context);
   9557       return;
   9558     }
   9559     setAux = 1;
   9560   }
   9561   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
   9562   if( zStr!=0 ){
   9563     sqlite3_result_int(context, re_match(pRe, zStr, -1));
   9564   }
   9565   if( setAux ){
   9566     sqlite3_set_auxdata(context, 0, pRe, re_free_voidptr);
   9567   }
   9568 }
   9569 
   9570 #if defined(SQLITE_DEBUG)
   9571 /*
   9572 ** This function is used for testing and debugging only.  It is only available
   9573 ** if the SQLITE_DEBUG compile-time option is used.
   9574 **
   9575 ** Compile a regular expression and then convert the compiled expression into
   9576 ** text and return that text.
   9577 */
   9578 static void re_bytecode_func(
   9579   sqlite3_context *context,
   9580   int argc,
   9581   sqlite3_value **argv
   9582 ){
   9583   const char *zPattern;
   9584   const char *zErr;
   9585   ReCompiled *pRe;
   9586   sqlite3_str *pStr;
   9587   int i;
   9588   int n;
   9589   char *z;
   9590   static const char *ReOpName[] = {
   9591     "EOF",
   9592     "MATCH",
   9593     "ANY",
   9594     "ANYSTAR",
   9595     "FORK",
   9596     "GOTO",
   9597     "ACCEPT",
   9598     "CC_INC",
   9599     "CC_EXC",
   9600     "CC_VALUE",
   9601     "CC_RANGE",
   9602     "WORD",
   9603     "NOTWORD",
   9604     "DIGIT",
   9605     "NOTDIGIT",
   9606     "SPACE",
   9607     "NOTSPACE",
   9608     "BOUNDARY",
   9609     "ATSTART",
   9610   };
   9611 
   9612   (void)argc;
   9613   zPattern = (const char*)sqlite3_value_text(argv[0]);
   9614   if( zPattern==0 ) return;
   9615   zErr = re_compile(&pRe, zPattern, re_maxnfa(re_maxlen(context)),
   9616                     sqlite3_user_data(context)!=0);
   9617   if( zErr ){
   9618     re_free(pRe);
   9619     sqlite3_result_error(context, zErr, -1);
   9620     return;
   9621   }
   9622   if( pRe==0 ){
   9623     sqlite3_result_error_nomem(context);
   9624     return;
   9625   }
   9626   pStr = sqlite3_str_new(0);
   9627   if( pStr==0 ) goto re_bytecode_func_err;
   9628   if( pRe->nInit>0 ){
   9629     sqlite3_str_appendf(pStr, "INIT     ");
   9630     for(i=0; i<pRe->nInit; i++){
   9631       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
   9632     }
   9633     sqlite3_str_appendf(pStr, "\n");
   9634   }
   9635   for(i=0; (unsigned)i<pRe->nState; i++){
   9636     sqlite3_str_appendf(pStr, "%-8s %4d\n",
   9637          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
   9638   }
   9639   n = sqlite3_str_length(pStr);
   9640   z = sqlite3_str_finish(pStr);
   9641   if( n==0 ){
   9642     sqlite3_free(z);
   9643   }else{
   9644     sqlite3_result_text(context, z, n-1, sqlite3_free);
   9645   }
   9646 
   9647 re_bytecode_func_err:
   9648   re_free(pRe);
   9649 }
   9650 
   9651 #endif /* SQLITE_DEBUG */
   9652 
   9653 
   9654 /*
   9655 ** Invoke this routine to register the regexp() function with the
   9656 ** SQLite database connection.
   9657 */
   9658 #ifdef _WIN32
   9659 
   9660 #endif
   9661 static int sqlite3_regexp_init(
   9662   sqlite3 *db,
   9663   char **pzErrMsg,
   9664   const sqlite3_api_routines *pApi
   9665 ){
   9666   int rc = SQLITE_OK;
   9667   SQLITE_EXTENSION_INIT2(pApi);
   9668   (void)pzErrMsg;  /* Unused */
   9669   rc = sqlite3_create_function(db, "regexp", 2,
   9670                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
   9671                             0, re_sql_func, 0, 0);
   9672   if( rc==SQLITE_OK ){
   9673     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
   9674     ** of regexp(PATTERN,STRING). */
   9675     rc = sqlite3_create_function(db, "regexpi", 2,
   9676                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
   9677                             (void*)db, re_sql_func, 0, 0);
   9678 #if defined(SQLITE_DEBUG)
   9679     if( rc==SQLITE_OK ){
   9680       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
   9681                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
   9682                             0, re_bytecode_func, 0, 0);
   9683     }
   9684 #endif /* SQLITE_DEBUG */
   9685   }
   9686   return rc;
   9687 }
   9688 
   9689 /************************* End ext/misc/regexp.c ********************/
   9690 #ifndef SQLITE_SHELL_FIDDLE
   9691 /************************* Begin ext/misc/fileio.c ******************/
   9692 /*
   9693 ** 2014-06-13
   9694 **
   9695 ** The author disclaims copyright to this source code.  In place of
   9696 ** a legal notice, here is a blessing:
   9697 **
   9698 **    May you do good and not evil.
   9699 **    May you find forgiveness for yourself and forgive others.
   9700 **    May you share freely, never taking more than you give.
   9701 **
   9702 ******************************************************************************
   9703 **
   9704 ** This SQLite extension implements SQL functions readfile() and
   9705 ** writefile(), and eponymous virtual type "fsdir".
   9706 **
   9707 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
   9708 **
   9709 **   If neither of the optional arguments is present, then this UDF
   9710 **   function writes blob DATA to file FILE. If successful, the number
   9711 **   of bytes written is returned. If an error occurs, NULL is returned.
   9712 **
   9713 **   If the first option argument - MODE - is present, then it must
   9714 **   be passed an integer value that corresponds to a POSIX mode
   9715 **   value (file type + permissions, as returned in the stat.st_mode
   9716 **   field by the stat() system call). Three types of files may
   9717 **   be written/created:
   9718 **
   9719 **     regular files:  (mode & 0170000)==0100000
   9720 **     symbolic links: (mode & 0170000)==0120000
   9721 **     directories:    (mode & 0170000)==0040000
   9722 **
   9723 **   For a directory, the DATA is ignored. For a symbolic link, it is
   9724 **   interpreted as text and used as the target of the link. For a
   9725 **   regular file, it is interpreted as a blob and written into the
   9726 **   named file. Regardless of the type of file, its permissions are
   9727 **   set to (mode & 0777) before returning.
   9728 **
   9729 **   If the optional MTIME argument is present, then it is interpreted
   9730 **   as an integer - the number of seconds since the unix epoch. The
   9731 **   modification-time of the target file is set to this value before
   9732 **   returning.
   9733 **
   9734 **   If five or more arguments are passed to this function and an
   9735 **   error is encountered, an exception is raised.
   9736 **
   9737 ** READFILE(FILE):
   9738 **
   9739 **   Read and return the contents of file FILE (type blob) from disk.
   9740 **
   9741 ** FSDIR:
   9742 **
   9743 **   Used as follows:
   9744 **
   9745 **     SELECT * FROM fsdir($path [, $dir]);
   9746 **
   9747 **   Parameter $path is an absolute or relative pathname. If the file that it
   9748 **   refers to does not exist, it is an error. If the path refers to a regular
   9749 **   file or symbolic link, it returns a single row. Or, if the path refers
   9750 **   to a directory, it returns one row for the directory, and one row for each
   9751 **   file within the hierarchy rooted at $path.
   9752 **
   9753 **   Each row has the following columns:
   9754 **
   9755 **     name:  Path to file or directory (text value).
   9756 **     mode:  Value of stat.st_mode for directory entry (an integer).
   9757 **     mtime: Value of stat.st_mtime for directory entry (an integer).
   9758 **     data:  For a regular file, a blob containing the file data. For a
   9759 **            symlink, a text value containing the text of the link. For a
   9760 **            directory, NULL.
   9761 **     level: Directory hierarchy level.  Topmost is 1.
   9762 **
   9763 **   If a non-NULL value is specified for the optional $dir parameter and
   9764 **   $path is a relative path, then $path is interpreted relative to $dir.
   9765 **   And the paths returned in the "name" column of the table are also
   9766 **   relative to directory $dir.
   9767 */
   9768 /* #include "sqlite3ext.h" */
   9769 SQLITE_EXTENSION_INIT1
   9770 #include <stdio.h>
   9771 #include <string.h>
   9772 #include <assert.h>
   9773 
   9774 #include <sys/types.h>
   9775 #include <sys/stat.h>
   9776 #include <fcntl.h>
   9777 #if !defined(_WIN32) && !defined(WIN32)
   9778 #  include <unistd.h>
   9779 #  include <dirent.h>
   9780 #  include <utime.h>
   9781 #  include <sys/time.h>
   9782 #  define STRUCT_STAT struct stat
   9783 #  include <limits.h>
   9784 #  include <stdlib.h>
   9785 #else
   9786 /* #  include "windirent.h" */
   9787 #  include <direct.h>
   9788 #  define STRUCT_STAT struct _stat
   9789 #  define chmod(path,mode) fileio_chmod(path,mode)
   9790 #  define mkdir(path,mode) fileio_mkdir(path)
   9791    extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
   9792    extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
   9793 #endif
   9794 #include <time.h>
   9795 #include <errno.h>
   9796 
   9797 /* When used as part of the CLI, the sqlite3_stdio.h module will have
   9798 ** been included before this one. In that case use the sqlite3_stdio.h
   9799 ** #defines.  If not, create our own for fopen().
   9800 */
   9801 #ifndef _SQLITE3_STDIO_H_
   9802 # define sqlite3_fopen fopen
   9803 #endif
   9804 
   9805 /*
   9806 ** Structure of the fsdir() table-valued function
   9807 */
   9808                  /*    0    1    2     3    4     5           6          */
   9809 #define FSDIR_SCHEMA "(name,mode,mtime,data,level,path HIDDEN,dir HIDDEN)"
   9810 
   9811 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
   9812 #define FSDIR_COLUMN_MODE     1     /* Access mode */
   9813 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
   9814 #define FSDIR_COLUMN_DATA     3     /* File content */
   9815 #define FSDIR_COLUMN_LEVEL    4     /* Level.  Topmost is 1 */
   9816 #define FSDIR_COLUMN_PATH     5     /* Path to top of search */
   9817 #define FSDIR_COLUMN_DIR      6     /* Path is relative to this directory */
   9818 
   9819 /*
   9820 ** UTF8 chmod() function for Windows
   9821 */
   9822 #if defined(_WIN32) || defined(WIN32)
   9823 static int fileio_chmod(const char *zPath, int pmode){
   9824   int rc;
   9825   wchar_t *b1 = sqlite3_win32_utf8_to_unicode(zPath);
   9826   if( b1==0 ) return -1;
   9827   rc = _wchmod(b1, pmode);
   9828   sqlite3_free(b1);
   9829   return rc;
   9830 }
   9831 #endif
   9832 
   9833 /*
   9834 ** UTF8 mkdir() function for Windows
   9835 */
   9836 #if defined(_WIN32) || defined(WIN32)
   9837 static int fileio_mkdir(const char *zPath){
   9838   int rc;
   9839   wchar_t *b1 = sqlite3_win32_utf8_to_unicode(zPath);
   9840   if( b1==0 ) return -1;
   9841   rc = _wmkdir(b1);
   9842   sqlite3_free(b1);
   9843   return rc;
   9844 }
   9845 #endif
   9846 
   9847 
   9848 /*
   9849 ** Set the result stored by context ctx to a blob containing the
   9850 ** contents of file zName.  Or, leave the result unchanged (NULL)
   9851 ** if the file does not exist or is unreadable.
   9852 **
   9853 ** If the file exceeds the SQLite blob size limit, through an
   9854 ** SQLITE_TOOBIG error.
   9855 **
   9856 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
   9857 ** off of disk.
   9858 */
   9859 static void readFileContents(sqlite3_context *ctx, const char *zName){
   9860   FILE *in;
   9861   sqlite3_int64 nIn;
   9862   void *pBuf;
   9863   sqlite3 *db;
   9864   int mxBlob;
   9865 
   9866   in = sqlite3_fopen(zName, "rb");
   9867   if( in==0 ){
   9868     /* File does not exist or is unreadable. Leave the result set to NULL. */
   9869     return;
   9870   }
   9871   fseek(in, 0, SEEK_END);
   9872   nIn = ftell(in);
   9873   rewind(in);
   9874   db = sqlite3_context_db_handle(ctx);
   9875   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
   9876   if( nIn>mxBlob ){
   9877     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
   9878     fclose(in);
   9879     return;
   9880   }
   9881   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
   9882   if( pBuf==0 ){
   9883     sqlite3_result_error_nomem(ctx);
   9884     fclose(in);
   9885     return;
   9886   }
   9887   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
   9888     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
   9889   }else{
   9890     sqlite3_result_error_code(ctx, SQLITE_IOERR);
   9891     sqlite3_free(pBuf);
   9892   }
   9893   fclose(in);
   9894 }
   9895 
   9896 /*
   9897 ** Implementation of the "readfile(X)" SQL function.  The entire content
   9898 ** of the file named X is read and returned as a BLOB.  NULL is returned
   9899 ** if the file does not exist or is unreadable.
   9900 */
   9901 static void readfileFunc(
   9902   sqlite3_context *context,
   9903   int argc,
   9904   sqlite3_value **argv
   9905 ){
   9906   const char *zName;
   9907   (void)(argc);  /* Unused parameter */
   9908   zName = (const char*)sqlite3_value_text(argv[0]);
   9909   if( zName==0 ) return;
   9910   readFileContents(context, zName);
   9911 }
   9912 
   9913 /*
   9914 ** Set the error message contained in context ctx to the results of
   9915 ** vprintf(zFmt, ...).
   9916 */
   9917 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
   9918   char *zMsg = 0;
   9919   va_list ap;
   9920   va_start(ap, zFmt);
   9921   zMsg = sqlite3_vmprintf(zFmt, ap);
   9922   sqlite3_result_error(ctx, zMsg, -1);
   9923   sqlite3_free(zMsg);
   9924   va_end(ap);
   9925 }
   9926 
   9927 #if defined(_WIN32)
   9928 /*
   9929 ** This function is designed to convert a Win32 FILETIME structure into the
   9930 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
   9931 */
   9932 static sqlite3_uint64 fileTimeToUnixTime(
   9933   LPFILETIME pFileTime
   9934 ){
   9935   SYSTEMTIME epochSystemTime;
   9936   ULARGE_INTEGER epochIntervals;
   9937   FILETIME epochFileTime;
   9938   ULARGE_INTEGER fileIntervals;
   9939 
   9940   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
   9941   epochSystemTime.wYear = 1970;
   9942   epochSystemTime.wMonth = 1;
   9943   epochSystemTime.wDay = 1;
   9944   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
   9945   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
   9946   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
   9947 
   9948   fileIntervals.LowPart = pFileTime->dwLowDateTime;
   9949   fileIntervals.HighPart = pFileTime->dwHighDateTime;
   9950 
   9951   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
   9952 }
   9953 #endif /* _WIN32 */
   9954 
   9955 /*
   9956 ** This function is used in place of stat().  On Windows, special handling
   9957 ** is required in order for the included time to be returned as UTC.  On all
   9958 ** other systems, this function simply calls stat().
   9959 */
   9960 static int fileStat(
   9961   const char *zPath,
   9962   STRUCT_STAT *pStatBuf
   9963 ){
   9964 #if defined(_WIN32)
   9965   int rc;
   9966   wchar_t *b1 = sqlite3_win32_utf8_to_unicode(zPath);
   9967   if( b1==0 ) return 1;
   9968   rc = _wstat(b1, pStatBuf);
   9969   if( rc==0 ){
   9970     HANDLE hFindFile;
   9971     WIN32_FIND_DATAW fd;
   9972     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
   9973     hFindFile = FindFirstFileW(b1, &fd);
   9974     if( hFindFile!=NULL ){
   9975       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
   9976       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
   9977       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
   9978       FindClose(hFindFile);
   9979     }
   9980   }
   9981   sqlite3_free(b1);
   9982   return rc;
   9983 #else
   9984   return stat(zPath, pStatBuf);
   9985 #endif
   9986 }
   9987 
   9988 /*
   9989 ** This function is used in place of lstat().  On Windows, special handling
   9990 ** is required in order for the included time to be returned as UTC.  On all
   9991 ** other systems, this function simply calls lstat().
   9992 */
   9993 static int fileLinkStat(
   9994   const char *zPath,
   9995   STRUCT_STAT *pStatBuf
   9996 ){
   9997 #if defined(_WIN32)
   9998   return fileStat(zPath, pStatBuf);
   9999 #else
   10000   return lstat(zPath, pStatBuf);
   10001 #endif
   10002 }
   10003 
   10004 /*
   10005 ** Argument zFile is the name of a file that will be created and/or written
   10006 ** by SQL function writefile(). This function ensures that the directory
   10007 ** zFile will be written to exists, creating it if required. The permissions
   10008 ** for any path components created by this function are set in accordance
   10009 ** with the current umask.
   10010 **
   10011 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
   10012 ** SQLITE_OK is returned if the directory is successfully created, or
   10013 ** SQLITE_ERROR otherwise.
   10014 */
   10015 static int makeDirectory(
   10016   const char *zFile
   10017 ){
   10018   char *zCopy = sqlite3_mprintf("%s", zFile);
   10019   int rc = SQLITE_OK;
   10020 
   10021   if( zCopy==0 ){
   10022     rc = SQLITE_NOMEM;
   10023   }else{
   10024     int nCopy = (int)strlen(zCopy);
   10025     int i = 1;
   10026 
   10027     while( rc==SQLITE_OK ){
   10028       STRUCT_STAT sStat;
   10029       int rc2;
   10030 
   10031       for(; zCopy[i]!='/' && i<nCopy; i++);
   10032       if( i==nCopy ) break;
   10033       zCopy[i] = '\0';
   10034 
   10035       rc2 = fileStat(zCopy, &sStat);
   10036       if( rc2!=0 ){
   10037         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
   10038       }else{
   10039         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
   10040       }
   10041       zCopy[i] = '/';
   10042       i++;
   10043     }
   10044 
   10045     sqlite3_free(zCopy);
   10046   }
   10047 
   10048   return rc;
   10049 }
   10050 
   10051 /*
   10052 ** This function does the work for the writefile() UDF. Refer to
   10053 ** header comments at the top of this file for details.
   10054 */
   10055 static int writeFile(
   10056   sqlite3_context *pCtx,          /* Context to return bytes written in */
   10057   const char *zFile,              /* File to write */
   10058   sqlite3_value *pData,           /* Data to write */
   10059   mode_t mode,                    /* MODE parameter passed to writefile() */
   10060   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
   10061 ){
   10062   if( zFile==0 ) return 1;
   10063 #if !defined(_WIN32) && !defined(WIN32)
   10064   if( S_ISLNK(mode) ){
   10065     const char *zTo = (const char*)sqlite3_value_text(pData);
   10066     if( zTo==0 ) return 1;
   10067     unlink(zFile);
   10068     if( symlink(zTo, zFile)<0 ) return 1;
   10069   }else
   10070 #endif
   10071   {
   10072     if( S_ISDIR(mode) ){
   10073       if( mkdir(zFile, mode) ){
   10074         /* The mkdir() call to create the directory failed. This might not
   10075         ** be an error though - if there is already a directory at the same
   10076         ** path and either the permissions already match or can be changed
   10077         ** to do so using chmod(), it is not an error.  */
   10078         STRUCT_STAT sStat;
   10079         if( errno!=EEXIST
   10080          || 0!=fileStat(zFile, &sStat)
   10081          || !S_ISDIR(sStat.st_mode)
   10082          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
   10083         ){
   10084           return 1;
   10085         }
   10086       }
   10087     }else{
   10088       sqlite3_int64 nWrite = 0;
   10089       const char *z;
   10090       int rc = 0;
   10091       FILE *out = sqlite3_fopen(zFile, "wb");
   10092       if( out==0 ) return 1;
   10093       z = (const char*)sqlite3_value_blob(pData);
   10094       if( z ){
   10095         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
   10096         nWrite = sqlite3_value_bytes(pData);
   10097         if( nWrite!=n ){
   10098           rc = 1;
   10099         }
   10100       }
   10101       fclose(out);
   10102       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
   10103         rc = 1;
   10104       }
   10105       if( rc ) return 2;
   10106       sqlite3_result_int64(pCtx, nWrite);
   10107     }
   10108   }
   10109 
   10110   if( mtime>=0 ){
   10111 #if defined(_WIN32)
   10112     /* Windows */
   10113     FILETIME lastAccess;
   10114     FILETIME lastWrite;
   10115     SYSTEMTIME currentTime;
   10116     LONGLONG intervals;
   10117     HANDLE hFile;
   10118     LPWSTR zUnicodeName;
   10119     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
   10120 
   10121     GetSystemTime(&currentTime);
   10122     SystemTimeToFileTime(&currentTime, &lastAccess);
   10123     intervals = (mtime*10000000) + 116444736000000000;
   10124     lastWrite.dwLowDateTime = (DWORD)intervals;
   10125     lastWrite.dwHighDateTime = intervals >> 32;
   10126     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
   10127     if( zUnicodeName==0 ){
   10128       return 1;
   10129     }
   10130     hFile = CreateFileW(
   10131       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
   10132       FILE_FLAG_BACKUP_SEMANTICS, NULL
   10133     );
   10134     sqlite3_free(zUnicodeName);
   10135     if( hFile!=INVALID_HANDLE_VALUE ){
   10136       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
   10137       CloseHandle(hFile);
   10138       return !bResult;
   10139     }else{
   10140       return 1;
   10141     }
   10142 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
   10143     /* Recent unix */
   10144     struct timespec times[2];
   10145     times[0].tv_nsec = times[1].tv_nsec = 0;
   10146     times[0].tv_sec = time(0);
   10147     times[1].tv_sec = mtime;
   10148     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
   10149       return 1;
   10150     }
   10151 #else
   10152     /* Legacy unix.
   10153     **
   10154     ** Do not use utimes() on a symbolic link - it sees through the link and
   10155     ** modifies the timestamps on the target. Or fails if the target does
   10156     ** not exist.  */
   10157     if( 0==S_ISLNK(mode) ){
   10158       struct timeval times[2];
   10159       times[0].tv_usec = times[1].tv_usec = 0;
   10160       times[0].tv_sec = time(0);
   10161       times[1].tv_sec = mtime;
   10162       if( utimes(zFile, times) ){
   10163         return 1;
   10164       }
   10165     }
   10166 #endif
   10167   }
   10168 
   10169   return 0;
   10170 }
   10171 
   10172 /*
   10173 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
   10174 ** Refer to header comments at the top of this file for details.
   10175 */
   10176 static void writefileFunc(
   10177   sqlite3_context *context,
   10178   int argc,
   10179   sqlite3_value **argv
   10180 ){
   10181   const char *zFile;
   10182   mode_t mode = 0;
   10183   int res;
   10184   sqlite3_int64 mtime = -1;
   10185 
   10186   if( argc<2 || argc>4 ){
   10187     sqlite3_result_error(context,
   10188         "wrong number of arguments to function writefile()", -1
   10189     );
   10190     return;
   10191   }
   10192 
   10193   zFile = (const char*)sqlite3_value_text(argv[0]);
   10194   if( zFile==0 ) return;
   10195   if( argc>=3 ){
   10196     mode = (mode_t)sqlite3_value_int(argv[2]);
   10197   }
   10198   if( argc==4 ){
   10199     mtime = sqlite3_value_int64(argv[3]);
   10200   }
   10201 
   10202   res = writeFile(context, zFile, argv[1], mode, mtime);
   10203   if( res==1 && errno==ENOENT ){
   10204     if( makeDirectory(zFile)==SQLITE_OK ){
   10205       res = writeFile(context, zFile, argv[1], mode, mtime);
   10206     }
   10207   }
   10208 
   10209   if( argc>2 && res!=0 ){
   10210     if( S_ISLNK(mode) ){
   10211       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
   10212     }else if( S_ISDIR(mode) ){
   10213       ctxErrorMsg(context, "failed to create directory: %s", zFile);
   10214     }else{
   10215       ctxErrorMsg(context, "failed to write file: %s", zFile);
   10216     }
   10217   }
   10218 }
   10219 
   10220 /*
   10221 ** SQL function:   lsmode(MODE)
   10222 **
   10223 ** Given a numberic st_mode from stat(), convert it into a human-readable
   10224 ** text string in the style of "ls -l".
   10225 */
   10226 static void lsModeFunc(
   10227   sqlite3_context *context,
   10228   int argc,
   10229   sqlite3_value **argv
   10230 ){
   10231   int i;
   10232   int iMode = sqlite3_value_int(argv[0]);
   10233   char z[16];
   10234   (void)argc;
   10235   if( S_ISLNK(iMode) ){
   10236     z[0] = 'l';
   10237   }else if( S_ISREG(iMode) ){
   10238     z[0] = '-';
   10239   }else if( S_ISDIR(iMode) ){
   10240     z[0] = 'd';
   10241   }else{
   10242     z[0] = '?';
   10243   }
   10244   for(i=0; i<3; i++){
   10245     int m = (iMode >> ((2-i)*3));
   10246     char *a = &z[1 + i*3];
   10247     a[0] = (m & 0x4) ? 'r' : '-';
   10248     a[1] = (m & 0x2) ? 'w' : '-';
   10249     a[2] = (m & 0x1) ? 'x' : '-';
   10250   }
   10251   z[10] = '\0';
   10252   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
   10253 }
   10254 
   10255 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10256 
   10257 /*
   10258 ** Cursor type for recursively iterating through a directory structure.
   10259 */
   10260 typedef struct fsdir_cursor fsdir_cursor;
   10261 typedef struct FsdirLevel FsdirLevel;
   10262 
   10263 struct FsdirLevel {
   10264   DIR *pDir;                 /* From opendir() */
   10265   char *zDir;                /* Name of directory (nul-terminated) */
   10266 };
   10267 
   10268 struct fsdir_cursor {
   10269   sqlite3_vtab_cursor base;  /* Base class - must be first */
   10270 
   10271   int nLvl;                  /* Number of entries in aLvl[] array */
   10272   int mxLvl;                 /* Maximum level */
   10273   int iLvl;                  /* Index of current entry */
   10274   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
   10275 
   10276   const char *zBase;
   10277   int nBase;
   10278 
   10279   STRUCT_STAT sStat;         /* Current lstat() results */
   10280   char *zPath;               /* Path to current entry */
   10281   sqlite3_int64 iRowid;      /* Current rowid */
   10282 };
   10283 
   10284 typedef struct fsdir_tab fsdir_tab;
   10285 struct fsdir_tab {
   10286   sqlite3_vtab base;         /* Base class - must be first */
   10287 };
   10288 
   10289 /*
   10290 ** Construct a new fsdir virtual table object.
   10291 */
   10292 static int fsdirConnect(
   10293   sqlite3 *db,
   10294   void *pAux,
   10295   int argc, const char *const*argv,
   10296   sqlite3_vtab **ppVtab,
   10297   char **pzErr
   10298 ){
   10299   fsdir_tab *pNew = 0;
   10300   int rc;
   10301   (void)pAux;
   10302   (void)argc;
   10303   (void)argv;
   10304   (void)pzErr;
   10305   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
   10306   if( rc==SQLITE_OK ){
   10307     pNew = (fsdir_tab*)sqlite3_malloc64( sizeof(*pNew) );
   10308     if( pNew==0 ) return SQLITE_NOMEM;
   10309     memset(pNew, 0, sizeof(*pNew));
   10310     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
   10311   }
   10312   *ppVtab = (sqlite3_vtab*)pNew;
   10313   return rc;
   10314 }
   10315 
   10316 /*
   10317 ** This method is the destructor for fsdir vtab objects.
   10318 */
   10319 static int fsdirDisconnect(sqlite3_vtab *pVtab){
   10320   sqlite3_free(pVtab);
   10321   return SQLITE_OK;
   10322 }
   10323 
   10324 /*
   10325 ** Constructor for a new fsdir_cursor object.
   10326 */
   10327 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   10328   fsdir_cursor *pCur;
   10329   (void)p;
   10330   pCur = sqlite3_malloc64( sizeof(*pCur) );
   10331   if( pCur==0 ) return SQLITE_NOMEM;
   10332   memset(pCur, 0, sizeof(*pCur));
   10333   pCur->iLvl = -1;
   10334   *ppCursor = &pCur->base;
   10335   return SQLITE_OK;
   10336 }
   10337 
   10338 /*
   10339 ** Reset a cursor back to the state it was in when first returned
   10340 ** by fsdirOpen().
   10341 */
   10342 static void fsdirResetCursor(fsdir_cursor *pCur){
   10343   int i;
   10344   for(i=0; i<=pCur->iLvl; i++){
   10345     FsdirLevel *pLvl = &pCur->aLvl[i];
   10346     if( pLvl->pDir ) closedir(pLvl->pDir);
   10347     sqlite3_free(pLvl->zDir);
   10348   }
   10349   sqlite3_free(pCur->zPath);
   10350   sqlite3_free(pCur->aLvl);
   10351   pCur->aLvl = 0;
   10352   pCur->zPath = 0;
   10353   pCur->zBase = 0;
   10354   pCur->nBase = 0;
   10355   pCur->nLvl = 0;
   10356   pCur->iLvl = -1;
   10357   pCur->iRowid = 1;
   10358 }
   10359 
   10360 /*
   10361 ** Destructor for an fsdir_cursor.
   10362 */
   10363 static int fsdirClose(sqlite3_vtab_cursor *cur){
   10364   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   10365 
   10366   fsdirResetCursor(pCur);
   10367   sqlite3_free(pCur);
   10368   return SQLITE_OK;
   10369 }
   10370 
   10371 /*
   10372 ** Set the error message for the virtual table associated with cursor
   10373 ** pCur to the results of vprintf(zFmt, ...).
   10374 */
   10375 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
   10376   va_list ap;
   10377   va_start(ap, zFmt);
   10378   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
   10379   va_end(ap);
   10380 }
   10381 
   10382 
   10383 /*
   10384 ** Advance an fsdir_cursor to its next row of output.
   10385 */
   10386 static int fsdirNext(sqlite3_vtab_cursor *cur){
   10387   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   10388   mode_t m = pCur->sStat.st_mode;
   10389 
   10390   pCur->iRowid++;
   10391   if( S_ISDIR(m) && pCur->iLvl+3<pCur->mxLvl ){
   10392     /* Descend into this directory */
   10393     int iNew = pCur->iLvl + 1;
   10394     FsdirLevel *pLvl;
   10395     if( iNew>=pCur->nLvl ){
   10396       int nNew = iNew+1;
   10397       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
   10398       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
   10399       if( aNew==0 ) return SQLITE_NOMEM;
   10400       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
   10401       pCur->aLvl = aNew;
   10402       pCur->nLvl = nNew;
   10403     }
   10404     pCur->iLvl = iNew;
   10405     pLvl = &pCur->aLvl[iNew];
   10406 
   10407     pLvl->zDir = pCur->zPath;
   10408     pCur->zPath = 0;
   10409     pLvl->pDir = opendir(pLvl->zDir);
   10410     if( pLvl->pDir==0 ){
   10411       fsdirSetErrmsg(pCur, "cannot read directory: %s", pLvl->zDir);
   10412       return SQLITE_ERROR;
   10413     }
   10414   }
   10415 
   10416   while( pCur->iLvl>=0 ){
   10417     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
   10418     struct dirent *pEntry = readdir(pLvl->pDir);
   10419     if( pEntry ){
   10420       if( pEntry->d_name[0]=='.' ){
   10421        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
   10422        if( pEntry->d_name[1]=='\0' ) continue;
   10423       }
   10424       sqlite3_free(pCur->zPath);
   10425       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
   10426       if( pCur->zPath==0 ) return SQLITE_NOMEM;
   10427       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
   10428         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
   10429         return SQLITE_ERROR;
   10430       }
   10431       return SQLITE_OK;
   10432     }
   10433     closedir(pLvl->pDir);
   10434     sqlite3_free(pLvl->zDir);
   10435     pLvl->pDir = 0;
   10436     pLvl->zDir = 0;
   10437     pCur->iLvl--;
   10438   }
   10439 
   10440   /* EOF */
   10441   sqlite3_free(pCur->zPath);
   10442   pCur->zPath = 0;
   10443   return SQLITE_OK;
   10444 }
   10445 
   10446 /*
   10447 ** Return values of columns for the row at which the series_cursor
   10448 ** is currently pointing.
   10449 */
   10450 static int fsdirColumn(
   10451   sqlite3_vtab_cursor *cur,   /* The cursor */
   10452   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   10453   int i                       /* Which column to return */
   10454 ){
   10455   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   10456   switch( i ){
   10457     case FSDIR_COLUMN_NAME: {
   10458       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
   10459       break;
   10460     }
   10461 
   10462     case FSDIR_COLUMN_MODE:
   10463       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
   10464       break;
   10465 
   10466     case FSDIR_COLUMN_MTIME:
   10467       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
   10468       break;
   10469 
   10470     case FSDIR_COLUMN_DATA: {
   10471       mode_t m = pCur->sStat.st_mode;
   10472       if( S_ISDIR(m) ){
   10473         sqlite3_result_null(ctx);
   10474 #if !defined(_WIN32) && !defined(WIN32)
   10475       }else if( S_ISLNK(m) ){
   10476         char aStatic[64];
   10477         char *aBuf = aStatic;
   10478         sqlite3_int64 nBuf = 64;
   10479         int n;
   10480 
   10481         while( 1 ){
   10482           n = readlink(pCur->zPath, aBuf, nBuf);
   10483           if( n<nBuf ) break;
   10484           if( aBuf!=aStatic ) sqlite3_free(aBuf);
   10485           nBuf = nBuf*2;
   10486           aBuf = sqlite3_malloc64(nBuf);
   10487           if( aBuf==0 ){
   10488             sqlite3_result_error_nomem(ctx);
   10489             return SQLITE_NOMEM;
   10490           }
   10491         }
   10492 
   10493         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
   10494         if( aBuf!=aStatic ) sqlite3_free(aBuf);
   10495 #endif
   10496       }else{
   10497         readFileContents(ctx, pCur->zPath);
   10498       }
   10499       break;
   10500     }
   10501     case FSDIR_COLUMN_LEVEL:
   10502       sqlite3_result_int(ctx, pCur->iLvl+2);
   10503       break;
   10504     case FSDIR_COLUMN_PATH:
   10505     default: {
   10506       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
   10507       ** always return their values as NULL */
   10508       break;
   10509     }
   10510   }
   10511   return SQLITE_OK;
   10512 }
   10513 
   10514 /*
   10515 ** Return the rowid for the current row. In this implementation, the
   10516 ** first row returned is assigned rowid value 1, and each subsequent
   10517 ** row a value 1 more than that of the previous.
   10518 */
   10519 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   10520   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   10521   *pRowid = pCur->iRowid;
   10522   return SQLITE_OK;
   10523 }
   10524 
   10525 /*
   10526 ** Return TRUE if the cursor has been moved off of the last
   10527 ** row of output.
   10528 */
   10529 static int fsdirEof(sqlite3_vtab_cursor *cur){
   10530   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   10531   return (pCur->zPath==0);
   10532 }
   10533 
   10534 /*
   10535 ** xFilter callback.
   10536 **
   10537 ** idxNum bit      Meaning
   10538 **     0x01         PATH=N
   10539 **     0x02         DIR=N
   10540 **     0x04         LEVEL<N
   10541 **     0x08         LEVEL<=N
   10542 */
   10543 static int fsdirFilter(
   10544   sqlite3_vtab_cursor *cur,
   10545   int idxNum, const char *idxStr,
   10546   int argc, sqlite3_value **argv
   10547 ){
   10548   const char *zDir = 0;
   10549   fsdir_cursor *pCur = (fsdir_cursor*)cur;
   10550   int i;
   10551   (void)idxStr;
   10552   fsdirResetCursor(pCur);
   10553 
   10554   if( idxNum==0 ){
   10555     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
   10556     return SQLITE_ERROR;
   10557   }
   10558 
   10559   assert( (idxNum & 0x01)!=0 && argc>0 );
   10560   zDir = (const char*)sqlite3_value_text(argv[0]);
   10561   if( zDir==0 ){
   10562     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
   10563     return SQLITE_ERROR;
   10564   }
   10565   i = 1;
   10566   if( (idxNum & 0x02)!=0 ){
   10567     assert( argc>i );
   10568     pCur->zBase = (const char*)sqlite3_value_text(argv[i++]);
   10569   }
   10570   if( (idxNum & 0x0c)!=0 ){
   10571     assert( argc>i );
   10572     pCur->mxLvl = sqlite3_value_int(argv[i++]);
   10573     if( idxNum & 0x08 ) pCur->mxLvl++;
   10574     if( pCur->mxLvl<=0 ) pCur->mxLvl = 1000000000;
   10575   }else{
   10576     pCur->mxLvl = 1000000000;
   10577   }
   10578   if( pCur->zBase ){
   10579     pCur->nBase = (int)strlen(pCur->zBase)+1;
   10580     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
   10581   }else{
   10582     pCur->zPath = sqlite3_mprintf("%s", zDir);
   10583   }
   10584 
   10585   if( pCur->zPath==0 ){
   10586     return SQLITE_NOMEM;
   10587   }
   10588   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
   10589     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
   10590     return SQLITE_ERROR;
   10591   }
   10592 
   10593   return SQLITE_OK;
   10594 }
   10595 
   10596 /*
   10597 ** SQLite will invoke this method one or more times while planning a query
   10598 ** that uses the generate_series virtual table.  This routine needs to create
   10599 ** a query plan for each invocation and compute an estimated cost for that
   10600 ** plan.
   10601 **
   10602 ** In this implementation idxNum is used to represent the
   10603 ** query plan.  idxStr is unused.
   10604 **
   10605 ** The query plan is represented by bits in idxNum:
   10606 **
   10607 **  0x01  The path value is supplied by argv[0]
   10608 **  0x02  dir is in argv[1]
   10609 **  0x04  maxdepth is in argv[1] or [2]
   10610 */
   10611 static int fsdirBestIndex(
   10612   sqlite3_vtab *tab,
   10613   sqlite3_index_info *pIdxInfo
   10614 ){
   10615   int i;                 /* Loop over constraints */
   10616   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
   10617   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
   10618   int idxLevel = -1;     /* Index in pIdxInfo->aConstraint of LEVEL< or <= */
   10619   int idxLevelEQ = 0;    /* 0x08 for LEVEL<= or LEVEL=.  0x04 for LEVEL< */
   10620   int omitLevel = 0;     /* omit the LEVEL constraint */
   10621   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
   10622   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
   10623   const struct sqlite3_index_constraint *pConstraint;
   10624 
   10625   (void)tab;
   10626   pConstraint = pIdxInfo->aConstraint;
   10627   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   10628     if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   10629       switch( pConstraint->iColumn ){
   10630         case FSDIR_COLUMN_PATH: {
   10631           if( pConstraint->usable ){
   10632             idxPath = i;
   10633             seenPath = 0;
   10634           }else if( idxPath<0 ){
   10635             seenPath = 1;
   10636           }
   10637           break;
   10638         }
   10639         case FSDIR_COLUMN_DIR: {
   10640           if( pConstraint->usable ){
   10641             idxDir = i;
   10642             seenDir = 0;
   10643           }else if( idxDir<0 ){
   10644             seenDir = 1;
   10645           }
   10646           break;
   10647         }
   10648         case FSDIR_COLUMN_LEVEL: {
   10649           if( pConstraint->usable && idxLevel<0 ){
   10650             idxLevel = i;
   10651             idxLevelEQ = 0x08;
   10652             omitLevel = 0;
   10653           }
   10654           break;
   10655         }
   10656       }
   10657     }else
   10658     if( pConstraint->iColumn==FSDIR_COLUMN_LEVEL
   10659      && pConstraint->usable
   10660      && idxLevel<0
   10661     ){
   10662       if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE ){
   10663         idxLevel = i;
   10664         idxLevelEQ = 0x08;
   10665         omitLevel = 1;
   10666       }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ){
   10667         idxLevel = i;
   10668         idxLevelEQ = 0x04;
   10669         omitLevel = 1;
   10670       }
   10671     }
   10672   }
   10673   if( seenPath || seenDir ){
   10674     /* If input parameters are unusable, disallow this plan */
   10675     return SQLITE_CONSTRAINT;
   10676   }
   10677 
   10678   if( idxPath<0 ){
   10679     pIdxInfo->idxNum = 0;
   10680     /* The pIdxInfo->estimatedCost should have been initialized to a huge
   10681     ** number.  Leave it unchanged. */
   10682     pIdxInfo->estimatedRows = 0x7fffffff;
   10683   }else{
   10684     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
   10685     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
   10686     pIdxInfo->idxNum = 0x01;
   10687     pIdxInfo->estimatedCost = 1.0e9;
   10688     i = 2;
   10689     if( idxDir>=0 ){
   10690       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
   10691       pIdxInfo->aConstraintUsage[idxDir].argvIndex = i++;
   10692       pIdxInfo->idxNum |= 0x02;
   10693       pIdxInfo->estimatedCost /= 1.0e4;
   10694     }
   10695     if( idxLevel>=0 ){
   10696       pIdxInfo->aConstraintUsage[idxLevel].omit = omitLevel;
   10697       pIdxInfo->aConstraintUsage[idxLevel].argvIndex = i++;
   10698       pIdxInfo->idxNum |= idxLevelEQ;
   10699       pIdxInfo->estimatedCost /= 1.0e4;
   10700     }
   10701   }
   10702 
   10703   return SQLITE_OK;
   10704 }
   10705 
   10706 /*
   10707 ** Register the "fsdir" virtual table.
   10708 */
   10709 static int fsdirRegister(sqlite3 *db){
   10710   static sqlite3_module fsdirModule = {
   10711     0,                         /* iVersion */
   10712     0,                         /* xCreate */
   10713     fsdirConnect,              /* xConnect */
   10714     fsdirBestIndex,            /* xBestIndex */
   10715     fsdirDisconnect,           /* xDisconnect */
   10716     0,                         /* xDestroy */
   10717     fsdirOpen,                 /* xOpen - open a cursor */
   10718     fsdirClose,                /* xClose - close a cursor */
   10719     fsdirFilter,               /* xFilter - configure scan constraints */
   10720     fsdirNext,                 /* xNext - advance a cursor */
   10721     fsdirEof,                  /* xEof - check for end of scan */
   10722     fsdirColumn,               /* xColumn - read data */
   10723     fsdirRowid,                /* xRowid - read data */
   10724     0,                         /* xUpdate */
   10725     0,                         /* xBegin */
   10726     0,                         /* xSync */
   10727     0,                         /* xCommit */
   10728     0,                         /* xRollback */
   10729     0,                         /* xFindMethod */
   10730     0,                         /* xRename */
   10731     0,                         /* xSavepoint */
   10732     0,                         /* xRelease */
   10733     0,                         /* xRollbackTo */
   10734     0,                         /* xShadowName */
   10735     0                          /* xIntegrity */
   10736   };
   10737 
   10738   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
   10739   return rc;
   10740 }
   10741 #else         /* SQLITE_OMIT_VIRTUALTABLE */
   10742 # define fsdirRegister(x) SQLITE_OK
   10743 #endif
   10744 
   10745 /*
   10746 ** This version of realpath() works on any system.  The string
   10747 ** returned is held in memory allocated using sqlite3_malloc64().
   10748 ** The caller is responsible for calling sqlite3_free().
   10749 */
   10750 static char *portable_realpath(const char *zPath){
   10751 #if !defined(_WIN32)       /* BEGIN unix */
   10752 
   10753   char *zOut = 0;          /* Result */
   10754   char *z;                 /* Temporary buffer */
   10755 #if defined(PATH_MAX)
   10756   char zBuf[PATH_MAX+1];   /* Space for the temporary buffer */
   10757 #endif
   10758 
   10759   if( zPath==0 ) return 0;
   10760 #if defined(PATH_MAX)
   10761   z = realpath(zPath, zBuf);
   10762   if( z ){
   10763     zOut = sqlite3_mprintf("%s", zBuf);
   10764   }
   10765 #endif /* defined(PATH_MAX) */
   10766   if( zOut==0 ){
   10767     /* Try POSIX.1-2008 malloc behavior */
   10768     z = realpath(zPath, NULL);
   10769     if( z ){
   10770       zOut = sqlite3_mprintf("%s", z);
   10771       free(z);
   10772     }
   10773   }
   10774   return zOut;
   10775 
   10776 #else /* End UNIX, Begin WINDOWS */
   10777 
   10778   wchar_t *zPath16;        /* UTF16 translation of zPath */
   10779   char *zOut = 0;          /* Result */
   10780   wchar_t *z = 0;          /* Temporary buffer */
   10781 
   10782   if( zPath==0 ) return 0;
   10783 
   10784   zPath16 = sqlite3_win32_utf8_to_unicode(zPath);
   10785   if( zPath16==0 ) return 0;
   10786   z = _wfullpath(NULL, zPath16, 0);
   10787   sqlite3_free(zPath16);
   10788   if( z ){
   10789     zOut = sqlite3_win32_unicode_to_utf8(z);
   10790     free(z);
   10791   }
   10792   return zOut;
   10793 
   10794 #endif /* End WINDOWS, Begin common code */
   10795 }
   10796 
   10797 /*
   10798 ** SQL function:   realpath(X)
   10799 **
   10800 ** Try to convert file or pathname X into its real, absolute pathname.
   10801 ** Return NULL if unable.
   10802 **
   10803 ** The file or directory X is not required to exist.  The answer is formed
   10804 ** by calling system realpath() on the prefix of X that does exist and
   10805 ** appending the tail of X that does not (yet) exist.
   10806 */
   10807 static void realpathFunc(
   10808   sqlite3_context *context,
   10809   int argc,
   10810   sqlite3_value **argv
   10811 ){
   10812   const char *zPath;    /* Original input path */
   10813   char *zCopy;          /* An editable copy of zPath */
   10814   char *zOut;           /* The result */
   10815   char cSep = 0;        /* Separator turned into \000 */
   10816   size_t len;           /* Prefix length before cSep */
   10817 #ifdef _WIN32
   10818   const int isWin = 1;
   10819 #else
   10820   const int isWin = 0;
   10821 #endif
   10822 
   10823   (void)argc;
   10824   zPath = (const char*)sqlite3_value_text(argv[0]);
   10825   if( zPath==0 ) return;
   10826   if( zPath[0]==0 ) zPath = ".";
   10827   zCopy = sqlite3_mprintf("%s",zPath);
   10828   len = strlen(zCopy);
   10829   while( len>1 && (zCopy[len-1]=='/' || (isWin && zCopy[len-1]=='\\')) ){
   10830     len--;
   10831   }
   10832   zCopy[len] = 0;
   10833   while( 1 /*exit-by-break*/ ){
   10834     zOut = portable_realpath(zCopy);
   10835     zCopy[len] = cSep;
   10836     if( zOut ){
   10837       if( cSep ){
   10838         zOut = sqlite3_mprintf("%z%s",zOut,&zCopy[len]);
   10839       }
   10840       break;
   10841     }else{
   10842       size_t i = len-1;
   10843       while( i>0 ){
   10844         if( zCopy[i]=='/' || (isWin && zCopy[i]=='\\') ) break;
   10845         i--;
   10846       }
   10847       if( i<=0 ){
   10848         if( zCopy[0]=='/' ){
   10849           zOut = zCopy;
   10850           zCopy = 0;
   10851         }else if( (zOut = portable_realpath("."))!=0 ){
   10852           zOut = sqlite3_mprintf("%z/%s", zOut, zCopy);
   10853         }
   10854         break;
   10855       }
   10856       cSep = zCopy[i];
   10857       zCopy[i] = 0;
   10858       len = i;
   10859     }
   10860   }
   10861   sqlite3_free(zCopy);
   10862   if( zOut ){
   10863     /* Simplify any "/./" or "/../" that might have snuck into the
   10864     ** pathname due to appending of zCopy.  We only have to consider
   10865     ** unix "/" separators, because the _wfilepath() system call on
   10866     ** Windows will have already done this simplification for us. */
   10867     size_t i, j, n;
   10868     n = strlen(zOut);
   10869     for(i=j=0; i<n; i++){
   10870       if( zOut[i]=='/' ){
   10871         if( zOut[i+1]=='/' ) continue;
   10872         if( zOut[i+1]=='.' && i+2<n && zOut[i+2]=='/' ){
   10873           i += 1;
   10874           continue;
   10875         }
   10876         if( zOut[i+1]=='.' && i+3<n && zOut[i+2]=='.' && zOut[i+3]=='/' ){
   10877           while( j>0 && zOut[j-1]!='/' ){ j--; }
   10878           if( j>0 ){ j--; }
   10879           i += 2;
   10880           continue;
   10881         }
   10882       }
   10883       zOut[j++] = zOut[i];
   10884     }
   10885     zOut[j] = 0;
   10886 
   10887     /* Return the result */
   10888     sqlite3_result_text(context, zOut, -1, sqlite3_free);
   10889   }
   10890 }
   10891 
   10892 
   10893 #ifdef _WIN32
   10894 
   10895 #endif
   10896 static int sqlite3_fileio_init(
   10897   sqlite3 *db,
   10898   char **pzErrMsg,
   10899   const sqlite3_api_routines *pApi
   10900 ){
   10901   int rc = SQLITE_OK;
   10902   SQLITE_EXTENSION_INIT2(pApi);
   10903   (void)pzErrMsg;  /* Unused parameter */
   10904   rc = sqlite3_create_function(db, "readfile", 1,
   10905                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
   10906                                readfileFunc, 0, 0);
   10907   if( rc==SQLITE_OK ){
   10908     rc = sqlite3_create_function(db, "writefile", -1,
   10909                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
   10910                                  writefileFunc, 0, 0);
   10911   }
   10912   if( rc==SQLITE_OK ){
   10913     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
   10914                                  lsModeFunc, 0, 0);
   10915   }
   10916   if( rc==SQLITE_OK ){
   10917     rc = fsdirRegister(db);
   10918   }
   10919   if( rc==SQLITE_OK ){
   10920     rc = sqlite3_create_function(db, "realpath", 1,
   10921                                  SQLITE_UTF8, 0,
   10922                                  realpathFunc, 0, 0);
   10923   }
   10924   return rc;
   10925 }
   10926 
   10927 /************************* End ext/misc/fileio.c ********************/
   10928 /************************* Begin ext/misc/completion.c ******************/
   10929 /*
   10930 ** 2017-07-10
   10931 **
   10932 ** The author disclaims copyright to this source code.  In place of
   10933 ** a legal notice, here is a blessing:
   10934 **
   10935 **    May you do good and not evil.
   10936 **    May you find forgiveness for yourself and forgive others.
   10937 **    May you share freely, never taking more than you give.
   10938 **
   10939 *************************************************************************
   10940 **
   10941 ** This file implements an eponymous virtual table that returns suggested
   10942 ** completions for a partial SQL input.
   10943 **
   10944 ** Suggested usage:
   10945 **
   10946 **     SELECT DISTINCT candidate COLLATE nocase
   10947 **       FROM completion($prefix,$wholeline)
   10948 **      ORDER BY 1;
   10949 **
   10950 ** The two query parameters are optional.  $prefix is the text of the
   10951 ** current word being typed and that is to be completed.  $wholeline is
   10952 ** the complete input line, used for context.
   10953 **
   10954 ** The raw completion() table might return the same candidate multiple
   10955 ** times, for example if the same column name is used to two or more
   10956 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
   10957 ** the DISTINCT and ORDER BY are recommended.
   10958 **
   10959 ** This virtual table operates at the speed of human typing, and so there
   10960 ** is no attempt to make it fast.  Even a slow implementation will be much
   10961 ** faster than any human can type.
   10962 **
   10963 */
   10964 /* #include "sqlite3ext.h" */
   10965 SQLITE_EXTENSION_INIT1
   10966 #include <assert.h>
   10967 #include <string.h>
   10968 #include <ctype.h>
   10969 
   10970 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10971 
   10972 #ifndef IsAlnum
   10973 #define IsAlnum(X)  isalnum((unsigned char)X)
   10974 #endif
   10975 
   10976 
   10977 /* completion_vtab is a subclass of sqlite3_vtab which will
   10978 ** serve as the underlying representation of a completion virtual table
   10979 */
   10980 typedef struct completion_vtab completion_vtab;
   10981 struct completion_vtab {
   10982   sqlite3_vtab base;  /* Base class - must be first */
   10983   sqlite3 *db;        /* Database connection for this completion vtab */
   10984 };
   10985 
   10986 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
   10987 ** serve as the underlying representation of a cursor that scans
   10988 ** over rows of the result
   10989 */
   10990 typedef struct completion_cursor completion_cursor;
   10991 struct completion_cursor {
   10992   sqlite3_vtab_cursor base;  /* Base class - must be first */
   10993   sqlite3 *db;               /* Database connection for this cursor */
   10994   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
   10995   char *zPrefix;             /* The prefix for the word we want to complete */
   10996   char *zLine;               /* The whole that we want to complete */
   10997   const char *zCurrentRow;   /* Current output row */
   10998   int szRow;                 /* Length of the zCurrentRow string */
   10999   sqlite3_stmt *pStmt;       /* Current statement */
   11000   sqlite3_int64 iRowid;      /* The rowid */
   11001   int ePhase;                /* Current phase */
   11002   int j;                     /* inter-phase counter */
   11003 };
   11004 
   11005 /* Values for ePhase:
   11006 */
   11007 #define COMPLETION_FIRST_PHASE   1
   11008 #define COMPLETION_KEYWORDS      1
   11009 #define COMPLETION_PRAGMAS       2
   11010 #define COMPLETION_FUNCTIONS     3
   11011 #define COMPLETION_COLLATIONS    4
   11012 #define COMPLETION_INDEXES       5
   11013 #define COMPLETION_TRIGGERS      6
   11014 #define COMPLETION_DATABASES     7
   11015 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
   11016 #define COMPLETION_COLUMNS       9
   11017 #define COMPLETION_MODULES       10
   11018 #define COMPLETION_EOF           11
   11019 
   11020 /*
   11021 ** The completionConnect() method is invoked to create a new
   11022 ** completion_vtab that describes the completion virtual table.
   11023 **
   11024 ** Think of this routine as the constructor for completion_vtab objects.
   11025 **
   11026 ** All this routine needs to do is:
   11027 **
   11028 **    (1) Allocate the completion_vtab object and initialize all fields.
   11029 **
   11030 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
   11031 **        result set of queries against completion will look like.
   11032 */
   11033 static int completionConnect(
   11034   sqlite3 *db,
   11035   void *pAux,
   11036   int argc, const char *const*argv,
   11037   sqlite3_vtab **ppVtab,
   11038   char **pzErr
   11039 ){
   11040   completion_vtab *pNew;
   11041   int rc;
   11042 
   11043   (void)(pAux);    /* Unused parameter */
   11044   (void)(argc);    /* Unused parameter */
   11045   (void)(argv);    /* Unused parameter */
   11046   (void)(pzErr);   /* Unused parameter */
   11047 
   11048 /* Column numbers */
   11049 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
   11050 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
   11051 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
   11052 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
   11053 
   11054   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
   11055   rc = sqlite3_declare_vtab(db,
   11056       "CREATE TABLE x("
   11057       "  candidate TEXT,"
   11058       "  prefix TEXT HIDDEN,"
   11059       "  wholeline TEXT HIDDEN,"
   11060       "  phase INT HIDDEN"        /* Used for debugging only */
   11061       ")");
   11062   if( rc==SQLITE_OK ){
   11063     pNew = sqlite3_malloc64( sizeof(*pNew) );
   11064     *ppVtab = (sqlite3_vtab*)pNew;
   11065     if( pNew==0 ) return SQLITE_NOMEM;
   11066     memset(pNew, 0, sizeof(*pNew));
   11067     pNew->db = db;
   11068   }
   11069   return rc;
   11070 }
   11071 
   11072 /*
   11073 ** This method is the destructor for completion_cursor objects.
   11074 */
   11075 static int completionDisconnect(sqlite3_vtab *pVtab){
   11076   sqlite3_free(pVtab);
   11077   return SQLITE_OK;
   11078 }
   11079 
   11080 /*
   11081 ** Constructor for a new completion_cursor object.
   11082 */
   11083 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
   11084   completion_cursor *pCur;
   11085   pCur = sqlite3_malloc64( sizeof(*pCur) );
   11086   if( pCur==0 ) return SQLITE_NOMEM;
   11087   memset(pCur, 0, sizeof(*pCur));
   11088   pCur->db = ((completion_vtab*)p)->db;
   11089   *ppCursor = &pCur->base;
   11090   return SQLITE_OK;
   11091 }
   11092 
   11093 /*
   11094 ** Reset the completion_cursor.
   11095 */
   11096 static void completionCursorReset(completion_cursor *pCur){
   11097   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
   11098   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
   11099   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
   11100   pCur->j = 0;
   11101 }
   11102 
   11103 /*
   11104 ** Destructor for a completion_cursor.
   11105 */
   11106 static int completionClose(sqlite3_vtab_cursor *cur){
   11107   completionCursorReset((completion_cursor*)cur);
   11108   sqlite3_free(cur);
   11109   return SQLITE_OK;
   11110 }
   11111 
   11112 /*
   11113 ** Advance a completion_cursor to its next row of output.
   11114 **
   11115 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
   11116 ** record the current state of the scan.  This routine sets ->zCurrentRow
   11117 ** to the current row of output and then returns.  If no more rows remain,
   11118 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
   11119 ** table that has reached the end of its scan.
   11120 **
   11121 ** The current implementation just lists potential identifiers and
   11122 ** keywords and filters them by zPrefix.  Future enhancements should
   11123 ** take zLine into account to try to restrict the set of identifiers and
   11124 ** keywords based on what would be legal at the current point of input.
   11125 */
   11126 static int completionNext(sqlite3_vtab_cursor *cur){
   11127   completion_cursor *pCur = (completion_cursor*)cur;
   11128   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
   11129   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
   11130   int rc;
   11131   pCur->iRowid++;
   11132   while( pCur->ePhase!=COMPLETION_EOF ){
   11133     switch( pCur->ePhase ){
   11134       case COMPLETION_KEYWORDS: {
   11135         if( pCur->j >= sqlite3_keyword_count() ){
   11136           pCur->zCurrentRow = 0;
   11137           pCur->ePhase = COMPLETION_DATABASES;
   11138         }else{
   11139           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
   11140         }
   11141         iCol = -1;
   11142         break;
   11143       }
   11144       case COMPLETION_DATABASES: {
   11145         if( pCur->pStmt==0 ){
   11146           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
   11147                              &pCur->pStmt, 0);
   11148         }
   11149         iCol = 1;
   11150         eNextPhase = COMPLETION_TABLES;
   11151         break;
   11152       }
   11153       case COMPLETION_TABLES: {
   11154         if( pCur->pStmt==0 ){
   11155           sqlite3_stmt *pS2;
   11156           sqlite3_str* pStr = sqlite3_str_new(pCur->db);
   11157           char *zSql = 0;
   11158           const char *zSep = "";
   11159           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
   11160           while( sqlite3_step(pS2)==SQLITE_ROW ){
   11161             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
   11162             sqlite3_str_appendf(pStr,
   11163                "%s"
   11164                "SELECT name FROM \"%w\".sqlite_schema",
   11165                zSep, zDb
   11166             );
   11167             zSep = " UNION ";
   11168           }
   11169           rc = sqlite3_finalize(pS2);
   11170           zSql = sqlite3_str_finish(pStr);
   11171           if( zSql==0 ) return SQLITE_NOMEM;
   11172           if( rc==SQLITE_OK ){
   11173             sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
   11174           }
   11175           sqlite3_free(zSql);
   11176           if( rc ) return rc;
   11177         }
   11178         iCol = 0;
   11179         eNextPhase = COMPLETION_COLUMNS;
   11180         break;
   11181       }
   11182       case COMPLETION_COLUMNS: {
   11183         if( pCur->pStmt==0 ){
   11184           sqlite3_stmt *pS2;
   11185           sqlite3_str *pStr = sqlite3_str_new(pCur->db);
   11186           char *zSql = 0;
   11187           const char *zSep = "";
   11188           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
   11189           while( sqlite3_step(pS2)==SQLITE_ROW ){
   11190             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
   11191             sqlite3_str_appendf(pStr,
   11192                "%s"
   11193                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
   11194                        " JOIN pragma_table_xinfo(sm.name,%Q) AS pti"
   11195                " WHERE sm.type='table'",
   11196                zSep, zDb, zDb
   11197             );
   11198             zSep = " UNION ";
   11199           }
   11200           rc = sqlite3_finalize(pS2);
   11201           zSql = sqlite3_str_finish(pStr);
   11202           if( zSql==0 ) return SQLITE_NOMEM;
   11203           if( rc==SQLITE_OK ){
   11204             sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
   11205           }
   11206           sqlite3_free(zSql);
   11207           if( rc ) return rc;
   11208         }
   11209         iCol = 0;
   11210         eNextPhase = COMPLETION_EOF;
   11211         break;
   11212       }
   11213     }
   11214     if( iCol<0 ){
   11215       /* This case is when the phase presets zCurrentRow */
   11216       if( pCur->zCurrentRow==0 ) continue;
   11217     }else{
   11218       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
   11219         /* Extract the next row of content */
   11220         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
   11221         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
   11222       }else{
   11223         /* When all rows are finished, advance to the next phase */
   11224         rc = sqlite3_finalize(pCur->pStmt);
   11225         pCur->pStmt = 0;
   11226         pCur->ePhase = eNextPhase;
   11227         if( rc ) return rc;
   11228         continue;
   11229       }
   11230     }
   11231     if( pCur->nPrefix==0 ) break;
   11232     if( pCur->nPrefix<=pCur->szRow
   11233      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
   11234     ){
   11235       break;
   11236     }
   11237   }
   11238 
   11239   return SQLITE_OK;
   11240 }
   11241 
   11242 /*
   11243 ** Return values of columns for the row at which the completion_cursor
   11244 ** is currently pointing.
   11245 */
   11246 static int completionColumn(
   11247   sqlite3_vtab_cursor *cur,   /* The cursor */
   11248   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   11249   int i                       /* Which column to return */
   11250 ){
   11251   completion_cursor *pCur = (completion_cursor*)cur;
   11252   switch( i ){
   11253     case COMPLETION_COLUMN_CANDIDATE: {
   11254       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
   11255       break;
   11256     }
   11257     case COMPLETION_COLUMN_PREFIX: {
   11258       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
   11259       break;
   11260     }
   11261     case COMPLETION_COLUMN_WHOLELINE: {
   11262       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
   11263       break;
   11264     }
   11265     case COMPLETION_COLUMN_PHASE: {
   11266       sqlite3_result_int(ctx, pCur->ePhase);
   11267       break;
   11268     }
   11269   }
   11270   return SQLITE_OK;
   11271 }
   11272 
   11273 /*
   11274 ** Return the rowid for the current row.  In this implementation, the
   11275 ** rowid is the same as the output value.
   11276 */
   11277 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   11278   completion_cursor *pCur = (completion_cursor*)cur;
   11279   *pRowid = pCur->iRowid;
   11280   return SQLITE_OK;
   11281 }
   11282 
   11283 /*
   11284 ** Return TRUE if the cursor has been moved off of the last
   11285 ** row of output.
   11286 */
   11287 static int completionEof(sqlite3_vtab_cursor *cur){
   11288   completion_cursor *pCur = (completion_cursor*)cur;
   11289   return pCur->ePhase >= COMPLETION_EOF;
   11290 }
   11291 
   11292 /*
   11293 ** This method is called to "rewind" the completion_cursor object back
   11294 ** to the first row of output.  This method is always called at least
   11295 ** once prior to any call to completionColumn() or completionRowid() or
   11296 ** completionEof().
   11297 */
   11298 static int completionFilter(
   11299   sqlite3_vtab_cursor *pVtabCursor,
   11300   int idxNum, const char *idxStr,
   11301   int argc, sqlite3_value **argv
   11302 ){
   11303   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
   11304   int iArg = 0;
   11305   (void)(idxStr);   /* Unused parameter */
   11306   (void)(argc);     /* Unused parameter */
   11307   completionCursorReset(pCur);
   11308   if( idxNum & 1 ){
   11309     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
   11310     if( pCur->nPrefix>0 ){
   11311       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
   11312       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
   11313       pCur->nPrefix = (int)strlen(pCur->zPrefix);
   11314     }
   11315     iArg = 1;
   11316   }
   11317   if( idxNum & 2 ){
   11318     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
   11319     if( pCur->nLine>0 ){
   11320       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
   11321       if( pCur->zLine==0 ) return SQLITE_NOMEM;
   11322       pCur->nLine = (int)strlen(pCur->zLine);
   11323     }
   11324   }
   11325   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
   11326     int i = pCur->nLine;
   11327     while( i>0 && (IsAlnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
   11328       i--;
   11329     }
   11330     pCur->nPrefix = pCur->nLine - i;
   11331     if( pCur->nPrefix>0 ){
   11332       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
   11333       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
   11334       pCur->nPrefix = (int)strlen(pCur->zPrefix);
   11335     }
   11336   }
   11337   pCur->iRowid = 0;
   11338   pCur->ePhase = COMPLETION_FIRST_PHASE;
   11339   return completionNext(pVtabCursor);
   11340 }
   11341 
   11342 /*
   11343 ** SQLite will invoke this method one or more times while planning a query
   11344 ** that uses the completion virtual table.  This routine needs to create
   11345 ** a query plan for each invocation and compute an estimated cost for that
   11346 ** plan.
   11347 **
   11348 ** There are two hidden parameters that act as arguments to the table-valued
   11349 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
   11350 ** is available and bit 1 is set if "wholeline" is available.
   11351 */
   11352 static int completionBestIndex(
   11353   sqlite3_vtab *tab,
   11354   sqlite3_index_info *pIdxInfo
   11355 ){
   11356   int i;                 /* Loop over constraints */
   11357   int idxNum = 0;        /* The query plan bitmask */
   11358   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
   11359   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
   11360   int nArg = 0;          /* Number of arguments that completeFilter() expects */
   11361   const struct sqlite3_index_constraint *pConstraint;
   11362 
   11363   (void)(tab);    /* Unused parameter */
   11364   pConstraint = pIdxInfo->aConstraint;
   11365   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
   11366     if( pConstraint->usable==0 ) continue;
   11367     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
   11368     switch( pConstraint->iColumn ){
   11369       case COMPLETION_COLUMN_PREFIX:
   11370         prefixIdx = i;
   11371         idxNum |= 1;
   11372         break;
   11373       case COMPLETION_COLUMN_WHOLELINE:
   11374         wholelineIdx = i;
   11375         idxNum |= 2;
   11376         break;
   11377     }
   11378   }
   11379   if( prefixIdx>=0 ){
   11380     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
   11381     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
   11382   }
   11383   if( wholelineIdx>=0 ){
   11384     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
   11385     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
   11386   }
   11387   pIdxInfo->idxNum = idxNum;
   11388   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
   11389   pIdxInfo->estimatedRows = 500 - 100*nArg;
   11390   return SQLITE_OK;
   11391 }
   11392 
   11393 /*
   11394 ** This following structure defines all the methods for the
   11395 ** completion virtual table.
   11396 */
   11397 static sqlite3_module completionModule = {
   11398   0,                         /* iVersion */
   11399   0,                         /* xCreate */
   11400   completionConnect,         /* xConnect */
   11401   completionBestIndex,       /* xBestIndex */
   11402   completionDisconnect,      /* xDisconnect */
   11403   0,                         /* xDestroy */
   11404   completionOpen,            /* xOpen - open a cursor */
   11405   completionClose,           /* xClose - close a cursor */
   11406   completionFilter,          /* xFilter - configure scan constraints */
   11407   completionNext,            /* xNext - advance a cursor */
   11408   completionEof,             /* xEof - check for end of scan */
   11409   completionColumn,          /* xColumn - read data */
   11410   completionRowid,           /* xRowid - read data */
   11411   0,                         /* xUpdate */
   11412   0,                         /* xBegin */
   11413   0,                         /* xSync */
   11414   0,                         /* xCommit */
   11415   0,                         /* xRollback */
   11416   0,                         /* xFindMethod */
   11417   0,                         /* xRename */
   11418   0,                         /* xSavepoint */
   11419   0,                         /* xRelease */
   11420   0,                         /* xRollbackTo */
   11421   0,                         /* xShadowName */
   11422   0                          /* xIntegrity */
   11423 };
   11424 
   11425 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   11426 
   11427 static int sqlite3CompletionVtabInit(sqlite3 *db){
   11428   int rc = SQLITE_OK;
   11429 #ifndef SQLITE_OMIT_VIRTUALTABLE
   11430   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
   11431 #endif
   11432   return rc;
   11433 }
   11434 
   11435 #ifdef _WIN32
   11436 
   11437 #endif
   11438 static int sqlite3_completion_init(
   11439   sqlite3 *db,
   11440   char **pzErrMsg,
   11441   const sqlite3_api_routines *pApi
   11442 ){
   11443   int rc = SQLITE_OK;
   11444   SQLITE_EXTENSION_INIT2(pApi);
   11445   (void)(pzErrMsg);  /* Unused parameter */
   11446 #ifndef SQLITE_OMIT_VIRTUALTABLE
   11447   rc = sqlite3CompletionVtabInit(db);
   11448 #endif
   11449   return rc;
   11450 }
   11451 
   11452 /************************* End ext/misc/completion.c ********************/
   11453 /************************* Begin ext/misc/appendvfs.c ******************/
   11454 /*
   11455 ** 2017-10-20
   11456 **
   11457 ** The author disclaims copyright to this source code.  In place of
   11458 ** a legal notice, here is a blessing:
   11459 **
   11460 **    May you do good and not evil.
   11461 **    May you find forgiveness for yourself and forgive others.
   11462 **    May you share freely, never taking more than you give.
   11463 **
   11464 ******************************************************************************
   11465 **
   11466 ** This file implements a VFS shim that allows an SQLite database to be
   11467 ** appended onto the end of some other file, such as an executable.
   11468 **
   11469 ** A special record must appear at the end of the file that identifies the
   11470 ** file as an appended database and provides the offset to the first page
   11471 ** of the exposed content. (Or, it is the length of the content prefix.)
   11472 ** For best performance page 1 should be located at a disk page boundary,
   11473 ** though that is not required.
   11474 **
   11475 ** When opening a database using this VFS, the connection might treat
   11476 ** the file as an ordinary SQLite database, or it might treat it as a
   11477 ** database appended onto some other file.  The decision is made by
   11478 ** applying the following rules in order:
   11479 **
   11480 **  (1)  An empty file is an ordinary database.
   11481 **
   11482 **  (2)  If the file ends with the appendvfs trailer string
   11483 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
   11484 **
   11485 **  (3)  If the file begins with the standard SQLite prefix string
   11486 **       "SQLite format 3", that file is an ordinary database.
   11487 **
   11488 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
   11489 **       set, then a new database is appended to the already existing file.
   11490 **
   11491 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
   11492 **
   11493 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
   11494 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
   11495 ** This VFS will not read or write past the 1GiB mark.  This restriction
   11496 ** might be lifted in future versions.  For now, if you need a larger
   11497 ** database, then keep it in a separate file.
   11498 **
   11499 ** If the file being opened is a plain database (not an appended one), then
   11500 ** this shim is a pass-through into the default underlying VFS. (rule 3)
   11501 **/
   11502 /* #include "sqlite3ext.h" */
   11503 SQLITE_EXTENSION_INIT1
   11504 #include <string.h>
   11505 #include <assert.h>
   11506 
   11507 /* The append mark at the end of the database is:
   11508 **
   11509 **     Start-Of-SQLite3-NNNNNNNN
   11510 **     123456789 123456789 12345
   11511 **
   11512 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
   11513 ** the offset to page 1, and also the length of the prefix content.
   11514 */
   11515 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
   11516 #define APND_MARK_PREFIX_SZ  17
   11517 #define APND_MARK_FOS_SZ      8
   11518 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
   11519 
   11520 /*
   11521 ** Maximum size of the combined prefix + database + append-mark.  This
   11522 ** must be less than 0x40000000 to avoid locking issues on Windows.
   11523 */
   11524 #define APND_MAX_SIZE  (0x40000000)
   11525 
   11526 /*
   11527 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
   11528 */
   11529 #ifndef APND_ROUNDUP
   11530 #define APND_ROUNDUP 4096
   11531 #endif
   11532 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
   11533 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
   11534 
   11535 /*
   11536 ** Forward declaration of objects used by this utility
   11537 */
   11538 typedef struct sqlite3_vfs ApndVfs;
   11539 typedef struct ApndFile ApndFile;
   11540 
   11541 /* Access to a lower-level VFS that (might) implement dynamic loading,
   11542 ** access to randomness, etc.
   11543 */
   11544 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
   11545 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
   11546 
   11547 /* An open appendvfs file
   11548 **
   11549 ** An instance of this structure describes the appended database file.
   11550 ** A separate sqlite3_file object is always appended. The appended
   11551 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
   11552 ** the entire file, including the prefix, the database, and the
   11553 ** append-mark.
   11554 **
   11555 ** The structure of an AppendVFS database is like this:
   11556 **
   11557 **   +-------------+---------+----------+-------------+
   11558 **   | prefix-file | padding | database | append-mark |
   11559 **   +-------------+---------+----------+-------------+
   11560 **                           ^          ^
   11561 **                           |          |
   11562 **                         iPgOne      iMark
   11563 **
   11564 **
   11565 ** "prefix file" -  file onto which the database has been appended.
   11566 ** "padding"     -  zero or more bytes inserted so that "database"
   11567 **                  starts on an APND_ROUNDUP boundary
   11568 ** "database"    -  The SQLite database file
   11569 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
   11570 **                  the offset from the start of prefix-file to the start
   11571 **                  of "database".
   11572 **
   11573 ** The size of the database is iMark - iPgOne.
   11574 **
   11575 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
   11576 ** of iPgOne stored as a big-ending 64-bit integer.
   11577 **
   11578 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
   11579 ** Or, iMark is -1 to indicate that it has not yet been written.
   11580 */
   11581 struct ApndFile {
   11582   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
   11583   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
   11584   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
   11585   /* Always followed by another sqlite3_file that describes the whole file */
   11586 };
   11587 
   11588 /*
   11589 ** Methods for ApndFile
   11590 */
   11591 static int apndClose(sqlite3_file*);
   11592 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   11593 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
   11594 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
   11595 static int apndSync(sqlite3_file*, int flags);
   11596 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
   11597 static int apndLock(sqlite3_file*, int);
   11598 static int apndUnlock(sqlite3_file*, int);
   11599 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
   11600 static int apndFileControl(sqlite3_file*, int op, void *pArg);
   11601 static int apndSectorSize(sqlite3_file*);
   11602 static int apndDeviceCharacteristics(sqlite3_file*);
   11603 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   11604 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
   11605 static void apndShmBarrier(sqlite3_file*);
   11606 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
   11607 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
   11608 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
   11609 
   11610 /*
   11611 ** Methods for ApndVfs
   11612 */
   11613 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
   11614 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
   11615 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
   11616 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
   11617 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
   11618 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
   11619 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
   11620 static void apndDlClose(sqlite3_vfs*, void*);
   11621 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
   11622 static int apndSleep(sqlite3_vfs*, int microseconds);
   11623 static int apndCurrentTime(sqlite3_vfs*, double*);
   11624 static int apndGetLastError(sqlite3_vfs*, int, char *);
   11625 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
   11626 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
   11627 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
   11628 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
   11629 
   11630 static sqlite3_vfs apnd_vfs = {
   11631   3,                            /* iVersion (set when registered) */
   11632   0,                            /* szOsFile (set when registered) */
   11633   1024,                         /* mxPathname */
   11634   0,                            /* pNext */
   11635   "apndvfs",                    /* zName */
   11636   0,                            /* pAppData (set when registered) */
   11637   apndOpen,                     /* xOpen */
   11638   apndDelete,                   /* xDelete */
   11639   apndAccess,                   /* xAccess */
   11640   apndFullPathname,             /* xFullPathname */
   11641   apndDlOpen,                   /* xDlOpen */
   11642   apndDlError,                  /* xDlError */
   11643   apndDlSym,                    /* xDlSym */
   11644   apndDlClose,                  /* xDlClose */
   11645   apndRandomness,               /* xRandomness */
   11646   apndSleep,                    /* xSleep */
   11647   apndCurrentTime,              /* xCurrentTime */
   11648   apndGetLastError,             /* xGetLastError */
   11649   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
   11650   apndSetSystemCall,            /* xSetSystemCall */
   11651   apndGetSystemCall,            /* xGetSystemCall */
   11652   apndNextSystemCall            /* xNextSystemCall */
   11653 };
   11654 
   11655 static const sqlite3_io_methods apnd_io_methods = {
   11656   3,                              /* iVersion */
   11657   apndClose,                      /* xClose */
   11658   apndRead,                       /* xRead */
   11659   apndWrite,                      /* xWrite */
   11660   apndTruncate,                   /* xTruncate */
   11661   apndSync,                       /* xSync */
   11662   apndFileSize,                   /* xFileSize */
   11663   apndLock,                       /* xLock */
   11664   apndUnlock,                     /* xUnlock */
   11665   apndCheckReservedLock,          /* xCheckReservedLock */
   11666   apndFileControl,                /* xFileControl */
   11667   apndSectorSize,                 /* xSectorSize */
   11668   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
   11669   apndShmMap,                     /* xShmMap */
   11670   apndShmLock,                    /* xShmLock */
   11671   apndShmBarrier,                 /* xShmBarrier */
   11672   apndShmUnmap,                   /* xShmUnmap */
   11673   apndFetch,                      /* xFetch */
   11674   apndUnfetch                     /* xUnfetch */
   11675 };
   11676 
   11677 /*
   11678 ** Close an apnd-file.
   11679 */
   11680 static int apndClose(sqlite3_file *pFile){
   11681   pFile = ORIGFILE(pFile);
   11682   return pFile->pMethods->xClose(pFile);
   11683 }
   11684 
   11685 /*
   11686 ** Read data from an apnd-file.
   11687 */
   11688 static int apndRead(
   11689   sqlite3_file *pFile,
   11690   void *zBuf,
   11691   int iAmt,
   11692   sqlite_int64 iOfst
   11693 ){
   11694   ApndFile *paf = (ApndFile *)pFile;
   11695   pFile = ORIGFILE(pFile);
   11696   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
   11697 }
   11698 
   11699 /*
   11700 ** Add the append-mark onto what should become the end of the file.
   11701 *  If and only if this succeeds, internal ApndFile.iMark is updated.
   11702 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
   11703 */
   11704 static int apndWriteMark(
   11705   ApndFile *paf,
   11706   sqlite3_file *pFile,
   11707   sqlite_int64 iWriteEnd
   11708 ){
   11709   sqlite_int64 iPgOne = paf->iPgOne;
   11710   unsigned char a[APND_MARK_SIZE];
   11711   int i = APND_MARK_FOS_SZ;
   11712   int rc;
   11713   assert(pFile == ORIGFILE(paf));
   11714   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
   11715   while( --i >= 0 ){
   11716     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
   11717     iPgOne >>= 8;
   11718   }
   11719   iWriteEnd += paf->iPgOne;
   11720   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
   11721                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
   11722     paf->iMark = iWriteEnd;
   11723   }
   11724   return rc;
   11725 }
   11726 
   11727 /*
   11728 ** Write data to an apnd-file.
   11729 */
   11730 static int apndWrite(
   11731   sqlite3_file *pFile,
   11732   const void *zBuf,
   11733   int iAmt,
   11734   sqlite_int64 iOfst
   11735 ){
   11736   ApndFile *paf = (ApndFile *)pFile;
   11737   sqlite_int64 iWriteEnd = iOfst + iAmt;
   11738   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
   11739   pFile = ORIGFILE(pFile);
   11740   /* If append-mark is absent or will be overwritten, write it. */
   11741   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
   11742     int rc = apndWriteMark(paf, pFile, iWriteEnd);
   11743     if( SQLITE_OK!=rc ) return rc;
   11744   }
   11745   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
   11746 }
   11747 
   11748 /*
   11749 ** Truncate an apnd-file.
   11750 */
   11751 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
   11752   ApndFile *paf = (ApndFile *)pFile;
   11753   pFile = ORIGFILE(pFile);
   11754   /* The append mark goes out first so truncate failure does not lose it. */
   11755   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
   11756   /* Truncate underlying file just past append mark */
   11757   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
   11758 }
   11759 
   11760 /*
   11761 ** Sync an apnd-file.
   11762 */
   11763 static int apndSync(sqlite3_file *pFile, int flags){
   11764   pFile = ORIGFILE(pFile);
   11765   return pFile->pMethods->xSync(pFile, flags);
   11766 }
   11767 
   11768 /*
   11769 ** Return the current file-size of an apnd-file.
   11770 ** If the append mark is not yet there, the file-size is 0.
   11771 */
   11772 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
   11773   ApndFile *paf = (ApndFile *)pFile;
   11774   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
   11775   return SQLITE_OK;
   11776 }
   11777 
   11778 /*
   11779 ** Lock an apnd-file.
   11780 */
   11781 static int apndLock(sqlite3_file *pFile, int eLock){
   11782   pFile = ORIGFILE(pFile);
   11783   return pFile->pMethods->xLock(pFile, eLock);
   11784 }
   11785 
   11786 /*
   11787 ** Unlock an apnd-file.
   11788 */
   11789 static int apndUnlock(sqlite3_file *pFile, int eLock){
   11790   pFile = ORIGFILE(pFile);
   11791   return pFile->pMethods->xUnlock(pFile, eLock);
   11792 }
   11793 
   11794 /*
   11795 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
   11796 */
   11797 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
   11798   pFile = ORIGFILE(pFile);
   11799   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
   11800 }
   11801 
   11802 /*
   11803 ** File control method. For custom operations on an apnd-file.
   11804 */
   11805 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
   11806   ApndFile *paf = (ApndFile *)pFile;
   11807   int rc;
   11808   pFile = ORIGFILE(pFile);
   11809   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
   11810   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
   11811   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
   11812     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
   11813   }
   11814   return rc;
   11815 }
   11816 
   11817 /*
   11818 ** Return the sector-size in bytes for an apnd-file.
   11819 */
   11820 static int apndSectorSize(sqlite3_file *pFile){
   11821   pFile = ORIGFILE(pFile);
   11822   return pFile->pMethods->xSectorSize(pFile);
   11823 }
   11824 
   11825 /*
   11826 ** Return the device characteristic flags supported by an apnd-file.
   11827 */
   11828 static int apndDeviceCharacteristics(sqlite3_file *pFile){
   11829   pFile = ORIGFILE(pFile);
   11830   return pFile->pMethods->xDeviceCharacteristics(pFile);
   11831 }
   11832 
   11833 /* Create a shared memory file mapping */
   11834 static int apndShmMap(
   11835   sqlite3_file *pFile,
   11836   int iPg,
   11837   int pgsz,
   11838   int bExtend,
   11839   void volatile **pp
   11840 ){
   11841   pFile = ORIGFILE(pFile);
   11842   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
   11843 }
   11844 
   11845 /* Perform locking on a shared-memory segment */
   11846 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
   11847   pFile = ORIGFILE(pFile);
   11848   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
   11849 }
   11850 
   11851 /* Memory barrier operation on shared memory */
   11852 static void apndShmBarrier(sqlite3_file *pFile){
   11853   pFile = ORIGFILE(pFile);
   11854   pFile->pMethods->xShmBarrier(pFile);
   11855 }
   11856 
   11857 /* Unmap a shared memory segment */
   11858 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
   11859   pFile = ORIGFILE(pFile);
   11860   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
   11861 }
   11862 
   11863 /* Fetch a page of a memory-mapped file */
   11864 static int apndFetch(
   11865   sqlite3_file *pFile,
   11866   sqlite3_int64 iOfst,
   11867   int iAmt,
   11868   void **pp
   11869 ){
   11870   ApndFile *p = (ApndFile *)pFile;
   11871   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
   11872     return SQLITE_IOERR; /* Cannot read what is not yet there. */
   11873   }
   11874   pFile = ORIGFILE(pFile);
   11875   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
   11876 }
   11877 
   11878 /* Release a memory-mapped page */
   11879 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
   11880   ApndFile *p = (ApndFile *)pFile;
   11881   pFile = ORIGFILE(pFile);
   11882   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
   11883 }
   11884 
   11885 /*
   11886 ** Try to read the append-mark off the end of a file.  Return the
   11887 ** start of the appended database if the append-mark is present.
   11888 ** If there is no valid append-mark, return -1;
   11889 **
   11890 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
   11891 ** indicates that the appended database contains at least one page.  The
   11892 ** start-of-database value must be a multiple of 512.
   11893 */
   11894 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
   11895   int rc, i;
   11896   sqlite3_int64 iMark;
   11897   int msbs = 8 * (APND_MARK_FOS_SZ-1);
   11898   unsigned char a[APND_MARK_SIZE];
   11899 
   11900   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
   11901   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
   11902   if( rc ) return -1;
   11903   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
   11904   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
   11905   for(i=1; i<8; i++){
   11906     msbs -= 8;
   11907     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
   11908   }
   11909   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
   11910   if( iMark & 0x1ff ) return -1;
   11911   return iMark;
   11912 }
   11913 
   11914 static const char apvfsSqliteHdr[] = "SQLite format 3";
   11915 /*
   11916 ** Check to see if the file is an appendvfs SQLite database file.
   11917 ** Return true iff it is such. Parameter sz is the file's size.
   11918 */
   11919 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
   11920   int rc;
   11921   char zHdr[16];
   11922   sqlite3_int64 iMark = apndReadMark(sz, pFile);
   11923   if( iMark>=0 ){
   11924     /* If file has the correct end-marker, the expected odd size, and the
   11925     ** SQLite DB type marker where the end-marker puts it, then it
   11926     ** is an appendvfs database.
   11927     */
   11928     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
   11929     if( SQLITE_OK==rc
   11930      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
   11931      && (sz & 0x1ff) == APND_MARK_SIZE
   11932      && sz>=512+APND_MARK_SIZE
   11933     ){
   11934       return 1; /* It's an appendvfs database */
   11935     }
   11936   }
   11937   return 0;
   11938 }
   11939 
   11940 /*
   11941 ** Check to see if the file is an ordinary SQLite database file.
   11942 ** Return true iff so. Parameter sz is the file's size.
   11943 */
   11944 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
   11945   char zHdr[16];
   11946   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
   11947    || (sz & 0x1ff) != 0
   11948    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
   11949    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
   11950   ){
   11951     return 0;
   11952   }else{
   11953     return 1;
   11954   }
   11955 }
   11956 
   11957 /*
   11958 ** Open an apnd file handle.
   11959 */
   11960 static int apndOpen(
   11961   sqlite3_vfs *pApndVfs,
   11962   const char *zName,
   11963   sqlite3_file *pFile,
   11964   int flags,
   11965   int *pOutFlags
   11966 ){
   11967   ApndFile *pApndFile = (ApndFile*)pFile;
   11968   sqlite3_file *pBaseFile = ORIGFILE(pFile);
   11969   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
   11970   int rc;
   11971   sqlite3_int64 sz = 0;
   11972   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
   11973     /* The appendvfs is not to be used for transient or temporary databases.
   11974     ** Just use the base VFS open to initialize the given file object and
   11975     ** open the underlying file. (Appendvfs is then unused for this file.)
   11976     */
   11977     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
   11978   }
   11979   memset(pApndFile, 0, sizeof(ApndFile));
   11980   pFile->pMethods = &apnd_io_methods;
   11981   pApndFile->iMark = -1;    /* Append mark not yet written */
   11982 
   11983   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
   11984   if( rc==SQLITE_OK ){
   11985     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
   11986     if( rc ){
   11987       pBaseFile->pMethods->xClose(pBaseFile);
   11988     }
   11989   }
   11990   if( rc ){
   11991     pFile->pMethods = 0;
   11992     return rc;
   11993   }
   11994   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
   11995     /* The file being opened appears to be just an ordinary DB. Copy
   11996     ** the base dispatch-table so this instance mimics the base VFS.
   11997     */
   11998     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
   11999     return SQLITE_OK;
   12000   }
   12001   pApndFile->iPgOne = apndReadMark(sz, pFile);
   12002   if( pApndFile->iPgOne>=0 ){
   12003     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
   12004     return SQLITE_OK;
   12005   }
   12006   if( (flags & SQLITE_OPEN_CREATE)==0 ){
   12007     pBaseFile->pMethods->xClose(pBaseFile);
   12008     rc = SQLITE_CANTOPEN;
   12009     pFile->pMethods = 0;
   12010   }else{
   12011     /* Round newly added appendvfs location to #define'd page boundary.
   12012     ** Note that nothing has yet been written to the underlying file.
   12013     ** The append mark will be written along with first content write.
   12014     ** Until then, paf->iMark value indicates it is not yet written.
   12015     */
   12016     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
   12017   }
   12018   return rc;
   12019 }
   12020 
   12021 /*
   12022 ** Delete an apnd file.
   12023 ** For an appendvfs, this could mean delete the appendvfs portion,
   12024 ** leaving the appendee as it was before it gained an appendvfs.
   12025 ** For now, this code deletes the underlying file too.
   12026 */
   12027 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   12028   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
   12029 }
   12030 
   12031 /*
   12032 ** All other VFS methods are pass-thrus.
   12033 */
   12034 static int apndAccess(
   12035   sqlite3_vfs *pVfs,
   12036   const char *zPath,
   12037   int flags,
   12038   int *pResOut
   12039 ){
   12040   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
   12041 }
   12042 static int apndFullPathname(
   12043   sqlite3_vfs *pVfs,
   12044   const char *zPath,
   12045   int nOut,
   12046   char *zOut
   12047 ){
   12048   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
   12049 }
   12050 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   12051   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
   12052 }
   12053 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
   12054   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
   12055 }
   12056 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
   12057   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
   12058 }
   12059 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
   12060   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
   12061 }
   12062 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   12063   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
   12064 }
   12065 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
   12066   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
   12067 }
   12068 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
   12069   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
   12070 }
   12071 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
   12072   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
   12073 }
   12074 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
   12075   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
   12076 }
   12077 static int apndSetSystemCall(
   12078   sqlite3_vfs *pVfs,
   12079   const char *zName,
   12080   sqlite3_syscall_ptr pCall
   12081 ){
   12082   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
   12083 }
   12084 static sqlite3_syscall_ptr apndGetSystemCall(
   12085   sqlite3_vfs *pVfs,
   12086   const char *zName
   12087 ){
   12088   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
   12089 }
   12090 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
   12091   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
   12092 }
   12093 
   12094 
   12095 #ifdef _WIN32
   12096 
   12097 #endif
   12098 /*
   12099 ** This routine is called when the extension is loaded.
   12100 ** Register the new VFS.
   12101 */
   12102 static int sqlite3_appendvfs_init(
   12103   sqlite3 *db,
   12104   char **pzErrMsg,
   12105   const sqlite3_api_routines *pApi
   12106 ){
   12107   int rc = SQLITE_OK;
   12108   sqlite3_vfs *pOrig;
   12109   SQLITE_EXTENSION_INIT2(pApi);
   12110   (void)pzErrMsg;
   12111   (void)db;
   12112   pOrig = sqlite3_vfs_find(0);
   12113   if( pOrig==0 ) return SQLITE_ERROR;
   12114   apnd_vfs.iVersion = pOrig->iVersion;
   12115   apnd_vfs.pAppData = pOrig;
   12116   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
   12117   rc = sqlite3_vfs_register(&apnd_vfs, 0);
   12118 #ifdef APPENDVFS_TEST
   12119   if( rc==SQLITE_OK ){
   12120     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
   12121   }
   12122 #endif
   12123   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
   12124   return rc;
   12125 }
   12126 
   12127 /************************* End ext/misc/appendvfs.c ********************/
   12128 #endif
   12129 #ifdef SQLITE_HAVE_ZLIB
   12130 /************************* Begin ext/misc/zipfile.c ******************/
   12131 /*
   12132 ** 2017-12-26
   12133 **
   12134 ** The author disclaims copyright to this source code.  In place of
   12135 ** a legal notice, here is a blessing:
   12136 **
   12137 **    May you do good and not evil.
   12138 **    May you find forgiveness for yourself and forgive others.
   12139 **    May you share freely, never taking more than you give.
   12140 **
   12141 ******************************************************************************
   12142 **
   12143 ** This file implements a virtual table for reading and writing ZIP archive
   12144 ** files.
   12145 **
   12146 ** Usage example:
   12147 **
   12148 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
   12149 **
   12150 ** Current limitations:
   12151 **
   12152 **    *  No support for encryption
   12153 **    *  No support for ZIP archives spanning multiple files
   12154 **    *  No support for zip64 extensions
   12155 **    *  Only the "inflate/deflate" (zlib) compression method is supported
   12156 */
   12157 /* #include "sqlite3ext.h" */
   12158 SQLITE_EXTENSION_INIT1
   12159 #include <stdio.h>
   12160 #include <string.h>
   12161 #include <assert.h>
   12162 #ifndef SQLITE_NO_STDINT
   12163 #  include <stdint.h>
   12164 #endif
   12165 
   12166 #include <zlib.h>
   12167 
   12168 /* When used as part of the CLI, the sqlite3_stdio.h module will have
   12169 ** been included before this one. In that case use the sqlite3_stdio.h
   12170 ** #defines.  If not, create our own for fopen().
   12171 */
   12172 #ifndef _SQLITE3_STDIO_H_
   12173 # define sqlite3_fopen fopen
   12174 #endif
   12175 
   12176 #ifndef SQLITE_OMIT_VIRTUALTABLE
   12177 
   12178 #ifndef SQLITE_AMALGAMATION
   12179 
   12180 #ifndef UINT32_TYPE
   12181 # ifdef HAVE_UINT32_T
   12182 #  define UINT32_TYPE uint32_t
   12183 # else
   12184 #  define UINT32_TYPE unsigned int
   12185 # endif
   12186 #endif
   12187 #ifndef UINT16_TYPE
   12188 # ifdef HAVE_UINT16_T
   12189 #  define UINT16_TYPE uint16_t
   12190 # else
   12191 #  define UINT16_TYPE unsigned short int
   12192 # endif
   12193 #endif
   12194 /* typedef sqlite3_int64 i64; */
   12195 /* typedef unsigned char u8; */
   12196 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
   12197 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
   12198 #define MIN(a,b) ((a)<(b) ? (a) : (b))
   12199 
   12200 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
   12201 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
   12202 #endif
   12203 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
   12204 # define ALWAYS(X)      (1)
   12205 # define NEVER(X)       (0)
   12206 #elif !defined(NDEBUG)
   12207 # define ALWAYS(X)      ((X)?1:(assert(0),0))
   12208 # define NEVER(X)       ((X)?(assert(0),1):0)
   12209 #else
   12210 # define ALWAYS(X)      (X)
   12211 # define NEVER(X)       (X)
   12212 #endif
   12213 
   12214 #endif   /* SQLITE_AMALGAMATION */
   12215 
   12216 /*
   12217 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
   12218 **
   12219 ** In some ways it would be better to obtain these values from system
   12220 ** header files. But, the dependency is undesirable and (a) these
   12221 ** have been stable for decades, (b) the values are part of POSIX and
   12222 ** are also made explicit in [man stat], and (c) are part of the
   12223 ** file format for zip archives.
   12224 */
   12225 #ifndef S_IFDIR
   12226 # define S_IFDIR 0040000
   12227 #endif
   12228 #ifndef S_IFREG
   12229 # define S_IFREG 0100000
   12230 #endif
   12231 #ifndef S_IFLNK
   12232 # define S_IFLNK 0120000
   12233 #endif
   12234 
   12235 static const char ZIPFILE_SCHEMA[] =
   12236   "CREATE TABLE y("
   12237     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
   12238     "mode,"              /* 1: POSIX mode for file */
   12239     "mtime,"             /* 2: Last modification time (secs since 1970)*/
   12240     "sz,"                /* 3: Size of object */
   12241     "rawdata,"           /* 4: Raw data */
   12242     "data,"              /* 5: Uncompressed data */
   12243     "method,"            /* 6: Compression method (integer) */
   12244     "z HIDDEN"           /* 7: Name of zip file */
   12245   ") WITHOUT ROWID;";
   12246 
   12247 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
   12248 #define ZIPFILE_MX_NAME (250)     /* Windows limitation on filename size */
   12249 
   12250 /*
   12251 ** The buffer should be large enough to contain 3 65536 byte strings - the
   12252 ** filename, the extra field and the file comment.
   12253 */
   12254 #define ZIPFILE_BUFFER_SIZE (200*1024)
   12255 
   12256 
   12257 /*
   12258 ** Magic numbers used to read and write zip files.
   12259 **
   12260 ** ZIPFILE_NEWENTRY_MADEBY:
   12261 **   Use this value for the "version-made-by" field in new zip file
   12262 **   entries. The upper byte indicates "unix", and the lower byte
   12263 **   indicates that the zip file matches pkzip specification 3.0.
   12264 **   This is what info-zip seems to do.
   12265 **
   12266 ** ZIPFILE_NEWENTRY_REQUIRED:
   12267 **   Value for "version-required-to-extract" field of new entries.
   12268 **   Version 2.0 is required to support folders and deflate compression.
   12269 **
   12270 ** ZIPFILE_NEWENTRY_FLAGS:
   12271 **   Value for "general-purpose-bit-flags" field of new entries. Bit
   12272 **   11 means "utf-8 filename and comment".
   12273 **
   12274 ** ZIPFILE_SIGNATURE_CDS:
   12275 **   First 4 bytes of a valid CDS record.
   12276 **
   12277 ** ZIPFILE_SIGNATURE_LFH:
   12278 **   First 4 bytes of a valid LFH record.
   12279 **
   12280 ** ZIPFILE_SIGNATURE_EOCD
   12281 **   First 4 bytes of a valid EOCD record.
   12282 */
   12283 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
   12284 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
   12285 #define ZIPFILE_NEWENTRY_REQUIRED 20
   12286 #define ZIPFILE_NEWENTRY_FLAGS    0x800
   12287 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
   12288 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
   12289 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
   12290 
   12291 /*
   12292 ** The sizes of the fixed-size part of each of the three main data
   12293 ** structures in a zip archive.
   12294 */
   12295 #define ZIPFILE_LFH_FIXED_SZ      30
   12296 #define ZIPFILE_EOCD_FIXED_SZ     22
   12297 #define ZIPFILE_CDS_FIXED_SZ      46
   12298 
   12299 /*
   12300 *** 4.3.16  End of central directory record:
   12301 ***
   12302 ***   end of central dir signature    4 bytes  (0x06054b50)
   12303 ***   number of this disk             2 bytes
   12304 ***   number of the disk with the
   12305 ***   start of the central directory  2 bytes
   12306 ***   total number of entries in the
   12307 ***   central directory on this disk  2 bytes
   12308 ***   total number of entries in
   12309 ***   the central directory           2 bytes
   12310 ***   size of the central directory   4 bytes
   12311 ***   offset of start of central
   12312 ***   directory with respect to
   12313 ***   the starting disk number        4 bytes
   12314 ***   .ZIP file comment length        2 bytes
   12315 ***   .ZIP file comment       (variable size)
   12316 */
   12317 typedef struct ZipfileEOCD ZipfileEOCD;
   12318 struct ZipfileEOCD {
   12319   u16 iDisk;
   12320   u16 iFirstDisk;
   12321   u16 nEntry;
   12322   u16 nEntryTotal;
   12323   u32 nSize;
   12324   u32 iOffset;
   12325 };
   12326 
   12327 /*
   12328 *** 4.3.12  Central directory structure:
   12329 ***
   12330 *** ...
   12331 ***
   12332 ***   central file header signature   4 bytes  (0x02014b50)
   12333 ***   version made by                 2 bytes
   12334 ***   version needed to extract       2 bytes
   12335 ***   general purpose bit flag        2 bytes
   12336 ***   compression method              2 bytes
   12337 ***   last mod file time              2 bytes
   12338 ***   last mod file date              2 bytes
   12339 ***   crc-32                          4 bytes
   12340 ***   compressed size                 4 bytes
   12341 ***   uncompressed size               4 bytes
   12342 ***   file name length                2 bytes
   12343 ***   extra field length              2 bytes
   12344 ***   file comment length             2 bytes
   12345 ***   disk number start               2 bytes
   12346 ***   internal file attributes        2 bytes
   12347 ***   external file attributes        4 bytes
   12348 ***   relative offset of local header 4 bytes
   12349 */
   12350 typedef struct ZipfileCDS ZipfileCDS;
   12351 struct ZipfileCDS {
   12352   u16 iVersionMadeBy;
   12353   u16 iVersionExtract;
   12354   u16 flags;
   12355   u16 iCompression;
   12356   u16 mTime;
   12357   u16 mDate;
   12358   u32 crc32;
   12359   u32 szCompressed;
   12360   u32 szUncompressed;
   12361   u16 nFile;
   12362   u16 nExtra;
   12363   u16 nComment;
   12364   u16 iDiskStart;
   12365   u16 iInternalAttr;
   12366   u32 iExternalAttr;
   12367   u32 iOffset;
   12368   char *zFile;                    /* Filename (sqlite3_malloc()) */
   12369 };
   12370 
   12371 /*
   12372 *** 4.3.7  Local file header:
   12373 ***
   12374 ***   local file header signature     4 bytes  (0x04034b50)
   12375 ***   version needed to extract       2 bytes
   12376 ***   general purpose bit flag        2 bytes
   12377 ***   compression method              2 bytes
   12378 ***   last mod file time              2 bytes
   12379 ***   last mod file date              2 bytes
   12380 ***   crc-32                          4 bytes
   12381 ***   compressed size                 4 bytes
   12382 ***   uncompressed size               4 bytes
   12383 ***   file name length                2 bytes
   12384 ***   extra field length              2 bytes
   12385 ***
   12386 */
   12387 typedef struct ZipfileLFH ZipfileLFH;
   12388 struct ZipfileLFH {
   12389   u16 iVersionExtract;
   12390   u16 flags;
   12391   u16 iCompression;
   12392   u16 mTime;
   12393   u16 mDate;
   12394   u32 crc32;
   12395   u32 szCompressed;
   12396   u32 szUncompressed;
   12397   u16 nFile;
   12398   u16 nExtra;
   12399 };
   12400 
   12401 typedef struct ZipfileEntry ZipfileEntry;
   12402 struct ZipfileEntry {
   12403   ZipfileCDS cds;            /* Parsed CDS record */
   12404   u32 mUnixTime;             /* Modification time, in UNIX format */
   12405   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
   12406   i64 iDataOff;              /* Offset to data in file (if aData==0) */
   12407   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
   12408   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
   12409 };
   12410 
   12411 /*
   12412 ** Cursor type for zipfile tables.
   12413 */
   12414 typedef struct ZipfileCsr ZipfileCsr;
   12415 struct ZipfileCsr {
   12416   sqlite3_vtab_cursor base;  /* Base class - must be first */
   12417   i64 iId;                   /* Cursor ID */
   12418   u8 bEof;                   /* True when at EOF */
   12419   u8 bNoop;                  /* If next xNext() call is no-op */
   12420 
   12421   /* Used outside of write transactions */
   12422   FILE *pFile;               /* Zip file */
   12423   i64 iNextOff;              /* Offset of next record in central directory */
   12424   ZipfileEOCD eocd;          /* Parse of central directory record */
   12425 
   12426   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
   12427   ZipfileEntry *pCurrent;    /* Current entry */
   12428   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
   12429 };
   12430 
   12431 typedef struct ZipfileTab ZipfileTab;
   12432 struct ZipfileTab {
   12433   sqlite3_vtab base;         /* Base class - must be first */
   12434   char *zFile;               /* Zip file this table accesses (may be NULL) */
   12435   sqlite3 *db;               /* Host database connection */
   12436   u8 *aBuffer;               /* Temporary buffer used for various tasks */
   12437 
   12438   ZipfileCsr *pCsrList;      /* List of cursors */
   12439   i64 iNextCsrid;
   12440 
   12441   /* The following are used by write transactions only */
   12442   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
   12443   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
   12444   FILE *pWriteFd;            /* File handle open on zip archive */
   12445   i64 szCurrent;             /* Current size of zip archive */
   12446   i64 szOrig;                /* Size of archive at start of transaction */
   12447 };
   12448 
   12449 /*
   12450 ** Set the error message contained in context ctx to the results of
   12451 ** vprintf(zFmt, ...).
   12452 */
   12453 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
   12454   char *zMsg = 0;
   12455   va_list ap;
   12456   va_start(ap, zFmt);
   12457   zMsg = sqlite3_vmprintf(zFmt, ap);
   12458   sqlite3_result_error(ctx, zMsg, -1);
   12459   sqlite3_free(zMsg);
   12460   va_end(ap);
   12461 }
   12462 
   12463 /*
   12464 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
   12465 ** is not quoted, do nothing.
   12466 */
   12467 static void zipfileDequote(char *zIn){
   12468   char q = zIn[0];
   12469   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
   12470     int iIn = 1;
   12471     int iOut = 0;
   12472     if( q=='[' ) q = ']';
   12473     while( ALWAYS(zIn[iIn]) ){
   12474       char c = zIn[iIn++];
   12475       if( c==q && zIn[iIn++]!=q ) break;
   12476       zIn[iOut++] = c;
   12477     }
   12478     zIn[iOut] = '\0';
   12479   }
   12480 }
   12481 
   12482 /*
   12483 ** Construct a new ZipfileTab virtual table object.
   12484 **
   12485 **   argv[0]   -> module name  ("zipfile")
   12486 **   argv[1]   -> database name
   12487 **   argv[2]   -> table name
   12488 **   argv[...] -> "column name" and other module argument fields.
   12489 */
   12490 static int zipfileConnect(
   12491   sqlite3 *db,
   12492   void *pAux,
   12493   int argc, const char *const*argv,
   12494   sqlite3_vtab **ppVtab,
   12495   char **pzErr
   12496 ){
   12497   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
   12498   int nFile = 0;
   12499   const char *zFile = 0;
   12500   ZipfileTab *pNew = 0;
   12501   int rc;
   12502   (void)pAux;
   12503 
   12504   /* If the table name is not "zipfile", require that the argument be
   12505   ** specified. This stops zipfile tables from being created as:
   12506   **
   12507   **   CREATE VIRTUAL TABLE zzz USING zipfile();
   12508   **
   12509   ** It does not prevent:
   12510   **
   12511   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
   12512   */
   12513   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
   12514   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
   12515     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
   12516     return SQLITE_ERROR;
   12517   }
   12518 
   12519   if( argc>3 ){
   12520     zFile = argv[3];
   12521     nFile = (int)strlen(zFile)+1;
   12522   }
   12523 
   12524   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
   12525   if( rc==SQLITE_OK ){
   12526     pNew = (ZipfileTab*)sqlite3_malloc64((i64)nByte+nFile);
   12527     if( pNew==0 ) return SQLITE_NOMEM;
   12528     memset(pNew, 0, nByte+nFile);
   12529     pNew->db = db;
   12530     pNew->aBuffer = (u8*)&pNew[1];
   12531     if( zFile ){
   12532       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
   12533       memcpy(pNew->zFile, zFile, nFile);
   12534       zipfileDequote(pNew->zFile);
   12535     }
   12536   }
   12537   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
   12538   *ppVtab = (sqlite3_vtab*)pNew;
   12539   return rc;
   12540 }
   12541 
   12542 /*
   12543 ** Free the ZipfileEntry structure indicated by the only argument.
   12544 */
   12545 static void zipfileEntryFree(ZipfileEntry *p){
   12546   if( p ){
   12547     sqlite3_free(p->cds.zFile);
   12548     sqlite3_free(p);
   12549   }
   12550 }
   12551 
   12552 /*
   12553 ** Release resources that should be freed at the end of a write
   12554 ** transaction.
   12555 */
   12556 static void zipfileCleanupTransaction(ZipfileTab *pTab){
   12557   ZipfileEntry *pEntry;
   12558   ZipfileEntry *pNext;
   12559 
   12560   if( pTab->pWriteFd ){
   12561     fclose(pTab->pWriteFd);
   12562     pTab->pWriteFd = 0;
   12563   }
   12564   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
   12565     pNext = pEntry->pNext;
   12566     zipfileEntryFree(pEntry);
   12567   }
   12568   pTab->pFirstEntry = 0;
   12569   pTab->pLastEntry = 0;
   12570   pTab->szCurrent = 0;
   12571   pTab->szOrig = 0;
   12572 }
   12573 
   12574 /*
   12575 ** This method is the destructor for zipfile vtab objects.
   12576 */
   12577 static int zipfileDisconnect(sqlite3_vtab *pVtab){
   12578   zipfileCleanupTransaction((ZipfileTab*)pVtab);
   12579   sqlite3_free(pVtab);
   12580   return SQLITE_OK;
   12581 }
   12582 
   12583 /*
   12584 ** Constructor for a new ZipfileCsr object.
   12585 */
   12586 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
   12587   ZipfileTab *pTab = (ZipfileTab*)p;
   12588   ZipfileCsr *pCsr;
   12589   pCsr = sqlite3_malloc64(sizeof(*pCsr));
   12590   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
   12591   if( pCsr==0 ){
   12592     return SQLITE_NOMEM;
   12593   }
   12594   memset(pCsr, 0, sizeof(*pCsr));
   12595   pCsr->iId = ++pTab->iNextCsrid;
   12596   pCsr->pCsrNext = pTab->pCsrList;
   12597   pTab->pCsrList = pCsr;
   12598   return SQLITE_OK;
   12599 }
   12600 
   12601 /*
   12602 ** Reset a cursor back to the state it was in when first returned
   12603 ** by zipfileOpen().
   12604 */
   12605 static void zipfileResetCursor(ZipfileCsr *pCsr){
   12606   ZipfileEntry *p;
   12607   ZipfileEntry *pNext;
   12608 
   12609   pCsr->bEof = 0;
   12610   if( pCsr->pFile ){
   12611     fclose(pCsr->pFile);
   12612     pCsr->pFile = 0;
   12613     zipfileEntryFree(pCsr->pCurrent);
   12614     pCsr->pCurrent = 0;
   12615   }
   12616 
   12617   for(p=pCsr->pFreeEntry; p; p=pNext){
   12618     pNext = p->pNext;
   12619     zipfileEntryFree(p);
   12620   }
   12621 }
   12622 
   12623 /*
   12624 ** Destructor for an ZipfileCsr.
   12625 */
   12626 static int zipfileClose(sqlite3_vtab_cursor *cur){
   12627   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   12628   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
   12629   ZipfileCsr **pp;
   12630   zipfileResetCursor(pCsr);
   12631 
   12632   /* Remove this cursor from the ZipfileTab.pCsrList list. */
   12633   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
   12634   *pp = pCsr->pCsrNext;
   12635 
   12636   sqlite3_free(pCsr);
   12637   return SQLITE_OK;
   12638 }
   12639 
   12640 /*
   12641 ** Set the error message for the virtual table associated with cursor
   12642 ** pCsr to the results of vprintf(zFmt, ...).
   12643 */
   12644 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
   12645   va_list ap;
   12646   va_start(ap, zFmt);
   12647   sqlite3_free(pTab->base.zErrMsg);
   12648   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
   12649   va_end(ap);
   12650 }
   12651 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
   12652   va_list ap;
   12653   va_start(ap, zFmt);
   12654   sqlite3_free(pCsr->base.pVtab->zErrMsg);
   12655   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
   12656   va_end(ap);
   12657 }
   12658 
   12659 /*
   12660 ** Read nRead bytes of data from offset iOff of file pFile into buffer
   12661 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
   12662 ** otherwise.
   12663 **
   12664 ** If an error does occur, output variable (*pzErrmsg) may be set to point
   12665 ** to an English language error message. It is the responsibility of the
   12666 ** caller to eventually free this buffer using
   12667 ** sqlite3_free().
   12668 */
   12669 static int zipfileReadData(
   12670   FILE *pFile,                    /* Read from this file */
   12671   u8 *aRead,                      /* Read into this buffer */
   12672   i64 nRead,                      /* Number of bytes to read */
   12673   i64 iOff,                       /* Offset to read from */
   12674   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
   12675 ){
   12676   size_t n;
   12677   fseek(pFile, (long)iOff, SEEK_SET);
   12678   n = fread(aRead, 1, (long)nRead, pFile);
   12679   if( n!=(size_t)nRead ){
   12680     sqlite3_free(*pzErrmsg);
   12681     *pzErrmsg = sqlite3_mprintf("error in fread()");
   12682     return SQLITE_ERROR;
   12683   }
   12684   return SQLITE_OK;
   12685 }
   12686 
   12687 static int zipfileAppendData(
   12688   ZipfileTab *pTab,
   12689   const u8 *aWrite,
   12690   int nWrite
   12691 ){
   12692   if( nWrite>0 ){
   12693     size_t n = nWrite;
   12694     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
   12695     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
   12696     if( (int)n!=nWrite ){
   12697       zipfileTableErr(pTab,"error in fwrite()");
   12698       return SQLITE_ERROR;
   12699     }
   12700     pTab->szCurrent += nWrite;
   12701   }
   12702   return SQLITE_OK;
   12703 }
   12704 
   12705 /*
   12706 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
   12707 */
   12708 static u16 zipfileGetU16(const u8 *aBuf){
   12709   return (aBuf[1] << 8) + aBuf[0];
   12710 }
   12711 
   12712 /*
   12713 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
   12714 */
   12715 static u32 zipfileGetU32(const u8 *aBuf){
   12716   if( aBuf==0 ) return 0;
   12717   return ((u32)(aBuf[3]) << 24)
   12718        + ((u32)(aBuf[2]) << 16)
   12719        + ((u32)(aBuf[1]) <<  8)
   12720        + ((u32)(aBuf[0]) <<  0);
   12721 }
   12722 
   12723 /*
   12724 ** Write a 16-bit little endiate integer into buffer aBuf.
   12725 */
   12726 static void zipfilePutU16(u8 *aBuf, u16 val){
   12727   aBuf[0] = val & 0xFF;
   12728   aBuf[1] = (val>>8) & 0xFF;
   12729 }
   12730 
   12731 /*
   12732 ** Write a 32-bit little endiate integer into buffer aBuf.
   12733 */
   12734 static void zipfilePutU32(u8 *aBuf, u32 val){
   12735   aBuf[0] = val & 0xFF;
   12736   aBuf[1] = (val>>8) & 0xFF;
   12737   aBuf[2] = (val>>16) & 0xFF;
   12738   aBuf[3] = (val>>24) & 0xFF;
   12739 }
   12740 
   12741 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
   12742 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
   12743 
   12744 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
   12745 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
   12746 
   12747 /*
   12748 ** Magic numbers used to read CDS records.
   12749 */
   12750 #define ZIPFILE_CDS_NFILE_OFF        28
   12751 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
   12752 
   12753 /*
   12754 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
   12755 ** if the record is not well-formed, or SQLITE_OK otherwise.
   12756 */
   12757 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
   12758   u8 *aRead = aBuf;
   12759   u32 sig = zipfileRead32(aRead);
   12760   int rc = SQLITE_OK;
   12761   if( sig!=ZIPFILE_SIGNATURE_CDS ){
   12762     rc = SQLITE_ERROR;
   12763   }else{
   12764     pCDS->iVersionMadeBy = zipfileRead16(aRead);
   12765     pCDS->iVersionExtract = zipfileRead16(aRead);
   12766     pCDS->flags = zipfileRead16(aRead);
   12767     pCDS->iCompression = zipfileRead16(aRead);
   12768     pCDS->mTime = zipfileRead16(aRead);
   12769     pCDS->mDate = zipfileRead16(aRead);
   12770     pCDS->crc32 = zipfileRead32(aRead);
   12771     pCDS->szCompressed = zipfileRead32(aRead);
   12772     pCDS->szUncompressed = zipfileRead32(aRead);
   12773     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
   12774     pCDS->nFile = zipfileRead16(aRead);
   12775     pCDS->nExtra = zipfileRead16(aRead);
   12776     pCDS->nComment = zipfileRead16(aRead);
   12777     pCDS->iDiskStart = zipfileRead16(aRead);
   12778     pCDS->iInternalAttr = zipfileRead16(aRead);
   12779     pCDS->iExternalAttr = zipfileRead32(aRead);
   12780     pCDS->iOffset = zipfileRead32(aRead);
   12781     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
   12782   }
   12783 
   12784   return rc;
   12785 }
   12786 
   12787 /*
   12788 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
   12789 ** if the record is not well-formed, or SQLITE_OK otherwise.
   12790 */
   12791 static int zipfileReadLFH(
   12792   u8 *aBuffer,
   12793   ZipfileLFH *pLFH
   12794 ){
   12795   u8 *aRead = aBuffer;
   12796   int rc = SQLITE_OK;
   12797 
   12798   u32 sig = zipfileRead32(aRead);
   12799   if( sig!=ZIPFILE_SIGNATURE_LFH ){
   12800     rc = SQLITE_ERROR;
   12801   }else{
   12802     pLFH->iVersionExtract = zipfileRead16(aRead);
   12803     pLFH->flags = zipfileRead16(aRead);
   12804     pLFH->iCompression = zipfileRead16(aRead);
   12805     pLFH->mTime = zipfileRead16(aRead);
   12806     pLFH->mDate = zipfileRead16(aRead);
   12807     pLFH->crc32 = zipfileRead32(aRead);
   12808     pLFH->szCompressed = zipfileRead32(aRead);
   12809     pLFH->szUncompressed = zipfileRead32(aRead);
   12810     pLFH->nFile = zipfileRead16(aRead);
   12811     pLFH->nExtra = zipfileRead16(aRead);
   12812     if( pLFH->nFile>ZIPFILE_MX_NAME ) rc = SQLITE_ERROR;
   12813   }
   12814   return rc;
   12815 }
   12816 
   12817 
   12818 /*
   12819 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
   12820 ** Scan through this buffer to find an "extra-timestamp" field. If one
   12821 ** exists, extract the 32-bit modification-timestamp from it and store
   12822 ** the value in output parameter *pmTime.
   12823 **
   12824 ** Zero is returned if no extra-timestamp record could be found (and so
   12825 ** *pmTime is left unchanged), or non-zero otherwise.
   12826 **
   12827 ** The general format of an extra field is:
   12828 **
   12829 **   Header ID    2 bytes
   12830 **   Data Size    2 bytes
   12831 **   Data         N bytes
   12832 */
   12833 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
   12834   int ret = 0;
   12835   u8 *p = aExtra;
   12836   u8 *pEnd = &aExtra[nExtra];
   12837 
   12838   /* Stop when there are less than 9 bytes left to scan in the buffer. This
   12839   ** is because the timestamp field requires exactly 9 bytes - 4 bytes of
   12840   ** header fields and 5 bytes of data. If there are less than 9 bytes
   12841   ** remaining, either it is some other field or else the extra data
   12842   ** is corrupt. Either way, do not process it.  */
   12843   while( p+(2*sizeof(u16) + 1 + sizeof(u32))<=pEnd ){
   12844     u16 id = zipfileRead16(p);
   12845     u16 nByte = zipfileRead16(p);
   12846 
   12847     switch( id ){
   12848       case ZIPFILE_EXTRA_TIMESTAMP: {
   12849         u8 b = p[0];
   12850         if( b & 0x01 ){     /* 0x01 -> modtime is present */
   12851           *pmTime = zipfileGetU32(&p[1]);
   12852           ret = 1;
   12853         }
   12854         break;
   12855       }
   12856     }
   12857 
   12858     p += nByte;
   12859   }
   12860   return ret;
   12861 }
   12862 
   12863 /*
   12864 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
   12865 ** fields of the CDS structure passed as the only argument to a 32-bit
   12866 ** UNIX seconds-since-the-epoch timestamp. Return the result.
   12867 **
   12868 ** "Standard" MS-DOS time format:
   12869 **
   12870 **   File modification time:
   12871 **     Bits 00-04: seconds divided by 2
   12872 **     Bits 05-10: minute
   12873 **     Bits 11-15: hour
   12874 **   File modification date:
   12875 **     Bits 00-04: day
   12876 **     Bits 05-08: month (1-12)
   12877 **     Bits 09-15: years from 1980
   12878 **
   12879 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
   12880 */
   12881 static u32 zipfileMtime(ZipfileCDS *pCDS){
   12882   int Y,M,D,X1,X2,A,B,sec,min,hr;
   12883   i64 JDsec;
   12884   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
   12885   M = ((pCDS->mDate >> 5) & 0x0F);
   12886   D = (pCDS->mDate & 0x1F);
   12887   sec = (pCDS->mTime & 0x1F)*2;
   12888   min = (pCDS->mTime >> 5) & 0x3F;
   12889   hr = (pCDS->mTime >> 11) & 0x1F;
   12890   if( M<=2 ){
   12891     Y--;
   12892     M += 12;
   12893   }
   12894   X1 = 36525*(Y+4716)/100;
   12895   X2 = 306001*(M+1)/10000;
   12896   A = Y/100;
   12897   B = 2 - A + (A/4);
   12898   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
   12899   return (u32)(JDsec - (i64)24405875*(i64)8640);
   12900 }
   12901 
   12902 /*
   12903 ** The opposite of zipfileMtime(). This function populates the mTime and
   12904 ** mDate fields of the CDS structure passed as the first argument according
   12905 ** to the UNIX timestamp value passed as the second.
   12906 */
   12907 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
   12908   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
   12909   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
   12910 
   12911   int A, B, C, D, E;
   12912   int yr, mon, day;
   12913   int hr, min, sec;
   12914 
   12915   A = (int)((JD - 1867216.25)/36524.25);
   12916   A = (int)(JD + 1 + A - (A/4));
   12917   B = A + 1524;
   12918   C = (int)((B - 122.1)/365.25);
   12919   D = (36525*(C&32767))/100;
   12920   E = (int)((B-D)/30.6001);
   12921 
   12922   day = B - D - (int)(30.6001*E);
   12923   mon = (E<14 ? E-1 : E-13);
   12924   yr = mon>2 ? C-4716 : C-4715;
   12925 
   12926   hr = (mUnixTime % (24*60*60)) / (60*60);
   12927   min = (mUnixTime % (60*60)) / 60;
   12928   sec = (mUnixTime % 60);
   12929 
   12930   if( yr>=1980 ){
   12931     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
   12932     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
   12933   }else{
   12934     pCds->mDate = pCds->mTime = 0;
   12935   }
   12936 
   12937   assert( mUnixTime<315507600
   12938        || mUnixTime==zipfileMtime(pCds)
   12939        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
   12940        /* || (mUnixTime % 2) */
   12941   );
   12942 }
   12943 
   12944 /*
   12945 ** Set (*pzErr) to point to a buffer from sqlite3_malloc() containing a
   12946 ** generic corruption message and return SQLITE_CORRUPT;
   12947 */
   12948 static int zipfileCorrupt(char **pzErr){
   12949   sqlite3_free(*pzErr);
   12950   *pzErr = sqlite3_mprintf("zip archive is corrupt");
   12951   return SQLITE_CORRUPT;
   12952 }
   12953 
   12954 /*
   12955 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
   12956 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
   12957 ** then pFile is a file-handle open on a zip file. In either case, this
   12958 ** function creates a ZipfileEntry object based on the zip archive entry
   12959 ** for which the CDS record is at offset iOff.
   12960 **
   12961 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
   12962 ** the new object. Otherwise, an SQLite error code is returned and the
   12963 ** final value of (*ppEntry) undefined.
   12964 */
   12965 static int zipfileGetEntry(
   12966   ZipfileTab *pTab,               /* Store any error message here */
   12967   const u8 *aBlob,                /* Pointer to in-memory file image */
   12968   i64 nBlob,                      /* Size of aBlob[] in bytes */
   12969   FILE *pFile,                    /* If aBlob==0, read from this file */
   12970   i64 iOff,                       /* Offset of CDS record */
   12971   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
   12972 ){
   12973   u8 *aRead;
   12974   char **pzErr = &pTab->base.zErrMsg;
   12975   int rc = SQLITE_OK;
   12976 
   12977   if( aBlob==0 ){
   12978     aRead = pTab->aBuffer;
   12979     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
   12980   }else{
   12981     if( (iOff+ZIPFILE_CDS_FIXED_SZ)>nBlob ){
   12982       /* Not enough data for the CDS structure. Corruption. */
   12983       return zipfileCorrupt(pzErr);
   12984     }
   12985     aRead = (u8*)&aBlob[iOff];
   12986   }
   12987 
   12988   if( rc==SQLITE_OK ){
   12989     sqlite3_int64 nAlloc;
   12990     ZipfileEntry *pNew;
   12991 
   12992     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
   12993     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
   12994     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
   12995 
   12996     nAlloc = sizeof(ZipfileEntry) + nExtra;
   12997     if( aBlob ){
   12998       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
   12999     }
   13000 
   13001     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
   13002     if( pNew==0 ){
   13003       rc = SQLITE_NOMEM;
   13004     }else{
   13005       memset(pNew, 0, sizeof(ZipfileEntry));
   13006       rc = zipfileReadCDS(aRead, &pNew->cds);
   13007       if( rc!=SQLITE_OK ){
   13008         zipfileTableErr(pTab, "failed to read CDS at offset %lld", iOff);
   13009       }else if( aBlob==0 ){
   13010         rc = zipfileReadData(
   13011             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
   13012         );
   13013       }else{
   13014         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
   13015         if( (iOff + ZIPFILE_CDS_FIXED_SZ + nFile + nExtra)>nBlob ){
   13016           rc = zipfileCorrupt(pzErr);
   13017         }
   13018       }
   13019     }
   13020 
   13021     if( rc==SQLITE_OK ){
   13022       u32 *pt = &pNew->mUnixTime;
   13023       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
   13024       pNew->aExtra = (u8*)&pNew[1];
   13025       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
   13026       if( pNew->cds.zFile==0 ){
   13027         rc = SQLITE_NOMEM;
   13028       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
   13029         pNew->mUnixTime = zipfileMtime(&pNew->cds);
   13030       }
   13031     }
   13032 
   13033     if( rc==SQLITE_OK ){
   13034       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
   13035       ZipfileLFH lfh;
   13036       if( pFile ){
   13037         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
   13038       }else{
   13039         aRead = (u8*)&aBlob[pNew->cds.iOffset];
   13040         if( ((i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ)>nBlob ){
   13041           rc = zipfileCorrupt(pzErr);
   13042         }
   13043       }
   13044 
   13045       memset(&lfh, 0, sizeof(lfh));
   13046       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
   13047       if( rc==SQLITE_OK ){
   13048         pNew->iDataOff =  (i64)pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
   13049         pNew->iDataOff += lfh.nFile + lfh.nExtra;
   13050         if( aBlob && pNew->cds.szCompressed ){
   13051           if( pNew->iDataOff + pNew->cds.szCompressed > nBlob ){
   13052             rc = zipfileCorrupt(pzErr);
   13053           }else{
   13054             pNew->aData = &pNew->aExtra[nExtra];
   13055             memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
   13056           }
   13057         }
   13058       }else{
   13059         zipfileTableErr(pTab, "failed to read LFH at offset %d",
   13060             (int)pNew->cds.iOffset
   13061         );
   13062       }
   13063     }
   13064 
   13065     if( rc!=SQLITE_OK ){
   13066       zipfileEntryFree(pNew);
   13067     }else{
   13068       *ppEntry = pNew;
   13069     }
   13070   }
   13071 
   13072   return rc;
   13073 }
   13074 
   13075 /*
   13076 ** Advance an ZipfileCsr to its next row of output.
   13077 */
   13078 static int zipfileNext(sqlite3_vtab_cursor *cur){
   13079   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   13080   int rc = SQLITE_OK;
   13081 
   13082   if( pCsr->pFile ){
   13083     i64 iEof = (i64)pCsr->eocd.iOffset + (i64)pCsr->eocd.nSize;
   13084     zipfileEntryFree(pCsr->pCurrent);
   13085     pCsr->pCurrent = 0;
   13086     if( pCsr->iNextOff>=iEof ){
   13087       pCsr->bEof = 1;
   13088     }else{
   13089       ZipfileEntry *p = 0;
   13090       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
   13091       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
   13092       if( rc==SQLITE_OK ){
   13093         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
   13094         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
   13095       }
   13096       pCsr->pCurrent = p;
   13097     }
   13098   }else{
   13099     if( !pCsr->bNoop ){
   13100       pCsr->pCurrent = pCsr->pCurrent->pNext;
   13101     }
   13102     if( pCsr->pCurrent==0 ){
   13103       pCsr->bEof = 1;
   13104     }
   13105   }
   13106 
   13107   pCsr->bNoop = 0;
   13108   return rc;
   13109 }
   13110 
   13111 static void zipfileFree(void *p) {
   13112   sqlite3_free(p);
   13113 }
   13114 
   13115 /*
   13116 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
   13117 ** size is nOut bytes. This function uncompresses the data and sets the
   13118 ** return value in context pCtx to the result (a blob).
   13119 **
   13120 ** If an error occurs, an error code is left in pCtx instead.
   13121 */
   13122 static void zipfileInflate(
   13123   sqlite3_context *pCtx,          /* Store result here */
   13124   const u8 *aIn,                  /* Compressed data */
   13125   int nIn,                        /* Size of buffer aIn[] in bytes */
   13126   int nOut                        /* Expected output size */
   13127 ){
   13128   u8 *aRes = sqlite3_malloc64(nOut);
   13129   if( aRes==0 ){
   13130     sqlite3_result_error_nomem(pCtx);
   13131   }else{
   13132     int err;
   13133     z_stream str;
   13134     memset(&str, 0, sizeof(str));
   13135 
   13136     str.next_in = (Byte*)aIn;
   13137     str.avail_in = nIn;
   13138     str.next_out = (Byte*)aRes;
   13139     str.avail_out = nOut;
   13140 
   13141     err = inflateInit2(&str, -15);
   13142     if( err!=Z_OK ){
   13143       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
   13144     }else{
   13145       err = inflate(&str, Z_NO_FLUSH);
   13146       if( err!=Z_STREAM_END ){
   13147         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
   13148       }else{
   13149         sqlite3_result_blob(pCtx, aRes, (int)str.total_out, zipfileFree);
   13150         aRes = 0;
   13151       }
   13152     }
   13153     sqlite3_free(aRes);
   13154     inflateEnd(&str);
   13155   }
   13156 }
   13157 
   13158 /*
   13159 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
   13160 ** compresses it and sets (*ppOut) to point to a buffer containing the
   13161 ** compressed data. The caller is responsible for eventually calling
   13162 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
   13163 ** is set to the size of buffer (*ppOut) in bytes.
   13164 **
   13165 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
   13166 ** code is returned and an error message left in virtual-table handle
   13167 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
   13168 ** case.
   13169 */
   13170 static int zipfileDeflate(
   13171   const u8 *aIn, int nIn,         /* Input */
   13172   u8 **ppOut, int *pnOut,         /* Output */
   13173   char **pzErr                    /* OUT: Error message */
   13174 ){
   13175   int rc = SQLITE_OK;
   13176   sqlite3_int64 nAlloc;
   13177   z_stream str;
   13178   u8 *aOut;
   13179 
   13180   memset(&str, 0, sizeof(str));
   13181   str.next_in = (Bytef*)aIn;
   13182   str.avail_in = nIn;
   13183   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
   13184 
   13185   nAlloc = deflateBound(&str, nIn);
   13186   aOut = (u8*)sqlite3_malloc64(nAlloc);
   13187   if( aOut==0 ){
   13188     rc = SQLITE_NOMEM;
   13189   }else{
   13190     int res;
   13191     str.next_out = aOut;
   13192     str.avail_out = nAlloc;
   13193     res = deflate(&str, Z_FINISH);
   13194     if( res==Z_STREAM_END ){
   13195       *ppOut = aOut;
   13196       *pnOut = (int)str.total_out;
   13197     }else{
   13198       sqlite3_free(aOut);
   13199       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
   13200       rc = SQLITE_ERROR;
   13201     }
   13202     deflateEnd(&str);
   13203   }
   13204 
   13205   return rc;
   13206 }
   13207 
   13208 
   13209 /*
   13210 ** Return values of columns for the row at which the series_cursor
   13211 ** is currently pointing.
   13212 */
   13213 static int zipfileColumn(
   13214   sqlite3_vtab_cursor *cur,   /* The cursor */
   13215   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
   13216   int i                       /* Which column to return */
   13217 ){
   13218   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   13219   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
   13220   int rc = SQLITE_OK;
   13221   switch( i ){
   13222     case 0:   /* name */
   13223       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
   13224       break;
   13225     case 1:   /* mode */
   13226       /* TODO: Whether or not the following is correct surely depends on
   13227       ** the platform on which the archive was created.  */
   13228       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
   13229       break;
   13230     case 2: { /* mtime */
   13231       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
   13232       break;
   13233     }
   13234     case 3: { /* sz */
   13235       if( sqlite3_vtab_nochange(ctx)==0 ){
   13236         sqlite3_result_int64(ctx, pCDS->szUncompressed);
   13237       }
   13238       break;
   13239     }
   13240     case 4:   /* rawdata */
   13241       if( sqlite3_vtab_nochange(ctx) ) break;
   13242     case 5: { /* data */
   13243       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
   13244         int sz = pCDS->szCompressed;
   13245         int szFinal = pCDS->szUncompressed;
   13246         if( szFinal>0 ){
   13247           u8 *aBuf;
   13248           u8 *aFree = 0;
   13249           if( pCsr->pCurrent->aData ){
   13250             aBuf = pCsr->pCurrent->aData;
   13251           }else{
   13252             aBuf = aFree = sqlite3_malloc64(sz);
   13253             if( aBuf==0 ){
   13254               rc = SQLITE_NOMEM;
   13255             }else{
   13256               FILE *pFile = pCsr->pFile;
   13257               if( pFile==0 ){
   13258                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
   13259               }
   13260               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
   13261                   &pCsr->base.pVtab->zErrMsg
   13262               );
   13263             }
   13264           }
   13265           if( rc==SQLITE_OK ){
   13266             if( i==5 && pCDS->iCompression ){
   13267               zipfileInflate(ctx, aBuf, sz, szFinal);
   13268             }else{
   13269               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
   13270             }
   13271           }
   13272           sqlite3_free(aFree);
   13273         }else{
   13274           /* Figure out if this is a directory or a zero-sized file. Consider
   13275           ** it to be a directory either if the mode suggests so, or if
   13276           ** the final character in the name is '/'.  */
   13277           u32 mode = pCDS->iExternalAttr >> 16;
   13278           if( !(mode & S_IFDIR)
   13279            && pCDS->nFile>=1
   13280            && pCDS->zFile[pCDS->nFile-1]!='/'
   13281           ){
   13282             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
   13283           }
   13284         }
   13285       }
   13286       break;
   13287     }
   13288     case 6:   /* method */
   13289       sqlite3_result_int(ctx, pCDS->iCompression);
   13290       break;
   13291     default:  /* z */
   13292       assert( i==7 );
   13293       sqlite3_result_int64(ctx, pCsr->iId);
   13294       break;
   13295   }
   13296 
   13297   return rc;
   13298 }
   13299 
   13300 /*
   13301 ** Return TRUE if the cursor is at EOF.
   13302 */
   13303 static int zipfileEof(sqlite3_vtab_cursor *cur){
   13304   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   13305   return pCsr->bEof;
   13306 }
   13307 
   13308 /*
   13309 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
   13310 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
   13311 ** is guaranteed to be a file-handle open on a zip file.
   13312 **
   13313 ** This function attempts to locate the EOCD record within the zip archive
   13314 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
   13315 ** returned if successful. Otherwise, an SQLite error code is returned and
   13316 ** an English language error message may be left in virtual-table pTab.
   13317 */
   13318 static int zipfileReadEOCD(
   13319   ZipfileTab *pTab,               /* Return errors here */
   13320   const u8 *aBlob,                /* Pointer to in-memory file image */
   13321   i64 nBlob,                      /* Size of aBlob[] in bytes */
   13322   FILE *pFile,                    /* Read from this file if aBlob==0 */
   13323   ZipfileEOCD *pEOCD              /* Object to populate */
   13324 ){
   13325   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
   13326   i64 nRead;                      /* Bytes to read from file */
   13327   int rc = SQLITE_OK;
   13328 
   13329   memset(pEOCD, 0, sizeof(ZipfileEOCD));
   13330   if( aBlob==0 ){
   13331     i64 iOff;                     /* Offset to read from */
   13332     i64 szFile;                   /* Total size of file in bytes */
   13333     fseek(pFile, 0, SEEK_END);
   13334     szFile = (i64)ftell(pFile);
   13335     if( szFile==0 ){
   13336       return SQLITE_OK;
   13337     }
   13338     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
   13339     iOff = szFile - nRead;
   13340     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
   13341   }else{
   13342     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
   13343     aRead = (u8*)&aBlob[nBlob-nRead];
   13344   }
   13345 
   13346   if( rc==SQLITE_OK ){
   13347     i64 i;
   13348 
   13349     /* Scan backwards looking for the signature bytes */
   13350     for(i=nRead-20; i>=0; i--){
   13351       if( aRead[i]==0x50 && aRead[i+1]==0x4b
   13352        && aRead[i+2]==0x05 && aRead[i+3]==0x06
   13353       ){
   13354         break;
   13355       }
   13356     }
   13357     if( i<0 ){
   13358       zipfileTableErr(pTab, "cannot find end of central directory record");
   13359       return SQLITE_ERROR;
   13360     }
   13361 
   13362     aRead += i+4;
   13363     pEOCD->iDisk = zipfileRead16(aRead);
   13364     pEOCD->iFirstDisk = zipfileRead16(aRead);
   13365     pEOCD->nEntry = zipfileRead16(aRead);
   13366     pEOCD->nEntryTotal = zipfileRead16(aRead);
   13367     pEOCD->nSize = zipfileRead32(aRead);
   13368     pEOCD->iOffset = zipfileRead32(aRead);
   13369   }
   13370 
   13371   return rc;
   13372 }
   13373 
   13374 /*
   13375 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
   13376 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
   13377 ** to the end of the list. Otherwise, it is added to the list immediately
   13378 ** before pBefore (which is guaranteed to be a part of said list).
   13379 */
   13380 static void zipfileAddEntry(
   13381   ZipfileTab *pTab,
   13382   ZipfileEntry *pBefore,
   13383   ZipfileEntry *pNew
   13384 ){
   13385   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
   13386   assert( pNew->pNext==0 );
   13387   if( pBefore==0 ){
   13388     if( pTab->pFirstEntry==0 ){
   13389       pTab->pFirstEntry = pTab->pLastEntry = pNew;
   13390     }else{
   13391       assert( pTab->pLastEntry->pNext==0 );
   13392       pTab->pLastEntry->pNext = pNew;
   13393       pTab->pLastEntry = pNew;
   13394     }
   13395   }else{
   13396     ZipfileEntry **pp;
   13397     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
   13398     pNew->pNext = pBefore;
   13399     *pp = pNew;
   13400   }
   13401 }
   13402 
   13403 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, i64 nBlob){
   13404   ZipfileEOCD eocd;
   13405   int rc;
   13406   int i;
   13407   i64 iOff;
   13408 
   13409   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
   13410   iOff = eocd.iOffset;
   13411   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
   13412     ZipfileEntry *pNew = 0;
   13413     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
   13414 
   13415     if( rc==SQLITE_OK ){
   13416       zipfileAddEntry(pTab, 0, pNew);
   13417       iOff += ZIPFILE_CDS_FIXED_SZ;
   13418       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
   13419     }
   13420   }
   13421   return rc;
   13422 }
   13423 
   13424 /*
   13425 ** xFilter callback.
   13426 */
   13427 static int zipfileFilter(
   13428   sqlite3_vtab_cursor *cur,
   13429   int idxNum, const char *idxStr,
   13430   int argc, sqlite3_value **argv
   13431 ){
   13432   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
   13433   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
   13434   const char *zFile = 0;          /* Zip file to scan */
   13435   int rc = SQLITE_OK;             /* Return Code */
   13436   int bInMemory = 0;              /* True for an in-memory zipfile */
   13437 
   13438   (void)idxStr;
   13439   (void)argc;
   13440 
   13441   zipfileResetCursor(pCsr);
   13442 
   13443   if( pTab->zFile ){
   13444     zFile = pTab->zFile;
   13445   }else if( idxNum==0 ){
   13446     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
   13447     return SQLITE_ERROR;
   13448   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
   13449     static const u8 aEmptyBlob = 0;
   13450     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
   13451     i64 nBlob = sqlite3_value_bytes(argv[0]);
   13452     assert( pTab->pFirstEntry==0 );
   13453     if( aBlob==0 ){
   13454       aBlob = &aEmptyBlob;
   13455       nBlob = 0;
   13456     }
   13457     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
   13458     pCsr->pFreeEntry = pTab->pFirstEntry;
   13459     pTab->pFirstEntry = pTab->pLastEntry = 0;
   13460     if( rc!=SQLITE_OK ) return rc;
   13461     bInMemory = 1;
   13462   }else{
   13463     zFile = (const char*)sqlite3_value_text(argv[0]);
   13464   }
   13465 
   13466   if( 0==pTab->pWriteFd && 0==bInMemory ){
   13467     pCsr->pFile = zFile ? sqlite3_fopen(zFile, "rb") : 0;
   13468     if( pCsr->pFile==0 ){
   13469       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
   13470       rc = SQLITE_ERROR;
   13471     }else{
   13472       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
   13473       if( rc==SQLITE_OK ){
   13474         if( pCsr->eocd.nEntry==0 ){
   13475           pCsr->bEof = 1;
   13476         }else{
   13477           pCsr->iNextOff = pCsr->eocd.iOffset;
   13478           rc = zipfileNext(cur);
   13479         }
   13480       }
   13481     }
   13482   }else{
   13483     pCsr->bNoop = 1;
   13484     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
   13485     rc = zipfileNext(cur);
   13486   }
   13487 
   13488   return rc;
   13489 }
   13490 
   13491 /*
   13492 ** xBestIndex callback.
   13493 */
   13494 static int zipfileBestIndex(
   13495   sqlite3_vtab *tab,
   13496   sqlite3_index_info *pIdxInfo
   13497 ){
   13498   int i;
   13499   int idx = -1;
   13500   int unusable = 0;
   13501   (void)tab;
   13502 
   13503   for(i=0; i<pIdxInfo->nConstraint; i++){
   13504     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
   13505     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
   13506     if( pCons->usable==0 ){
   13507       unusable = 1;
   13508     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   13509       idx = i;
   13510     }
   13511   }
   13512   pIdxInfo->estimatedCost = 1000.0;
   13513   if( idx>=0 ){
   13514     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
   13515     pIdxInfo->aConstraintUsage[idx].omit = 1;
   13516     pIdxInfo->idxNum = 1;
   13517   }else if( unusable ){
   13518     return SQLITE_CONSTRAINT;
   13519   }
   13520   return SQLITE_OK;
   13521 }
   13522 
   13523 static ZipfileEntry *zipfileNewEntry(const char *zPath){
   13524   ZipfileEntry *pNew;
   13525   pNew = sqlite3_malloc64(sizeof(ZipfileEntry));
   13526   if( pNew ){
   13527     memset(pNew, 0, sizeof(ZipfileEntry));
   13528     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
   13529     if( pNew->cds.zFile==0 ){
   13530       sqlite3_free(pNew);
   13531       pNew = 0;
   13532     }
   13533   }
   13534   return pNew;
   13535 }
   13536 
   13537 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
   13538   ZipfileCDS *pCds = &pEntry->cds;
   13539   u8 *a = aBuf;
   13540 
   13541   pCds->nExtra = 9;
   13542 
   13543   /* Write the LFH itself */
   13544   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
   13545   zipfileWrite16(a, pCds->iVersionExtract);
   13546   zipfileWrite16(a, pCds->flags);
   13547   zipfileWrite16(a, pCds->iCompression);
   13548   zipfileWrite16(a, pCds->mTime);
   13549   zipfileWrite16(a, pCds->mDate);
   13550   zipfileWrite32(a, pCds->crc32);
   13551   zipfileWrite32(a, pCds->szCompressed);
   13552   zipfileWrite32(a, pCds->szUncompressed);
   13553   zipfileWrite16(a, (u16)pCds->nFile);
   13554   zipfileWrite16(a, pCds->nExtra);
   13555   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
   13556 
   13557   /* Add the file name */
   13558   memcpy(a, pCds->zFile, (int)pCds->nFile);
   13559   a += (int)pCds->nFile;
   13560 
   13561   /* The "extra" data */
   13562   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
   13563   zipfileWrite16(a, 5);
   13564   *a++ = 0x01;
   13565   zipfileWrite32(a, pEntry->mUnixTime);
   13566 
   13567   return a-aBuf;
   13568 }
   13569 
   13570 static int zipfileAppendEntry(
   13571   ZipfileTab *pTab,
   13572   ZipfileEntry *pEntry,
   13573   const u8 *pData,
   13574   int nData
   13575 ){
   13576   u8 *aBuf = pTab->aBuffer;
   13577   int nBuf;
   13578   int rc;
   13579 
   13580   nBuf = zipfileSerializeLFH(pEntry, aBuf);
   13581   rc = zipfileAppendData(pTab, aBuf, nBuf);
   13582   if( rc==SQLITE_OK ){
   13583     pEntry->iDataOff = pTab->szCurrent;
   13584     rc = zipfileAppendData(pTab, pData, nData);
   13585   }
   13586 
   13587   return rc;
   13588 }
   13589 
   13590 static int zipfileGetMode(
   13591   sqlite3_value *pVal,
   13592   int bIsDir,                     /* If true, default to directory */
   13593   u32 *pMode,                     /* OUT: Mode value */
   13594   char **pzErr                    /* OUT: Error message */
   13595 ){
   13596   const char *z = (const char*)sqlite3_value_text(pVal);
   13597   u32 mode = 0;
   13598   if( z==0 ){
   13599     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
   13600   }else if( z[0]>='0' && z[0]<='9' ){
   13601     mode = (unsigned int)sqlite3_value_int(pVal);
   13602   }else{
   13603     const char zTemplate[11] = "-rwxrwxrwx";
   13604     int i;
   13605     if( strlen(z)!=10 ) goto parse_error;
   13606     switch( z[0] ){
   13607       case '-': mode |= S_IFREG; break;
   13608       case 'd': mode |= S_IFDIR; break;
   13609       case 'l': mode |= S_IFLNK; break;
   13610       default: goto parse_error;
   13611     }
   13612     for(i=1; i<10; i++){
   13613       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
   13614       else if( z[i]!='-' ) goto parse_error;
   13615     }
   13616   }
   13617   if( ((mode & S_IFDIR)==0)==bIsDir ){
   13618     /* The "mode" attribute is a directory, but data has been specified.
   13619     ** Or vice-versa - no data but "mode" is a file or symlink.  */
   13620     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
   13621     return SQLITE_CONSTRAINT;
   13622   }
   13623   *pMode = mode;
   13624   return SQLITE_OK;
   13625 
   13626  parse_error:
   13627   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
   13628   return SQLITE_ERROR;
   13629 }
   13630 
   13631 /*
   13632 ** Both (const char*) arguments point to nul-terminated strings. Argument
   13633 ** nB is the value of strlen(zB). This function returns 0 if the strings are
   13634 ** identical, ignoring any trailing '/' character in either path.  */
   13635 static int zipfileComparePath(const char *zA, const char *zB, int nB){
   13636   int nA = (int)strlen(zA);
   13637   if( nA>0 && zA[nA-1]=='/' ) nA--;
   13638   if( nB>0 && zB[nB-1]=='/' ) nB--;
   13639   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
   13640   return 1;
   13641 }
   13642 
   13643 static int zipfileBegin(sqlite3_vtab *pVtab){
   13644   ZipfileTab *pTab = (ZipfileTab*)pVtab;
   13645   int rc = SQLITE_OK;
   13646 
   13647   assert( pTab->pWriteFd==0 );
   13648   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
   13649     zipfileTableErr(pTab, "zipfile: missing filename");
   13650     return SQLITE_ERROR;
   13651   }
   13652 
   13653   /* Open a write fd on the file. Also load the entire central directory
   13654   ** structure into memory. During the transaction any new file data is
   13655   ** appended to the archive file, but the central directory is accumulated
   13656   ** in main-memory until the transaction is committed.  */
   13657   pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+");
   13658   if( pTab->pWriteFd==0 ){
   13659     zipfileTableErr(pTab,
   13660       "zipfile: failed to open file %s for writing", pTab->zFile
   13661     );
   13662     rc = SQLITE_ERROR;
   13663   }else{
   13664     fseek(pTab->pWriteFd, 0, SEEK_END);
   13665     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
   13666     rc = zipfileLoadDirectory(pTab, 0, 0);
   13667   }
   13668 
   13669   if( rc!=SQLITE_OK ){
   13670     zipfileCleanupTransaction(pTab);
   13671   }
   13672 
   13673   return rc;
   13674 }
   13675 
   13676 /*
   13677 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
   13678 ** time(2)).
   13679 */
   13680 static u32 zipfileTime(void){
   13681   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
   13682   u32 ret;
   13683   if( pVfs==0 ) return 0;
   13684   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
   13685     i64 ms;
   13686     pVfs->xCurrentTimeInt64(pVfs, &ms);
   13687     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
   13688   }else{
   13689     double day;
   13690     pVfs->xCurrentTime(pVfs, &day);
   13691     ret = (u32)((day - 2440587.5) * 86400);
   13692   }
   13693   return ret;
   13694 }
   13695 
   13696 /*
   13697 ** Return a 32-bit timestamp in UNIX epoch format.
   13698 **
   13699 ** If the value passed as the only argument is either NULL or an SQL NULL,
   13700 ** return the current time. Otherwise, return the value stored in (*pVal)
   13701 ** cast to a 32-bit unsigned integer.
   13702 */
   13703 static u32 zipfileGetTime(sqlite3_value *pVal){
   13704   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
   13705     return zipfileTime();
   13706   }
   13707   return (u32)sqlite3_value_int64(pVal);
   13708 }
   13709 
   13710 /*
   13711 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
   13712 ** linked list.  Remove it from the list and free the object.
   13713 */
   13714 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
   13715   if( pOld ){
   13716     if( pTab->pFirstEntry==pOld ){
   13717       pTab->pFirstEntry = pOld->pNext;
   13718       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
   13719     }else{
   13720       ZipfileEntry *p;
   13721       for(p=pTab->pFirstEntry; p; p=p->pNext){
   13722         if( p->pNext==pOld ){
   13723           p->pNext = pOld->pNext;
   13724           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
   13725           break;
   13726         }
   13727       }
   13728     }
   13729     zipfileEntryFree(pOld);
   13730   }
   13731 }
   13732 
   13733 /*
   13734 ** xUpdate method.
   13735 */
   13736 static int zipfileUpdate(
   13737   sqlite3_vtab *pVtab,
   13738   int nVal,
   13739   sqlite3_value **apVal,
   13740   sqlite_int64 *pRowid
   13741 ){
   13742   ZipfileTab *pTab = (ZipfileTab*)pVtab;
   13743   int rc = SQLITE_OK;             /* Return Code */
   13744   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
   13745 
   13746   u32 mode = 0;                   /* Mode for new entry */
   13747   u32 mTime = 0;                  /* Modification time for new entry */
   13748   i64 sz = 0;                     /* Uncompressed size */
   13749   const char *zPath = 0;          /* Path for new entry */
   13750   int nPath = 0;                  /* strlen(zPath) */
   13751   const u8 *pData = 0;            /* Pointer to buffer containing content */
   13752   int nData = 0;                  /* Size of pData buffer in bytes */
   13753   int iMethod = 0;                /* Compression method for new entry */
   13754   u8 *pFree = 0;                  /* Free this */
   13755   char *zFree = 0;                /* Also free this */
   13756   ZipfileEntry *pOld = 0;
   13757   ZipfileEntry *pOld2 = 0;
   13758   int bUpdate = 0;                /* True for an update that modifies "name" */
   13759   int bIsDir = 0;
   13760   u32 iCrc32 = 0;
   13761 
   13762   (void)pRowid;
   13763 
   13764   if( pTab->pWriteFd==0 ){
   13765     rc = zipfileBegin(pVtab);
   13766     if( rc!=SQLITE_OK ) return rc;
   13767   }
   13768 
   13769   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
   13770   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   13771     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
   13772     int nDelete = (int)strlen(zDelete);
   13773     if( nVal>1 ){
   13774       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
   13775       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
   13776         bUpdate = 1;
   13777       }
   13778     }
   13779     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
   13780       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
   13781         break;
   13782       }
   13783       assert( pOld->pNext );
   13784     }
   13785   }
   13786 
   13787   if( nVal>1 ){
   13788     /* Check that "sz" and "rawdata" are both NULL: */
   13789     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
   13790       zipfileTableErr(pTab, "sz must be NULL");
   13791       rc = SQLITE_CONSTRAINT;
   13792     }
   13793     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
   13794       zipfileTableErr(pTab, "rawdata must be NULL");
   13795       rc = SQLITE_CONSTRAINT;
   13796     }
   13797 
   13798     if( rc==SQLITE_OK ){
   13799       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
   13800         /* data=NULL. A directory */
   13801         bIsDir = 1;
   13802       }else{
   13803         /* Value specified for "data", and possibly "method". This must be
   13804         ** a regular file or a symlink. */
   13805         const u8 *aIn = sqlite3_value_blob(apVal[7]);
   13806         int nIn = sqlite3_value_bytes(apVal[7]);
   13807         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
   13808 
   13809         iMethod = sqlite3_value_int(apVal[8]);
   13810         sz = nIn;
   13811         pData = aIn;
   13812         nData = nIn;
   13813         if( iMethod!=0 && iMethod!=8 ){
   13814           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
   13815           rc = SQLITE_CONSTRAINT;
   13816         }else{
   13817           if( bAuto || iMethod ){
   13818             int nCmp;
   13819             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
   13820             if( rc==SQLITE_OK ){
   13821               if( iMethod || nCmp<nIn ){
   13822                 iMethod = 8;
   13823                 pData = pFree;
   13824                 nData = nCmp;
   13825               }
   13826             }
   13827           }
   13828           iCrc32 = crc32(0, aIn, nIn);
   13829         }
   13830       }
   13831     }
   13832 
   13833     if( rc==SQLITE_OK ){
   13834       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
   13835     }
   13836 
   13837     if( rc==SQLITE_OK ){
   13838       zPath = (const char*)sqlite3_value_text(apVal[2]);
   13839       if( zPath==0 ) zPath = "";
   13840       nPath = (int)strlen(zPath);
   13841       if( nPath>ZIPFILE_MX_NAME ){
   13842         zipfileTableErr(pTab, "filename too long; max: %d bytes",
   13843                         ZIPFILE_MX_NAME);
   13844         rc = SQLITE_CONSTRAINT;
   13845       }
   13846       mTime = zipfileGetTime(apVal[4]);
   13847     }
   13848 
   13849     if( rc==SQLITE_OK && bIsDir ){
   13850       /* For a directory, check that the last character in the path is a
   13851       ** '/'. This appears to be required for compatibility with info-zip
   13852       ** (the unzip command on unix). It does not create directories
   13853       ** otherwise.  */
   13854       if( nPath<=0 || zPath[nPath-1]!='/' ){
   13855         zFree = sqlite3_mprintf("%s/", zPath);
   13856         zPath = (const char*)zFree;
   13857         if( zFree==0 ){
   13858           rc = SQLITE_NOMEM;
   13859           nPath = 0;
   13860         }else{
   13861           nPath = (int)strlen(zPath);
   13862         }
   13863       }
   13864     }
   13865 
   13866     /* Check that we're not inserting a duplicate entry -OR- updating an
   13867     ** entry with a path, thereby making it into a duplicate. */
   13868     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
   13869       ZipfileEntry *p;
   13870       for(p=pTab->pFirstEntry; p; p=p->pNext){
   13871         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
   13872           switch( sqlite3_vtab_on_conflict(pTab->db) ){
   13873             case SQLITE_IGNORE: {
   13874               goto zipfile_update_done;
   13875             }
   13876             case SQLITE_REPLACE: {
   13877               pOld2 = p;
   13878               break;
   13879             }
   13880             default: {
   13881               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
   13882               rc = SQLITE_CONSTRAINT;
   13883               break;
   13884             }
   13885           }
   13886           break;
   13887         }
   13888       }
   13889     }
   13890 
   13891     if( rc==SQLITE_OK ){
   13892       /* Create the new CDS record. */
   13893       pNew = zipfileNewEntry(zPath);
   13894       if( pNew==0 ){
   13895         rc = SQLITE_NOMEM;
   13896       }else{
   13897         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
   13898         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
   13899         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
   13900         pNew->cds.iCompression = (u16)iMethod;
   13901         zipfileMtimeToDos(&pNew->cds, mTime);
   13902         pNew->cds.crc32 = iCrc32;
   13903         pNew->cds.szCompressed = nData;
   13904         pNew->cds.szUncompressed = (u32)sz;
   13905         pNew->cds.iExternalAttr = (mode<<16);
   13906         pNew->cds.iOffset = (u32)pTab->szCurrent;
   13907         pNew->cds.nFile = (u16)nPath;
   13908         pNew->mUnixTime = (u32)mTime;
   13909         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
   13910         zipfileAddEntry(pTab, pOld, pNew);
   13911       }
   13912     }
   13913   }
   13914 
   13915   if( rc==SQLITE_OK && (pOld || pOld2) ){
   13916     ZipfileCsr *pCsr;
   13917     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
   13918       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
   13919         pCsr->pCurrent = pCsr->pCurrent->pNext;
   13920         pCsr->bNoop = 1;
   13921       }
   13922     }
   13923 
   13924     zipfileRemoveEntryFromList(pTab, pOld);
   13925     zipfileRemoveEntryFromList(pTab, pOld2);
   13926   }
   13927 
   13928 zipfile_update_done:
   13929   sqlite3_free(pFree);
   13930   sqlite3_free(zFree);
   13931   return rc;
   13932 }
   13933 
   13934 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
   13935   u8 *a = aBuf;
   13936   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
   13937   zipfileWrite16(a, p->iDisk);
   13938   zipfileWrite16(a, p->iFirstDisk);
   13939   zipfileWrite16(a, p->nEntry);
   13940   zipfileWrite16(a, p->nEntryTotal);
   13941   zipfileWrite32(a, p->nSize);
   13942   zipfileWrite32(a, p->iOffset);
   13943   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
   13944 
   13945   return a-aBuf;
   13946 }
   13947 
   13948 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
   13949   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
   13950   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
   13951   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
   13952 }
   13953 
   13954 /*
   13955 ** Serialize the CDS structure into buffer aBuf[]. Return the number
   13956 ** of bytes written.
   13957 */
   13958 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
   13959   u8 *a = aBuf;
   13960   ZipfileCDS *pCDS = &pEntry->cds;
   13961 
   13962   if( pEntry->aExtra==0 ){
   13963     pCDS->nExtra = 9;
   13964   }
   13965 
   13966   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
   13967   zipfileWrite16(a, pCDS->iVersionMadeBy);
   13968   zipfileWrite16(a, pCDS->iVersionExtract);
   13969   zipfileWrite16(a, pCDS->flags);
   13970   zipfileWrite16(a, pCDS->iCompression);
   13971   zipfileWrite16(a, pCDS->mTime);
   13972   zipfileWrite16(a, pCDS->mDate);
   13973   zipfileWrite32(a, pCDS->crc32);
   13974   zipfileWrite32(a, pCDS->szCompressed);
   13975   zipfileWrite32(a, pCDS->szUncompressed);
   13976   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
   13977   zipfileWrite16(a, pCDS->nFile);
   13978   zipfileWrite16(a, pCDS->nExtra);
   13979   zipfileWrite16(a, pCDS->nComment);
   13980   zipfileWrite16(a, pCDS->iDiskStart);
   13981   zipfileWrite16(a, pCDS->iInternalAttr);
   13982   zipfileWrite32(a, pCDS->iExternalAttr);
   13983   zipfileWrite32(a, pCDS->iOffset);
   13984 
   13985   memcpy(a, pCDS->zFile, pCDS->nFile);
   13986   a += pCDS->nFile;
   13987 
   13988   if( pEntry->aExtra ){
   13989     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
   13990     memcpy(a, pEntry->aExtra, n);
   13991     a += n;
   13992   }else{
   13993     assert( pCDS->nExtra==9 );
   13994     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
   13995     zipfileWrite16(a, 5);
   13996     *a++ = 0x01;
   13997     zipfileWrite32(a, pEntry->mUnixTime);
   13998   }
   13999 
   14000   return a-aBuf;
   14001 }
   14002 
   14003 static int zipfileCommit(sqlite3_vtab *pVtab){
   14004   ZipfileTab *pTab = (ZipfileTab*)pVtab;
   14005   int rc = SQLITE_OK;
   14006   if( pTab->pWriteFd ){
   14007     i64 iOffset = pTab->szCurrent;
   14008     ZipfileEntry *p;
   14009     ZipfileEOCD eocd;
   14010     int nEntry = 0;
   14011 
   14012     /* Write out all entries */
   14013     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
   14014       int n = zipfileSerializeCDS(p, pTab->aBuffer);
   14015       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
   14016       nEntry++;
   14017     }
   14018 
   14019     /* Write out the EOCD record */
   14020     eocd.iDisk = 0;
   14021     eocd.iFirstDisk = 0;
   14022     eocd.nEntry = (u16)nEntry;
   14023     eocd.nEntryTotal = (u16)nEntry;
   14024     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
   14025     eocd.iOffset = (u32)iOffset;
   14026     rc = zipfileAppendEOCD(pTab, &eocd);
   14027 
   14028     zipfileCleanupTransaction(pTab);
   14029   }
   14030   return rc;
   14031 }
   14032 
   14033 static int zipfileRollback(sqlite3_vtab *pVtab){
   14034   return zipfileCommit(pVtab);
   14035 }
   14036 
   14037 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
   14038   ZipfileCsr *pCsr;
   14039   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
   14040     if( iId==pCsr->iId ) break;
   14041   }
   14042   return pCsr;
   14043 }
   14044 
   14045 static void zipfileFunctionCds(
   14046   sqlite3_context *context,
   14047   int argc,
   14048   sqlite3_value **argv
   14049 ){
   14050   ZipfileCsr *pCsr;
   14051   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
   14052   assert( argc>0 );
   14053 
   14054   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
   14055   if( pCsr ){
   14056     ZipfileCDS *p = &pCsr->pCurrent->cds;
   14057     char *zRes = sqlite3_mprintf("{"
   14058         "\"version-made-by\" : %u, "
   14059         "\"version-to-extract\" : %u, "
   14060         "\"flags\" : %u, "
   14061         "\"compression\" : %u, "
   14062         "\"time\" : %u, "
   14063         "\"date\" : %u, "
   14064         "\"crc32\" : %u, "
   14065         "\"compressed-size\" : %u, "
   14066         "\"uncompressed-size\" : %u, "
   14067         "\"file-name-length\" : %u, "
   14068         "\"extra-field-length\" : %u, "
   14069         "\"file-comment-length\" : %u, "
   14070         "\"disk-number-start\" : %u, "
   14071         "\"internal-attr\" : %u, "
   14072         "\"external-attr\" : %u, "
   14073         "\"offset\" : %u }",
   14074         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
   14075         (u32)p->flags, (u32)p->iCompression,
   14076         (u32)p->mTime, (u32)p->mDate,
   14077         (u32)p->crc32, (u32)p->szCompressed,
   14078         (u32)p->szUncompressed, (u32)p->nFile,
   14079         (u32)p->nExtra, (u32)p->nComment,
   14080         (u32)p->iDiskStart, (u32)p->iInternalAttr,
   14081         (u32)p->iExternalAttr, (u32)p->iOffset
   14082     );
   14083 
   14084     if( zRes==0 ){
   14085       sqlite3_result_error_nomem(context);
   14086     }else{
   14087       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
   14088       sqlite3_free(zRes);
   14089     }
   14090   }
   14091 }
   14092 
   14093 /*
   14094 ** xFindFunction method.
   14095 */
   14096 static int zipfileFindFunction(
   14097   sqlite3_vtab *pVtab,            /* Virtual table handle */
   14098   int nArg,                       /* Number of SQL function arguments */
   14099   const char *zName,              /* Name of SQL function */
   14100   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   14101   void **ppArg                    /* OUT: User data for *pxFunc */
   14102 ){
   14103   (void)nArg;
   14104   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
   14105     *pxFunc = zipfileFunctionCds;
   14106     *ppArg = (void*)pVtab;
   14107     return 1;
   14108   }
   14109   return 0;
   14110 }
   14111 
   14112 typedef struct ZipfileBuffer ZipfileBuffer;
   14113 struct ZipfileBuffer {
   14114   u8 *a;                          /* Pointer to buffer */
   14115   int n;                          /* Size of buffer in bytes */
   14116   int nAlloc;                     /* Byte allocated at a[] */
   14117 };
   14118 
   14119 typedef struct ZipfileCtx ZipfileCtx;
   14120 struct ZipfileCtx {
   14121   int nEntry;
   14122   ZipfileBuffer body;
   14123   ZipfileBuffer cds;
   14124 };
   14125 
   14126 static int zipfileBufferGrow(ZipfileBuffer *pBuf, i64 nByte){
   14127   if( pBuf->n+nByte>pBuf->nAlloc ){
   14128     u8 *aNew;
   14129     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
   14130     int nReq = pBuf->n + nByte;
   14131 
   14132     while( nNew<nReq ) nNew = nNew*2;
   14133     aNew = sqlite3_realloc64(pBuf->a, nNew);
   14134     if( aNew==0 ) return SQLITE_NOMEM;
   14135     pBuf->a = aNew;
   14136     pBuf->nAlloc = (int)nNew;
   14137   }
   14138   return SQLITE_OK;
   14139 }
   14140 
   14141 /*
   14142 ** xStep() callback for the zipfile() aggregate. This can be called in
   14143 ** any of the following ways:
   14144 **
   14145 **   SELECT zipfile(name,data) ...
   14146 **   SELECT zipfile(name,mode,mtime,data) ...
   14147 **   SELECT zipfile(name,mode,mtime,data,method) ...
   14148 */
   14149 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
   14150   ZipfileCtx *p;                  /* Aggregate function context */
   14151   ZipfileEntry e;                 /* New entry to add to zip archive */
   14152 
   14153   sqlite3_value *pName = 0;
   14154   sqlite3_value *pMode = 0;
   14155   sqlite3_value *pMtime = 0;
   14156   sqlite3_value *pData = 0;
   14157   sqlite3_value *pMethod = 0;
   14158 
   14159   int bIsDir = 0;
   14160   u32 mode;
   14161   int rc = SQLITE_OK;
   14162   char *zErr = 0;
   14163 
   14164   int iMethod = -1;               /* Compression method to use (0 or 8) */
   14165 
   14166   const u8 *aData = 0;            /* Possibly compressed data for new entry */
   14167   int nData = 0;                  /* Size of aData[] in bytes */
   14168   int szUncompressed = 0;         /* Size of data before compression */
   14169   u8 *aFree = 0;                  /* Free this before returning */
   14170   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
   14171 
   14172   char *zName = 0;                /* Path (name) of new entry */
   14173   int nName = 0;                  /* Size of zName in bytes */
   14174   char *zFree = 0;                /* Free this before returning */
   14175   i64 nByte;
   14176 
   14177   memset(&e, 0, sizeof(e));
   14178   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
   14179   if( p==0 ) return;
   14180 
   14181   /* Martial the arguments into stack variables */
   14182   if( nVal!=2 && nVal!=4 && nVal!=5 ){
   14183     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
   14184     rc = SQLITE_ERROR;
   14185     goto zipfile_step_out;
   14186   }
   14187   pName = apVal[0];
   14188   if( nVal==2 ){
   14189     pData = apVal[1];
   14190   }else{
   14191     pMode = apVal[1];
   14192     pMtime = apVal[2];
   14193     pData = apVal[3];
   14194     if( nVal==5 ){
   14195       pMethod = apVal[4];
   14196     }
   14197   }
   14198 
   14199   /* Check that the 'name' parameter looks ok. */
   14200   zName = (char*)sqlite3_value_text(pName);
   14201   nName = sqlite3_value_bytes(pName);
   14202   if( zName==0 ){
   14203     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
   14204     rc = SQLITE_ERROR;
   14205     goto zipfile_step_out;
   14206   }
   14207   if( nName>ZIPFILE_MX_NAME ){
   14208     zErr = sqlite3_mprintf(
   14209                "filename argument to zipfile() too big; max: %d bytes",
   14210                ZIPFILE_MX_NAME);
   14211     rc = SQLITE_ERROR;
   14212     goto zipfile_step_out;
   14213   }
   14214 
   14215   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
   14216   ** deflate compression) or NULL (choose automatically).  */
   14217   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
   14218     iMethod = (int)sqlite3_value_int64(pMethod);
   14219     if( iMethod!=0 && iMethod!=8 ){
   14220       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
   14221       rc = SQLITE_ERROR;
   14222       goto zipfile_step_out;
   14223     }
   14224   }
   14225 
   14226   /* Now inspect the data. If this is NULL, then the new entry must be a
   14227   ** directory.  Otherwise, figure out whether or not the data should
   14228   ** be deflated or simply stored in the zip archive. */
   14229   if( sqlite3_value_type(pData)==SQLITE_NULL ){
   14230     bIsDir = 1;
   14231     iMethod = 0;
   14232   }else{
   14233     aData = sqlite3_value_blob(pData);
   14234     szUncompressed = nData = sqlite3_value_bytes(pData);
   14235     iCrc32 = crc32(0, aData, nData);
   14236     if( iMethod<0 || iMethod==8 ){
   14237       int nOut = 0;
   14238       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
   14239       if( rc!=SQLITE_OK ){
   14240         goto zipfile_step_out;
   14241       }
   14242       if( iMethod==8 || nOut<nData ){
   14243         aData = aFree;
   14244         nData = nOut;
   14245         iMethod = 8;
   14246       }else{
   14247         iMethod = 0;
   14248       }
   14249     }
   14250   }
   14251 
   14252   /* Decode the "mode" argument. */
   14253   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
   14254   if( rc ) goto zipfile_step_out;
   14255 
   14256   /* Decode the "mtime" argument. */
   14257   e.mUnixTime = zipfileGetTime(pMtime);
   14258 
   14259   /* If this is a directory entry, ensure that there is exactly one '/'
   14260   ** at the end of the path. Or, if this is not a directory and the path
   14261   ** ends in '/' it is an error. */
   14262   if( bIsDir==0 ){
   14263     if( nName>0 && zName[nName-1]=='/' ){
   14264       zErr = sqlite3_mprintf("non-directory name must not end with /");
   14265       rc = SQLITE_ERROR;
   14266       goto zipfile_step_out;
   14267     }
   14268   }else{
   14269     if( nName==0 || zName[nName-1]!='/' ){
   14270       zName = zFree = sqlite3_mprintf("%s/", zName);
   14271       if( zName==0 ){
   14272         rc = SQLITE_NOMEM;
   14273         goto zipfile_step_out;
   14274       }
   14275       nName = (int)strlen(zName);
   14276     }else{
   14277       while( nName>1 && zName[nName-2]=='/' ) nName--;
   14278     }
   14279   }
   14280 
   14281   /* Assemble the ZipfileEntry object for the new zip archive entry */
   14282   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
   14283   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
   14284   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
   14285   e.cds.iCompression = (u16)iMethod;
   14286   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
   14287   e.cds.crc32 = iCrc32;
   14288   e.cds.szCompressed = nData;
   14289   e.cds.szUncompressed = szUncompressed;
   14290   e.cds.iExternalAttr = (mode<<16);
   14291   e.cds.iOffset = p->body.n;
   14292   e.cds.nFile = (u16)nName;
   14293   e.cds.zFile = zName;
   14294 
   14295   /* Append the LFH to the body of the new archive */
   14296   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
   14297   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
   14298   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
   14299 
   14300   /* Append the data to the body of the new archive */
   14301   if( nData>0 ){
   14302     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
   14303     memcpy(&p->body.a[p->body.n], aData, nData);
   14304     p->body.n += nData;
   14305   }
   14306 
   14307   /* Append the CDS record to the directory of the new archive */
   14308   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
   14309   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
   14310   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
   14311 
   14312   /* Increment the count of entries in the archive */
   14313   p->nEntry++;
   14314 
   14315  zipfile_step_out:
   14316   sqlite3_free(aFree);
   14317   sqlite3_free(zFree);
   14318   if( rc ){
   14319     if( zErr ){
   14320       sqlite3_result_error(pCtx, zErr, -1);
   14321     }else{
   14322       sqlite3_result_error_code(pCtx, rc);
   14323     }
   14324   }
   14325   sqlite3_free(zErr);
   14326 }
   14327 
   14328 /*
   14329 ** xFinalize() callback for zipfile aggregate function.
   14330 */
   14331 static void zipfileFinal(sqlite3_context *pCtx){
   14332   ZipfileCtx *p;
   14333   ZipfileEOCD eocd;
   14334   sqlite3_int64 nZip;
   14335   u8 *aZip;
   14336 
   14337   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
   14338   if( p==0 ) return;
   14339   if( p->nEntry>0 ){
   14340     memset(&eocd, 0, sizeof(eocd));
   14341     eocd.nEntry = (u16)p->nEntry;
   14342     eocd.nEntryTotal = (u16)p->nEntry;
   14343     eocd.nSize = p->cds.n;
   14344     eocd.iOffset = p->body.n;
   14345 
   14346     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
   14347     aZip = (u8*)sqlite3_malloc64(nZip);
   14348     if( aZip==0 ){
   14349       sqlite3_result_error_nomem(pCtx);
   14350     }else{
   14351       memcpy(aZip, p->body.a, p->body.n);
   14352       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
   14353       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
   14354       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
   14355     }
   14356   }
   14357 
   14358   sqlite3_free(p->body.a);
   14359   sqlite3_free(p->cds.a);
   14360 }
   14361 
   14362 
   14363 /*
   14364 ** Register the "zipfile" virtual table.
   14365 */
   14366 static int zipfileRegister(sqlite3 *db){
   14367   static sqlite3_module zipfileModule = {
   14368     1,                         /* iVersion */
   14369     zipfileConnect,            /* xCreate */
   14370     zipfileConnect,            /* xConnect */
   14371     zipfileBestIndex,          /* xBestIndex */
   14372     zipfileDisconnect,         /* xDisconnect */
   14373     zipfileDisconnect,         /* xDestroy */
   14374     zipfileOpen,               /* xOpen - open a cursor */
   14375     zipfileClose,              /* xClose - close a cursor */
   14376     zipfileFilter,             /* xFilter - configure scan constraints */
   14377     zipfileNext,               /* xNext - advance a cursor */
   14378     zipfileEof,                /* xEof - check for end of scan */
   14379     zipfileColumn,             /* xColumn - read data */
   14380     0,                         /* xRowid - read data */
   14381     zipfileUpdate,             /* xUpdate */
   14382     zipfileBegin,              /* xBegin */
   14383     0,                         /* xSync */
   14384     zipfileCommit,             /* xCommit */
   14385     zipfileRollback,           /* xRollback */
   14386     zipfileFindFunction,       /* xFindMethod */
   14387     0,                         /* xRename */
   14388     0,                         /* xSavepoint */
   14389     0,                         /* xRelease */
   14390     0,                         /* xRollback */
   14391     0,                         /* xShadowName */
   14392     0                          /* xIntegrity */
   14393   };
   14394 
   14395   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
   14396   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
   14397   if( rc==SQLITE_OK ){
   14398     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
   14399         zipfileStep, zipfileFinal
   14400     );
   14401   }
   14402   assert( sizeof(i64)==8 );
   14403   assert( sizeof(u32)==4 );
   14404   assert( sizeof(u16)==2 );
   14405   assert( sizeof(u8)==1 );
   14406   return rc;
   14407 }
   14408 #else         /* SQLITE_OMIT_VIRTUALTABLE */
   14409 # define zipfileRegister(x) SQLITE_OK
   14410 #endif
   14411 
   14412 #ifdef _WIN32
   14413 
   14414 #endif
   14415 int sqlite3_zipfile_init(
   14416   sqlite3 *db,
   14417   char **pzErrMsg,
   14418   const sqlite3_api_routines *pApi
   14419 ){
   14420   SQLITE_EXTENSION_INIT2(pApi);
   14421   (void)pzErrMsg;  /* Unused parameter */
   14422   return zipfileRegister(db);
   14423 }
   14424 
   14425 /************************* End ext/misc/zipfile.c ********************/
   14426 /************************* Begin ext/misc/sqlar.c ******************/
   14427 /*
   14428 ** 2017-12-17
   14429 **
   14430 ** The author disclaims copyright to this source code.  In place of
   14431 ** a legal notice, here is a blessing:
   14432 **
   14433 **    May you do good and not evil.
   14434 **    May you find forgiveness for yourself and forgive others.
   14435 **    May you share freely, never taking more than you give.
   14436 **
   14437 ******************************************************************************
   14438 **
   14439 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
   14440 ** for working with sqlar archives and used by the shell tool's built-in
   14441 ** sqlar support.
   14442 */
   14443 /* #include "sqlite3ext.h" */
   14444 SQLITE_EXTENSION_INIT1
   14445 #include <zlib.h>
   14446 #include <assert.h>
   14447 
   14448 /*
   14449 ** Implementation of the "sqlar_compress(X)" SQL function.
   14450 **
   14451 ** If the type of X is SQLITE_BLOB, and compressing that blob using
   14452 ** zlib utility function compress() yields a smaller blob, return the
   14453 ** compressed blob. Otherwise, return a copy of X.
   14454 **
   14455 ** SQLar uses the "zlib format" for compressed content.  The zlib format
   14456 ** contains a two-byte identification header and a four-byte checksum at
   14457 ** the end.  This is different from ZIP which uses the raw deflate format.
   14458 **
   14459 ** Future enhancements to SQLar might add support for new compression formats.
   14460 ** If so, those new formats will be identified by alternative headers in the
   14461 ** compressed data.
   14462 */
   14463 static void sqlarCompressFunc(
   14464   sqlite3_context *context,
   14465   int argc,
   14466   sqlite3_value **argv
   14467 ){
   14468   assert( argc==1 );
   14469   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
   14470     const Bytef *pData = sqlite3_value_blob(argv[0]);
   14471     uLong nData = sqlite3_value_bytes(argv[0]);
   14472     uLongf nOut = compressBound(nData);
   14473     Bytef *pOut;
   14474 
   14475     pOut = (Bytef*)sqlite3_malloc64(nOut);
   14476     if( pOut==0 ){
   14477       sqlite3_result_error_nomem(context);
   14478       return;
   14479     }else{
   14480       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
   14481         sqlite3_result_error(context, "error in compress()", -1);
   14482       }else if( nOut<nData ){
   14483         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
   14484       }else{
   14485         sqlite3_result_value(context, argv[0]);
   14486       }
   14487       sqlite3_free(pOut);
   14488     }
   14489   }else{
   14490     sqlite3_result_value(context, argv[0]);
   14491   }
   14492 }
   14493 
   14494 /*
   14495 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
   14496 **
   14497 ** Parameter SZ is interpreted as an integer. If it is less than or
   14498 ** equal to zero, then this function returns a copy of X. Or, if
   14499 ** SZ is equal to the size of X when interpreted as a blob, also
   14500 ** return a copy of X. Otherwise, decompress blob X using zlib
   14501 ** utility function uncompress() and return the results (another
   14502 ** blob).
   14503 */
   14504 static void sqlarUncompressFunc(
   14505   sqlite3_context *context,
   14506   int argc,
   14507   sqlite3_value **argv
   14508 ){
   14509   uLong nData;
   14510   sqlite3_int64 sz;
   14511 
   14512   assert( argc==2 );
   14513   sz = sqlite3_value_int64(argv[1]);
   14514 
   14515   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
   14516     sqlite3_result_value(context, argv[0]);
   14517   }else{
   14518     uLongf szf = sz;
   14519     const Bytef *pData= sqlite3_value_blob(argv[0]);
   14520     Bytef *pOut = sqlite3_malloc64(sz);
   14521     if( pOut==0 ){
   14522       sqlite3_result_error_nomem(context);
   14523     }else if( Z_OK!=uncompress(pOut, &szf, pData, nData) ){
   14524       sqlite3_result_error(context, "error in uncompress()", -1);
   14525     }else{
   14526       sqlite3_result_blob(context, pOut, szf, SQLITE_TRANSIENT);
   14527     }
   14528     sqlite3_free(pOut);
   14529   }
   14530 }
   14531 
   14532 #ifdef _WIN32
   14533 
   14534 #endif
   14535 int sqlite3_sqlar_init(
   14536   sqlite3 *db,
   14537   char **pzErrMsg,
   14538   const sqlite3_api_routines *pApi
   14539 ){
   14540   int rc = SQLITE_OK;
   14541   SQLITE_EXTENSION_INIT2(pApi);
   14542   (void)pzErrMsg;  /* Unused parameter */
   14543   rc = sqlite3_create_function(db, "sqlar_compress", 1,
   14544                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
   14545                                sqlarCompressFunc, 0, 0);
   14546   if( rc==SQLITE_OK ){
   14547     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
   14548                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
   14549                                  sqlarUncompressFunc, 0, 0);
   14550   }
   14551   return rc;
   14552 }
   14553 
   14554 /************************* End ext/misc/sqlar.c ********************/
   14555 #endif
   14556 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   14557 /************************* Begin ext/expert/sqlite3expert.h ******************/
   14558 /*
   14559 ** 2017 April 07
   14560 **
   14561 ** The author disclaims copyright to this source code.  In place of
   14562 ** a legal notice, here is a blessing:
   14563 **
   14564 **    May you do good and not evil.
   14565 **    May you find forgiveness for yourself and forgive others.
   14566 **    May you share freely, never taking more than you give.
   14567 **
   14568 *************************************************************************
   14569 */
   14570 #if !defined(SQLITEEXPERT_H)
   14571 #define SQLITEEXPERT_H 1
   14572 /* #include "sqlite3.h" */
   14573 
   14574 typedef struct sqlite3expert sqlite3expert;
   14575 
   14576 /*
   14577 ** Create a new sqlite3expert object.
   14578 **
   14579 ** If successful, a pointer to the new object is returned and (*pzErr) set
   14580 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
   14581 ** an English-language error message. In this case it is the responsibility
   14582 ** of the caller to eventually free the error message buffer using
   14583 ** sqlite3_free().
   14584 */
   14585 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
   14586 
   14587 /*
   14588 ** Configure an sqlite3expert object.
   14589 **
   14590 ** EXPERT_CONFIG_SAMPLE:
   14591 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
   14592 **   each candidate index. This involves scanning and sorting the entire
   14593 **   contents of each user database table once for each candidate index
   14594 **   associated with the table. For large databases, this can be
   14595 **   prohibitively slow. This option allows the sqlite3expert object to
   14596 **   be configured so that sqlite_stat1 data is instead generated based on a
   14597 **   subset of each table, or so that no sqlite_stat1 data is used at all.
   14598 **
   14599 **   A single integer argument is passed to this option. If the value is less
   14600 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
   14601 **   the analysis - indexes are recommended based on the database schema only.
   14602 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
   14603 **   generated for each candidate index (this is the default). Finally, if the
   14604 **   value falls between 0 and 100, then it represents the percentage of user
   14605 **   table rows that should be considered when generating sqlite_stat1 data.
   14606 **
   14607 **   Examples:
   14608 **
   14609 **     // Do not generate any sqlite_stat1 data
   14610 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
   14611 **
   14612 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
   14613 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
   14614 */
   14615 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
   14616 
   14617 #define EXPERT_CONFIG_SAMPLE 1    /* int */
   14618 
   14619 /*
   14620 ** Specify zero or more SQL statements to be included in the analysis.
   14621 **
   14622 ** Buffer zSql must contain zero or more complete SQL statements. This
   14623 ** function parses all statements contained in the buffer and adds them
   14624 ** to the internal list of statements to analyze. If successful, SQLITE_OK
   14625 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
   14626 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
   14627 ** may be set to point to an English language error message. In this case
   14628 ** the caller is responsible for eventually freeing the error message buffer
   14629 ** using sqlite3_free().
   14630 **
   14631 ** If an error does occur while processing one of the statements in the
   14632 ** buffer passed as the second argument, none of the statements in the
   14633 ** buffer are added to the analysis.
   14634 **
   14635 ** This function must be called before sqlite3_expert_analyze(). If a call
   14636 ** to this function is made on an sqlite3expert object that has already
   14637 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
   14638 ** immediately and no statements are added to the analysis.
   14639 */
   14640 int sqlite3_expert_sql(
   14641   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
   14642   const char *zSql,               /* SQL statement(s) to add */
   14643   char **pzErr                    /* OUT: Error message (if any) */
   14644 );
   14645 
   14646 
   14647 /*
   14648 ** This function is called after the sqlite3expert object has been configured
   14649 ** with all SQL statements using sqlite3_expert_sql() to actually perform
   14650 ** the analysis. Once this function has been called, it is not possible to
   14651 ** add further SQL statements to the analysis.
   14652 **
   14653 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
   14654 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
   14655 ** point to a buffer containing an English language error message. In this
   14656 ** case it is the responsibility of the caller to eventually free the buffer
   14657 ** using sqlite3_free().
   14658 **
   14659 ** If an error does occur within this function, the sqlite3expert object
   14660 ** is no longer useful for any purpose. At that point it is no longer
   14661 ** possible to add further SQL statements to the object or to re-attempt
   14662 ** the analysis. The sqlite3expert object must still be freed using a call
   14663 ** sqlite3_expert_destroy().
   14664 */
   14665 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
   14666 
   14667 /*
   14668 ** Return the total number of statements loaded using sqlite3_expert_sql().
   14669 ** The total number of SQL statements may be different from the total number
   14670 ** to calls to sqlite3_expert_sql().
   14671 */
   14672 int sqlite3_expert_count(sqlite3expert*);
   14673 
   14674 /*
   14675 ** Return a component of the report.
   14676 **
   14677 ** This function is called after sqlite3_expert_analyze() to extract the
   14678 ** results of the analysis. Each call to this function returns either a
   14679 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
   14680 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
   14681 ** #define constants defined below.
   14682 **
   14683 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
   14684 ** information relating to a specific SQL statement. In these cases that
   14685 ** SQL statement is identified by the value passed as the second argument.
   14686 ** SQL statements are numbered from 0 in the order in which they are parsed.
   14687 ** If an out-of-range value (less than zero or equal to or greater than the
   14688 ** value returned by sqlite3_expert_count()) is passed as the second argument
   14689 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
   14690 **
   14691 ** EXPERT_REPORT_SQL:
   14692 **   Return the text of SQL statement iStmt.
   14693 **
   14694 ** EXPERT_REPORT_INDEXES:
   14695 **   Return a buffer containing the CREATE INDEX statements for all recommended
   14696 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
   14697 **   is returned.
   14698 **
   14699 ** EXPERT_REPORT_PLAN:
   14700 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
   14701 **   iStmt after the proposed indexes have been added to the database schema.
   14702 **
   14703 ** EXPERT_REPORT_CANDIDATES:
   14704 **   Return a pointer to a buffer containing the CREATE INDEX statements
   14705 **   for all indexes that were tested (for all SQL statements). The iStmt
   14706 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
   14707 */
   14708 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
   14709 
   14710 /*
   14711 ** Values for the third argument passed to sqlite3_expert_report().
   14712 */
   14713 #define EXPERT_REPORT_SQL        1
   14714 #define EXPERT_REPORT_INDEXES    2
   14715 #define EXPERT_REPORT_PLAN       3
   14716 #define EXPERT_REPORT_CANDIDATES 4
   14717 
   14718 /*
   14719 ** Free an (sqlite3expert*) handle and all associated resources. There
   14720 ** should be one call to this function for each successful call to
   14721 ** sqlite3-expert_new().
   14722 */
   14723 void sqlite3_expert_destroy(sqlite3expert*);
   14724 
   14725 #endif  /* !defined(SQLITEEXPERT_H) */
   14726 
   14727 /************************* End ext/expert/sqlite3expert.h ********************/
   14728 /************************* Begin ext/expert/sqlite3expert.c ******************/
   14729 /*
   14730 ** 2017 April 09
   14731 **
   14732 ** The author disclaims copyright to this source code.  In place of
   14733 ** a legal notice, here is a blessing:
   14734 **
   14735 **    May you do good and not evil.
   14736 **    May you find forgiveness for yourself and forgive others.
   14737 **    May you share freely, never taking more than you give.
   14738 **
   14739 *************************************************************************
   14740 */
   14741 /* #include "sqlite3expert.h" */
   14742 #include <assert.h>
   14743 #include <string.h>
   14744 #include <stdio.h>
   14745 
   14746 #if !defined(SQLITE_AMALGAMATION)
   14747 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
   14748 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
   14749 #endif
   14750 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
   14751 # define ALWAYS(X)      (1)
   14752 # define NEVER(X)       (0)
   14753 #elif !defined(NDEBUG)
   14754 # define ALWAYS(X)      ((X)?1:(assert(0),0))
   14755 # define NEVER(X)       ((X)?(assert(0),1):0)
   14756 #else
   14757 # define ALWAYS(X)      (X)
   14758 # define NEVER(X)       (X)
   14759 #endif
   14760 #endif /* !defined(SQLITE_AMALGAMATION) */
   14761 
   14762 
   14763 #ifndef SQLITE_OMIT_VIRTUALTABLE
   14764 
   14765 /* typedef sqlite3_int64 i64; */
   14766 /* typedef sqlite3_uint64 u64; */
   14767 
   14768 typedef struct IdxColumn IdxColumn;
   14769 typedef struct IdxConstraint IdxConstraint;
   14770 typedef struct IdxScan IdxScan;
   14771 typedef struct IdxStatement IdxStatement;
   14772 typedef struct IdxTable IdxTable;
   14773 typedef struct IdxWrite IdxWrite;
   14774 
   14775 #define STRLEN  (int)strlen
   14776 
   14777 /*
   14778 ** A temp table name that we assume no user database will actually use.
   14779 ** If this assumption proves incorrect triggers on the table with the
   14780 ** conflicting name will be ignored.
   14781 */
   14782 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
   14783 
   14784 /*
   14785 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
   14786 ** any other type of single-ended range constraint on a column).
   14787 **
   14788 ** pLink:
   14789 **   Used to temporarily link IdxConstraint objects into lists while
   14790 **   creating candidate indexes.
   14791 */
   14792 struct IdxConstraint {
   14793   char *zColl;                    /* Collation sequence */
   14794   int bRange;                     /* True for range, false for eq */
   14795   int iCol;                       /* Constrained table column */
   14796   int bFlag;                      /* Used by idxFindCompatible() */
   14797   int bDesc;                      /* True if ORDER BY <expr> DESC */
   14798   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
   14799   IdxConstraint *pLink;           /* See above */
   14800 };
   14801 
   14802 /*
   14803 ** A single scan of a single table.
   14804 */
   14805 struct IdxScan {
   14806   IdxTable *pTab;                 /* Associated table object */
   14807   int iDb;                        /* Database containing table zTable */
   14808   i64 covering;                   /* Mask of columns required for cov. index */
   14809   IdxConstraint *pOrder;          /* ORDER BY columns */
   14810   IdxConstraint *pEq;             /* List of == constraints */
   14811   IdxConstraint *pRange;          /* List of < constraints */
   14812   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
   14813 };
   14814 
   14815 /*
   14816 ** Information regarding a single database table. Extracted from
   14817 ** "PRAGMA table_info" by function idxGetTableInfo().
   14818 */
   14819 struct IdxColumn {
   14820   char *zName;
   14821   char *zColl;
   14822   int iPk;
   14823 };
   14824 struct IdxTable {
   14825   int nCol;
   14826   char *zName;                    /* Table name */
   14827   IdxColumn *aCol;
   14828   IdxTable *pNext;                /* Next table in linked list of all tables */
   14829 };
   14830 
   14831 /*
   14832 ** An object of the following type is created for each unique table/write-op
   14833 ** seen. The objects are stored in a singly-linked list beginning at
   14834 ** sqlite3expert.pWrite.
   14835 */
   14836 struct IdxWrite {
   14837   IdxTable *pTab;
   14838   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
   14839   IdxWrite *pNext;
   14840 };
   14841 
   14842 /*
   14843 ** Each statement being analyzed is represented by an instance of this
   14844 ** structure.
   14845 */
   14846 struct IdxStatement {
   14847   int iId;                        /* Statement number */
   14848   char *zSql;                     /* SQL statement */
   14849   char *zIdx;                     /* Indexes */
   14850   char *zEQP;                     /* Plan */
   14851   IdxStatement *pNext;
   14852 };
   14853 
   14854 
   14855 /*
   14856 ** A hash table for storing strings. With space for a payload string
   14857 ** with each entry. Methods are:
   14858 **
   14859 **   idxHashInit()
   14860 **   idxHashClear()
   14861 **   idxHashAdd()
   14862 **   idxHashSearch()
   14863 */
   14864 #define IDX_HASH_SIZE 1023
   14865 typedef struct IdxHashEntry IdxHashEntry;
   14866 typedef struct IdxHash IdxHash;
   14867 struct IdxHashEntry {
   14868   char *zKey;                     /* nul-terminated key */
   14869   char *zVal;                     /* nul-terminated value string */
   14870   char *zVal2;                    /* nul-terminated value string 2 */
   14871   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
   14872   IdxHashEntry *pNext;            /* Next entry in hash */
   14873 };
   14874 struct IdxHash {
   14875   IdxHashEntry *pFirst;
   14876   IdxHashEntry *aHash[IDX_HASH_SIZE];
   14877 };
   14878 
   14879 /*
   14880 ** sqlite3expert object.
   14881 */
   14882 struct sqlite3expert {
   14883   int iSample;                    /* Percentage of tables to sample for stat1 */
   14884   sqlite3 *db;                    /* User database */
   14885   sqlite3 *dbm;                   /* In-memory db for this analysis */
   14886   sqlite3 *dbv;                   /* Vtab schema for this analysis */
   14887   IdxTable *pTable;               /* List of all IdxTable objects */
   14888   IdxScan *pScan;                 /* List of scan objects */
   14889   IdxWrite *pWrite;               /* List of write objects */
   14890   IdxStatement *pStatement;       /* List of IdxStatement objects */
   14891   int bRun;                       /* True once analysis has run */
   14892   char **pzErrmsg;
   14893   int rc;                         /* Error code from whereinfo hook */
   14894   IdxHash hIdx;                   /* Hash containing all candidate indexes */
   14895   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
   14896 };
   14897 
   14898 
   14899 /*
   14900 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
   14901 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
   14902 */
   14903 static void *idxMalloc(int *pRc, i64 nByte){
   14904   void *pRet;
   14905   assert( *pRc==SQLITE_OK );
   14906   assert( nByte>0 );
   14907   pRet = sqlite3_malloc64(nByte);
   14908   if( pRet ){
   14909     memset(pRet, 0, nByte);
   14910   }else{
   14911     *pRc = SQLITE_NOMEM;
   14912   }
   14913   return pRet;
   14914 }
   14915 
   14916 /*
   14917 ** Initialize an IdxHash hash table.
   14918 */
   14919 static void idxHashInit(IdxHash *pHash){
   14920   memset(pHash, 0, sizeof(IdxHash));
   14921 }
   14922 
   14923 /*
   14924 ** Reset an IdxHash hash table.
   14925 */
   14926 static void idxHashClear(IdxHash *pHash){
   14927   int i;
   14928   for(i=0; i<IDX_HASH_SIZE; i++){
   14929     IdxHashEntry *pEntry;
   14930     IdxHashEntry *pNext;
   14931     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
   14932       pNext = pEntry->pHashNext;
   14933       sqlite3_free(pEntry->zVal2);
   14934       sqlite3_free(pEntry);
   14935     }
   14936   }
   14937   memset(pHash, 0, sizeof(IdxHash));
   14938 }
   14939 
   14940 /*
   14941 ** Return the index of the hash bucket that the string specified by the
   14942 ** arguments to this function belongs.
   14943 */
   14944 static int idxHashString(const char *z, int n){
   14945   unsigned int ret = 0;
   14946   int i;
   14947   for(i=0; i<n; i++){
   14948     ret += (ret<<3) + (unsigned char)(z[i]);
   14949   }
   14950   return (int)(ret % IDX_HASH_SIZE);
   14951 }
   14952 
   14953 /*
   14954 ** If zKey is already present in the hash table, return non-zero and do
   14955 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
   14956 ** the hash table passed as the second argument.
   14957 */
   14958 static int idxHashAdd(
   14959   int *pRc,
   14960   IdxHash *pHash,
   14961   const char *zKey,
   14962   const char *zVal
   14963 ){
   14964   int nKey = STRLEN(zKey);
   14965   int iHash = idxHashString(zKey, nKey);
   14966   int nVal = (zVal ? STRLEN(zVal) : 0);
   14967   IdxHashEntry *pEntry;
   14968   assert( iHash>=0 );
   14969   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
   14970     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
   14971       return 1;
   14972     }
   14973   }
   14974   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + (i64)nKey+1 + (i64)nVal+1);
   14975   if( pEntry ){
   14976     pEntry->zKey = (char*)&pEntry[1];
   14977     memcpy(pEntry->zKey, zKey, nKey);
   14978     if( zVal ){
   14979       pEntry->zVal = &pEntry->zKey[nKey+1];
   14980       memcpy(pEntry->zVal, zVal, nVal);
   14981     }
   14982     pEntry->pHashNext = pHash->aHash[iHash];
   14983     pHash->aHash[iHash] = pEntry;
   14984 
   14985     pEntry->pNext = pHash->pFirst;
   14986     pHash->pFirst = pEntry;
   14987   }
   14988   return 0;
   14989 }
   14990 
   14991 /*
   14992 ** If zKey/nKey is present in the hash table, return a pointer to the
   14993 ** hash-entry object.
   14994 */
   14995 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
   14996   int iHash;
   14997   IdxHashEntry *pEntry;
   14998   if( nKey<0 ) nKey = STRLEN(zKey);
   14999   iHash = idxHashString(zKey, nKey);
   15000   assert( iHash>=0 );
   15001   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
   15002     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
   15003       return pEntry;
   15004     }
   15005   }
   15006   return 0;
   15007 }
   15008 
   15009 /*
   15010 ** If the hash table contains an entry with a key equal to the string
   15011 ** passed as the final two arguments to this function, return a pointer
   15012 ** to the payload string. Otherwise, if zKey/nKey is not present in the
   15013 ** hash table, return NULL.
   15014 */
   15015 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
   15016   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
   15017   if( pEntry ) return pEntry->zVal;
   15018   return 0;
   15019 }
   15020 
   15021 /*
   15022 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
   15023 ** variable to point to a copy of nul-terminated string zColl.
   15024 */
   15025 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
   15026   IdxConstraint *pNew;
   15027   int nColl = STRLEN(zColl);
   15028 
   15029   assert( *pRc==SQLITE_OK );
   15030   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
   15031   if( pNew ){
   15032     pNew->zColl = (char*)&pNew[1];
   15033     memcpy(pNew->zColl, zColl, nColl+1);
   15034   }
   15035   return pNew;
   15036 }
   15037 
   15038 /*
   15039 ** An error associated with database handle db has just occurred. Pass
   15040 ** the error message to callback function xOut.
   15041 */
   15042 static void idxDatabaseError(
   15043   sqlite3 *db,                    /* Database handle */
   15044   char **pzErrmsg                 /* Write error here */
   15045 ){
   15046   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   15047 }
   15048 
   15049 /*
   15050 ** Prepare an SQL statement.
   15051 */
   15052 static int idxPrepareStmt(
   15053   sqlite3 *db,                    /* Database handle to compile against */
   15054   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
   15055   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
   15056   const char *zSql                /* SQL statement to compile */
   15057 ){
   15058   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
   15059   if( rc!=SQLITE_OK ){
   15060     *ppStmt = 0;
   15061     idxDatabaseError(db, pzErrmsg);
   15062   }
   15063   return rc;
   15064 }
   15065 
   15066 /*
   15067 ** Prepare an SQL statement using the results of a printf() formatting.
   15068 */
   15069 static int idxPrintfPrepareStmt(
   15070   sqlite3 *db,                    /* Database handle to compile against */
   15071   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
   15072   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
   15073   const char *zFmt,               /* printf() format of SQL statement */
   15074   ...                             /* Trailing printf() arguments */
   15075 ){
   15076   va_list ap;
   15077   int rc;
   15078   char *zSql;
   15079   va_start(ap, zFmt);
   15080   zSql = sqlite3_vmprintf(zFmt, ap);
   15081   if( zSql==0 ){
   15082     rc = SQLITE_NOMEM;
   15083   }else{
   15084     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
   15085     sqlite3_free(zSql);
   15086   }
   15087   va_end(ap);
   15088   return rc;
   15089 }
   15090 
   15091 
   15092 /*************************************************************************
   15093 ** Beginning of virtual table implementation.
   15094 */
   15095 typedef struct ExpertVtab ExpertVtab;
   15096 struct ExpertVtab {
   15097   sqlite3_vtab base;
   15098   IdxTable *pTab;
   15099   sqlite3expert *pExpert;
   15100 };
   15101 
   15102 typedef struct ExpertCsr ExpertCsr;
   15103 struct ExpertCsr {
   15104   sqlite3_vtab_cursor base;
   15105   sqlite3_stmt *pData;
   15106 };
   15107 
   15108 static char *expertDequote(const char *zIn){
   15109   i64 n = STRLEN(zIn);
   15110   char *zRet = sqlite3_malloc64(n);
   15111 
   15112   assert( zIn[0]=='\'' );
   15113   assert( zIn[n-1]=='\'' );
   15114 
   15115   if( zRet ){
   15116     i64 iOut = 0;
   15117     i64 iIn = 0;
   15118     for(iIn=1; iIn<(n-1); iIn++){
   15119       if( zIn[iIn]=='\'' ){
   15120         assert( zIn[iIn+1]=='\'' );
   15121         iIn++;
   15122       }
   15123       zRet[iOut++] = zIn[iIn];
   15124     }
   15125     zRet[iOut] = '\0';
   15126   }
   15127 
   15128   return zRet;
   15129 }
   15130 
   15131 /*
   15132 ** This function is the implementation of both the xConnect and xCreate
   15133 ** methods of the r-tree virtual table.
   15134 **
   15135 **   argv[0]   -> module name
   15136 **   argv[1]   -> database name
   15137 **   argv[2]   -> table name
   15138 **   argv[...] -> column names...
   15139 */
   15140 static int expertConnect(
   15141   sqlite3 *db,
   15142   void *pAux,
   15143   int argc, const char *const*argv,
   15144   sqlite3_vtab **ppVtab,
   15145   char **pzErr
   15146 ){
   15147   sqlite3expert *pExpert = (sqlite3expert*)pAux;
   15148   ExpertVtab *p = 0;
   15149   int rc;
   15150 
   15151   if( argc!=4 ){
   15152     *pzErr = sqlite3_mprintf("internal error!");
   15153     rc = SQLITE_ERROR;
   15154   }else{
   15155     char *zCreateTable = expertDequote(argv[3]);
   15156     if( zCreateTable ){
   15157       rc = sqlite3_declare_vtab(db, zCreateTable);
   15158       if( rc==SQLITE_OK ){
   15159         p = idxMalloc(&rc, sizeof(ExpertVtab));
   15160       }
   15161       if( rc==SQLITE_OK ){
   15162         p->pExpert = pExpert;
   15163         p->pTab = pExpert->pTable;
   15164         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
   15165       }
   15166       sqlite3_free(zCreateTable);
   15167     }else{
   15168       rc = SQLITE_NOMEM;
   15169     }
   15170   }
   15171 
   15172   *ppVtab = (sqlite3_vtab*)p;
   15173   return rc;
   15174 }
   15175 
   15176 static int expertDisconnect(sqlite3_vtab *pVtab){
   15177   ExpertVtab *p = (ExpertVtab*)pVtab;
   15178   sqlite3_free(p);
   15179   return SQLITE_OK;
   15180 }
   15181 
   15182 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
   15183   ExpertVtab *p = (ExpertVtab*)pVtab;
   15184   int rc = SQLITE_OK;
   15185   int n = 0;
   15186   IdxScan *pScan;
   15187   const int opmask =
   15188     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
   15189     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
   15190     SQLITE_INDEX_CONSTRAINT_LE;
   15191 
   15192   pScan = idxMalloc(&rc, sizeof(IdxScan));
   15193   if( pScan ){
   15194     int i;
   15195 
   15196     /* Link the new scan object into the list */
   15197     pScan->pTab = p->pTab;
   15198     pScan->pNextScan = p->pExpert->pScan;
   15199     p->pExpert->pScan = pScan;
   15200 
   15201     /* Add the constraints to the IdxScan object */
   15202     for(i=0; i<pIdxInfo->nConstraint; i++){
   15203       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
   15204       if( pCons->usable
   15205        && pCons->iColumn>=0
   15206        && p->pTab->aCol[pCons->iColumn].iPk==0
   15207        && (pCons->op & opmask)
   15208       ){
   15209         IdxConstraint *pNew;
   15210         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
   15211         pNew = idxNewConstraint(&rc, zColl);
   15212         if( pNew ){
   15213           pNew->iCol = pCons->iColumn;
   15214           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   15215             pNew->pNext = pScan->pEq;
   15216             pScan->pEq = pNew;
   15217           }else{
   15218             pNew->bRange = 1;
   15219             pNew->pNext = pScan->pRange;
   15220             pScan->pRange = pNew;
   15221           }
   15222         }
   15223         n++;
   15224         pIdxInfo->aConstraintUsage[i].argvIndex = n;
   15225       }
   15226     }
   15227 
   15228     /* Add the ORDER BY to the IdxScan object */
   15229     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
   15230       int iCol = pIdxInfo->aOrderBy[i].iColumn;
   15231       if( iCol>=0 ){
   15232         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
   15233         if( pNew ){
   15234           pNew->iCol = iCol;
   15235           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
   15236           pNew->pNext = pScan->pOrder;
   15237           pNew->pLink = pScan->pOrder;
   15238           pScan->pOrder = pNew;
   15239           n++;
   15240         }
   15241       }
   15242     }
   15243   }
   15244 
   15245   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
   15246   return rc;
   15247 }
   15248 
   15249 static int expertUpdate(
   15250   sqlite3_vtab *pVtab,
   15251   int nData,
   15252   sqlite3_value **azData,
   15253   sqlite_int64 *pRowid
   15254 ){
   15255   (void)pVtab;
   15256   (void)nData;
   15257   (void)azData;
   15258   (void)pRowid;
   15259   return SQLITE_OK;
   15260 }
   15261 
   15262 /*
   15263 ** Virtual table module xOpen method.
   15264 */
   15265 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   15266   int rc = SQLITE_OK;
   15267   ExpertCsr *pCsr;
   15268   (void)pVTab;
   15269   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
   15270   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
   15271   return rc;
   15272 }
   15273 
   15274 /*
   15275 ** Virtual table module xClose method.
   15276 */
   15277 static int expertClose(sqlite3_vtab_cursor *cur){
   15278   ExpertCsr *pCsr = (ExpertCsr*)cur;
   15279   sqlite3_finalize(pCsr->pData);
   15280   sqlite3_free(pCsr);
   15281   return SQLITE_OK;
   15282 }
   15283 
   15284 /*
   15285 ** Virtual table module xEof method.
   15286 **
   15287 ** Return non-zero if the cursor does not currently point to a valid
   15288 ** record (i.e if the scan has finished), or zero otherwise.
   15289 */
   15290 static int expertEof(sqlite3_vtab_cursor *cur){
   15291   ExpertCsr *pCsr = (ExpertCsr*)cur;
   15292   return pCsr->pData==0;
   15293 }
   15294 
   15295 /*
   15296 ** Virtual table module xNext method.
   15297 */
   15298 static int expertNext(sqlite3_vtab_cursor *cur){
   15299   ExpertCsr *pCsr = (ExpertCsr*)cur;
   15300   int rc = SQLITE_OK;
   15301 
   15302   assert( pCsr->pData );
   15303   rc = sqlite3_step(pCsr->pData);
   15304   if( rc!=SQLITE_ROW ){
   15305     rc = sqlite3_finalize(pCsr->pData);
   15306     pCsr->pData = 0;
   15307   }else{
   15308     rc = SQLITE_OK;
   15309   }
   15310 
   15311   return rc;
   15312 }
   15313 
   15314 /*
   15315 ** Virtual table module xRowid method.
   15316 */
   15317 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
   15318   (void)cur;
   15319   *pRowid = 0;
   15320   return SQLITE_OK;
   15321 }
   15322 
   15323 /*
   15324 ** Virtual table module xColumn method.
   15325 */
   15326 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   15327   ExpertCsr *pCsr = (ExpertCsr*)cur;
   15328   sqlite3_value *pVal;
   15329   pVal = sqlite3_column_value(pCsr->pData, i);
   15330   if( pVal ){
   15331     sqlite3_result_value(ctx, pVal);
   15332   }
   15333   return SQLITE_OK;
   15334 }
   15335 
   15336 /*
   15337 ** Virtual table module xFilter method.
   15338 */
   15339 static int expertFilter(
   15340   sqlite3_vtab_cursor *cur,
   15341   int idxNum, const char *idxStr,
   15342   int argc, sqlite3_value **argv
   15343 ){
   15344   ExpertCsr *pCsr = (ExpertCsr*)cur;
   15345   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
   15346   sqlite3expert *pExpert = pVtab->pExpert;
   15347   int rc;
   15348 
   15349   (void)idxNum;
   15350   (void)idxStr;
   15351   (void)argc;
   15352   (void)argv;
   15353   rc = sqlite3_finalize(pCsr->pData);
   15354   pCsr->pData = 0;
   15355   if( rc==SQLITE_OK ){
   15356     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
   15357         "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName
   15358     );
   15359   }
   15360 
   15361   if( rc==SQLITE_OK ){
   15362     rc = expertNext(cur);
   15363   }
   15364   return rc;
   15365 }
   15366 
   15367 static int idxRegisterVtab(sqlite3expert *p){
   15368   static sqlite3_module expertModule = {
   15369     2,                            /* iVersion */
   15370     expertConnect,                /* xCreate - create a table */
   15371     expertConnect,                /* xConnect - connect to an existing table */
   15372     expertBestIndex,              /* xBestIndex - Determine search strategy */
   15373     expertDisconnect,             /* xDisconnect - Disconnect from a table */
   15374     expertDisconnect,             /* xDestroy - Drop a table */
   15375     expertOpen,                   /* xOpen - open a cursor */
   15376     expertClose,                  /* xClose - close a cursor */
   15377     expertFilter,                 /* xFilter - configure scan constraints */
   15378     expertNext,                   /* xNext - advance a cursor */
   15379     expertEof,                    /* xEof */
   15380     expertColumn,                 /* xColumn - read data */
   15381     expertRowid,                  /* xRowid - read data */
   15382     expertUpdate,                 /* xUpdate - write data */
   15383     0,                            /* xBegin - begin transaction */
   15384     0,                            /* xSync - sync transaction */
   15385     0,                            /* xCommit - commit transaction */
   15386     0,                            /* xRollback - rollback transaction */
   15387     0,                            /* xFindFunction - function overloading */
   15388     0,                            /* xRename - rename the table */
   15389     0,                            /* xSavepoint */
   15390     0,                            /* xRelease */
   15391     0,                            /* xRollbackTo */
   15392     0,                            /* xShadowName */
   15393     0,                            /* xIntegrity */
   15394   };
   15395 
   15396   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
   15397 }
   15398 /*
   15399 ** End of virtual table implementation.
   15400 *************************************************************************/
   15401 /*
   15402 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
   15403 ** is called, set it to the return value of sqlite3_finalize() before
   15404 ** returning. Otherwise, discard the sqlite3_finalize() return value.
   15405 */
   15406 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
   15407   int rc = sqlite3_finalize(pStmt);
   15408   if( *pRc==SQLITE_OK ) *pRc = rc;
   15409 }
   15410 
   15411 /*
   15412 ** Attempt to allocate an IdxTable structure corresponding to table zTab
   15413 ** in the main database of connection db. If successful, set (*ppOut) to
   15414 ** point to the new object and return SQLITE_OK. Otherwise, return an
   15415 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
   15416 ** set to point to an error string.
   15417 **
   15418 ** It is the responsibility of the caller to eventually free either the
   15419 ** IdxTable object or error message using sqlite3_free().
   15420 */
   15421 static int idxGetTableInfo(
   15422   sqlite3 *db,                    /* Database connection to read details from */
   15423   const char *zTab,               /* Table name */
   15424   IdxTable **ppOut,               /* OUT: New object (if successful) */
   15425   char **pzErrmsg                 /* OUT: Error message (if not) */
   15426 ){
   15427   sqlite3_stmt *p1 = 0;
   15428   int nCol = 0;
   15429   int nTab;
   15430   i64 nByte;
   15431   IdxTable *pNew = 0;
   15432   int rc, rc2;
   15433   char *pCsr = 0;
   15434   int nPk = 0;
   15435 
   15436   *ppOut = 0;
   15437   if( zTab==0 ) return SQLITE_ERROR;
   15438   nTab = STRLEN(zTab);
   15439   nByte = sizeof(IdxTable) + nTab + 1;
   15440   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
   15441   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
   15442     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
   15443     const char *zColSeq = 0;
   15444     if( zCol==0 ){
   15445       rc = SQLITE_ERROR;
   15446       break;
   15447     }
   15448     nByte += 1 + STRLEN(zCol);
   15449     rc = sqlite3_table_column_metadata(
   15450         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
   15451     );
   15452     if( zColSeq==0 ) zColSeq = "binary";
   15453     nByte += 1 + STRLEN(zColSeq);
   15454     nCol++;
   15455     nPk += (sqlite3_column_int(p1, 5)>0);
   15456   }
   15457   rc2 = sqlite3_reset(p1);
   15458   if( rc==SQLITE_OK ) rc = rc2;
   15459 
   15460   nByte += sizeof(IdxColumn) * nCol;
   15461   if( rc==SQLITE_OK ){
   15462     pNew = idxMalloc(&rc, nByte);
   15463   }
   15464   if( rc==SQLITE_OK ){
   15465     pNew->aCol = (IdxColumn*)&pNew[1];
   15466     pNew->nCol = nCol;
   15467     pCsr = (char*)&pNew->aCol[nCol];
   15468   }
   15469 
   15470   nCol = 0;
   15471   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
   15472     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
   15473     const char *zColSeq = 0;
   15474     int nCopy;
   15475     if( zCol==0 ) continue;
   15476     nCopy = STRLEN(zCol) + 1;
   15477     pNew->aCol[nCol].zName = pCsr;
   15478     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
   15479     memcpy(pCsr, zCol, nCopy);
   15480     pCsr += nCopy;
   15481 
   15482     rc = sqlite3_table_column_metadata(
   15483         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
   15484     );
   15485     if( rc==SQLITE_OK ){
   15486       if( zColSeq==0 ) zColSeq = "binary";
   15487       nCopy = STRLEN(zColSeq) + 1;
   15488       pNew->aCol[nCol].zColl = pCsr;
   15489       memcpy(pCsr, zColSeq, nCopy);
   15490       pCsr += nCopy;
   15491     }
   15492 
   15493     nCol++;
   15494   }
   15495   idxFinalize(&rc, p1);
   15496 
   15497   if( rc!=SQLITE_OK ){
   15498     sqlite3_free(pNew);
   15499     pNew = 0;
   15500   }else if( ALWAYS(pNew!=0) ){
   15501     pNew->zName = pCsr;
   15502     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
   15503   }
   15504 
   15505   *ppOut = pNew;
   15506   return rc;
   15507 }
   15508 
   15509 /*
   15510 ** This function is a no-op if *pRc is set to anything other than
   15511 ** SQLITE_OK when it is called.
   15512 **
   15513 ** If *pRc is initially set to SQLITE_OK, then the text specified by
   15514 ** the printf() style arguments is appended to zIn and the result returned
   15515 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
   15516 ** zIn before returning.
   15517 */
   15518 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
   15519   va_list ap;
   15520   char *zAppend = 0;
   15521   char *zRet = 0;
   15522   i64 nIn = zIn ? STRLEN(zIn) : 0;
   15523   i64 nAppend = 0;
   15524   va_start(ap, zFmt);
   15525   if( *pRc==SQLITE_OK ){
   15526     zAppend = sqlite3_vmprintf(zFmt, ap);
   15527     if( zAppend ){
   15528       nAppend = STRLEN(zAppend);
   15529       zRet = (char*)sqlite3_malloc64(nIn + nAppend + 1);
   15530     }
   15531     if( zAppend && zRet ){
   15532       if( nIn ) memcpy(zRet, zIn, nIn);
   15533       memcpy(&zRet[nIn], zAppend, nAppend+1);
   15534     }else{
   15535       sqlite3_free(zRet);
   15536       zRet = 0;
   15537       *pRc = SQLITE_NOMEM;
   15538     }
   15539     sqlite3_free(zAppend);
   15540     sqlite3_free(zIn);
   15541   }
   15542   va_end(ap);
   15543   return zRet;
   15544 }
   15545 
   15546 /*
   15547 ** Return true if zId must be quoted in order to use it as an SQL
   15548 ** identifier, or false otherwise.
   15549 */
   15550 static int idxIdentifierRequiresQuotes(const char *zId){
   15551   int i;
   15552   int nId = STRLEN(zId);
   15553 
   15554   if( sqlite3_keyword_check(zId, nId) ) return 1;
   15555 
   15556   for(i=0; zId[i]; i++){
   15557     if( !(zId[i]=='_')
   15558      && !(zId[i]>='0' && zId[i]<='9')
   15559      && !(zId[i]>='a' && zId[i]<='z')
   15560      && !(zId[i]>='A' && zId[i]<='Z')
   15561     ){
   15562       return 1;
   15563     }
   15564   }
   15565   return 0;
   15566 }
   15567 
   15568 /*
   15569 ** This function appends an index column definition suitable for constraint
   15570 ** pCons to the string passed as zIn and returns the result.
   15571 */
   15572 static char *idxAppendColDefn(
   15573   int *pRc,                       /* IN/OUT: Error code */
   15574   char *zIn,                      /* Column defn accumulated so far */
   15575   IdxTable *pTab,                 /* Table index will be created on */
   15576   IdxConstraint *pCons
   15577 ){
   15578   char *zRet = zIn;
   15579   IdxColumn *p = &pTab->aCol[pCons->iCol];
   15580   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
   15581 
   15582   if( idxIdentifierRequiresQuotes(p->zName) ){
   15583     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
   15584   }else{
   15585     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
   15586   }
   15587 
   15588   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
   15589     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
   15590       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
   15591     }else{
   15592       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
   15593     }
   15594   }
   15595 
   15596   if( pCons->bDesc ){
   15597     zRet = idxAppendText(pRc, zRet, " DESC");
   15598   }
   15599   return zRet;
   15600 }
   15601 
   15602 /*
   15603 ** Search database dbm for an index compatible with the one idxCreateFromCons()
   15604 ** would create from arguments pScan, pEq and pTail. If no error occurs and
   15605 ** such an index is found, return non-zero. Or, if no such index is found,
   15606 ** return zero.
   15607 **
   15608 ** If an error occurs, set *pRc to an SQLite error code and return zero.
   15609 */
   15610 static int idxFindCompatible(
   15611   int *pRc,                       /* OUT: Error code */
   15612   sqlite3* dbm,                   /* Database to search */
   15613   IdxScan *pScan,                 /* Scan for table to search for index on */
   15614   IdxConstraint *pEq,             /* List of == constraints */
   15615   IdxConstraint *pTail            /* List of range constraints */
   15616 ){
   15617   const char *zTbl = pScan->pTab->zName;
   15618   sqlite3_stmt *pIdxList = 0;
   15619   IdxConstraint *pIter;
   15620   int nEq = 0;                    /* Number of elements in pEq */
   15621   int rc;
   15622 
   15623   /* Count the elements in list pEq */
   15624   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
   15625 
   15626   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
   15627   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
   15628     int bMatch = 1;
   15629     IdxConstraint *pT = pTail;
   15630     sqlite3_stmt *pInfo = 0;
   15631     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
   15632     if( zIdx==0 ) continue;
   15633 
   15634     /* Zero the IdxConstraint.bFlag values in the pEq list */
   15635     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
   15636 
   15637     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
   15638     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
   15639       int iIdx = sqlite3_column_int(pInfo, 0);
   15640       int iCol = sqlite3_column_int(pInfo, 1);
   15641       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
   15642 
   15643       if( iIdx<nEq ){
   15644         for(pIter=pEq; pIter; pIter=pIter->pLink){
   15645           if( pIter->bFlag ) continue;
   15646           if( pIter->iCol!=iCol ) continue;
   15647           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
   15648           pIter->bFlag = 1;
   15649           break;
   15650         }
   15651         if( pIter==0 ){
   15652           bMatch = 0;
   15653           break;
   15654         }
   15655       }else{
   15656         if( pT ){
   15657           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
   15658             bMatch = 0;
   15659             break;
   15660           }
   15661           pT = pT->pLink;
   15662         }
   15663       }
   15664     }
   15665     idxFinalize(&rc, pInfo);
   15666 
   15667     if( rc==SQLITE_OK && bMatch ){
   15668       sqlite3_finalize(pIdxList);
   15669       return 1;
   15670     }
   15671   }
   15672   idxFinalize(&rc, pIdxList);
   15673 
   15674   *pRc = rc;
   15675   return 0;
   15676 }
   15677 
   15678 /* Callback for sqlite3_exec() with query with leading count(*) column.
   15679  * The first argument is expected to be an int*, referent to be incremented
   15680  * if that leading column is not exactly '0'.
   15681  */
   15682 static int countNonzeros(void* pCount, int nc,
   15683                          char* azResults[], char* azColumns[]){
   15684   (void)azColumns;  /* Suppress unused parameter warning */
   15685   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
   15686     *((int *)pCount) += 1;
   15687   }
   15688   return 0;
   15689 }
   15690 
   15691 static int idxCreateFromCons(
   15692   sqlite3expert *p,
   15693   IdxScan *pScan,
   15694   IdxConstraint *pEq,
   15695   IdxConstraint *pTail
   15696 ){
   15697   sqlite3 *dbm = p->dbm;
   15698   int rc = SQLITE_OK;
   15699   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
   15700     IdxTable *pTab = pScan->pTab;
   15701     char *zCols = 0;
   15702     char *zIdx = 0;
   15703     IdxConstraint *pCons;
   15704     unsigned int h = 0;
   15705     const char *zFmt;
   15706 
   15707     for(pCons=pEq; pCons; pCons=pCons->pLink){
   15708       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
   15709     }
   15710     for(pCons=pTail; pCons; pCons=pCons->pLink){
   15711       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
   15712     }
   15713 
   15714     if( rc==SQLITE_OK ){
   15715       /* Hash the list of columns to come up with a name for the index */
   15716       const char *zTable = pScan->pTab->zName;
   15717       int quoteTable = idxIdentifierRequiresQuotes(zTable);
   15718       char *zName = 0;          /* Index name */
   15719       int collisions = 0;
   15720       do{
   15721         int i;
   15722         char *zFind;
   15723         for(i=0; zCols[i]; i++){
   15724           h += ((h<<3) + zCols[i]);
   15725         }
   15726         sqlite3_free(zName);
   15727         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
   15728         if( zName==0 ) break;
   15729         /* Is is unique among table, view and index names? */
   15730         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
   15731           " AND type in ('index','table','view')";
   15732         zFind = sqlite3_mprintf(zFmt, zName);
   15733         i = 0;
   15734         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
   15735         assert(rc==SQLITE_OK);
   15736         sqlite3_free(zFind);
   15737         if( i==0 ){
   15738           collisions = 0;
   15739           break;
   15740         }
   15741         ++collisions;
   15742       }while( collisions<50 && zName!=0 );
   15743       if( collisions ){
   15744         /* This return means "Gave up trying to find a unique index name." */
   15745         rc = SQLITE_BUSY_TIMEOUT;
   15746       }else if( zName==0 ){
   15747         rc = SQLITE_NOMEM;
   15748       }else{
   15749         if( quoteTable ){
   15750           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
   15751         }else{
   15752           zFmt = "CREATE INDEX %s ON %s(%s)";
   15753         }
   15754         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
   15755         if( !zIdx ){
   15756           rc = SQLITE_NOMEM;
   15757         }else{
   15758           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
   15759           if( rc!=SQLITE_OK ){
   15760             rc = SQLITE_BUSY_TIMEOUT;
   15761           }else{
   15762             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
   15763           }
   15764         }
   15765         sqlite3_free(zName);
   15766         sqlite3_free(zIdx);
   15767       }
   15768     }
   15769 
   15770     sqlite3_free(zCols);
   15771   }
   15772   return rc;
   15773 }
   15774 
   15775 /*
   15776 ** Return true if list pList (linked by IdxConstraint.pLink) contains
   15777 ** a constraint compatible with *p. Otherwise return false.
   15778 */
   15779 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
   15780   IdxConstraint *pCmp;
   15781   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
   15782     if( p->iCol==pCmp->iCol ) return 1;
   15783   }
   15784   return 0;
   15785 }
   15786 
   15787 static int idxCreateFromWhere(
   15788   sqlite3expert *p,
   15789   IdxScan *pScan,                 /* Create indexes for this scan */
   15790   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
   15791 ){
   15792   IdxConstraint *p1 = 0;
   15793   IdxConstraint *pCon;
   15794   int rc;
   15795 
   15796   /* Gather up all the == constraints. */
   15797   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
   15798     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
   15799       pCon->pLink = p1;
   15800       p1 = pCon;
   15801     }
   15802   }
   15803 
   15804   /* Create an index using the == constraints collected above. And the
   15805   ** range constraint/ORDER BY terms passed in by the caller, if any. */
   15806   rc = idxCreateFromCons(p, pScan, p1, pTail);
   15807 
   15808   /* If no range/ORDER BY passed by the caller, create a version of the
   15809   ** index for each range constraint.  */
   15810   if( pTail==0 ){
   15811     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
   15812       assert( pCon->pLink==0 );
   15813       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
   15814         rc = idxCreateFromCons(p, pScan, p1, pCon);
   15815       }
   15816     }
   15817   }
   15818 
   15819   return rc;
   15820 }
   15821 
   15822 /*
   15823 ** Create candidate indexes in database [dbm] based on the data in
   15824 ** linked-list pScan.
   15825 */
   15826 static int idxCreateCandidates(sqlite3expert *p){
   15827   int rc = SQLITE_OK;
   15828   IdxScan *pIter;
   15829 
   15830   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
   15831     rc = idxCreateFromWhere(p, pIter, 0);
   15832     if( rc==SQLITE_OK && pIter->pOrder ){
   15833       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
   15834     }
   15835   }
   15836 
   15837   return rc;
   15838 }
   15839 
   15840 /*
   15841 ** Free all elements of the linked list starting at pConstraint.
   15842 */
   15843 static void idxConstraintFree(IdxConstraint *pConstraint){
   15844   IdxConstraint *pNext;
   15845   IdxConstraint *p;
   15846 
   15847   for(p=pConstraint; p; p=pNext){
   15848     pNext = p->pNext;
   15849     sqlite3_free(p);
   15850   }
   15851 }
   15852 
   15853 /*
   15854 ** Free all elements of the linked list starting from pScan up until pLast
   15855 ** (pLast is not freed).
   15856 */
   15857 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
   15858   IdxScan *p;
   15859   IdxScan *pNext;
   15860   for(p=pScan; p!=pLast; p=pNext){
   15861     pNext = p->pNextScan;
   15862     idxConstraintFree(p->pOrder);
   15863     idxConstraintFree(p->pEq);
   15864     idxConstraintFree(p->pRange);
   15865     sqlite3_free(p);
   15866   }
   15867 }
   15868 
   15869 /*
   15870 ** Free all elements of the linked list starting from pStatement up
   15871 ** until pLast (pLast is not freed).
   15872 */
   15873 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
   15874   IdxStatement *p;
   15875   IdxStatement *pNext;
   15876   for(p=pStatement; p!=pLast; p=pNext){
   15877     pNext = p->pNext;
   15878     sqlite3_free(p->zEQP);
   15879     sqlite3_free(p->zIdx);
   15880     sqlite3_free(p);
   15881   }
   15882 }
   15883 
   15884 /*
   15885 ** Free the linked list of IdxTable objects starting at pTab.
   15886 */
   15887 static void idxTableFree(IdxTable *pTab){
   15888   IdxTable *pIter;
   15889   IdxTable *pNext;
   15890   for(pIter=pTab; pIter; pIter=pNext){
   15891     pNext = pIter->pNext;
   15892     sqlite3_free(pIter);
   15893   }
   15894 }
   15895 
   15896 /*
   15897 ** Free the linked list of IdxWrite objects starting at pTab.
   15898 */
   15899 static void idxWriteFree(IdxWrite *pTab){
   15900   IdxWrite *pIter;
   15901   IdxWrite *pNext;
   15902   for(pIter=pTab; pIter; pIter=pNext){
   15903     pNext = pIter->pNext;
   15904     sqlite3_free(pIter);
   15905   }
   15906 }
   15907 
   15908 
   15909 
   15910 /*
   15911 ** This function is called after candidate indexes have been created. It
   15912 ** runs all the queries to see which indexes they prefer, and populates
   15913 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
   15914 */
   15915 static int idxFindIndexes(
   15916   sqlite3expert *p,
   15917   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
   15918 ){
   15919   IdxStatement *pStmt;
   15920   sqlite3 *dbm = p->dbm;
   15921   int rc = SQLITE_OK;
   15922 
   15923   IdxHash hIdx;
   15924   idxHashInit(&hIdx);
   15925 
   15926   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
   15927     IdxHashEntry *pEntry;
   15928     sqlite3_stmt *pExplain = 0;
   15929     idxHashClear(&hIdx);
   15930     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
   15931         "EXPLAIN QUERY PLAN %s", pStmt->zSql
   15932     );
   15933     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
   15934       /* int iId = sqlite3_column_int(pExplain, 0); */
   15935       /* int iParent = sqlite3_column_int(pExplain, 1); */
   15936       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
   15937       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
   15938       int nDetail;
   15939       int i;
   15940 
   15941       if( !zDetail ) continue;
   15942       nDetail = STRLEN(zDetail);
   15943 
   15944       for(i=0; i<nDetail; i++){
   15945         const char *zIdx = 0;
   15946         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
   15947           zIdx = &zDetail[i+13];
   15948         }else if( i+22<nDetail
   15949             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
   15950         ){
   15951           zIdx = &zDetail[i+22];
   15952         }
   15953         if( zIdx ){
   15954           const char *zSql;
   15955           int nIdx = 0;
   15956           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
   15957             nIdx++;
   15958           }
   15959           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
   15960           if( zSql ){
   15961             idxHashAdd(&rc, &hIdx, zSql, 0);
   15962             if( rc ) goto find_indexes_out;
   15963           }
   15964           break;
   15965         }
   15966       }
   15967 
   15968       if( zDetail[0]!='-' ){
   15969         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
   15970       }
   15971     }
   15972 
   15973     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
   15974       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
   15975     }
   15976 
   15977     idxFinalize(&rc, pExplain);
   15978   }
   15979 
   15980  find_indexes_out:
   15981   idxHashClear(&hIdx);
   15982   return rc;
   15983 }
   15984 
   15985 static int idxAuthCallback(
   15986   void *pCtx,
   15987   int eOp,
   15988   const char *z3,
   15989   const char *z4,
   15990   const char *zDb,
   15991   const char *zTrigger
   15992 ){
   15993   int rc = SQLITE_OK;
   15994   (void)z4;
   15995   (void)zTrigger;
   15996   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
   15997     if( sqlite3_stricmp(zDb, "main")==0 ){
   15998       sqlite3expert *p = (sqlite3expert*)pCtx;
   15999       IdxTable *pTab;
   16000       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
   16001         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
   16002       }
   16003       if( pTab ){
   16004         IdxWrite *pWrite;
   16005         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
   16006           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
   16007         }
   16008         if( pWrite==0 ){
   16009           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
   16010           if( rc==SQLITE_OK ){
   16011             pWrite->pTab = pTab;
   16012             pWrite->eOp = eOp;
   16013             pWrite->pNext = p->pWrite;
   16014             p->pWrite = pWrite;
   16015           }
   16016         }
   16017       }
   16018     }
   16019   }
   16020   return rc;
   16021 }
   16022 
   16023 static int idxProcessOneTrigger(
   16024   sqlite3expert *p,
   16025   IdxWrite *pWrite,
   16026   char **pzErr
   16027 ){
   16028   static const char *zInt = UNIQUE_TABLE_NAME;
   16029   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
   16030   IdxTable *pTab = pWrite->pTab;
   16031   const char *zTab = pTab->zName;
   16032   const char *zSql =
   16033     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
   16034     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
   16035     "ORDER BY type;";
   16036   sqlite3_stmt *pSelect = 0;
   16037   int rc = SQLITE_OK;
   16038   char *zWrite = 0;
   16039 
   16040   /* Create the table and its triggers in the temp schema */
   16041   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
   16042   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
   16043     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
   16044     if( zCreate==0 ) continue;
   16045     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
   16046   }
   16047   idxFinalize(&rc, pSelect);
   16048 
   16049   /* Rename the table in the temp schema to zInt */
   16050   if( rc==SQLITE_OK ){
   16051     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
   16052     if( z==0 ){
   16053       rc = SQLITE_NOMEM;
   16054     }else{
   16055       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
   16056       sqlite3_free(z);
   16057     }
   16058   }
   16059 
   16060   switch( pWrite->eOp ){
   16061     case SQLITE_INSERT: {
   16062       int i;
   16063       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
   16064       for(i=0; i<pTab->nCol; i++){
   16065         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
   16066       }
   16067       zWrite = idxAppendText(&rc, zWrite, ")");
   16068       break;
   16069     }
   16070     case SQLITE_UPDATE: {
   16071       int i;
   16072       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
   16073       for(i=0; i<pTab->nCol; i++){
   16074         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
   16075             pTab->aCol[i].zName
   16076         );
   16077       }
   16078       break;
   16079     }
   16080     default: {
   16081       assert( pWrite->eOp==SQLITE_DELETE );
   16082       if( rc==SQLITE_OK ){
   16083         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
   16084         if( zWrite==0 ) rc = SQLITE_NOMEM;
   16085       }
   16086     }
   16087   }
   16088 
   16089   if( rc==SQLITE_OK ){
   16090     sqlite3_stmt *pX = 0;
   16091     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
   16092     idxFinalize(&rc, pX);
   16093     if( rc!=SQLITE_OK ){
   16094       idxDatabaseError(p->dbv, pzErr);
   16095     }
   16096   }
   16097   sqlite3_free(zWrite);
   16098 
   16099   if( rc==SQLITE_OK ){
   16100     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
   16101   }
   16102 
   16103   return rc;
   16104 }
   16105 
   16106 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
   16107   int rc = SQLITE_OK;
   16108   IdxWrite *pEnd = 0;
   16109   IdxWrite *pFirst = p->pWrite;
   16110 
   16111   while( rc==SQLITE_OK && pFirst!=pEnd ){
   16112     IdxWrite *pIter;
   16113     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
   16114       rc = idxProcessOneTrigger(p, pIter, pzErr);
   16115     }
   16116     pEnd = pFirst;
   16117     pFirst = p->pWrite;
   16118   }
   16119 
   16120   return rc;
   16121 }
   16122 
   16123 /*
   16124 ** This function tests if the schema of the main database of database handle
   16125 ** db contains an object named zTab. Assuming no error occurs, output parameter
   16126 ** (*pbContains) is set to true if zTab exists, or false if it does not.
   16127 **
   16128 ** Or, if an error occurs, an SQLite error code is returned. The final value
   16129 ** of (*pbContains) is undefined in this case.
   16130 */
   16131 static int expertDbContainsObject(
   16132   sqlite3 *db,
   16133   const char *zTab,
   16134   int *pbContains                 /* OUT: True if object exists */
   16135 ){
   16136   const char *zSql = "SELECT 1 FROM sqlite_schema WHERE name = ?";
   16137   sqlite3_stmt *pSql = 0;
   16138   int rc = SQLITE_OK;
   16139   int ret = 0;
   16140 
   16141   rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
   16142   if( rc==SQLITE_OK ){
   16143     sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC);
   16144     if( SQLITE_ROW==sqlite3_step(pSql) ){
   16145       ret = 1;
   16146     }
   16147     rc = sqlite3_finalize(pSql);
   16148   }
   16149 
   16150   *pbContains = ret;
   16151   return rc;
   16152 }
   16153 
   16154 /*
   16155 ** Execute SQL command zSql using database handle db. If no error occurs,
   16156 ** set (*pzErr) to NULL and return SQLITE_OK.
   16157 **
   16158 ** If an error does occur, return an SQLite error code and set (*pzErr) to
   16159 ** point to a buffer containing an English language error message. Except,
   16160 ** if the error message begins with "no such module:", then ignore the
   16161 ** error and return as if the SQL statement had succeeded.
   16162 **
   16163 ** This is used to copy as much of the database schema as possible while
   16164 ** ignoring any errors related to missing virtual table modules.
   16165 */
   16166 static int expertSchemaSql(sqlite3 *db, const char *zSql, char **pzErr){
   16167   int rc = SQLITE_OK;
   16168   char *zErr = 0;
   16169 
   16170   rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
   16171   if( rc!=SQLITE_OK && zErr ){
   16172     int nErr = STRLEN(zErr);
   16173     if( nErr>=15 && memcmp(zErr, "no such module:", 15)==0 ){
   16174       sqlite3_free(zErr);
   16175       rc = SQLITE_OK;
   16176       zErr = 0;
   16177     }
   16178   }
   16179 
   16180   *pzErr = zErr;
   16181   return rc;
   16182 }
   16183 
   16184 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
   16185   int rc = idxRegisterVtab(p);
   16186   sqlite3_stmt *pSchema = 0;
   16187 
   16188   /* For each table in the main db schema:
   16189   **
   16190   **   1) Add an entry to the p->pTable list, and
   16191   **   2) Create the equivalent virtual table in dbv.
   16192   */
   16193   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
   16194       "SELECT type, name, sql, 1, "
   16195       "       substr(sql,1,14)=='create virtual' COLLATE nocase "
   16196       "FROM sqlite_schema "
   16197       "WHERE type IN ('table','view') AND "
   16198       "      substr(name,1,7)!='sqlite_' COLLATE nocase "
   16199       " UNION ALL "
   16200       "SELECT type, name, sql, 2, 0 FROM sqlite_schema "
   16201       "WHERE type = 'trigger'"
   16202       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
   16203       "ORDER BY 4, 5 DESC, 1"
   16204   );
   16205   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
   16206     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
   16207     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
   16208     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
   16209     int bVirtual = sqlite3_column_int(pSchema, 4);
   16210     int bExists = 0;
   16211 
   16212     if( zType==0 || zName==0 ) continue;
   16213     rc = expertDbContainsObject(p->dbv, zName, &bExists);
   16214     if( rc || bExists ) continue;
   16215 
   16216     if( zType[0]=='v' || zType[1]=='r' || bVirtual ){
   16217       /* A view. Or a trigger on a view. */
   16218       if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg);
   16219     }else{
   16220       IdxTable *pTab;
   16221       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
   16222       if( rc==SQLITE_OK && ALWAYS(pTab!=0) ){
   16223         int i;
   16224         char *zInner = 0;
   16225         char *zOuter = 0;
   16226         pTab->pNext = p->pTable;
   16227         p->pTable = pTab;
   16228 
   16229         /* The statement the vtab will pass to sqlite3_declare_vtab() */
   16230         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
   16231         for(i=0; i<pTab->nCol; i++){
   16232           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
   16233               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
   16234           );
   16235         }
   16236         zInner = idxAppendText(&rc, zInner, ")");
   16237 
   16238         /* The CVT statement to create the vtab */
   16239         zOuter = idxAppendText(&rc, 0,
   16240             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
   16241         );
   16242         if( rc==SQLITE_OK ){
   16243           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
   16244         }
   16245         sqlite3_free(zInner);
   16246         sqlite3_free(zOuter);
   16247       }
   16248     }
   16249   }
   16250   idxFinalize(&rc, pSchema);
   16251   return rc;
   16252 }
   16253 
   16254 struct IdxSampleCtx {
   16255   int iTarget;
   16256   double target;                  /* Target nRet/nRow value */
   16257   double nRow;                    /* Number of rows seen */
   16258   double nRet;                    /* Number of rows returned */
   16259 };
   16260 
   16261 static void idxSampleFunc(
   16262   sqlite3_context *pCtx,
   16263   int argc,
   16264   sqlite3_value **argv
   16265 ){
   16266   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
   16267   int bRet;
   16268 
   16269   (void)argv;
   16270   assert( argc==0 );
   16271   if( p->nRow==0.0 ){
   16272     bRet = 1;
   16273   }else{
   16274     bRet = (p->nRet / p->nRow) <= p->target;
   16275     if( bRet==0 ){
   16276       unsigned short rnd;
   16277       sqlite3_randomness(2, (void*)&rnd);
   16278       bRet = ((int)rnd % 100) <= p->iTarget;
   16279     }
   16280   }
   16281 
   16282   sqlite3_result_int(pCtx, bRet);
   16283   p->nRow += 1.0;
   16284   p->nRet += (double)bRet;
   16285 }
   16286 
   16287 struct IdxRemCtx {
   16288   int nSlot;
   16289   struct IdxRemSlot {
   16290     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
   16291     i64 iVal;                     /* SQLITE_INTEGER value */
   16292     double rVal;                  /* SQLITE_FLOAT value */
   16293     i64 nByte;                    /* Bytes of space allocated at z */
   16294     i64 n;                        /* Size of buffer z */
   16295     char *z;                      /* SQLITE_TEXT/BLOB value */
   16296   } aSlot[1];
   16297 };
   16298 
   16299 /*
   16300 ** Implementation of scalar function sqlite_expert_rem().
   16301 */
   16302 static void idxRemFunc(
   16303   sqlite3_context *pCtx,
   16304   int argc,
   16305   sqlite3_value **argv
   16306 ){
   16307   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
   16308   struct IdxRemSlot *pSlot;
   16309   int iSlot;
   16310   assert( argc==2 );
   16311 
   16312   iSlot = sqlite3_value_int(argv[0]);
   16313   assert( iSlot<p->nSlot );
   16314   pSlot = &p->aSlot[iSlot];
   16315 
   16316   switch( pSlot->eType ){
   16317     case SQLITE_NULL:
   16318       /* no-op */
   16319       break;
   16320 
   16321     case SQLITE_INTEGER:
   16322       sqlite3_result_int64(pCtx, pSlot->iVal);
   16323       break;
   16324 
   16325     case SQLITE_FLOAT:
   16326       sqlite3_result_double(pCtx, pSlot->rVal);
   16327       break;
   16328 
   16329     case SQLITE_BLOB:
   16330       assert( pSlot->n <= 0x7fffffff );
   16331       sqlite3_result_blob(pCtx, pSlot->z, (int)pSlot->n, SQLITE_TRANSIENT);
   16332       break;
   16333 
   16334     case SQLITE_TEXT:
   16335       assert( pSlot->n <= 0x7fffffff );
   16336       sqlite3_result_text(pCtx, pSlot->z, (int)pSlot->n, SQLITE_TRANSIENT);
   16337       break;
   16338   }
   16339 
   16340   pSlot->eType = sqlite3_value_type(argv[1]);
   16341   switch( pSlot->eType ){
   16342     case SQLITE_NULL:
   16343       /* no-op */
   16344       break;
   16345 
   16346     case SQLITE_INTEGER:
   16347       pSlot->iVal = sqlite3_value_int64(argv[1]);
   16348       break;
   16349 
   16350     case SQLITE_FLOAT:
   16351       pSlot->rVal = sqlite3_value_double(argv[1]);
   16352       break;
   16353 
   16354     case SQLITE_BLOB:
   16355     case SQLITE_TEXT: {
   16356       i64 nByte = sqlite3_value_bytes(argv[1]);
   16357       const void *pData = 0;
   16358       if( nByte>pSlot->nByte ){
   16359         char *zNew = (char*)sqlite3_realloc64(pSlot->z, nByte*2);
   16360         if( zNew==0 ){
   16361           sqlite3_result_error_nomem(pCtx);
   16362           return;
   16363         }
   16364         pSlot->nByte = nByte*2;
   16365         pSlot->z = zNew;
   16366       }
   16367       pSlot->n = nByte;
   16368       if( pSlot->eType==SQLITE_BLOB ){
   16369         pData = sqlite3_value_blob(argv[1]);
   16370         if( pData ) memcpy(pSlot->z, pData, nByte);
   16371       }else{
   16372         pData = sqlite3_value_text(argv[1]);
   16373         memcpy(pSlot->z, pData, nByte);
   16374       }
   16375       break;
   16376     }
   16377   }
   16378 }
   16379 
   16380 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
   16381   int rc = SQLITE_OK;
   16382   const char *zMax =
   16383     "SELECT max(i.seqno) FROM "
   16384     "  sqlite_schema AS s, "
   16385     "  pragma_index_list(s.name) AS l, "
   16386     "  pragma_index_info(l.name) AS i "
   16387     "WHERE s.type = 'table'";
   16388   sqlite3_stmt *pMax = 0;
   16389 
   16390   *pnMax = 0;
   16391   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
   16392   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
   16393     *pnMax = sqlite3_column_int(pMax, 0) + 1;
   16394   }
   16395   idxFinalize(&rc, pMax);
   16396 
   16397   return rc;
   16398 }
   16399 
   16400 static int idxPopulateOneStat1(
   16401   sqlite3expert *p,
   16402   sqlite3_stmt *pIndexXInfo,
   16403   sqlite3_stmt *pWriteStat,
   16404   const char *zTab,
   16405   const char *zIdx,
   16406   char **pzErr
   16407 ){
   16408   char *zCols = 0;
   16409   char *zOrder = 0;
   16410   char *zQuery = 0;
   16411   int nCol = 0;
   16412   int i;
   16413   sqlite3_stmt *pQuery = 0;
   16414   i64 *aStat = 0;
   16415   int rc = SQLITE_OK;
   16416 
   16417   assert( p->iSample>0 );
   16418 
   16419   /* Formulate the query text */
   16420   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
   16421   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
   16422     const char *zComma = zCols==0 ? "" : ", ";
   16423     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
   16424     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
   16425     if( zName==0 ){
   16426       /* This index contains an expression. Ignore it. */
   16427       sqlite3_free(zCols);
   16428       sqlite3_free(zOrder);
   16429       return sqlite3_reset(pIndexXInfo);
   16430     }
   16431     zCols = idxAppendText(&rc, zCols,
   16432         "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s",
   16433         zComma, zName, nCol, zName, zColl
   16434     );
   16435     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
   16436   }
   16437   sqlite3_reset(pIndexXInfo);
   16438   if( rc==SQLITE_OK ){
   16439     if( p->iSample==100 ){
   16440       zQuery = sqlite3_mprintf(
   16441           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
   16442       );
   16443     }else{
   16444       zQuery = sqlite3_mprintf(
   16445           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
   16446       );
   16447     }
   16448   }
   16449   sqlite3_free(zCols);
   16450   sqlite3_free(zOrder);
   16451 
   16452   /* Formulate the query text */
   16453   if( rc==SQLITE_OK ){
   16454     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
   16455     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
   16456   }
   16457   sqlite3_free(zQuery);
   16458 
   16459   if( rc==SQLITE_OK ){
   16460     aStat = (i64*)idxMalloc(&rc, sizeof(i64)*(nCol+1));
   16461   }
   16462   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
   16463     IdxHashEntry *pEntry;
   16464     char *zStat = 0;
   16465     for(i=0; i<=nCol; i++) aStat[i] = 1;
   16466     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
   16467       aStat[0]++;
   16468       for(i=0; i<nCol; i++){
   16469         if( sqlite3_column_int(pQuery, i)==0 ) break;
   16470       }
   16471       for(/*no-op*/; i<nCol; i++){
   16472         aStat[i+1]++;
   16473       }
   16474     }
   16475 
   16476     if( rc==SQLITE_OK ){
   16477       i64 s0 = aStat[0];
   16478       zStat = sqlite3_mprintf("%lld", s0);
   16479       if( zStat==0 ) rc = SQLITE_NOMEM;
   16480       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
   16481         zStat = idxAppendText(&rc, zStat, " %lld", (s0+aStat[i]/2) / aStat[i]);
   16482       }
   16483     }
   16484 
   16485     if( rc==SQLITE_OK ){
   16486       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
   16487       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
   16488       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
   16489       sqlite3_step(pWriteStat);
   16490       rc = sqlite3_reset(pWriteStat);
   16491     }
   16492 
   16493     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
   16494     if( pEntry ){
   16495       assert( pEntry->zVal2==0 );
   16496       pEntry->zVal2 = zStat;
   16497     }else{
   16498       sqlite3_free(zStat);
   16499     }
   16500   }
   16501   sqlite3_free(aStat);
   16502   idxFinalize(&rc, pQuery);
   16503 
   16504   return rc;
   16505 }
   16506 
   16507 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
   16508   int rc;
   16509   char *zSql;
   16510 
   16511   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
   16512   if( rc!=SQLITE_OK ) return rc;
   16513 
   16514   zSql = sqlite3_mprintf(
   16515       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
   16516   );
   16517   if( zSql==0 ) return SQLITE_NOMEM;
   16518   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
   16519   sqlite3_free(zSql);
   16520 
   16521   return rc;
   16522 }
   16523 
   16524 /*
   16525 ** This function is called as part of sqlite3_expert_analyze(). Candidate
   16526 ** indexes have already been created in database sqlite3expert.dbm, this
   16527 ** function populates sqlite_stat1 table in the same database.
   16528 **
   16529 ** The stat1 data is generated by querying the
   16530 */
   16531 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
   16532   int rc = SQLITE_OK;
   16533   int nMax =0;
   16534   struct IdxRemCtx *pCtx = 0;
   16535   struct IdxSampleCtx samplectx;
   16536   int i;
   16537   i64 iPrev = -100000;
   16538   sqlite3_stmt *pAllIndex = 0;
   16539   sqlite3_stmt *pIndexXInfo = 0;
   16540   sqlite3_stmt *pWrite = 0;
   16541 
   16542   const char *zAllIndex =
   16543     "SELECT s.rowid, s.name, l.name FROM "
   16544     "  sqlite_schema AS s, "
   16545     "  pragma_index_list(s.name) AS l "
   16546     "WHERE s.type = 'table'";
   16547   const char *zIndexXInfo =
   16548     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
   16549   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
   16550 
   16551   /* If iSample==0, no sqlite_stat1 data is required. */
   16552   if( p->iSample==0 ) return SQLITE_OK;
   16553 
   16554   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
   16555   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
   16556 
   16557   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
   16558 
   16559   if( rc==SQLITE_OK ){
   16560     i64 nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
   16561     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
   16562   }
   16563 
   16564   if( rc==SQLITE_OK ){
   16565     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
   16566     rc = sqlite3_create_function(dbrem, "sqlite_expert_rem",
   16567         2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
   16568     );
   16569   }
   16570   if( rc==SQLITE_OK ){
   16571     rc = sqlite3_create_function(p->db, "sqlite_expert_sample",
   16572         0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
   16573     );
   16574   }
   16575 
   16576   if( rc==SQLITE_OK ){
   16577     pCtx->nSlot = (i64)nMax+1;
   16578     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
   16579   }
   16580   if( rc==SQLITE_OK ){
   16581     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
   16582   }
   16583   if( rc==SQLITE_OK ){
   16584     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
   16585   }
   16586 
   16587   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
   16588     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
   16589     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
   16590     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
   16591     if( zTab==0 || zIdx==0 ) continue;
   16592     if( p->iSample<100 && iPrev!=iRowid ){
   16593       samplectx.target = (double)p->iSample / 100.0;
   16594       samplectx.iTarget = p->iSample;
   16595       samplectx.nRow = 0.0;
   16596       samplectx.nRet = 0.0;
   16597       rc = idxBuildSampleTable(p, zTab);
   16598       if( rc!=SQLITE_OK ) break;
   16599     }
   16600     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
   16601     iPrev = iRowid;
   16602   }
   16603   if( rc==SQLITE_OK && p->iSample<100 ){
   16604     rc = sqlite3_exec(p->dbv,
   16605         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
   16606     );
   16607   }
   16608 
   16609   idxFinalize(&rc, pAllIndex);
   16610   idxFinalize(&rc, pIndexXInfo);
   16611   idxFinalize(&rc, pWrite);
   16612 
   16613   if( pCtx ){
   16614     for(i=0; i<pCtx->nSlot; i++){
   16615       sqlite3_free(pCtx->aSlot[i].z);
   16616     }
   16617     sqlite3_free(pCtx);
   16618   }
   16619 
   16620   if( rc==SQLITE_OK ){
   16621     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
   16622   }
   16623 
   16624   sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0);
   16625   sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0);
   16626 
   16627   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
   16628   return rc;
   16629 }
   16630 
   16631 /*
   16632 ** Define and possibly pretend to use a useless collation sequence.
   16633 ** This pretense allows expert to accept SQL using custom collations.
   16634 */
   16635 static int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
   16636   (void)up1;
   16637   (void)up2;
   16638   (void)up3;
   16639   (void)up4;
   16640   (void)up5;
   16641   assert(0); /* VDBE should never be run. */
   16642   return 0;
   16643 }
   16644 /* And a callback to register above upon actual need */
   16645 static void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
   16646   (void)up1;
   16647   sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
   16648 }
   16649 
   16650 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
   16651   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
   16652 /*
   16653 ** dummy functions for no-op implementation of UDFs during expert's work
   16654 */
   16655 static void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
   16656   (void)up1;
   16657   (void)up2;
   16658   (void)up3;
   16659   assert(0); /* VDBE should never be run. */
   16660 }
   16661 static void dummyUDFvalue(sqlite3_context *up1){
   16662   (void)up1;
   16663   assert(0); /* VDBE should never be run. */
   16664 }
   16665 
   16666 /*
   16667 ** Register UDFs from user database with another.
   16668 */
   16669 static int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
   16670   sqlite3_stmt *pStmt;
   16671   int rc = sqlite3_prepare_v2(dbSrc,
   16672             "SELECT name,type,enc,narg,flags "
   16673             "FROM pragma_function_list() "
   16674             "WHERE builtin==0", -1, &pStmt, 0);
   16675   if( rc==SQLITE_OK ){
   16676     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   16677       int nargs = sqlite3_column_int(pStmt,3);
   16678       int flags = sqlite3_column_int(pStmt,4);
   16679       const char *name = (char*)sqlite3_column_text(pStmt,0);
   16680       const char *type = (char*)sqlite3_column_text(pStmt,1);
   16681       const char *enc = (char*)sqlite3_column_text(pStmt,2);
   16682       if( name==0 || type==0 || enc==0 ){
   16683         /* no-op.  Only happens on OOM */
   16684       }else{
   16685         int ienc = SQLITE_UTF8;
   16686         int rcf = SQLITE_ERROR;
   16687         if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
   16688         else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
   16689         ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
   16690         if( strcmp(type,"w")==0 ){
   16691           rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
   16692                                                dummyUDF,dummyUDFvalue,0,0,0);
   16693         }else if( strcmp(type,"a")==0 ){
   16694           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
   16695                                         0,dummyUDF,dummyUDFvalue);
   16696         }else if( strcmp(type,"s")==0 ){
   16697           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
   16698                                         dummyUDF,0,0);
   16699         }
   16700         if( rcf!=SQLITE_OK ){
   16701           rc = rcf;
   16702           break;
   16703         }
   16704       }
   16705     }
   16706     sqlite3_finalize(pStmt);
   16707     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   16708   }
   16709   return rc;
   16710 }
   16711 #endif
   16712 
   16713 /*
   16714 ** Allocate a new sqlite3expert object.
   16715 */
   16716 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
   16717   int rc = SQLITE_OK;
   16718   sqlite3expert *pNew;
   16719 
   16720   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
   16721 
   16722   /* Open two in-memory databases to work with. The "vtab database" (dbv)
   16723   ** will contain a virtual table corresponding to each real table in
   16724   ** the user database schema, and a copy of each view. It is used to
   16725   ** collect information regarding the WHERE, ORDER BY and other clauses
   16726   ** of the user's query.
   16727   */
   16728   if( rc==SQLITE_OK ){
   16729     pNew->db = db;
   16730     pNew->iSample = 100;
   16731     rc = sqlite3_open(":memory:", &pNew->dbv);
   16732   }
   16733   if( rc==SQLITE_OK ){
   16734     rc = sqlite3_open(":memory:", &pNew->dbm);
   16735     if( rc==SQLITE_OK ){
   16736       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
   16737     }
   16738   }
   16739 
   16740   /* Allow custom collations to be dealt with through prepare. */
   16741   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
   16742   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
   16743 
   16744 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
   16745   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
   16746   /* Register UDFs from database [db] with [dbm] and [dbv]. */
   16747   if( rc==SQLITE_OK ){
   16748     rc = registerUDFs(pNew->db, pNew->dbm);
   16749   }
   16750   if( rc==SQLITE_OK ){
   16751     rc = registerUDFs(pNew->db, pNew->dbv);
   16752   }
   16753 #endif
   16754 
   16755   /* Copy the entire schema of database [db] into [dbm]. */
   16756   if( rc==SQLITE_OK ){
   16757     sqlite3_stmt *pSql = 0;
   16758     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
   16759         "SELECT sql, name, substr(sql,1,14)=='create virtual' COLLATE nocase"
   16760         " FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' COLLATE nocase"
   16761         " ORDER BY 3 DESC, rowid"
   16762     );
   16763     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
   16764       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
   16765       const char *zName = (const char*)sqlite3_column_text(pSql, 1);
   16766       int bExists = 0;
   16767       rc = expertDbContainsObject(pNew->dbm, zName, &bExists);
   16768       if( rc==SQLITE_OK && zSql && bExists==0 ){
   16769         rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg);
   16770       }
   16771     }
   16772     idxFinalize(&rc, pSql);
   16773   }
   16774 
   16775   /* Create the vtab schema */
   16776   if( rc==SQLITE_OK ){
   16777     rc = idxCreateVtabSchema(pNew, pzErrmsg);
   16778   }
   16779 
   16780   /* Register the auth callback with dbv */
   16781   if( rc==SQLITE_OK ){
   16782     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
   16783   }
   16784 
   16785   /* If an error has occurred, free the new object and return NULL. Otherwise,
   16786   ** return the new sqlite3expert handle.  */
   16787   if( rc!=SQLITE_OK ){
   16788     sqlite3_expert_destroy(pNew);
   16789     pNew = 0;
   16790   }
   16791   return pNew;
   16792 }
   16793 
   16794 /*
   16795 ** Configure an sqlite3expert object.
   16796 */
   16797 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
   16798   int rc = SQLITE_OK;
   16799   va_list ap;
   16800   va_start(ap, op);
   16801   switch( op ){
   16802     case EXPERT_CONFIG_SAMPLE: {
   16803       int iVal = va_arg(ap, int);
   16804       if( iVal<0 ) iVal = 0;
   16805       if( iVal>100 ) iVal = 100;
   16806       p->iSample = iVal;
   16807       break;
   16808     }
   16809     default:
   16810       rc = SQLITE_NOTFOUND;
   16811       break;
   16812   }
   16813 
   16814   va_end(ap);
   16815   return rc;
   16816 }
   16817 
   16818 /*
   16819 ** Add an SQL statement to the analysis.
   16820 */
   16821 int sqlite3_expert_sql(
   16822   sqlite3expert *p,               /* From sqlite3_expert_new() */
   16823   const char *zSql,               /* SQL statement to add */
   16824   char **pzErr                    /* OUT: Error message (if any) */
   16825 ){
   16826   IdxScan *pScanOrig = p->pScan;
   16827   IdxStatement *pStmtOrig = p->pStatement;
   16828   int rc = SQLITE_OK;
   16829   const char *zStmt = zSql;
   16830 
   16831   if( p->bRun ) return SQLITE_MISUSE;
   16832 
   16833   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
   16834     sqlite3_stmt *pStmt = 0;
   16835     /* Ensure that the provided statement compiles against user's DB. */
   16836     rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
   16837     if( rc!=SQLITE_OK ) break;
   16838     sqlite3_finalize(pStmt);
   16839     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
   16840     if( rc==SQLITE_OK ){
   16841       if( pStmt ){
   16842         IdxStatement *pNew;
   16843         const char *z = sqlite3_sql(pStmt);
   16844         i64 n = STRLEN(z);
   16845         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
   16846         if( rc==SQLITE_OK ){
   16847           pNew->zSql = (char*)&pNew[1];
   16848           memcpy(pNew->zSql, z, n+1);
   16849           pNew->pNext = p->pStatement;
   16850           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
   16851           p->pStatement = pNew;
   16852         }
   16853         sqlite3_finalize(pStmt);
   16854       }
   16855     }else{
   16856       idxDatabaseError(p->dbv, pzErr);
   16857     }
   16858   }
   16859 
   16860   if( rc!=SQLITE_OK ){
   16861     idxScanFree(p->pScan, pScanOrig);
   16862     idxStatementFree(p->pStatement, pStmtOrig);
   16863     p->pScan = pScanOrig;
   16864     p->pStatement = pStmtOrig;
   16865   }
   16866 
   16867   return rc;
   16868 }
   16869 
   16870 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
   16871   int rc;
   16872   IdxHashEntry *pEntry;
   16873 
   16874   /* Do trigger processing to collect any extra IdxScan structures */
   16875   rc = idxProcessTriggers(p, pzErr);
   16876 
   16877   /* Create candidate indexes within the in-memory database file */
   16878   if( rc==SQLITE_OK ){
   16879     rc = idxCreateCandidates(p);
   16880   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
   16881     if( pzErr )
   16882       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
   16883     return rc;
   16884   }
   16885 
   16886   /* Generate the stat1 data */
   16887   if( rc==SQLITE_OK ){
   16888     rc = idxPopulateStat1(p, pzErr);
   16889   }
   16890 
   16891   /* Formulate the EXPERT_REPORT_CANDIDATES text */
   16892   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
   16893     p->zCandidates = idxAppendText(&rc, p->zCandidates,
   16894         "%s;%s%s\n", pEntry->zVal,
   16895         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
   16896     );
   16897   }
   16898 
   16899   /* Figure out which of the candidate indexes are preferred by the query
   16900   ** planner and report the results to the user.  */
   16901   if( rc==SQLITE_OK ){
   16902     rc = idxFindIndexes(p, pzErr);
   16903   }
   16904 
   16905   if( rc==SQLITE_OK ){
   16906     p->bRun = 1;
   16907   }
   16908   return rc;
   16909 }
   16910 
   16911 /*
   16912 ** Return the total number of statements that have been added to this
   16913 ** sqlite3expert using sqlite3_expert_sql().
   16914 */
   16915 int sqlite3_expert_count(sqlite3expert *p){
   16916   int nRet = 0;
   16917   if( p->pStatement ) nRet = p->pStatement->iId+1;
   16918   return nRet;
   16919 }
   16920 
   16921 /*
   16922 ** Return a component of the report.
   16923 */
   16924 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
   16925   const char *zRet = 0;
   16926   IdxStatement *pStmt;
   16927 
   16928   if( p->bRun==0 ) return 0;
   16929   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
   16930   switch( eReport ){
   16931     case EXPERT_REPORT_SQL:
   16932       if( pStmt ) zRet = pStmt->zSql;
   16933       break;
   16934     case EXPERT_REPORT_INDEXES:
   16935       if( pStmt ) zRet = pStmt->zIdx;
   16936       break;
   16937     case EXPERT_REPORT_PLAN:
   16938       if( pStmt ) zRet = pStmt->zEQP;
   16939       break;
   16940     case EXPERT_REPORT_CANDIDATES:
   16941       zRet = p->zCandidates;
   16942       break;
   16943   }
   16944   return zRet;
   16945 }
   16946 
   16947 /*
   16948 ** Free an sqlite3expert object.
   16949 */
   16950 void sqlite3_expert_destroy(sqlite3expert *p){
   16951   if( p ){
   16952     sqlite3_close(p->dbm);
   16953     sqlite3_close(p->dbv);
   16954     idxScanFree(p->pScan, 0);
   16955     idxStatementFree(p->pStatement, 0);
   16956     idxTableFree(p->pTable);
   16957     idxWriteFree(p->pWrite);
   16958     idxHashClear(&p->hIdx);
   16959     sqlite3_free(p->zCandidates);
   16960     sqlite3_free(p);
   16961   }
   16962 }
   16963 
   16964 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
   16965 
   16966 /************************* End ext/expert/sqlite3expert.c ********************/
   16967 #endif
   16968 /************************* Begin ext/intck/sqlite3intck.h ******************/
   16969 /*
   16970 ** 2024-02-08
   16971 **
   16972 ** The author disclaims copyright to this source code.  In place of
   16973 ** a legal notice, here is a blessing:
   16974 **
   16975 **    May you do good and not evil.
   16976 **    May you find forgiveness for yourself and forgive others.
   16977 **    May you share freely, never taking more than you give.
   16978 **
   16979 *************************************************************************
   16980 */
   16981 
   16982 /*
   16983 ** Incremental Integrity-Check Extension
   16984 ** -------------------------------------
   16985 **
   16986 ** This module contains code to check whether or not an SQLite database
   16987 ** is well-formed or corrupt. This is the same task as performed by SQLite's
   16988 ** built-in "PRAGMA integrity_check" command. This module differs from
   16989 ** "PRAGMA integrity_check" in that:
   16990 **
   16991 **   +  It is less thorough - this module does not detect certain types
   16992 **      of corruption that are detected by the PRAGMA command. However,
   16993 **      it does detect all kinds of corruption that are likely to cause
   16994 **      errors in SQLite applications.
   16995 **
   16996 **   +  It is slower. Sometimes up to three times slower.
   16997 **
   16998 **   +  It allows integrity-check operations to be split into multiple
   16999 **      transactions, so that the database does not need to be read-locked
   17000 **      for the duration of the integrity-check.
   17001 **
   17002 ** One way to use the API to run integrity-check on the "main" database
   17003 ** of handle db is:
   17004 **
   17005 **   int rc = SQLITE_OK;
   17006 **   sqlite3_intck *p = 0;
   17007 **
   17008 **   sqlite3_intck_open(db, "main", &p);
   17009 **   while( SQLITE_OK==sqlite3_intck_step(p) ){
   17010 **     const char *zMsg = sqlite3_intck_message(p);
   17011 **     if( zMsg ) printf("corruption: %s\n", zMsg);
   17012 **   }
   17013 **   rc = sqlite3_intck_error(p, &zErr);
   17014 **   if( rc!=SQLITE_OK ){
   17015 **     printf("error occured (rc=%d), (errmsg=%s)\n", rc, zErr);
   17016 **   }
   17017 **   sqlite3_intck_close(p);
   17018 **
   17019 ** Usually, the sqlite3_intck object opens a read transaction within the
   17020 ** first call to sqlite3_intck_step() and holds it open until the
   17021 ** integrity-check is complete. However, if sqlite3_intck_unlock() is
   17022 ** called, the read transaction is ended and a new read transaction opened
   17023 ** by the subsequent call to sqlite3_intck_step().
   17024 */
   17025 
   17026 #ifndef _SQLITE_INTCK_H
   17027 #define _SQLITE_INTCK_H
   17028 
   17029 /* #include "sqlite3.h" */
   17030 
   17031 #ifdef __cplusplus
   17032 extern "C" {
   17033 #endif
   17034 
   17035 /*
   17036 ** An ongoing incremental integrity-check operation is represented by an
   17037 ** opaque pointer of the following type.
   17038 */
   17039 typedef struct sqlite3_intck sqlite3_intck;
   17040 
   17041 /*
   17042 ** Open a new incremental integrity-check object. If successful, populate
   17043 ** output variable (*ppOut) with the new object handle and return SQLITE_OK.
   17044 ** Or, if an error occurs, set (*ppOut) to NULL and return an SQLite error
   17045 ** code (e.g. SQLITE_NOMEM).
   17046 **
   17047 ** The integrity-check will be conducted on database zDb (which must be "main",
   17048 ** "temp", or the name of an attached database) of database handle db. Once
   17049 ** this function has been called successfully, the caller should not use
   17050 ** database handle db until the integrity-check object has been destroyed
   17051 ** using sqlite3_intck_close().
   17052 */
   17053 int sqlite3_intck_open(
   17054   sqlite3 *db,                    /* Database handle */
   17055   const char *zDb,                /* Database name ("main", "temp" etc.) */
   17056   sqlite3_intck **ppOut           /* OUT: New sqlite3_intck handle */
   17057 );
   17058 
   17059 /*
   17060 ** Close and release all resources associated with a handle opened by an
   17061 ** earlier call to sqlite3_intck_open(). The results of using an
   17062 ** integrity-check handle after it has been passed to this function are
   17063 ** undefined.
   17064 */
   17065 void sqlite3_intck_close(sqlite3_intck *pCk);
   17066 
   17067 /*
   17068 ** Do the next step of the integrity-check operation specified by the handle
   17069 ** passed as the only argument. This function returns SQLITE_DONE if the
   17070 ** integrity-check operation is finished, or an SQLite error code if
   17071 ** an error occurs, or SQLITE_OK if no error occurs but the integrity-check
   17072 ** is not finished. It is not considered an error if database corruption
   17073 ** is encountered.
   17074 **
   17075 ** Following a successful call to sqlite3_intck_step() (one that returns
   17076 ** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if
   17077 ** corruption was detected in the db.
   17078 **
   17079 ** If an error occurs and a value other than SQLITE_OK or SQLITE_DONE is
   17080 ** returned, then the integrity-check handle is placed in an error state.
   17081 ** In this state all subsequent calls to sqlite3_intck_step() or
   17082 ** sqlite3_intck_unlock() will immediately return the same error. The
   17083 ** sqlite3_intck_error() method may be used to obtain an English language
   17084 ** error message in this case.
   17085 */
   17086 int sqlite3_intck_step(sqlite3_intck *pCk);
   17087 
   17088 /*
   17089 ** If the previous call to sqlite3_intck_step() encountered corruption
   17090 ** within the database, then this function returns a pointer to a buffer
   17091 ** containing a nul-terminated string describing the corruption in
   17092 ** English. If the previous call to sqlite3_intck_step() did not encounter
   17093 ** corruption, or if there was no previous call, this function returns
   17094 ** NULL.
   17095 */
   17096 const char *sqlite3_intck_message(sqlite3_intck *pCk);
   17097 
   17098 /*
   17099 ** Close any read-transaction opened by an earlier call to
   17100 ** sqlite3_intck_step(). Any subsequent call to sqlite3_intck_step() will
   17101 ** open a new transaction. Return SQLITE_OK if successful, or an SQLite error
   17102 ** code otherwise.
   17103 **
   17104 ** If an error occurs, then the integrity-check handle is placed in an error
   17105 ** state. In this state all subsequent calls to sqlite3_intck_step() or
   17106 ** sqlite3_intck_unlock() will immediately return the same error. The
   17107 ** sqlite3_intck_error() method may be used to obtain an English language
   17108 ** error message in this case.
   17109 */
   17110 int sqlite3_intck_unlock(sqlite3_intck *pCk);
   17111 
   17112 /*
   17113 ** If an error has occurred in an earlier call to sqlite3_intck_step()
   17114 ** or sqlite3_intck_unlock(), then this method returns the associated
   17115 ** SQLite error code. Additionally, if pzErr is not NULL, then (*pzErr)
   17116 ** may be set to point to a nul-terminated string containing an English
   17117 ** language error message. Or, if no error message is available, to
   17118 ** NULL.
   17119 **
   17120 ** If no error has occurred within sqlite3_intck_step() or
   17121 ** sqlite_intck_unlock() calls on the handle passed as the first argument,
   17122 ** then SQLITE_OK is returned and (*pzErr) set to NULL.
   17123 */
   17124 int sqlite3_intck_error(sqlite3_intck *pCk, const char **pzErr);
   17125 
   17126 /*
   17127 ** This API is used for testing only. It returns the full-text of an SQL
   17128 ** statement used to test object zObj, which may be a table or index.
   17129 ** The returned buffer is valid until the next call to either this function
   17130 ** or sqlite3_intck_close() on the same sqlite3_intck handle.
   17131 */
   17132 const char *sqlite3_intck_test_sql(sqlite3_intck *pCk, const char *zObj);
   17133 
   17134 
   17135 #ifdef __cplusplus
   17136 }  /* end of the 'extern "C"' block */
   17137 #endif
   17138 
   17139 #endif /* ifndef _SQLITE_INTCK_H */
   17140 
   17141 /************************* End ext/intck/sqlite3intck.h ********************/
   17142 /************************* Begin ext/intck/sqlite3intck.c ******************/
   17143 /*
   17144 ** 2024-02-08
   17145 **
   17146 ** The author disclaims copyright to this source code.  In place of
   17147 ** a legal notice, here is a blessing:
   17148 **
   17149 **    May you do good and not evil.
   17150 **    May you find forgiveness for yourself and forgive others.
   17151 **    May you share freely, never taking more than you give.
   17152 **
   17153 *************************************************************************
   17154 */
   17155 
   17156 /* #include "sqlite3intck.h" */
   17157 #include <string.h>
   17158 #include <assert.h>
   17159 
   17160 #include <stdio.h>
   17161 #include <stdlib.h>
   17162 
   17163 /*
   17164 ** nKeyVal:
   17165 **   The number of values that make up the 'key' for the current pCheck
   17166 **   statement.
   17167 **
   17168 ** rc:
   17169 **   Error code returned by most recent sqlite3_intck_step() or
   17170 **   sqlite3_intck_unlock() call. This is set to SQLITE_DONE when
   17171 **   the integrity-check operation is finished.
   17172 **
   17173 ** zErr:
   17174 **   If the object has entered the error state, this is the error message.
   17175 **   Is freed using sqlite3_free() when the object is deleted.
   17176 **
   17177 ** zTestSql:
   17178 **   The value returned by the most recent call to sqlite3_intck_testsql().
   17179 **   Each call to testsql() frees the previous zTestSql value (using
   17180 **   sqlite3_free()) and replaces it with the new value it will return.
   17181 */
   17182 struct sqlite3_intck {
   17183   sqlite3 *db;
   17184   const char *zDb;                /* Copy of zDb parameter to _open() */
   17185   char *zObj;                     /* Current object. Or NULL. */
   17186 
   17187   sqlite3_stmt *pCheck;           /* Current check statement */
   17188   char *zKey;
   17189   int nKeyVal;
   17190 
   17191   char *zMessage;
   17192   int bCorruptSchema;
   17193 
   17194   int rc;                         /* Error code */
   17195   char *zErr;                     /* Error message */
   17196   char *zTestSql;                 /* Returned by sqlite3_intck_test_sql() */
   17197 };
   17198 
   17199 
   17200 /*
   17201 ** Some error has occurred while using database p->db. Save the error message
   17202 ** and error code currently held by the database handle in p->rc and p->zErr.
   17203 */
   17204 static void intckSaveErrmsg(sqlite3_intck *p){
   17205   p->rc = sqlite3_errcode(p->db);
   17206   sqlite3_free(p->zErr);
   17207   p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
   17208 }
   17209 
   17210 /*
   17211 ** If the handle passed as the first argument is already in the error state,
   17212 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
   17213 ** error occurs within this function, it leaves an error in said handle.
   17214 **
   17215 ** Otherwise, this function attempts to prepare SQL statement zSql and
   17216 ** return the resulting statement handle to the user.
   17217 */
   17218 static sqlite3_stmt *intckPrepare(sqlite3_intck *p, const char *zSql){
   17219   sqlite3_stmt *pRet = 0;
   17220   if( p->rc==SQLITE_OK ){
   17221     p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0);
   17222     if( p->rc!=SQLITE_OK ){
   17223       intckSaveErrmsg(p);
   17224       assert( pRet==0 );
   17225     }
   17226   }
   17227   return pRet;
   17228 }
   17229 
   17230 /*
   17231 ** If the handle passed as the first argument is already in the error state,
   17232 ** then this function is a no-op (returns NULL immediately). Otherwise, if an
   17233 ** error occurs within this function, it leaves an error in said handle.
   17234 **
   17235 ** Otherwise, this function treats argument zFmt as a printf() style format
   17236 ** string. It formats it according to the trailing arguments and then
   17237 ** attempts to prepare the results and return the resulting prepared
   17238 ** statement.
   17239 */
   17240 static sqlite3_stmt *intckPrepareFmt(sqlite3_intck *p, const char *zFmt, ...){
   17241   sqlite3_stmt *pRet = 0;
   17242   va_list ap;
   17243   char *zSql = 0;
   17244   va_start(ap, zFmt);
   17245   zSql = sqlite3_vmprintf(zFmt, ap);
   17246   if( p->rc==SQLITE_OK && zSql==0 ){
   17247     p->rc = SQLITE_NOMEM;
   17248   }
   17249   pRet = intckPrepare(p, zSql);
   17250   sqlite3_free(zSql);
   17251   va_end(ap);
   17252   return pRet;
   17253 }
   17254 
   17255 /*
   17256 ** Finalize SQL statement pStmt. If an error occurs and the handle passed
   17257 ** as the first argument does not already contain an error, store the
   17258 ** error in the handle.
   17259 */
   17260 static void intckFinalize(sqlite3_intck *p, sqlite3_stmt *pStmt){
   17261   int rc = sqlite3_finalize(pStmt);
   17262   if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
   17263     intckSaveErrmsg(p);
   17264   }
   17265 }
   17266 
   17267 /*
   17268 ** If there is already an error in handle p, return it. Otherwise, call
   17269 ** sqlite3_step() on the statement handle and return that value.
   17270 */
   17271 static int intckStep(sqlite3_intck *p, sqlite3_stmt *pStmt){
   17272   if( p->rc ) return p->rc;
   17273   return sqlite3_step(pStmt);
   17274 }
   17275 
   17276 /*
   17277 ** Execute SQL statement zSql. There is no way to obtain any results
   17278 ** returned by the statement. This function uses the sqlite3_intck error
   17279 ** code convention.
   17280 */
   17281 static void intckExec(sqlite3_intck *p, const char *zSql){
   17282   sqlite3_stmt *pStmt = 0;
   17283   pStmt = intckPrepare(p, zSql);
   17284   intckStep(p, pStmt);
   17285   intckFinalize(p, pStmt);
   17286 }
   17287 
   17288 /*
   17289 ** A wrapper around sqlite3_mprintf() that uses the sqlite3_intck error
   17290 ** code convention.
   17291 */
   17292 static char *intckMprintf(sqlite3_intck *p, const char *zFmt, ...){
   17293   va_list ap;
   17294   char *zRet = 0;
   17295   va_start(ap, zFmt);
   17296   zRet = sqlite3_vmprintf(zFmt, ap);
   17297   if( p->rc==SQLITE_OK ){
   17298     if( zRet==0 ){
   17299       p->rc = SQLITE_NOMEM;
   17300     }
   17301   }else{
   17302     sqlite3_free(zRet);
   17303     zRet = 0;
   17304   }
   17305   va_end(ap);
   17306   return zRet;
   17307 }
   17308 
   17309 /*
   17310 ** This is used by sqlite3_intck_unlock() to save the vector key value
   17311 ** required to restart the current pCheck query as a nul-terminated string
   17312 ** in p->zKey.
   17313 */
   17314 static void intckSaveKey(sqlite3_intck *p){
   17315   int ii;
   17316   char *zSql = 0;
   17317   sqlite3_stmt *pStmt = 0;
   17318   sqlite3_stmt *pXinfo = 0;
   17319   const char *zDir = 0;
   17320 
   17321   assert( p->pCheck );
   17322   assert( p->zKey==0 );
   17323 
   17324   pXinfo = intckPrepareFmt(p,
   17325       "SELECT group_concat(desc, '') FROM %Q.sqlite_schema s, "
   17326       "pragma_index_xinfo(%Q, %Q) "
   17327       "WHERE s.type='index' AND s.name=%Q",
   17328       p->zDb, p->zObj, p->zDb, p->zObj
   17329   );
   17330   if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){
   17331     zDir = (const char*)sqlite3_column_text(pXinfo, 0);
   17332   }
   17333 
   17334   if( zDir==0 ){
   17335     /* Object is a table, not an index. This is the easy case,as there are
   17336     ** no DESC columns or NULL values in a primary key.  */
   17337     const char *zSep = "SELECT '(' || ";
   17338     for(ii=0; ii<p->nKeyVal; ii++){
   17339       zSql = intckMprintf(p, "%z%squote(?)", zSql, zSep);
   17340       zSep = " || ', ' || ";
   17341     }
   17342     zSql = intckMprintf(p, "%z || ')'", zSql);
   17343   }else{
   17344 
   17345     /* Object is an index. */
   17346     assert( p->nKeyVal>1 );
   17347     for(ii=p->nKeyVal; ii>0; ii--){
   17348       int bLastIsDesc = zDir[ii-1]=='1';
   17349       int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL;
   17350       const char *zLast = sqlite3_column_name(p->pCheck, ii);
   17351       char *zLhs = 0;
   17352       char *zRhs = 0;
   17353       char *zWhere = 0;
   17354 
   17355       if( bLastIsNull ){
   17356         if( bLastIsDesc ) continue;
   17357         zWhere = intckMprintf(p, "'%s IS NOT NULL'", zLast);
   17358       }else{
   17359         const char *zOp = bLastIsDesc ? "<" : ">";
   17360         zWhere = intckMprintf(p, "'%s %s ' || quote(?%d)", zLast, zOp, ii);
   17361       }
   17362 
   17363       if( ii>1 ){
   17364         const char *zLhsSep = "";
   17365         const char *zRhsSep = "";
   17366         int jj;
   17367         for(jj=0; jj<ii-1; jj++){
   17368           const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1);
   17369           zLhs = intckMprintf(p, "%z%s%s", zLhs, zLhsSep, zAlias);
   17370           zRhs = intckMprintf(p, "%z%squote(?%d)", zRhs, zRhsSep, jj+1);
   17371           zLhsSep = ",";
   17372           zRhsSep = " || ',' || ";
   17373         }
   17374 
   17375         zWhere = intckMprintf(p,
   17376             "'(%z) IS (' || %z || ') AND ' || %z",
   17377             zLhs, zRhs, zWhere);
   17378       }
   17379       zWhere = intckMprintf(p, "'WHERE ' || %z", zWhere);
   17380 
   17381       zSql = intckMprintf(p, "%z%s(quote( %z ) )",
   17382           zSql,
   17383           (zSql==0 ? "VALUES" : ",\n      "),
   17384           zWhere
   17385       );
   17386     }
   17387     zSql = intckMprintf(p,
   17388         "WITH wc(q) AS (\n%z\n)"
   17389         "SELECT 'VALUES' || group_concat('(' || q || ')', ',\n      ') FROM wc"
   17390         , zSql
   17391     );
   17392   }
   17393 
   17394   pStmt = intckPrepare(p, zSql);
   17395   if( p->rc==SQLITE_OK ){
   17396     for(ii=0; ii<p->nKeyVal; ii++){
   17397       sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1));
   17398     }
   17399     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   17400       p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
   17401     }
   17402     intckFinalize(p, pStmt);
   17403   }
   17404 
   17405   sqlite3_free(zSql);
   17406   intckFinalize(p, pXinfo);
   17407 }
   17408 
   17409 /*
   17410 ** Find the next database object (table or index) to check. If successful,
   17411 ** set sqlite3_intck.zObj to point to a nul-terminated buffer containing
   17412 ** the object's name before returning.
   17413 */
   17414 static void intckFindObject(sqlite3_intck *p){
   17415   sqlite3_stmt *pStmt = 0;
   17416   char *zPrev = p->zObj;
   17417   p->zObj = 0;
   17418 
   17419   assert( p->rc==SQLITE_OK );
   17420   assert( p->pCheck==0 );
   17421 
   17422   pStmt = intckPrepareFmt(p,
   17423     "WITH tables(table_name) AS ("
   17424     "  SELECT name"
   17425     "  FROM %Q.sqlite_schema WHERE (type='table' OR type='index') AND rootpage"
   17426     "  UNION ALL "
   17427     "  SELECT 'sqlite_schema'"
   17428     ")"
   17429     "SELECT table_name FROM tables "
   17430     "WHERE ?1 IS NULL OR table_name%s?1 "
   17431     "ORDER BY 1"
   17432     , p->zDb, (p->zKey ? ">=" : ">")
   17433   );
   17434 
   17435   if( p->rc==SQLITE_OK ){
   17436     sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT);
   17437     if( sqlite3_step(pStmt)==SQLITE_ROW ){
   17438       p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
   17439     }
   17440   }
   17441   intckFinalize(p, pStmt);
   17442 
   17443   /* If this is a new object, ensure the previous key value is cleared. */
   17444   if( sqlite3_stricmp(p->zObj, zPrev) ){
   17445     sqlite3_free(p->zKey);
   17446     p->zKey = 0;
   17447   }
   17448 
   17449   sqlite3_free(zPrev);
   17450 }
   17451 
   17452 /*
   17453 ** Return the size in bytes of the first token in nul-terminated buffer z.
   17454 ** For the purposes of this call, a token is either:
   17455 **
   17456 **   *  a quoted SQL string,
   17457 *    *  a contiguous series of ascii alphabet characters, or
   17458 *    *  any other single byte.
   17459 */
   17460 static int intckGetToken(const char *z){
   17461   char c = z[0];
   17462   int iRet = 1;
   17463   if( c=='\'' || c=='"' || c=='`' ){
   17464     while( z[iRet] ){
   17465       if( z[iRet]==c ){
   17466         iRet++;
   17467         if( z[iRet]!=c ) break;
   17468       }
   17469       iRet++;
   17470     }
   17471   }
   17472   else if( c=='[' ){
   17473     while( z[iRet++]!=']' && z[iRet] );
   17474   }
   17475   else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
   17476     while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
   17477       iRet++;
   17478     }
   17479   }
   17480 
   17481   return iRet;
   17482 }
   17483 
   17484 /*
   17485 ** Return true if argument c is an ascii whitespace character.
   17486 */
   17487 static int intckIsSpace(char c){
   17488   return (c==' ' || c=='\t' || c=='\n' || c=='\r');
   17489 }
   17490 
   17491 /*
   17492 ** Argument z points to the text of a CREATE INDEX statement. This function
   17493 ** identifies the part of the text that contains either the index WHERE
   17494 ** clause (if iCol<0) or the iCol'th column of the index.
   17495 **
   17496 ** If (iCol<0), the identified fragment does not include the "WHERE" keyword,
   17497 ** only the expression that follows it. If (iCol>=0) then the identified
   17498 ** fragment does not include any trailing sort-order keywords - "ASC" or
   17499 ** "DESC".
   17500 **
   17501 ** If the CREATE INDEX statement does not contain the requested field or
   17502 ** clause, NULL is returned and (*pnByte) is set to 0. Otherwise, a pointer to
   17503 ** the identified fragment is returned and output parameter (*pnByte) set
   17504 ** to its size in bytes.
   17505 */
   17506 static const char *intckParseCreateIndex(const char *z, int iCol, int *pnByte){
   17507   int iOff = 0;
   17508   int iThisCol = 0;
   17509   int iStart = 0;
   17510   int nOpen = 0;
   17511 
   17512   const char *zRet = 0;
   17513   int nRet = 0;
   17514 
   17515   int iEndOfCol = 0;
   17516 
   17517   /* Skip forward until the first "(" token */
   17518   while( z[iOff]!='(' ){
   17519     iOff += intckGetToken(&z[iOff]);
   17520     if( z[iOff]=='\0' ) return 0;
   17521   }
   17522   assert( z[iOff]=='(' );
   17523 
   17524   nOpen = 1;
   17525   iOff++;
   17526   iStart = iOff;
   17527   while( z[iOff] ){
   17528     const char *zToken = &z[iOff];
   17529     int nToken = 0;
   17530 
   17531     /* Check if this is the end of the current column - either a "," or ")"
   17532     ** when nOpen==1.  */
   17533     if( nOpen==1 ){
   17534       if( z[iOff]==',' || z[iOff]==')' ){
   17535         if( iCol==iThisCol ){
   17536           int iEnd = iEndOfCol ? iEndOfCol : iOff;
   17537           nRet = (iEnd - iStart);
   17538           zRet = &z[iStart];
   17539           break;
   17540         }
   17541         iStart = iOff+1;
   17542         while( intckIsSpace(z[iStart]) ) iStart++;
   17543         iThisCol++;
   17544       }
   17545       if( z[iOff]==')' ) break;
   17546     }
   17547     if( z[iOff]=='(' ) nOpen++;
   17548     if( z[iOff]==')' ) nOpen--;
   17549     nToken = intckGetToken(zToken);
   17550 
   17551     if( (nToken==3 && 0==sqlite3_strnicmp(zToken, "ASC", nToken))
   17552      || (nToken==4 && 0==sqlite3_strnicmp(zToken, "DESC", nToken))
   17553     ){
   17554       iEndOfCol = iOff;
   17555     }else if( 0==intckIsSpace(zToken[0]) ){
   17556       iEndOfCol = 0;
   17557     }
   17558 
   17559     iOff += nToken;
   17560   }
   17561 
   17562   /* iStart is now the byte offset of 1 byte passed the final ')' in the
   17563   ** CREATE INDEX statement. Try to find a WHERE clause to return.  */
   17564   while( zRet==0 && z[iOff] ){
   17565     int n = intckGetToken(&z[iOff]);
   17566     if( n==5 && 0==sqlite3_strnicmp(&z[iOff], "where", 5) ){
   17567       zRet = &z[iOff+5];
   17568       nRet = (int)strlen(zRet);
   17569     }
   17570     iOff += n;
   17571   }
   17572 
   17573   /* Trim any whitespace from the start and end of the returned string. */
   17574   if( zRet ){
   17575     while( intckIsSpace(zRet[0]) ){
   17576       nRet--;
   17577       zRet++;
   17578     }
   17579     while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--;
   17580   }
   17581 
   17582   *pnByte = nRet;
   17583   return zRet;
   17584 }
   17585 
   17586 /*
   17587 ** User-defined SQL function wrapper for intckParseCreateIndex():
   17588 **
   17589 **     SELECT parse_create_index(<sql>, <icol>);
   17590 */
   17591 static void intckParseCreateIndexFunc(
   17592   sqlite3_context *pCtx,
   17593   int nVal,
   17594   sqlite3_value **apVal
   17595 ){
   17596   const char *zSql = (const char*)sqlite3_value_text(apVal[0]);
   17597   int idx = sqlite3_value_int(apVal[1]);
   17598   const char *zRes = 0;
   17599   int nRes = 0;
   17600 
   17601   assert( nVal==2 );
   17602   if( zSql ){
   17603     zRes = intckParseCreateIndex(zSql, idx, &nRes);
   17604   }
   17605   sqlite3_result_text(pCtx, zRes, nRes, SQLITE_TRANSIENT);
   17606 }
   17607 
   17608 /*
   17609 ** Return true if sqlite3_intck.db has automatic indexes enabled, false
   17610 ** otherwise.
   17611 */
   17612 static int intckGetAutoIndex(sqlite3_intck *p){
   17613   int bRet = 0;
   17614   sqlite3_stmt *pStmt = 0;
   17615   pStmt = intckPrepare(p, "PRAGMA automatic_index");
   17616   if( SQLITE_ROW==intckStep(p, pStmt) ){
   17617     bRet = sqlite3_column_int(pStmt, 0);
   17618   }
   17619   intckFinalize(p, pStmt);
   17620   return bRet;
   17621 }
   17622 
   17623 /*
   17624 ** Return true if zObj is an index, or false otherwise.
   17625 */
   17626 static int intckIsIndex(sqlite3_intck *p, const char *zObj){
   17627   int bRet = 0;
   17628   sqlite3_stmt *pStmt = 0;
   17629   pStmt = intckPrepareFmt(p,
   17630       "SELECT 1 FROM %Q.sqlite_schema WHERE name=%Q AND type='index'",
   17631       p->zDb, zObj
   17632   );
   17633   if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   17634     bRet = 1;
   17635   }
   17636   intckFinalize(p, pStmt);
   17637   return bRet;
   17638 }
   17639 
   17640 /*
   17641 ** Return a pointer to a nul-terminated buffer containing the SQL statement
   17642 ** used to check database object zObj (a table or index) for corruption.
   17643 ** If parameter zPrev is not NULL, then it must be a string containing the
   17644 ** vector key required to restart the check where it left off last time.
   17645 ** If pnKeyVal is not NULL, then (*pnKeyVal) is set to the number of
   17646 ** columns in the vector key value for the specified object.
   17647 **
   17648 ** This function uses the sqlite3_intck error code convention.
   17649 */
   17650 static char *intckCheckObjectSql(
   17651   sqlite3_intck *p,               /* Integrity check object */
   17652   const char *zObj,               /* Object (table or index) to scan */
   17653   const char *zPrev,              /* Restart key vector, if any */
   17654   int *pnKeyVal                   /* OUT: Number of key-values for this scan */
   17655 ){
   17656   char *zRet = 0;
   17657   sqlite3_stmt *pStmt = 0;
   17658   int bAutoIndex = 0;
   17659   int bIsIndex = 0;
   17660 
   17661   const char *zCommon =
   17662       /* Relation without_rowid also contains just one row. Column "b" is
   17663       ** set to true if the table being examined is a WITHOUT ROWID table,
   17664       ** or false otherwise.  */
   17665       ", without_rowid(b) AS ("
   17666       "  SELECT EXISTS ("
   17667       "    SELECT 1 FROM tabname, pragma_index_list(tab, db) AS l"
   17668       "      WHERE origin='pk' "
   17669       "      AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name=l.name)"
   17670       "  )"
   17671       ")"
   17672       ""
   17673       /* Table idx_cols contains 1 row for each column in each index on the
   17674       ** table being checked. Columns are:
   17675       **
   17676       **   idx_name: Name of the index.
   17677       **   idx_ispk: True if this index is the PK of a WITHOUT ROWID table.
   17678       **   col_name: Name of indexed column, or NULL for index on expression.
   17679       **   col_expr: Indexed expression, including COLLATE clause.
   17680       **   col_alias: Alias used for column in 'intck_wrapper' table.
   17681       */
   17682       ", idx_cols(idx_name, idx_ispk, col_name, col_expr, col_alias) AS ("
   17683       "  SELECT l.name, (l.origin=='pk' AND w.b), i.name, COALESCE(("
   17684       "    SELECT parse_create_index(sql, i.seqno) FROM "
   17685       "    sqlite_schema WHERE name = l.name"
   17686       "  ), format('\"%w\"', i.name) || ' COLLATE ' || quote(i.coll)),"
   17687       "  'c' || row_number() OVER ()"
   17688       "  FROM "
   17689       "      tabname t,"
   17690       "      without_rowid w,"
   17691       "      pragma_index_list(t.tab, t.db) l,"
   17692       "      pragma_index_xinfo(l.name) i"
   17693       "      WHERE i.key"
   17694       "  UNION ALL"
   17695       "  SELECT '', 1, '_rowid_', '_rowid_', 'r1' FROM without_rowid WHERE b=0"
   17696       ")"
   17697       ""
   17698       ""
   17699       /*
   17700       ** For a PK declared as "PRIMARY KEY(a, b) ... WITHOUT ROWID", where
   17701       ** the intck_wrapper aliases of "a" and "b" are "c1" and "c2":
   17702       **
   17703       **   o_pk:   "o.c1, o.c2"
   17704       **   i_pk:   "i.'a', i.'b'"
   17705       **   ...
   17706       **   n_pk:   2
   17707       */
   17708       ", tabpk(db, tab, idx, o_pk, i_pk, q_pk, eq_pk, ps_pk, pk_pk, n_pk) AS ("
   17709       "    WITH pkfields(f, a) AS ("
   17710       "      SELECT i.col_name, i.col_alias FROM idx_cols i WHERE i.idx_ispk"
   17711       "    )"
   17712       "    SELECT t.db, t.tab, t.idx, "
   17713       "           group_concat(a, ', '), "
   17714       "           group_concat('i.'||quote(f), ', '), "
   17715       "           group_concat('quote(o.'||a||')', ' || '','' || '),  "
   17716       "           format('(%s)==(%s)',"
   17717       "               group_concat('o.'||a, ', '), "
   17718       "               group_concat(format('\"%w\"', f), ', ')"
   17719       "           ),"
   17720       "           group_concat('%s', ','),"
   17721       "           group_concat('quote('||a||')', ', '),  "
   17722       "           count(*)"
   17723       "    FROM tabname t, pkfields"
   17724       ")"
   17725       ""
   17726       ", idx(name, match_expr, partial, partial_alias, idx_ps, idx_idx) AS ("
   17727       "  SELECT idx_name,"
   17728       "    format('(%s,%s) IS (%s,%s)', "
   17729       "           group_concat(i.col_expr, ', '), i_pk,"
   17730       "           group_concat('o.'||i.col_alias, ', '), o_pk"
   17731       "    ), "
   17732       "    parse_create_index("
   17733       "        (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1"
   17734       "    ),"
   17735       "    'cond' || row_number() OVER ()"
   17736       "    , group_concat('%s', ',')"
   17737       "    , group_concat('quote('||i.col_alias||')', ', ')"
   17738       "  FROM tabpk t, "
   17739       "       without_rowid w,"
   17740       "       idx_cols i"
   17741       "  WHERE i.idx_ispk==0 "
   17742       "  GROUP BY idx_name"
   17743       ")"
   17744       ""
   17745       ", wrapper_with(s) AS ("
   17746       "  SELECT 'intck_wrapper AS (\n  SELECT\n    ' || ("
   17747       "      WITH f(a, b) AS ("
   17748       "        SELECT col_expr, col_alias FROM idx_cols"
   17749       "          UNION ALL "
   17750       "        SELECT partial, partial_alias FROM idx WHERE partial IS NOT NULL"
   17751       "      )"
   17752       "      SELECT group_concat(format('%s AS %s', a, b), ',\n    ') FROM f"
   17753       "    )"
   17754       "    || format('\n  FROM %Q.%Q ', t.db, t.tab)"
   17755            /* If the object being checked is a table, append "NOT INDEXED".
   17756            ** Otherwise, append "INDEXED BY <index>", and then, if the index
   17757            ** is a partial index " WHERE <condition>".  */
   17758       "    || CASE WHEN t.idx IS NULL THEN "
   17759       "        'NOT INDEXED'"
   17760       "       ELSE"
   17761       "        format('INDEXED BY %Q%s', t.idx, ' WHERE '||i.partial)"
   17762       "       END"
   17763       "    || '\n)'"
   17764       "    FROM tabname t LEFT JOIN idx i ON (i.name=t.idx)"
   17765       ")"
   17766       ""
   17767   ;
   17768 
   17769   bAutoIndex = intckGetAutoIndex(p);
   17770   if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 0");
   17771 
   17772   bIsIndex = intckIsIndex(p, zObj);
   17773   if( bIsIndex ){
   17774     pStmt = intckPrepareFmt(p,
   17775       /* Table idxname contains a single row. The first column, "db", contains
   17776       ** the name of the db containing the table (e.g. "main") and the second,
   17777       ** "tab", the name of the table itself.  */
   17778       "WITH tabname(db, tab, idx) AS ("
   17779       "  SELECT %Q, (SELECT tbl_name FROM %Q.sqlite_schema WHERE name=%Q), %Q "
   17780       ")"
   17781       ""
   17782       ", whereclause(w_c) AS (%s)"
   17783       ""
   17784       "%s" /* zCommon */
   17785       ""
   17786       ", case_statement(c) AS ("
   17787       "  SELECT "
   17788       "    'CASE WHEN (' || group_concat(col_alias, ', ') || ', 1) IS (\n' "
   17789       "    || '      SELECT ' || group_concat(col_expr, ', ') || ', 1 FROM '"
   17790       "    || format('%%Q.%%Q NOT INDEXED WHERE %%s\n', t.db, t.tab, p.eq_pk)"
   17791       "    || '    )\n  THEN NULL\n    '"
   17792       "    || 'ELSE format(''surplus entry ('"
   17793       "    ||   group_concat('%%s', ',') || ',' || p.ps_pk"
   17794       "    || ') in index ' || t.idx || ''', ' "
   17795       "    ||   group_concat('quote('||i.col_alias||')', ', ') || ', ' || p.pk_pk"
   17796       "    || ')'"
   17797       "    || '\n  END AS error_message'"
   17798       "  FROM tabname t, tabpk p, idx_cols i WHERE i.idx_name=t.idx"
   17799       ")"
   17800       ""
   17801       ", thiskey(k, n) AS ("
   17802       "    SELECT group_concat(i.col_alias, ', ') || ', ' || p.o_pk, "
   17803       "           count(*) + p.n_pk "
   17804       "    FROM tabpk p, idx_cols i WHERE i.idx_name=p.idx"
   17805       ")"
   17806       ""
   17807       ", main_select(m, n) AS ("
   17808       "  SELECT format("
   17809       "      'WITH %%s\n' ||"
   17810       "      ', idx_checker AS (\n' ||"
   17811       "      '  SELECT %%s,\n' ||"
   17812       "      '  %%s\n' || "
   17813       "      '  FROM intck_wrapper AS o\n' ||"
   17814       "      ')\n',"
   17815       "      ww.s, c, t.k"
   17816       "  ), t.n"
   17817       "  FROM case_statement, wrapper_with ww, thiskey t"
   17818       ")"
   17819 
   17820       "SELECT m || "
   17821       "    group_concat('SELECT * FROM idx_checker ' || w_c, ' UNION ALL '), n"
   17822       " FROM "
   17823       "main_select, whereclause "
   17824       , p->zDb, p->zDb, zObj, zObj
   17825       , zPrev ? zPrev : "VALUES('')", zCommon
   17826       );
   17827   }else{
   17828     pStmt = intckPrepareFmt(p,
   17829       /* Table tabname contains a single row. The first column, "db", contains
   17830       ** the name of the db containing the table (e.g. "main") and the second,
   17831       ** "tab", the name of the table itself.  */
   17832       "WITH tabname(db, tab, idx, prev) AS (SELECT %Q, %Q, NULL, %Q)"
   17833       ""
   17834       "%s" /* zCommon */
   17835 
   17836       /* expr(e) contains one row for each index on table zObj. Value e
   17837       ** is set to an expression that evaluates to NULL if the required
   17838       ** entry is present in the index, or an error message otherwise.  */
   17839       ", expr(e, p) AS ("
   17840       "  SELECT format('CASE WHEN EXISTS \n"
   17841       "    (SELECT 1 FROM %%Q.%%Q AS i INDEXED BY %%Q WHERE %%s%%s)\n"
   17842       "    THEN NULL\n"
   17843       "    ELSE format(''entry (%%s,%%s) missing from index %%s'', %%s, %%s)\n"
   17844       "  END\n'"
   17845       "    , t.db, t.tab, i.name, i.match_expr, ' AND (' || partial || ')',"
   17846       "      i.idx_ps, t.ps_pk, i.name, i.idx_idx, t.pk_pk),"
   17847       "    CASE WHEN partial IS NULL THEN NULL ELSE i.partial_alias END"
   17848       "  FROM tabpk t, idx i"
   17849       ")"
   17850 
   17851       ", numbered(ii, cond, e) AS ("
   17852       "  SELECT 0, 'n.ii=0', 'NULL'"
   17853       "    UNION ALL "
   17854       "  SELECT row_number() OVER (),"
   17855       "      '(n.ii='||row_number() OVER ()||COALESCE(' AND '||p||')', ')'), e"
   17856       "  FROM expr"
   17857       ")"
   17858 
   17859       ", counter_with(w) AS ("
   17860       "    SELECT 'WITH intck_counter(ii) AS (\n  ' || "
   17861       "       group_concat('SELECT '||ii, ' UNION ALL\n  ') "
   17862       "    || '\n)' FROM numbered"
   17863       ")"
   17864       ""
   17865       ", case_statement(c) AS ("
   17866       "    SELECT 'CASE ' || "
   17867       "    group_concat(format('\n  WHEN %%s THEN (%%s)', cond, e), '') ||"
   17868       "    '\nEND AS error_message'"
   17869       "    FROM numbered"
   17870       ")"
   17871       ""
   17872 
   17873       /* This table contains a single row consisting of a single value -
   17874       ** the text of an SQL expression that may be used by the main SQL
   17875       ** statement to output an SQL literal that can be used to resume
   17876       ** the scan if it is suspended. e.g. for a rowid table, an expression
   17877       ** like:
   17878       **
   17879       **     format('(%d,%d)', _rowid_, n.ii)
   17880       */
   17881       ", thiskey(k, n) AS ("
   17882       "    SELECT o_pk || ', ii', n_pk+1 FROM tabpk"
   17883       ")"
   17884       ""
   17885       ", whereclause(w_c) AS ("
   17886       "    SELECT CASE WHEN prev!='' THEN "
   17887       "    '\nWHERE (' || o_pk ||', n.ii) > ' || prev"
   17888       "    ELSE ''"
   17889       "    END"
   17890       "    FROM tabpk, tabname"
   17891       ")"
   17892       ""
   17893       ", main_select(m, n) AS ("
   17894       "  SELECT format("
   17895       "      '%%s, %%s\nSELECT %%s,\n%%s\nFROM intck_wrapper AS o"
   17896                ", intck_counter AS n%%s\nORDER BY %%s', "
   17897       "      w, ww.s, c, thiskey.k, whereclause.w_c, t.o_pk"
   17898       "  ), thiskey.n"
   17899       "  FROM case_statement, tabpk t, counter_with, "
   17900       "       wrapper_with ww, thiskey, whereclause"
   17901       ")"
   17902 
   17903       "SELECT m, n FROM main_select",
   17904       p->zDb, zObj, zPrev, zCommon
   17905     );
   17906   }
   17907 
   17908   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   17909     zRet = intckMprintf(p, "%s", (const char*)sqlite3_column_text(pStmt, 0));
   17910     if( pnKeyVal ){
   17911       *pnKeyVal = sqlite3_column_int(pStmt, 1);
   17912     }
   17913   }
   17914   intckFinalize(p, pStmt);
   17915 
   17916   if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
   17917   return zRet;
   17918 }
   17919 
   17920 /*
   17921 ** Open a new integrity-check object.
   17922 */
   17923 int sqlite3_intck_open(
   17924   sqlite3 *db,                    /* Database handle to operate on */
   17925   const char *zDbArg,             /* "main", "temp" etc. */
   17926   sqlite3_intck **ppOut           /* OUT: New integrity-check handle */
   17927 ){
   17928   sqlite3_intck *pNew = 0;
   17929   int rc = SQLITE_OK;
   17930   const char *zDb = zDbArg ? zDbArg : "main";
   17931   int nDb = (int)strlen(zDb);
   17932 
   17933   pNew = (sqlite3_intck*)sqlite3_malloc(sizeof(*pNew) + nDb + 1);
   17934   if( pNew==0 ){
   17935     rc = SQLITE_NOMEM;
   17936   }else{
   17937     memset(pNew, 0, sizeof(*pNew));
   17938     pNew->db = db;
   17939     pNew->zDb = (const char*)&pNew[1];
   17940     memcpy(&pNew[1], zDb, nDb+1);
   17941     rc = sqlite3_create_function(db, "parse_create_index",
   17942         2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0
   17943     );
   17944     if( rc!=SQLITE_OK ){
   17945       sqlite3_intck_close(pNew);
   17946       pNew = 0;
   17947     }
   17948   }
   17949 
   17950   *ppOut = pNew;
   17951   return rc;
   17952 }
   17953 
   17954 /*
   17955 ** Free the integrity-check object.
   17956 */
   17957 void sqlite3_intck_close(sqlite3_intck *p){
   17958   if( p ){
   17959     sqlite3_finalize(p->pCheck);
   17960     sqlite3_create_function(
   17961         p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0
   17962     );
   17963     sqlite3_free(p->zObj);
   17964     sqlite3_free(p->zKey);
   17965     sqlite3_free(p->zTestSql);
   17966     sqlite3_free(p->zErr);
   17967     sqlite3_free(p->zMessage);
   17968     sqlite3_free(p);
   17969   }
   17970 }
   17971 
   17972 /*
   17973 ** Step the integrity-check object.
   17974 */
   17975 int sqlite3_intck_step(sqlite3_intck *p){
   17976   if( p->rc==SQLITE_OK ){
   17977 
   17978     if( p->zMessage ){
   17979       sqlite3_free(p->zMessage);
   17980       p->zMessage = 0;
   17981     }
   17982 
   17983     if( p->bCorruptSchema ){
   17984       p->rc = SQLITE_DONE;
   17985     }else
   17986     if( p->pCheck==0 ){
   17987       intckFindObject(p);
   17988       if( p->rc==SQLITE_OK ){
   17989         if( p->zObj ){
   17990           char *zSql = 0;
   17991           zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal);
   17992           p->pCheck = intckPrepare(p, zSql);
   17993           sqlite3_free(zSql);
   17994           sqlite3_free(p->zKey);
   17995           p->zKey = 0;
   17996         }else{
   17997           p->rc = SQLITE_DONE;
   17998         }
   17999       }else if( p->rc==SQLITE_CORRUPT ){
   18000         p->rc = SQLITE_OK;
   18001         p->zMessage = intckMprintf(p, "%s",
   18002             "corruption found while reading database schema"
   18003         );
   18004         p->bCorruptSchema = 1;
   18005       }
   18006     }
   18007 
   18008     if( p->pCheck ){
   18009       assert( p->rc==SQLITE_OK );
   18010       if( sqlite3_step(p->pCheck)==SQLITE_ROW ){
   18011         /* Normal case, do nothing. */
   18012       }else{
   18013         intckFinalize(p, p->pCheck);
   18014         p->pCheck = 0;
   18015         p->nKeyVal = 0;
   18016         if( p->rc==SQLITE_CORRUPT ){
   18017           p->rc = SQLITE_OK;
   18018           p->zMessage = intckMprintf(p,
   18019               "corruption found while scanning database object %s", p->zObj
   18020           );
   18021         }
   18022       }
   18023     }
   18024   }
   18025 
   18026   return p->rc;
   18027 }
   18028 
   18029 /*
   18030 ** Return a message describing the corruption encountered by the most recent
   18031 ** call to sqlite3_intck_step(), or NULL if no corruption was encountered.
   18032 */
   18033 const char *sqlite3_intck_message(sqlite3_intck *p){
   18034   assert( p->pCheck==0 || p->zMessage==0 );
   18035   if( p->zMessage ){
   18036     return p->zMessage;
   18037   }
   18038   if( p->pCheck ){
   18039     return (const char*)sqlite3_column_text(p->pCheck, 0);
   18040   }
   18041   return 0;
   18042 }
   18043 
   18044 /*
   18045 ** Return the error code and message.
   18046 */
   18047 int sqlite3_intck_error(sqlite3_intck *p, const char **pzErr){
   18048   if( pzErr ) *pzErr = p->zErr;
   18049   return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc);
   18050 }
   18051 
   18052 /*
   18053 ** Close any read transaction the integrity-check object is holding open
   18054 ** on the database.
   18055 */
   18056 int sqlite3_intck_unlock(sqlite3_intck *p){
   18057   if( p->rc==SQLITE_OK && p->pCheck ){
   18058     assert( p->zKey==0 && p->nKeyVal>0 );
   18059     intckSaveKey(p);
   18060     intckFinalize(p, p->pCheck);
   18061     p->pCheck = 0;
   18062   }
   18063   return p->rc;
   18064 }
   18065 
   18066 /*
   18067 ** Return the SQL statement used to check object zObj. Or, if zObj is
   18068 ** NULL, the current SQL statement.
   18069 */
   18070 const char *sqlite3_intck_test_sql(sqlite3_intck *p, const char *zObj){
   18071   sqlite3_free(p->zTestSql);
   18072   if( zObj ){
   18073     p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0);
   18074   }else{
   18075     if( p->zObj ){
   18076       p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0);
   18077     }else{
   18078       sqlite3_free(p->zTestSql);
   18079       p->zTestSql = 0;
   18080     }
   18081   }
   18082   return p->zTestSql;
   18083 }
   18084 
   18085 /************************* End ext/intck/sqlite3intck.c ********************/
   18086 /************************* Begin ext/misc/stmtrand.c ******************/
   18087 /*
   18088 ** 2024-05-24
   18089 **
   18090 ** The author disclaims copyright to this source code.  In place of
   18091 ** a legal notice, here is a blessing:
   18092 **
   18093 **    May you do good and not evil.
   18094 **    May you find forgiveness for yourself and forgive others.
   18095 **    May you share freely, never taking more than you give.
   18096 **
   18097 ******************************************************************************
   18098 **
   18099 ** An SQL function that return pseudo-random non-negative integers.
   18100 **
   18101 **      SELECT stmtrand(123);
   18102 **
   18103 ** A special feature of this function is that the same sequence of random
   18104 ** integers is returned for each invocation of the statement.  This makes
   18105 ** the results repeatable, and hence useful for testing.  The argument is
   18106 ** an integer which is the seed for the random number sequence.  The seed
   18107 ** is used by the first invocation of this function only and is ignored
   18108 ** for all subsequent calls within the same statement.
   18109 **
   18110 ** Resetting a statement (sqlite3_reset()) also resets the random number
   18111 ** sequence.
   18112 */
   18113 /* #include "sqlite3ext.h" */
   18114 SQLITE_EXTENSION_INIT1
   18115 #include <assert.h>
   18116 #include <string.h>
   18117 
   18118 /* State of the pseudo-random number generator */
   18119 typedef struct Stmtrand {
   18120   unsigned int x, y;
   18121 } Stmtrand;
   18122 
   18123 /* auxdata key */
   18124 #define STMTRAND_KEY  (-4418371)
   18125 
   18126 /*
   18127 ** Function:     stmtrand(SEED)
   18128 **
   18129 ** Return a pseudo-random number.
   18130 */
   18131 static void stmtrandFunc(
   18132   sqlite3_context *context,
   18133   int argc,
   18134   sqlite3_value **argv
   18135 ){
   18136   Stmtrand *p;
   18137 
   18138   p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY);
   18139   if( p==0 ){
   18140     unsigned int seed;
   18141     p = sqlite3_malloc64( sizeof(*p) );
   18142     if( p==0 ){
   18143       sqlite3_result_error_nomem(context);
   18144       return;
   18145     }
   18146     if( argc>=1 ){
   18147       seed = (unsigned int)sqlite3_value_int(argv[0]);
   18148     }else{
   18149       seed = 0;
   18150     }
   18151     p->x = seed | 1;
   18152     p->y = seed;
   18153     sqlite3_set_auxdata(context, STMTRAND_KEY, p, sqlite3_free);
   18154     p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY);
   18155     if( p==0 ){
   18156       sqlite3_result_error_nomem(context);
   18157       return;
   18158     }
   18159   }
   18160   p->x = (p->x>>1) ^ ((1+~(p->x&1)) & 0xd0000001);
   18161   p->y = p->y*1103515245 + 12345;
   18162   sqlite3_result_int(context, (int)((p->x ^ p->y)&0x7fffffff));
   18163 }
   18164 
   18165 #ifdef _WIN32
   18166 
   18167 #endif
   18168 static int sqlite3_stmtrand_init(
   18169   sqlite3 *db,
   18170   char **pzErrMsg,
   18171   const sqlite3_api_routines *pApi
   18172 ){
   18173   int rc = SQLITE_OK;
   18174   SQLITE_EXTENSION_INIT2(pApi);
   18175   (void)pzErrMsg;  /* Unused parameter */
   18176   rc = sqlite3_create_function(db, "stmtrand", 1, SQLITE_UTF8, 0,
   18177                                stmtrandFunc, 0, 0);
   18178   if( rc==SQLITE_OK ){
   18179     rc = sqlite3_create_function(db, "stmtrand", 0, SQLITE_UTF8, 0,
   18180                                  stmtrandFunc, 0, 0);
   18181   }
   18182   return rc;
   18183 }
   18184 
   18185 /************************* End ext/misc/stmtrand.c ********************/
   18186 /************************* Begin ext/misc/vfstrace.c ******************/
   18187 /*
   18188 ** 2011 March 16
   18189 **
   18190 ** The author disclaims copyright to this source code.  In place of
   18191 ** a legal notice, here is a blessing:
   18192 **
   18193 **    May you do good and not evil.
   18194 **    May you find forgiveness for yourself and forgive others.
   18195 **    May you share freely, never taking more than you give.
   18196 **
   18197 ******************************************************************************
   18198 **
   18199 ** This file contains code implements a VFS shim that writes diagnostic
   18200 ** output for each VFS call, similar to "strace".
   18201 **
   18202 ** USAGE:
   18203 **
   18204 ** This source file exports a single symbol which is the name of a
   18205 ** function:
   18206 **
   18207 **   int vfstrace_register(
   18208 **     const char *zTraceName,         // Name of the newly constructed VFS
   18209 **     const char *zOldVfsName,        // Name of the underlying VFS
   18210 **     int (*xOut)(const char*,void*), // Output routine.  ex: fputs
   18211 **     void *pOutArg,                  // 2nd argument to xOut.  ex: stderr
   18212 **     int makeDefault                 // Make the new VFS the default
   18213 **   );
   18214 **
   18215 ** Applications that want to trace their VFS usage must provide a callback
   18216 ** function with this prototype:
   18217 **
   18218 **   int traceOutput(const char *zMessage, void *pAppData);
   18219 **
   18220 ** This function will "output" the trace messages, where "output" can
   18221 ** mean different things to different applications.  The traceOutput function
   18222 ** for the command-line shell (see shell.c) is "fputs" from the standard
   18223 ** library, which means that all trace output is written on the stream
   18224 ** specified by the second argument.  In the case of the command-line shell
   18225 ** the second argument is stderr.  Other applications might choose to output
   18226 ** trace information to a file, over a socket, or write it into a buffer.
   18227 **
   18228 ** The vfstrace_register() function creates a new "shim" VFS named by
   18229 ** the zTraceName parameter.  A "shim" VFS is an SQLite backend that does
   18230 ** not really perform the duties of a true backend, but simply filters or
   18231 ** interprets VFS calls before passing them off to another VFS which does
   18232 ** the actual work.  In this case the other VFS - the one that does the
   18233 ** real work - is identified by the second parameter, zOldVfsName.  If
   18234 ** the 2nd parameter is NULL then the default VFS is used.  The common
   18235 ** case is for the 2nd parameter to be NULL.
   18236 **
   18237 ** The third and fourth parameters are the pointer to the output function
   18238 ** and the second argument to the output function.  For the SQLite
   18239 ** command-line shell, when the -vfstrace option is used, these parameters
   18240 ** are fputs and stderr, respectively.
   18241 **
   18242 ** The fifth argument is true (non-zero) to cause the newly created VFS
   18243 ** to become the default VFS.  The common case is for the fifth parameter
   18244 ** to be true.
   18245 **
   18246 ** The call to vfstrace_register() simply creates the shim VFS that does
   18247 ** tracing.  The application must also arrange to use the new VFS for
   18248 ** all database connections that are created and for which tracing is
   18249 ** desired.  This can be done by specifying the trace VFS using URI filename
   18250 ** notation, or by specifying the trace VFS as the 4th parameter to
   18251 ** sqlite3_open_v2() or by making the trace VFS be the default (by setting
   18252 ** the 5th parameter of vfstrace_register() to 1).
   18253 **
   18254 **
   18255 ** ENABLING VFSTRACE IN A COMMAND-LINE SHELL
   18256 **
   18257 ** The SQLite command line shell implemented by the shell.c source file
   18258 ** can be used with this module.  To compile in -vfstrace support, first
   18259 ** gather this file (test_vfstrace.c), the shell source file (shell.c),
   18260 ** and the SQLite amalgamation source files (sqlite3.c, sqlite3.h) into
   18261 ** the working directory.  Then compile using a command like the following:
   18262 **
   18263 **    gcc -o sqlite3 -Os -I. -DSQLITE_ENABLE_VFSTRACE \
   18264 **        -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE \
   18265 **        -DHAVE_READLINE -DHAVE_USLEEP=1 \
   18266 **        shell.c test_vfstrace.c sqlite3.c -ldl -lreadline -lncurses
   18267 **
   18268 ** The gcc command above works on Linux and provides (in addition to the
   18269 ** -vfstrace option) support for FTS3 and FTS4, RTREE, and command-line
   18270 ** editing using the readline library.  The command-line shell does not
   18271 ** use threads so we added -DSQLITE_THREADSAFE=0 just to make the code
   18272 ** run a little faster.   For compiling on a Mac, you'll probably need
   18273 ** to omit the -DHAVE_READLINE, the -lreadline, and the -lncurses options.
   18274 ** The compilation could be simplified to just this:
   18275 **
   18276 **    gcc -DSQLITE_ENABLE_VFSTRACE \
   18277 **         shell.c test_vfstrace.c sqlite3.c -ldl -lpthread
   18278 **
   18279 ** In this second example, all unnecessary options have been removed
   18280 ** Note that since the code is now threadsafe, we had to add the -lpthread
   18281 ** option to pull in the pthreads library.
   18282 **
   18283 ** To cross-compile for windows using MinGW, a command like this might
   18284 ** work:
   18285 **
   18286 **    /opt/mingw/bin/i386-mingw32msvc-gcc -o sqlite3.exe -Os -I \
   18287 **         -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_VFSTRACE \
   18288 **         shell.c test_vfstrace.c sqlite3.c
   18289 **
   18290 ** Similar compiler commands will work on different systems.  The key
   18291 ** invariants are (1) you must have -DSQLITE_ENABLE_VFSTRACE so that
   18292 ** the shell.c source file will know to include the -vfstrace command-line
   18293 ** option and (2) you must compile and link the three source files
   18294 ** shell,c, test_vfstrace.c, and sqlite3.c.
   18295 **
   18296 ** RUNTIME CONTROL OF VFSTRACE OUTPUT
   18297 **
   18298 ** The application can use the "vfstrace" pragma to control which VFS
   18299 ** APIs are traced.  To disable all output:
   18300 **
   18301 **    PRAGMA vfstrace('-all');
   18302 **
   18303 ** To enable all output (which is the default setting):
   18304 **
   18305 **    PRAGMA vfstrace('+all');
   18306 **
   18307 ** Individual APIs can be enabled or disabled by name, with or without
   18308 ** the initial "x" character.  For example, to set up for tracing lock
   18309 ** primitives only:
   18310 **
   18311 **    PRAGMA vfstrace('-all, +Lock,Unlock,ShmLock');
   18312 **
   18313 ** The argument to the vfstrace pragma ignores capitalization and any
   18314 ** characters other than alphabetics, '+', and '-'.
   18315 */
   18316 #include <stdlib.h>
   18317 #include <string.h>
   18318 /* #include "sqlite3.h" */
   18319 
   18320 /*
   18321 ** An instance of this structure is attached to the each trace VFS to
   18322 ** provide auxiliary information.
   18323 */
   18324 typedef struct vfstrace_info vfstrace_info;
   18325 struct vfstrace_info {
   18326   sqlite3_vfs *pRootVfs;              /* The underlying real VFS */
   18327   int (*xOut)(const char*, void*);    /* Send output here */
   18328   unsigned int mTrace;                /* Mask of interfaces to trace */
   18329   u8 bOn;                             /* Tracing on/off */
   18330   void *pOutArg;                      /* First argument to xOut */
   18331   const char *zVfsName;               /* Name of this trace-VFS */
   18332   sqlite3_vfs *pTraceVfs;             /* Pointer back to the trace VFS */
   18333 };
   18334 
   18335 /*
   18336 ** The sqlite3_file object for the trace VFS
   18337 */
   18338 typedef struct vfstrace_file vfstrace_file;
   18339 struct vfstrace_file {
   18340   sqlite3_file base;        /* Base class.  Must be first */
   18341   vfstrace_info *pInfo;     /* The trace-VFS to which this file belongs */
   18342   const char *zFName;       /* Base name of the file */
   18343   sqlite3_file *pReal;      /* The real underlying file */
   18344 };
   18345 
   18346 /*
   18347 ** Bit values for vfstrace_info.mTrace.
   18348 */
   18349 #define VTR_CLOSE           0x00000001
   18350 #define VTR_READ            0x00000002
   18351 #define VTR_WRITE           0x00000004
   18352 #define VTR_TRUNC           0x00000008
   18353 #define VTR_SYNC            0x00000010
   18354 #define VTR_FSIZE           0x00000020
   18355 #define VTR_LOCK            0x00000040
   18356 #define VTR_UNLOCK          0x00000080
   18357 #define VTR_CRL             0x00000100
   18358 #define VTR_FCTRL           0x00000200
   18359 #define VTR_SECSZ           0x00000400
   18360 #define VTR_DEVCHAR         0x00000800
   18361 #define VTR_SHMLOCK         0x00001000
   18362 #define VTR_SHMMAP          0x00002000
   18363 #define VTR_SHMBAR          0x00004000
   18364 #define VTR_SHMUNMAP        0x00008000
   18365 #define VTR_OPEN            0x00010000
   18366 #define VTR_DELETE          0x00020000
   18367 #define VTR_ACCESS          0x00040000
   18368 #define VTR_FULLPATH        0x00080000
   18369 #define VTR_DLOPEN          0x00100000
   18370 #define VTR_DLERR           0x00200000
   18371 #define VTR_DLSYM           0x00400000
   18372 #define VTR_DLCLOSE         0x00800000
   18373 #define VTR_RAND            0x01000000
   18374 #define VTR_SLEEP           0x02000000
   18375 #define VTR_CURTIME         0x04000000
   18376 #define VTR_LASTERR         0x08000000
   18377 #define VTR_FETCH           0x10000000   /* Also coverse xUnfetch */
   18378 
   18379 /*
   18380 ** Method declarations for vfstrace_file.
   18381 */
   18382 static int vfstraceClose(sqlite3_file*);
   18383 static int vfstraceRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   18384 static int vfstraceWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64);
   18385 static int vfstraceTruncate(sqlite3_file*, sqlite3_int64 size);
   18386 static int vfstraceSync(sqlite3_file*, int flags);
   18387 static int vfstraceFileSize(sqlite3_file*, sqlite3_int64 *pSize);
   18388 static int vfstraceLock(sqlite3_file*, int);
   18389 static int vfstraceUnlock(sqlite3_file*, int);
   18390 static int vfstraceCheckReservedLock(sqlite3_file*, int *);
   18391 static int vfstraceFileControl(sqlite3_file*, int op, void *pArg);
   18392 static int vfstraceSectorSize(sqlite3_file*);
   18393 static int vfstraceDeviceCharacteristics(sqlite3_file*);
   18394 static int vfstraceShmLock(sqlite3_file*,int,int,int);
   18395 static int vfstraceShmMap(sqlite3_file*,int,int,int, void volatile **);
   18396 static void vfstraceShmBarrier(sqlite3_file*);
   18397 static int vfstraceShmUnmap(sqlite3_file*,int);
   18398 
   18399 /*
   18400 ** Method declarations for vfstrace_vfs.
   18401 */
   18402 static int vfstraceOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
   18403 static int vfstraceDelete(sqlite3_vfs*, const char *zName, int syncDir);
   18404 static int vfstraceAccess(sqlite3_vfs*, const char *zName, int flags, int *);
   18405 static int vfstraceFullPathname(sqlite3_vfs*, const char *zName, int, char *);
   18406 static void *vfstraceDlOpen(sqlite3_vfs*, const char *zFilename);
   18407 static void vfstraceDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
   18408 static void (*vfstraceDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void);
   18409 static void vfstraceDlClose(sqlite3_vfs*, void*);
   18410 static int vfstraceRandomness(sqlite3_vfs*, int nByte, char *zOut);
   18411 static int vfstraceSleep(sqlite3_vfs*, int microseconds);
   18412 static int vfstraceCurrentTime(sqlite3_vfs*, double*);
   18413 static int vfstraceGetLastError(sqlite3_vfs*, int, char*);
   18414 static int vfstraceCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
   18415 static int vfstraceSetSystemCall(sqlite3_vfs*,const char*, sqlite3_syscall_ptr);
   18416 static sqlite3_syscall_ptr vfstraceGetSystemCall(sqlite3_vfs*, const char *);
   18417 static const char *vfstraceNextSystemCall(sqlite3_vfs*, const char *zName);
   18418 
   18419 /*
   18420 ** Return a pointer to the tail of the pathname.  Examples:
   18421 **
   18422 **     /home/drh/xyzzy.txt -> xyzzy.txt
   18423 **     xyzzy.txt           -> xyzzy.txt
   18424 */
   18425 static const char *fileTail(const char *z){
   18426   size_t i;
   18427   if( z==0 ) return 0;
   18428   i = strlen(z)-1;
   18429   while( i>0 && z[i-1]!='/' ){ i--; }
   18430   return &z[i];
   18431 }
   18432 
   18433 /*
   18434 ** Send trace output defined by zFormat and subsequent arguments.
   18435 */
   18436 static void vfstrace_printf(
   18437   vfstrace_info *pInfo,
   18438   const char *zFormat,
   18439   ...
   18440 ){
   18441   va_list ap;
   18442   char *zMsg;
   18443   if( pInfo->bOn ){
   18444     va_start(ap, zFormat);
   18445     zMsg = sqlite3_vmprintf(zFormat, ap);
   18446     va_end(ap);
   18447     pInfo->xOut(zMsg, pInfo->pOutArg);
   18448     sqlite3_free(zMsg);
   18449   }
   18450 }
   18451 
   18452 /*
   18453 ** Try to convert an error code into a symbolic name for that error code.
   18454 */
   18455 static const char *vfstrace_errcode_name(int rc ){
   18456   const char *zVal = 0;
   18457   switch( rc ){
   18458     case SQLITE_OK:                 zVal = "SQLITE_OK";                 break;
   18459     case SQLITE_INTERNAL:           zVal = "SQLITE_INTERNAL";           break;
   18460     case SQLITE_ERROR:              zVal = "SQLITE_ERROR";              break;
   18461     case SQLITE_PERM:               zVal = "SQLITE_PERM";               break;
   18462     case SQLITE_ABORT:              zVal = "SQLITE_ABORT";              break;
   18463     case SQLITE_BUSY:               zVal = "SQLITE_BUSY";               break;
   18464     case SQLITE_LOCKED:             zVal = "SQLITE_LOCKED";             break;
   18465     case SQLITE_NOMEM:              zVal = "SQLITE_NOMEM";              break;
   18466     case SQLITE_READONLY:           zVal = "SQLITE_READONLY";           break;
   18467     case SQLITE_INTERRUPT:          zVal = "SQLITE_INTERRUPT";          break;
   18468     case SQLITE_IOERR:              zVal = "SQLITE_IOERR";              break;
   18469     case SQLITE_CORRUPT:            zVal = "SQLITE_CORRUPT";            break;
   18470     case SQLITE_NOTFOUND:           zVal = "SQLITE_NOTFOUND";           break;
   18471     case SQLITE_FULL:               zVal = "SQLITE_FULL";               break;
   18472     case SQLITE_CANTOPEN:           zVal = "SQLITE_CANTOPEN";           break;
   18473     case SQLITE_PROTOCOL:           zVal = "SQLITE_PROTOCOL";           break;
   18474     case SQLITE_EMPTY:              zVal = "SQLITE_EMPTY";              break;
   18475     case SQLITE_SCHEMA:             zVal = "SQLITE_SCHEMA";             break;
   18476     case SQLITE_TOOBIG:             zVal = "SQLITE_TOOBIG";             break;
   18477     case SQLITE_CONSTRAINT:         zVal = "SQLITE_CONSTRAINT";         break;
   18478     case SQLITE_MISMATCH:           zVal = "SQLITE_MISMATCH";           break;
   18479     case SQLITE_MISUSE:             zVal = "SQLITE_MISUSE";             break;
   18480     case SQLITE_NOLFS:              zVal = "SQLITE_NOLFS";              break;
   18481     case SQLITE_IOERR_READ:         zVal = "SQLITE_IOERR_READ";         break;
   18482     case SQLITE_IOERR_SHORT_READ:   zVal = "SQLITE_IOERR_SHORT_READ";   break;
   18483     case SQLITE_IOERR_WRITE:        zVal = "SQLITE_IOERR_WRITE";        break;
   18484     case SQLITE_IOERR_FSYNC:        zVal = "SQLITE_IOERR_FSYNC";        break;
   18485     case SQLITE_IOERR_DIR_FSYNC:    zVal = "SQLITE_IOERR_DIR_FSYNC";    break;
   18486     case SQLITE_IOERR_TRUNCATE:     zVal = "SQLITE_IOERR_TRUNCATE";     break;
   18487     case SQLITE_IOERR_FSTAT:        zVal = "SQLITE_IOERR_FSTAT";        break;
   18488     case SQLITE_IOERR_UNLOCK:       zVal = "SQLITE_IOERR_UNLOCK";       break;
   18489     case SQLITE_IOERR_RDLOCK:       zVal = "SQLITE_IOERR_RDLOCK";       break;
   18490     case SQLITE_IOERR_DELETE:       zVal = "SQLITE_IOERR_DELETE";       break;
   18491     case SQLITE_IOERR_BLOCKED:      zVal = "SQLITE_IOERR_BLOCKED";      break;
   18492     case SQLITE_IOERR_NOMEM:        zVal = "SQLITE_IOERR_NOMEM";        break;
   18493     case SQLITE_IOERR_ACCESS:       zVal = "SQLITE_IOERR_ACCESS";       break;
   18494     case SQLITE_IOERR_CHECKRESERVEDLOCK:
   18495                                zVal = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
   18496     case SQLITE_IOERR_LOCK:         zVal = "SQLITE_IOERR_LOCK";         break;
   18497     case SQLITE_IOERR_CLOSE:        zVal = "SQLITE_IOERR_CLOSE";        break;
   18498     case SQLITE_IOERR_DIR_CLOSE:    zVal = "SQLITE_IOERR_DIR_CLOSE";    break;
   18499     case SQLITE_IOERR_SHMOPEN:      zVal = "SQLITE_IOERR_SHMOPEN";      break;
   18500     case SQLITE_IOERR_SHMSIZE:      zVal = "SQLITE_IOERR_SHMSIZE";      break;
   18501     case SQLITE_IOERR_SHMLOCK:      zVal = "SQLITE_IOERR_SHMLOCK";      break;
   18502     case SQLITE_IOERR_SHMMAP:       zVal = "SQLITE_IOERR_SHMMAP";       break;
   18503     case SQLITE_IOERR_SEEK:         zVal = "SQLITE_IOERR_SEEK";         break;
   18504     case SQLITE_IOERR_GETTEMPPATH:  zVal = "SQLITE_IOERR_GETTEMPPATH";  break;
   18505     case SQLITE_IOERR_CONVPATH:     zVal = "SQLITE_IOERR_CONVPATH";     break;
   18506     case SQLITE_READONLY_DBMOVED:   zVal = "SQLITE_READONLY_DBMOVED";   break;
   18507     case SQLITE_LOCKED_SHAREDCACHE: zVal = "SQLITE_LOCKED_SHAREDCACHE"; break;
   18508     case SQLITE_BUSY_RECOVERY:      zVal = "SQLITE_BUSY_RECOVERY";      break;
   18509     case SQLITE_CANTOPEN_NOTEMPDIR: zVal = "SQLITE_CANTOPEN_NOTEMPDIR"; break;
   18510   }
   18511   return zVal;
   18512 }
   18513 
   18514 /*
   18515 ** Convert value rc into a string and print it using zFormat.  zFormat
   18516 ** should have exactly one %s
   18517 */
   18518 static void vfstrace_print_errcode(
   18519   vfstrace_info *pInfo,
   18520   const char *zFormat,
   18521   int rc
   18522 ){
   18523   const char *zVal;
   18524   char zBuf[50];
   18525   zVal = vfstrace_errcode_name(rc);
   18526   if( zVal==0 ){
   18527     zVal = vfstrace_errcode_name(rc&0xff);
   18528     if( zVal ){
   18529       sqlite3_snprintf(sizeof(zBuf), zBuf, "%s | 0x%x", zVal, rc&0xffff00);
   18530     }else{
   18531       sqlite3_snprintf(sizeof(zBuf), zBuf, "%d (0x%x)", rc, rc);
   18532     }
   18533     zVal = zBuf;
   18534   }
   18535   vfstrace_printf(pInfo, zFormat, zVal);
   18536 }
   18537 
   18538 /*
   18539 ** Append to a buffer.
   18540 */
   18541 static void strappend(char *z, int *pI, const char *zAppend){
   18542   int i = *pI;
   18543   while( zAppend[0] ){ z[i++] = *(zAppend++); }
   18544   z[i] = 0;
   18545   *pI = i;
   18546 }
   18547 
   18548 /*
   18549 ** Turn tracing output on or off according to mMask.
   18550 */
   18551 static void vfstraceOnOff(vfstrace_info *pInfo, unsigned int mMask){
   18552   pInfo->bOn = (pInfo->mTrace & mMask)!=0;
   18553 }
   18554 
   18555 /*
   18556 ** Close an vfstrace-file.
   18557 */
   18558 static int vfstraceClose(sqlite3_file *pFile){
   18559   vfstrace_file *p = (vfstrace_file *)pFile;
   18560   vfstrace_info *pInfo = p->pInfo;
   18561   int rc;
   18562   vfstraceOnOff(pInfo, VTR_CLOSE);
   18563   vfstrace_printf(pInfo, "%s.xClose(%s)", pInfo->zVfsName, p->zFName);
   18564   rc = p->pReal->pMethods->xClose(p->pReal);
   18565   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18566   if( rc==SQLITE_OK ){
   18567     sqlite3_free((void*)p->base.pMethods);
   18568     p->base.pMethods = 0;
   18569   }
   18570   return rc;
   18571 }
   18572 
   18573 /*
   18574 ** Read data from an vfstrace-file.
   18575 */
   18576 static int vfstraceRead(
   18577   sqlite3_file *pFile,
   18578   void *zBuf,
   18579   int iAmt,
   18580   sqlite_int64 iOfst
   18581 ){
   18582   vfstrace_file *p = (vfstrace_file *)pFile;
   18583   vfstrace_info *pInfo = p->pInfo;
   18584   int rc;
   18585   vfstraceOnOff(pInfo, VTR_READ);
   18586   vfstrace_printf(pInfo, "%s.xRead(%s,n=%d,ofst=%lld)",
   18587                   pInfo->zVfsName, p->zFName, iAmt, iOfst);
   18588   rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
   18589   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18590   return rc;
   18591 }
   18592 
   18593 /*
   18594 ** Write data to an vfstrace-file.
   18595 */
   18596 static int vfstraceWrite(
   18597   sqlite3_file *pFile,
   18598   const void *zBuf,
   18599   int iAmt,
   18600   sqlite_int64 iOfst
   18601 ){
   18602   vfstrace_file *p = (vfstrace_file *)pFile;
   18603   vfstrace_info *pInfo = p->pInfo;
   18604   int rc;
   18605   vfstraceOnOff(pInfo, VTR_WRITE);
   18606   vfstrace_printf(pInfo, "%s.xWrite(%s,n=%d,ofst=%lld)",
   18607                   pInfo->zVfsName, p->zFName, iAmt, iOfst);
   18608   rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
   18609   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18610   return rc;
   18611 }
   18612 
   18613 /*
   18614 ** Truncate an vfstrace-file.
   18615 */
   18616 static int vfstraceTruncate(sqlite3_file *pFile, sqlite_int64 size){
   18617   vfstrace_file *p = (vfstrace_file *)pFile;
   18618   vfstrace_info *pInfo = p->pInfo;
   18619   int rc;
   18620   vfstraceOnOff(pInfo, VTR_TRUNC);
   18621   vfstrace_printf(pInfo, "%s.xTruncate(%s,%lld)", pInfo->zVfsName, p->zFName,
   18622                   size);
   18623   rc = p->pReal->pMethods->xTruncate(p->pReal, size);
   18624   vfstrace_printf(pInfo, " -> %d\n", rc);
   18625   return rc;
   18626 }
   18627 
   18628 /*
   18629 ** Sync an vfstrace-file.
   18630 */
   18631 static int vfstraceSync(sqlite3_file *pFile, int flags){
   18632   vfstrace_file *p = (vfstrace_file *)pFile;
   18633   vfstrace_info *pInfo = p->pInfo;
   18634   int rc;
   18635   int i;
   18636   char zBuf[100];
   18637   memcpy(zBuf, "|0", 3);
   18638   i = 0;
   18639   if( flags & SQLITE_SYNC_FULL )        strappend(zBuf, &i, "|FULL");
   18640   else if( flags & SQLITE_SYNC_NORMAL ) strappend(zBuf, &i, "|NORMAL");
   18641   if( flags & SQLITE_SYNC_DATAONLY )    strappend(zBuf, &i, "|DATAONLY");
   18642   if( flags & ~(SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY) ){
   18643     sqlite3_snprintf(sizeof(zBuf)-i, &zBuf[i], "|0x%x", flags);
   18644   }
   18645   vfstraceOnOff(pInfo, VTR_SYNC);
   18646   vfstrace_printf(pInfo, "%s.xSync(%s,%s)", pInfo->zVfsName, p->zFName,
   18647                   &zBuf[1]);
   18648   rc = p->pReal->pMethods->xSync(p->pReal, flags);
   18649   vfstrace_printf(pInfo, " -> %d\n", rc);
   18650   return rc;
   18651 }
   18652 
   18653 /*
   18654 ** Return the current file-size of an vfstrace-file.
   18655 */
   18656 static int vfstraceFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
   18657   vfstrace_file *p = (vfstrace_file *)pFile;
   18658   vfstrace_info *pInfo = p->pInfo;
   18659   int rc;
   18660   vfstraceOnOff(pInfo, VTR_FSIZE);
   18661   vfstrace_printf(pInfo, "%s.xFileSize(%s)", pInfo->zVfsName, p->zFName);
   18662   rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
   18663   vfstrace_print_errcode(pInfo, " -> %s,", rc);
   18664   vfstrace_printf(pInfo, " size=%lld\n", *pSize);
   18665   return rc;
   18666 }
   18667 
   18668 /*
   18669 ** Return the name of a lock.
   18670 */
   18671 static const char *lockName(int eLock){
   18672   const char *azLockNames[] = {
   18673      "NONE", "SHARED", "RESERVED", "PENDING", "EXCLUSIVE"
   18674   };
   18675   if( eLock<0 || eLock>=(int)(sizeof(azLockNames)/sizeof(azLockNames[0])) ){
   18676     return "???";
   18677   }else{
   18678     return azLockNames[eLock];
   18679   }
   18680 }
   18681 
   18682 /*
   18683 ** Lock an vfstrace-file.
   18684 */
   18685 static int vfstraceLock(sqlite3_file *pFile, int eLock){
   18686   vfstrace_file *p = (vfstrace_file *)pFile;
   18687   vfstrace_info *pInfo = p->pInfo;
   18688   int rc;
   18689   vfstraceOnOff(pInfo, VTR_LOCK);
   18690   vfstrace_printf(pInfo, "%s.xLock(%s,%s)", pInfo->zVfsName, p->zFName,
   18691                   lockName(eLock));
   18692   rc = p->pReal->pMethods->xLock(p->pReal, eLock);
   18693   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18694   return rc;
   18695 }
   18696 
   18697 /*
   18698 ** Unlock an vfstrace-file.
   18699 */
   18700 static int vfstraceUnlock(sqlite3_file *pFile, int eLock){
   18701   vfstrace_file *p = (vfstrace_file *)pFile;
   18702   vfstrace_info *pInfo = p->pInfo;
   18703   int rc;
   18704   vfstraceOnOff(pInfo, VTR_UNLOCK);
   18705   vfstrace_printf(pInfo, "%s.xUnlock(%s,%s)", pInfo->zVfsName, p->zFName,
   18706                   lockName(eLock));
   18707   rc = p->pReal->pMethods->xUnlock(p->pReal, eLock);
   18708   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18709   return rc;
   18710 }
   18711 
   18712 /*
   18713 ** Check if another file-handle holds a RESERVED lock on an vfstrace-file.
   18714 */
   18715 static int vfstraceCheckReservedLock(sqlite3_file *pFile, int *pResOut){
   18716   vfstrace_file *p = (vfstrace_file *)pFile;
   18717   vfstrace_info *pInfo = p->pInfo;
   18718   int rc;
   18719   vfstraceOnOff(pInfo, VTR_CRL);
   18720   vfstrace_printf(pInfo, "%s.xCheckReservedLock(%s,%d)",
   18721                   pInfo->zVfsName, p->zFName);
   18722   rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
   18723   vfstrace_print_errcode(pInfo, " -> %s", rc);
   18724   vfstrace_printf(pInfo, ", out=%d\n", *pResOut);
   18725   return rc;
   18726 }
   18727 
   18728 /*
   18729 ** File control method. For custom operations on an vfstrace-file.
   18730 */
   18731 static int vfstraceFileControl(sqlite3_file *pFile, int op, void *pArg){
   18732   vfstrace_file *p = (vfstrace_file *)pFile;
   18733   vfstrace_info *pInfo = p->pInfo;
   18734   int rc;
   18735   char zBuf[100];
   18736   char zBuf2[100];
   18737   char *zOp;
   18738   char *zRVal = 0;
   18739   vfstraceOnOff(pInfo, VTR_FCTRL);
   18740   switch( op ){
   18741     case SQLITE_FCNTL_LOCKSTATE:           zOp = "LOCKSTATE";           break;
   18742     case SQLITE_GET_LOCKPROXYFILE:         zOp = "GET_LOCKPROXYFILE";   break;
   18743     case SQLITE_SET_LOCKPROXYFILE:         zOp = "SET_LOCKPROXYFILE";   break;
   18744     case SQLITE_LAST_ERRNO:                zOp = "LAST_ERRNO";          break;
   18745     case SQLITE_FCNTL_SIZE_HINT: {
   18746       sqlite3_snprintf(sizeof(zBuf), zBuf, "SIZE_HINT,%lld",
   18747                        *(sqlite3_int64*)pArg);
   18748       zOp = zBuf;
   18749       break;
   18750     }
   18751     case SQLITE_FCNTL_CHUNK_SIZE: {
   18752       sqlite3_snprintf(sizeof(zBuf), zBuf, "CHUNK_SIZE,%d", *(int*)pArg);
   18753       zOp = zBuf;
   18754       break;
   18755     }
   18756     case SQLITE_FCNTL_FILE_POINTER:        zOp = "FILE_POINTER";        break;
   18757     case SQLITE_FCNTL_WIN32_AV_RETRY:      zOp = "WIN32_AV_RETRY";      break;
   18758     case SQLITE_FCNTL_PERSIST_WAL: {
   18759        sqlite3_snprintf(sizeof(zBuf), zBuf, "PERSIST_WAL,%d", *(int*)pArg);
   18760        zOp = zBuf;
   18761        break;
   18762     }
   18763     case SQLITE_FCNTL_OVERWRITE:           zOp = "OVERWRITE";           break;
   18764     case SQLITE_FCNTL_VFSNAME:             zOp = "VFSNAME";             break;
   18765     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: zOp = "POWERSAFE_OVERWRITE"; break;
   18766     case SQLITE_FCNTL_PRAGMA: {
   18767       const char *const* a = (const char*const*)pArg;
   18768       if( a[1] && strcmp(a[1],"vfstrace")==0 && a[2] ){
   18769         const u8 *zArg = (const u8*)a[2];
   18770         if( zArg[0]>='0' && zArg[0]<='9' ){
   18771           pInfo->mTrace = (sqlite3_uint64)strtoll(a[2], 0, 0);
   18772         }else{
   18773           static const struct {
   18774             const char *z;
   18775             unsigned int m;
   18776           } aKw[] = {
   18777             { "all",                   0xffffffff   },
   18778             { "close",                 VTR_CLOSE    },
   18779             { "read",                  VTR_READ     },
   18780             { "write",                 VTR_WRITE    },
   18781             { "truncate",              VTR_TRUNC    },
   18782             { "sync",                  VTR_SYNC     },
   18783             { "filesize",              VTR_FSIZE    },
   18784             { "lock",                  VTR_LOCK     },
   18785             { "unlock",                VTR_UNLOCK   },
   18786             { "checkreservedlock",     VTR_CRL      },
   18787             { "filecontrol",           VTR_FCTRL    },
   18788             { "sectorsize",            VTR_SECSZ    },
   18789             { "devicecharacteristics", VTR_DEVCHAR  },
   18790             { "shmlock",               VTR_SHMLOCK  },
   18791             { "shmmap",                VTR_SHMMAP   },
   18792             { "shmummap",              VTR_SHMUNMAP },
   18793             { "shmbarrier",            VTR_SHMBAR   },
   18794             { "open",                  VTR_OPEN     },
   18795             { "delete",                VTR_DELETE   },
   18796             { "access",                VTR_ACCESS   },
   18797             { "fullpathname",          VTR_FULLPATH },
   18798             { "dlopen",                VTR_DLOPEN   },
   18799             { "dlerror",               VTR_DLERR    },
   18800             { "dlsym",                 VTR_DLSYM    },
   18801             { "dlclose",               VTR_DLCLOSE  },
   18802             { "randomness",            VTR_RAND     },
   18803             { "sleep",                 VTR_SLEEP    },
   18804             { "currenttime",           VTR_CURTIME  },
   18805             { "currenttimeint64",      VTR_CURTIME  },
   18806             { "getlasterror",          VTR_LASTERR  },
   18807             { "fetch",                 VTR_FETCH    },
   18808           };
   18809           int onOff = 1;
   18810           while( zArg[0] ){
   18811             int jj, n;
   18812             while( zArg[0]!=0 && zArg[0]!='-' && zArg[0]!='+'
   18813                    && !isalpha(zArg[0]) ) zArg++;
   18814             if( zArg[0]==0 ) break;
   18815             if( zArg[0]=='-' ){
   18816               onOff = 0;
   18817               zArg++;
   18818             }else if( zArg[0]=='+' ){
   18819               onOff = 1;
   18820               zArg++;
   18821             }
   18822             while( !isalpha(zArg[0]) ){
   18823               if( zArg[0]==0 ) break;
   18824               zArg++;
   18825             }
   18826             if( zArg[0]=='x' && isalpha(zArg[1]) ) zArg++;
   18827             for(n=0; isalpha(zArg[n]); n++){}
   18828             for(jj=0; jj<(int)(sizeof(aKw)/sizeof(aKw[0])); jj++){
   18829               if( sqlite3_strnicmp(aKw[jj].z,(const char*)zArg,n)==0 ){
   18830                 if( onOff ){
   18831                   pInfo->mTrace |= aKw[jj].m;
   18832                 }else{
   18833                   pInfo->mTrace &= ~aKw[jj].m;
   18834                 }
   18835                 break;
   18836               }
   18837             }
   18838             zArg += n;
   18839           }
   18840         }
   18841       }
   18842       sqlite3_snprintf(sizeof(zBuf), zBuf, "PRAGMA,[%s,%s]",a[1],a[2]);
   18843       zOp = zBuf;
   18844       break;
   18845     }
   18846     case SQLITE_FCNTL_BUSYHANDLER:         zOp = "BUSYHANDLER";         break;
   18847     case SQLITE_FCNTL_TEMPFILENAME:        zOp = "TEMPFILENAME";        break;
   18848     case SQLITE_FCNTL_MMAP_SIZE: {
   18849       sqlite3_int64 iMMap = *(sqlite3_int64*)pArg;
   18850       sqlite3_snprintf(sizeof(zBuf), zBuf, "MMAP_SIZE,%lld",iMMap);
   18851       zOp = zBuf;
   18852       break;
   18853     }
   18854     case SQLITE_FCNTL_TRACE:               zOp = "TRACE";               break;
   18855     case SQLITE_FCNTL_HAS_MOVED:           zOp = "HAS_MOVED";           break;
   18856     case SQLITE_FCNTL_SYNC:                zOp = "SYNC";                break;
   18857     case SQLITE_FCNTL_COMMIT_PHASETWO:     zOp = "COMMIT_PHASETWO";     break;
   18858     case SQLITE_FCNTL_WIN32_SET_HANDLE:    zOp = "WIN32_SET_HANDLE";    break;
   18859     case SQLITE_FCNTL_WAL_BLOCK:           zOp = "WAL_BLOCK";           break;
   18860     case SQLITE_FCNTL_ZIPVFS:              zOp = "ZIPVFS";              break;
   18861     case SQLITE_FCNTL_RBU:                 zOp = "RBU";                 break;
   18862     case SQLITE_FCNTL_VFS_POINTER:         zOp = "VFS_POINTER";         break;
   18863     case SQLITE_FCNTL_JOURNAL_POINTER:     zOp = "JOURNAL_POINTER";     break;
   18864     case SQLITE_FCNTL_WIN32_GET_HANDLE:    zOp = "WIN32_GET_HANDLE";    break;
   18865     case SQLITE_FCNTL_PDB:                 zOp = "PDB";                 break;
   18866     case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE:  zOp = "BEGIN_ATOMIC_WRITE";  break;
   18867     case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: zOp = "COMMIT_ATOMIC_WRITE"; break;
   18868     case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
   18869        zOp = "ROLLBACK_ATOMIC_WRITE";
   18870        break;
   18871     }
   18872     case SQLITE_FCNTL_LOCK_TIMEOUT: {
   18873        sqlite3_snprintf(sizeof(zBuf), zBuf, "LOCK_TIMEOUT,%d", *(int*)pArg);
   18874        zOp = zBuf;
   18875        break;
   18876     }
   18877     case SQLITE_FCNTL_DATA_VERSION:        zOp = "DATA_VERSION";        break;
   18878     case SQLITE_FCNTL_SIZE_LIMIT:          zOp = "SIZE_LIMIT";          break;
   18879     case SQLITE_FCNTL_CKPT_DONE:           zOp = "CKPT_DONE";           break;
   18880     case SQLITE_FCNTL_RESERVE_BYTES:       zOp = "RESERVED_BYTES";      break;
   18881     case SQLITE_FCNTL_CKPT_START:          zOp = "CKPT_START";          break;
   18882     case SQLITE_FCNTL_EXTERNAL_READER:     zOp = "EXTERNAL_READER";     break;
   18883     case SQLITE_FCNTL_CKSM_FILE:           zOp = "CKSM_FILE";           break;
   18884     case SQLITE_FCNTL_RESET_CACHE:         zOp = "RESET_CACHE";         break;
   18885     case 0xca093fa0:                       zOp = "DB_UNCHANGED";        break;
   18886     default: {
   18887       sqlite3_snprintf(sizeof zBuf, zBuf, "%d", op);
   18888       zOp = zBuf;
   18889       break;
   18890     }
   18891   }
   18892   vfstrace_printf(pInfo, "%s.xFileControl(%s,%s)",
   18893                   pInfo->zVfsName, p->zFName, zOp);
   18894   rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg);
   18895   if( rc==SQLITE_OK ){
   18896     switch( op ){
   18897       case SQLITE_FCNTL_VFSNAME: {
   18898         *(char**)pArg = sqlite3_mprintf("vfstrace.%s/%z",
   18899                                     pInfo->zVfsName, *(char**)pArg);
   18900         zRVal = *(char**)pArg;
   18901         break;
   18902       }
   18903       case SQLITE_FCNTL_MMAP_SIZE: {
   18904         sqlite3_snprintf(sizeof(zBuf2), zBuf2, "%lld", *(sqlite3_int64*)pArg);
   18905         zRVal = zBuf2;
   18906         break;
   18907       }
   18908       case SQLITE_FCNTL_HAS_MOVED:
   18909       case SQLITE_FCNTL_PERSIST_WAL: {
   18910         sqlite3_snprintf(sizeof(zBuf2), zBuf2, "%d", *(int*)pArg);
   18911         zRVal = zBuf2;
   18912         break;
   18913       }
   18914       case SQLITE_FCNTL_PRAGMA:
   18915       case SQLITE_FCNTL_TEMPFILENAME: {
   18916         zRVal = *(char**)pArg;
   18917         break;
   18918       }
   18919     }
   18920   }
   18921   if( zRVal ){
   18922     vfstrace_print_errcode(pInfo, " -> %s", rc);
   18923     vfstrace_printf(pInfo, ", %s\n", zRVal);
   18924   }else{
   18925     vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18926   }
   18927   return rc;
   18928 }
   18929 
   18930 /*
   18931 ** Return the sector-size in bytes for an vfstrace-file.
   18932 */
   18933 static int vfstraceSectorSize(sqlite3_file *pFile){
   18934   vfstrace_file *p = (vfstrace_file *)pFile;
   18935   vfstrace_info *pInfo = p->pInfo;
   18936   int rc;
   18937   vfstraceOnOff(pInfo, VTR_SECSZ);
   18938   vfstrace_printf(pInfo, "%s.xSectorSize(%s)", pInfo->zVfsName, p->zFName);
   18939   rc = p->pReal->pMethods->xSectorSize(p->pReal);
   18940   vfstrace_printf(pInfo, " -> %d\n", rc);
   18941   return rc;
   18942 }
   18943 
   18944 /*
   18945 ** Return the device characteristic flags supported by an vfstrace-file.
   18946 */
   18947 static int vfstraceDeviceCharacteristics(sqlite3_file *pFile){
   18948   vfstrace_file *p = (vfstrace_file *)pFile;
   18949   vfstrace_info *pInfo = p->pInfo;
   18950   int rc;
   18951   vfstraceOnOff(pInfo, VTR_DEVCHAR);
   18952   vfstrace_printf(pInfo, "%s.xDeviceCharacteristics(%s)",
   18953                   pInfo->zVfsName, p->zFName);
   18954   rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
   18955   vfstrace_printf(pInfo, " -> 0x%08x\n", rc);
   18956   return rc;
   18957 }
   18958 
   18959 /*
   18960 ** Shared-memory operations.
   18961 */
   18962 static int vfstraceShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
   18963   static const char *azLockName[] = {
   18964      "WRITE",
   18965      "CKPT",
   18966      "RECOVER",
   18967      "READ0",
   18968      "READ1",
   18969      "READ2",
   18970      "READ3",
   18971      "READ4",
   18972   };
   18973   vfstrace_file *p = (vfstrace_file *)pFile;
   18974   vfstrace_info *pInfo = p->pInfo;
   18975   int rc;
   18976   char zLck[100];
   18977   int i = 0;
   18978   vfstraceOnOff(pInfo, VTR_SHMLOCK);
   18979   memcpy(zLck, "|0", 3);
   18980   if( flags & SQLITE_SHM_UNLOCK )    strappend(zLck, &i, "|UNLOCK");
   18981   if( flags & SQLITE_SHM_LOCK )      strappend(zLck, &i, "|LOCK");
   18982   if( flags & SQLITE_SHM_SHARED )    strappend(zLck, &i, "|SHARED");
   18983   if( flags & SQLITE_SHM_EXCLUSIVE ) strappend(zLck, &i, "|EXCLUSIVE");
   18984   if( flags & ~(0xf) ){
   18985      sqlite3_snprintf(sizeof(zLck)-i, &zLck[i], "|0x%x", flags);
   18986   }
   18987   if( ofst>=0 && ofst<(int)(sizeof(azLockName)/sizeof(azLockName[0])) ){
   18988     vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=%d(%s),n=%d,%s)",
   18989                   pInfo->zVfsName, p->zFName, ofst, azLockName[ofst],
   18990                   n, &zLck[1]);
   18991   }else{
   18992     vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=5d,n=%d,%s)",
   18993                   pInfo->zVfsName, p->zFName, ofst,
   18994                   n, &zLck[1]);
   18995   }
   18996   rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
   18997   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   18998   return rc;
   18999 }
   19000 static int vfstraceShmMap(
   19001   sqlite3_file *pFile,
   19002   int iRegion,
   19003   int szRegion,
   19004   int isWrite,
   19005   void volatile **pp
   19006 ){
   19007   vfstrace_file *p = (vfstrace_file *)pFile;
   19008   vfstrace_info *pInfo = p->pInfo;
   19009   int rc;
   19010   vfstraceOnOff(pInfo, VTR_SHMMAP);
   19011   vfstrace_printf(pInfo, "%s.xShmMap(%s,iRegion=%d,szRegion=%d,isWrite=%d,*)",
   19012                   pInfo->zVfsName, p->zFName, iRegion, szRegion, isWrite);
   19013   rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
   19014   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   19015   return rc;
   19016 }
   19017 static void vfstraceShmBarrier(sqlite3_file *pFile){
   19018   vfstrace_file *p = (vfstrace_file *)pFile;
   19019   vfstrace_info *pInfo = p->pInfo;
   19020   vfstraceOnOff(pInfo, VTR_SHMBAR);
   19021   vfstrace_printf(pInfo, "%s.xShmBarrier(%s)\n", pInfo->zVfsName, p->zFName);
   19022   p->pReal->pMethods->xShmBarrier(p->pReal);
   19023 }
   19024 static int vfstraceShmUnmap(sqlite3_file *pFile, int delFlag){
   19025   vfstrace_file *p = (vfstrace_file *)pFile;
   19026   vfstrace_info *pInfo = p->pInfo;
   19027   int rc;
   19028   vfstraceOnOff(pInfo, VTR_SHMUNMAP);
   19029   vfstrace_printf(pInfo, "%s.xShmUnmap(%s,delFlag=%d)",
   19030                   pInfo->zVfsName, p->zFName, delFlag);
   19031   rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
   19032   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   19033   return rc;
   19034 }
   19035 static int vfstraceFetch(sqlite3_file *pFile, i64 iOff, int nAmt, void **pptr){
   19036   vfstrace_file *p = (vfstrace_file *)pFile;
   19037   vfstrace_info *pInfo = p->pInfo;
   19038   int rc;
   19039   vfstraceOnOff(pInfo, VTR_FETCH);
   19040   vfstrace_printf(pInfo, "%s.xFetch(%s,iOff=%lld,nAmt=%d,p=%p)",
   19041                   pInfo->zVfsName, p->zFName, iOff, nAmt, *pptr);
   19042   rc = p->pReal->pMethods->xFetch(p->pReal, iOff, nAmt, pptr);
   19043   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   19044   return rc;
   19045 }
   19046 static int vfstraceUnfetch(sqlite3_file *pFile, i64 iOff, void *ptr){
   19047   vfstrace_file *p = (vfstrace_file *)pFile;
   19048   vfstrace_info *pInfo = p->pInfo;
   19049   int rc;
   19050   vfstraceOnOff(pInfo, VTR_FETCH);
   19051   vfstrace_printf(pInfo, "%s.xUnfetch(%s,iOff=%lld,p=%p)",
   19052                   pInfo->zVfsName, p->zFName, iOff, ptr);
   19053   rc = p->pReal->pMethods->xUnfetch(p->pReal, iOff, ptr);
   19054   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   19055   return rc;
   19056 }
   19057 
   19058 
   19059 /*
   19060 ** Open an vfstrace file handle.
   19061 */
   19062 static int vfstraceOpen(
   19063   sqlite3_vfs *pVfs,
   19064   const char *zName,
   19065   sqlite3_file *pFile,
   19066   int flags,
   19067   int *pOutFlags
   19068 ){
   19069   int rc;
   19070   vfstrace_file *p = (vfstrace_file *)pFile;
   19071   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19072   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19073   p->pInfo = pInfo;
   19074   p->zFName = zName ? fileTail(zName) : "<temp>";
   19075   p->pReal = (sqlite3_file *)&p[1];
   19076   rc = pRoot->xOpen(pRoot, zName, p->pReal, flags, pOutFlags);
   19077   vfstraceOnOff(pInfo, VTR_OPEN);
   19078   vfstrace_printf(pInfo, "%s.xOpen(%s,flags=0x%x)",
   19079                   pInfo->zVfsName, p->zFName, flags);
   19080   if( p->pReal->pMethods ){
   19081     sqlite3_io_methods *pNew = sqlite3_malloc64( sizeof(*pNew) );
   19082     const sqlite3_io_methods *pSub = p->pReal->pMethods;
   19083     memset(pNew, 0, sizeof(*pNew));
   19084     pNew->iVersion = pSub->iVersion;
   19085     pNew->xClose = vfstraceClose;
   19086     pNew->xRead = vfstraceRead;
   19087     pNew->xWrite = vfstraceWrite;
   19088     pNew->xTruncate = vfstraceTruncate;
   19089     pNew->xSync = vfstraceSync;
   19090     pNew->xFileSize = vfstraceFileSize;
   19091     pNew->xLock = vfstraceLock;
   19092     pNew->xUnlock = vfstraceUnlock;
   19093     pNew->xCheckReservedLock = vfstraceCheckReservedLock;
   19094     pNew->xFileControl = vfstraceFileControl;
   19095     pNew->xSectorSize = vfstraceSectorSize;
   19096     pNew->xDeviceCharacteristics = vfstraceDeviceCharacteristics;
   19097     if( pNew->iVersion>=2 ){
   19098       pNew->xShmMap = pSub->xShmMap ? vfstraceShmMap : 0;
   19099       pNew->xShmLock = pSub->xShmLock ? vfstraceShmLock : 0;
   19100       pNew->xShmBarrier = pSub->xShmBarrier ? vfstraceShmBarrier : 0;
   19101       pNew->xShmUnmap = pSub->xShmUnmap ? vfstraceShmUnmap : 0;
   19102     }
   19103     if( pNew->iVersion>=3 ){
   19104       pNew->xFetch = pSub->xFetch ? vfstraceFetch : 0;
   19105       pNew->xUnfetch = pSub->xUnfetch ? vfstraceUnfetch : 0;
   19106     }
   19107     pFile->pMethods = pNew;
   19108   }
   19109   vfstrace_print_errcode(pInfo, " -> %s", rc);
   19110   if( pOutFlags ){
   19111     vfstrace_printf(pInfo, ", outFlags=0x%x\n", *pOutFlags);
   19112   }else{
   19113     vfstrace_printf(pInfo, "\n");
   19114   }
   19115   return rc;
   19116 }
   19117 
   19118 /*
   19119 ** Delete the file located at zPath. If the dirSync argument is true,
   19120 ** ensure the file-system modifications are synced to disk before
   19121 ** returning.
   19122 */
   19123 static int vfstraceDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   19124   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19125   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19126   int rc;
   19127   vfstraceOnOff(pInfo, VTR_DELETE);
   19128   vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)",
   19129                   pInfo->zVfsName, zPath, dirSync);
   19130   rc = pRoot->xDelete(pRoot, zPath, dirSync);
   19131   vfstrace_print_errcode(pInfo, " -> %s\n", rc);
   19132   return rc;
   19133 }
   19134 
   19135 /*
   19136 ** Test for access permissions. Return true if the requested permission
   19137 ** is available, or false otherwise.
   19138 */
   19139 static int vfstraceAccess(
   19140   sqlite3_vfs *pVfs,
   19141   const char *zPath,
   19142   int flags,
   19143   int *pResOut
   19144 ){
   19145   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19146   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19147   int rc;
   19148   vfstraceOnOff(pInfo, VTR_ACCESS);
   19149   vfstrace_printf(pInfo, "%s.xAccess(\"%s\",%d)",
   19150                   pInfo->zVfsName, zPath, flags);
   19151   rc = pRoot->xAccess(pRoot, zPath, flags, pResOut);
   19152   vfstrace_print_errcode(pInfo, " -> %s", rc);
   19153   vfstrace_printf(pInfo, ", out=%d\n", *pResOut);
   19154   return rc;
   19155 }
   19156 
   19157 /*
   19158 ** Populate buffer zOut with the full canonical pathname corresponding
   19159 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
   19160 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
   19161 */
   19162 static int vfstraceFullPathname(
   19163   sqlite3_vfs *pVfs,
   19164   const char *zPath,
   19165   int nOut,
   19166   char *zOut
   19167 ){
   19168   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19169   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19170   int rc;
   19171   vfstraceOnOff(pInfo, VTR_FULLPATH);
   19172   vfstrace_printf(pInfo, "%s.xFullPathname(\"%s\")",
   19173                   pInfo->zVfsName, zPath);
   19174   rc = pRoot->xFullPathname(pRoot, zPath, nOut, zOut);
   19175   vfstrace_print_errcode(pInfo, " -> %s", rc);
   19176   vfstrace_printf(pInfo, ", out=\"%.*s\"\n", nOut, zOut);
   19177   return rc;
   19178 }
   19179 
   19180 /*
   19181 ** Open the dynamic library located at zPath and return a handle.
   19182 */
   19183 static void *vfstraceDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   19184   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19185   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19186   vfstraceOnOff(pInfo, VTR_DLOPEN);
   19187   vfstrace_printf(pInfo, "%s.xDlOpen(\"%s\")\n", pInfo->zVfsName, zPath);
   19188   return pRoot->xDlOpen(pRoot, zPath);
   19189 }
   19190 
   19191 /*
   19192 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
   19193 ** utf-8 string describing the most recent error encountered associated
   19194 ** with dynamic libraries.
   19195 */
   19196 static void vfstraceDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
   19197   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19198   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19199   vfstraceOnOff(pInfo, VTR_DLERR);
   19200   vfstrace_printf(pInfo, "%s.xDlError(%d)", pInfo->zVfsName, nByte);
   19201   pRoot->xDlError(pRoot, nByte, zErrMsg);
   19202   vfstrace_printf(pInfo, " -> \"%s\"", zErrMsg);
   19203 }
   19204 
   19205 /*
   19206 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
   19207 */
   19208 static void (*vfstraceDlSym(sqlite3_vfs *pVfs,void *p,const char *zSym))(void){
   19209   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19210   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19211   vfstrace_printf(pInfo, "%s.xDlSym(\"%s\")\n", pInfo->zVfsName, zSym);
   19212   return pRoot->xDlSym(pRoot, p, zSym);
   19213 }
   19214 
   19215 /*
   19216 ** Close the dynamic library handle pHandle.
   19217 */
   19218 static void vfstraceDlClose(sqlite3_vfs *pVfs, void *pHandle){
   19219   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19220   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19221   vfstraceOnOff(pInfo, VTR_DLCLOSE);
   19222   vfstrace_printf(pInfo, "%s.xDlClose()\n", pInfo->zVfsName);
   19223   pRoot->xDlClose(pRoot, pHandle);
   19224 }
   19225 
   19226 /*
   19227 ** Populate the buffer pointed to by zBufOut with nByte bytes of
   19228 ** random data.
   19229 */
   19230 static int vfstraceRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   19231   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19232   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19233   vfstraceOnOff(pInfo, VTR_RAND);
   19234   vfstrace_printf(pInfo, "%s.xRandomness(%d)\n", pInfo->zVfsName, nByte);
   19235   return pRoot->xRandomness(pRoot, nByte, zBufOut);
   19236 }
   19237 
   19238 /*
   19239 ** Sleep for nMicro microseconds. Return the number of microseconds
   19240 ** actually slept.
   19241 */
   19242 static int vfstraceSleep(sqlite3_vfs *pVfs, int nMicro){
   19243   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19244   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19245   vfstraceOnOff(pInfo, VTR_SLEEP);
   19246   vfstrace_printf(pInfo, "%s.xSleep(%d)\n", pInfo->zVfsName, nMicro);
   19247   return pRoot->xSleep(pRoot, nMicro);
   19248 }
   19249 
   19250 /*
   19251 ** Return the current time as a Julian Day number in *pTimeOut.
   19252 */
   19253 static int vfstraceCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
   19254   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19255   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19256   int rc;
   19257   vfstraceOnOff(pInfo, VTR_CURTIME);
   19258   vfstrace_printf(pInfo, "%s.xCurrentTime()", pInfo->zVfsName);
   19259   rc = pRoot->xCurrentTime(pRoot, pTimeOut);
   19260   vfstrace_printf(pInfo, " -> %.17g\n", *pTimeOut);
   19261   return rc;
   19262 }
   19263 static int vfstraceCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
   19264   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19265   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19266   int rc;
   19267   vfstraceOnOff(pInfo, VTR_CURTIME);
   19268   vfstrace_printf(pInfo, "%s.xCurrentTimeInt64()", pInfo->zVfsName);
   19269   rc = pRoot->xCurrentTimeInt64(pRoot, pTimeOut);
   19270   vfstrace_printf(pInfo, " -> %lld\n", *pTimeOut);
   19271   return rc;
   19272 }
   19273 
   19274 /*
   19275 ** Return the most recent error code and message
   19276 */
   19277 static int vfstraceGetLastError(sqlite3_vfs *pVfs, int nErr, char *zErr){
   19278   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19279   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19280   int rc;
   19281   vfstraceOnOff(pInfo, VTR_LASTERR);
   19282   vfstrace_printf(pInfo, "%s.xGetLastError(%d,zBuf)", pInfo->zVfsName, nErr);
   19283   if( nErr ) zErr[0] = 0;
   19284   rc = pRoot->xGetLastError(pRoot, nErr, zErr);
   19285   vfstrace_printf(pInfo, " -> zBuf[] = \"%s\", rc = %d\n", nErr?zErr:"", rc);
   19286   return rc;
   19287 }
   19288 
   19289 /*
   19290 ** Override system calls.
   19291 */
   19292 static int vfstraceSetSystemCall(
   19293   sqlite3_vfs *pVfs,
   19294   const char *zName,
   19295   sqlite3_syscall_ptr pFunc
   19296 ){
   19297   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19298   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19299   return pRoot->xSetSystemCall(pRoot, zName, pFunc);
   19300 }
   19301 static sqlite3_syscall_ptr vfstraceGetSystemCall(
   19302   sqlite3_vfs *pVfs,
   19303   const char *zName
   19304 ){
   19305   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19306   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19307   return pRoot->xGetSystemCall(pRoot, zName);
   19308 }
   19309 static const char *vfstraceNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
   19310   vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData;
   19311   sqlite3_vfs *pRoot = pInfo->pRootVfs;
   19312   return pRoot->xNextSystemCall(pRoot, zName);
   19313 }
   19314 
   19315 
   19316 /*
   19317 ** Clients invoke this routine to construct a new trace-vfs shim.
   19318 **
   19319 ** Return SQLITE_OK on success.
   19320 **
   19321 ** SQLITE_NOMEM is returned in the case of a memory allocation error.
   19322 ** SQLITE_NOTFOUND is returned if zOldVfsName does not exist.
   19323 */
   19324 static int vfstrace_register(
   19325    const char *zTraceName,           /* Name of the newly constructed VFS */
   19326    const char *zOldVfsName,          /* Name of the underlying VFS */
   19327    int (*xOut)(const char*,void*),   /* Output routine.  ex: fputs */
   19328    void *pOutArg,                    /* 2nd argument to xOut.  ex: stderr */
   19329    int makeDefault                   /* True to make the new VFS the default */
   19330 ){
   19331   sqlite3_vfs *pNew;
   19332   sqlite3_vfs *pRoot;
   19333   vfstrace_info *pInfo;
   19334   size_t nName;
   19335   size_t nByte;
   19336 
   19337   pRoot = sqlite3_vfs_find(zOldVfsName);
   19338   if( pRoot==0 ) return SQLITE_NOTFOUND;
   19339   nName = strlen(zTraceName);
   19340   nByte = sizeof(*pNew) + sizeof(*pInfo) + nName + 1;
   19341   pNew = sqlite3_malloc64( nByte );
   19342   if( pNew==0 ) return SQLITE_NOMEM;
   19343   memset(pNew, 0, nByte);
   19344   pInfo = (vfstrace_info*)&pNew[1];
   19345   pNew->iVersion = pRoot->iVersion;
   19346   pNew->szOsFile = pRoot->szOsFile + sizeof(vfstrace_file);
   19347   pNew->mxPathname = pRoot->mxPathname;
   19348   pNew->zName = (char*)&pInfo[1];
   19349   memcpy((char*)&pInfo[1], zTraceName, nName+1);
   19350   pNew->pAppData = pInfo;
   19351   pNew->xOpen = vfstraceOpen;
   19352   pNew->xDelete = vfstraceDelete;
   19353   pNew->xAccess = vfstraceAccess;
   19354   pNew->xFullPathname = vfstraceFullPathname;
   19355   pNew->xDlOpen = pRoot->xDlOpen==0 ? 0 : vfstraceDlOpen;
   19356   pNew->xDlError = pRoot->xDlError==0 ? 0 : vfstraceDlError;
   19357   pNew->xDlSym = pRoot->xDlSym==0 ? 0 : vfstraceDlSym;
   19358   pNew->xDlClose = pRoot->xDlClose==0 ? 0 : vfstraceDlClose;
   19359   pNew->xRandomness = vfstraceRandomness;
   19360   pNew->xSleep = vfstraceSleep;
   19361   pNew->xCurrentTime = vfstraceCurrentTime;
   19362   pNew->xGetLastError = pRoot->xGetLastError==0 ? 0 : vfstraceGetLastError;
   19363   if( pNew->iVersion>=2 ){
   19364     pNew->xCurrentTimeInt64 = pRoot->xCurrentTimeInt64==0 ? 0 :
   19365                                    vfstraceCurrentTimeInt64;
   19366     if( pNew->iVersion>=3 ){
   19367       pNew->xSetSystemCall = pRoot->xSetSystemCall==0 ? 0 :
   19368                                    vfstraceSetSystemCall;
   19369       pNew->xGetSystemCall = pRoot->xGetSystemCall==0 ? 0 :
   19370                                    vfstraceGetSystemCall;
   19371       pNew->xNextSystemCall = pRoot->xNextSystemCall==0 ? 0 :
   19372                                    vfstraceNextSystemCall;
   19373     }
   19374   }
   19375   pInfo->pRootVfs = pRoot;
   19376   pInfo->xOut = xOut;
   19377   pInfo->pOutArg = pOutArg;
   19378   pInfo->zVfsName = pNew->zName;
   19379   pInfo->pTraceVfs = pNew;
   19380   pInfo->mTrace = 0xffffffff;
   19381   pInfo->bOn = 1;
   19382   vfstrace_printf(pInfo, "%s.enabled_for(\"%s\")\n",
   19383        pInfo->zVfsName, pRoot->zName);
   19384   return sqlite3_vfs_register(pNew, makeDefault);
   19385 }
   19386 
   19387 /*
   19388 ** Look for the named VFS.  If it is a TRACEVFS, then unregister it
   19389 ** and delete it.
   19390 */
   19391 static void vfstrace_unregister(const char *zTraceName){
   19392   sqlite3_vfs *pVfs = sqlite3_vfs_find(zTraceName);
   19393   if( pVfs==0 ) return;
   19394   if( pVfs->xOpen!=vfstraceOpen ) return;
   19395   sqlite3_vfs_unregister(pVfs);
   19396   sqlite3_free(pVfs);
   19397 }
   19398 
   19399 /************************* End ext/misc/vfstrace.c ********************/
   19400 
   19401 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
   19402 #define SQLITE_SHELL_HAVE_RECOVER 1
   19403 #else
   19404 #define SQLITE_SHELL_HAVE_RECOVER 0
   19405 #endif
   19406 #if SQLITE_SHELL_HAVE_RECOVER
   19407 /************************* Begin ext/recover/sqlite3recover.h ******************/
   19408 /*
   19409 ** 2022-08-27
   19410 **
   19411 ** The author disclaims copyright to this source code.  In place of
   19412 ** a legal notice, here is a blessing:
   19413 **
   19414 **    May you do good and not evil.
   19415 **    May you find forgiveness for yourself and forgive others.
   19416 **    May you share freely, never taking more than you give.
   19417 **
   19418 *************************************************************************
   19419 **
   19420 ** This file contains the public interface to the "recover" extension -
   19421 ** an SQLite extension designed to recover data from corrupted database
   19422 ** files.
   19423 */
   19424 
   19425 /*
   19426 ** OVERVIEW:
   19427 **
   19428 ** To use the API to recover data from a corrupted database, an
   19429 ** application:
   19430 **
   19431 **   1) Creates an sqlite3_recover handle by calling either
   19432 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
   19433 **
   19434 **   2) Configures the new handle using one or more calls to
   19435 **      sqlite3_recover_config().
   19436 **
   19437 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
   19438 **      the handle until it returns something other than SQLITE_OK. If it
   19439 **      returns SQLITE_DONE, then the recovery operation completed without
   19440 **      error. If it returns some other non-SQLITE_OK value, then an error
   19441 **      has occurred.
   19442 **
   19443 **   4) Retrieves any error code and English language error message using the
   19444 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
   19445 **      respectively.
   19446 **
   19447 **   5) Destroys the sqlite3_recover handle and frees all resources
   19448 **      using sqlite3_recover_finish().
   19449 **
   19450 ** The application may abandon the recovery operation at any point
   19451 ** before it is finished by passing the sqlite3_recover handle to
   19452 ** sqlite3_recover_finish(). This is not an error, but the final state
   19453 ** of the output database, or the results of running the partial script
   19454 ** delivered to the SQL callback, are undefined.
   19455 */
   19456 
   19457 #ifndef _SQLITE_RECOVER_H
   19458 #define _SQLITE_RECOVER_H
   19459 
   19460 /* #include "sqlite3.h" */
   19461 
   19462 #ifdef __cplusplus
   19463 extern "C" {
   19464 #endif
   19465 
   19466 /*
   19467 ** An instance of the sqlite3_recover object represents a recovery
   19468 ** operation in progress.
   19469 **
   19470 ** Constructors:
   19471 **
   19472 **    sqlite3_recover_init()
   19473 **    sqlite3_recover_init_sql()
   19474 **
   19475 ** Destructor:
   19476 **
   19477 **    sqlite3_recover_finish()
   19478 **
   19479 ** Methods:
   19480 **
   19481 **    sqlite3_recover_config()
   19482 **    sqlite3_recover_errcode()
   19483 **    sqlite3_recover_errmsg()
   19484 **    sqlite3_recover_run()
   19485 **    sqlite3_recover_step()
   19486 */
   19487 typedef struct sqlite3_recover sqlite3_recover;
   19488 
   19489 /*
   19490 ** These two APIs attempt to create and return a new sqlite3_recover object.
   19491 ** In both cases the first two arguments identify the (possibly
   19492 ** corrupt) database to recover data from. The first argument is an open
   19493 ** database handle and the second the name of a database attached to that
   19494 ** handle (i.e. "main", "temp" or the name of an attached database).
   19495 **
   19496 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
   19497 ** handle, then data is recovered into a new database, identified by
   19498 ** string parameter zUri. zUri may be an absolute or relative file path,
   19499 ** or may be an SQLite URI. If the identified database file already exists,
   19500 ** it is overwritten.
   19501 **
   19502 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
   19503 ** be returned to the user as a series of SQL statements. Executing these
   19504 ** SQL statements results in the same database as would have been created
   19505 ** had sqlite3_recover_init() been used. For each SQL statement in the
   19506 ** output, the callback function passed as the third argument (xSql) is
   19507 ** invoked once. The first parameter is a passed a copy of the fourth argument
   19508 ** to this function (pCtx) as its first parameter, and a pointer to a
   19509 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
   19510 ** the second. If the xSql callback returns any value other than SQLITE_OK,
   19511 ** then processing is immediately abandoned and the value returned used as
   19512 ** the recover handle error code (see below).
   19513 **
   19514 ** If an out-of-memory error occurs, NULL may be returned instead of
   19515 ** a valid handle. In all other cases, it is the responsibility of the
   19516 ** application to avoid resource leaks by ensuring that
   19517 ** sqlite3_recover_finish() is called on all allocated handles.
   19518 */
   19519 sqlite3_recover *sqlite3_recover_init(
   19520   sqlite3* db,
   19521   const char *zDb,
   19522   const char *zUri
   19523 );
   19524 sqlite3_recover *sqlite3_recover_init_sql(
   19525   sqlite3* db,
   19526   const char *zDb,
   19527   int (*xSql)(void*, const char*),
   19528   void *pCtx
   19529 );
   19530 
   19531 /*
   19532 ** Configure an sqlite3_recover object that has just been created using
   19533 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
   19534 ** may only be called before the first call to sqlite3_recover_step()
   19535 ** or sqlite3_recover_run() on the object.
   19536 **
   19537 ** The second argument passed to this function must be one of the
   19538 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
   19539 ** depend on the specific SQLITE_RECOVER_* symbol in use.
   19540 **
   19541 ** SQLITE_OK is returned if the configuration operation was successful,
   19542 ** or an SQLite error code otherwise.
   19543 */
   19544 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
   19545 
   19546 /*
   19547 ** SQLITE_RECOVER_LOST_AND_FOUND:
   19548 **   The pArg argument points to a string buffer containing the name
   19549 **   of a "lost-and-found" table in the output database, or NULL. If
   19550 **   the argument is non-NULL and the database contains seemingly
   19551 **   valid pages that cannot be associated with any table in the
   19552 **   recovered part of the schema, data is extracted from these
   19553 **   pages to add to the lost-and-found table.
   19554 **
   19555 ** SQLITE_RECOVER_FREELIST_CORRUPT:
   19556 **   The pArg value must actually be a pointer to a value of type
   19557 **   int containing value 0 or 1 cast as a (void*). If this option is set
   19558 **   (argument is 1) and a lost-and-found table has been configured using
   19559 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
   19560 **   corrupt and an attempt is made to recover records from pages that
   19561 **   appear to be linked into the freelist. Otherwise, pages on the freelist
   19562 **   are ignored. Setting this option can recover more data from the
   19563 **   database, but often ends up "recovering" deleted records. The default
   19564 **   value is 0 (clear).
   19565 **
   19566 ** SQLITE_RECOVER_ROWIDS:
   19567 **   The pArg value must actually be a pointer to a value of type
   19568 **   int containing value 0 or 1 cast as a (void*). If this option is set
   19569 **   (argument is 1), then an attempt is made to recover rowid values
   19570 **   that are not also INTEGER PRIMARY KEY values. If this option is
   19571 **   clear, then new rowids are assigned to all recovered rows. The
   19572 **   default value is 1 (set).
   19573 **
   19574 ** SQLITE_RECOVER_SLOWINDEXES:
   19575 **   The pArg value must actually be a pointer to a value of type
   19576 **   int containing value 0 or 1 cast as a (void*). If this option is clear
   19577 **   (argument is 0), then when creating an output database, the recover
   19578 **   module creates and populates non-UNIQUE indexes right at the end of the
   19579 **   recovery operation - after all recoverable data has been inserted
   19580 **   into the new database. This is faster overall, but means that the
   19581 **   final call to sqlite3_recover_step() for a recovery operation may
   19582 **   be need to create a large number of indexes, which may be very slow.
   19583 **
   19584 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
   19585 **   are created in the output database before it is populated with
   19586 **   recovered data. This is slower overall, but avoids the slow call
   19587 **   to sqlite3_recover_step() at the end of the recovery operation.
   19588 **
   19589 **   The default option value is 0.
   19590 */
   19591 #define SQLITE_RECOVER_LOST_AND_FOUND   1
   19592 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
   19593 #define SQLITE_RECOVER_ROWIDS           3
   19594 #define SQLITE_RECOVER_SLOWINDEXES      4
   19595 
   19596 /*
   19597 ** Perform a unit of work towards the recovery operation. This function
   19598 ** must normally be called multiple times to complete database recovery.
   19599 **
   19600 ** If no error occurs but the recovery operation is not completed, this
   19601 ** function returns SQLITE_OK. If recovery has been completed successfully
   19602 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
   19603 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
   19604 ** considered an error if some or all of the data cannot be recovered
   19605 ** due to database corruption.
   19606 **
   19607 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
   19608 ** all further such calls on the same recover handle are no-ops that return
   19609 ** the same non-SQLITE_OK value.
   19610 */
   19611 int sqlite3_recover_step(sqlite3_recover*);
   19612 
   19613 /*
   19614 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
   19615 ** or an SQLite error code otherwise. Calling this function is the same
   19616 ** as executing:
   19617 **
   19618 **     while( SQLITE_OK==sqlite3_recover_step(p) );
   19619 **     return sqlite3_recover_errcode(p);
   19620 */
   19621 int sqlite3_recover_run(sqlite3_recover*);
   19622 
   19623 /*
   19624 ** If an error has been encountered during a prior call to
   19625 ** sqlite3_recover_step(), then this function attempts to return a
   19626 ** pointer to a buffer containing an English language explanation of
   19627 ** the error. If no error message is available, or if an out-of memory
   19628 ** error occurs while attempting to allocate a buffer in which to format
   19629 ** the error message, NULL is returned.
   19630 **
   19631 ** The returned buffer remains valid until the sqlite3_recover handle is
   19632 ** destroyed using sqlite3_recover_finish().
   19633 */
   19634 const char *sqlite3_recover_errmsg(sqlite3_recover*);
   19635 
   19636 /*
   19637 ** If this function is called on an sqlite3_recover handle after
   19638 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
   19639 */
   19640 int sqlite3_recover_errcode(sqlite3_recover*);
   19641 
   19642 /*
   19643 ** Clean up a recovery object created by a call to sqlite3_recover_init().
   19644 ** The results of using a recovery object with any API after it has been
   19645 ** passed to this function are undefined.
   19646 **
   19647 ** This function returns the same value as sqlite3_recover_errcode().
   19648 */
   19649 int sqlite3_recover_finish(sqlite3_recover*);
   19650 
   19651 
   19652 #ifdef __cplusplus
   19653 }  /* end of the 'extern "C"' block */
   19654 #endif
   19655 
   19656 #endif /* ifndef _SQLITE_RECOVER_H */
   19657 
   19658 /************************* End ext/recover/sqlite3recover.h ********************/
   19659 # ifndef SQLITE_HAVE_SQLITE3R
   19660 /************************* Begin ext/recover/dbdata.c ******************/
   19661 /*
   19662 ** 2019-04-17
   19663 **
   19664 ** The author disclaims copyright to this source code.  In place of
   19665 ** a legal notice, here is a blessing:
   19666 **
   19667 **    May you do good and not evil.
   19668 **    May you find forgiveness for yourself and forgive others.
   19669 **    May you share freely, never taking more than you give.
   19670 **
   19671 ******************************************************************************
   19672 **
   19673 ** This file contains an implementation of two eponymous virtual tables,
   19674 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
   19675 ** "sqlite_dbpage" eponymous virtual table be available.
   19676 **
   19677 ** SQLITE_DBDATA:
   19678 **   sqlite_dbdata is used to extract data directly from a database b-tree
   19679 **   page and its associated overflow pages, bypassing the b-tree layer.
   19680 **   The table schema is equivalent to:
   19681 **
   19682 **     CREATE TABLE sqlite_dbdata(
   19683 **       pgno INTEGER,
   19684 **       cell INTEGER,
   19685 **       field INTEGER,
   19686 **       value ANY,
   19687 **       schema TEXT HIDDEN
   19688 **     );
   19689 **
   19690 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
   19691 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
   19692 **   "schema".
   19693 **
   19694 **   Each page of the database is inspected. If it cannot be interpreted as
   19695 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
   19696 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
   19697 **   table contains one row for each field in the record associated with
   19698 **   each cell on the page. For intkey b-trees, the key value is stored in
   19699 **   field -1.
   19700 **
   19701 **   For example, for the database:
   19702 **
   19703 **     CREATE TABLE t1(a, b);     -- root page is page 2
   19704 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
   19705 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
   19706 **
   19707 **   the sqlite_dbdata table contains, as well as from entries related to
   19708 **   page 1, content equivalent to:
   19709 **
   19710 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
   19711 **         (2, 0, -1, 5     ),
   19712 **         (2, 0,  0, 'v'   ),
   19713 **         (2, 0,  1, 'five'),
   19714 **         (2, 1, -1, 10    ),
   19715 **         (2, 1,  0, 'x'   ),
   19716 **         (2, 1,  1, 'ten' );
   19717 **
   19718 **   If database corruption is encountered, this module does not report an
   19719 **   error. Instead, it attempts to extract as much data as possible and
   19720 **   ignores the corruption.
   19721 **
   19722 ** SQLITE_DBPTR:
   19723 **   The sqlite_dbptr table has the following schema:
   19724 **
   19725 **     CREATE TABLE sqlite_dbptr(
   19726 **       pgno INTEGER,
   19727 **       child INTEGER,
   19728 **       schema TEXT HIDDEN
   19729 **     );
   19730 **
   19731 **   It contains one entry for each b-tree pointer between a parent and
   19732 **   child page in the database.
   19733 */
   19734 
   19735 #if !defined(SQLITEINT_H)
   19736 /* #include "sqlite3.h" */
   19737 
   19738 /* typedef unsigned char u8; */
   19739 /* typedef unsigned int u32; */
   19740 
   19741 #endif
   19742 #include <string.h>
   19743 #include <assert.h>
   19744 
   19745 #ifndef SQLITE_OMIT_VIRTUALTABLE
   19746 
   19747 #define DBDATA_PADDING_BYTES 100
   19748 
   19749 typedef struct DbdataTable DbdataTable;
   19750 typedef struct DbdataCursor DbdataCursor;
   19751 typedef struct DbdataBuffer DbdataBuffer;
   19752 
   19753 /*
   19754 ** Buffer type.
   19755 */
   19756 struct DbdataBuffer {
   19757   u8 *aBuf;
   19758   sqlite3_int64 nBuf;
   19759 };
   19760 
   19761 /* Cursor object */
   19762 struct DbdataCursor {
   19763   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
   19764   sqlite3_stmt *pStmt;            /* For fetching database pages */
   19765 
   19766   int iPgno;                      /* Current page number */
   19767   u8 *aPage;                      /* Buffer containing page */
   19768   int nPage;                      /* Size of aPage[] in bytes */
   19769   int nCell;                      /* Number of cells on aPage[] */
   19770   int iCell;                      /* Current cell number */
   19771   int bOnePage;                   /* True to stop after one page */
   19772   int szDb;
   19773   sqlite3_int64 iRowid;
   19774 
   19775   /* Only for the sqlite_dbdata table */
   19776   DbdataBuffer rec;
   19777   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
   19778   sqlite3_int64 nHdr;             /* Size of header in bytes */
   19779   int iField;                     /* Current field number */
   19780   u8 *pHdrPtr;
   19781   u8 *pPtr;
   19782   u32 enc;                        /* Text encoding */
   19783 
   19784   sqlite3_int64 iIntkey;          /* Integer key value */
   19785 };
   19786 
   19787 /* Table object */
   19788 struct DbdataTable {
   19789   sqlite3_vtab base;              /* Base class.  Must be first */
   19790   sqlite3 *db;                    /* The database connection */
   19791   sqlite3_stmt *pStmt;            /* For fetching database pages */
   19792   int bPtr;                       /* True for sqlite3_dbptr table */
   19793 };
   19794 
   19795 /* Column and schema definitions for sqlite_dbdata */
   19796 #define DBDATA_COLUMN_PGNO        0
   19797 #define DBDATA_COLUMN_CELL        1
   19798 #define DBDATA_COLUMN_FIELD       2
   19799 #define DBDATA_COLUMN_VALUE       3
   19800 #define DBDATA_COLUMN_SCHEMA      4
   19801 #define DBDATA_SCHEMA             \
   19802       "CREATE TABLE x("           \
   19803       "  pgno INTEGER,"           \
   19804       "  cell INTEGER,"           \
   19805       "  field INTEGER,"          \
   19806       "  value ANY,"              \
   19807       "  schema TEXT HIDDEN"      \
   19808       ")"
   19809 
   19810 /* Column and schema definitions for sqlite_dbptr */
   19811 #define DBPTR_COLUMN_PGNO         0
   19812 #define DBPTR_COLUMN_CHILD        1
   19813 #define DBPTR_COLUMN_SCHEMA       2
   19814 #define DBPTR_SCHEMA              \
   19815       "CREATE TABLE x("           \
   19816       "  pgno INTEGER,"           \
   19817       "  child INTEGER,"          \
   19818       "  schema TEXT HIDDEN"      \
   19819       ")"
   19820 
   19821 /*
   19822 ** Ensure the buffer passed as the first argument is at least nMin bytes
   19823 ** in size. If an error occurs while attempting to resize the buffer,
   19824 ** SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   19825 */
   19826 static int dbdataBufferSize(DbdataBuffer *pBuf, sqlite3_int64 nMin){
   19827   if( nMin>pBuf->nBuf ){
   19828     sqlite3_int64 nNew = nMin+16384;
   19829     u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew);
   19830 
   19831     if( aNew==0 ) return SQLITE_NOMEM;
   19832     pBuf->aBuf = aNew;
   19833     pBuf->nBuf = nNew;
   19834   }
   19835   return SQLITE_OK;
   19836 }
   19837 
   19838 /*
   19839 ** Release the allocation managed by buffer pBuf.
   19840 */
   19841 static void dbdataBufferFree(DbdataBuffer *pBuf){
   19842   sqlite3_free(pBuf->aBuf);
   19843   memset(pBuf, 0, sizeof(*pBuf));
   19844 }
   19845 
   19846 /*
   19847 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
   19848 ** table.
   19849 */
   19850 static int dbdataConnect(
   19851   sqlite3 *db,
   19852   void *pAux,
   19853   int argc, const char *const*argv,
   19854   sqlite3_vtab **ppVtab,
   19855   char **pzErr
   19856 ){
   19857   DbdataTable *pTab = 0;
   19858   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
   19859 
   19860   (void)argc;
   19861   (void)argv;
   19862   (void)pzErr;
   19863   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
   19864   if( rc==SQLITE_OK ){
   19865     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
   19866     if( pTab==0 ){
   19867       rc = SQLITE_NOMEM;
   19868     }else{
   19869       memset(pTab, 0, sizeof(DbdataTable));
   19870       pTab->db = db;
   19871       pTab->bPtr = (pAux!=0);
   19872     }
   19873   }
   19874 
   19875   *ppVtab = (sqlite3_vtab*)pTab;
   19876   return rc;
   19877 }
   19878 
   19879 /*
   19880 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
   19881 */
   19882 static int dbdataDisconnect(sqlite3_vtab *pVtab){
   19883   DbdataTable *pTab = (DbdataTable*)pVtab;
   19884   if( pTab ){
   19885     sqlite3_finalize(pTab->pStmt);
   19886     sqlite3_free(pVtab);
   19887   }
   19888   return SQLITE_OK;
   19889 }
   19890 
   19891 /*
   19892 ** This function interprets two types of constraints:
   19893 **
   19894 **       schema=?
   19895 **       pgno=?
   19896 **
   19897 ** If neither are present, idxNum is set to 0. If schema=? is present,
   19898 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
   19899 ** in idxNum is set.
   19900 **
   19901 ** If both parameters are present, schema is in position 0 and pgno in
   19902 ** position 1.
   19903 */
   19904 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
   19905   DbdataTable *pTab = (DbdataTable*)tab;
   19906   int i;
   19907   int iSchema = -1;
   19908   int iPgno = -1;
   19909   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
   19910 
   19911   for(i=0; i<pIdx->nConstraint; i++){
   19912     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
   19913     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   19914       if( p->iColumn==colSchema ){
   19915         if( p->usable==0 ) return SQLITE_CONSTRAINT;
   19916         iSchema = i;
   19917       }
   19918       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
   19919         iPgno = i;
   19920       }
   19921     }
   19922   }
   19923 
   19924   if( iSchema>=0 ){
   19925     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
   19926     pIdx->aConstraintUsage[iSchema].omit = 1;
   19927   }
   19928   if( iPgno>=0 ){
   19929     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
   19930     pIdx->aConstraintUsage[iPgno].omit = 1;
   19931     pIdx->estimatedCost = 100;
   19932     pIdx->estimatedRows =  50;
   19933 
   19934     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
   19935       int iCol = pIdx->aOrderBy[0].iColumn;
   19936       if( pIdx->nOrderBy==1 ){
   19937         pIdx->orderByConsumed = (iCol==0 || iCol==1);
   19938       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
   19939         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
   19940       }
   19941     }
   19942 
   19943   }else{
   19944     pIdx->estimatedCost = 100000000;
   19945     pIdx->estimatedRows = 1000000000;
   19946   }
   19947   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
   19948   return SQLITE_OK;
   19949 }
   19950 
   19951 /*
   19952 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
   19953 */
   19954 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   19955   DbdataCursor *pCsr;
   19956 
   19957   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
   19958   if( pCsr==0 ){
   19959     return SQLITE_NOMEM;
   19960   }else{
   19961     memset(pCsr, 0, sizeof(DbdataCursor));
   19962     pCsr->base.pVtab = pVTab;
   19963   }
   19964 
   19965   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   19966   return SQLITE_OK;
   19967 }
   19968 
   19969 /*
   19970 ** Restore a cursor object to the state it was in when first allocated
   19971 ** by dbdataOpen().
   19972 */
   19973 static void dbdataResetCursor(DbdataCursor *pCsr){
   19974   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
   19975   if( pTab->pStmt==0 ){
   19976     pTab->pStmt = pCsr->pStmt;
   19977   }else{
   19978     sqlite3_finalize(pCsr->pStmt);
   19979   }
   19980   pCsr->pStmt = 0;
   19981   pCsr->iPgno = 1;
   19982   pCsr->iCell = 0;
   19983   pCsr->iField = 0;
   19984   pCsr->bOnePage = 0;
   19985   sqlite3_free(pCsr->aPage);
   19986   dbdataBufferFree(&pCsr->rec);
   19987   pCsr->aPage = 0;
   19988   pCsr->nRec = 0;
   19989 }
   19990 
   19991 /*
   19992 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
   19993 */
   19994 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
   19995   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
   19996   dbdataResetCursor(pCsr);
   19997   sqlite3_free(pCsr);
   19998   return SQLITE_OK;
   19999 }
   20000 
   20001 /*
   20002 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
   20003 */
   20004 static u32 get_uint16(unsigned char *a){
   20005   return (a[0]<<8)|a[1];
   20006 }
   20007 static u32 get_uint32(unsigned char *a){
   20008   return ((u32)a[0]<<24)
   20009        | ((u32)a[1]<<16)
   20010        | ((u32)a[2]<<8)
   20011        | ((u32)a[3]);
   20012 }
   20013 
   20014 /*
   20015 ** Load page pgno from the database via the sqlite_dbpage virtual table.
   20016 ** If successful, set (*ppPage) to point to a buffer containing the page
   20017 ** data, (*pnPage) to the size of that buffer in bytes and return
   20018 ** SQLITE_OK. In this case it is the responsibility of the caller to
   20019 ** eventually free the buffer using sqlite3_free().
   20020 **
   20021 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
   20022 ** return an SQLite error code.
   20023 */
   20024 static int dbdataLoadPage(
   20025   DbdataCursor *pCsr,             /* Cursor object */
   20026   u32 pgno,                       /* Page number of page to load */
   20027   u8 **ppPage,                    /* OUT: pointer to page buffer */
   20028   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
   20029 ){
   20030   int rc2;
   20031   int rc = SQLITE_OK;
   20032   sqlite3_stmt *pStmt = pCsr->pStmt;
   20033 
   20034   *ppPage = 0;
   20035   *pnPage = 0;
   20036   if( pgno>0 ){
   20037     sqlite3_bind_int64(pStmt, 2, pgno);
   20038     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   20039       int nCopy = sqlite3_column_bytes(pStmt, 0);
   20040       if( nCopy>0 ){
   20041         u8 *pPage;
   20042         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
   20043         if( pPage==0 ){
   20044           rc = SQLITE_NOMEM;
   20045         }else{
   20046           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
   20047           memcpy(pPage, pCopy, nCopy);
   20048           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
   20049         }
   20050         *ppPage = pPage;
   20051         *pnPage = nCopy;
   20052       }
   20053     }
   20054     rc2 = sqlite3_reset(pStmt);
   20055     if( rc==SQLITE_OK ) rc = rc2;
   20056   }
   20057 
   20058   return rc;
   20059 }
   20060 
   20061 /*
   20062 ** Read a varint.  Put the value in *pVal and return the number of bytes.
   20063 */
   20064 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
   20065   sqlite3_uint64 u = 0;
   20066   int i;
   20067   for(i=0; i<8; i++){
   20068     u = (u<<7) + (z[i]&0x7f);
   20069     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
   20070   }
   20071   u = (u<<8) + (z[i]&0xff);
   20072   *pVal = (sqlite3_int64)u;
   20073   return 9;
   20074 }
   20075 
   20076 /*
   20077 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
   20078 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
   20079 ** SQLite database except for key values in intkey tables.
   20080 */
   20081 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
   20082   sqlite3_int64 val;
   20083   int nRet = dbdataGetVarint(z, &val);
   20084   if( val<0 || val>0xFFFFFFFF ) val = 0;
   20085   *pVal = val;
   20086   return nRet;
   20087 }
   20088 
   20089 /*
   20090 ** Return the number of bytes of space used by an SQLite value of type
   20091 ** eType.
   20092 */
   20093 static int dbdataValueBytes(int eType){
   20094   switch( eType ){
   20095     case 0: case 8: case 9:
   20096     case 10: case 11:
   20097       return 0;
   20098     case 1:
   20099       return 1;
   20100     case 2:
   20101       return 2;
   20102     case 3:
   20103       return 3;
   20104     case 4:
   20105       return 4;
   20106     case 5:
   20107       return 6;
   20108     case 6:
   20109     case 7:
   20110       return 8;
   20111     default:
   20112       if( eType>0 ){
   20113         return ((eType-12) / 2);
   20114       }
   20115       return 0;
   20116   }
   20117 }
   20118 
   20119 /*
   20120 ** Load a value of type eType from buffer pData and use it to set the
   20121 ** result of context object pCtx.
   20122 */
   20123 static void dbdataValue(
   20124   sqlite3_context *pCtx,
   20125   u32 enc,
   20126   int eType,
   20127   u8 *pData,
   20128   sqlite3_int64 nData
   20129 ){
   20130   if( eType>=0 ){
   20131     if( dbdataValueBytes(eType)<=nData ){
   20132       switch( eType ){
   20133         case 0:
   20134         case 10:
   20135         case 11:
   20136           sqlite3_result_null(pCtx);
   20137           break;
   20138 
   20139         case 8:
   20140           sqlite3_result_int(pCtx, 0);
   20141           break;
   20142         case 9:
   20143           sqlite3_result_int(pCtx, 1);
   20144           break;
   20145 
   20146         case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
   20147           sqlite3_uint64 v = (signed char)pData[0];
   20148           pData++;
   20149           switch( eType ){
   20150             case 7:
   20151             case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
   20152             case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
   20153             case 4:  v = (v<<8) + pData[0];  pData++;
   20154             case 3:  v = (v<<8) + pData[0];  pData++;
   20155             case 2:  v = (v<<8) + pData[0];  pData++;
   20156           }
   20157 
   20158           if( eType==7 ){
   20159             double r;
   20160             memcpy(&r, &v, sizeof(r));
   20161             sqlite3_result_double(pCtx, r);
   20162           }else{
   20163             sqlite3_result_int64(pCtx, (sqlite3_int64)v);
   20164           }
   20165           break;
   20166         }
   20167 
   20168         default: {
   20169           int n = ((eType-12) / 2);
   20170           if( eType % 2 ){
   20171             switch( enc ){
   20172   #ifndef SQLITE_OMIT_UTF16
   20173               case SQLITE_UTF16BE:
   20174                 sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
   20175                 break;
   20176               case SQLITE_UTF16LE:
   20177                 sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
   20178                 break;
   20179   #endif
   20180               default:
   20181                 sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
   20182                 break;
   20183             }
   20184           }else{
   20185             sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
   20186           }
   20187         }
   20188       }
   20189     }else{
   20190       if( eType==7 ){
   20191         sqlite3_result_double(pCtx, 0.0);
   20192       }else if( eType<7 ){
   20193         sqlite3_result_int(pCtx, 0);
   20194       }else if( eType%2 ){
   20195         sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   20196       }else{
   20197         sqlite3_result_blob(pCtx, "", 0, SQLITE_STATIC);
   20198       }
   20199     }
   20200   }
   20201 }
   20202 
   20203 /* This macro is a copy of the MX_CELL() macro in the SQLite core. Given
   20204 ** a page-size, it returns the maximum number of cells that may be present
   20205 ** on the page.  */
   20206 #define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6)
   20207 
   20208 /* Maximum number of fields that may appear in a single record. This is
   20209 ** the "hard-limit", according to comments in sqliteLimit.h. */
   20210 #define DBDATA_MX_FIELD 32676
   20211 
   20212 /*
   20213 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
   20214 */
   20215 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
   20216   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
   20217   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
   20218 
   20219   pCsr->iRowid++;
   20220   while( 1 ){
   20221     int rc;
   20222     int iOff = (pCsr->iPgno==1 ? 100 : 0);
   20223     int bNextPage = 0;
   20224 
   20225     if( pCsr->aPage==0 ){
   20226       while( 1 ){
   20227         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
   20228         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
   20229         if( rc!=SQLITE_OK ) return rc;
   20230         if( pCsr->aPage && pCsr->nPage>=256 ) break;
   20231         sqlite3_free(pCsr->aPage);
   20232         pCsr->aPage = 0;
   20233         if( pCsr->bOnePage ) return SQLITE_OK;
   20234         pCsr->iPgno++;
   20235       }
   20236 
   20237       assert( iOff+3+2<=pCsr->nPage );
   20238       pCsr->iCell = pTab->bPtr ? -2 : 0;
   20239       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
   20240       if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){
   20241         pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage);
   20242       }
   20243     }
   20244 
   20245     if( pTab->bPtr ){
   20246       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
   20247         pCsr->iCell = pCsr->nCell;
   20248       }
   20249       pCsr->iCell++;
   20250       if( pCsr->iCell>=pCsr->nCell ){
   20251         sqlite3_free(pCsr->aPage);
   20252         pCsr->aPage = 0;
   20253         if( pCsr->bOnePage ) return SQLITE_OK;
   20254         pCsr->iPgno++;
   20255       }else{
   20256         return SQLITE_OK;
   20257       }
   20258     }else{
   20259       /* If there is no record loaded, load it now. */
   20260       assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 );
   20261       if( pCsr->nRec==0 ){
   20262         int bHasRowid = 0;
   20263         int nPointer = 0;
   20264         sqlite3_int64 nPayload = 0;
   20265         sqlite3_int64 nHdr = 0;
   20266         int iHdr;
   20267         int U, X;
   20268         int nLocal;
   20269 
   20270         switch( pCsr->aPage[iOff] ){
   20271           case 0x02:
   20272             nPointer = 4;
   20273             break;
   20274           case 0x0a:
   20275             break;
   20276           case 0x0d:
   20277             bHasRowid = 1;
   20278             break;
   20279           default:
   20280             /* This is not a b-tree page with records on it. Continue. */
   20281             pCsr->iCell = pCsr->nCell;
   20282             break;
   20283         }
   20284 
   20285         if( pCsr->iCell>=pCsr->nCell ){
   20286           bNextPage = 1;
   20287         }else{
   20288           int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2;
   20289 
   20290           if( iCellPtr>pCsr->nPage ){
   20291             bNextPage = 1;
   20292           }else{
   20293             iOff = get_uint16(&pCsr->aPage[iCellPtr]);
   20294           }
   20295 
   20296           /* For an interior node cell, skip past the child-page number */
   20297           iOff += nPointer;
   20298 
   20299           /* Load the "byte of payload including overflow" field */
   20300           if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){
   20301             bNextPage = 1;
   20302           }else{
   20303             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
   20304             if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
   20305             if( nPayload==0 ) nPayload = 1;
   20306           }
   20307 
   20308           /* If this is a leaf intkey cell, load the rowid */
   20309           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
   20310             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
   20311           }
   20312 
   20313           /* Figure out how much data to read from the local page */
   20314           U = pCsr->nPage;
   20315           if( bHasRowid ){
   20316             X = U-35;
   20317           }else{
   20318             X = ((U-12)*64/255)-23;
   20319           }
   20320           if( nPayload<=X ){
   20321             nLocal = nPayload;
   20322           }else{
   20323             int M, K;
   20324             M = ((U-12)*32/255)-23;
   20325             K = M+((nPayload-M)%(U-4));
   20326             if( K<=X ){
   20327               nLocal = K;
   20328             }else{
   20329               nLocal = M;
   20330             }
   20331           }
   20332 
   20333           if( bNextPage || nLocal+iOff>pCsr->nPage ){
   20334             bNextPage = 1;
   20335           }else{
   20336 
   20337             /* Allocate space for payload. And a bit more to catch small buffer
   20338             ** overruns caused by attempting to read a varint or similar from
   20339             ** near the end of a corrupt record.  */
   20340             rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES);
   20341             if( rc!=SQLITE_OK ) return rc;
   20342             assert( pCsr->rec.aBuf!=0 );
   20343             assert( nPayload!=0 );
   20344 
   20345             /* Load the nLocal bytes of payload */
   20346             memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal);
   20347             iOff += nLocal;
   20348 
   20349             /* Load content from overflow pages */
   20350             if( nPayload>nLocal ){
   20351               sqlite3_int64 nRem = nPayload - nLocal;
   20352               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
   20353               while( nRem>0 ){
   20354                 u8 *aOvfl = 0;
   20355                 int nOvfl = 0;
   20356                 int nCopy;
   20357                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
   20358                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
   20359                 if( rc!=SQLITE_OK ) return rc;
   20360                 if( aOvfl==0 ) break;
   20361 
   20362                 nCopy = U-4;
   20363                 if( nCopy>nRem ) nCopy = nRem;
   20364                 memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy);
   20365                 nRem -= nCopy;
   20366 
   20367                 pgnoOvfl = get_uint32(aOvfl);
   20368                 sqlite3_free(aOvfl);
   20369               }
   20370               nPayload -= nRem;
   20371             }
   20372             memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES);
   20373             pCsr->nRec = nPayload;
   20374 
   20375             iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr);
   20376             if( nHdr>nPayload ) nHdr = 0;
   20377             pCsr->nHdr = nHdr;
   20378             pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr];
   20379             pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr];
   20380             pCsr->iField = (bHasRowid ? -1 : 0);
   20381           }
   20382         }
   20383       }else{
   20384         pCsr->iField++;
   20385         if( pCsr->iField>0 ){
   20386           sqlite3_int64 iType;
   20387           if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec]
   20388            || pCsr->iField>=DBDATA_MX_FIELD
   20389           ){
   20390             bNextPage = 1;
   20391           }else{
   20392             int szField = 0;
   20393             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
   20394             szField = dbdataValueBytes(iType);
   20395             if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){
   20396               pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec];
   20397             }else{
   20398               pCsr->pPtr += szField;
   20399             }
   20400           }
   20401         }
   20402       }
   20403 
   20404       if( bNextPage ){
   20405         sqlite3_free(pCsr->aPage);
   20406         pCsr->aPage = 0;
   20407         pCsr->nRec = 0;
   20408         if( pCsr->bOnePage ) return SQLITE_OK;
   20409         pCsr->iPgno++;
   20410       }else{
   20411         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){
   20412           return SQLITE_OK;
   20413         }
   20414 
   20415         /* Advance to the next cell. The next iteration of the loop will load
   20416         ** the record and so on. */
   20417         pCsr->nRec = 0;
   20418         pCsr->iCell++;
   20419       }
   20420     }
   20421   }
   20422 
   20423   assert( !"can't get here" );
   20424   return SQLITE_OK;
   20425 }
   20426 
   20427 /*
   20428 ** Return true if the cursor is at EOF.
   20429 */
   20430 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
   20431   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
   20432   return pCsr->aPage==0;
   20433 }
   20434 
   20435 /*
   20436 ** Return true if nul-terminated string zSchema ends in "()". Or false
   20437 ** otherwise.
   20438 */
   20439 static int dbdataIsFunction(const char *zSchema){
   20440   size_t n = strlen(zSchema);
   20441   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
   20442     return (int)n-2;
   20443   }
   20444   return 0;
   20445 }
   20446 
   20447 /*
   20448 ** Determine the size in pages of database zSchema (where zSchema is
   20449 ** "main", "temp" or the name of an attached database) and set
   20450 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
   20451 ** an SQLite error code.
   20452 */
   20453 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
   20454   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
   20455   char *zSql = 0;
   20456   int rc, rc2;
   20457   int nFunc = 0;
   20458   sqlite3_stmt *pStmt = 0;
   20459 
   20460   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
   20461     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
   20462   }else{
   20463     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
   20464   }
   20465   if( zSql==0 ) return SQLITE_NOMEM;
   20466 
   20467   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
   20468   sqlite3_free(zSql);
   20469   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   20470     pCsr->szDb = sqlite3_column_int(pStmt, 0);
   20471   }
   20472   rc2 = sqlite3_finalize(pStmt);
   20473   if( rc==SQLITE_OK ) rc = rc2;
   20474   return rc;
   20475 }
   20476 
   20477 /*
   20478 ** Attempt to figure out the encoding of the database by retrieving page 1
   20479 ** and inspecting the header field. If successful, set the pCsr->enc variable
   20480 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
   20481 */
   20482 static int dbdataGetEncoding(DbdataCursor *pCsr){
   20483   int rc = SQLITE_OK;
   20484   int nPg1 = 0;
   20485   u8 *aPg1 = 0;
   20486   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
   20487   if( rc==SQLITE_OK && nPg1>=(56+4) ){
   20488     pCsr->enc = get_uint32(&aPg1[56]);
   20489   }
   20490   sqlite3_free(aPg1);
   20491   return rc;
   20492 }
   20493 
   20494 
   20495 /*
   20496 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
   20497 */
   20498 static int dbdataFilter(
   20499   sqlite3_vtab_cursor *pCursor,
   20500   int idxNum, const char *idxStr,
   20501   int argc, sqlite3_value **argv
   20502 ){
   20503   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
   20504   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
   20505   int rc = SQLITE_OK;
   20506   const char *zSchema = "main";
   20507   (void)idxStr;
   20508   (void)argc;
   20509 
   20510   dbdataResetCursor(pCsr);
   20511   assert( pCsr->iPgno==1 );
   20512   if( idxNum & 0x01 ){
   20513     zSchema = (const char*)sqlite3_value_text(argv[0]);
   20514     if( zSchema==0 ) zSchema = "";
   20515   }
   20516   if( idxNum & 0x02 ){
   20517     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
   20518     pCsr->bOnePage = 1;
   20519   }else{
   20520     rc = dbdataDbsize(pCsr, zSchema);
   20521   }
   20522 
   20523   if( rc==SQLITE_OK ){
   20524     int nFunc = 0;
   20525     if( pTab->pStmt ){
   20526       pCsr->pStmt = pTab->pStmt;
   20527       pTab->pStmt = 0;
   20528     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
   20529       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
   20530       if( zSql==0 ){
   20531         rc = SQLITE_NOMEM;
   20532       }else{
   20533         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
   20534         sqlite3_free(zSql);
   20535       }
   20536     }else{
   20537       rc = sqlite3_prepare_v2(pTab->db,
   20538           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
   20539           &pCsr->pStmt, 0
   20540       );
   20541     }
   20542   }
   20543   if( rc==SQLITE_OK ){
   20544     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
   20545   }
   20546 
   20547   /* Try to determine the encoding of the db by inspecting the header
   20548   ** field on page 1. */
   20549   if( rc==SQLITE_OK ){
   20550     rc = dbdataGetEncoding(pCsr);
   20551   }
   20552 
   20553   if( rc!=SQLITE_OK ){
   20554     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
   20555   }
   20556 
   20557   if( rc==SQLITE_OK ){
   20558     rc = dbdataNext(pCursor);
   20559   }
   20560   return rc;
   20561 }
   20562 
   20563 /*
   20564 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
   20565 */
   20566 static int dbdataColumn(
   20567   sqlite3_vtab_cursor *pCursor,
   20568   sqlite3_context *ctx,
   20569   int i
   20570 ){
   20571   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
   20572   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
   20573   if( pTab->bPtr ){
   20574     switch( i ){
   20575       case DBPTR_COLUMN_PGNO:
   20576         sqlite3_result_int64(ctx, pCsr->iPgno);
   20577         break;
   20578       case DBPTR_COLUMN_CHILD: {
   20579         int iOff = pCsr->iPgno==1 ? 100 : 0;
   20580         if( pCsr->iCell<0 ){
   20581           iOff += 8;
   20582         }else{
   20583           iOff += 12 + pCsr->iCell*2;
   20584           if( iOff>pCsr->nPage ) return SQLITE_OK;
   20585           iOff = get_uint16(&pCsr->aPage[iOff]);
   20586         }
   20587         if( iOff<=pCsr->nPage ){
   20588           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
   20589         }
   20590         break;
   20591       }
   20592     }
   20593   }else{
   20594     switch( i ){
   20595       case DBDATA_COLUMN_PGNO:
   20596         sqlite3_result_int64(ctx, pCsr->iPgno);
   20597         break;
   20598       case DBDATA_COLUMN_CELL:
   20599         sqlite3_result_int(ctx, pCsr->iCell);
   20600         break;
   20601       case DBDATA_COLUMN_FIELD:
   20602         sqlite3_result_int(ctx, pCsr->iField);
   20603         break;
   20604       case DBDATA_COLUMN_VALUE: {
   20605         if( pCsr->iField<0 ){
   20606           sqlite3_result_int64(ctx, pCsr->iIntkey);
   20607         }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){
   20608           sqlite3_int64 iType;
   20609           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
   20610           dbdataValue(
   20611               ctx, pCsr->enc, iType, pCsr->pPtr,
   20612               &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr
   20613           );
   20614         }
   20615         break;
   20616       }
   20617     }
   20618   }
   20619   return SQLITE_OK;
   20620 }
   20621 
   20622 /*
   20623 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
   20624 */
   20625 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   20626   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
   20627   *pRowid = pCsr->iRowid;
   20628   return SQLITE_OK;
   20629 }
   20630 
   20631 
   20632 /*
   20633 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
   20634 */
   20635 static int sqlite3DbdataRegister(sqlite3 *db){
   20636   static sqlite3_module dbdata_module = {
   20637     0,                            /* iVersion */
   20638     0,                            /* xCreate */
   20639     dbdataConnect,                /* xConnect */
   20640     dbdataBestIndex,              /* xBestIndex */
   20641     dbdataDisconnect,             /* xDisconnect */
   20642     0,                            /* xDestroy */
   20643     dbdataOpen,                   /* xOpen - open a cursor */
   20644     dbdataClose,                  /* xClose - close a cursor */
   20645     dbdataFilter,                 /* xFilter - configure scan constraints */
   20646     dbdataNext,                   /* xNext - advance a cursor */
   20647     dbdataEof,                    /* xEof - check for end of scan */
   20648     dbdataColumn,                 /* xColumn - read data */
   20649     dbdataRowid,                  /* xRowid - read data */
   20650     0,                            /* xUpdate */
   20651     0,                            /* xBegin */
   20652     0,                            /* xSync */
   20653     0,                            /* xCommit */
   20654     0,                            /* xRollback */
   20655     0,                            /* xFindMethod */
   20656     0,                            /* xRename */
   20657     0,                            /* xSavepoint */
   20658     0,                            /* xRelease */
   20659     0,                            /* xRollbackTo */
   20660     0,                            /* xShadowName */
   20661     0                             /* xIntegrity */
   20662   };
   20663 
   20664   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
   20665   if( rc==SQLITE_OK ){
   20666     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
   20667   }
   20668   return rc;
   20669 }
   20670 
   20671 #ifdef _WIN32
   20672 
   20673 #endif
   20674 int sqlite3_dbdata_init(
   20675   sqlite3 *db,
   20676   char **pzErrMsg,
   20677   const sqlite3_api_routines *pApi
   20678 ){
   20679   (void)pzErrMsg;
   20680   return sqlite3DbdataRegister(db);
   20681 }
   20682 
   20683 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
   20684 
   20685 /************************* End ext/recover/dbdata.c ********************/
   20686 /************************* Begin ext/recover/sqlite3recover.c ******************/
   20687 /*
   20688 ** 2022-08-27
   20689 **
   20690 ** The author disclaims copyright to this source code.  In place of
   20691 ** a legal notice, here is a blessing:
   20692 **
   20693 **    May you do good and not evil.
   20694 **    May you find forgiveness for yourself and forgive others.
   20695 **    May you share freely, never taking more than you give.
   20696 **
   20697 *************************************************************************
   20698 **
   20699 */
   20700 
   20701 
   20702 /* #include "sqlite3recover.h" */
   20703 #include <assert.h>
   20704 #include <string.h>
   20705 
   20706 #ifndef SQLITE_OMIT_VIRTUALTABLE
   20707 
   20708 /*
   20709 ** Declaration for public API function in file dbdata.c. This may be called
   20710 ** with NULL as the final two arguments to register the sqlite_dbptr and
   20711 ** sqlite_dbdata virtual tables with a database handle.
   20712 */
   20713 #ifdef _WIN32
   20714 
   20715 #endif
   20716 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
   20717 
   20718 /* typedef unsigned int u32; */
   20719 /* typedef unsigned char u8; */
   20720 /* typedef sqlite3_int64 i64; */
   20721 
   20722 /*
   20723 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
   20724 ** to avoid complaints from -fsanitize=strict-bounds.
   20725 */
   20726 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
   20727 # define FLEXARRAY
   20728 #else
   20729 # define FLEXARRAY 1
   20730 #endif
   20731 
   20732 typedef struct RecoverTable RecoverTable;
   20733 typedef struct RecoverColumn RecoverColumn;
   20734 
   20735 /*
   20736 ** When recovering rows of data that can be associated with table
   20737 ** definitions recovered from the sqlite_schema table, each table is
   20738 ** represented by an instance of the following object.
   20739 **
   20740 ** iRoot:
   20741 **   The root page in the original database. Not necessarily (and usually
   20742 **   not) the same in the recovered database.
   20743 **
   20744 ** zTab:
   20745 **   Name of the table.
   20746 **
   20747 ** nCol/aCol[]:
   20748 **   aCol[] is an array of nCol columns. In the order in which they appear
   20749 **   in the table.
   20750 **
   20751 ** bIntkey:
   20752 **   Set to true for intkey tables, false for WITHOUT ROWID.
   20753 **
   20754 ** iRowidBind:
   20755 **   Each column in the aCol[] array has associated with it the index of
   20756 **   the bind parameter its values will be bound to in the INSERT statement
   20757 **   used to construct the output database. If the table does has a rowid
   20758 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
   20759 **   index of the bind paramater to which the rowid value should be bound.
   20760 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
   20761 **   KEY column, then the rowid value should be bound to the index associated
   20762 **   with the column.
   20763 **
   20764 ** pNext:
   20765 **   All RecoverTable objects used by the recovery operation are allocated
   20766 **   and populated as part of creating the recovered database schema in
   20767 **   the output database, before any non-schema data are recovered. They
   20768 **   are then stored in a singly-linked list linked by this variable beginning
   20769 **   at sqlite3_recover.pTblList.
   20770 */
   20771 struct RecoverTable {
   20772   u32 iRoot;                      /* Root page in original database */
   20773   char *zTab;                     /* Name of table */
   20774   int nCol;                       /* Number of columns in table */
   20775   RecoverColumn *aCol;            /* Array of columns */
   20776   int bIntkey;                    /* True for intkey, false for without rowid */
   20777   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
   20778   RecoverTable *pNext;
   20779 };
   20780 
   20781 /*
   20782 ** Each database column is represented by an instance of the following object
   20783 ** stored in the RecoverTable.aCol[] array of the associated table.
   20784 **
   20785 ** iField:
   20786 **   The index of the associated field within database records. Or -1 if
   20787 **   there is no associated field (e.g. for virtual generated columns).
   20788 **
   20789 ** iBind:
   20790 **   The bind index of the INSERT statement to bind this columns values
   20791 **   to. Or 0 if there is no such index (iff (iField<0)).
   20792 **
   20793 ** bIPK:
   20794 **   True if this is the INTEGER PRIMARY KEY column.
   20795 **
   20796 ** zCol:
   20797 **   Name of column.
   20798 **
   20799 ** eHidden:
   20800 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
   20801 */
   20802 struct RecoverColumn {
   20803   int iField;                     /* Field in record on disk */
   20804   int iBind;                      /* Binding to use in INSERT */
   20805   int bIPK;                       /* True for IPK column */
   20806   char *zCol;
   20807   int eHidden;
   20808 };
   20809 
   20810 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
   20811 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
   20812 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
   20813 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
   20814 
   20815 /*
   20816 ** Bitmap object used to track pages in the input database. Allocated
   20817 ** and manipulated only by the following functions:
   20818 **
   20819 **     recoverBitmapAlloc()
   20820 **     recoverBitmapFree()
   20821 **     recoverBitmapSet()
   20822 **     recoverBitmapQuery()
   20823 **
   20824 ** nPg:
   20825 **   Largest page number that may be stored in the bitmap. The range
   20826 **   of valid keys is 1 to nPg, inclusive.
   20827 **
   20828 ** aElem[]:
   20829 **   Array large enough to contain a bit for each key. For key value
   20830 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
   20831 **   In other words, the following is true if bit iKey is set, or
   20832 **   false if it is clear:
   20833 **
   20834 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
   20835 */
   20836 typedef struct RecoverBitmap RecoverBitmap;
   20837 struct RecoverBitmap {
   20838   i64 nPg;                        /* Size of bitmap */
   20839   u32 aElem[FLEXARRAY];           /* Array of 32-bit bitmasks */
   20840 };
   20841 
   20842 /* Size in bytes of a RecoverBitmap object sufficient to cover 32 pages */
   20843 #define SZ_RECOVERBITMAP_32  (16)
   20844 
   20845 /*
   20846 ** State variables (part of the sqlite3_recover structure) used while
   20847 ** recovering data for tables identified in the recovered schema (state
   20848 ** RECOVER_STATE_WRITING).
   20849 */
   20850 typedef struct RecoverStateW1 RecoverStateW1;
   20851 struct RecoverStateW1 {
   20852   sqlite3_stmt *pTbls;
   20853   sqlite3_stmt *pSel;
   20854   sqlite3_stmt *pInsert;
   20855   int nInsert;
   20856 
   20857   RecoverTable *pTab;             /* Table currently being written */
   20858   int nMax;                       /* Max column count in any schema table */
   20859   sqlite3_value **apVal;          /* Array of nMax values */
   20860   int nVal;                       /* Number of valid entries in apVal[] */
   20861   int bHaveRowid;
   20862   i64 iRowid;
   20863   i64 iPrevPage;
   20864   int iPrevCell;
   20865 };
   20866 
   20867 /*
   20868 ** State variables (part of the sqlite3_recover structure) used while
   20869 ** recovering data destined for the lost and found table (states
   20870 ** RECOVER_STATE_LOSTANDFOUND[123]).
   20871 */
   20872 typedef struct RecoverStateLAF RecoverStateLAF;
   20873 struct RecoverStateLAF {
   20874   RecoverBitmap *pUsed;
   20875   i64 nPg;                        /* Size of db in pages */
   20876   sqlite3_stmt *pAllAndParent;
   20877   sqlite3_stmt *pMapInsert;
   20878   sqlite3_stmt *pMaxField;
   20879   sqlite3_stmt *pUsedPages;
   20880   sqlite3_stmt *pFindRoot;
   20881   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
   20882   sqlite3_stmt *pAllPage;
   20883   sqlite3_stmt *pPageData;
   20884   sqlite3_value **apVal;
   20885   int nMaxField;
   20886 };
   20887 
   20888 /*
   20889 ** Main recover handle structure.
   20890 */
   20891 struct sqlite3_recover {
   20892   /* Copies of sqlite3_recover_init[_sql]() parameters */
   20893   sqlite3 *dbIn;                  /* Input database */
   20894   char *zDb;                      /* Name of input db ("main" etc.) */
   20895   char *zUri;                     /* URI for output database */
   20896   void *pSqlCtx;                  /* SQL callback context */
   20897   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
   20898 
   20899   /* Values configured by sqlite3_recover_config() */
   20900   char *zStateDb;                 /* State database to use (or NULL) */
   20901   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
   20902   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
   20903   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
   20904   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
   20905 
   20906   int pgsz;
   20907   int detected_pgsz;
   20908   int nReserve;
   20909   u8 *pPage1Disk;
   20910   u8 *pPage1Cache;
   20911 
   20912   /* Error code and error message */
   20913   int errCode;                    /* For sqlite3_recover_errcode() */
   20914   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
   20915 
   20916   int eState;
   20917   int bCloseTransaction;
   20918 
   20919   /* Variables used with eState==RECOVER_STATE_WRITING */
   20920   RecoverStateW1 w1;
   20921 
   20922   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
   20923   RecoverStateLAF laf;
   20924 
   20925   /* Fields used within sqlite3_recover_run() */
   20926   sqlite3 *dbOut;                 /* Output database */
   20927   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
   20928   RecoverTable *pTblList;         /* List of tables recovered from schema */
   20929 };
   20930 
   20931 /*
   20932 ** The various states in which an sqlite3_recover object may exist:
   20933 **
   20934 **   RECOVER_STATE_INIT:
   20935 **    The object is initially created in this state. sqlite3_recover_step()
   20936 **    has yet to be called. This is the only state in which it is permitted
   20937 **    to call sqlite3_recover_config().
   20938 **
   20939 **   RECOVER_STATE_WRITING:
   20940 **
   20941 **   RECOVER_STATE_LOSTANDFOUND1:
   20942 **    State to populate the bitmap of pages used by other tables or the
   20943 **    database freelist.
   20944 **
   20945 **   RECOVER_STATE_LOSTANDFOUND2:
   20946 **    Populate the recovery.map table - used to figure out a "root" page
   20947 **    for each lost page from in the database from which records are
   20948 **    extracted.
   20949 **
   20950 **   RECOVER_STATE_LOSTANDFOUND3:
   20951 **    Populate the lost-and-found table itself.
   20952 */
   20953 #define RECOVER_STATE_INIT           0
   20954 #define RECOVER_STATE_WRITING        1
   20955 #define RECOVER_STATE_LOSTANDFOUND1  2
   20956 #define RECOVER_STATE_LOSTANDFOUND2  3
   20957 #define RECOVER_STATE_LOSTANDFOUND3  4
   20958 #define RECOVER_STATE_SCHEMA2        5
   20959 #define RECOVER_STATE_DONE           6
   20960 
   20961 
   20962 /*
   20963 ** Global variables used by this extension.
   20964 */
   20965 typedef struct RecoverGlobal RecoverGlobal;
   20966 struct RecoverGlobal {
   20967   const sqlite3_io_methods *pMethods;
   20968   sqlite3_recover *p;
   20969 };
   20970 static RecoverGlobal recover_g;
   20971 
   20972 /*
   20973 ** Use this static SQLite mutex to protect the globals during the
   20974 ** first call to sqlite3_recover_step().
   20975 */
   20976 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
   20977 
   20978 
   20979 /*
   20980 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
   20981 */
   20982 #define RECOVER_ROWID_DEFAULT 1
   20983 
   20984 /*
   20985 ** Mutex handling:
   20986 **
   20987 **    recoverEnterMutex()       -   Enter the recovery mutex
   20988 **    recoverLeaveMutex()       -   Leave the recovery mutex
   20989 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
   20990 */
   20991 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
   20992 # define recoverEnterMutex()
   20993 # define recoverLeaveMutex()
   20994 #else
   20995 static void recoverEnterMutex(void){
   20996   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
   20997 }
   20998 static void recoverLeaveMutex(void){
   20999   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
   21000 }
   21001 #endif
   21002 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
   21003 static void recoverAssertMutexHeld(void){
   21004   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
   21005 }
   21006 #else
   21007 # define recoverAssertMutexHeld()
   21008 #endif
   21009 
   21010 
   21011 /*
   21012 ** Like strlen(). But handles NULL pointer arguments.
   21013 */
   21014 static int recoverStrlen(const char *zStr){
   21015   if( zStr==0 ) return 0;
   21016   return (int)(strlen(zStr)&0x7fffffff);
   21017 }
   21018 
   21019 /*
   21020 ** This function is a no-op if the recover handle passed as the first
   21021 ** argument already contains an error (if p->errCode!=SQLITE_OK).
   21022 **
   21023 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
   21024 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
   21025 ** if an OOM error occurs, NULL is returned and the handle error code
   21026 ** (p->errCode) set to SQLITE_NOMEM.
   21027 */
   21028 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
   21029   void *pRet = 0;
   21030   assert( nByte>0 );
   21031   if( p->errCode==SQLITE_OK ){
   21032     pRet = sqlite3_malloc64(nByte);
   21033     if( pRet ){
   21034       memset(pRet, 0, nByte);
   21035     }else{
   21036       p->errCode = SQLITE_NOMEM;
   21037     }
   21038   }
   21039   return pRet;
   21040 }
   21041 
   21042 /*
   21043 ** Set the error code and error message for the recover handle passed as
   21044 ** the first argument. The error code is set to the value of parameter
   21045 ** errCode.
   21046 **
   21047 ** Parameter zFmt must be a printf() style formatting string. The handle
   21048 ** error message is set to the result of using any trailing arguments for
   21049 ** parameter substitutions in the formatting string.
   21050 **
   21051 ** For example:
   21052 **
   21053 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
   21054 */
   21055 static int recoverError(
   21056   sqlite3_recover *p,
   21057   int errCode,
   21058   const char *zFmt, ...
   21059 ){
   21060   char *z = 0;
   21061   va_list ap;
   21062   va_start(ap, zFmt);
   21063   if( zFmt ){
   21064     z = sqlite3_vmprintf(zFmt, ap);
   21065   }
   21066   va_end(ap);
   21067   sqlite3_free(p->zErrMsg);
   21068   p->zErrMsg = z;
   21069   p->errCode = errCode;
   21070   return errCode;
   21071 }
   21072 
   21073 
   21074 /*
   21075 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
   21076 ** In this case it returns NULL.
   21077 **
   21078 ** Otherwise, an attempt is made to allocate and return a bitmap object
   21079 ** large enough to store a bit for all page numbers between 1 and nPg,
   21080 ** inclusive. The bitmap is initially zeroed.
   21081 */
   21082 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
   21083   int nElem = (nPg+1+31) / 32;
   21084   int nByte = SZ_RECOVERBITMAP_32 + nElem*sizeof(u32);
   21085   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
   21086 
   21087   if( pRet ){
   21088     pRet->nPg = nPg;
   21089   }
   21090   return pRet;
   21091 }
   21092 
   21093 /*
   21094 ** Free a bitmap object allocated by recoverBitmapAlloc().
   21095 */
   21096 static void recoverBitmapFree(RecoverBitmap *pMap){
   21097   sqlite3_free(pMap);
   21098 }
   21099 
   21100 /*
   21101 ** Set the bit associated with page iPg in bitvec pMap.
   21102 */
   21103 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
   21104   if( iPg<=pMap->nPg ){
   21105     int iElem = (iPg / 32);
   21106     int iBit = (iPg % 32);
   21107     pMap->aElem[iElem] |= (((u32)1) << iBit);
   21108   }
   21109 }
   21110 
   21111 /*
   21112 ** Query bitmap object pMap for the state of the bit associated with page
   21113 ** iPg. Return 1 if it is set, or 0 otherwise.
   21114 */
   21115 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
   21116   int ret = 1;
   21117   if( iPg<=pMap->nPg && iPg>0 ){
   21118     int iElem = (iPg / 32);
   21119     int iBit = (iPg % 32);
   21120     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
   21121   }
   21122   return ret;
   21123 }
   21124 
   21125 /*
   21126 ** Set the recover handle error to the error code and message returned by
   21127 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
   21128 ** handle db.
   21129 */
   21130 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
   21131   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
   21132 }
   21133 
   21134 /*
   21135 ** This function is a no-op if recover handle p already contains an error
   21136 ** (if p->errCode!=SQLITE_OK).
   21137 **
   21138 ** Otherwise, it attempts to prepare the SQL statement in zSql against
   21139 ** database handle db. If successful, the statement handle is returned.
   21140 ** Or, if an error occurs, NULL is returned and an error left in the
   21141 ** recover handle.
   21142 */
   21143 static sqlite3_stmt *recoverPrepare(
   21144   sqlite3_recover *p,
   21145   sqlite3 *db,
   21146   const char *zSql
   21147 ){
   21148   sqlite3_stmt *pStmt = 0;
   21149   if( p->errCode==SQLITE_OK ){
   21150     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
   21151       recoverDbError(p, db);
   21152     }
   21153   }
   21154   return pStmt;
   21155 }
   21156 
   21157 /*
   21158 ** This function is a no-op if recover handle p already contains an error
   21159 ** (if p->errCode!=SQLITE_OK).
   21160 **
   21161 ** Otherwise, argument zFmt is used as a printf() style format string,
   21162 ** along with any trailing arguments, to create an SQL statement. This
   21163 ** SQL statement is prepared against database handle db and, if successful,
   21164 ** the statment handle returned. Or, if an error occurs - either during
   21165 ** the printf() formatting or when preparing the resulting SQL - an
   21166 ** error code and message are left in the recover handle.
   21167 */
   21168 static sqlite3_stmt *recoverPreparePrintf(
   21169   sqlite3_recover *p,
   21170   sqlite3 *db,
   21171   const char *zFmt, ...
   21172 ){
   21173   sqlite3_stmt *pStmt = 0;
   21174   if( p->errCode==SQLITE_OK ){
   21175     va_list ap;
   21176     char *z;
   21177     va_start(ap, zFmt);
   21178     z = sqlite3_vmprintf(zFmt, ap);
   21179     va_end(ap);
   21180     if( z==0 ){
   21181       p->errCode = SQLITE_NOMEM;
   21182     }else{
   21183       pStmt = recoverPrepare(p, db, z);
   21184       sqlite3_free(z);
   21185     }
   21186   }
   21187   return pStmt;
   21188 }
   21189 
   21190 /*
   21191 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
   21192 ** indicates that an error occurred, and there is not already an error
   21193 ** in the recover handle passed as the first argument, set the error
   21194 ** code and error message appropriately.
   21195 **
   21196 ** This function returns a copy of the statement handle pointer passed
   21197 ** as the second argument.
   21198 */
   21199 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
   21200   int rc = sqlite3_reset(pStmt);
   21201   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
   21202     recoverDbError(p, sqlite3_db_handle(pStmt));
   21203   }
   21204   return pStmt;
   21205 }
   21206 
   21207 /*
   21208 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
   21209 ** indicates that an error occurred, and there is not already an error
   21210 ** in the recover handle passed as the first argument, set the error
   21211 ** code and error message appropriately.
   21212 */
   21213 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
   21214   sqlite3 *db = sqlite3_db_handle(pStmt);
   21215   int rc = sqlite3_finalize(pStmt);
   21216   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
   21217     recoverDbError(p, db);
   21218   }
   21219 }
   21220 
   21221 /*
   21222 ** This function is a no-op if recover handle p already contains an error
   21223 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
   21224 ** case.
   21225 **
   21226 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
   21227 ** Or, if an error occurs, leave an error code and message in the recover
   21228 ** handle and return a copy of the error code.
   21229 */
   21230 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
   21231   if( p->errCode==SQLITE_OK ){
   21232     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
   21233     if( rc ){
   21234       recoverDbError(p, db);
   21235     }
   21236   }
   21237   return p->errCode;
   21238 }
   21239 
   21240 /*
   21241 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
   21242 ** error in the recover handle passed as the first argument if an error
   21243 ** (e.g. an OOM) occurs.
   21244 */
   21245 static void recoverBindValue(
   21246   sqlite3_recover *p,
   21247   sqlite3_stmt *pStmt,
   21248   int iBind,
   21249   sqlite3_value *pVal
   21250 ){
   21251   if( p->errCode==SQLITE_OK ){
   21252     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
   21253     if( rc ) recoverError(p, rc, 0);
   21254   }
   21255 }
   21256 
   21257 /*
   21258 ** This function is a no-op if recover handle p already contains an error
   21259 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
   21260 **
   21261 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
   21262 ** formatting string and the result of using the trailing arguments for
   21263 ** parameter substitution with it written into a buffer obtained from
   21264 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
   21265 ** It is the responsibility of the caller to eventually free the buffer
   21266 ** using sqlite3_free().
   21267 **
   21268 ** Or, if an error occurs, an error code and message is left in the recover
   21269 ** handle and NULL returned.
   21270 */
   21271 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
   21272   va_list ap;
   21273   char *z;
   21274   va_start(ap, zFmt);
   21275   z = sqlite3_vmprintf(zFmt, ap);
   21276   va_end(ap);
   21277   if( p->errCode==SQLITE_OK ){
   21278     if( z==0 ) p->errCode = SQLITE_NOMEM;
   21279   }else{
   21280     sqlite3_free(z);
   21281     z = 0;
   21282   }
   21283   return z;
   21284 }
   21285 
   21286 /*
   21287 ** This function is a no-op if recover handle p already contains an error
   21288 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
   21289 **
   21290 ** Otherwise, execute "PRAGMA page_count" against the input database. If
   21291 ** successful, return the integer result. Or, if an error occurs, leave an
   21292 ** error code and error message in the sqlite3_recover handle and return
   21293 ** zero.
   21294 */
   21295 static i64 recoverPageCount(sqlite3_recover *p){
   21296   i64 nPg = 0;
   21297   if( p->errCode==SQLITE_OK ){
   21298     sqlite3_stmt *pStmt = 0;
   21299     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
   21300     if( pStmt ){
   21301       sqlite3_step(pStmt);
   21302       nPg = sqlite3_column_int64(pStmt, 0);
   21303     }
   21304     recoverFinalize(p, pStmt);
   21305   }
   21306   return nPg;
   21307 }
   21308 
   21309 /*
   21310 ** Implementation of SQL scalar function "read_i32". The first argument to
   21311 ** this function must be a blob. The second a non-negative integer. This
   21312 ** function reads and returns a 32-bit big-endian integer from byte
   21313 ** offset (4*<arg2>) of the blob.
   21314 **
   21315 **     SELECT read_i32(<blob>, <idx>)
   21316 */
   21317 static void recoverReadI32(
   21318   sqlite3_context *context,
   21319   int argc,
   21320   sqlite3_value **argv
   21321 ){
   21322   const unsigned char *pBlob;
   21323   int nBlob;
   21324   int iInt;
   21325 
   21326   assert( argc==2 );
   21327   nBlob = sqlite3_value_bytes(argv[0]);
   21328   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
   21329   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
   21330 
   21331   if( (iInt+1)*4<=nBlob ){
   21332     const unsigned char *a = &pBlob[iInt*4];
   21333     i64 iVal = ((i64)a[0]<<24)
   21334              + ((i64)a[1]<<16)
   21335              + ((i64)a[2]<< 8)
   21336              + ((i64)a[3]<< 0);
   21337     sqlite3_result_int64(context, iVal);
   21338   }
   21339 }
   21340 
   21341 /*
   21342 ** Implementation of SQL scalar function "page_is_used". This function
   21343 ** is used as part of the procedure for locating orphan rows for the
   21344 ** lost-and-found table, and it depends on those routines having populated
   21345 ** the sqlite3_recover.laf.pUsed variable.
   21346 **
   21347 ** The only argument to this function is a page-number. It returns true
   21348 ** if the page has already been used somehow during data recovery, or false
   21349 ** otherwise.
   21350 **
   21351 **     SELECT page_is_used(<pgno>);
   21352 */
   21353 static void recoverPageIsUsed(
   21354   sqlite3_context *pCtx,
   21355   int nArg,
   21356   sqlite3_value **apArg
   21357 ){
   21358   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
   21359   i64 pgno = sqlite3_value_int64(apArg[0]);
   21360   assert( nArg==1 );
   21361   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
   21362 }
   21363 
   21364 /*
   21365 ** The implementation of a user-defined SQL function invoked by the
   21366 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
   21367 ** of the database being recovered.
   21368 **
   21369 ** This function always takes a single integer argument. If the argument
   21370 ** is zero, then the value returned is the number of pages in the db being
   21371 ** recovered. If the argument is greater than zero, it is a page number.
   21372 ** The value returned in this case is an SQL blob containing the data for
   21373 ** the identified page of the db being recovered. e.g.
   21374 **
   21375 **     SELECT getpage(0);       -- return number of pages in db
   21376 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
   21377 */
   21378 static void recoverGetPage(
   21379   sqlite3_context *pCtx,
   21380   int nArg,
   21381   sqlite3_value **apArg
   21382 ){
   21383   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
   21384   i64 pgno = sqlite3_value_int64(apArg[0]);
   21385   sqlite3_stmt *pStmt = 0;
   21386 
   21387   assert( nArg==1 );
   21388   if( pgno==0 ){
   21389     i64 nPg = recoverPageCount(p);
   21390     sqlite3_result_int64(pCtx, nPg);
   21391     return;
   21392   }else{
   21393     if( p->pGetPage==0 ){
   21394       pStmt = p->pGetPage = recoverPreparePrintf(
   21395           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
   21396       );
   21397     }else if( p->errCode==SQLITE_OK ){
   21398       pStmt = p->pGetPage;
   21399     }
   21400 
   21401     if( pStmt ){
   21402       sqlite3_bind_int64(pStmt, 1, pgno);
   21403       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   21404         const u8 *aPg;
   21405         int nPg;
   21406         assert( p->errCode==SQLITE_OK );
   21407         aPg = sqlite3_column_blob(pStmt, 0);
   21408         nPg = sqlite3_column_bytes(pStmt, 0);
   21409         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
   21410           aPg = p->pPage1Disk;
   21411         }
   21412         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
   21413       }
   21414       recoverReset(p, pStmt);
   21415     }
   21416   }
   21417 
   21418   if( p->errCode ){
   21419     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
   21420     sqlite3_result_error_code(pCtx, p->errCode);
   21421   }
   21422 }
   21423 
   21424 /*
   21425 ** Find a string that is not found anywhere in z[].  Return a pointer
   21426 ** to that string.
   21427 **
   21428 ** Try to use zA and zB first.  If both of those are already found in z[]
   21429 ** then make up some string and store it in the buffer zBuf.
   21430 */
   21431 static const char *recoverUnusedString(
   21432   const char *z,                    /* Result must not appear anywhere in z */
   21433   const char *zA, const char *zB,   /* Try these first */
   21434   char *zBuf                        /* Space to store a generated string */
   21435 ){
   21436   unsigned i = 0;
   21437   if( strstr(z, zA)==0 ) return zA;
   21438   if( strstr(z, zB)==0 ) return zB;
   21439   do{
   21440     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
   21441   }while( strstr(z,zBuf)!=0 );
   21442   return zBuf;
   21443 }
   21444 
   21445 /*
   21446 ** Implementation of scalar SQL function "escape_crlf".  The argument passed to
   21447 ** this function is the output of built-in function quote(). If the first
   21448 ** character of the input is "'", indicating that the value passed to quote()
   21449 ** was a text value, then this function searches the input for "\n" and "\r"
   21450 ** characters and adds a wrapper similar to the following:
   21451 **
   21452 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
   21453 **
   21454 ** Or, if the first character of the input is not "'", then a copy of the input
   21455 ** is returned.
   21456 */
   21457 static void recoverEscapeCrlf(
   21458   sqlite3_context *context,
   21459   int argc,
   21460   sqlite3_value **argv
   21461 ){
   21462   const char *zText = (const char*)sqlite3_value_text(argv[0]);
   21463   (void)argc;
   21464   if( zText && zText[0]=='\'' ){
   21465     int nText = sqlite3_value_bytes(argv[0]);
   21466     int i;
   21467     char zBuf1[20];
   21468     char zBuf2[20];
   21469     const char *zNL = 0;
   21470     const char *zCR = 0;
   21471     int nCR = 0;
   21472     int nNL = 0;
   21473 
   21474     for(i=0; zText[i]; i++){
   21475       if( zNL==0 && zText[i]=='\n' ){
   21476         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
   21477         nNL = (int)strlen(zNL);
   21478       }
   21479       if( zCR==0 && zText[i]=='\r' ){
   21480         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
   21481         nCR = (int)strlen(zCR);
   21482       }
   21483     }
   21484 
   21485     if( zNL || zCR ){
   21486       int iOut = 0;
   21487       i64 nMax = (nNL > nCR) ? nNL : nCR;
   21488       i64 nAlloc = nMax * nText + (nMax+64)*2;
   21489       char *zOut = (char*)sqlite3_malloc64(nAlloc);
   21490       if( zOut==0 ){
   21491         sqlite3_result_error_nomem(context);
   21492         return;
   21493       }
   21494 
   21495       if( zNL && zCR ){
   21496         memcpy(&zOut[iOut], "replace(replace(", 16);
   21497         iOut += 16;
   21498       }else{
   21499         memcpy(&zOut[iOut], "replace(", 8);
   21500         iOut += 8;
   21501       }
   21502       for(i=0; zText[i]; i++){
   21503         if( zText[i]=='\n' ){
   21504           memcpy(&zOut[iOut], zNL, nNL);
   21505           iOut += nNL;
   21506         }else if( zText[i]=='\r' ){
   21507           memcpy(&zOut[iOut], zCR, nCR);
   21508           iOut += nCR;
   21509         }else{
   21510           zOut[iOut] = zText[i];
   21511           iOut++;
   21512         }
   21513       }
   21514 
   21515       if( zNL ){
   21516         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
   21517         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
   21518         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
   21519       }
   21520       if( zCR ){
   21521         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
   21522         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
   21523         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
   21524       }
   21525 
   21526       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
   21527       sqlite3_free(zOut);
   21528       return;
   21529     }
   21530   }
   21531 
   21532   sqlite3_result_value(context, argv[0]);
   21533 }
   21534 
   21535 /*
   21536 ** This function is a no-op if recover handle p already contains an error
   21537 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
   21538 ** this case.
   21539 **
   21540 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
   21541 ** parts of the database schema that can be extracted from the input database.
   21542 **
   21543 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
   21544 ** and error message are left in the recover handle and a copy of the
   21545 ** error code returned. It is not considered an error if part of all of
   21546 ** the database schema cannot be recovered due to corruption.
   21547 */
   21548 static int recoverCacheSchema(sqlite3_recover *p){
   21549   return recoverExec(p, p->dbOut,
   21550     "WITH RECURSIVE pages(p) AS ("
   21551     "  SELECT 1"
   21552     "    UNION"
   21553     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
   21554     ")"
   21555     "INSERT INTO recovery.schema SELECT"
   21556     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
   21557     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
   21558     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
   21559     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
   21560     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
   21561     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
   21562     "  SELECT p FROM pages"
   21563     ") GROUP BY pgno, cell"
   21564   );
   21565 }
   21566 
   21567 /*
   21568 ** If this recover handle is not in SQL callback mode (i.e. was not created
   21569 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
   21570 ** this function is a no-op. Otherwise, issue a callback with SQL statement
   21571 ** zSql as the parameter.
   21572 **
   21573 ** If the callback returns non-zero, set the recover handle error code to
   21574 ** the value returned (so that the caller will abandon processing).
   21575 */
   21576 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
   21577   if( p->errCode==SQLITE_OK && p->xSql ){
   21578     int res = p->xSql(p->pSqlCtx, zSql);
   21579     if( res ){
   21580       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
   21581     }
   21582   }
   21583 }
   21584 
   21585 /*
   21586 ** Transfer the following settings from the input database to the output
   21587 ** database:
   21588 **
   21589 **   + page-size,
   21590 **   + auto-vacuum settings,
   21591 **   + database encoding,
   21592 **   + user-version (PRAGMA user_version), and
   21593 **   + application-id (PRAGMA application_id), and
   21594 */
   21595 static void recoverTransferSettings(sqlite3_recover *p){
   21596   const char *aPragma[] = {
   21597     "encoding",
   21598     "page_size",
   21599     "auto_vacuum",
   21600     "user_version",
   21601     "application_id"
   21602   };
   21603   int ii;
   21604 
   21605   /* Truncate the output database to 0 pages in size. This is done by
   21606   ** opening a new, empty, temp db, then using the backup API to clobber
   21607   ** any existing output db with a copy of it. */
   21608   if( p->errCode==SQLITE_OK ){
   21609     sqlite3 *db2 = 0;
   21610     int rc = sqlite3_open("", &db2);
   21611     if( rc!=SQLITE_OK ){
   21612       recoverDbError(p, db2);
   21613       return;
   21614     }
   21615 
   21616     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
   21617       const char *zPrag = aPragma[ii];
   21618       sqlite3_stmt *p1 = 0;
   21619       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
   21620       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
   21621         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
   21622         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
   21623         recoverSqlCallback(p, z2);
   21624         recoverExec(p, db2, z2);
   21625         sqlite3_free(z2);
   21626         if( zArg==0 ){
   21627           recoverError(p, SQLITE_NOMEM, 0);
   21628         }
   21629       }
   21630       recoverFinalize(p, p1);
   21631     }
   21632     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
   21633 
   21634     if( p->errCode==SQLITE_OK ){
   21635       sqlite3 *db = p->dbOut;
   21636       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
   21637       if( pBackup ){
   21638         sqlite3_backup_step(pBackup, -1);
   21639         p->errCode = sqlite3_backup_finish(pBackup);
   21640       }else{
   21641         recoverDbError(p, db);
   21642       }
   21643     }
   21644 
   21645     sqlite3_close(db2);
   21646   }
   21647 }
   21648 
   21649 /*
   21650 ** This function is a no-op if recover handle p already contains an error
   21651 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
   21652 ** this case.
   21653 **
   21654 ** Otherwise, an attempt is made to open the output database, attach
   21655 ** and create the schema of the temporary database used to store
   21656 ** intermediate data, and to register all required user functions and
   21657 ** virtual table modules with the output handle.
   21658 **
   21659 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
   21660 ** and error message are left in the recover handle and a copy of the
   21661 ** error code returned.
   21662 */
   21663 static int recoverOpenOutput(sqlite3_recover *p){
   21664   struct Func {
   21665     const char *zName;
   21666     int nArg;
   21667     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
   21668   } aFunc[] = {
   21669     { "getpage", 1, recoverGetPage },
   21670     { "page_is_used", 1, recoverPageIsUsed },
   21671     { "read_i32", 2, recoverReadI32 },
   21672     { "escape_crlf", 1, recoverEscapeCrlf },
   21673   };
   21674 
   21675   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
   21676   sqlite3 *db = 0;                /* New database handle */
   21677   int ii;                         /* For iterating through aFunc[] */
   21678 
   21679   assert( p->dbOut==0 );
   21680 
   21681   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
   21682     recoverDbError(p, db);
   21683   }
   21684 
   21685   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
   21686   ** These two are registered with the output database handle - this
   21687   ** module depends on the input handle supporting the sqlite_dbpage
   21688   ** virtual table only.  */
   21689   if( p->errCode==SQLITE_OK ){
   21690     p->errCode = sqlite3_dbdata_init(db, 0, 0);
   21691   }
   21692 
   21693   /* Register the custom user-functions with the output handle. */
   21694   for(ii=0;
   21695       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
   21696       ii++){
   21697     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
   21698         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
   21699     );
   21700   }
   21701 
   21702   p->dbOut = db;
   21703   return p->errCode;
   21704 }
   21705 
   21706 /*
   21707 ** Attach the auxiliary database 'recovery' to the output database handle.
   21708 ** This temporary database is used during the recovery process and then
   21709 ** discarded.
   21710 */
   21711 static void recoverOpenRecovery(sqlite3_recover *p){
   21712   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
   21713   recoverExec(p, p->dbOut, zSql);
   21714   recoverExec(p, p->dbOut,
   21715       "PRAGMA writable_schema = 1;"
   21716       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
   21717       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
   21718   );
   21719   sqlite3_free(zSql);
   21720 }
   21721 
   21722 
   21723 /*
   21724 ** This function is a no-op if recover handle p already contains an error
   21725 ** (if p->errCode!=SQLITE_OK).
   21726 **
   21727 ** Otherwise, argument zName must be the name of a table that has just been
   21728 ** created in the output database. This function queries the output db
   21729 ** for the schema of said table, and creates a RecoverTable object to
   21730 ** store the schema in memory. The new RecoverTable object is linked into
   21731 ** the list at sqlite3_recover.pTblList.
   21732 **
   21733 ** Parameter iRoot must be the root page of table zName in the INPUT
   21734 ** database.
   21735 */
   21736 static void recoverAddTable(
   21737   sqlite3_recover *p,
   21738   const char *zName,              /* Name of table created in output db */
   21739   i64 iRoot                       /* Root page of same table in INPUT db */
   21740 ){
   21741   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
   21742       "PRAGMA table_xinfo(%Q)", zName
   21743   );
   21744 
   21745   if( pStmt ){
   21746     int iPk = -1;
   21747     int iBind = 1;
   21748     RecoverTable *pNew = 0;
   21749     int nCol = 0;
   21750     int nName = recoverStrlen(zName);
   21751     int nByte = 0;
   21752     while( sqlite3_step(pStmt)==SQLITE_ROW ){
   21753       nCol++;
   21754       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
   21755     }
   21756     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
   21757     recoverReset(p, pStmt);
   21758 
   21759     pNew = recoverMalloc(p, nByte);
   21760     if( pNew ){
   21761       int i = 0;
   21762       int iField = 0;
   21763       char *csr = 0;
   21764       pNew->aCol = (RecoverColumn*)&pNew[1];
   21765       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
   21766       pNew->nCol = nCol;
   21767       pNew->iRoot = iRoot;
   21768       memcpy(csr, zName, nName);
   21769       csr += nName+1;
   21770 
   21771       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
   21772         int iPKF = sqlite3_column_int(pStmt, 5);
   21773         int n = sqlite3_column_bytes(pStmt, 1);
   21774         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
   21775         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
   21776         int eHidden = sqlite3_column_int(pStmt, 6);
   21777 
   21778         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
   21779         if( iPKF>1 ) iPk = -2;
   21780         pNew->aCol[i].zCol = csr;
   21781         pNew->aCol[i].eHidden = eHidden;
   21782         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
   21783           pNew->aCol[i].iField = -1;
   21784         }else{
   21785           pNew->aCol[i].iField = iField++;
   21786         }
   21787         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
   21788          && eHidden!=RECOVER_EHIDDEN_STORED
   21789         ){
   21790           pNew->aCol[i].iBind = iBind++;
   21791         }
   21792         memcpy(csr, z, n);
   21793         csr += (n+1);
   21794       }
   21795 
   21796       pNew->pNext = p->pTblList;
   21797       p->pTblList = pNew;
   21798       pNew->bIntkey = 1;
   21799     }
   21800 
   21801     recoverFinalize(p, pStmt);
   21802 
   21803     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
   21804     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
   21805       int iField = sqlite3_column_int(pStmt, 0);
   21806       int iCol = sqlite3_column_int(pStmt, 1);
   21807 
   21808       assert( iCol<pNew->nCol );
   21809       pNew->aCol[iCol].iField = iField;
   21810 
   21811       pNew->bIntkey = 0;
   21812       iPk = -2;
   21813     }
   21814     recoverFinalize(p, pStmt);
   21815 
   21816     if( p->errCode==SQLITE_OK ){
   21817       if( iPk>=0 ){
   21818         pNew->aCol[iPk].bIPK = 1;
   21819       }else if( pNew->bIntkey ){
   21820         pNew->iRowidBind = iBind++;
   21821       }
   21822     }
   21823   }
   21824 }
   21825 
   21826 /*
   21827 ** This function is called after recoverCacheSchema() has cached those parts
   21828 ** of the input database schema that could be recovered in temporary table
   21829 ** "recovery.schema". This function creates in the output database copies
   21830 ** of all parts of that schema that must be created before the tables can
   21831 ** be populated. Specifically, this means:
   21832 **
   21833 **     * all tables that are not VIRTUAL, and
   21834 **     * UNIQUE indexes.
   21835 **
   21836 ** If the recovery handle uses SQL callbacks, then callbacks containing
   21837 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
   21838 **
   21839 ** Additionally, records are added to the sqlite_schema table of the
   21840 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
   21841 ** records are written directly to sqlite_schema, not actually executed.
   21842 ** If the handle is in SQL callback mode, then callbacks are invoked
   21843 ** with equivalent SQL statements.
   21844 */
   21845 static int recoverWriteSchema1(sqlite3_recover *p){
   21846   sqlite3_stmt *pSelect = 0;
   21847   sqlite3_stmt *pTblname = 0;
   21848 
   21849   pSelect = recoverPrepare(p, p->dbOut,
   21850       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
   21851       "  SELECT rootpage, name, sql, "
   21852       "    type='table', "
   21853       "    sql LIKE 'create virtual%',"
   21854       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
   21855       "  FROM recovery.schema"
   21856       ")"
   21857       "SELECT rootpage, tbl, isVirtual, name, sql"
   21858       " FROM dbschema "
   21859       "  WHERE tbl OR isIndex"
   21860       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
   21861   );
   21862 
   21863   pTblname = recoverPrepare(p, p->dbOut,
   21864       "SELECT name FROM sqlite_schema "
   21865       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
   21866   );
   21867 
   21868   if( pSelect ){
   21869     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
   21870     while( sqlite3_step(pSelect)==SQLITE_ROW ){
   21871       i64 iRoot = sqlite3_column_int64(pSelect, 0);
   21872       int bTable = sqlite3_column_int(pSelect, 1);
   21873       int bVirtual = sqlite3_column_int(pSelect, 2);
   21874       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
   21875       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
   21876       char *zFree = 0;
   21877       int rc = SQLITE_OK;
   21878 
   21879       if( bVirtual ){
   21880         zSql = (const char*)(zFree = recoverMPrintf(p,
   21881             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
   21882             zName, zName, zSql
   21883         ));
   21884       }
   21885       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
   21886       if( rc==SQLITE_OK ){
   21887         recoverSqlCallback(p, zSql);
   21888         if( bTable && !bVirtual ){
   21889           if( SQLITE_ROW==sqlite3_step(pTblname) ){
   21890             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
   21891             if( zTbl ) recoverAddTable(p, zTbl, iRoot);
   21892           }
   21893           recoverReset(p, pTblname);
   21894         }
   21895       }else if( rc!=SQLITE_ERROR ){
   21896         recoverDbError(p, p->dbOut);
   21897       }
   21898       sqlite3_free(zFree);
   21899     }
   21900   }
   21901   recoverFinalize(p, pSelect);
   21902   recoverFinalize(p, pTblname);
   21903 
   21904   return p->errCode;
   21905 }
   21906 
   21907 /*
   21908 ** This function is called after the output database has been populated. It
   21909 ** adds all recovered schema elements that were not created in the output
   21910 ** database by recoverWriteSchema1() - everything except for tables and
   21911 ** UNIQUE indexes. Specifically:
   21912 **
   21913 **     * views,
   21914 **     * triggers,
   21915 **     * non-UNIQUE indexes.
   21916 **
   21917 ** If the recover handle is in SQL callback mode, then equivalent callbacks
   21918 ** are issued to create the schema elements.
   21919 */
   21920 static int recoverWriteSchema2(sqlite3_recover *p){
   21921   sqlite3_stmt *pSelect = 0;
   21922 
   21923   pSelect = recoverPrepare(p, p->dbOut,
   21924       p->bSlowIndexes ?
   21925       "SELECT rootpage, sql FROM recovery.schema "
   21926       "  WHERE type!='table' AND type!='index'"
   21927       :
   21928       "SELECT rootpage, sql FROM recovery.schema "
   21929       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
   21930   );
   21931 
   21932   if( pSelect ){
   21933     while( sqlite3_step(pSelect)==SQLITE_ROW ){
   21934       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
   21935       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
   21936       if( rc==SQLITE_OK ){
   21937         recoverSqlCallback(p, zSql);
   21938       }else if( rc!=SQLITE_ERROR ){
   21939         recoverDbError(p, p->dbOut);
   21940       }
   21941     }
   21942   }
   21943   recoverFinalize(p, pSelect);
   21944 
   21945   return p->errCode;
   21946 }
   21947 
   21948 /*
   21949 ** This function is a no-op if recover handle p already contains an error
   21950 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
   21951 **
   21952 ** Otherwise, if the recover handle is configured to create an output
   21953 ** database (was created by sqlite3_recover_init()), then this function
   21954 ** prepares and returns an SQL statement to INSERT a new record into table
   21955 ** pTab, assuming the first nField fields of a record extracted from disk
   21956 ** are valid.
   21957 **
   21958 ** For example, if table pTab is:
   21959 **
   21960 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
   21961 **
   21962 ** And nField is 4, then the SQL statement prepared and returned is:
   21963 **
   21964 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
   21965 **
   21966 ** In this case even though 4 values were extracted from the input db,
   21967 ** only 3 are written to the output, as the generated STORED column
   21968 ** cannot be written.
   21969 **
   21970 ** If the recover handle is in SQL callback mode, then the SQL statement
   21971 ** prepared is such that evaluating it returns a single row containing
   21972 ** a single text value - itself an SQL statement similar to the above,
   21973 ** except with SQL literals in place of the variables. For example:
   21974 **
   21975 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
   21976 **          || quote(?1) || ', '
   21977 **          || quote(?2) || ', '
   21978 **          || quote(?3) || ')';
   21979 **
   21980 ** In either case, it is the responsibility of the caller to eventually
   21981 ** free the statement handle using sqlite3_finalize().
   21982 */
   21983 static sqlite3_stmt *recoverInsertStmt(
   21984   sqlite3_recover *p,
   21985   RecoverTable *pTab,
   21986   int nField
   21987 ){
   21988   sqlite3_stmt *pRet = 0;
   21989   const char *zSep = "";
   21990   const char *zSqlSep = "";
   21991   char *zSql = 0;
   21992   char *zFinal = 0;
   21993   char *zBind = 0;
   21994   int ii;
   21995   int bSql = p->xSql ? 1 : 0;
   21996 
   21997   if( nField<=0 ) return 0;
   21998 
   21999   assert( nField<=pTab->nCol );
   22000 
   22001   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
   22002 
   22003   if( pTab->iRowidBind ){
   22004     assert( pTab->bIntkey );
   22005     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
   22006     if( bSql ){
   22007       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
   22008     }else{
   22009       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
   22010     }
   22011     zSqlSep = "||', '||";
   22012     zSep = ", ";
   22013   }
   22014 
   22015   for(ii=0; ii<nField; ii++){
   22016     int eHidden = pTab->aCol[ii].eHidden;
   22017     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
   22018      && eHidden!=RECOVER_EHIDDEN_STORED
   22019     ){
   22020       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
   22021       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
   22022 
   22023       if( bSql ){
   22024         zBind = recoverMPrintf(p,
   22025             "%z%sescape_crlf(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
   22026         );
   22027         zSqlSep = "||', '||";
   22028       }else{
   22029         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
   22030       }
   22031       zSep = ", ";
   22032     }
   22033   }
   22034 
   22035   if( bSql ){
   22036     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
   22037         zSql, zBind
   22038     );
   22039   }else{
   22040     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
   22041   }
   22042 
   22043   pRet = recoverPrepare(p, p->dbOut, zFinal);
   22044   sqlite3_free(zSql);
   22045   sqlite3_free(zBind);
   22046   sqlite3_free(zFinal);
   22047 
   22048   return pRet;
   22049 }
   22050 
   22051 
   22052 /*
   22053 ** Search the list of RecoverTable objects at p->pTblList for one that
   22054 ** has root page iRoot in the input database. If such an object is found,
   22055 ** return a pointer to it. Otherwise, return NULL.
   22056 */
   22057 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
   22058   RecoverTable *pRet = 0;
   22059   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
   22060   return pRet;
   22061 }
   22062 
   22063 /*
   22064 ** This function attempts to create a lost and found table within the
   22065 ** output db. If successful, it returns a pointer to a buffer containing
   22066 ** the name of the new table. It is the responsibility of the caller to
   22067 ** eventually free this buffer using sqlite3_free().
   22068 **
   22069 ** If an error occurs, NULL is returned and an error code and error
   22070 ** message left in the recover handle.
   22071 */
   22072 static char *recoverLostAndFoundCreate(
   22073   sqlite3_recover *p,             /* Recover object */
   22074   int nField                      /* Number of column fields in new table */
   22075 ){
   22076   char *zTbl = 0;
   22077   sqlite3_stmt *pProbe = 0;
   22078   int ii = 0;
   22079 
   22080   pProbe = recoverPrepare(p, p->dbOut,
   22081     "SELECT 1 FROM sqlite_schema WHERE name=?"
   22082   );
   22083   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
   22084     int bFail = 0;
   22085     if( ii<0 ){
   22086       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
   22087     }else{
   22088       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
   22089     }
   22090 
   22091     if( p->errCode==SQLITE_OK ){
   22092       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
   22093       if( SQLITE_ROW==sqlite3_step(pProbe) ){
   22094         bFail = 1;
   22095       }
   22096       recoverReset(p, pProbe);
   22097     }
   22098 
   22099     if( bFail ){
   22100       sqlite3_clear_bindings(pProbe);
   22101       sqlite3_free(zTbl);
   22102       zTbl = 0;
   22103     }
   22104   }
   22105   recoverFinalize(p, pProbe);
   22106 
   22107   if( zTbl ){
   22108     const char *zSep = 0;
   22109     char *zField = 0;
   22110     char *zSql = 0;
   22111 
   22112     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
   22113     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
   22114       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
   22115       zSep = ", ";
   22116     }
   22117 
   22118     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
   22119     sqlite3_free(zField);
   22120 
   22121     recoverExec(p, p->dbOut, zSql);
   22122     recoverSqlCallback(p, zSql);
   22123     sqlite3_free(zSql);
   22124   }else if( p->errCode==SQLITE_OK ){
   22125     recoverError(
   22126         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
   22127     );
   22128   }
   22129 
   22130   return zTbl;
   22131 }
   22132 
   22133 /*
   22134 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
   22135 ** table in the output database. The name of the table is zTab, and it has
   22136 ** nField c* fields.
   22137 */
   22138 static sqlite3_stmt *recoverLostAndFoundInsert(
   22139   sqlite3_recover *p,
   22140   const char *zTab,
   22141   int nField
   22142 ){
   22143   int nTotal = nField + 4;
   22144   int ii;
   22145   char *zBind = 0;
   22146   sqlite3_stmt *pRet = 0;
   22147 
   22148   if( p->xSql==0 ){
   22149     for(ii=0; ii<nTotal; ii++){
   22150       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
   22151     }
   22152     pRet = recoverPreparePrintf(
   22153         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
   22154     );
   22155   }else{
   22156     const char *zSep = "";
   22157     for(ii=0; ii<nTotal; ii++){
   22158       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
   22159       zSep = "|| ', ' ||";
   22160     }
   22161     pRet = recoverPreparePrintf(
   22162         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
   22163     );
   22164   }
   22165 
   22166   sqlite3_free(zBind);
   22167   return pRet;
   22168 }
   22169 
   22170 /*
   22171 ** Input database page iPg contains data that will be written to the
   22172 ** lost-and-found table of the output database. This function attempts
   22173 ** to identify the root page of the tree that page iPg belonged to.
   22174 ** If successful, it sets output variable (*piRoot) to the page number
   22175 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
   22176 ** an SQLite error code is returned and the final value of *piRoot
   22177 ** undefined.
   22178 */
   22179 static int recoverLostAndFoundFindRoot(
   22180   sqlite3_recover *p,
   22181   i64 iPg,
   22182   i64 *piRoot
   22183 ){
   22184   RecoverStateLAF *pLaf = &p->laf;
   22185 
   22186   if( pLaf->pFindRoot==0 ){
   22187     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
   22188         "WITH RECURSIVE p(pgno) AS ("
   22189         "  SELECT ?"
   22190         "    UNION"
   22191         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
   22192         ") "
   22193         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
   22194         "    AND m.parent IS NULL"
   22195     );
   22196   }
   22197   if( p->errCode==SQLITE_OK ){
   22198     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
   22199     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
   22200       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
   22201     }else{
   22202       *piRoot = iPg;
   22203     }
   22204     recoverReset(p, pLaf->pFindRoot);
   22205   }
   22206   return p->errCode;
   22207 }
   22208 
   22209 /*
   22210 ** Recover data from page iPage of the input database and write it to
   22211 ** the lost-and-found table in the output database.
   22212 */
   22213 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
   22214   RecoverStateLAF *pLaf = &p->laf;
   22215   sqlite3_value **apVal = pLaf->apVal;
   22216   sqlite3_stmt *pPageData = pLaf->pPageData;
   22217   sqlite3_stmt *pInsert = pLaf->pInsert;
   22218 
   22219   int nVal = -1;
   22220   int iPrevCell = 0;
   22221   i64 iRoot = 0;
   22222   int bHaveRowid = 0;
   22223   i64 iRowid = 0;
   22224   int ii = 0;
   22225 
   22226   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
   22227   sqlite3_bind_int64(pPageData, 1, iPage);
   22228   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
   22229     int iCell = sqlite3_column_int64(pPageData, 0);
   22230     int iField = sqlite3_column_int64(pPageData, 1);
   22231 
   22232     if( iPrevCell!=iCell && nVal>=0 ){
   22233       /* Insert the new row */
   22234       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
   22235       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
   22236       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
   22237       if( bHaveRowid ){
   22238         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
   22239       }
   22240       for(ii=0; ii<nVal; ii++){
   22241         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
   22242       }
   22243       if( sqlite3_step(pInsert)==SQLITE_ROW ){
   22244         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
   22245       }
   22246       recoverReset(p, pInsert);
   22247 
   22248       /* Discard the accumulated row data */
   22249       for(ii=0; ii<nVal; ii++){
   22250         sqlite3_value_free(apVal[ii]);
   22251         apVal[ii] = 0;
   22252       }
   22253       sqlite3_clear_bindings(pInsert);
   22254       bHaveRowid = 0;
   22255       nVal = -1;
   22256     }
   22257 
   22258     if( iCell<0 ) break;
   22259 
   22260     if( iField<0 ){
   22261       assert( nVal==-1 );
   22262       iRowid = sqlite3_column_int64(pPageData, 2);
   22263       bHaveRowid = 1;
   22264       nVal = 0;
   22265     }else if( iField<pLaf->nMaxField ){
   22266       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
   22267       apVal[iField] = sqlite3_value_dup(pVal);
   22268       assert( iField==nVal || (nVal==-1 && iField==0) );
   22269       nVal = iField+1;
   22270       if( apVal[iField]==0 ){
   22271         recoverError(p, SQLITE_NOMEM, 0);
   22272       }
   22273     }
   22274 
   22275     iPrevCell = iCell;
   22276   }
   22277   recoverReset(p, pPageData);
   22278 
   22279   for(ii=0; ii<nVal; ii++){
   22280     sqlite3_value_free(apVal[ii]);
   22281     apVal[ii] = 0;
   22282   }
   22283 }
   22284 
   22285 /*
   22286 ** Perform one step (sqlite3_recover_step()) of work for the connection
   22287 ** passed as the only argument, which is guaranteed to be in
   22288 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
   22289 ** table of the output database is populated with recovered data that can
   22290 ** not be assigned to any recovered schema object.
   22291 */
   22292 static int recoverLostAndFound3Step(sqlite3_recover *p){
   22293   RecoverStateLAF *pLaf = &p->laf;
   22294   if( p->errCode==SQLITE_OK ){
   22295     if( pLaf->pInsert==0 ){
   22296       return SQLITE_DONE;
   22297     }else{
   22298       if( p->errCode==SQLITE_OK ){
   22299         int res = sqlite3_step(pLaf->pAllPage);
   22300         if( res==SQLITE_ROW ){
   22301           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
   22302           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
   22303             recoverLostAndFoundOnePage(p, iPage);
   22304           }
   22305         }else{
   22306           recoverReset(p, pLaf->pAllPage);
   22307           return SQLITE_DONE;
   22308         }
   22309       }
   22310     }
   22311   }
   22312   return SQLITE_OK;
   22313 }
   22314 
   22315 /*
   22316 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
   22317 ** state - during which the lost-and-found table of the output database
   22318 ** is populated with recovered data that can not be assigned to any
   22319 ** recovered schema object.
   22320 */
   22321 static void recoverLostAndFound3Init(sqlite3_recover *p){
   22322   RecoverStateLAF *pLaf = &p->laf;
   22323 
   22324   if( pLaf->nMaxField>0 ){
   22325     char *zTab = 0;               /* Name of lost_and_found table */
   22326 
   22327     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
   22328     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
   22329     sqlite3_free(zTab);
   22330 
   22331     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
   22332         "WITH RECURSIVE seq(ii) AS ("
   22333         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
   22334         ")"
   22335         "SELECT ii FROM seq" , p->laf.nPg
   22336     );
   22337     pLaf->pPageData = recoverPrepare(p, p->dbOut,
   22338         "SELECT cell, field, value "
   22339         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
   22340         "UNION ALL "
   22341         "SELECT -1, -1, -1"
   22342     );
   22343 
   22344     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
   22345         pLaf->nMaxField*sizeof(sqlite3_value*)
   22346     );
   22347   }
   22348 }
   22349 
   22350 /*
   22351 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
   22352 ** tables recovered from the schema of the input database are populated with
   22353 ** recovered data.
   22354 */
   22355 static int recoverWriteDataInit(sqlite3_recover *p){
   22356   RecoverStateW1 *p1 = &p->w1;
   22357   RecoverTable *pTbl = 0;
   22358   int nByte = 0;
   22359 
   22360   /* Figure out the maximum number of columns for any table in the schema */
   22361   assert( p1->nMax==0 );
   22362   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
   22363     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
   22364   }
   22365 
   22366   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
   22367   ** that will be written to the output database in a single row. */
   22368   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
   22369   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
   22370   if( p1->apVal==0 ) return p->errCode;
   22371 
   22372   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
   22373   ** to loop through cells that appear to belong to a single table (pSel). */
   22374   p1->pTbls = recoverPrepare(p, p->dbOut,
   22375       "SELECT rootpage FROM recovery.schema "
   22376       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
   22377       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
   22378   );
   22379   p1->pSel = recoverPrepare(p, p->dbOut,
   22380       "WITH RECURSIVE pages(page) AS ("
   22381       "  SELECT ?1"
   22382       "    UNION"
   22383       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
   22384       "    WHERE pgno=page"
   22385       ") "
   22386       "SELECT page, cell, field, value "
   22387       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
   22388       "UNION ALL "
   22389       "SELECT 0, 0, 0, 0"
   22390   );
   22391 
   22392   return p->errCode;
   22393 }
   22394 
   22395 /*
   22396 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
   22397 ** sqlite3_recover.w1).
   22398 */
   22399 static void recoverWriteDataCleanup(sqlite3_recover *p){
   22400   RecoverStateW1 *p1 = &p->w1;
   22401   int ii;
   22402   for(ii=0; ii<p1->nVal; ii++){
   22403     sqlite3_value_free(p1->apVal[ii]);
   22404   }
   22405   sqlite3_free(p1->apVal);
   22406   recoverFinalize(p, p1->pInsert);
   22407   recoverFinalize(p, p1->pTbls);
   22408   recoverFinalize(p, p1->pSel);
   22409   memset(p1, 0, sizeof(*p1));
   22410 }
   22411 
   22412 /*
   22413 ** Perform one step (sqlite3_recover_step()) of work for the connection
   22414 ** passed as the only argument, which is guaranteed to be in
   22415 ** RECOVER_STATE_WRITING state - during which tables recovered from the
   22416 ** schema of the input database are populated with recovered data.
   22417 */
   22418 static int recoverWriteDataStep(sqlite3_recover *p){
   22419   RecoverStateW1 *p1 = &p->w1;
   22420   sqlite3_stmt *pSel = p1->pSel;
   22421   sqlite3_value **apVal = p1->apVal;
   22422 
   22423   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
   22424     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
   22425       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
   22426       p1->pTab = recoverFindTable(p, iRoot);
   22427 
   22428       recoverFinalize(p, p1->pInsert);
   22429       p1->pInsert = 0;
   22430 
   22431       /* If this table is unknown, return early. The caller will invoke this
   22432       ** function again and it will move on to the next table.  */
   22433       if( p1->pTab==0 ) return p->errCode;
   22434 
   22435       /* If this is the sqlite_sequence table, delete any rows added by
   22436       ** earlier INSERT statements on tables with AUTOINCREMENT primary
   22437       ** keys before recovering its contents. The p1->pTbls SELECT statement
   22438       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
   22439       ** worry about it being modified after it is recovered. */
   22440       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
   22441         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
   22442         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
   22443       }
   22444 
   22445       /* Bind the root page of this table within the original database to
   22446       ** SELECT statement p1->pSel. The SELECT statement will then iterate
   22447       ** through cells that look like they belong to table pTab.  */
   22448       sqlite3_bind_int64(pSel, 1, iRoot);
   22449 
   22450       p1->nVal = 0;
   22451       p1->bHaveRowid = 0;
   22452       p1->iPrevPage = -1;
   22453       p1->iPrevCell = -1;
   22454     }else{
   22455       return SQLITE_DONE;
   22456     }
   22457   }
   22458   assert( p->errCode!=SQLITE_OK || p1->pTab );
   22459 
   22460   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
   22461     RecoverTable *pTab = p1->pTab;
   22462 
   22463     i64 iPage = sqlite3_column_int64(pSel, 0);
   22464     int iCell = sqlite3_column_int(pSel, 1);
   22465     int iField = sqlite3_column_int(pSel, 2);
   22466     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
   22467     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
   22468 
   22469     assert( bNewCell==0 || (iField==-1 || iField==0) );
   22470     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
   22471 
   22472     if( bNewCell ){
   22473       int ii = 0;
   22474       if( p1->nVal>=0 ){
   22475         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
   22476           recoverFinalize(p, p1->pInsert);
   22477           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
   22478           p1->nInsert = p1->nVal;
   22479         }
   22480         if( p1->nVal>0 ){
   22481           sqlite3_stmt *pInsert = p1->pInsert;
   22482           for(ii=0; ii<pTab->nCol; ii++){
   22483             RecoverColumn *pCol = &pTab->aCol[ii];
   22484             int iBind = pCol->iBind;
   22485             if( iBind>0 ){
   22486               if( pCol->bIPK ){
   22487                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
   22488               }else if( pCol->iField<p1->nVal ){
   22489                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
   22490               }
   22491             }
   22492           }
   22493           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
   22494             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
   22495           }
   22496           if( SQLITE_ROW==sqlite3_step(pInsert) ){
   22497             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
   22498             recoverSqlCallback(p, z);
   22499           }
   22500           recoverReset(p, pInsert);
   22501           assert( p->errCode || pInsert );
   22502           if( pInsert ) sqlite3_clear_bindings(pInsert);
   22503         }
   22504       }
   22505 
   22506       for(ii=0; ii<p1->nVal; ii++){
   22507         sqlite3_value_free(apVal[ii]);
   22508         apVal[ii] = 0;
   22509       }
   22510       p1->nVal = -1;
   22511       p1->bHaveRowid = 0;
   22512     }
   22513 
   22514     if( iPage!=0 ){
   22515       if( iField<0 ){
   22516         p1->iRowid = sqlite3_column_int64(pSel, 3);
   22517         assert( p1->nVal==-1 );
   22518         p1->nVal = 0;
   22519         p1->bHaveRowid = 1;
   22520       }else if( iField<pTab->nCol ){
   22521         assert( apVal[iField]==0 );
   22522         apVal[iField] = sqlite3_value_dup( pVal );
   22523         if( apVal[iField]==0 ){
   22524           recoverError(p, SQLITE_NOMEM, 0);
   22525         }
   22526         p1->nVal = iField+1;
   22527       }else if( pTab->nCol==0 ){
   22528         p1->nVal = pTab->nCol;
   22529       }
   22530       p1->iPrevCell = iCell;
   22531       p1->iPrevPage = iPage;
   22532     }
   22533   }else{
   22534     recoverReset(p, pSel);
   22535     p1->pTab = 0;
   22536   }
   22537 
   22538   return p->errCode;
   22539 }
   22540 
   22541 /*
   22542 ** Initialize resources required by sqlite3_recover_step() in
   22543 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
   22544 ** already allocated to a recovered schema element is determined.
   22545 */
   22546 static void recoverLostAndFound1Init(sqlite3_recover *p){
   22547   RecoverStateLAF *pLaf = &p->laf;
   22548   sqlite3_stmt *pStmt = 0;
   22549 
   22550   assert( p->laf.pUsed==0 );
   22551   pLaf->nPg = recoverPageCount(p);
   22552   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
   22553 
   22554   /* Prepare a statement to iterate through all pages that are part of any tree
   22555   ** in the recoverable part of the input database schema to the bitmap. And,
   22556   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
   22557   ** freelist.  */
   22558   pStmt = recoverPrepare(
   22559       p, p->dbOut,
   22560       "WITH trunk(pgno) AS ("
   22561       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
   22562       "    UNION"
   22563       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
   22564       "),"
   22565       "trunkdata(pgno, data) AS ("
   22566       "  SELECT pgno, getpage(pgno) FROM trunk"
   22567       "),"
   22568       "freelist(data, n, freepgno) AS ("
   22569       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
   22570       "    UNION ALL"
   22571       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
   22572       "),"
   22573       ""
   22574       "roots(r) AS ("
   22575       "  SELECT 1 UNION ALL"
   22576       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
   22577       "),"
   22578       "used(page) AS ("
   22579       "  SELECT r FROM roots"
   22580       "    UNION"
   22581       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
   22582       "    WHERE pgno=page"
   22583       ") "
   22584       "SELECT page FROM used"
   22585       " UNION ALL "
   22586       "SELECT freepgno FROM freelist WHERE NOT ?"
   22587   );
   22588   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
   22589   pLaf->pUsedPages = pStmt;
   22590 }
   22591 
   22592 /*
   22593 ** Perform one step (sqlite3_recover_step()) of work for the connection
   22594 ** passed as the only argument, which is guaranteed to be in
   22595 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
   22596 ** already allocated to a recovered schema element is determined.
   22597 */
   22598 static int recoverLostAndFound1Step(sqlite3_recover *p){
   22599   RecoverStateLAF *pLaf = &p->laf;
   22600   int rc = p->errCode;
   22601   if( rc==SQLITE_OK ){
   22602     rc = sqlite3_step(pLaf->pUsedPages);
   22603     if( rc==SQLITE_ROW ){
   22604       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
   22605       recoverBitmapSet(pLaf->pUsed, iPg);
   22606       rc = SQLITE_OK;
   22607     }else{
   22608       recoverFinalize(p, pLaf->pUsedPages);
   22609       pLaf->pUsedPages = 0;
   22610     }
   22611   }
   22612   return rc;
   22613 }
   22614 
   22615 /*
   22616 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
   22617 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
   22618 ** are sorted into sets that likely belonged to the same database tree.
   22619 */
   22620 static void recoverLostAndFound2Init(sqlite3_recover *p){
   22621   RecoverStateLAF *pLaf = &p->laf;
   22622 
   22623   assert( p->laf.pAllAndParent==0 );
   22624   assert( p->laf.pMapInsert==0 );
   22625   assert( p->laf.pMaxField==0 );
   22626   assert( p->laf.nMaxField==0 );
   22627 
   22628   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
   22629       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
   22630   );
   22631   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
   22632       "WITH RECURSIVE seq(ii) AS ("
   22633       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
   22634       ")"
   22635       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
   22636       " UNION ALL "
   22637       "SELECT NULL, ii FROM seq", p->laf.nPg
   22638   );
   22639   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
   22640       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
   22641   );
   22642 }
   22643 
   22644 /*
   22645 ** Perform one step (sqlite3_recover_step()) of work for the connection
   22646 ** passed as the only argument, which is guaranteed to be in
   22647 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
   22648 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
   22649 ** to the same database tree.
   22650 */
   22651 static int recoverLostAndFound2Step(sqlite3_recover *p){
   22652   RecoverStateLAF *pLaf = &p->laf;
   22653   if( p->errCode==SQLITE_OK ){
   22654     int res = sqlite3_step(pLaf->pAllAndParent);
   22655     if( res==SQLITE_ROW ){
   22656       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
   22657       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
   22658         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
   22659         sqlite3_bind_value(pLaf->pMapInsert, 2,
   22660             sqlite3_column_value(pLaf->pAllAndParent, 0)
   22661         );
   22662         sqlite3_step(pLaf->pMapInsert);
   22663         recoverReset(p, pLaf->pMapInsert);
   22664         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
   22665         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
   22666           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
   22667           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
   22668         }
   22669         recoverReset(p, pLaf->pMaxField);
   22670       }
   22671     }else{
   22672       recoverFinalize(p, pLaf->pAllAndParent);
   22673       pLaf->pAllAndParent =0;
   22674       return SQLITE_DONE;
   22675     }
   22676   }
   22677   return p->errCode;
   22678 }
   22679 
   22680 /*
   22681 ** Free all resources allocated as part of sqlite3_recover_step() calls
   22682 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
   22683 */
   22684 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
   22685   recoverBitmapFree(p->laf.pUsed);
   22686   p->laf.pUsed = 0;
   22687   sqlite3_finalize(p->laf.pUsedPages);
   22688   sqlite3_finalize(p->laf.pAllAndParent);
   22689   sqlite3_finalize(p->laf.pMapInsert);
   22690   sqlite3_finalize(p->laf.pMaxField);
   22691   sqlite3_finalize(p->laf.pFindRoot);
   22692   sqlite3_finalize(p->laf.pInsert);
   22693   sqlite3_finalize(p->laf.pAllPage);
   22694   sqlite3_finalize(p->laf.pPageData);
   22695   p->laf.pUsedPages = 0;
   22696   p->laf.pAllAndParent = 0;
   22697   p->laf.pMapInsert = 0;
   22698   p->laf.pMaxField = 0;
   22699   p->laf.pFindRoot = 0;
   22700   p->laf.pInsert = 0;
   22701   p->laf.pAllPage = 0;
   22702   p->laf.pPageData = 0;
   22703   sqlite3_free(p->laf.apVal);
   22704   p->laf.apVal = 0;
   22705 }
   22706 
   22707 /*
   22708 ** Free all resources allocated as part of sqlite3_recover_step() calls.
   22709 */
   22710 static void recoverFinalCleanup(sqlite3_recover *p){
   22711   RecoverTable *pTab = 0;
   22712   RecoverTable *pNext = 0;
   22713 
   22714   recoverWriteDataCleanup(p);
   22715   recoverLostAndFoundCleanup(p);
   22716 
   22717   for(pTab=p->pTblList; pTab; pTab=pNext){
   22718     pNext = pTab->pNext;
   22719     sqlite3_free(pTab);
   22720   }
   22721   p->pTblList = 0;
   22722   sqlite3_finalize(p->pGetPage);
   22723   p->pGetPage = 0;
   22724   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
   22725 
   22726   {
   22727 #ifndef NDEBUG
   22728     int res =
   22729 #endif
   22730        sqlite3_close(p->dbOut);
   22731     assert( res==SQLITE_OK );
   22732   }
   22733   p->dbOut = 0;
   22734 }
   22735 
   22736 /*
   22737 ** Decode and return an unsigned 16-bit big-endian integer value from
   22738 ** buffer a[].
   22739 */
   22740 static u32 recoverGetU16(const u8 *a){
   22741   return (((u32)a[0])<<8) + ((u32)a[1]);
   22742 }
   22743 
   22744 /*
   22745 ** Decode and return an unsigned 32-bit big-endian integer value from
   22746 ** buffer a[].
   22747 */
   22748 static u32 recoverGetU32(const u8 *a){
   22749   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
   22750 }
   22751 
   22752 /*
   22753 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
   22754 ** and return the number of bytes consumed.
   22755 */
   22756 static int recoverGetVarint(const u8 *a, i64 *pVal){
   22757   sqlite3_uint64 u = 0;
   22758   int i;
   22759   for(i=0; i<8; i++){
   22760     u = (u<<7) + (a[i]&0x7f);
   22761     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
   22762   }
   22763   u = (u<<8) + (a[i]&0xff);
   22764   *pVal = (sqlite3_int64)u;
   22765   return 9;
   22766 }
   22767 
   22768 /*
   22769 ** The second argument points to a buffer n bytes in size. If this buffer
   22770 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
   22771 ** return the page-size in bytes. Otherwise, if the buffer does not
   22772 ** appear to contain a well-formed b-tree page, return 0.
   22773 */
   22774 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
   22775   u8 *aUsed = aTmp;
   22776   int nFrag = 0;
   22777   int nActual = 0;
   22778   int iFree = 0;
   22779   int nCell = 0;                  /* Number of cells on page */
   22780   int iCellOff = 0;               /* Offset of cell array in page */
   22781   int iContent = 0;
   22782   int eType = 0;
   22783   int ii = 0;
   22784 
   22785   eType = (int)a[0];
   22786   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
   22787 
   22788   iFree = (int)recoverGetU16(&a[1]);
   22789   nCell = (int)recoverGetU16(&a[3]);
   22790   iContent = (int)recoverGetU16(&a[5]);
   22791   if( iContent==0 ) iContent = 65536;
   22792   nFrag = (int)a[7];
   22793 
   22794   if( iContent>n ) return 0;
   22795 
   22796   memset(aUsed, 0, n);
   22797   memset(aUsed, 0xFF, iContent);
   22798 
   22799   /* Follow the free-list. This is the same format for all b-tree pages. */
   22800   if( iFree && iFree<=iContent ) return 0;
   22801   while( iFree ){
   22802     int iNext = 0;
   22803     int nByte = 0;
   22804     if( iFree>(n-4) ) return 0;
   22805     iNext = recoverGetU16(&a[iFree]);
   22806     nByte = recoverGetU16(&a[iFree+2]);
   22807     if( iFree+nByte>n || nByte<4 ) return 0;
   22808     if( iNext && iNext<iFree+nByte ) return 0;
   22809     memset(&aUsed[iFree], 0xFF, nByte);
   22810     iFree = iNext;
   22811   }
   22812 
   22813   /* Run through the cells */
   22814   if( eType==0x02 || eType==0x05 ){
   22815     iCellOff = 12;
   22816   }else{
   22817     iCellOff = 8;
   22818   }
   22819   if( (iCellOff + 2*nCell)>iContent ) return 0;
   22820   for(ii=0; ii<nCell; ii++){
   22821     int iByte;
   22822     i64 nPayload = 0;
   22823     int nByte = 0;
   22824     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
   22825     if( iOff<iContent || iOff>n ){
   22826       return 0;
   22827     }
   22828     if( eType==0x05 || eType==0x02 ) nByte += 4;
   22829     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
   22830     if( eType==0x0D ){
   22831       i64 dummy = 0;
   22832       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
   22833     }
   22834     if( eType!=0x05 ){
   22835       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
   22836       int M = ((n-12)*32/255)-23;
   22837       int K = M+((nPayload-M)%(n-4));
   22838 
   22839       if( nPayload<X ){
   22840         nByte += nPayload;
   22841       }else if( K<=X ){
   22842         nByte += K+4;
   22843       }else{
   22844         nByte += M+4;
   22845       }
   22846     }
   22847 
   22848     if( iOff+nByte>n ){
   22849       return 0;
   22850     }
   22851     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
   22852       if( aUsed[iByte]!=0 ){
   22853         return 0;
   22854       }
   22855       aUsed[iByte] = 0xFF;
   22856     }
   22857   }
   22858 
   22859   nActual = 0;
   22860   for(ii=0; ii<n; ii++){
   22861     if( aUsed[ii]==0 ) nActual++;
   22862   }
   22863   return (nActual==nFrag);
   22864 }
   22865 
   22866 
   22867 static int recoverVfsClose(sqlite3_file*);
   22868 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   22869 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
   22870 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
   22871 static int recoverVfsSync(sqlite3_file*, int flags);
   22872 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
   22873 static int recoverVfsLock(sqlite3_file*, int);
   22874 static int recoverVfsUnlock(sqlite3_file*, int);
   22875 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
   22876 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
   22877 static int recoverVfsSectorSize(sqlite3_file*);
   22878 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
   22879 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
   22880 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
   22881 static void recoverVfsShmBarrier(sqlite3_file*);
   22882 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
   22883 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
   22884 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
   22885 
   22886 static sqlite3_io_methods recover_methods = {
   22887   2, /* iVersion */
   22888   recoverVfsClose,
   22889   recoverVfsRead,
   22890   recoverVfsWrite,
   22891   recoverVfsTruncate,
   22892   recoverVfsSync,
   22893   recoverVfsFileSize,
   22894   recoverVfsLock,
   22895   recoverVfsUnlock,
   22896   recoverVfsCheckReservedLock,
   22897   recoverVfsFileControl,
   22898   recoverVfsSectorSize,
   22899   recoverVfsDeviceCharacteristics,
   22900   recoverVfsShmMap,
   22901   recoverVfsShmLock,
   22902   recoverVfsShmBarrier,
   22903   recoverVfsShmUnmap,
   22904   recoverVfsFetch,
   22905   recoverVfsUnfetch
   22906 };
   22907 
   22908 static int recoverVfsClose(sqlite3_file *pFd){
   22909   assert( pFd->pMethods!=&recover_methods );
   22910   return pFd->pMethods->xClose(pFd);
   22911 }
   22912 
   22913 /*
   22914 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
   22915 */
   22916 static void recoverPutU16(u8 *a, u32 v){
   22917   a[0] = (v>>8) & 0x00FF;
   22918   a[1] = (v>>0) & 0x00FF;
   22919 }
   22920 
   22921 /*
   22922 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
   22923 */
   22924 static void recoverPutU32(u8 *a, u32 v){
   22925   a[0] = (v>>24) & 0x00FF;
   22926   a[1] = (v>>16) & 0x00FF;
   22927   a[2] = (v>>8) & 0x00FF;
   22928   a[3] = (v>>0) & 0x00FF;
   22929 }
   22930 
   22931 /*
   22932 ** Detect the page-size of the database opened by file-handle pFd by
   22933 ** searching the first part of the file for a well-formed SQLite b-tree
   22934 ** page. If parameter nReserve is non-zero, then as well as searching for
   22935 ** a b-tree page with zero reserved bytes, this function searches for one
   22936 ** with nReserve reserved bytes at the end of it.
   22937 **
   22938 ** If successful, set variable p->detected_pgsz to the detected page-size
   22939 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
   22940 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
   22941 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
   22942 ** is returned. The final value of p->detected_pgsz is undefined in this
   22943 ** case.
   22944 */
   22945 static int recoverVfsDetectPagesize(
   22946   sqlite3_recover *p,             /* Recover handle */
   22947   sqlite3_file *pFd,              /* File-handle open on input database */
   22948   u32 nReserve,                   /* Possible nReserve value */
   22949   i64 nSz                         /* Size of database file in bytes */
   22950 ){
   22951   int rc = SQLITE_OK;
   22952   const int nMin = 512;
   22953   const int nMax = 65536;
   22954   const int nMaxBlk = 4;
   22955   u32 pgsz = 0;
   22956   int iBlk = 0;
   22957   u8 *aPg = 0;
   22958   u8 *aTmp = 0;
   22959   int nBlk = 0;
   22960 
   22961   aPg = (u8*)sqlite3_malloc(2*nMax);
   22962   if( aPg==0 ) return SQLITE_NOMEM;
   22963   aTmp = &aPg[nMax];
   22964 
   22965   nBlk = (nSz+nMax-1)/nMax;
   22966   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
   22967 
   22968   do {
   22969     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
   22970       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
   22971       memset(aPg, 0, nMax);
   22972       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
   22973       if( rc==SQLITE_OK ){
   22974         int pgsz2;
   22975         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
   22976           int iOff;
   22977           for(iOff=0; iOff<nMax; iOff+=pgsz2){
   22978             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
   22979               pgsz = pgsz2;
   22980               break;
   22981             }
   22982           }
   22983         }
   22984       }
   22985     }
   22986     if( pgsz>(u32)p->detected_pgsz ){
   22987       p->detected_pgsz = pgsz;
   22988       p->nReserve = nReserve;
   22989     }
   22990     if( nReserve==0 ) break;
   22991     nReserve = 0;
   22992   }while( 1 );
   22993 
   22994   p->detected_pgsz = pgsz;
   22995   sqlite3_free(aPg);
   22996   return rc;
   22997 }
   22998 
   22999 /*
   23000 ** The xRead() method of the wrapper VFS. This is used to intercept calls
   23001 ** to read page 1 of the input database.
   23002 */
   23003 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
   23004   int rc = SQLITE_OK;
   23005   if( pFd->pMethods==&recover_methods ){
   23006     pFd->pMethods = recover_g.pMethods;
   23007     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
   23008     if( nByte==16 ){
   23009       sqlite3_randomness(16, aBuf);
   23010     }else
   23011     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
   23012       /* Ensure that the database has a valid header file. The only fields
   23013       ** that really matter to recovery are:
   23014       **
   23015       **   + Database page size (16-bits at offset 16)
   23016       **   + Size of db in pages (32-bits at offset 28)
   23017       **   + Database encoding (32-bits at offset 56)
   23018       **
   23019       ** Also preserved are:
   23020       **
   23021       **   + first freelist page (32-bits at offset 32)
   23022       **   + size of freelist (32-bits at offset 36)
   23023       **   + the wal-mode flags (16-bits at offset 18)
   23024       **
   23025       ** We also try to preserve the auto-vacuum, incr-value, user-version
   23026       ** and application-id fields - all 32 bit quantities at offsets
   23027       ** 52, 60, 64 and 68. All other fields are set to known good values.
   23028       **
   23029       ** Byte offset 105 should also contain the page-size as a 16-bit
   23030       ** integer.
   23031       */
   23032       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
   23033       u8 aHdr[108] = {
   23034         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
   23035         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
   23036         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
   23037         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
   23038         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
   23039         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
   23040         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
   23041         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
   23042         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
   23043         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   23044         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   23045         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   23046         0x00, 0x2e, 0x5b, 0x30,
   23047 
   23048         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
   23049       };
   23050       u8 *a = (u8*)aBuf;
   23051 
   23052       u32 pgsz = recoverGetU16(&a[16]);
   23053       u32 nReserve = a[20];
   23054       u32 enc = recoverGetU32(&a[56]);
   23055       u32 dbsz = 0;
   23056       i64 dbFileSize = 0;
   23057       int ii;
   23058       sqlite3_recover *p = recover_g.p;
   23059 
   23060       if( pgsz==0x01 ) pgsz = 65536;
   23061       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
   23062 
   23063       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
   23064         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
   23065       }
   23066       if( p->detected_pgsz ){
   23067         pgsz = p->detected_pgsz;
   23068         nReserve = p->nReserve;
   23069       }
   23070 
   23071       if( pgsz ){
   23072         dbsz = dbFileSize / pgsz;
   23073       }
   23074       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
   23075         enc = SQLITE_UTF8;
   23076       }
   23077 
   23078       sqlite3_free(p->pPage1Cache);
   23079       p->pPage1Cache = 0;
   23080       p->pPage1Disk = 0;
   23081 
   23082       p->pgsz = nByte;
   23083       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
   23084       if( p->pPage1Cache ){
   23085         p->pPage1Disk = &p->pPage1Cache[nByte];
   23086         memcpy(p->pPage1Disk, aBuf, nByte);
   23087         aHdr[18] = a[18];
   23088         aHdr[19] = a[19];
   23089         recoverPutU32(&aHdr[28], dbsz);
   23090         recoverPutU32(&aHdr[56], enc);
   23091         recoverPutU16(&aHdr[105], pgsz-nReserve);
   23092         if( pgsz==65536 ) pgsz = 1;
   23093         recoverPutU16(&aHdr[16], pgsz);
   23094         aHdr[20] = nReserve;
   23095         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
   23096           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
   23097         }
   23098         memcpy(aBuf, aHdr, sizeof(aHdr));
   23099         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
   23100 
   23101         memcpy(p->pPage1Cache, aBuf, nByte);
   23102       }else{
   23103         rc = p->errCode;
   23104       }
   23105 
   23106     }
   23107     pFd->pMethods = &recover_methods;
   23108   }else{
   23109     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
   23110   }
   23111   return rc;
   23112 }
   23113 
   23114 /*
   23115 ** Used to make sqlite3_io_methods wrapper methods less verbose.
   23116 */
   23117 #define RECOVER_VFS_WRAPPER(code)                         \
   23118   int rc = SQLITE_OK;                                     \
   23119   if( pFd->pMethods==&recover_methods ){                  \
   23120     pFd->pMethods = recover_g.pMethods;                   \
   23121     rc = code;                                            \
   23122     pFd->pMethods = &recover_methods;                     \
   23123   }else{                                                  \
   23124     rc = code;                                            \
   23125   }                                                       \
   23126   return rc;
   23127 
   23128 /*
   23129 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
   23130 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
   23131 ** method on the lower level VFS, then reinstall the wrapper before returning.
   23132 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
   23133 */
   23134 static int recoverVfsWrite(
   23135   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
   23136 ){
   23137   RECOVER_VFS_WRAPPER (
   23138       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
   23139   );
   23140 }
   23141 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
   23142   RECOVER_VFS_WRAPPER (
   23143       pFd->pMethods->xTruncate(pFd, size)
   23144   );
   23145 }
   23146 static int recoverVfsSync(sqlite3_file *pFd, int flags){
   23147   RECOVER_VFS_WRAPPER (
   23148       pFd->pMethods->xSync(pFd, flags)
   23149   );
   23150 }
   23151 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
   23152   RECOVER_VFS_WRAPPER (
   23153       pFd->pMethods->xFileSize(pFd, pSize)
   23154   );
   23155 }
   23156 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
   23157   RECOVER_VFS_WRAPPER (
   23158       pFd->pMethods->xLock(pFd, eLock)
   23159   );
   23160 }
   23161 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
   23162   RECOVER_VFS_WRAPPER (
   23163       pFd->pMethods->xUnlock(pFd, eLock)
   23164   );
   23165 }
   23166 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
   23167   RECOVER_VFS_WRAPPER (
   23168       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
   23169   );
   23170 }
   23171 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
   23172   RECOVER_VFS_WRAPPER (
   23173     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
   23174   );
   23175 }
   23176 static int recoverVfsSectorSize(sqlite3_file *pFd){
   23177   RECOVER_VFS_WRAPPER (
   23178       pFd->pMethods->xSectorSize(pFd)
   23179   );
   23180 }
   23181 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
   23182   RECOVER_VFS_WRAPPER (
   23183       pFd->pMethods->xDeviceCharacteristics(pFd)
   23184   );
   23185 }
   23186 static int recoverVfsShmMap(
   23187   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
   23188 ){
   23189   RECOVER_VFS_WRAPPER (
   23190       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
   23191   );
   23192 }
   23193 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
   23194   RECOVER_VFS_WRAPPER (
   23195       pFd->pMethods->xShmLock(pFd, offset, n, flags)
   23196   );
   23197 }
   23198 static void recoverVfsShmBarrier(sqlite3_file *pFd){
   23199   if( pFd->pMethods==&recover_methods ){
   23200     pFd->pMethods = recover_g.pMethods;
   23201     pFd->pMethods->xShmBarrier(pFd);
   23202     pFd->pMethods = &recover_methods;
   23203   }else{
   23204     pFd->pMethods->xShmBarrier(pFd);
   23205   }
   23206 }
   23207 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
   23208   RECOVER_VFS_WRAPPER (
   23209       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
   23210   );
   23211 }
   23212 
   23213 static int recoverVfsFetch(
   23214   sqlite3_file *pFd,
   23215   sqlite3_int64 iOff,
   23216   int iAmt,
   23217   void **pp
   23218 ){
   23219   (void)pFd;
   23220   (void)iOff;
   23221   (void)iAmt;
   23222   *pp = 0;
   23223   return SQLITE_OK;
   23224 }
   23225 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
   23226   (void)pFd;
   23227   (void)iOff;
   23228   (void)p;
   23229   return SQLITE_OK;
   23230 }
   23231 
   23232 /*
   23233 ** Install the VFS wrapper around the file-descriptor open on the input
   23234 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
   23235 ** when this function is called.
   23236 */
   23237 static void recoverInstallWrapper(sqlite3_recover *p){
   23238   sqlite3_file *pFd = 0;
   23239   assert( recover_g.pMethods==0 );
   23240   recoverAssertMutexHeld();
   23241   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
   23242   assert( pFd==0 || pFd->pMethods!=&recover_methods );
   23243   if( pFd && pFd->pMethods ){
   23244     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
   23245     recover_g.pMethods = pFd->pMethods;
   23246     recover_g.p = p;
   23247     recover_methods.iVersion = iVersion;
   23248     pFd->pMethods = &recover_methods;
   23249   }
   23250 }
   23251 
   23252 /*
   23253 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
   23254 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
   23255 ** held when this function is called.
   23256 */
   23257 static void recoverUninstallWrapper(sqlite3_recover *p){
   23258   sqlite3_file *pFd = 0;
   23259   recoverAssertMutexHeld();
   23260   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
   23261   if( pFd && pFd->pMethods ){
   23262     pFd->pMethods = recover_g.pMethods;
   23263     recover_g.pMethods = 0;
   23264     recover_g.p = 0;
   23265   }
   23266 }
   23267 
   23268 /*
   23269 ** This function does the work of a single sqlite3_recover_step() call. It
   23270 ** is guaranteed that the handle is not in an error state when this
   23271 ** function is called.
   23272 */
   23273 static void recoverStep(sqlite3_recover *p){
   23274   assert( p && p->errCode==SQLITE_OK );
   23275   switch( p->eState ){
   23276     case RECOVER_STATE_INIT: {
   23277       int bUseWrapper = 1;
   23278       /* This is the very first call to sqlite3_recover_step() on this object.
   23279       */
   23280       recoverSqlCallback(p, "BEGIN");
   23281       recoverSqlCallback(p, "PRAGMA writable_schema = on");
   23282       recoverSqlCallback(p, "PRAGMA foreign_keys = off");
   23283 
   23284       recoverEnterMutex();
   23285 
   23286       /* Open the output database. And register required virtual tables and
   23287       ** user functions with the new handle. */
   23288       recoverOpenOutput(p);
   23289 
   23290       /* Attempt to open a transaction and read page 1 of the input database.
   23291       ** Two attempts may be made - one with a wrapper installed to ensure
   23292       ** that the database header is sane, and then if that attempt returns
   23293       ** SQLITE_NOTADB, then again with no wrapper. The second attempt is
   23294       ** required for encrypted databases.  */
   23295       if( p->errCode==SQLITE_OK ){
   23296         do{
   23297           p->errCode = SQLITE_OK;
   23298           if( bUseWrapper ) recoverInstallWrapper(p);
   23299 
   23300           /* Open a transaction on the input database. */
   23301           sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
   23302           recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
   23303           recoverExec(p, p->dbIn, "BEGIN");
   23304           if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
   23305           recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
   23306           recoverTransferSettings(p);
   23307           recoverOpenRecovery(p);
   23308           recoverCacheSchema(p);
   23309 
   23310           if( bUseWrapper ) recoverUninstallWrapper(p);
   23311         }while( p->errCode==SQLITE_NOTADB
   23312              && (bUseWrapper--)
   23313              && SQLITE_OK==sqlite3_exec(p->dbIn, "ROLLBACK", 0, 0, 0)
   23314         );
   23315       }
   23316 
   23317       recoverLeaveMutex();
   23318       recoverExec(p, p->dbOut, "BEGIN");
   23319       recoverWriteSchema1(p);
   23320       p->eState = RECOVER_STATE_WRITING;
   23321       break;
   23322     }
   23323 
   23324     case RECOVER_STATE_WRITING: {
   23325       if( p->w1.pTbls==0 ){
   23326         recoverWriteDataInit(p);
   23327       }
   23328       if( SQLITE_DONE==recoverWriteDataStep(p) ){
   23329         recoverWriteDataCleanup(p);
   23330         if( p->zLostAndFound ){
   23331           p->eState = RECOVER_STATE_LOSTANDFOUND1;
   23332         }else{
   23333           p->eState = RECOVER_STATE_SCHEMA2;
   23334         }
   23335       }
   23336       break;
   23337     }
   23338 
   23339     case RECOVER_STATE_LOSTANDFOUND1: {
   23340       if( p->laf.pUsed==0 ){
   23341         recoverLostAndFound1Init(p);
   23342       }
   23343       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
   23344         p->eState = RECOVER_STATE_LOSTANDFOUND2;
   23345       }
   23346       break;
   23347     }
   23348     case RECOVER_STATE_LOSTANDFOUND2: {
   23349       if( p->laf.pAllAndParent==0 ){
   23350         recoverLostAndFound2Init(p);
   23351       }
   23352       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
   23353         p->eState = RECOVER_STATE_LOSTANDFOUND3;
   23354       }
   23355       break;
   23356     }
   23357 
   23358     case RECOVER_STATE_LOSTANDFOUND3: {
   23359       if( p->laf.pInsert==0 ){
   23360         recoverLostAndFound3Init(p);
   23361       }
   23362       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
   23363         p->eState = RECOVER_STATE_SCHEMA2;
   23364       }
   23365       break;
   23366     }
   23367 
   23368     case RECOVER_STATE_SCHEMA2: {
   23369       int rc = SQLITE_OK;
   23370 
   23371       recoverWriteSchema2(p);
   23372       p->eState = RECOVER_STATE_DONE;
   23373 
   23374       /* If no error has occurred, commit the write transaction on the output
   23375       ** database. Regardless of whether or not an error has occurred, make
   23376       ** an attempt to end the read transaction on the input database.  */
   23377       recoverExec(p, p->dbOut, "COMMIT");
   23378       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
   23379       if( p->errCode==SQLITE_OK ) p->errCode = rc;
   23380 
   23381       recoverSqlCallback(p, "PRAGMA writable_schema = off");
   23382       recoverSqlCallback(p, "COMMIT");
   23383       p->eState = RECOVER_STATE_DONE;
   23384       recoverFinalCleanup(p);
   23385       break;
   23386     };
   23387 
   23388     case RECOVER_STATE_DONE: {
   23389       /* no-op */
   23390       break;
   23391     };
   23392   }
   23393 }
   23394 
   23395 
   23396 /*
   23397 ** This is a worker function that does the heavy lifting for both init
   23398 ** functions:
   23399 **
   23400 **     sqlite3_recover_init()
   23401 **     sqlite3_recover_init_sql()
   23402 **
   23403 ** All this function does is allocate space for the recover handle and
   23404 ** take copies of the input parameters. All the real work is done within
   23405 ** sqlite3_recover_run().
   23406 */
   23407 sqlite3_recover *recoverInit(
   23408   sqlite3* db,
   23409   const char *zDb,
   23410   const char *zUri,               /* Output URI for _recover_init() */
   23411   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
   23412   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
   23413 ){
   23414   sqlite3_recover *pRet = 0;
   23415   int nDb = 0;
   23416   int nUri = 0;
   23417   int nByte = 0;
   23418 
   23419   if( zDb==0 ){ zDb = "main"; }
   23420 
   23421   nDb = recoverStrlen(zDb);
   23422   nUri = recoverStrlen(zUri);
   23423 
   23424   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
   23425   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
   23426   if( pRet ){
   23427     memset(pRet, 0, nByte);
   23428     pRet->dbIn = db;
   23429     pRet->zDb = (char*)&pRet[1];
   23430     pRet->zUri = &pRet->zDb[nDb+1];
   23431     memcpy(pRet->zDb, zDb, nDb);
   23432     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
   23433     pRet->xSql = xSql;
   23434     pRet->pSqlCtx = pSqlCtx;
   23435     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
   23436   }
   23437 
   23438   return pRet;
   23439 }
   23440 
   23441 /*
   23442 ** Initialize a recovery handle that creates a new database containing
   23443 ** the recovered data.
   23444 */
   23445 sqlite3_recover *sqlite3_recover_init(
   23446   sqlite3* db,
   23447   const char *zDb,
   23448   const char *zUri
   23449 ){
   23450   return recoverInit(db, zDb, zUri, 0, 0);
   23451 }
   23452 
   23453 /*
   23454 ** Initialize a recovery handle that returns recovered data in the
   23455 ** form of SQL statements via a callback.
   23456 */
   23457 sqlite3_recover *sqlite3_recover_init_sql(
   23458   sqlite3* db,
   23459   const char *zDb,
   23460   int (*xSql)(void*, const char*),
   23461   void *pSqlCtx
   23462 ){
   23463   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
   23464 }
   23465 
   23466 /*
   23467 ** Return the handle error message, if any.
   23468 */
   23469 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
   23470   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
   23471 }
   23472 
   23473 /*
   23474 ** Return the handle error code.
   23475 */
   23476 int sqlite3_recover_errcode(sqlite3_recover *p){
   23477   return p ? p->errCode : SQLITE_NOMEM;
   23478 }
   23479 
   23480 /*
   23481 ** Configure the handle.
   23482 */
   23483 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
   23484   int rc = SQLITE_OK;
   23485   if( p==0 ){
   23486     rc = SQLITE_NOMEM;
   23487   }else if( p->eState!=RECOVER_STATE_INIT ){
   23488     rc = SQLITE_MISUSE;
   23489   }else{
   23490     switch( op ){
   23491       case 789:
   23492         /* This undocumented magic configuration option is used to set the
   23493         ** name of the auxiliary database that is ATTACH-ed to the database
   23494         ** connection and used to hold state information during the
   23495         ** recovery process.  This option is for debugging use only and
   23496         ** is subject to change or removal at any time. */
   23497         sqlite3_free(p->zStateDb);
   23498         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
   23499         break;
   23500 
   23501       case SQLITE_RECOVER_LOST_AND_FOUND: {
   23502         const char *zArg = (const char*)pArg;
   23503         sqlite3_free(p->zLostAndFound);
   23504         if( zArg ){
   23505           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
   23506         }else{
   23507           p->zLostAndFound = 0;
   23508         }
   23509         break;
   23510       }
   23511 
   23512       case SQLITE_RECOVER_FREELIST_CORRUPT:
   23513         p->bFreelistCorrupt = *(int*)pArg;
   23514         break;
   23515 
   23516       case SQLITE_RECOVER_ROWIDS:
   23517         p->bRecoverRowid = *(int*)pArg;
   23518         break;
   23519 
   23520       case SQLITE_RECOVER_SLOWINDEXES:
   23521         p->bSlowIndexes = *(int*)pArg;
   23522         break;
   23523 
   23524       default:
   23525         rc = SQLITE_NOTFOUND;
   23526         break;
   23527     }
   23528   }
   23529 
   23530   return rc;
   23531 }
   23532 
   23533 /*
   23534 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
   23535 ** no error has occurred but database recovery is not finished, SQLITE_DONE
   23536 ** if database recovery has been successfully completed, or an SQLite
   23537 ** error code if an error has occurred.
   23538 */
   23539 int sqlite3_recover_step(sqlite3_recover *p){
   23540   if( p==0 ) return SQLITE_NOMEM;
   23541   if( p->errCode==SQLITE_OK ) recoverStep(p);
   23542   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
   23543     return SQLITE_DONE;
   23544   }
   23545   return p->errCode;
   23546 }
   23547 
   23548 /*
   23549 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
   23550 ** else an SQLite error code.
   23551 */
   23552 int sqlite3_recover_run(sqlite3_recover *p){
   23553   while( SQLITE_OK==sqlite3_recover_step(p) );
   23554   return sqlite3_recover_errcode(p);
   23555 }
   23556 
   23557 
   23558 /*
   23559 ** Free all resources associated with the recover handle passed as the only
   23560 ** argument. The results of using a handle with any sqlite3_recover_**
   23561 ** API function after it has been passed to this function are undefined.
   23562 **
   23563 ** A copy of the value returned by the first call made to sqlite3_recover_run()
   23564 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
   23565 ** not been called on this handle.
   23566 */
   23567 int sqlite3_recover_finish(sqlite3_recover *p){
   23568   int rc;
   23569   if( p==0 ){
   23570     rc = SQLITE_NOMEM;
   23571   }else{
   23572     recoverFinalCleanup(p);
   23573     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
   23574       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
   23575       if( p->errCode==SQLITE_OK ) p->errCode = rc;
   23576     }
   23577     rc = p->errCode;
   23578     sqlite3_free(p->zErrMsg);
   23579     sqlite3_free(p->zStateDb);
   23580     sqlite3_free(p->zLostAndFound);
   23581     sqlite3_free(p->pPage1Cache);
   23582     sqlite3_free(p);
   23583   }
   23584   return rc;
   23585 }
   23586 
   23587 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
   23588 
   23589 /************************* End ext/recover/sqlite3recover.c ********************/
   23590 # endif /* SQLITE_HAVE_SQLITE3R */
   23591 #endif
   23592 #ifdef SQLITE_SHELL_EXTSRC
   23593 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
   23594 #endif
   23595 
   23596 #if defined(SQLITE_ENABLE_SESSION)
   23597 /*
   23598 ** State information for a single open session
   23599 */
   23600 typedef struct OpenSession OpenSession;
   23601 struct OpenSession {
   23602   char *zName;             /* Symbolic name for this session */
   23603   int nFilter;             /* Number of xFilter rejection GLOB patterns */
   23604   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
   23605   sqlite3_session *p;      /* The open session */
   23606 };
   23607 #endif
   23608 
   23609 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   23610 typedef struct ExpertInfo ExpertInfo;
   23611 struct ExpertInfo {
   23612   sqlite3expert *pExpert;
   23613   int bVerbose;
   23614 };
   23615 #endif
   23616 
   23617 /* All the parameters that determine how to render query results.
   23618 */
   23619 typedef struct Mode {
   23620   u8 autoExplain;        /* Automatically turn on .explain mode */
   23621   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
   23622   u8 autoEQPtrace;       /* autoEQP is in trace mode */
   23623   u8 scanstatsOn;        /* True to display scan stats before each finalize */
   23624   u8 bAutoScreenWidth;   /* Using the TTY to determine screen width */
   23625   u8 mFlags;             /* MFLG_ECHO, MFLG_CRLF, etc. */
   23626   u8 eMode;              /* One of the MODE_ values */
   23627   sqlite3_qrf_spec spec; /* Spec to be passed into QRF */
   23628 } Mode;
   23629 
   23630 /* Flags for Mode.mFlags */
   23631 #define MFLG_ECHO  0x01  /* Echo inputs to output */
   23632 #define MFLG_CRLF  0x02  /* Use CR/LF output line endings */
   23633 #define MFLG_HDR   0x04  /* .header used to change headers on/off */
   23634 
   23635 
   23636 /*
   23637 ** State information about the database connection is contained in an
   23638 ** instance of the following structure.
   23639 */
   23640 typedef struct ShellState ShellState;
   23641 struct ShellState {
   23642   sqlite3 *db;           /* The database */
   23643   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
   23644   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
   23645   u8 nEqpLevel;          /* Depth of the EQP output graph */
   23646   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
   23647   u8 bSafeMode;          /* True to prohibit unsafe operations */
   23648   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
   23649   u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
   23650   unsigned statsOn;      /* True to display memory stats before each finalize */
   23651   unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
   23652   u8 nPopOutput;         /* Revert .output settings when reaching zero */
   23653   u8 nPopMode;           /* Revert .mode settings when reaching zero */
   23654   u8 enableTimer;        /* Enable the timer.  2: permanently 1: only once */
   23655   int inputNesting;      /* Track nesting level of .read and other redirects */
   23656   double prevTimer;      /* Last reported timer value */
   23657   double tmProgress;     /* --timeout option for .progress */
   23658   i64 lineno;            /* Line number of last line read from in */
   23659   const char *zInFile;   /* Name of the input file */
   23660   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
   23661   FILE *in;              /* Read commands from this stream */
   23662   FILE *out;             /* Write results here */
   23663   FILE *traceOut;        /* Output for sqlite3_trace() */
   23664   int nErr;              /* Number of errors seen */
   23665   int writableSchema;    /* True if PRAGMA writable_schema=ON */
   23666   int nCheck;            /* Number of ".check" commands run */
   23667   unsigned nProgress;    /* Number of progress callbacks encountered */
   23668   unsigned mxProgress;   /* Maximum progress callbacks before failing */
   23669   unsigned flgProgress;  /* Flags for the progress callback */
   23670   unsigned shellFlgs;    /* Various flags */
   23671   unsigned nTestRun;     /* Number of test cases run */
   23672   unsigned nTestErr;     /* Number of test cases that failed */
   23673   sqlite3_int64 szMax;   /* --maxsize argument to .open */
   23674   char *zDestTable;      /* Name of destination table when MODE_Insert */
   23675   char *zTempFile;       /* Temporary file that might need deleting */
   23676   char *zErrPrefix;      /* Alternative error message prefix */
   23677   char zTestcase[30];    /* Name of current test case */
   23678   char outfile[FILENAME_MAX]; /* Filename for *out */
   23679   sqlite3_stmt *pStmt;   /* Current statement if any. */
   23680   FILE *pLog;            /* Write log output here */
   23681   Mode mode;             /* Current display mode */
   23682   Mode modePrior;        /* Backup */
   23683   struct SavedMode {     /* Ability to define custom mode configurations */
   23684     char *zTag;            /* Name of this saved mode */
   23685     Mode mode;              /* The saved mode */
   23686   } *aSavedModes;        /* Array of saved .mode settings. system malloc() */
   23687   int nSavedModes;       /* Number of saved .mode settings */
   23688   struct AuxDb {         /* Storage space for auxiliary database connections */
   23689     sqlite3 *db;               /* Connection pointer */
   23690     const char *zDbFilename;   /* Filename used to open the connection */
   23691     char *zFreeOnClose;        /* Free this memory allocation on close */
   23692 #if defined(SQLITE_ENABLE_SESSION)
   23693     int nSession;              /* Number of active sessions */
   23694     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
   23695 #endif
   23696   } aAuxDb[5],           /* Array of all database connections */
   23697     *pAuxDb;             /* Currently active database connection */
   23698   char *zNonce;          /* Nonce for temporary safe-mode escapes */
   23699 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   23700   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
   23701 #endif
   23702   struct DotCmdLine {    /* Info about arguments to a dot-command */
   23703     const char *zOrig;      /* Original text of the dot-command */
   23704     char *zCopy;            /* Copy of zOrig, from malloc() */
   23705     int nAlloc;             /* Size of allocates for arrays below */
   23706     int nArg;               /* Number of argument slots actually used */
   23707     char **azArg;           /* Pointer to each argument, dequoted */
   23708     int *aiOfst;            /* Offset into zOrig[] for start of each arg */
   23709     char *abQuot;           /* True if the argment was originally quoted */
   23710   } dot;
   23711 #ifdef SQLITE_SHELL_FIDDLE
   23712   struct {
   23713     const char * zInput; /* Input string from wasm/JS proxy */
   23714     const char * zPos;   /* Cursor pos into zInput */
   23715     const char * zDefaultDbName; /* Default name for db file */
   23716   } wasm;
   23717 #endif
   23718 };
   23719 
   23720 #ifdef SQLITE_SHELL_FIDDLE
   23721 static ShellState shellState;
   23722 #endif
   23723 
   23724 
   23725 /* Allowed values for ShellState.mode.autoEQP
   23726 */
   23727 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
   23728 #define AUTOEQP_on       1           /* Automatic EQP is on */
   23729 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
   23730 #define AUTOEQP_full     3           /* Show full EXPLAIN */
   23731 
   23732 /* Allowed values for ShellState.openMode
   23733 */
   23734 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
   23735 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
   23736 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
   23737 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
   23738 #define SHELL_OPEN_DESERIALIZE 4      /* Open using sqlite3_deserialize() */
   23739 #define SHELL_OPEN_HEXDB       5      /* Use "dbtotxt" output as data source */
   23740 
   23741 /* Allowed values for ShellState.eTraceType
   23742 */
   23743 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
   23744 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
   23745 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
   23746 
   23747 /* Bits in the ShellState.flgProgress variable */
   23748 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
   23749 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
   23750                                    ** callback limit is reached, and for each
   23751                                    ** top-level SQL statement */
   23752 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
   23753 #define SHELL_PROGRESS_TMOUT 0x08  /* Stop after tmProgress seconds */
   23754 
   23755 /* Names of values for Mode.spec.eEsc and Mode.spec.eText
   23756 */
   23757 static const char *qrfEscNames[] = { "auto", "off", "ascii", "symbol" };
   23758 static const char *qrfQuoteNames[] =
   23759       { "off","off","sql","hex","csv","tcl","json","relaxed"};
   23760 
   23761 /*
   23762 ** These are the allowed shellFlgs values
   23763 */
   23764 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
   23765 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
   23766 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
   23767 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
   23768 #define SHFLG_NoErrLineno    0x00000010 /* Omit line numbers from error msgs */
   23769 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
   23770 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
   23771 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
   23772 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
   23773 
   23774 /*
   23775 ** Macros for testing and setting shellFlgs
   23776 */
   23777 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
   23778 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
   23779 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
   23780 
   23781 /*
   23782 ** These are the allowed values for Mode.eMode.  There is a lot of overlap
   23783 ** between these values and the Mode.spec.eStyle values, but they are not
   23784 ** one-to-one, and thus need to be tracked separately.
   23785 */
   23786 #define MODE_Ascii     0  /* Use ASCII unit and record separators (0x1F/0x1E) */
   23787 #define MODE_Box       1  /* Unicode box-drawing characters */
   23788 #define MODE_C         2  /* Comma-separated list of C-strings */
   23789 #define MODE_Column    3  /* One record per line in neat columns */
   23790 #define MODE_Count     4  /* Output only a count of the rows of output */
   23791 #define MODE_Csv       5  /* Quote strings, numbers are plain */
   23792 #define MODE_Html      6  /* Generate an XHTML table */
   23793 #define MODE_Insert    7  /* Generate SQL "insert" statements */
   23794 #define MODE_JAtom     8  /* Comma-separated list of JSON atoms */
   23795 #define MODE_JObject   9  /* One JSON object per row */
   23796 #define MODE_Json     10  /* Output JSON */
   23797 #define MODE_Line     11  /* One column per line.  Blank line between records */
   23798 #define MODE_List     12  /* One record per line with a separator */
   23799 #define MODE_Markdown 13  /* Markdown formatting */
   23800 #define MODE_Off      14  /* No query output shown */
   23801 #define MODE_Psql     15  /* Similar to psql */
   23802 #define MODE_QBox     16  /* BOX with SQL-quoted content */
   23803 #define MODE_Quote    17  /* Quote values as for SQL */
   23804 #define MODE_Split    18  /* Split-column mode */
   23805 #define MODE_Table    19  /* MySQL-style table formatting */
   23806 #define MODE_Tabs     20  /* Tab-separated values */
   23807 #define MODE_Tcl      21  /* Space-separated list of TCL strings */
   23808 #define MODE_Www      22  /* Full web-page output */
   23809 
   23810 #define MODE_BUILTIN  22  /* Maximum built-in mode */
   23811 #define MODE_BATCH    50  /* Default mode for batch processing */
   23812 #define MODE_TTY      51  /* Default mode for interactive processing */
   23813 #define MODE_USER     75  /* First user-defined mode */
   23814 #define MODE_N_USER   25  /* Maximum number of user-defined modes */
   23815 
   23816 /*
   23817 ** Information about built-in display modes
   23818 */
   23819 typedef struct ModeInfo ModeInfo;
   23820 struct ModeInfo {
   23821   char zName[9];         /* Symbolic name of the mode */
   23822   unsigned char eCSep;   /* Column separator */
   23823   unsigned char eRSep;   /* Row separator */
   23824   unsigned char eNull;   /* Null representation */
   23825   unsigned char eText;   /* Default text encoding */
   23826   unsigned char eHdr;    /* Default header encoding. */
   23827   unsigned char eBlob;   /* Default blob encoding. */
   23828   unsigned char bHdr;    /* Show headers by default.  0: n/a, 1: no 2: yes */
   23829   unsigned char eStyle;  /* Underlying QRF style */
   23830   unsigned char eCx;     /* 0: other, 1: line, 2: columnar */
   23831   unsigned char mFlg;    /* Flags. 1=border-off 2=split-column */
   23832 };
   23833 
   23834 /* String constants used by built-in modes */
   23835 static const char *aModeStr[] =
   23836   /* 0    1       2       3       4     5        6        7        8    */
   23837    { 0,   "\n",   "|",    " ",    ",",  "\r\n",  "\036",  "\037",  "\t",
   23838      "",  "NULL", "null", "\"\"", ": ",                                   };
   23839   /* 9    10      11      12      13                                    */
   23840 
   23841 static const ModeInfo aModeInfo[] = {
   23842 /*   zName      eCSep  eRSep eNull eText eHdr eBlob bHdr eStyle eCx mFlg */
   23843   { "ascii",    7,     6,    9,    1,    1,    0,   1,   12,    0,  0 },
   23844   { "box",      0,     0,    9,    1,    1,    0,   2,   1,     2,  0 },
   23845   { "c",        4,     1,    10,   5,    5,    4,   1,   12,    0,  0 },
   23846   { "column",   0,     0,    9,    1,    1,    0,   2,   2,     2,  0 },
   23847   { "count",    0,     0,    0,    0,    0,    0,   0,   3,     0,  0 },
   23848   { "csv",      4,     5,    9,    3,    3,    0,   1,   12,    0,  0 },
   23849   { "html",     0,     0,    9,    4,    4,    0,   2,   7,     0,  0 },
   23850   { "insert",   0,     0,    10,   2,    2,    0,   1,   8,     0,  0 },
   23851   { "jatom",    4,     1,    11,   6,    6,    0,   1,   12,    0,  0 },
   23852   { "jobject",  0,     1,    11,   6,    6,    0,   0,   10,    0,  0 },
   23853   { "json",     0,     0,    11,   6,    6,    0,   0,   9,     0,  0 },
   23854   { "line",     13,    1,    9,    1,    1,    0,   0,   11,    1,  0 },
   23855   { "list",     2,     1,    9,    1,    1,    0,   1,   12,    0,  0 },
   23856   { "markdown", 0,     0,    9,    1,    1,    0,   2,   13,    2,  0 },
   23857   { "off",      0,     0,    0,    0,    0,    0,   0,   14,    0,  0 },
   23858   { "psql",     0,     0,    9,    1,    1,    0,   2,   19,    2,  1 },
   23859   { "qbox",     0,     0,    10,   2,    1,    0,   2,   1,     2,  0 },
   23860   { "quote",    4,     1,    10,   2,    2,    0,   1,   12,    0,  0 },
   23861   { "split",    0,     0,    9,    1,    1,    0,   1,   2,     2,  2 },
   23862   { "table",    0,     0,    9,    1,    1,    0,   2,   19,    2,  0 },
   23863   { "tabs",     8,     1,    9,    3,    3,    0,   1,   12,    0,  0 },
   23864   { "tcl",      3,     1,    12,   5,    5,    4,   1,   12,    0,  0 },
   23865   { "www",      0,     0,    9,    4,    4,    0,   2,   7,     0,  0 }
   23866 };     /*       |     /     /      |     /    /     |    |       \
   23867        **       |    /     /       |    /    /      |    |        \_ 2: columnar
   23868        ** Index into aModeStr[]    |   /    /       |    |           1: line
   23869        **                          |  /    /        |    |           0: other
   23870        **                          | /    /         |     \
   23871        **           text encoding  |/     |    show |      \
   23872        **      v-------------------'      |   hdrs? |       The QRF style
   23873        **      0: n/a                blob |   v-----'
   23874        **      1: plain        v_---------'   0: n/a
   23875        **      2: sql          0: auto        1: no
   23876        **      3: csv          1: as-text     2: yes
   23877        **      4: html         2: sql
   23878        **      5: c            3: hex
   23879        **      6: json         4: c
   23880        **                      5: json
   23881        **                      6: size
   23882        ******************************************************************/
   23883 /*
   23884 ** These are the column/row/line separators used by the various
   23885 ** import/export modes.
   23886 */
   23887 #define SEP_Column    "|"
   23888 #define SEP_Row       "\n"
   23889 #define SEP_Tab       "\t"
   23890 #define SEP_Space     " "
   23891 #define SEP_Comma     ","
   23892 #define SEP_CrLf      "\r\n"
   23893 #define SEP_Unit      "\x1F"
   23894 #define SEP_Record    "\x1E"
   23895 
   23896 /*
   23897 ** Default values for the various QRF limits
   23898 */
   23899 #ifndef DFLT_CHAR_LIMIT
   23900 # define DFLT_CHAR_LIMIT  300
   23901 #endif
   23902 #ifndef DFLT_LINE_LIMIT
   23903 # define DFLT_LINE_LIMIT  5
   23904 #endif
   23905 #ifndef DFLT_TITLE_LIMIT
   23906 # define DFLT_TITLE_LIMIT 20
   23907 #endif
   23908 #ifndef DFLT_MULTI_INSERT
   23909 # define DFLT_MULTI_INSERT 3000
   23910 #endif
   23911 
   23912 /*
   23913 ** If the following flag is set, then command execution stops
   23914 ** at an error if we are not interactive.
   23915 */
   23916 static int bail_on_error = 0;
   23917 
   23918 /*
   23919 ** Treat stdin as an interactive input if the following variable
   23920 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
   23921 */
   23922 static int stdin_is_interactive = 1;
   23923 
   23924 /*
   23925 ** Treat stdout like a TTY if true.
   23926 */
   23927 static int stdout_is_console = 1;
   23928 
   23929 /*
   23930 ** Use this value as the width of the output device.  Or, figure it
   23931 ** out at runtime if the value is negative.  Or use a default width
   23932 ** if this value is zero.
   23933 */
   23934 static int stdout_tty_width = -1;
   23935 
   23936 /*
   23937 ** The following is the open SQLite database.  We make a pointer
   23938 ** to this database a static variable so that it can be accessed
   23939 ** by the SIGINT handler to interrupt database processing.
   23940 */
   23941 static sqlite3 *globalDb = 0;
   23942 
   23943 /*
   23944 ** True if an interrupt (Control-C) has been received.
   23945 */
   23946 static volatile int seenInterrupt = 0;
   23947 
   23948 /*
   23949 ** This is the name of our program. It is set in main(), used
   23950 ** in a number of other places, mostly for error messages.
   23951 */
   23952 static char *Argv0;
   23953 
   23954 /*
   23955 ** Prompt strings. Initialized in main. Settable with
   23956 **   .prompt main continue
   23957 */
   23958 #define PROMPT_LEN_MAX 128
   23959 /* First line prompt.   default: "sqlite> " */
   23960 static char mainPrompt[PROMPT_LEN_MAX];
   23961 /* Continuation prompt. default: "   ...> " */
   23962 static char continuePrompt[PROMPT_LEN_MAX];
   23963 
   23964 /*
   23965 ** Write I/O traces to the following stream.
   23966 */
   23967 #ifdef SQLITE_ENABLE_IOTRACE
   23968 static FILE *iotrace = 0;
   23969 #endif
   23970 
   23971 /*
   23972 ** Output routines that are able to redirect to memory rather than
   23973 ** doing actually I/O.
   23974 **                                                Works like.
   23975 **                                                --------------
   23976 **   cli_printf(FILE*, const char*, ...);         fprintf()
   23977 **   cli_puts(const char*, FILE*);                fputs()
   23978 **   cli_vprintf(FILE*, const char*, va_list);    vfprintf()
   23979 **
   23980 ** These are just thin wrappers with the following added semantics:
   23981 ** If the file-scope variable cli_output_capture is not NULL, and
   23982 ** if the FILE* argument is stdout or stderr, then rather than
   23983 ** writing to stdout/stdout, append the text to the cli_output_capture
   23984 ** variable.
   23985 **
   23986 ** The cli_exit(int) routine works like exit() except that it
   23987 ** first dumps any capture output to stdout.
   23988 */
   23989 static sqlite3_str *cli_output_capture = 0;
   23990 static int cli_printf(FILE *out, const char *zFormat, ...){
   23991   va_list ap;
   23992   int rc;
   23993   va_start(ap,zFormat);
   23994   if( cli_output_capture && (out==stdout || out==stderr) ){
   23995     sqlite3_str_vappendf(cli_output_capture, zFormat, ap);
   23996     rc = 1;
   23997   }else{
   23998     rc = sqlite3_vfprintf(out, zFormat, ap);
   23999   }
   24000   va_end(ap);
   24001   return rc;
   24002 }
   24003 static int cli_puts(const char *zText, FILE *out){
   24004   if( cli_output_capture && (out==stdout || out==stderr) ){
   24005     sqlite3_str_appendall(cli_output_capture, zText);
   24006     return 1;
   24007   }
   24008   return sqlite3_fputs(zText, out);
   24009 }
   24010 #if 0 /* Not currently used - available if we need it later */
   24011 static int cli_vprintf(FILE *out, const char *zFormat, va_list ap){
   24012   if( cli_output_capture && (out==stdout || out==stderr) ){
   24013     sqlite3_str_vappendf(cli_output_capture, zFormat, ap);
   24014     return 1;
   24015   }else{
   24016     return sqlite3_vfprintf(out, zFormat, ap);
   24017   }
   24018 }
   24019 #endif
   24020 static void cli_exit(int rc){
   24021   if( cli_output_capture ){
   24022     char *z = sqlite3_str_finish(cli_output_capture);
   24023     sqlite3_fputs(z, stdout);
   24024     fflush(stdout);
   24025   }
   24026   exit(rc);
   24027 }
   24028 
   24029 
   24030 #define eputz(z) cli_puts(z,stderr)
   24031 #define sputz(fp,z) cli_puts(z,fp)
   24032 
   24033 /* A version of strcmp() that works with NULL values */
   24034 static int cli_strcmp(const char *a, const char *b){
   24035   if( a==0 ) a = "";
   24036   if( b==0 ) b = "";
   24037   return strcmp(a,b);
   24038 }
   24039 static int cli_strncmp(const char *a, const char *b, size_t n){
   24040   if( a==0 ) a = "";
   24041   if( b==0 ) b = "";
   24042   return strncmp(a,b,n);
   24043 }
   24044 
   24045 /* Return the current wall-clock time in microseconds since the
   24046 ** Unix epoch (1970-01-01T00:00:00Z)
   24047 */
   24048 static sqlite3_int64 timeOfDay(void){
   24049 #if defined(_WIN64) && _WIN32_WINNT >= _WIN32_WINNT_WIN8
   24050   sqlite3_uint64 t;
   24051   FILETIME tm;
   24052   GetSystemTimePreciseAsFileTime(&tm);
   24053   t =  ((u64)tm.dwHighDateTime<<32) | (u64)tm.dwLowDateTime;
   24054   t += 116444736000000000LL;
   24055   t /= 10;
   24056   return t;
   24057 #elif defined(_WIN32)
   24058   static sqlite3_vfs *clockVfs = 0;
   24059   sqlite3_int64 t;
   24060   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
   24061   if( clockVfs==0 ) return 0;  /* Never actually happens */
   24062   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
   24063     clockVfs->xCurrentTimeInt64(clockVfs, &t);
   24064   }else{
   24065     double r;
   24066     clockVfs->xCurrentTime(clockVfs, &r);
   24067     t = (sqlite3_int64)(r*86400000.0);
   24068   }
   24069   return t*1000;
   24070 #else
   24071   struct timeval sNow;
   24072   (void)gettimeofday(&sNow,0);
   24073   return ((i64)sNow.tv_sec)*1000000 + sNow.tv_usec;
   24074 #endif
   24075 }
   24076 
   24077 
   24078 
   24079 /* This is variant of the standard-library strncpy() routine with the
   24080 ** one change that the destination string is always zero-terminated, even
   24081 ** if there is no zero-terminator in the first n-1 characters of the source
   24082 ** string.
   24083 */
   24084 static char *shell_strncpy(char *dest, const char *src, size_t n){
   24085   size_t i;
   24086   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
   24087   dest[i] = 0;
   24088   return dest;
   24089 }
   24090 
   24091 /*
   24092 ** strcpy() workalike to squelch an unwarranted link-time warning
   24093 ** from OpenBSD.
   24094 */
   24095 static void shell_strcpy(char *dest, const char *src){
   24096   while( (*(dest++) = *(src++))!=0 ){}
   24097 }
   24098 
   24099 /*
   24100 ** Optionally disable dynamic continuation prompt.
   24101 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
   24102 ** or open parentheses level if non-zero, or continuation prompt as set.
   24103 ** This facility interacts with the scanner and process_input() where the
   24104 ** below 5 macros are used.
   24105 */
   24106 #ifdef SQLITE_OMIT_DYNAPROMPT
   24107 # define CONTINUATION_PROMPT continuePrompt
   24108 # define CONTINUE_PROMPT_RESET
   24109 # define CONTINUE_PROMPT_AWAITS(p,s)
   24110 # define CONTINUE_PROMPT_AWAITC(p,c)
   24111 # define CONTINUE_PAREN_INCR(p,n)
   24112 # define CONTINUE_PROMPT_PSTATE 0
   24113 typedef void *t_NoDynaPrompt;
   24114 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
   24115 #else
   24116 # define CONTINUATION_PROMPT dynamicContinuePrompt()
   24117 # define CONTINUE_PROMPT_RESET \
   24118   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
   24119 # define CONTINUE_PROMPT_AWAITS(p,s) \
   24120   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
   24121 # define CONTINUE_PROMPT_AWAITC(p,c) \
   24122   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
   24123 # define CONTINUE_PAREN_INCR(p,n) \
   24124   if(p && stdin_is_interactive) (trackParenLevel(p,n))
   24125 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
   24126 typedef struct DynaPrompt *t_DynaPromptRef;
   24127 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
   24128 
   24129 static struct DynaPrompt {
   24130   char dynamicPrompt[PROMPT_LEN_MAX];
   24131   char acAwait[2];
   24132   int inParenLevel;
   24133   char *zScannerAwaits;
   24134 } dynPrompt = { {0}, {0}, 0, 0 };
   24135 
   24136 /* Record parenthesis nesting level change, or force level to 0. */
   24137 static void trackParenLevel(struct DynaPrompt *p, int ni){
   24138   p->inParenLevel += ni;
   24139   if( ni==0 ) p->inParenLevel = 0;
   24140   p->zScannerAwaits = 0;
   24141 }
   24142 
   24143 /* Record that a lexeme is opened, or closed with args==0. */
   24144 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
   24145   if( s!=0 || c==0 ){
   24146     p->zScannerAwaits = s;
   24147     p->acAwait[0] = 0;
   24148   }else{
   24149     p->acAwait[0] = c;
   24150     p->zScannerAwaits = p->acAwait;
   24151   }
   24152 }
   24153 
   24154 /* Upon demand, derive the continuation prompt to display. */
   24155 static char *dynamicContinuePrompt(void){
   24156   if( continuePrompt[0]==0
   24157       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
   24158     return continuePrompt;
   24159   }else{
   24160     if( dynPrompt.zScannerAwaits ){
   24161       size_t ncp = strlen(continuePrompt);
   24162       size_t ndp = strlen(dynPrompt.zScannerAwaits);
   24163       if( ndp > ncp-3 ) return continuePrompt;
   24164       shell_strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
   24165       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
   24166       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
   24167               PROMPT_LEN_MAX-4);
   24168     }else{
   24169       if( dynPrompt.inParenLevel>9 ){
   24170         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
   24171       }else if( dynPrompt.inParenLevel<0 ){
   24172         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
   24173       }else{
   24174         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
   24175         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
   24176       }
   24177       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
   24178                     PROMPT_LEN_MAX-4);
   24179     }
   24180   }
   24181   return dynPrompt.dynamicPrompt;
   24182 }
   24183 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
   24184 
   24185 /* Indicate out-of-memory and exit. */
   24186 static void shell_out_of_memory(void){
   24187   eputz("Error: out of memory\n");
   24188   cli_exit(1);
   24189 }
   24190 
   24191 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
   24192 ** out-of-memory error.
   24193 */
   24194 static void shell_check_oom(const void *p){
   24195   if( p==0 ) shell_out_of_memory();
   24196 }
   24197 
   24198 /*
   24199 ** This routine works like printf in that its first argument is a
   24200 ** format string and subsequent arguments are values to be substituted
   24201 ** in place of % fields.  The result of formatting this string
   24202 ** is written to iotrace.
   24203 */
   24204 #ifdef SQLITE_ENABLE_IOTRACE
   24205 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
   24206   va_list ap;
   24207   char *z;
   24208   if( iotrace==0 ) return;
   24209   va_start(ap, zFormat);
   24210   z = sqlite3_vmprintf(zFormat, ap);
   24211   va_end(ap);
   24212   cli_printf(iotrace, "%s", z);
   24213   sqlite3_free(z);
   24214 }
   24215 #endif
   24216 
   24217 /*
   24218 ** Compute a string length that is limited to what can be stored in
   24219 ** lower 30 bits of a 32-bit signed integer.
   24220 */
   24221 static int strlen30(const char *z){
   24222   size_t n;
   24223   if( z==0 ) return 0;
   24224   n = strlen(z);
   24225   return n>0x3fffffff ? 0x3fffffff : (int)n;
   24226 }
   24227 
   24228 /*
   24229 ** Return open FILE * if zFile exists, can be opened for read
   24230 ** and is an ordinary file or a character stream source.
   24231 ** Otherwise return 0.
   24232 */
   24233 static FILE * openChrSource(const char *zFile){
   24234 #if defined(_WIN32) || defined(WIN32)
   24235   struct __stat64 x = {0};
   24236 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
   24237   /* On Windows, open first, then check the stream nature. This order
   24238   ** is necessary because _stat() and sibs, when checking a named pipe,
   24239   ** effectively break the pipe as its supplier sees it. */
   24240   FILE *rv = sqlite3_fopen(zFile, "rb");
   24241   if( rv==0 ) return 0;
   24242   if( _fstat64(_fileno(rv), &x) != 0
   24243       || !STAT_CHR_SRC(x.st_mode)){
   24244     fclose(rv);
   24245     rv = 0;
   24246   }
   24247   return rv;
   24248 #else
   24249   struct stat x = {0};
   24250   int rc = stat(zFile, &x);
   24251 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
   24252   if( rc!=0 ) return 0;
   24253   if( STAT_CHR_SRC(x.st_mode) ){
   24254     return sqlite3_fopen(zFile, "rb");
   24255   }else{
   24256     return 0;
   24257   }
   24258 #endif
   24259 #undef STAT_CHR_SRC
   24260 }
   24261 
   24262 /*
   24263 ** This routine reads a line of text from FILE in, stores
   24264 ** the text in memory obtained from malloc() and returns a pointer
   24265 ** to the text.  NULL is returned at end of file, or if malloc()
   24266 ** fails, or if the length of the line is longer than about a gigabyte.
   24267 **
   24268 ** If zLine is not NULL then it is a malloced buffer returned from
   24269 ** a previous call to this routine that may be reused.
   24270 */
   24271 static char *local_getline(char *zLine, FILE *in){
   24272   int nLine = zLine==0 ? 0 : 100;
   24273   int n = 0;
   24274 
   24275   while( 1 ){
   24276     if( n+100>nLine ){
   24277       if( nLine>=1073741773 ){
   24278         free(zLine);
   24279         return 0;
   24280       }
   24281       nLine = nLine*2 + 100;
   24282       zLine = realloc(zLine, nLine);
   24283       shell_check_oom(zLine);
   24284     }
   24285     if( sqlite3_fgets(&zLine[n], nLine - n, in)==0 ){
   24286       if( n==0 ){
   24287         free(zLine);
   24288         return 0;
   24289       }
   24290       zLine[n] = 0;
   24291       break;
   24292     }
   24293     while( zLine[n] ) n++;
   24294     if( n>0 && zLine[n-1]=='\n' ){
   24295       n--;
   24296       if( n>0 && zLine[n-1]=='\r' ) n--;
   24297       zLine[n] = 0;
   24298       break;
   24299     }
   24300   }
   24301   return zLine;
   24302 }
   24303 
   24304 /*
   24305 ** Retrieve a single line of input text.
   24306 **
   24307 ** If in==0 then read from standard input and prompt before each line.
   24308 ** If isContinuation is true, then a continuation prompt is appropriate.
   24309 ** If isContinuation is zero, then the main prompt should be used.
   24310 **
   24311 ** If zPrior is not NULL then it is a buffer from a prior call to this
   24312 ** routine that can be reused.
   24313 **
   24314 ** The result is stored in space obtained from malloc() and must either
   24315 ** be freed by the caller or else passed back into this routine via the
   24316 ** zPrior argument for reuse.
   24317 */
   24318 #ifndef SQLITE_SHELL_FIDDLE
   24319 static char *one_input_line(ShellState *p, char *zPrior, int isContinuation){
   24320   char *zPrompt;
   24321   char *zResult;
   24322   FILE *in = p->in;
   24323   if( in!=0 ){
   24324     zResult = local_getline(zPrior, in);
   24325   }else{
   24326     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
   24327 #if SHELL_USE_LOCAL_GETLINE
   24328     sputz(stdout, zPrompt);
   24329     fflush(stdout);
   24330     do{
   24331       zResult = local_getline(zPrior, stdin);
   24332       zPrior = 0;
   24333       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
   24334       if( zResult==0 ) sqlite3_sleep(50);
   24335     }while( zResult==0 && seenInterrupt>0 );
   24336 #else
   24337     free(zPrior);
   24338     zResult = shell_readline(zPrompt);
   24339     while( zResult==0 ){
   24340       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
   24341       sqlite3_sleep(50);
   24342       if( seenInterrupt==0 ) break;
   24343       zResult = shell_readline("");
   24344     }
   24345     if( zResult && *zResult ) shell_add_history(zResult);
   24346 #endif
   24347   }
   24348   return zResult;
   24349 }
   24350 #endif /* !SQLITE_SHELL_FIDDLE */
   24351 
   24352 /*
   24353 ** Return the value of a hexadecimal digit.  Return -1 if the input
   24354 ** is not a hex digit.
   24355 */
   24356 static int hexDigitValue(char c){
   24357   if( c>='0' && c<='9' ) return c - '0';
   24358   if( c>='a' && c<='f' ) return c - 'a' + 10;
   24359   if( c>='A' && c<='F' ) return c - 'A' + 10;
   24360   return -1;
   24361 }
   24362 
   24363 /*
   24364 ** Interpret zArg as an integer value, possibly with suffixes.
   24365 **
   24366 ** If the value specified by zArg is outside the range of values that
   24367 ** can be represented using a 64-bit twos-complement integer, then return
   24368 ** the nearest representable value.
   24369 */
   24370 static sqlite3_int64 integerValue(const char *zArg){
   24371   sqlite3_uint64 v = 0;
   24372   static const struct { char *zSuffix; unsigned int iMult; } aMult[] = {
   24373     { "KiB", 1024 },
   24374     { "MiB", 1024*1024 },
   24375     { "GiB", 1024*1024*1024 },
   24376     { "KB",  1000 },
   24377     { "MB",  1000000 },
   24378     { "GB",  1000000000 },
   24379     { "K",   1000 },
   24380     { "M",   1000000 },
   24381     { "G",   1000000000 },
   24382   };
   24383   int i;
   24384   int isNeg = 0;
   24385   if( zArg[0]=='-' ){
   24386     isNeg = 1;
   24387     zArg++;
   24388   }else if( zArg[0]=='+' ){
   24389     zArg++;
   24390   }
   24391   if( zArg[0]=='0' && zArg[1]=='x' ){
   24392     int x;
   24393     zArg += 2;
   24394     while( (x = hexDigitValue(zArg[0]))>=0 ){
   24395       if( v > 0x0fffffffffffffffULL ) goto integer_overflow;
   24396       v = (v<<4) + x;
   24397       zArg++;
   24398     }
   24399   }else{
   24400     while( IsDigit(zArg[0]) ){
   24401       if( v>=922337203685477580LL ){
   24402         if( v>922337203685477580LL || zArg[0]>='8' ) goto integer_overflow;
   24403       }
   24404       v = v*10 + (zArg[0] - '0');
   24405       zArg++;
   24406     }
   24407   }
   24408   for(i=0; i<ArraySize(aMult); i++){
   24409     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
   24410       if( 0x7fffffffffffffffULL/aMult[i].iMult < v ) goto integer_overflow;
   24411       v *= aMult[i].iMult;
   24412       break;
   24413     }
   24414   }
   24415   if( isNeg && v>0x7fffffffffffffffULL ) goto integer_overflow;
   24416   return isNeg? -(sqlite3_int64)v : (sqlite3_int64)v;
   24417 integer_overflow:
   24418   return isNeg ? (i64)0x8000000000000000LL : 0x7fffffffffffffffLL;
   24419 }
   24420 
   24421 /*
   24422 ** A variable length string to which one can append text.
   24423 */
   24424 typedef struct ShellText ShellText;
   24425 struct ShellText {
   24426   char *zTxt;       /* The text */
   24427   i64 n;            /* Number of bytes of zTxt[] actually used */
   24428   i64 nAlloc;       /* Number of bytes allocated for zTxt[] */
   24429 };
   24430 
   24431 /*
   24432 ** Initialize and destroy a ShellText object
   24433 */
   24434 static void initText(ShellText *p){
   24435   memset(p, 0, sizeof(*p));
   24436 }
   24437 static void freeText(ShellText *p){
   24438   sqlite3_free(p->zTxt);
   24439   initText(p);
   24440 }
   24441 
   24442 /* zIn is either a pointer to a NULL-terminated string in memory obtained
   24443 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
   24444 ** added to zIn, and the result returned in memory obtained from malloc().
   24445 ** zIn, if it was not NULL, is freed.
   24446 **
   24447 ** If the third argument, quote, is not '\0', then it is used as a
   24448 ** quote character for zAppend.
   24449 */
   24450 static void appendText(ShellText *p, const char *zAppend, char quote){
   24451   i64 len;
   24452   i64 i;
   24453   i64 nAppend = strlen30(zAppend);
   24454 
   24455   len = nAppend+p->n+1;
   24456   if( quote ){
   24457     len += 2;
   24458     for(i=0; i<nAppend; i++){
   24459       if( zAppend[i]==quote ) len++;
   24460     }
   24461   }
   24462 
   24463   if( p->zTxt==0 || p->n+len>=p->nAlloc ){
   24464     p->nAlloc = p->nAlloc*2 + len + 20;
   24465     p->zTxt = sqlite3_realloc64(p->zTxt, p->nAlloc);
   24466     shell_check_oom(p->zTxt);
   24467   }
   24468 
   24469   if( quote ){
   24470     char *zCsr = p->zTxt+p->n;
   24471     *zCsr++ = quote;
   24472     for(i=0; i<nAppend; i++){
   24473       *zCsr++ = zAppend[i];
   24474       if( zAppend[i]==quote ) *zCsr++ = quote;
   24475     }
   24476     *zCsr++ = quote;
   24477     p->n = (i64)(zCsr - p->zTxt);
   24478     *zCsr = '\0';
   24479   }else{
   24480     memcpy(p->zTxt+p->n, zAppend, nAppend);
   24481     p->n += nAppend;
   24482     p->zTxt[p->n] = '\0';
   24483   }
   24484 }
   24485 
   24486 /*
   24487 ** Attempt to determine if identifier zName needs to be quoted, either
   24488 ** because it contains non-alphanumeric characters, or because it is an
   24489 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
   24490 ** that quoting is required.
   24491 **
   24492 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
   24493 */
   24494 static char quoteChar(const char *zName){
   24495   int i;
   24496   if( zName==0 ) return '"';
   24497   if( !IsAlpha(zName[0]) && zName[0]!='_' ) return '"';
   24498   for(i=0; zName[i]; i++){
   24499     if( !IsAlnum(zName[i]) && zName[i]!='_' ) return '"';
   24500   }
   24501   return sqlite3_keyword_check(zName, i) ? '"' : 0;
   24502 }
   24503 
   24504 /*
   24505 ** Construct a fake object name and column list to describe the structure
   24506 ** of the view, virtual table, or table valued function zSchema.zName.
   24507 **
   24508 ** The returned string comes from sqlite3_mprintf() and should be freed
   24509 ** by the caller using sqlite3_free().
   24510 */
   24511 static char *shellFakeSchema(
   24512   sqlite3 *db,            /* The database connection containing the vtab */
   24513   const char *zSchema,    /* Schema of the database holding the vtab */
   24514   const char *zName       /* The name of the virtual table */
   24515 ){
   24516   sqlite3_stmt *pStmt = 0;
   24517   char *zSql;
   24518   ShellText s;
   24519   char cQuote;
   24520   char *zDiv = "(";
   24521   int nRow = 0;
   24522 
   24523   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
   24524                          zSchema ? zSchema : "main", zName);
   24525   shell_check_oom(zSql);
   24526   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   24527   sqlite3_free(zSql);
   24528   initText(&s);
   24529   if( zSchema ){
   24530     cQuote = quoteChar(zSchema);
   24531     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
   24532     appendText(&s, zSchema, cQuote);
   24533     appendText(&s, ".", 0);
   24534   }
   24535   cQuote = quoteChar(zName);
   24536   appendText(&s, zName, cQuote);
   24537   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   24538     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
   24539     nRow++;
   24540     appendText(&s, zDiv, 0);
   24541     zDiv = ",";
   24542     if( zCol==0 ) zCol = "";
   24543     cQuote = quoteChar(zCol);
   24544     appendText(&s, zCol, cQuote);
   24545   }
   24546   appendText(&s, ")", 0);
   24547   sqlite3_finalize(pStmt);
   24548   if( nRow==0 ){
   24549     freeText(&s);
   24550     s.zTxt = 0;
   24551   }
   24552   return s.zTxt;
   24553 }
   24554 
   24555 /*
   24556 ** SQL function:  strtod(X)
   24557 **
   24558 ** Use the C-library strtod() function to convert string X into a double.
   24559 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
   24560 ** routines against the C-library.
   24561 */
   24562 static void shellStrtod(
   24563   sqlite3_context *pCtx,
   24564   int nVal,
   24565   sqlite3_value **apVal
   24566 ){
   24567   char *z = (char*)sqlite3_value_text(apVal[0]);
   24568   UNUSED_PARAMETER(nVal);
   24569   if( z==0 ) return;
   24570   sqlite3_result_double(pCtx, strtod(z,0));
   24571 }
   24572 
   24573 /*
   24574 ** SQL function:  dtostr(X)
   24575 **
   24576 ** Use the C-library printf() function to convert real value X into a string.
   24577 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
   24578 ** routines against the C-library.
   24579 */
   24580 static void shellDtostr(
   24581   sqlite3_context *pCtx,
   24582   int nVal,
   24583   sqlite3_value **apVal
   24584 ){
   24585   double r = sqlite3_value_double(apVal[0]);
   24586   int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
   24587   char z[400];
   24588   if( n<1 ) n = 1;
   24589   if( n>350 ) n = 350;
   24590   sprintf(z, "%#+.*e", n, r);
   24591   sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
   24592 }
   24593 
   24594 /*
   24595 ** SQL function:  shell_add_schema(S,X)
   24596 **
   24597 ** Add the schema name X to the CREATE statement in S and return the result.
   24598 ** Examples:
   24599 **
   24600 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
   24601 **
   24602 ** Also works on
   24603 **
   24604 **    CREATE INDEX
   24605 **    CREATE UNIQUE INDEX
   24606 **    CREATE VIEW
   24607 **    CREATE TRIGGER
   24608 **    CREATE VIRTUAL TABLE
   24609 **
   24610 ** This UDF is used by the .schema command to insert the schema name of
   24611 ** attached databases into the middle of the sqlite_schema.sql field.
   24612 */
   24613 static void shellAddSchemaName(
   24614   sqlite3_context *pCtx,
   24615   int nVal,
   24616   sqlite3_value **apVal
   24617 ){
   24618   static const char *aPrefix[] = {
   24619      "TABLE",
   24620      "INDEX",
   24621      "UNIQUE INDEX",
   24622      "VIEW",
   24623      "TRIGGER",
   24624      "VIRTUAL TABLE"
   24625   };
   24626   int i = 0;
   24627   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
   24628   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
   24629   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
   24630   sqlite3 *db = sqlite3_context_db_handle(pCtx);
   24631   UNUSED_PARAMETER(nVal);
   24632   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
   24633     for(i=0; i<ArraySize(aPrefix); i++){
   24634       int n = strlen30(aPrefix[i]);
   24635       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
   24636         char *z = 0;
   24637         char *zFake = 0;
   24638         if( zSchema ){
   24639           char cQuote = quoteChar(zSchema);
   24640           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
   24641             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
   24642           }else{
   24643             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
   24644           }
   24645         }
   24646         if( zName
   24647          && aPrefix[i][0]=='V'
   24648          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
   24649         ){
   24650           if( z==0 ){
   24651             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
   24652           }else{
   24653             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
   24654           }
   24655           sqlite3_free(zFake);
   24656         }
   24657         if( z ){
   24658           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
   24659           return;
   24660         }
   24661       }
   24662     }
   24663   }
   24664   sqlite3_result_value(pCtx, apVal[0]);
   24665 }
   24666 
   24667 
   24668 /************************* BEGIN PERFORMANCE TIMER *****************************/
   24669 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
   24670 #include <sys/time.h>
   24671 #include <sys/resource.h>
   24672 /* VxWorks does not support getrusage() as far as we can determine */
   24673 #if defined(_WRS_KERNEL) || defined(__RTP__)
   24674 struct rusage {
   24675   struct timeval ru_utime; /* user CPU time used */
   24676   struct timeval ru_stime; /* system CPU time used */
   24677 };
   24678 #define getrusage(A,B) memset(B,0,sizeof(*B))
   24679 #endif
   24680 
   24681 /* Saved resource information for the beginning of an operation */
   24682 static struct rusage sBegin;  /* CPU time at start */
   24683 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
   24684 
   24685 /*
   24686 ** Begin timing an operation
   24687 */
   24688 static void beginTimer(ShellState *p){
   24689   if( p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0 ){
   24690     getrusage(RUSAGE_SELF, &sBegin);
   24691     iBegin = timeOfDay();
   24692   }
   24693 }
   24694 
   24695 /* Return the difference of two time_structs in seconds */
   24696 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
   24697   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
   24698          (double)(pEnd->tv_sec - pStart->tv_sec);
   24699 }
   24700 
   24701 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   24702 /* Return the time since the start of the timer in
   24703 ** seconds. */
   24704 static double elapseTime(ShellState *NotUsed){
   24705   (void)NotUsed;
   24706   if( iBegin==0 ) return 0.0;
   24707   return (timeOfDay() - iBegin)*0.000001;
   24708 }
   24709 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
   24710 
   24711 /*
   24712 ** Print the timing results.
   24713 */
   24714 static void endTimer(ShellState *p){
   24715   if( p->enableTimer ){
   24716     sqlite3_int64 iEnd = timeOfDay();
   24717     struct rusage sEnd;
   24718     getrusage(RUSAGE_SELF, &sEnd);
   24719     p->prevTimer = (iEnd - iBegin)*0.000001;
   24720     cli_printf(p->out, "Run Time: real %.6f user %.6f sys %.6f\n",
   24721           p->prevTimer,
   24722           timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
   24723           timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
   24724     if( p->enableTimer==1 ) p->enableTimer = 0;
   24725     iBegin = 0;
   24726   }
   24727 }
   24728 
   24729 #define BEGIN_TIMER(X) beginTimer(X)
   24730 #define END_TIMER(X)   endTimer(X)
   24731 #define ELAPSE_TIME(X) elapseTime(X)
   24732 #define HAS_TIMER 1
   24733 
   24734 #elif (defined(_WIN32) || defined(WIN32))
   24735 
   24736 /* Saved resource information for the beginning of an operation */
   24737 static HANDLE hProcess;
   24738 static FILETIME ftKernelBegin;
   24739 static FILETIME ftUserBegin;
   24740 static sqlite3_int64 ftWallBegin;
   24741 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
   24742                                     LPFILETIME, LPFILETIME);
   24743 static GETPROCTIMES getProcessTimesAddr = NULL;
   24744 
   24745 /*
   24746 ** Check to see if we have timer support.  Return 1 if necessary
   24747 ** support found (or found previously).
   24748 */
   24749 static int hasTimer(void){
   24750   if( getProcessTimesAddr ){
   24751     return 1;
   24752   } else {
   24753     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
   24754     ** versions. See if the version we are running on has it, and if it
   24755     ** does, save off a pointer to it and the current process handle.
   24756     */
   24757     hProcess = GetCurrentProcess();
   24758     if( hProcess ){
   24759       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
   24760       if( NULL != hinstLib ){
   24761         getProcessTimesAddr =
   24762             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
   24763         if( NULL != getProcessTimesAddr ){
   24764           return 1;
   24765         }
   24766         FreeLibrary(hinstLib);
   24767       }
   24768     }
   24769   }
   24770   return 0;
   24771 }
   24772 
   24773 /*
   24774 ** Begin timing an operation
   24775 */
   24776 static void beginTimer(ShellState *p){
   24777   if( (p->enableTimer || (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0)
   24778    && getProcessTimesAddr
   24779   ){
   24780     FILETIME ftCreation, ftExit;
   24781     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
   24782                         &ftKernelBegin,&ftUserBegin);
   24783     ftWallBegin = timeOfDay();
   24784   }
   24785 }
   24786 
   24787 /* Return the difference of two FILETIME structs in seconds */
   24788 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
   24789   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
   24790   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
   24791   return (double) ((i64End - i64Start) / 10000000.0);
   24792 }
   24793 
   24794 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   24795 /* Return the time since the start of the timer in
   24796 ** seconds. */
   24797 static double elapseTime(ShellState *NotUsed){
   24798   (void)NotUsed;
   24799   if( ftWallBegin==0 ) return 0.0;
   24800   return (timeOfDay() - ftWallBegin)*0.000001;
   24801 }
   24802 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
   24803 
   24804 /*
   24805 ** Print the timing results.
   24806 */
   24807 static void endTimer(ShellState *p){
   24808   if( p->enableTimer && getProcessTimesAddr){
   24809     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
   24810     sqlite3_int64 ftWallEnd = timeOfDay();
   24811     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
   24812     p->prevTimer = (ftWallEnd - ftWallBegin)*0.000001;
   24813 #ifdef _WIN64
   24814     /* microsecond precision on 64-bit windows */
   24815     cli_printf(p->out, "Run Time: real %.6f user %f sys %f\n",
   24816           p->prevTimer,
   24817           timeDiff(&ftUserBegin, &ftUserEnd),
   24818           timeDiff(&ftKernelBegin, &ftKernelEnd));
   24819 #else
   24820     /* millisecond precisino on 32-bit windows */
   24821     cli_printf(p->out, "Run Time: real %.3f user %.3f sys %.3f\n",
   24822           p->prevTimer,
   24823           timeDiff(&ftUserBegin, &ftUserEnd),
   24824           timeDiff(&ftKernelBegin, &ftKernelEnd));
   24825 #endif
   24826     if( p->enableTimer==1 ) p->enableTimer = 0;
   24827     ftWallBegin = 0;
   24828   }
   24829 }
   24830 
   24831 #define BEGIN_TIMER(X) beginTimer(X)
   24832 #define ELAPSE_TIME(X) elapseTime(X)
   24833 #define END_TIMER(X)   endTimer(X)
   24834 #define HAS_TIMER      hasTimer()
   24835 
   24836 #else
   24837 #define BEGIN_TIMER(X) /* no-op */
   24838 #define ELAPSE_TIME(X) 0.0
   24839 #define END_TIMER(X)   /*no-op*/
   24840 #define HAS_TIMER 0
   24841 #endif
   24842 /************************* END PERFORMANCE TIMER ******************************/
   24843 
   24844 /*
   24845 ** Clear a display mode, freeing any allocated memory that it
   24846 ** contains.
   24847 */
   24848 static void modeFree(Mode *p){
   24849   u8 autoExplain = p->autoExplain;
   24850   free(p->spec.aWidth);
   24851   free(p->spec.aAlign);
   24852   free(p->spec.zColumnSep);
   24853   free(p->spec.zRowSep);
   24854   free(p->spec.zTableName);
   24855   free(p->spec.zNull);
   24856   memset(p, 0, sizeof(*p));
   24857   p->spec.iVersion = 1;
   24858   p->autoExplain = autoExplain;
   24859 }
   24860 
   24861 /*
   24862 ** Duplicate Mode pSrc into pDest.  pDest is assumed to be
   24863 ** uninitialized prior to invoking this routine.
   24864 */
   24865 static void modeDup(Mode *pDest, Mode *pSrc){
   24866   memcpy(pDest, pSrc, sizeof(*pDest));
   24867   if( pDest->spec.aWidth ){
   24868     size_t sz = sizeof(pSrc->spec.aWidth[0]) * pSrc->spec.nWidth;
   24869     pDest->spec.aWidth = malloc( sz );
   24870     if( pDest->spec.aWidth ){
   24871       memcpy(pDest->spec.aWidth, pSrc->spec.aWidth, sz);
   24872     }else{
   24873       pDest->spec.nWidth = 0;
   24874     }
   24875   }
   24876   if( pDest->spec.aAlign ){
   24877     size_t sz = sizeof(pSrc->spec.aAlign[0]) * pSrc->spec.nAlign;
   24878     pDest->spec.aAlign = malloc( sz );
   24879     if( pDest->spec.aAlign ){
   24880       memcpy(pDest->spec.aAlign, pSrc->spec.aAlign, sz);
   24881     }else{
   24882       pDest->spec.nAlign = 0;
   24883     }
   24884   }
   24885   if( pDest->spec.zColumnSep ){
   24886     pDest->spec.zColumnSep = strdup(pSrc->spec.zColumnSep);
   24887   }
   24888   if( pDest->spec.zRowSep ){
   24889     pDest->spec.zRowSep = strdup(pSrc->spec.zRowSep);
   24890   }
   24891   if( pDest->spec.zTableName ){
   24892     pDest->spec.zTableName = strdup(pSrc->spec.zTableName);
   24893   }
   24894   if( pDest->spec.zNull ){
   24895     pDest->spec.zNull = strdup(pSrc->spec.zNull);
   24896   }
   24897 }
   24898 
   24899 /*
   24900 ** Set a string value to a copy of the zNew string in memory
   24901 ** obtained from system malloc().
   24902 */
   24903 static void modeSetStr(char **az, const char *zNew){
   24904   free(*az);
   24905   if( zNew==0 ){
   24906     *az = 0;
   24907   }else{
   24908     size_t n = strlen(zNew);
   24909     *az = malloc( n+1 );
   24910     if( *az ){
   24911       memcpy(*az, zNew, n+1 );
   24912     }
   24913   }
   24914 }
   24915 
   24916 /*
   24917 ** Change the mode to eMode
   24918 */
   24919 static void modeChange(ShellState *p, unsigned char eMode){
   24920   const ModeInfo *pI;
   24921   if( eMode<ArraySize(aModeInfo) ){
   24922     Mode *pM = &p->mode;
   24923     pI = &aModeInfo[eMode];
   24924     pM->eMode = eMode;
   24925     if( pI->eCSep ) modeSetStr(&pM->spec.zColumnSep, aModeStr[pI->eCSep]);
   24926     if( pI->eRSep ) modeSetStr(&pM->spec.zRowSep, aModeStr[pI->eRSep]);
   24927     if( pI->eNull ) modeSetStr(&pM->spec.zNull, aModeStr[pI->eNull]);
   24928     pM->spec.eText = pI->eText;
   24929     pM->spec.eBlob = pI->eBlob;
   24930     if( (pM->mFlags & MFLG_HDR)==0 ){
   24931       pM->spec.bTitles = pI->bHdr;
   24932     }
   24933     pM->spec.eTitle = pI->eHdr;
   24934     if( pI->mFlg & 0x01 ){
   24935       pM->spec.bBorder = QRF_No;
   24936     }else{
   24937       pM->spec.bBorder = QRF_Auto;
   24938     }
   24939     if( pI->mFlg & 0x02 ){
   24940       pM->spec.bSplitColumn = QRF_Yes;
   24941       pM->bAutoScreenWidth = 1;
   24942     }else{
   24943       pM->spec.bSplitColumn = QRF_No;
   24944     }
   24945   }else if( eMode>=MODE_USER && eMode-MODE_USER<p->nSavedModes ){
   24946     modeFree(&p->mode);
   24947     modeDup(&p->mode, &p->aSavedModes[eMode-MODE_USER].mode);
   24948   }else if( eMode==MODE_BATCH ){
   24949     u8 mFlags = p->mode.mFlags;
   24950     modeFree(&p->mode);
   24951     modeChange(p, MODE_List);
   24952     p->mode.mFlags = mFlags;
   24953   }else if( eMode==MODE_TTY ){
   24954     u8 mFlags = p->mode.mFlags;
   24955     modeFree(&p->mode);
   24956     modeChange(p, MODE_QBox);
   24957     p->mode.bAutoScreenWidth = 1;
   24958     p->mode.spec.eText = QRF_TEXT_Relaxed;
   24959     p->mode.spec.nCharLimit = DFLT_CHAR_LIMIT;
   24960     p->mode.spec.nLineLimit = DFLT_LINE_LIMIT;
   24961     p->mode.spec.bTextJsonb = QRF_Yes;
   24962     p->mode.spec.nTitleLimit = DFLT_TITLE_LIMIT;
   24963     p->mode.spec.nMultiInsert = DFLT_MULTI_INSERT;
   24964     p->mode.mFlags = mFlags;
   24965   }
   24966 }
   24967 
   24968 /*
   24969 ** Set the mode to the default.  It assumed that the mode has
   24970 ** already been freed and zeroed prior to calling this routine.
   24971 */
   24972 static void modeDefault(ShellState *p){
   24973   p->mode.spec.iVersion = 1;
   24974   p->mode.autoExplain = 1;
   24975   if( stdin_is_interactive || stdout_is_console ){
   24976     modeChange(p, MODE_TTY);
   24977   }else{
   24978     modeChange(p, MODE_BATCH);
   24979   }
   24980 }
   24981 
   24982 /*
   24983 ** Find the number of a display mode given its name.  Return -1 if
   24984 ** the name does not match any mode.
   24985 **
   24986 ** Saved modes are also searched if p!=NULL.  The number returned
   24987 ** for a saved mode is the index into the p->aSavedModes[] array
   24988 ** plus MODE_USER.
   24989 **
   24990 ** Two special mode names are also available: "batch" and "tty".
   24991 ** evaluate to the default mode for batch operation and interactive
   24992 ** operation on a TTY, respectively.
   24993 */
   24994 static int modeFind(ShellState *p, const char *zName){
   24995   int i;
   24996   for(i=0; i<ArraySize(aModeInfo); i++){
   24997     if( cli_strcmp(aModeInfo[i].zName,zName)==0 ) return i;
   24998   }
   24999   for(i=0; i<p->nSavedModes; i++){
   25000     if( cli_strcmp(p->aSavedModes[i].zTag,zName)==0 ) return i+MODE_USER;
   25001   }
   25002   if( strcmp(zName,"batch")==0 ) return MODE_BATCH;
   25003   if( strcmp(zName,"tty")==0 ) return MODE_TTY;
   25004   return -1;
   25005 }
   25006 
   25007 /*
   25008 ** Save or restore the current output mode
   25009 */
   25010 static void modePush(ShellState *p){
   25011   if( p->nPopMode==0 ){
   25012     modeFree(&p->modePrior);
   25013     modeDup(&p->modePrior,&p->mode);
   25014   }
   25015 }
   25016 static void modePop(ShellState *p){
   25017   if( p->modePrior.spec.iVersion>0 ){
   25018     modeFree(&p->mode);
   25019     p->mode = p->modePrior;
   25020     memset(&p->modePrior, 0, sizeof(p->modePrior));
   25021   }
   25022 }
   25023 
   25024 
   25025 /*
   25026 ** A callback for the sqlite3_log() interface.
   25027 */
   25028 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
   25029   ShellState *p = (ShellState*)pArg;
   25030   if( p->pLog==0 ) return;
   25031   cli_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
   25032   fflush(p->pLog);
   25033 }
   25034 
   25035 /*
   25036 ** SQL function:  shell_putsnl(X)
   25037 **
   25038 ** Write the text X to the screen (or whatever output is being directed)
   25039 ** adding a newline at the end, and then return X.
   25040 */
   25041 static void shellPutsFunc(
   25042   sqlite3_context *pCtx,
   25043   int nVal,
   25044   sqlite3_value **apVal
   25045 ){
   25046   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
   25047   (void)nVal;
   25048   cli_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
   25049   sqlite3_result_value(pCtx, apVal[0]);
   25050 }
   25051 
   25052 /*
   25053 ** Compute the name of the location of an input error in memory
   25054 ** obtained from sqlite3_malloc().
   25055 */
   25056 static char *shellErrorLocation(ShellState *p){
   25057   char *zLoc;
   25058   if( p->zErrPrefix ){
   25059     zLoc = sqlite3_mprintf("%s", p->zErrPrefix);
   25060   }else if( p->zInFile==0 || strcmp(p->zInFile,"<stdin>")==0){
   25061     zLoc = sqlite3_mprintf("line %lld:", p->lineno);
   25062   }else{
   25063     zLoc = sqlite3_mprintf("%s:%lld:", p->zInFile, p->lineno);
   25064   }
   25065   return zLoc;
   25066 }
   25067 
   25068 /*
   25069 ** If in safe mode, print an error message described by the arguments
   25070 ** and exit immediately.
   25071 */
   25072 static void failIfSafeMode(
   25073   ShellState *p,
   25074   const char *zErrMsg,
   25075   ...
   25076 ){
   25077   if( p->bSafeMode ){
   25078     va_list ap;
   25079     char *zMsg;
   25080     char *zLoc = shellErrorLocation(p);
   25081     va_start(ap, zErrMsg);
   25082     zMsg = sqlite3_vmprintf(zErrMsg, ap);
   25083     va_end(ap);
   25084     cli_printf(stderr, "%s %s\n", zLoc, zMsg);
   25085     cli_exit(1);
   25086   }
   25087 }
   25088 
   25089 /*
   25090 ** Issue an error message from a dot-command.
   25091 */
   25092 static void dotCmdError(
   25093   ShellState *p,       /* Shell state */
   25094   int iArg,            /* Index of argument on which error occurred */
   25095   const char *zBrief,  /* Brief (<20 character) error description */
   25096   const char *zDetail, /* Error details */
   25097   ...
   25098 ){
   25099   FILE *out = stderr;
   25100   char *zLoc = shellErrorLocation(p);
   25101   if( zBrief!=0 && iArg>=0 && iArg<p->dot.nArg ){
   25102     int i = p->dot.aiOfst[iArg];
   25103     int nPrompt = strlen30(zBrief) + 5;
   25104     cli_printf(out, "%s %s\n", zLoc, p->dot.zOrig);
   25105     if( i > nPrompt ){
   25106       cli_printf(out, "%s %*s%s ---^\n", zLoc, 1+i-nPrompt, "", zBrief);
   25107     }else{
   25108       cli_printf(out, "%s %*s^--- %s\n", zLoc, i, "", zBrief);
   25109     }
   25110   }
   25111   if( zDetail ){
   25112     char *zMsg;
   25113     va_list ap;
   25114     va_start(ap, zDetail);
   25115     zMsg = sqlite3_vmprintf(zDetail,ap);
   25116     va_end(ap);
   25117     cli_printf(out,"%s %s\n", zLoc, zMsg);
   25118     sqlite3_free(zMsg);
   25119   }
   25120   sqlite3_free(zLoc);
   25121 }
   25122 
   25123 
   25124 /*
   25125 ** SQL function:   edit(VALUE)
   25126 **                 edit(VALUE,EDITOR)
   25127 **
   25128 ** These steps:
   25129 **
   25130 **     (1) Write VALUE into a temporary file.
   25131 **     (2) Run program EDITOR on that temporary file.
   25132 **     (3) Read the temporary file back and return its content as the result.
   25133 **     (4) Delete the temporary file
   25134 **
   25135 ** If the EDITOR argument is omitted, use the value in the VISUAL
   25136 ** environment variable.  If still there is no EDITOR, through an error.
   25137 **
   25138 ** Also throw an error if the EDITOR program returns a non-zero exit code.
   25139 */
   25140 #ifndef SQLITE_NOHAVE_SYSTEM
   25141 static void editFunc(
   25142   sqlite3_context *context,
   25143   int argc,
   25144   sqlite3_value **argv
   25145 ){
   25146   const char *zEditor;
   25147   char *zTempFile = 0;
   25148   sqlite3 *db;
   25149   char *zCmd = 0;
   25150   int bBin;
   25151   int rc;
   25152   int hasCRLF = 0;
   25153   FILE *f = 0;
   25154   sqlite3_int64 sz;
   25155   sqlite3_int64 x;
   25156   unsigned char *p = 0;
   25157 
   25158   if( argc==2 ){
   25159     zEditor = (const char*)sqlite3_value_text(argv[1]);
   25160   }else{
   25161     zEditor = getenv("VISUAL");
   25162   }
   25163   if( zEditor==0 ){
   25164     sqlite3_result_error(context, "no editor for edit()", -1);
   25165     return;
   25166   }
   25167   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   25168     sqlite3_result_error(context, "NULL input to edit()", -1);
   25169     return;
   25170   }
   25171   db = sqlite3_context_db_handle(context);
   25172   zTempFile = 0;
   25173   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
   25174   if( zTempFile==0 ){
   25175     sqlite3_uint64 r = 0;
   25176     sqlite3_randomness(sizeof(r), &r);
   25177     zTempFile = sqlite3_mprintf("temp%llx", r);
   25178     if( zTempFile==0 ){
   25179       sqlite3_result_error_nomem(context);
   25180       return;
   25181     }
   25182   }
   25183   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
   25184   /* When writing the file to be edited, do \n to \r\n conversions on systems
   25185   ** that want \r\n line endings */
   25186   f = sqlite3_fopen(zTempFile, bBin ? "wb" : "w");
   25187   if( f==0 ){
   25188     sqlite3_result_error(context, "edit() cannot open temp file", -1);
   25189     goto edit_func_end;
   25190   }
   25191   sz = sqlite3_value_bytes(argv[0]);
   25192   if( bBin ){
   25193     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
   25194   }else{
   25195     const char *z = (const char*)sqlite3_value_text(argv[0]);
   25196     /* Remember whether or not the value originally contained \r\n */
   25197     if( z && strstr(z,"\r\n")!=0 ) hasCRLF = 1;
   25198     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
   25199   }
   25200   fclose(f);
   25201   f = 0;
   25202   if( x!=sz ){
   25203     sqlite3_result_error(context, "edit() could not write the whole file", -1);
   25204     goto edit_func_end;
   25205   }
   25206   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
   25207   if( zCmd==0 ){
   25208     sqlite3_result_error_nomem(context);
   25209     goto edit_func_end;
   25210   }
   25211   rc = system(zCmd);
   25212   sqlite3_free(zCmd);
   25213   if( rc ){
   25214     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
   25215     goto edit_func_end;
   25216   }
   25217   f = sqlite3_fopen(zTempFile, "rb");
   25218   if( f==0 ){
   25219     sqlite3_result_error(context,
   25220       "edit() cannot reopen temp file after edit", -1);
   25221     goto edit_func_end;
   25222   }
   25223   fseek(f, 0, SEEK_END);
   25224   sz = ftell(f);
   25225   rewind(f);
   25226   p = sqlite3_malloc64( sz+1 );
   25227   if( p==0 ){
   25228     sqlite3_result_error_nomem(context);
   25229     goto edit_func_end;
   25230   }
   25231   x = fread(p, 1, (size_t)sz, f);
   25232   fclose(f);
   25233   f = 0;
   25234   if( x!=sz ){
   25235     sqlite3_result_error(context, "could not read back the whole file", -1);
   25236     goto edit_func_end;
   25237   }
   25238   if( bBin ){
   25239     sqlite3_result_blob64(context, p, sz, sqlite3_free);
   25240   }else{
   25241     sqlite3_int64 i, j;
   25242     if( hasCRLF ){
   25243       /* If the original contains \r\n then do no conversions back to \n */
   25244     }else{
   25245       /* If the file did not originally contain \r\n then convert any new
   25246       ** \r\n back into \n */
   25247       p[sz] = 0;
   25248       for(i=j=0; i<sz; i++){
   25249         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
   25250         p[j++] = p[i];
   25251       }
   25252       sz = j;
   25253       p[sz] = 0;
   25254     }
   25255     sqlite3_result_text64(context, (const char*)p, sz,
   25256                           sqlite3_free, SQLITE_UTF8);
   25257   }
   25258   p = 0;
   25259 
   25260 edit_func_end:
   25261   if( f ) fclose(f);
   25262   unlink(zTempFile);
   25263   sqlite3_free(zTempFile);
   25264   sqlite3_free(p);
   25265 }
   25266 #endif /* SQLITE_NOHAVE_SYSTEM */
   25267 
   25268 /*
   25269 ** Set output mode to text or binary for Windows.
   25270 */
   25271 static void setCrlfMode(ShellState *p){
   25272 #ifdef _WIN32
   25273   if( p->mode.mFlags & MFLG_CRLF ){
   25274     sqlite3_fsetmode(p->out, _O_TEXT);
   25275   }else{
   25276     sqlite3_fsetmode(p->out, _O_BINARY);
   25277   }
   25278 #else
   25279   UNUSED_PARAMETER(p);
   25280 #endif
   25281 }
   25282 
   25283 /*
   25284 ** Find earliest of chars within s specified in zAny.
   25285 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
   25286 */
   25287 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
   25288   const char *pcFirst = 0;
   25289   if( ns == ~(size_t)0 ) ns = strlen(s);
   25290   while(*zAny){
   25291     const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
   25292     if( pc ){
   25293       pcFirst = pc;
   25294       ns = pcFirst - s;
   25295     }
   25296     ++zAny;
   25297   }
   25298   return pcFirst;
   25299 }
   25300 
   25301 /* Skip over as much z[] input char sequence as is valid UTF-8,
   25302 ** limited per nAccept char's or whole characters and containing
   25303 ** no char cn such that ((1<<cn) & ccm)!=0. On return, the
   25304 ** sequence z:return (inclusive:exclusive) is validated UTF-8.
   25305 ** Limit: nAccept>=0 => char count, nAccept<0 => character
   25306  */
   25307 static const char *zSkipValidUtf8(const char *z, int nAccept, long ccm){
   25308   int ng = (nAccept<0)? -nAccept : 0;
   25309   const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
   25310   assert(z!=0);
   25311   while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
   25312     unsigned char c = *(u8*)z;
   25313     if( c<0x7f ){
   25314       if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
   25315       ++z; /* ASCII */
   25316     }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
   25317     else{
   25318       const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
   25319       do{
   25320         if( pcLimit && zt >= pcLimit ) return z;
   25321         else{
   25322           char ct = *zt++;
   25323           if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
   25324             /* Trailing bytes are too few, too many, or invalid. */
   25325             return z;
   25326           }
   25327         }
   25328       } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
   25329       z = zt;
   25330     }
   25331   }
   25332   return z;
   25333 }
   25334 
   25335 
   25336 /*
   25337 ** Output the given string as a quoted according to C or TCL quoting rules.
   25338 */
   25339 static void output_c_string(FILE *out, const char *z){
   25340   char c;
   25341   static const char *zq = "\"";
   25342   static long ctrlMask = ~0L;
   25343   static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
   25344   char ace[3] = "\\?";
   25345   char cbsSay;
   25346   cli_puts(zq, out);
   25347   if( z==0 ) z = "";
   25348   while( *z!=0 ){
   25349     const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
   25350     const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
   25351     const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
   25352     if( pcEnd > z ){
   25353       cli_printf(out, "%.*s", (int)(pcEnd-z), z);
   25354     }
   25355     if( (c = *pcEnd)==0 ) break;
   25356     ++pcEnd;
   25357     switch( c ){
   25358     case '\\': case '"':
   25359       cbsSay = (char)c;
   25360       break;
   25361     case '\t': cbsSay = 't'; break;
   25362     case '\n': cbsSay = 'n'; break;
   25363     case '\r': cbsSay = 'r'; break;
   25364     case '\f': cbsSay = 'f'; break;
   25365     default: cbsSay = 0; break;
   25366     }
   25367     if( cbsSay ){
   25368       ace[1] = cbsSay;
   25369       cli_puts(ace, out);
   25370     }else if( !isprint(c&0xff) ){
   25371       cli_printf(out, "\\%03o", c&0xff);
   25372     }else{
   25373       ace[1] = (char)c;
   25374       cli_puts(ace+1, out);
   25375     }
   25376     z = pcEnd;
   25377   }
   25378   cli_puts(zq, out);
   25379 }
   25380 
   25381 /* Encode input string z[] as a C-language string literal and
   25382 ** append it to the sqlite3_str.  If z is NULL render and empty string.
   25383 */
   25384 static void append_c_string(sqlite3_str *out, const char *z){
   25385   char c;
   25386   static const char *zq = "\"";
   25387   static long ctrlMask = ~0L;
   25388   static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
   25389   char ace[3] = "\\?";
   25390   char cbsSay;
   25391   if( z==0 ) z = "";
   25392   sqlite3_str_appendall(out,zq);
   25393   while( *z!=0 ){
   25394     const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
   25395     const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
   25396     const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
   25397     if( pcEnd > z ){
   25398       sqlite3_str_appendf(out, "%.*s", (int)(pcEnd-z), z);
   25399     }
   25400     if( (c = *pcEnd)==0 ) break;
   25401     ++pcEnd;
   25402     switch( c ){
   25403     case '\\': case '"':
   25404       cbsSay = (char)c;
   25405       break;
   25406     case '\t': cbsSay = 't'; break;
   25407     case '\n': cbsSay = 'n'; break;
   25408     case '\r': cbsSay = 'r'; break;
   25409     case '\f': cbsSay = 'f'; break;
   25410     default: cbsSay = 0; break;
   25411     }
   25412     if( cbsSay ){
   25413       ace[1] = cbsSay;
   25414       sqlite3_str_appendall(out,ace);
   25415     }else if( !isprint(c&0xff) ){
   25416       sqlite3_str_appendf(out, "\\%03o", c&0xff);
   25417     }else{
   25418       ace[1] = (char)c;
   25419       sqlite3_str_appendall(out, ace+1);
   25420     }
   25421     z = pcEnd;
   25422   }
   25423   sqlite3_str_appendall(out, zq);
   25424 }
   25425 
   25426 /*
   25427 ** This routine runs when the user presses Ctrl-C
   25428 */
   25429 static void interrupt_handler(int NotUsed){
   25430   UNUSED_PARAMETER(NotUsed);
   25431   if( ++seenInterrupt>1 ) cli_exit(1);
   25432   if( globalDb ) sqlite3_interrupt(globalDb);
   25433 }
   25434 
   25435 /* Try to determine the screen width.  Use the default if unable.
   25436 */
   25437 static int shellScreenWidth(void){
   25438   if( stdout_tty_width>0 ){
   25439     return stdout_tty_width;
   25440   }else{
   25441 #if defined(TIOCGSIZE)
   25442     struct ttysize ts;
   25443     if( ioctl(STDIN_FILENO, TIOCGSIZE, &ts)>=0
   25444      || ioctl(STDOUT_FILENO, TIOCGSIZE, &ts)>=0
   25445      || ioctl(STDERR_FILENO, TIOCGSIZE, &ts)>=0
   25446     ){
   25447       return ts.ts_cols;
   25448     }
   25449 #elif defined(TIOCGWINSZ)
   25450     struct winsize ws;
   25451     if( ioctl(STDIN_FILENO, TIOCGWINSZ, &ws)>=0
   25452      || ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws)>=0
   25453      || ioctl(STDERR_FILENO, TIOCGWINSZ, &ws)>=0
   25454     ){
   25455       return ws.ws_col;
   25456     }
   25457 #elif defined(_WIN32)
   25458     CONSOLE_SCREEN_BUFFER_INFO csbi;
   25459     if( GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)
   25460      || GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi)
   25461      || GetConsoleScreenBufferInfo(GetStdHandle(STD_INPUT_HANDLE), &csbi)
   25462     ){
   25463       return csbi.srWindow.Right - csbi.srWindow.Left + 1;
   25464     }
   25465 #endif
   25466 #define DEFAULT_SCREEN_WIDTH 80
   25467     return DEFAULT_SCREEN_WIDTH;
   25468   }
   25469 }
   25470 
   25471 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
   25472 /*
   25473 ** This routine runs for console events (e.g. Ctrl-C) on Win32
   25474 */
   25475 static BOOL WINAPI ConsoleCtrlHandler(
   25476   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
   25477 ){
   25478   if( dwCtrlType==CTRL_C_EVENT ){
   25479     interrupt_handler(0);
   25480     return TRUE;
   25481   }
   25482   return FALSE;
   25483 }
   25484 #endif
   25485 
   25486 #ifndef SQLITE_OMIT_AUTHORIZATION
   25487 /*
   25488 ** This authorizer runs in safe mode.
   25489 */
   25490 static int safeModeAuth(
   25491   void *pClientData,
   25492   int op,
   25493   const char *zA1,
   25494   const char *zA2,
   25495   const char *zA3,
   25496   const char *zA4
   25497 ){
   25498   ShellState *p = (ShellState*)pClientData;
   25499   static const char *azProhibitedFunctions[] = {
   25500     "edit",
   25501     "fts3_tokenizer",
   25502     "load_extension",
   25503     "readfile",
   25504     "realpath",
   25505     "writefile",
   25506     "zipfile",
   25507     "zipfile_cds",
   25508   };
   25509   UNUSED_PARAMETER(zA1);
   25510   UNUSED_PARAMETER(zA3);
   25511   UNUSED_PARAMETER(zA4);
   25512   switch( op ){
   25513     case SQLITE_ATTACH: {
   25514 #ifndef SQLITE_SHELL_FIDDLE
   25515       /* In WASM builds the filesystem is a virtual sandbox, so
   25516       ** there's no harm in using ATTACH. */
   25517       failIfSafeMode(p, "cannot run ATTACH in safe mode");
   25518 #endif
   25519       break;
   25520     }
   25521     case SQLITE_FUNCTION: {
   25522       int i;
   25523       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
   25524         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
   25525           failIfSafeMode(p, "cannot use the %s() function in safe mode",
   25526                          azProhibitedFunctions[i]);
   25527         }
   25528       }
   25529       break;
   25530     }
   25531   }
   25532   return SQLITE_OK;
   25533 }
   25534 
   25535 /*
   25536 ** When the ".auth ON" is set, the following authorizer callback is
   25537 ** invoked.  It always returns SQLITE_OK.
   25538 */
   25539 static int shellAuth(
   25540   void *pClientData,
   25541   int op,
   25542   const char *zA1,
   25543   const char *zA2,
   25544   const char *zA3,
   25545   const char *zA4
   25546 ){
   25547   ShellState *p = (ShellState*)pClientData;
   25548   static const char *azAction[] = { 0,
   25549      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
   25550      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
   25551      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
   25552      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
   25553      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
   25554      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
   25555      "PRAGMA",               "READ",                 "SELECT",
   25556      "TRANSACTION",          "UPDATE",               "ATTACH",
   25557      "DETACH",               "ALTER_TABLE",          "REINDEX",
   25558      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
   25559      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
   25560   };
   25561   int i;
   25562   const char *az[4];
   25563   az[0] = zA1;
   25564   az[1] = zA2;
   25565   az[2] = zA3;
   25566   az[3] = zA4;
   25567   cli_printf(p->out, "authorizer: %s", azAction[op]);
   25568   for(i=0; i<4; i++){
   25569     cli_puts(" ", p->out);
   25570     if( az[i] ){
   25571       output_c_string(p->out, az[i]);
   25572     }else{
   25573       cli_puts("NULL", p->out);
   25574     }
   25575   }
   25576   cli_puts("\n", p->out);
   25577   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
   25578   return SQLITE_OK;
   25579 }
   25580 #endif
   25581 
   25582 /*
   25583 ** Print a schema statement.  This is helper routine to dump_callbac().
   25584 **
   25585 ** This routine converts some CREATE TABLE statements for shadow tables
   25586 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
   25587 **
   25588 ** If the schema statement in z[] contains a start-of-comment and if
   25589 ** sqlite3_complete() returns false, try to terminate the comment before
   25590 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
   25591 */
   25592 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
   25593   char *zToFree = 0;
   25594   if( z==0 ) return;
   25595   if( zTail==0 ) return;
   25596   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
   25597     const char *zOrig = z;
   25598     static const char *azTerm[] = { "", "*/", "\n" };
   25599     int i;
   25600     for(i=0; i<ArraySize(azTerm); i++){
   25601       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
   25602       shell_check_oom(zNew);
   25603       if( sqlite3_complete(zNew) ){
   25604         size_t n = strlen(zNew);
   25605         zNew[n-1] = 0;
   25606         zToFree = zNew;
   25607         z = zNew;
   25608         break;
   25609       }
   25610       sqlite3_free(zNew);
   25611     }
   25612   }
   25613   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
   25614     cli_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
   25615   }else{
   25616     cli_printf(out, "%s%s", z, zTail);
   25617   }
   25618   sqlite3_free(zToFree);
   25619 }
   25620 
   25621 /*
   25622 ** Return true if string z[] has nothing but whitespace and comments to the
   25623 ** end of the first line.
   25624 */
   25625 static int wsToEol(const char *z){
   25626   int i;
   25627   for(i=0; z[i]; i++){
   25628     if( z[i]=='\n' ) return 1;
   25629     if( IsSpace(z[i]) ) continue;
   25630     if( z[i]=='-' && z[i+1]=='-' ) return 1;
   25631     return 0;
   25632   }
   25633   return 1;
   25634 }
   25635 
   25636 /*
   25637 ** SQL Function:  shell_format_schema(SQL,FLAGS)
   25638 **
   25639 ** This function is internally by the CLI to assist with the
   25640 ** ".schema", ".fullschema", and ".dump" commands.  The first
   25641 ** argument is the value from sqlite_schema.sql.  The value returned
   25642 ** is a modification of the input that can actually be run as SQL
   25643 ** to recreate the schema object.
   25644 **
   25645 ** When FLAGS is zero, the only changes is to append ";".  If the
   25646 ** 0x01 bit of FLAGS is set, then transformations are made to implement
   25647 ** ".schema --indent".
   25648 */
   25649 static void shellFormatSchema(
   25650   sqlite3_context *pCtx,
   25651   int nVal,
   25652   sqlite3_value **apVal
   25653 ){
   25654   int flags;          /* Value of 2nd parameter */
   25655   const char *zSql;   /* Value of 1st parameter */
   25656   int nSql;           /* Bytes of text in zSql[] */
   25657   sqlite3_str *pOut;  /* Output buffer */
   25658   char *z;            /* Writable copy of zSql */
   25659   int i, j;           /* Loop counters */
   25660   int nParen = 0;
   25661   char cEnd = 0;
   25662   char c;
   25663   int nLine = 0;
   25664   int isIndex;
   25665   int isWhere = 0;
   25666 
   25667   assert( nVal==2 );
   25668   pOut = sqlite3_str_new(sqlite3_context_db_handle(pCtx));
   25669   nSql = sqlite3_value_bytes(apVal[0]);
   25670   zSql = (const char*)sqlite3_value_text(apVal[0]);
   25671   if( zSql==0 || zSql[0]==0 ) goto shellFormatSchema_finish;
   25672   flags = sqlite3_value_int(apVal[1]);
   25673   if( (flags & 0x01)==0 ){
   25674     sqlite3_str_append(pOut, zSql, nSql);
   25675     sqlite3_str_append(pOut, ";", 1);
   25676     goto shellFormatSchema_finish;
   25677   }
   25678   if( sqlite3_strlike("CREATE VIEW%", zSql, 0)==0
   25679    || sqlite3_strlike("CREATE TRIG%", zSql, 0)==0
   25680   ){
   25681     sqlite3_str_append(pOut, zSql, nSql);
   25682     sqlite3_str_append(pOut, ";", 1);
   25683     goto shellFormatSchema_finish;
   25684   }
   25685   isIndex = sqlite3_strlike("CREATE INDEX%", zSql, 0)==0
   25686          || sqlite3_strlike("CREATE UNIQUE INDEX%", zSql, 0)==0;
   25687   z = sqlite3_mprintf("%s", zSql);
   25688   if( z==0 ){
   25689     sqlite3_str_free(pOut);
   25690     sqlite3_result_error_nomem(pCtx);
   25691     return;
   25692   }
   25693   j = 0;
   25694   for(i=0; IsSpace(z[i]); i++){}
   25695   for(; (c = z[i])!=0; i++){
   25696     if( IsSpace(c) ){
   25697       if( z[j-1]=='\r' ) z[j-1] = '\n';
   25698       if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
   25699     }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
   25700       j--;
   25701     }
   25702     z[j++] = c;
   25703   }
   25704   while( j>0 && IsSpace(z[j-1]) ){ j--; }
   25705   z[j] = 0;
   25706   if( strlen30(z)>=79 ){
   25707     for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
   25708       if( c==cEnd ){
   25709         cEnd = 0;
   25710       }else if( cEnd!=0){
   25711         /* No-op */
   25712       }else if( c=='"' || c=='\'' || c=='`' ){
   25713         cEnd = c;
   25714       }else if( c=='[' ){
   25715         cEnd = ']';
   25716       }else if( c=='-' && z[i+1]=='-' ){
   25717         cEnd = '\n';
   25718       }else if( c=='(' ){
   25719         nParen++;
   25720       }else if( c==')' ){
   25721         nParen--;
   25722         if( nLine>0 && nParen==0 && j>0 && !isWhere ){
   25723           sqlite3_str_append(pOut, z, j);
   25724           sqlite3_str_append(pOut, "\n", 1);
   25725           j = 0;
   25726         }
   25727       }else if( (c=='w' || c=='W')
   25728              && nParen==0 && isIndex
   25729              && sqlite3_strnicmp("WHERE",&z[i],5)==0
   25730              && !IsAlnum(z[i+5]) && z[i+5]!='_' ){
   25731         isWhere = 1;
   25732       }else if( isWhere && (c=='A' || c=='a')
   25733              && nParen==0
   25734              && sqlite3_strnicmp("AND",&z[i],3)==0
   25735              && !IsAlnum(z[i+3]) && z[i+3]!='_' ){
   25736         sqlite3_str_append(pOut, z, j);
   25737         sqlite3_str_append(pOut, "\n    ", 5);
   25738         j = 0;
   25739       }
   25740       z[j++] = c;
   25741       if( nParen==1 && cEnd==0
   25742        && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
   25743        && !isWhere
   25744       ){
   25745         if( c=='\n' ) j--;
   25746         sqlite3_str_append(pOut, z, j);
   25747         sqlite3_str_append(pOut, "\n  ", 3);
   25748         j = 0;
   25749         nLine++;
   25750         while( IsSpace(z[i+1]) ){ i++; }
   25751       }
   25752     }
   25753     z[j] = 0;
   25754   }
   25755   sqlite3_str_appendall(pOut, z);
   25756   sqlite3_str_append(pOut, ";", 1);
   25757   sqlite3_free(z);
   25758 
   25759 shellFormatSchema_finish:
   25760   sqlite3_result_text(pCtx, sqlite3_str_finish(pOut), -1, sqlite3_free);
   25761 }
   25762 
   25763 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   25764 /*
   25765 ** Progress handler callback.
   25766 */
   25767 static int progress_handler(void *pClientData) {
   25768   ShellState *p = (ShellState*)pClientData;
   25769   p->nProgress++;
   25770   if( (p->flgProgress & SHELL_PROGRESS_TMOUT)!=0
   25771    && ELAPSE_TIME(p)>=p->tmProgress
   25772   ){
   25773     cli_printf(p->out, "Progress timeout after %.6f seconds\n",
   25774                ELAPSE_TIME(p));
   25775     return 1;
   25776   }
   25777   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
   25778     cli_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
   25779     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
   25780     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
   25781     return 1;
   25782   }
   25783   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
   25784     cli_printf(p->out, "Progress %u\n", p->nProgress);
   25785   }
   25786   return 0;
   25787 }
   25788 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
   25789 
   25790 /*
   25791 ** This is the callback routine from sqlite3_exec() that appends all
   25792 ** output onto the end of a ShellText object.
   25793 */
   25794 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
   25795   ShellText *p = (ShellText*)pArg;
   25796   int i;
   25797   UNUSED_PARAMETER(az);
   25798   if( azArg==0 ) return 0;
   25799   if( p->n ) appendText(p, "|", 0);
   25800   for(i=0; i<nArg; i++){
   25801     if( i ) appendText(p, ",", 0);
   25802     if( azArg[i] ) appendText(p, azArg[i], 0);
   25803   }
   25804   return 0;
   25805 }
   25806 
   25807 /*
   25808 ** Generate an appropriate SELFTEST table in the main database.
   25809 */
   25810 static void createSelftestTable(ShellState *p){
   25811   char *zErrMsg = 0;
   25812   sqlite3_exec(p->db,
   25813     "SAVEPOINT selftest_init;\n"
   25814     "CREATE TABLE IF NOT EXISTS selftest(\n"
   25815     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
   25816     "  op TEXT,\n"                   /* Operator:  memo run */
   25817     "  cmd TEXT,\n"                  /* Command text */
   25818     "  ans TEXT\n"                   /* Desired answer */
   25819     ");"
   25820     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
   25821     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
   25822     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
   25823     "         'memo','Tests generated by --init');\n"
   25824     "INSERT INTO [_shell$self]\n"
   25825     "  SELECT 'run',\n"
   25826     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
   25827                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
   25828     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
   25829                           "FROM sqlite_schema ORDER BY 2',224));\n"
   25830     "INSERT INTO [_shell$self]\n"
   25831     "  SELECT 'run',"
   25832     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
   25833     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
   25834     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
   25835     "  FROM (\n"
   25836     "    SELECT name FROM sqlite_schema\n"
   25837     "     WHERE type='table'\n"
   25838     "       AND name<>'selftest'\n"
   25839     "       AND coalesce(rootpage,0)>0\n"
   25840     "  )\n"
   25841     " ORDER BY name;\n"
   25842     "INSERT INTO [_shell$self]\n"
   25843     "  VALUES('run','PRAGMA integrity_check','ok');\n"
   25844     "INSERT INTO selftest(tno,op,cmd,ans)"
   25845     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
   25846     "DROP TABLE [_shell$self];"
   25847     ,0,0,&zErrMsg);
   25848   if( zErrMsg ){
   25849     cli_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
   25850     sqlite3_free(zErrMsg);
   25851   }
   25852   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
   25853 }
   25854 
   25855 
   25856 /*
   25857 ** Set the destination table field of the ShellState structure to
   25858 ** the name of the table given.  Escape any quote characters in the
   25859 ** table name.
   25860 */
   25861 static void set_table_name(ShellState *p, const char *zName){
   25862   if( p->zDestTable ){
   25863     sqlite3_free(p->zDestTable);
   25864     p->zDestTable = 0;
   25865   }
   25866   if( zName==0 ) return;
   25867   p->zDestTable = sqlite3_mprintf("%s", zName);
   25868   shell_check_oom(p->zDestTable);
   25869 }
   25870 
   25871 /*
   25872 ** Maybe construct two lines of text that point out the position of a
   25873 ** syntax error.  Return a pointer to the text, in memory obtained from
   25874 ** sqlite3_malloc().  Or, if the most recent error does not involve a
   25875 ** specific token that we can point to, return an empty string.
   25876 **
   25877 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
   25878 ** and should be released by the caller invoking sqlite3_free().
   25879 */
   25880 static char *shell_error_context(const char *zSql, sqlite3 *db){
   25881   int iOffset;
   25882   size_t len;
   25883   char *zCode;
   25884   char *zMsg;
   25885   int i;
   25886   if( db==0
   25887    || zSql==0
   25888    || (iOffset = sqlite3_error_offset(db))<0
   25889    || iOffset>=(int)strlen(zSql)
   25890   ){
   25891     return sqlite3_mprintf("");
   25892   }
   25893   while( iOffset>50 ){
   25894     iOffset--;
   25895     zSql++;
   25896     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
   25897   }
   25898   len = strlen(zSql);
   25899   if( len>78 ){
   25900     len = 78;
   25901     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
   25902   }
   25903   zCode = sqlite3_mprintf("%.*s", len, zSql);
   25904   shell_check_oom(zCode);
   25905   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
   25906   if( iOffset<25 ){
   25907     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
   25908   }else{
   25909     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
   25910   }
   25911   return zMsg;
   25912 }
   25913 
   25914 
   25915 /*
   25916 ** Execute a query statement that will generate SQL output.  Print
   25917 ** the result columns, comma-separated, on a line and then add a
   25918 ** semicolon terminator to the end of that line.
   25919 **
   25920 ** If the number of columns is 1 and that column contains text "--"
   25921 ** then write the semicolon on a separate line.  That way, if a
   25922 ** "--" comment occurs at the end of the statement, the comment
   25923 ** won't consume the semicolon terminator.
   25924 */
   25925 static int run_table_dump_query(
   25926   ShellState *p,           /* Query context */
   25927   const char *zSelect      /* SELECT statement to extract content */
   25928 ){
   25929   sqlite3_stmt *pSelect;
   25930   int rc;
   25931   int nResult;
   25932   int i;
   25933   const char *z;
   25934   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
   25935   if( rc!=SQLITE_OK || !pSelect ){
   25936     char *zContext = shell_error_context(zSelect, p->db);
   25937     cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s",
   25938           rc, sqlite3_errmsg(p->db), zContext);
   25939     sqlite3_free(zContext);
   25940     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
   25941     return rc;
   25942   }
   25943   rc = sqlite3_step(pSelect);
   25944   nResult = sqlite3_column_count(pSelect);
   25945   while( rc==SQLITE_ROW ){
   25946     z = (const char*)sqlite3_column_text(pSelect, 0);
   25947     cli_printf(p->out, "%s", z);
   25948     for(i=1; i<nResult; i++){
   25949       cli_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
   25950     }
   25951     if( z==0 ) z = "";
   25952     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
   25953     if( z[0] ){
   25954       cli_puts("\n;\n", p->out);
   25955     }else{
   25956       cli_puts(";\n", p->out);
   25957     }
   25958     rc = sqlite3_step(pSelect);
   25959   }
   25960   rc = sqlite3_finalize(pSelect);
   25961   if( rc!=SQLITE_OK ){
   25962     cli_printf(p->out, "/**** ERROR: (%d) %s *****/\n",
   25963                     rc, sqlite3_errmsg(p->db));
   25964     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
   25965   }
   25966   return rc;
   25967 }
   25968 
   25969 /*
   25970 ** Allocate space and save off string indicating current error.
   25971 */
   25972 static char *save_err_msg(
   25973   sqlite3 *db,           /* Database to query */
   25974   const char *zPhase,    /* When the error occurs */
   25975   int rc,                /* Error code returned from API */
   25976   const char *zSql       /* SQL string, or NULL */
   25977 ){
   25978   char *zErr;
   25979   char *zContext;
   25980   sqlite3_str *pStr = sqlite3_str_new(0);
   25981   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
   25982   if( rc>1 ){
   25983     sqlite3_str_appendf(pStr, " (%d)", rc);
   25984   }
   25985   zContext = shell_error_context(zSql, db);
   25986   if( zContext ){
   25987     sqlite3_str_appendall(pStr, zContext);
   25988     sqlite3_free(zContext);
   25989   }
   25990   zErr = sqlite3_str_finish(pStr);
   25991   shell_check_oom(zErr);
   25992   return zErr;
   25993 }
   25994 
   25995 #ifdef __linux__
   25996 /*
   25997 ** Attempt to display I/O stats on Linux using /proc/PID/io
   25998 */
   25999 static void displayLinuxIoStats(FILE *out){
   26000   FILE *in;
   26001   char z[200];
   26002   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
   26003   in = sqlite3_fopen(z, "rb");
   26004   if( in==0 ) return;
   26005   while( sqlite3_fgets(z, sizeof(z), in)!=0 ){
   26006     static const struct {
   26007       const char *zPattern;
   26008       const char *zDesc;
   26009     } aTrans[] = {
   26010       { "rchar: ",                  "Bytes received by read():" },
   26011       { "wchar: ",                  "Bytes sent to write():"    },
   26012       { "syscr: ",                  "Read() system calls:"      },
   26013       { "syscw: ",                  "Write() system calls:"     },
   26014       { "read_bytes: ",             "Bytes read from storage:"  },
   26015       { "write_bytes: ",            "Bytes written to storage:" },
   26016       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
   26017     };
   26018     int i;
   26019     for(i=0; i<ArraySize(aTrans); i++){
   26020       int n = strlen30(aTrans[i].zPattern);
   26021       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
   26022         cli_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
   26023         break;
   26024       }
   26025     }
   26026   }
   26027   fclose(in);
   26028 }
   26029 #endif
   26030 
   26031 /*
   26032 ** Display a single line of status using 64-bit values.
   26033 */
   26034 static void displayStatLine(
   26035   FILE *out,                /* Write to this channel */
   26036   char *zLabel,             /* Label for this one line */
   26037   char *zFormat,            /* Format for the result */
   26038   int iStatusCtrl,          /* Which status to display */
   26039   int bReset                /* True to reset the stats */
   26040 ){
   26041   sqlite3_int64 iCur = -1;
   26042   sqlite3_int64 iHiwtr = -1;
   26043   int i, nPercent;
   26044   char zLine[200];
   26045   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
   26046   for(i=0, nPercent=0; zFormat[i]; i++){
   26047     if( zFormat[i]=='%' ) nPercent++;
   26048   }
   26049   if( nPercent>1 ){
   26050     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
   26051   }else{
   26052     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
   26053   }
   26054   cli_printf(out, "%-36s %s\n", zLabel, zLine);
   26055 }
   26056 
   26057 /*
   26058 ** Display memory stats.
   26059 */
   26060 static int display_stats(
   26061   sqlite3 *db,                /* Database to query */
   26062   ShellState *pArg,           /* Pointer to ShellState */
   26063   int bReset                  /* True to reset the stats */
   26064 ){
   26065   int iCur, iHiwtr;
   26066   sqlite3_int64 iCur64, iHiwtr64;
   26067   FILE *out;
   26068   if( pArg==0 || pArg->out==0 ) return 0;
   26069   out = pArg->out;
   26070 
   26071   if( pArg->pStmt && pArg->statsOn==2 ){
   26072     int nCol, i, x;
   26073     sqlite3_stmt *pStmt = pArg->pStmt;
   26074     char z[100];
   26075     nCol = sqlite3_column_count(pStmt);
   26076     cli_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
   26077     for(i=0; i<nCol; i++){
   26078       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
   26079       cli_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
   26080 #ifndef SQLITE_OMIT_DECLTYPE
   26081       sqlite3_snprintf(30, z+x, "declared type:");
   26082       cli_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
   26083 #endif
   26084 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   26085       sqlite3_snprintf(30, z+x, "database name:");
   26086       cli_printf(out, "%-36s %s\n", z,
   26087                            sqlite3_column_database_name(pStmt,i));
   26088       sqlite3_snprintf(30, z+x, "table name:");
   26089       cli_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
   26090       sqlite3_snprintf(30, z+x, "origin name:");
   26091       cli_printf(out, "%-36s %s\n", z,sqlite3_column_origin_name(pStmt,i));
   26092 #endif
   26093     }
   26094   }
   26095 
   26096   if( pArg->statsOn==3 ){
   26097     if( pArg->pStmt ){
   26098       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
   26099       cli_printf(out, "VM-steps: %d\n", iCur);
   26100     }
   26101     return 0;
   26102   }
   26103 
   26104   displayStatLine(out, "Memory Used:",
   26105      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
   26106   displayStatLine(out, "Number of Outstanding Allocations:",
   26107      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
   26108   if( pArg->shellFlgs & SHFLG_Pagecache ){
   26109     displayStatLine(out, "Number of Pcache Pages Used:",
   26110        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
   26111   }
   26112   displayStatLine(out, "Number of Pcache Overflow Bytes:",
   26113      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
   26114   displayStatLine(out, "Largest Allocation:",
   26115      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
   26116   displayStatLine(out, "Largest Pcache Allocation:",
   26117      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
   26118 #ifdef YYTRACKMAXSTACKDEPTH
   26119   displayStatLine(out, "Deepest Parser Stack:",
   26120      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
   26121 #endif
   26122 
   26123   if( db ){
   26124     if( pArg->shellFlgs & SHFLG_Lookaside ){
   26125       iHiwtr = iCur = -1;
   26126       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
   26127                         &iCur, &iHiwtr, bReset);
   26128       cli_printf(out,
   26129            "Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
   26130       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
   26131                         &iCur, &iHiwtr, bReset);
   26132       cli_printf(out,
   26133            "Successful lookaside attempts:       %d\n", iHiwtr);
   26134       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
   26135                         &iCur, &iHiwtr, bReset);
   26136       cli_printf(out,
   26137            "Lookaside failures due to size:      %d\n", iHiwtr);
   26138       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
   26139                         &iCur, &iHiwtr, bReset);
   26140       cli_printf(out,
   26141            "Lookaside failures due to OOM:       %d\n", iHiwtr);
   26142     }
   26143     iHiwtr = iCur = -1;
   26144     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
   26145     cli_printf(out,
   26146            "Pager Heap Usage:                    %d bytes\n", iCur);
   26147     iHiwtr = iCur = -1;
   26148     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
   26149     cli_printf(out,
   26150            "Page cache hits:                     %d\n", iCur);
   26151     iHiwtr = iCur = -1;
   26152     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
   26153     cli_printf(out,
   26154            "Page cache misses:                   %d\n", iCur);
   26155     iHiwtr64 = iCur64 = -1;
   26156     sqlite3_db_status64(db, SQLITE_DBSTATUS_TEMPBUF_SPILL, &iCur64, &iHiwtr64,
   26157                         0);
   26158     iHiwtr = iCur = -1;
   26159     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
   26160     cli_printf(out,
   26161            "Page cache writes:                   %d\n", iCur);
   26162     iHiwtr = iCur = -1;
   26163     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
   26164     cli_printf(out,
   26165            "Page cache spills:                   %d\n", iCur);
   26166     cli_printf(out,
   26167            "Temporary data spilled to disk:      %lld\n", iCur64);
   26168     sqlite3_db_status64(db, SQLITE_DBSTATUS_TEMPBUF_SPILL, &iCur64, &iHiwtr64,
   26169                         1);
   26170     iHiwtr = iCur = -1;
   26171     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
   26172     cli_printf(out,
   26173            "Schema Heap Usage:                   %d bytes\n", iCur);
   26174     iHiwtr = iCur = -1;
   26175     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
   26176     cli_printf(out,
   26177            "Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
   26178   }
   26179 
   26180   if( pArg->pStmt ){
   26181     int iHit, iMiss;
   26182     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
   26183                                bReset);
   26184     cli_printf(out,
   26185            "Fullscan Steps:                      %d\n", iCur);
   26186     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
   26187     cli_printf(out,
   26188            "Sort Operations:                     %d\n", iCur);
   26189     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
   26190     cli_printf(out,
   26191            "Autoindex Inserts:                   %d\n", iCur);
   26192     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
   26193                                bReset);
   26194     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
   26195                                 bReset);
   26196     if( iHit || iMiss ){
   26197       cli_printf(out,
   26198            "Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
   26199     }
   26200     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
   26201     cli_printf(out,
   26202            "Virtual Machine Steps:               %d\n", iCur);
   26203     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
   26204     cli_printf(out,
   26205            "Reprepare operations:                %d\n", iCur);
   26206     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
   26207     cli_printf(out,
   26208            "Number of times run:                 %d\n", iCur);
   26209     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
   26210     cli_printf(out,
   26211            "Memory used by prepared stmt:        %d\n", iCur);
   26212   }
   26213 
   26214 #ifdef __linux__
   26215   displayLinuxIoStats(pArg->out);
   26216 #endif
   26217 
   26218   /* Do not remove this machine readable comment: extra-stats-output-here */
   26219 
   26220   return 0;
   26221 }
   26222 
   26223 /*
   26224 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
   26225 */
   26226 static unsigned int savedSelectTrace;
   26227 static unsigned int savedWhereTrace;
   26228 static void disable_debug_trace_modes(void){
   26229   unsigned int zero = 0;
   26230   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
   26231   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
   26232   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
   26233   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
   26234 }
   26235 static void restore_debug_trace_modes(void){
   26236   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
   26237   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
   26238 }
   26239 
   26240 /* Create the TEMP table used to store parameter bindings */
   26241 static void bind_table_init(ShellState *p){
   26242   int wrSchema = 0;
   26243   int defensiveMode = 0;
   26244   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
   26245   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
   26246   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
   26247   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
   26248   sqlite3_exec(p->db,
   26249     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
   26250     "  key TEXT PRIMARY KEY,\n"
   26251     "  value\n"
   26252     ") WITHOUT ROWID;",
   26253     0, 0, 0);
   26254   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
   26255   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
   26256 }
   26257 
   26258 /*
   26259 ** Bind parameters on a prepared statement.
   26260 **
   26261 ** Parameter bindings are taken from a TEMP table of the form:
   26262 **
   26263 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
   26264 **    WITHOUT ROWID;
   26265 **
   26266 ** No bindings occur if this table does not exist.  The name of the table
   26267 ** begins with "sqlite_" so that it will not collide with ordinary application
   26268 ** tables.  The table must be in the TEMP schema.
   26269 */
   26270 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
   26271   int nVar;
   26272   int i;
   26273   int rc;
   26274   sqlite3_stmt *pQ = 0;
   26275 
   26276   nVar = sqlite3_bind_parameter_count(pStmt);
   26277   if( nVar==0 ) return;  /* Nothing to do */
   26278   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
   26279                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
   26280     rc = SQLITE_NOTFOUND;
   26281     pQ = 0;
   26282   }else{
   26283     rc = sqlite3_prepare_v2(pArg->db,
   26284             "SELECT value FROM temp.sqlite_parameters"
   26285             " WHERE key=?1", -1, &pQ, 0);
   26286   }
   26287   for(i=1; i<=nVar; i++){
   26288     char zNum[30];
   26289     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
   26290     if( zVar==0 ){
   26291       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
   26292       zVar = zNum;
   26293     }
   26294     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
   26295     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
   26296       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
   26297 #ifdef NAN
   26298     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
   26299       sqlite3_bind_double(pStmt, i, NAN);
   26300 #endif
   26301 #ifdef INFINITY
   26302     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
   26303       sqlite3_bind_double(pStmt, i, INFINITY);
   26304 #endif
   26305     }else if( strncmp(zVar, "$int_", 5)==0 ){
   26306       sqlite3_bind_int(pStmt, i, atoi(&zVar[5]));
   26307     }else if( strncmp(zVar, "$text_", 6)==0 ){
   26308       size_t szVar = strlen(zVar);
   26309       char *zBuf = sqlite3_malloc64( szVar-5 );
   26310       if( zBuf ){
   26311         memcpy(zBuf, &zVar[6], szVar-5);
   26312         sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8);
   26313       }
   26314     }else if( strcmp(zVar, "$TIMER")==0 ){
   26315       sqlite3_bind_double(pStmt, i, pArg->prevTimer);
   26316 #ifdef SQLITE_ENABLE_CARRAY
   26317     }else if( strncmp(zVar, "$carray_", 8)==0 ){
   26318       static char *azColorNames[] = {
   26319         "azure", "black", "blue",   "brown", "cyan",   "fuchsia", "gold",
   26320         "gray",  "green", "indigo", "khaki", "lime",   "magenta", "maroon",
   26321         "navy",  "olive", "orange", "pink",  "purple", "red",     "silver",
   26322         "tan",   "teal",  "violet", "white", "yellow"
   26323       };
   26324       static int aPrimes[] = {
   26325         1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
   26326        53, 59, 61, 67, 71, 73, 79, 83, 89, 97
   26327       };
   26328       /* Special bindings:  carray($carray_clr), carray($carray_primes)
   26329       ** with --unsafe-testing:  carray($carray_clr_p,26,'char*'),
   26330       **                         carray($carray_primes_p,26,'int32')
   26331       */
   26332       if( strcmp(zVar+8,"clr")==0 ){
   26333         sqlite3_carray_bind(pStmt,i,azColorNames,26,SQLITE_CARRAY_TEXT,0);
   26334       }else if( strcmp(zVar+8,"primes")==0 ){
   26335         sqlite3_carray_bind(pStmt,i,aPrimes,26,SQLITE_CARRAY_INT32,0);
   26336       }else if( strcmp(zVar+8,"clr_p")==0
   26337              && ShellHasFlag(pArg,SHFLG_TestingMode) ){
   26338         sqlite3_bind_pointer(pStmt,i,azColorNames,"carray",0);
   26339       }else if( strcmp(zVar+8,"primes_p")==0
   26340              && ShellHasFlag(pArg,SHFLG_TestingMode) ){
   26341         sqlite3_bind_pointer(pStmt,i,aPrimes,"carray",0);
   26342       }else{
   26343         sqlite3_bind_null(pStmt, i);
   26344       }
   26345 #endif
   26346     }else{
   26347       sqlite3_bind_null(pStmt, i);
   26348     }
   26349     sqlite3_reset(pQ);
   26350   }
   26351   sqlite3_finalize(pQ);
   26352 }
   26353 
   26354 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   26355 /*
   26356 ** This function is called to process SQL if the previous shell command
   26357 ** was ".expert". It passes the SQL in the second argument directly to
   26358 ** the sqlite3expert object.
   26359 **
   26360 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
   26361 ** code. In this case, (*pzErr) may be set to point to a buffer containing
   26362 ** an English language error message. It is the responsibility of the
   26363 ** caller to eventually free this buffer using sqlite3_free().
   26364 */
   26365 static int expertHandleSQL(
   26366   ShellState *pState,
   26367   const char *zSql,
   26368   char **pzErr
   26369 ){
   26370   assert( pState->expert.pExpert );
   26371   assert( pzErr==0 || *pzErr==0 );
   26372   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
   26373 }
   26374 
   26375 /*
   26376 ** This function is called either to silently clean up the object
   26377 ** created by the ".expert" command (if bCancel==1), or to generate a
   26378 ** report from it and then clean it up (if bCancel==0).
   26379 **
   26380 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
   26381 ** code. In this case, (*pzErr) may be set to point to a buffer containing
   26382 ** an English language error message. It is the responsibility of the
   26383 ** caller to eventually free this buffer using sqlite3_free().
   26384 */
   26385 static int expertFinish(
   26386   ShellState *pState,
   26387   int bCancel,
   26388   char **pzErr
   26389 ){
   26390   int rc = SQLITE_OK;
   26391   sqlite3expert *p = pState->expert.pExpert;
   26392   FILE *out = pState->out;
   26393   assert( p );
   26394   assert( bCancel || pzErr==0 || *pzErr==0 );
   26395   if( bCancel==0 ){
   26396     int bVerbose = pState->expert.bVerbose;
   26397 
   26398     rc = sqlite3_expert_analyze(p, pzErr);
   26399     if( rc==SQLITE_OK ){
   26400       int nQuery = sqlite3_expert_count(p);
   26401       int i;
   26402 
   26403       if( bVerbose ){
   26404         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
   26405         cli_puts("-- Candidates -----------------------------\n", out);
   26406         cli_printf(out, "%s\n", zCand);
   26407       }
   26408       for(i=0; i<nQuery; i++){
   26409         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
   26410         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
   26411         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
   26412         if( zIdx==0 ) zIdx = "(no new indexes)\n";
   26413         if( bVerbose ){
   26414           cli_printf(out,
   26415               "-- Query %d --------------------------------\n"
   26416               "%s\n\n"
   26417               ,i+1, zSql);
   26418         }
   26419         cli_printf(out, "%s\n%s\n", zIdx, zEQP);
   26420       }
   26421     }
   26422   }
   26423   sqlite3_expert_destroy(p);
   26424   pState->expert.pExpert = 0;
   26425   return rc;
   26426 }
   26427 
   26428 /*
   26429 ** Implementation of ".expert" dot command.
   26430 */
   26431 static int expertDotCommand(
   26432   ShellState *pState,             /* Current shell tool state */
   26433   char **azArg,                   /* Array of arguments passed to dot command */
   26434   int nArg                        /* Number of entries in azArg[] */
   26435 ){
   26436   int rc = SQLITE_OK;
   26437   char *zErr = 0;
   26438   int i;
   26439   int iSample = 0;
   26440 
   26441   assert( pState->expert.pExpert==0 );
   26442   memset(&pState->expert, 0, sizeof(ExpertInfo));
   26443 
   26444   for(i=1; rc==SQLITE_OK && i<nArg; i++){
   26445     char *z = azArg[i];
   26446     int n;
   26447     if( z[0]=='-' && z[1]=='-' ) z++;
   26448     n = strlen30(z);
   26449     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
   26450       pState->expert.bVerbose = 1;
   26451     }
   26452     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
   26453       if( i==(nArg-1) ){
   26454         cli_printf(stderr, "option requires an argument: %s\n", z);
   26455         rc = SQLITE_ERROR;
   26456       }else{
   26457         iSample = (int)integerValue(azArg[++i]);
   26458         if( iSample<0 || iSample>100 ){
   26459           cli_printf(stderr,"value out of range: %s\n", azArg[i]);
   26460           rc = SQLITE_ERROR;
   26461         }
   26462       }
   26463     }
   26464     else{
   26465       cli_printf(stderr,"unknown option: %s\n", z);
   26466       rc = SQLITE_ERROR;
   26467     }
   26468   }
   26469 
   26470   if( rc==SQLITE_OK ){
   26471     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
   26472     if( pState->expert.pExpert==0 ){
   26473       cli_printf(stderr,
   26474           "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
   26475       rc = SQLITE_ERROR;
   26476     }else{
   26477       sqlite3_expert_config(
   26478           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
   26479       );
   26480     }
   26481   }
   26482   sqlite3_free(zErr);
   26483 
   26484   return rc;
   26485 }
   26486 #endif /* !SQLITE_OMIT_VIRTUALTABLE && !SQLITE_OMIT_AUTHORIZATION */
   26487 
   26488 /*
   26489 ** QRF write callback
   26490 */
   26491 static int shellWriteQR(void *pX, const char *z, sqlite3_int64 n){
   26492   ShellState *pArg = (ShellState*)pX;
   26493   cli_printf(pArg->out, "%.*s", (int)n, z);
   26494   return SQLITE_OK;
   26495 }
   26496 
   26497 /*
   26498 ** Execute a statement or set of statements.  Print
   26499 ** any result rows/columns depending on the current mode
   26500 ** set via the supplied callback.
   26501 **
   26502 ** This is very similar to SQLite's built-in sqlite3_exec()
   26503 ** function except it takes a slightly different callback
   26504 ** and callback data argument.
   26505 */
   26506 static int shell_exec(
   26507   ShellState *pArg,                         /* Pointer to ShellState */
   26508   const char *zSql,                         /* SQL to be evaluated */
   26509   char **pzErrMsg                           /* Error msg written here */
   26510 ){
   26511   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
   26512   int rc = SQLITE_OK;             /* Return Code */
   26513   int rc2;
   26514   const char *zLeftover;          /* Tail of unprocessed SQL */
   26515   sqlite3 *db = pArg->db;
   26516   unsigned char eStyle;
   26517   sqlite3_qrf_spec spec;
   26518 
   26519   if( pzErrMsg ){
   26520     *pzErrMsg = NULL;
   26521   }
   26522   memcpy(&spec, &pArg->mode.spec, sizeof(spec));
   26523   spec.xWrite = shellWriteQR;
   26524   spec.pWriteArg = (void*)pArg;
   26525   if( pArg->mode.eMode==MODE_Insert && ShellHasFlag(pArg,SHFLG_PreserveRowid) ){
   26526     spec.bTitles = QRF_SW_On;
   26527   }
   26528          /*                        ,- This is true, but it is omitted
   26529          ** vvvvvvvvvvvvvvvvvvv ----- to avoid compiler warnings.         */
   26530   assert( /*pArg->mode.eMode>=0 &&*/ pArg->mode.eMode<ArraySize(aModeInfo) );
   26531   eStyle = aModeInfo[pArg->mode.eMode].eStyle;
   26532   if( pArg->mode.bAutoScreenWidth ){
   26533     spec.nScreenWidth = shellScreenWidth();
   26534   }
   26535   if( spec.eBlob==QRF_BLOB_Auto ){
   26536     switch( spec.eText ){
   26537       case QRF_TEXT_Relaxed: /* fall through */
   26538       case QRF_TEXT_Sql:  spec.eBlob = QRF_BLOB_Sql;   break;
   26539       case QRF_TEXT_Json: spec.eBlob = QRF_BLOB_Json;  break;
   26540       default:            spec.eBlob = QRF_BLOB_Text;  break;
   26541     }
   26542   }
   26543 
   26544 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   26545   if( pArg->expert.pExpert ){
   26546     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
   26547     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
   26548   }
   26549 #endif
   26550 
   26551   while( zSql && zSql[0] && (SQLITE_OK == rc) ){
   26552     static const char *zStmtSql;
   26553     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
   26554     if( SQLITE_OK != rc ){
   26555       if( pzErrMsg ){
   26556         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
   26557       }
   26558     }else{
   26559       int isExplain;
   26560       if( !pStmt ){
   26561         /* this happens for a comment or white-space */
   26562         zSql = zLeftover;
   26563         while( IsSpace(zSql[0]) ) zSql++;
   26564         continue;
   26565       }
   26566       zStmtSql = sqlite3_sql(pStmt);
   26567       if( zStmtSql==0 ) zStmtSql = "";
   26568       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
   26569 
   26570       /* save off the prepared statement handle */
   26571       if( pArg ){
   26572         pArg->pStmt = pStmt;
   26573       }
   26574 
   26575       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
   26576       isExplain = sqlite3_stmt_isexplain(pStmt);
   26577       if( pArg && pArg->mode.autoEQP && isExplain==0 && pArg->dot.nArg==0 ){
   26578         int triggerEQP = 0;
   26579         u8 savedEnableTimer = pArg->enableTimer;
   26580         pArg->enableTimer = 0;
   26581         disable_debug_trace_modes();
   26582         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
   26583         if( pArg->mode.autoEQP>=AUTOEQP_trigger ){
   26584           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
   26585         }
   26586         sqlite3_reset(pStmt);
   26587         spec.eStyle = QRF_STYLE_Auto;
   26588         sqlite3_stmt_explain(pStmt, 2);
   26589         sqlite3_format_query_result(pStmt, &spec, 0);
   26590         if( pArg->mode.autoEQP>=AUTOEQP_full ){
   26591           sqlite3_reset(pStmt);
   26592           sqlite3_stmt_explain(pStmt, 1);
   26593           sqlite3_format_query_result(pStmt, &spec, 0);
   26594         }
   26595 
   26596         if( pArg->mode.autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
   26597           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
   26598         }
   26599         sqlite3_reset(pStmt);
   26600         sqlite3_stmt_explain(pStmt, 0);
   26601         restore_debug_trace_modes();
   26602         pArg->enableTimer = savedEnableTimer;
   26603       }
   26604 
   26605       bind_prepared_stmt(pArg, pStmt);
   26606       if( isExplain && pArg->mode.autoExplain ){
   26607         spec.eStyle = isExplain==1 ? QRF_STYLE_Explain : QRF_STYLE_Eqp;
   26608         sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
   26609       }else if( pArg->mode.eMode==MODE_Www ){
   26610         cli_printf(pArg->out,
   26611               "</PRE>\n"
   26612               "<TABLE border='1' cellspacing='0' cellpadding='2'>\n");
   26613         spec.eStyle = QRF_STYLE_Html;
   26614         sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
   26615         cli_printf(pArg->out,
   26616               "</TABLE>\n"
   26617               "<PRE>");
   26618       }else{
   26619         spec.eStyle = eStyle;
   26620         sqlite3_format_query_result(pStmt, &spec, pzErrMsg);
   26621       }
   26622 
   26623       /* print usage stats if stats on */
   26624       if( pArg && pArg->statsOn ){
   26625         display_stats(db, pArg, 0);
   26626       }
   26627 
   26628       /* print loop-counters if required */
   26629       if( pArg && pArg->mode.scanstatsOn ){
   26630         char *zErr = 0;
   26631         switch( pArg->mode.scanstatsOn ){
   26632           case 1:   spec.eStyle = QRF_STYLE_Stats;     break;
   26633           case 2:   spec.eStyle = QRF_STYLE_StatsEst;  break;
   26634           default:  spec.eStyle = QRF_STYLE_StatsVm;   break;
   26635         }
   26636         sqlite3_reset(pStmt);
   26637         rc = sqlite3_format_query_result(pStmt, &spec, &zErr);
   26638         if( rc ){
   26639           cli_printf(stderr, "Stats query failed: %s\n", zErr);
   26640           sqlite3_free(zErr);
   26641         }
   26642       }
   26643 
   26644       /* Finalize the statement just executed. If this fails, save a
   26645       ** copy of the error message. Otherwise, set zSql to point to the
   26646       ** next statement to execute. */
   26647       rc2 = sqlite3_finalize(pStmt);
   26648       if( rc!=SQLITE_NOMEM ) rc = rc2;
   26649       if( rc==SQLITE_OK ){
   26650         zSql = zLeftover;
   26651         while( IsSpace(zSql[0]) ) zSql++;
   26652       }else if( pzErrMsg ){
   26653         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
   26654       }
   26655 
   26656       /* clear saved stmt handle */
   26657       if( pArg ){
   26658         pArg->pStmt = NULL;
   26659       }
   26660     }
   26661   } /* end while */
   26662 
   26663   return rc;
   26664 }
   26665 
   26666 /*
   26667 ** Release memory previously allocated by tableColumnList().
   26668 */
   26669 static void freeColumnList(char **azCol){
   26670   int i;
   26671   for(i=1; azCol[i]; i++){
   26672     sqlite3_free(azCol[i]);
   26673   }
   26674   /* azCol[0] is a static string */
   26675   sqlite3_free(azCol);
   26676 }
   26677 
   26678 /*
   26679 ** Return a list of pointers to strings which are the names of all
   26680 ** columns in table zTab.   The memory to hold the names is dynamically
   26681 ** allocated and must be released by the caller using a subsequent call
   26682 ** to freeColumnList().
   26683 **
   26684 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
   26685 ** value that needs to be preserved, then azCol[0] is filled in with the
   26686 ** name of the rowid column.
   26687 **
   26688 ** The first regular column in the table is azCol[1].  The list is terminated
   26689 ** by an entry with azCol[i]==0.
   26690 */
   26691 static char **tableColumnList(ShellState *p, const char *zTab){
   26692   char **azCol = 0;
   26693   sqlite3_stmt *pStmt;
   26694   char *zSql;
   26695   int nCol = 0;
   26696   i64 nAlloc = 0;
   26697   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
   26698   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
   26699   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
   26700   int rc;
   26701 
   26702   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
   26703   shell_check_oom(zSql);
   26704   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   26705   sqlite3_free(zSql);
   26706   if( rc ) return 0;
   26707   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   26708     if( nCol>=nAlloc-2 ){
   26709       nAlloc = nAlloc*2 + nCol + 10;
   26710       azCol = sqlite3_realloc64(azCol, nAlloc*sizeof(azCol[0]));
   26711       shell_check_oom(azCol);
   26712     }
   26713     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
   26714     shell_check_oom(azCol[nCol]);
   26715     if( sqlite3_column_int(pStmt, 5) ){
   26716       nPK++;
   26717       if( nPK==1
   26718        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
   26719                           "INTEGER")==0
   26720       ){
   26721         isIPK = 1;
   26722       }else{
   26723         isIPK = 0;
   26724       }
   26725     }
   26726   }
   26727   sqlite3_finalize(pStmt);
   26728   if( azCol==0 ) return 0;
   26729   azCol[0] = 0;
   26730   azCol[nCol+1] = 0;
   26731 
   26732   /* The decision of whether or not a rowid really needs to be preserved
   26733   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
   26734   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
   26735   ** rowids on tables where the rowid is inaccessible because there are other
   26736   ** columns in the table named "rowid", "_rowid_", and "oid".
   26737   */
   26738   if( preserveRowid && isIPK ){
   26739     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
   26740     ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
   26741     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
   26742     ** ROWID aliases.  To distinguish these cases, check to see if
   26743     ** there is a "pk" entry in "PRAGMA index_list".  There will be
   26744     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
   26745     */
   26746     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
   26747                            " WHERE origin='pk'", zTab);
   26748     shell_check_oom(zSql);
   26749     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   26750     sqlite3_free(zSql);
   26751     if( rc ){
   26752       freeColumnList(azCol);
   26753       return 0;
   26754     }
   26755     rc = sqlite3_step(pStmt);
   26756     sqlite3_finalize(pStmt);
   26757     preserveRowid = rc==SQLITE_ROW;
   26758   }
   26759   if( preserveRowid ){
   26760     /* Only preserve the rowid if we can find a name to use for the
   26761     ** rowid */
   26762     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
   26763     int i, j;
   26764     for(j=0; j<3; j++){
   26765       for(i=1; i<=nCol; i++){
   26766         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
   26767       }
   26768       if( i>nCol ){
   26769         /* At this point, we know that azRowid[j] is not the name of any
   26770         ** ordinary column in the table.  Verify that azRowid[j] is a valid
   26771         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
   26772         ** tables will fail this last check */
   26773         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
   26774         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
   26775         break;
   26776       }
   26777     }
   26778   }
   26779   return azCol;
   26780 }
   26781 
   26782 /*
   26783 ** Toggle the reverse_unordered_selects setting.
   26784 */
   26785 static void toggleSelectOrder(sqlite3 *db){
   26786   sqlite3_stmt *pStmt = 0;
   26787   int iSetting = 0;
   26788   char zStmt[100];
   26789   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
   26790   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   26791     iSetting = sqlite3_column_int(pStmt, 0);
   26792   }
   26793   sqlite3_finalize(pStmt);
   26794   sqlite3_snprintf(sizeof(zStmt), zStmt,
   26795        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
   26796   sqlite3_exec(db, zStmt, 0, 0, 0);
   26797 }
   26798 
   26799 /* Forward reference */
   26800 static int db_int(sqlite3 *db, const char *zSql, ...);
   26801 
   26802 /*
   26803 ** This is a different callback routine used for dumping the database.
   26804 ** Each row received by this callback consists of a table name,
   26805 ** the table type ("index" or "table") and SQL to create the table.
   26806 ** This routine should print text sufficient to recreate the table.
   26807 */
   26808 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
   26809   int rc;
   26810   const char *zTable;
   26811   const char *zType;
   26812   const char *zSql;
   26813   ShellState *p = (ShellState *)pArg;
   26814   int dataOnly;
   26815   int noSys;
   26816 
   26817   UNUSED_PARAMETER(azNotUsed);
   26818   if( nArg!=3 || azArg==0 ) return 0;
   26819   zTable = azArg[0];
   26820   zType = azArg[1];
   26821   zSql = azArg[2];
   26822   if( zTable==0 ) return 0;
   26823   if( zType==0 ) return 0;
   26824   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
   26825   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
   26826 
   26827   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
   26828     /* The sqlite_sequence table is repopulated last.  Delete content
   26829     ** in the sqlite_sequence table added by prior repopulations prior to
   26830     ** repopulating sqlite_sequence itself.  But only do this if the
   26831     ** table is non-empty, because if it is empty the table might not
   26832     ** have been recreated by prior repopulations. See forum posts:
   26833     ** 2024-10-13T17:10:01z and 2025-10-29T19:38:43z
   26834     */
   26835     if( db_int(p->db, "SELECT count(*) FROM sqlite_sequence")>0 ){
   26836       if( !p->writableSchema ){
   26837         cli_puts("PRAGMA writable_schema=ON;\n", p->out);
   26838         p->writableSchema = 1;
   26839       }
   26840       cli_puts("CREATE TABLE IF NOT EXISTS sqlite_sequence(name,seq);\n"
   26841                     "DELETE FROM sqlite_sequence;\n", p->out);
   26842     }
   26843   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
   26844     if( !dataOnly ) cli_puts("ANALYZE sqlite_schema;\n", p->out);
   26845   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
   26846     return 0;
   26847   }else if( dataOnly ){
   26848     /* no-op */
   26849   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
   26850     char *zIns;
   26851     if( !p->writableSchema ){
   26852       cli_puts("PRAGMA writable_schema=ON;\n", p->out);
   26853       p->writableSchema = 1;
   26854     }
   26855     zIns = sqlite3_mprintf(
   26856        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
   26857        "VALUES('table','%q','%q',0,'%q');",
   26858        zTable, zTable, zSql);
   26859     shell_check_oom(zIns);
   26860     cli_printf(p->out, "%s\n", zIns);
   26861     sqlite3_free(zIns);
   26862     return 0;
   26863   }else{
   26864     printSchemaLine(p->out, zSql, ";\n");
   26865   }
   26866 
   26867   if( cli_strcmp(zType, "table")==0 ){
   26868     ShellText sSelect;
   26869     ShellText sTable;
   26870     char **azCol;
   26871     int i;
   26872     Mode savedMode;
   26873 
   26874     azCol = tableColumnList(p, zTable);
   26875     if( azCol==0 ){
   26876       p->nErr++;
   26877       return 0;
   26878     }
   26879 
   26880     /* Always quote the table name, even if it appears to be pure ascii,
   26881     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
   26882     initText(&sTable);
   26883     appendText(&sTable, zTable, quoteChar(zTable));
   26884     /* If preserving the rowid, add a column list after the table name.
   26885     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
   26886     ** instead of the usual "INSERT INTO tab VALUES(...)".
   26887     */
   26888     if( azCol[0] ){
   26889       appendText(&sTable, "(", 0);
   26890       appendText(&sTable, azCol[0], 0);
   26891       for(i=1; azCol[i]; i++){
   26892         appendText(&sTable, ",", 0);
   26893         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
   26894       }
   26895       appendText(&sTable, ")", 0);
   26896     }
   26897 
   26898     /* Build an appropriate SELECT statement */
   26899     initText(&sSelect);
   26900     appendText(&sSelect, "SELECT ", 0);
   26901     if( azCol[0] ){
   26902       appendText(&sSelect, azCol[0], 0);
   26903       appendText(&sSelect, ",", 0);
   26904     }
   26905     for(i=1; azCol[i]; i++){
   26906       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
   26907       if( azCol[i+1] ){
   26908         appendText(&sSelect, ",", 0);
   26909       }
   26910     }
   26911     freeColumnList(azCol);
   26912     appendText(&sSelect, " FROM ", 0);
   26913     appendText(&sSelect, zTable, quoteChar(zTable));
   26914 
   26915 
   26916     savedMode = p->mode;
   26917     p->mode.spec.zTableName = (char*)zTable;
   26918     p->mode.eMode = MODE_Insert;
   26919     p->mode.spec.eText = QRF_TEXT_Sql;
   26920     p->mode.spec.eBlob = QRF_BLOB_Sql;
   26921     p->mode.spec.bTitles = QRF_No;
   26922     p->mode.spec.nCharLimit = 0;
   26923     rc = shell_exec(p, sSelect.zTxt, 0);
   26924     if( (rc&0xff)==SQLITE_CORRUPT ){
   26925       cli_puts("/****** CORRUPTION ERROR *******/\n", p->out);
   26926       toggleSelectOrder(p->db);
   26927       shell_exec(p, sSelect.zTxt, 0);
   26928       toggleSelectOrder(p->db);
   26929     }
   26930     p->mode = savedMode;
   26931     freeText(&sTable);
   26932     freeText(&sSelect);
   26933     if( rc ) p->nErr++;
   26934   }
   26935   return 0;
   26936 }
   26937 
   26938 /*
   26939 ** Run zQuery.  Use dump_callback() as the callback routine so that
   26940 ** the contents of the query are output as SQL statements.
   26941 **
   26942 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
   26943 ** "ORDER BY rowid DESC" to the end.
   26944 */
   26945 static int run_schema_dump_query(
   26946   ShellState *p,
   26947   const char *zQuery
   26948 ){
   26949   int rc;
   26950   char *zErr = 0;
   26951   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
   26952   if( rc==SQLITE_CORRUPT ){
   26953     char *zQ2;
   26954     int len = strlen30(zQuery);
   26955     cli_puts("/****** CORRUPTION ERROR *******/\n", p->out);
   26956     if( zErr ){
   26957       cli_printf(p->out, "/****** %s ******/\n", zErr);
   26958       sqlite3_free(zErr);
   26959       zErr = 0;
   26960     }
   26961     zQ2 = malloc( len+100 );
   26962     if( zQ2==0 ) return rc;
   26963     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
   26964     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
   26965     if( rc ){
   26966       cli_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
   26967     }else{
   26968       rc = SQLITE_CORRUPT;
   26969     }
   26970     free(zQ2);
   26971   }
   26972   sqlite3_free(zErr);
   26973   return rc;
   26974 }
   26975 
   26976 /*
   26977 ** Text of help messages.
   26978 **
   26979 ** The help text for each individual command begins with a line that starts
   26980 ** with ".".  Subsequent lines are supplemental information.
   26981 **
   26982 ** There must be two or more spaces between the end of the command and the
   26983 ** start of the description of what that command does.
   26984 */
   26985 static const char *(azHelp[]) = {
   26986 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
   26987   && !defined(SQLITE_SHELL_FIDDLE)
   26988   ".archive ...             Manage SQL archives",
   26989   "   Each command must have exactly one of the following options:",
   26990   "     -c, --create               Create a new archive",
   26991   "     -u, --update               Add or update files with changed mtime",
   26992   "     -i, --insert               Like -u but always add even if unchanged",
   26993   "     -r, --remove               Remove files from archive",
   26994   "     -t, --list                 List contents of archive",
   26995   "     -x, --extract              Extract files from archive",
   26996   "   Optional arguments:",
   26997   "     -v, --verbose              Print each filename as it is processed",
   26998   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
   26999   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
   27000   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
   27001   "     -g, --glob                 Use glob matching for names in archive",
   27002   "     -n, --dryrun               Show the SQL that would have occurred",
   27003   "   Examples:",
   27004   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
   27005   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
   27006   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
   27007   "   See also:",
   27008   "      http://sqlite.org/cli.html#sqlite_archive_support",
   27009 #endif
   27010 #ifndef SQLITE_OMIT_AUTHORIZATION
   27011   ".auth ON|OFF             Show authorizer callbacks",
   27012 #endif
   27013 #ifndef SQLITE_SHELL_FIDDLE
   27014   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
   27015   "   Options:",
   27016   "       --append            Use the appendvfs",
   27017   "       --async             Write to FILE without journal and fsync()",
   27018 #endif
   27019   ".bail on|off             Stop after hitting an error.  Default OFF",
   27020 #ifndef SQLITE_SHELL_FIDDLE
   27021   ".cd DIRECTORY            Change the working directory to DIRECTORY",
   27022 #endif
   27023   ".changes on|off          Show number of rows changed by SQL",
   27024   ".check OPTIONS ...       Verify the results of a .testcase",
   27025 #ifndef SQLITE_SHELL_FIDDLE
   27026   ".clone NEWDB             Clone data into NEWDB from the existing database",
   27027 #endif
   27028   ".connection [close] [#]  Open or close an auxiliary database connection",
   27029   ".crlf ?on|off?           Whether or not to use \\r\\n line endings",
   27030   ".databases               List names and files of attached databases",
   27031   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
   27032 #if SQLITE_SHELL_HAVE_RECOVER
   27033   ".dbinfo ?DB?             Show status information about the database",
   27034 #endif
   27035   ".dbtotxt                 Hex dump of the database file",
   27036   ".dump ?OBJECTS?          Render database content as SQL",
   27037   "   Options:",
   27038   "     --data-only            Output only INSERT statements",
   27039   "     --newlines             Allow unescaped newline characters in output",
   27040   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
   27041   "     --preserve-rowids      Include ROWID values in the output",
   27042   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
   27043   "   Additional LIKE patterns can be given in subsequent arguments",
   27044   ".echo on|off             Turn command echo on or off",
   27045   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
   27046   "   Other Modes:",
   27047 #ifdef SQLITE_DEBUG
   27048   "      test                  Show raw EXPLAIN QUERY PLAN output",
   27049   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
   27050 #endif
   27051   "      trigger               Like \"full\" but also show trigger bytecode",
   27052 #ifndef SQLITE_SHELL_FIDDLE
   27053   ".excel                   Display the output of next command in spreadsheet",
   27054   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
   27055 #endif
   27056 #ifndef SQLITE_SHELL_FIDDLE
   27057   ".exit ?CODE?             Exit this program with return-code CODE",
   27058 #endif
   27059 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   27060   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
   27061 #endif
   27062   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
   27063   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
   27064   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
   27065   "   --help                  Show CMD details",
   27066   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
   27067   ",headers on|off          Turn display of headers on or off",
   27068   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
   27069 #ifndef SQLITE_SHELL_FIDDLE
   27070   ".import FILE TABLE       Import data from FILE into TABLE",
   27071 #endif
   27072 #ifndef SQLITE_OMIT_TEST_CONTROL
   27073   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
   27074 #endif
   27075   ".indexes ?PATTERN?       Show names of indexes matching PATTERN",
   27076   "   -a|--all                Also show system-generated indexes",
   27077   "   --expr                  Show only expression indexes",
   27078   "   --sys                   Show only system-generated indexes",
   27079   ".intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db",
   27080 #ifdef SQLITE_ENABLE_IOTRACE
   27081   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
   27082 #endif
   27083   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
   27084   ".lint OPTIONS            Report potential schema issues.",
   27085   "     Options:",
   27086   "        fkey-indexes     Find missing foreign key indexes",
   27087 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
   27088   ".load FILE ?ENTRY?       Load an extension library",
   27089 #endif
   27090 #if !defined(SQLITE_SHELL_FIDDLE)
   27091   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
   27092 #else
   27093   ".log on|off              Turn logging on or off.",
   27094 #endif
   27095   ".mode ?MODE? ?OPTIONS?   Set output mode",
   27096 #ifndef SQLITE_SHELL_FIDDLE
   27097   ".nonce STRING            Suspend safe mode for one command if nonce matches",
   27098 #endif
   27099   ".nullvalue STRING        Use STRING in place of NULL values",
   27100 #ifndef SQLITE_SHELL_FIDDLE
   27101   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
   27102   /* Note that .open is (partially) available in WASM builds but is
   27103   ** currently only intended to be used by the fiddle tool, not
   27104   ** end users, so is "undocumented." */
   27105   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
   27106   "     Options:",
   27107   "        --append        Use appendvfs to append database to the end of FILE",
   27108 #endif
   27109 #ifndef SQLITE_OMIT_DESERIALIZE
   27110   "        --deserialize   Load into memory using sqlite3_deserialize()",
   27111 #endif
   27112 /*"        --exclusive     Set the SQLITE_OPEN_EXCLUSIVE flag", UNDOCUMENTED */
   27113 #ifndef SQLITE_OMIT_DESERIALIZE
   27114   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
   27115 #endif
   27116   "        --ifexist       Only open if FILE already exists",
   27117 #ifndef SQLITE_OMIT_DESERIALIZE
   27118   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
   27119 #endif
   27120   "        --new           Initialize FILE to an empty database",
   27121   "        --normal        FILE is an ordinary SQLite database",
   27122   "        --nofollow      Do not follow symbolic links",
   27123   "        --readonly      Open FILE readonly",
   27124   "        --zip           FILE is a ZIP archive",
   27125 #ifndef SQLITE_SHELL_FIDDLE
   27126   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
   27127 #endif
   27128   ".parameter CMD ...       Manage SQL parameter bindings",
   27129   "   clear                   Erase all bindings",
   27130   "   init                    Initialize the TEMP table that holds bindings",
   27131   "   list                    List the current parameter bindings",
   27132   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
   27133   "                           PARAMETER should start with one of: $ : @ ?",
   27134   "   unset PARAMETER         Remove PARAMETER from the binding table",
   27135   ".print STRING...         Print literal STRING",
   27136 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   27137   ".progress N              Invoke progress handler after every N opcodes",
   27138   "   --limit N                 Interrupt after N progress callbacks",
   27139   "   --once                    Do no more than one progress interrupt",
   27140   "   --quiet|-q                No output except at interrupts",
   27141   "   --reset                   Reset the count for each input and interrupt",
   27142   "   --timeout S               Halt after running for S seconds",
   27143 #endif
   27144   ".prompt MAIN CONTINUE    Replace the standard prompts",
   27145 #ifndef SQLITE_SHELL_FIDDLE
   27146   ".quit                    Stop interpreting input stream, exit if primary.",
   27147   ".read FILE               Read input from FILE or command output",
   27148   "    If FILE begins with \"|\", it is a command that generates the input.",
   27149 #endif
   27150 #if SQLITE_SHELL_HAVE_RECOVER
   27151   ".recover                 Recover as much data as possible from corrupt db.",
   27152   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
   27153   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
   27154   "   --no-rowids              Do not attempt to recover rowid values",
   27155   "                            that are not also INTEGER PRIMARY KEYs",
   27156 #endif
   27157 #ifndef SQLITE_SHELL_FIDDLE
   27158   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
   27159   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
   27160 #endif
   27161   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
   27162   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
   27163   "   Options:",
   27164   "      --indent             Try to pretty-print the schema",
   27165   "      --nosys              Omit objects whose names start with \"sqlite_\"",
   27166   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
   27167   "    Options:",
   27168   "       --init               Create a new SELFTEST table",
   27169   "       -v                   Verbose output",
   27170   ",separator COL ?ROW?     Change the column and row separators",
   27171 #if defined(SQLITE_ENABLE_SESSION)
   27172   ".session ?NAME? CMD ...  Create or control sessions",
   27173   "   Subcommands:",
   27174   "     attach TABLE             Attach TABLE",
   27175   "     changeset FILE           Write a changeset into FILE",
   27176   "     close                    Close one session",
   27177   "     enable ?BOOLEAN?         Set or query the enable bit",
   27178   "     filter GLOB...           Reject tables matching GLOBs",
   27179   "     indirect ?BOOLEAN?       Mark or query the indirect status",
   27180   "     isempty                  Query whether the session is empty",
   27181   "     list                     List currently open session names",
   27182   "     open DB NAME             Open a new session on DB",
   27183   "     patchset FILE            Write a patchset into FILE",
   27184   "   If ?NAME? is omitted, the first defined session is used.",
   27185 #endif
   27186   ".sha3sum ...             Compute a SHA3 hash of database content",
   27187   "    Options:",
   27188   "      --schema              Also hash the sqlite_schema table",
   27189   "      --sha3-224            Use the sha3-224 algorithm",
   27190   "      --sha3-256            Use the sha3-256 algorithm (default)",
   27191   "      --sha3-384            Use the sha3-384 algorithm",
   27192   "      --sha3-512            Use the sha3-512 algorithm",
   27193   "    Any other argument is a LIKE pattern for tables to hash",
   27194 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
   27195   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
   27196 #endif
   27197   ",show                    Show the current values for various settings",
   27198   ".stats ?ARG?             Show stats or turn stats on or off",
   27199   "   off                      Turn off automatic stat display",
   27200   "   on                       Turn on automatic stat display",
   27201   "   stmt                     Show statement stats",
   27202   "   vmstep                   Show the virtual machine step count only",
   27203 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
   27204   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
   27205 #endif
   27206   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
   27207   ".testcase NAME           Begin a test case.",
   27208   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
   27209   "                           Run \".testctrl\" with no arguments for details",
   27210   ".timeout MS              Try opening locked tables for MS milliseconds",
   27211   ".timer on|off|once       Turn SQL timer on or off.",
   27212 #ifndef SQLITE_OMIT_TRACE
   27213   ".trace ?OPTIONS?         Output each SQL statement as it is run",
   27214   "    FILE                    Send output to FILE",
   27215   "    stdout                  Send output to stdout",
   27216   "    stderr                  Send output to stderr",
   27217   "    off                     Disable tracing",
   27218   "    --expanded              Expand query parameters",
   27219 #ifdef SQLITE_ENABLE_NORMALIZE
   27220   "    --normalized            Normal the SQL statements",
   27221 #endif
   27222   "    --plain                 Show SQL as it is input",
   27223   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
   27224   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
   27225   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
   27226   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
   27227 #endif /* SQLITE_OMIT_TRACE */
   27228 #ifdef SQLITE_DEBUG
   27229   ".unmodule NAME ...       Unregister virtual table modules",
   27230   "    --allexcept             Unregister everything except those named",
   27231 #endif
   27232   ".version                 Show source, library and compiler versions",
   27233   ".vfsinfo ?AUX?           Information about the top-level VFS",
   27234   ".vfslist                 List all available VFSes",
   27235   ".vfsname ?AUX?           Print the name of the VFS stack",
   27236   ",width NUM1 NUM2 ...     Set minimum column widths for columnar output",
   27237   "     Negative values right-justify",
   27238 #ifndef SQLITE_SHELL_FIDDLE
   27239   ".www                     Display output of the next command in web browser",
   27240   "    --plain                 Show results as text/plain, not as HTML",
   27241 #endif
   27242 };
   27243 
   27244 /**************************************************************
   27245 ** "Usage" help text automatically generated from comments */
   27246 static const struct {
   27247   const char *zCmd;   /* Name of the dot-command */
   27248   const char *zUsage; /* Documentation */
   27249 } aUsage[] = {
   27250   { ".import",
   27251 "USAGE: .import [OPTIONS] FILE TABLE\n"
   27252 "\n"
   27253 "Import CSV or similar text from FILE into TABLE.  If TABLE does\n"
   27254 "not exist, it is created using the first row of FILE as the column\n"
   27255 "names.  If FILE begins with \"|\" then it is a command that is run\n"
   27256 "and the output from the command is used as the input data.  If\n"
   27257 "FILE begins with \"<<\" followed by a label, then content is read from\n"
   27258 "the script until the first line that matches the label.\n"
   27259 "\n"
   27260 "The content of FILE is interpreted using RFC-4180 (\"CSV\") quoting\n"
   27261 "rules unless the current mode is \"ascii\" or \"tabs\" or unless one\n"
   27262 "the --ascii option is used.\n"
   27263 "\n"
   27264 "The column and row separators must be single ASCII characters.  If\n"
   27265 "multiple characters or a Unicode character are specified for the\n"
   27266 "separators, then only the first byte of the separator is used.  Except,\n"
   27267 "if the row separator is \\n and the mode is not --ascii, then \\r\\n is\n"
   27268 "understood as a row separator too.\n"
   27269 "\n"
   27270 "Options:\n"
   27271 "  --ascii         Do not use RFC-4180 quoting.  Use \\037 and \\036\n"
   27272 "                  as column and row separators on input, unless other\n"
   27273 "                  delimiters are specified using --colsep and/or --rowsep\n"
   27274 "  --colsep CHAR   Use CHAR as the column separator.\n"
   27275 "  --csv           Input is standard RFC-4180 CSV.\n"
   27276 "  --esc CHAR      Use CHAR as an escape character in unquoted CSV inputs.\n"
   27277 "  --qesc CHAR     Use CHAR as an escape character in quoted CSV inputs.\n"
   27278 "  --rowsep CHAR   Use CHAR as the row separator.\n"
   27279 "  --schema S      When creating TABLE, put it in schema S\n"
   27280 "  --skip N        Ignore the first N rows of input\n"
   27281 "  -v              Verbose mode\n"
   27282   },
   27283   { ".mode",
   27284 "USAGE: .mode [MODE] [OPTIONS]\n"
   27285 "\n"
   27286 "Change the output mode to MODE and/or apply OPTIONS to the output mode.\n"
   27287 "Arguments are processed from left to right.  If no arguments, show the\n"
   27288 "current output mode and relevant options.\n"
   27289 "\n"
   27290 "Options:\n"
   27291 "  --align STRING           Set the alignment of text in columnar modes\n"
   27292 "                           String consists of characters 'L', 'C', 'R'\n"
   27293 "                           meaning \"left\", \"centered\", and \"right\", with\n"
   27294 "                           one letter per column starting from the left.\n"
   27295 "                           Unspecified alignment defaults to 'L'.\n"
   27296 "  --blob-quote ARG         ARG can be \"auto\", \"text\", \"sql\", \"hex\", \"tcl\",\n"
   27297 "                           \"json\", or \"size\".  Default is \"auto\".\n"
   27298 "  --border on|off          Show outer border on \"box\" and \"table\" modes.\n"
   27299 "  --charlimit N            Set the maximum number of output characters to\n"
   27300 "                           show for any single SQL value to N. Longer values\n"
   27301 "                           truncated. Zero means \"no limit\".\n"
   27302 "  --colsep STRING          Use STRING as the column separator\n"
   27303 "  --escape ESC             Enable/disable escaping of control characters\n"
   27304 "                           found in the output. ESC can be \"off\", \"ascii\",\n"
   27305 "                           or \"symbol\".\n"
   27306 "  --linelimit N            Set the maximum number of output lines to show for\n"
   27307 "                           any single SQL value to N. Longer values are\n"
   27308 "                           truncated. Zero means \"no limit\". Only works\n"
   27309 "                           in \"line\" mode and in columnar modes.\n"
   27310 "  --limits L,C,T           Shorthand for \"--linelimit L --charlimit C\n"
   27311 "                           --titlelimit T\". The \",T\" can be omitted in which\n"
   27312 "                           case the --titlelimit is unchanged.  The argument\n"
   27313 "                           can also be \"off\" to mean \"0,0,0\" or \"on\" to\n"
   27314 "                           mean \"5,300,20\".\n"
   27315 "  --list                   List available modes\n"
   27316 "  --multiinsert N          In \"insert\" mode, put multiple rows on a single\n"
   27317 "                           INSERT statement until the size exceeds N bytes.\n"
   27318 "  --null STRING            Render SQL NULL values as the given string\n"
   27319 "  --once                   Setting changes to the right are reverted after\n"
   27320 "                           the next SQL command.\n"
   27321 "  --quote ARG              Enable/disable quoting of text. ARG can be\n"
   27322 "                           \"off\", \"on\", \"sql\", \"relaxed\", \"csv\", \"html\",\n"
   27323 "                           \"tcl\", or \"json\". \"off\" means show the text as-is.\n"
   27324 "                           \"on\" is an alias for \"sql\".\n"
   27325 "  --reset                  Changes all mode settings back to their default.\n"
   27326 "  --rowsep STRING          Use STRING as the row separator\n"
   27327 "  --sw|--screenwidth N     Declare the screen width of the output device\n"
   27328 "                           to be N characters.  An attempt may be made to\n"
   27329 "                           wrap output text to fit within this limit. Zero\n"
   27330 "                           means \"no limit\".  Or N can be \"auto\" to set the\n"
   27331 "                           width automatically.\n"
   27332 "  --tablename NAME         Set the name of the table for \"insert\" mode.\n"
   27333 "  --tag NAME               Save mode to the left as NAME.\n"
   27334 "  --textjsonb BOOLEAN      If enabled, JSONB text is displayed as text JSON.\n"
   27335 "  --title ARG              Whether or not to show column headers, and if so\n"
   27336 "                           how to encode them.  ARG can be \"off\", \"on\",\n"
   27337 "                           \"sql\", \"csv\", \"html\", \"tcl\", or \"json\".\n"
   27338 "  --titlelimit N           Limit the length of column titles to N characters.\n"
   27339 "  -v|--verbose             Verbose output\n"
   27340 "  --widths LIST            Set the columns widths for columnar modes. The\n"
   27341 "                           argument is a list of integers, one for each\n"
   27342 "                           column. A \"0\" width means use a dynamic width\n"
   27343 "                           based on the actual width of data. If there are\n"
   27344 "                           fewer entries in LIST than columns, \"0\" is used\n"
   27345 "                           for the unspecified widths.\n"
   27346 "  --wordwrap BOOLEAN       Enable/disable word wrapping\n"
   27347 "  --wrap N                 Wrap columns wider than N characters\n"
   27348 "  --ww                     Shorthand for \"--wordwrap on\"\n"
   27349   },
   27350   { ".output",
   27351 "USAGE: .output [OPTIONS] [FILE]\n"
   27352 "\n"
   27353 "Begin redirecting output to FILE.  Or if FILE is omitted, revert\n"
   27354 "to sending output to the console.  If FILE begins with \"|\" then\n"
   27355 "the remainder of file is taken as a pipe and output is directed\n"
   27356 "into that pipe.  If FILE is \"memory\" then output is captured in an\n"
   27357 "internal memory buffer.  If FILE is \"off\" then output is redirected\n"
   27358 "into /dev/null or the equivalent.\n"
   27359 "\n"
   27360 "Options:\n"
   27361 "  --bom             Prepend a byte-order mark to the output\n"
   27362 "  -e                Accumulate output in a temporary text file then\n"
   27363 "                    launch a text editor when the redirection ends.\n"
   27364 "  --error-prefix X  Use X as the left-margin prefix for error messages.\n"
   27365 "                    Set to an empty string to restore the default.\n"
   27366 "  --keep            Keep redirecting output to its current destination.\n"
   27367 "                    Use this option in combination with --show or\n"
   27368 "                    with --error-prefix when you do not want to stop\n"
   27369 "                    a current redirection.\n"
   27370 "  --plain           Use plain text rather than HTML tables with -w\n"
   27371 "  --show            Show output text captured by .testcase or by\n"
   27372 "                    redirecting to \"memory\".\n"
   27373 "  -w                Show the output in a web browser.  Output is\n"
   27374 "                    written into a temporary HTML file until the\n"
   27375 "                    redirect ends, then the web browser is launched.\n"
   27376 "                    Query results  are shown as HTML tables, unless\n"
   27377 "                    the --plain is used too.\n"
   27378 "  -x                Show the output in a spreadsheet.  Output is\n"
   27379 "                    written to a temp file as CSV then the spreadsheet\n"
   27380 "                    is launched when\n"
   27381   },
   27382   { ".once",
   27383 "USAGE: .once [OPTIONS] FILE ...\n"
   27384 "\n"
   27385 "Write the output for the next line of SQL or the next dot-command into\n"
   27386 "FILE.  If FILE begins with \"|\" then it is a program into which output\n"
   27387 "is written. The FILE argument should be omitted if one of the -e, -w,\n"
   27388 "or -x options is used.\n"
   27389 "\n"
   27390 "Options:\n"
   27391 "  -e                Capture output into a temporary file then bring up\n"
   27392 "                    a text editor on that temporary file.\n"
   27393 "  --plain           Use plain text rather than HTML tables with -w\n"
   27394 "  -w                Capture output into an HTML file then bring up that\n"
   27395 "                    file in a web browser\n"
   27396 "  -x                Show the output in a spreadsheet.  Output is\n"
   27397 "                    written to a temp file as CSV then the spreadsheet\n"
   27398 "                    is launched when\n"
   27399   },
   27400   { ".check",
   27401 "USAGE: .check [OPTIONS] PATTERN\n"
   27402 "\n"
   27403 "Verify results of commands since the most recent .testcase command.\n"
   27404 "Restore output to the console, unless --keep is used.\n"
   27405 "\n"
   27406 "If PATTERN starts with \"<<ENDMARK\" then the actual pattern is taken from\n"
   27407 "subsequent lines of text up to the first line that begins with ENDMARK.\n"
   27408 "All pattern lines and the ENDMARK are discarded.\n"
   27409 "\n"
   27410 "Options:\n"
   27411 "  --exact                Do an exact comparison including leading and\n"
   27412 "                         trailing whitespace.\n"
   27413 "  --glob                 Treat PATTERN as a GLOB\n"
   27414 "  --keep                 Do not reset the testcase.  More .check commands\n"
   27415 "                         will follow.\n"
   27416 "  --notglob              Output should not match PATTERN\n"
   27417 "  --show                 Write testcase output to the screen, for debugging.\n"
   27418   },
   27419   { ".testcase",
   27420 "USAGE: .testcase [OPTIONS] NAME\n"
   27421 "\n"
   27422 "Start a new test case identified by NAME.  All output\n"
   27423 "through the next \".check\" command is captured for comparison. See the\n"
   27424 "\".check\" commandn for additional informatioon.\n"
   27425 "\n"
   27426 "Options:\n"
   27427 "  --error-prefix TEXT       Change error message prefix text to TEXT\n"
   27428   },
   27429 };
   27430 
   27431 /*
   27432 ** Return a pointer to usage text for zCmd, or NULL if none exists.
   27433 */
   27434 static const char *findUsage(const char *zCmd){
   27435   int i;
   27436   for(i=0; i<ArraySize(aUsage); i++){
   27437     if( sqlite3_strglob(zCmd, aUsage[i].zCmd)==0 ) return aUsage[i].zUsage;
   27438   }
   27439   return 0;
   27440 }
   27441 
   27442 /*
   27443 ** Output help text for commands that match zPattern.
   27444 **
   27445 **    *   If zPattern is NULL, then show all documented commands, but
   27446 **        only give a one-line summary of each.
   27447 **
   27448 **    *   If zPattern is "-a" or "-all" or "--all" then show all help text
   27449 **        for all commands except undocumented commands.
   27450 **
   27451 **    *   If zPattern is "0" then show all help for undocumented commands.
   27452 **        Undocumented commands begin with "," instead of "." in the azHelp[]
   27453 **        array.
   27454 **
   27455 **    *   If zPattern is a prefix for one or more documented commands, then
   27456 **        show help for those commands.  If only a single command matches the
   27457 **        prefix, show the full text of the help.  If multiple commands match,
   27458 **        Only show just the first line of each.
   27459 **
   27460 **    *   Otherwise, show the complete text of any documented command for which
   27461 **        zPattern is a LIKE match for any text within that command help
   27462 **        text.
   27463 **
   27464 ** Return the number commands that match zPattern.
   27465 */
   27466 static int showHelp(FILE *out, const char *zPattern){
   27467   int i = 0;
   27468   int j = 0;
   27469   int n = 0;
   27470   char *zPat;
   27471   const char *zHit = 0;
   27472   if( zPattern==0 ){
   27473     /* Show just the first line for all help topics */
   27474     zPattern = "[a-z]";
   27475   }else if( cli_strcmp(zPattern,"-a")==0
   27476          || cli_strcmp(zPattern,"-all")==0
   27477          || cli_strcmp(zPattern,"--all")==0
   27478   ){
   27479     /* Show everything except undocumented commands */
   27480     zPattern = ".";
   27481   }else if( cli_strcmp(zPattern,"0")==0 ){
   27482     /* Show complete help text of undocumented commands */
   27483     int show = 0;
   27484     for(i=0; i<ArraySize(azHelp); i++){
   27485       if( azHelp[i][0]=='.' ){
   27486         show = 0;
   27487       }else if( azHelp[i][0]==',' ){
   27488         show = 1;
   27489         cli_printf(out, ".%s\n", &azHelp[i][1]);
   27490         n++;
   27491       }else if( show ){
   27492         cli_printf(out, "%s\n", azHelp[i]);
   27493       }
   27494     }
   27495     return n;
   27496   }
   27497 
   27498   /* Seek documented commands for which zPattern is an exact prefix */
   27499   zPat = sqlite3_mprintf(".%s*", zPattern[0]=='.' ? &zPattern[1] : zPattern);
   27500   shell_check_oom(zPat);
   27501   for(i=0; i<ArraySize(azHelp); i++){
   27502     if( sqlite3_strglob(zPat, azHelp[i])==0 ){
   27503       if( zHit ) cli_printf(out, "%s\n", zHit);
   27504       zHit = azHelp[i];
   27505       j = i+1;
   27506       n++;
   27507     }
   27508   }
   27509   if( n ){
   27510     if( n==1 ){
   27511       const char *zUsage = findUsage(zPat);
   27512       if( zUsage ){
   27513         cli_puts(zUsage, out);
   27514       }else{
   27515         /* when zPattern is a prefix of exactly one command, then include
   27516         ** the details of that command, which should begin at offset j */
   27517         cli_printf(out, "%s\n", zHit);
   27518         while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
   27519           cli_printf(out, "%s\n", azHelp[j]);
   27520           j++;
   27521         }
   27522       }
   27523     }else{
   27524       cli_printf(out, "%s\n", zHit);
   27525     }
   27526   }
   27527   sqlite3_free(zPat);
   27528   if( n ) return n;
   27529 
   27530   /* Look for documented commands that contain zPattern anywhere.
   27531   ** Show complete text of all documented commands that match. */
   27532   zPat = sqlite3_mprintf("%%%s%%", zPattern);
   27533   shell_check_oom(zPat);
   27534   for(i=0; i<ArraySize(azHelp); i++){
   27535     if( azHelp[i][0]==',' ){
   27536       while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
   27537       continue;
   27538     }
   27539     if( azHelp[i][0]=='.' ) j = i;
   27540     if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
   27541       cli_printf(out, "%s\n", azHelp[j]);
   27542       while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
   27543         j++;
   27544         cli_printf(out, "%s\n", azHelp[j]);
   27545       }
   27546       i = j;
   27547       n++;
   27548     }
   27549   }
   27550   sqlite3_free(zPat);
   27551   return n;
   27552 }
   27553 
   27554 /* Forward reference */
   27555 static int process_input(ShellState *p, const char*);
   27556 
   27557 /*
   27558 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
   27559 ** and return a pointer to the buffer. The caller is responsible for freeing
   27560 ** the memory.
   27561 **
   27562 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
   27563 ** read.
   27564 **
   27565 ** For convenience, a nul-terminator byte is always appended to the data read
   27566 ** from the file before the buffer is returned. This byte is not included in
   27567 ** the final value of (*pnByte), if applicable.
   27568 **
   27569 ** NULL is returned if any error is encountered. The final value of *pnByte
   27570 ** is undefined in this case.
   27571 */
   27572 static char *readFile(const char *zName, int *pnByte){
   27573   FILE *in = sqlite3_fopen(zName, "rb");
   27574   long nIn;
   27575   size_t nRead;
   27576   char *pBuf;
   27577   int rc;
   27578   if( in==0 ) return 0;
   27579   rc = fseek(in, 0, SEEK_END);
   27580   if( rc!=0 ){
   27581     cli_printf(stderr,"Error: '%s' not seekable\n", zName);
   27582     fclose(in);
   27583     return 0;
   27584   }
   27585   nIn = ftell(in);
   27586   rewind(in);
   27587   pBuf = sqlite3_malloc64( nIn+1 );
   27588   if( pBuf==0 ){
   27589     cli_puts("Error: out of memory\n", stderr);
   27590     fclose(in);
   27591     return 0;
   27592   }
   27593   nRead = fread(pBuf, nIn, 1, in);
   27594   fclose(in);
   27595   if( nRead!=1 ){
   27596     sqlite3_free(pBuf);
   27597     cli_printf(stderr,"Error: cannot read '%s'\n", zName);
   27598     return 0;
   27599   }
   27600   pBuf[nIn] = 0;
   27601   if( pnByte ) *pnByte = nIn;
   27602   return pBuf;
   27603 }
   27604 
   27605 #if defined(SQLITE_ENABLE_SESSION)
   27606 /*
   27607 ** Close a single OpenSession object and release all of its associated
   27608 ** resources.
   27609 */
   27610 static void session_close(OpenSession *pSession){
   27611   int i;
   27612   sqlite3session_delete(pSession->p);
   27613   sqlite3_free(pSession->zName);
   27614   for(i=0; i<pSession->nFilter; i++){
   27615     sqlite3_free(pSession->azFilter[i]);
   27616   }
   27617   sqlite3_free(pSession->azFilter);
   27618   memset(pSession, 0, sizeof(OpenSession));
   27619 }
   27620 #endif
   27621 
   27622 /*
   27623 ** Close all OpenSession objects and release all associated resources.
   27624 */
   27625 #if defined(SQLITE_ENABLE_SESSION)
   27626 static void session_close_all(ShellState *p, int i){
   27627   int j;
   27628   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
   27629   for(j=0; j<pAuxDb->nSession; j++){
   27630     session_close(&pAuxDb->aSession[j]);
   27631   }
   27632   pAuxDb->nSession = 0;
   27633 }
   27634 #else
   27635 # define session_close_all(X,Y)
   27636 #endif
   27637 
   27638 /*
   27639 ** Implementation of the xFilter function for an open session.  Omit
   27640 ** any tables named by ".session filter" but let all other table through.
   27641 */
   27642 #if defined(SQLITE_ENABLE_SESSION)
   27643 static int session_filter(void *pCtx, const char *zTab){
   27644   OpenSession *pSession = (OpenSession*)pCtx;
   27645   int i;
   27646   for(i=0; i<pSession->nFilter; i++){
   27647     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
   27648   }
   27649   return 1;
   27650 }
   27651 #endif
   27652 
   27653 /*
   27654 ** Return the size of the named file in bytes.  Or return a negative
   27655 ** number if the file does not exist.
   27656 */
   27657 static sqlite3_int64 fileSize(const char *zFile){
   27658 #if defined(_WIN32) || defined(WIN32)
   27659   struct _stat64 x;
   27660   if( _stat64(zFile, &x)!=0 ) return -1;
   27661   return (sqlite3_int64)x.st_size;
   27662 #else
   27663   struct stat x;
   27664   if( stat(zFile, &x)!=0 ) return -1;
   27665   return (sqlite3_int64)x.st_size;
   27666 #endif
   27667 }
   27668 
   27669 /*
   27670 ** Return true if zFile is an SQLite database.
   27671 **
   27672 ** Algorithm:
   27673 **    * If the file does not exist -> return false
   27674 **    * If the size of the file is not a multiple of 512 -> return false
   27675 **    * If sqlite3_open() fails -> return false
   27676 **    * if sqlite3_prepare() or sqlite3_step() fails -> return false
   27677 **    * Otherwise -> return true
   27678 */
   27679 static int isDatabaseFile(const char *zFile, int openFlags){
   27680   sqlite3 *db = 0;
   27681   sqlite3_stmt *pStmt = 0;
   27682   int rc;
   27683   sqlite3_int64 sz = fileSize(zFile);
   27684   if( sz<512 || (sz%512)!=0 ) return 0;
   27685   if( sqlite3_open_v2(zFile, &db, openFlags, 0)==SQLITE_OK
   27686    && sqlite3_prepare_v2(db,"SELECT count(*) FROM sqlite_schema",-1,&pStmt,0)
   27687            ==SQLITE_OK
   27688    && sqlite3_step(pStmt)==SQLITE_ROW
   27689   ){
   27690     rc = 1;
   27691   }else{
   27692     rc = 0;
   27693   }
   27694   sqlite3_finalize(pStmt);
   27695   sqlite3_close(db);
   27696   return rc;
   27697 }
   27698 
   27699 /*
   27700 ** Try to deduce the type of file for zName based on its content.  Return
   27701 ** one of the SHELL_OPEN_* constants.
   27702 **
   27703 ** If the file does not exist or is empty but its name looks like a ZIP
   27704 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
   27705 ** Otherwise, assume an ordinary database regardless of the filename if
   27706 ** the type cannot be determined from content.
   27707 */
   27708 static int deduceDatabaseType(const char *zName, int dfltZip, int openFlags){
   27709   FILE *f;
   27710   size_t n;
   27711   int rc = SHELL_OPEN_UNSPEC;
   27712   char zBuf[100];
   27713   if( access(zName,0)!=0 ) goto database_type_by_name;
   27714   if( isDatabaseFile(zName, openFlags) ){
   27715     rc = SHELL_OPEN_NORMAL;
   27716   }
   27717   if( rc==SHELL_OPEN_NORMAL ) return SHELL_OPEN_NORMAL;
   27718   f = sqlite3_fopen(zName, "rb");
   27719   if( f==0 ) goto database_type_by_name;
   27720   n = fread(zBuf, 16, 1, f);
   27721   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
   27722     fclose(f);
   27723     return SHELL_OPEN_NORMAL;
   27724   }
   27725   fseek(f, -25, SEEK_END);
   27726   n = fread(zBuf, 25, 1, f);
   27727   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
   27728     rc = SHELL_OPEN_APPENDVFS;
   27729   }else{
   27730     fseek(f, -22, SEEK_END);
   27731     n = fread(zBuf, 22, 1, f);
   27732     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
   27733        && zBuf[3]==0x06 ){
   27734       rc = SHELL_OPEN_ZIPFILE;
   27735     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
   27736       rc = SHELL_OPEN_ZIPFILE;
   27737     }
   27738   }
   27739   fclose(f);
   27740   return rc;
   27741 
   27742 database_type_by_name:
   27743   if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
   27744     rc = SHELL_OPEN_ZIPFILE;
   27745   }else{
   27746     rc = SHELL_OPEN_NORMAL;
   27747   }
   27748   return rc;
   27749 }
   27750 
   27751 /*
   27752 ** If the text in z[] is the name of a readable file and that file appears
   27753 ** to contain SQL text and/or dot-commands, then return true.  If z[] is
   27754 ** not a file, or if the file is unreadable, or if the file is a database
   27755 ** or anything else that is not SQL text and dot-commands, then return false.
   27756 **
   27757 ** If the bLeaveUninit flag is set, then be sure to leave SQLite in an
   27758 ** uninitialized state.  This means invoking sqlite3_shutdown() after any
   27759 ** SQLite API is used.
   27760 **
   27761 ** Some amount of guesswork is involved in this decision.
   27762 */
   27763 static int isScriptFile(const char *z, int bLeaveUninit){
   27764   sqlite3_int64 sz = fileSize(z);
   27765   if( sz<=0 ) return 0;
   27766   if( (sz%512)==0 ){
   27767     int rc;
   27768     sqlite3_initialize();
   27769     rc = isDatabaseFile(z, SQLITE_OPEN_READONLY);
   27770     if( bLeaveUninit ){
   27771       sqlite3_shutdown();
   27772     }
   27773     if( rc ) return 0;  /* Is a database */
   27774   }
   27775   if( sqlite3_strlike("%.sql",z,0)==0 ) return 1;
   27776   if( sqlite3_strlike("%.txt",z,0)==0 ) return 1;
   27777   return 0;
   27778 }
   27779 
   27780 #ifndef SQLITE_OMIT_DESERIALIZE
   27781 /*
   27782 ** Reconstruct an in-memory database using the output from the "dbtotxt"
   27783 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
   27784 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
   27785 */
   27786 static unsigned char *readHexDb(ShellState *p, int *pnData){
   27787   unsigned char *a = 0;
   27788   i64 nLine;
   27789   int n = 0;                      /* Size of db per first line of hex dump */
   27790   i64 sz = 0;                     /* n rounded up to nearest page boundary */
   27791   int pgsz = 0;
   27792   i64 iOffset = 0;
   27793   int rc;
   27794   FILE *in;
   27795   const char *zDbFilename = p->pAuxDb->zDbFilename;
   27796   unsigned int x[16];
   27797   char zLine[1000];
   27798   if( zDbFilename ){
   27799     in = sqlite3_fopen(zDbFilename, "r");
   27800     if( in==0 ){
   27801       cli_printf(stderr,"cannot open \"%s\" for reading\n", zDbFilename);
   27802       return 0;
   27803     }
   27804     nLine = 0;
   27805   }else{
   27806     in = p->in;
   27807     nLine = p->lineno;
   27808     if( in==0 ) in = stdin;
   27809   }
   27810   *pnData = 0;
   27811   nLine++;
   27812   if( sqlite3_fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
   27813   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
   27814   if( rc!=2 ) goto readHexDb_error;
   27815   if( n<0 ) goto readHexDb_error;
   27816   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
   27817     cli_puts("invalid pagesize\n", stderr);
   27818     goto readHexDb_error;
   27819   }
   27820   sz = ((i64)n+pgsz-1)&~(pgsz-1); /* Round up to nearest multiple of pgsz */
   27821   a = sqlite3_malloc64( sz ? sz : 1 );
   27822   shell_check_oom(a);
   27823   memset(a, 0, sz);
   27824   for(nLine++; sqlite3_fgets(zLine, sizeof(zLine), in)!=0; nLine++){
   27825     int j = 0;                    /* Page number from "| page" line */
   27826     int k = 0;                    /* Offset from "| page" line */
   27827     if( nLine>=2000000000 ){
   27828       cli_printf(stderr, "input too big\n");
   27829       goto readHexDb_error;
   27830     }
   27831     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
   27832     if( rc==2 ){
   27833       iOffset = k;
   27834       continue;
   27835     }
   27836     if( cli_strncmp(zLine, "| end ", 6)==0 ){
   27837       break;
   27838     }
   27839     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
   27840                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
   27841                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
   27842     if( rc==17 ){
   27843       i64 iOff = iOffset+j;
   27844       if( iOff+16<=sz && iOff>=0 ){
   27845         int ii;
   27846         for(ii=0; ii<16; ii++) a[iOff+ii] = x[ii]&0xff;
   27847       }
   27848     }
   27849   }
   27850   *pnData = sz;
   27851   if( in!=p->in ){
   27852     fclose(in);
   27853   }else{
   27854     p->lineno = nLine;
   27855   }
   27856   return a;
   27857 
   27858 readHexDb_error:
   27859   if( in!=p->in ){
   27860     fclose(in);
   27861   }else{
   27862     while( sqlite3_fgets(zLine, sizeof(zLine), p->in)!=0 ){
   27863       nLine++;
   27864       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
   27865     }
   27866     p->lineno = nLine;
   27867   }
   27868   sqlite3_free(a);
   27869   cli_printf(stderr,"Error on line %lld of --hexdb input\n", nLine);
   27870   return 0;
   27871 }
   27872 #endif /* SQLITE_OMIT_DESERIALIZE */
   27873 
   27874 /*
   27875 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
   27876 */
   27877 static void shellUSleepFunc(
   27878   sqlite3_context *context,
   27879   int argcUnused,
   27880   sqlite3_value **argv
   27881 ){
   27882   int sleep = sqlite3_value_int(argv[0]);
   27883   (void)argcUnused;
   27884   sqlite3_sleep(sleep/1000);
   27885   sqlite3_result_int(context, sleep);
   27886 }
   27887 
   27888 /*
   27889 ** SQL function:  shell_module_schema(X)
   27890 **
   27891 ** Return a fake schema for the table-valued function or eponymous virtual
   27892 ** table X.
   27893 */
   27894 static void shellModuleSchema(
   27895   sqlite3_context *pCtx,
   27896   int nVal,
   27897   sqlite3_value **apVal
   27898 ){
   27899   const char *zName;
   27900   char *zFake;
   27901   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
   27902   FILE *pSavedLog = p->pLog;
   27903   UNUSED_PARAMETER(nVal);
   27904   zName = (const char*)sqlite3_value_text(apVal[0]);
   27905 
   27906   /* Temporarily disable the ".log" when calling shellFakeSchema() because
   27907   ** shellFakeSchema() might generate failures for some ephemeral virtual
   27908   ** tables due to missing arguments.  Example: fts4aux.
   27909   ** https://sqlite.org/forum/forumpost/42fe6520b803be51 */
   27910   p->pLog = 0;
   27911   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
   27912   p->pLog = pSavedLog;
   27913 
   27914   if( zFake ){
   27915     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
   27916                         -1, sqlite3_free);
   27917     sqlite3_free(zFake);
   27918   }
   27919 }
   27920 
   27921 /* Flags for open_db().
   27922 **
   27923 ** The default behavior of open_db() is to exit(1) if the database fails to
   27924 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
   27925 ** but still returns without calling exit.
   27926 **
   27927 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
   27928 ** ZIP archive if the file does not exist or is empty and its name matches
   27929 ** the *.zip pattern.
   27930 */
   27931 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
   27932 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
   27933 
   27934 /*
   27935 ** Make sure the database is open.  If it is not, then open it.  If
   27936 ** the database fails to open, print an error message and exit.
   27937 */
   27938 static void open_db(ShellState *p, int openFlags){
   27939   if( p->db==0 ){
   27940     const char *zDbFilename = p->pAuxDb->zDbFilename;
   27941     if( p->openMode==SHELL_OPEN_UNSPEC ){
   27942       if( zDbFilename==0 || zDbFilename[0]==0 ){
   27943         p->openMode = SHELL_OPEN_NORMAL;
   27944       }else{
   27945         p->openMode = (u8)deduceDatabaseType(zDbFilename,
   27946                              (openFlags & OPEN_DB_ZIPFILE)!=0, p->openFlags);
   27947       }
   27948     }
   27949     if( (p->openFlags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE))==0 ){
   27950       if( p->openFlags==0 ) p->openFlags = SQLITE_OPEN_CREATE;
   27951       p->openFlags |= SQLITE_OPEN_READWRITE;
   27952     }
   27953     switch( p->openMode ){
   27954       case SHELL_OPEN_APPENDVFS: {
   27955         sqlite3_open_v2(zDbFilename, &p->db, p->openFlags, "apndvfs");
   27956         break;
   27957       }
   27958       case SHELL_OPEN_HEXDB:
   27959       case SHELL_OPEN_DESERIALIZE: {
   27960         sqlite3_open(0, &p->db);
   27961         break;
   27962       }
   27963       case SHELL_OPEN_ZIPFILE: {
   27964         sqlite3_open(":memory:", &p->db);
   27965         break;
   27966       }
   27967       case SHELL_OPEN_UNSPEC:
   27968       case SHELL_OPEN_NORMAL: {
   27969         sqlite3_open_v2(zDbFilename, &p->db, p->openFlags, 0);
   27970         break;
   27971       }
   27972     }
   27973     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
   27974       cli_printf(stderr,"Error: unable to open database \"%s\": %s\n",
   27975             zDbFilename, sqlite3_errmsg(p->db));
   27976       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
   27977         cli_exit(1);
   27978       }
   27979       sqlite3_close(p->db);
   27980       sqlite3_open(":memory:", &p->db);
   27981       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
   27982         cli_puts("Also: unable to open substitute in-memory database.\n",
   27983                       stderr);
   27984         cli_exit(1);
   27985       }else{
   27986         cli_printf(stderr,
   27987               "Notice: using substitute in-memory database instead of \"%s\"\n",
   27988               zDbFilename);
   27989       }
   27990     }
   27991     globalDb = p->db;
   27992     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
   27993 
   27994     /* Reflect the use or absence of --unsafe-testing invocation. */
   27995     {
   27996       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
   27997       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
   27998       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
   27999     }
   28000 
   28001 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   28002     sqlite3_enable_load_extension(p->db, 1);
   28003 #endif
   28004     sqlite3_sha_init(p->db, 0, 0);
   28005     sqlite3_shathree_init(p->db, 0, 0);
   28006     sqlite3_uint_init(p->db, 0, 0);
   28007     sqlite3_stmtrand_init(p->db, 0, 0);
   28008     sqlite3_decimal_init(p->db, 0, 0);
   28009     sqlite3_base64_init(p->db, 0, 0);
   28010     sqlite3_base85_init(p->db, 0, 0);
   28011     sqlite3_regexp_init(p->db, 0, 0);
   28012     sqlite3_ieee_init(p->db, 0, 0);
   28013     sqlite3_series_init(p->db, 0, 0);
   28014 #ifndef SQLITE_SHELL_FIDDLE
   28015     sqlite3_fileio_init(p->db, 0, 0);
   28016     sqlite3_completion_init(p->db, 0, 0);
   28017 #endif
   28018 #ifdef SQLITE_HAVE_ZLIB
   28019     if( !p->bSafeModePersist ){
   28020       sqlite3_zipfile_init(p->db, 0, 0);
   28021       sqlite3_sqlar_init(p->db, 0, 0);
   28022     }
   28023 #endif
   28024 #ifdef SQLITE_SHELL_EXTFUNCS
   28025     /* Create a preprocessing mechanism for extensions to make
   28026      * their own provisions for being built into the shell.
   28027      * This is a short-span macro. See further below for usage.
   28028      */
   28029 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
   28030 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
   28031     /* Let custom-included extensions get their ..._init() called.
   28032      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
   28033      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
   28034      * initialization routine to be called.
   28035      */
   28036     {
   28037       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
   28038     /* Let custom-included extensions expose their functionality.
   28039      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
   28040      * the SQL functions, virtual tables, collating sequences or
   28041      * VFS's implemented by the extension to be registered.
   28042      */
   28043       if( irc==SQLITE_OK
   28044           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
   28045         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
   28046       }
   28047 #undef SHELL_SUB_MACRO
   28048 #undef SHELL_SUBMACRO
   28049     }
   28050 #endif
   28051 
   28052     sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
   28053                             shellStrtod, 0, 0);
   28054     sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
   28055                             shellDtostr, 0, 0);
   28056     sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
   28057                             shellDtostr, 0, 0);
   28058     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
   28059                             shellAddSchemaName, 0, 0);
   28060     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, p,
   28061                             shellModuleSchema, 0, 0);
   28062     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
   28063                             shellPutsFunc, 0, 0);
   28064     sqlite3_create_function(p->db, "shell_format_schema", 2, SQLITE_UTF8, p,
   28065                             shellFormatSchema, 0, 0);
   28066     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
   28067                             shellUSleepFunc, 0, 0);
   28068 #ifndef SQLITE_NOHAVE_SYSTEM
   28069     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
   28070                             editFunc, 0, 0);
   28071     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
   28072                             editFunc, 0, 0);
   28073 #endif
   28074 
   28075     if( p->openMode==SHELL_OPEN_ZIPFILE ){
   28076       char *zSql = sqlite3_mprintf(
   28077          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
   28078       shell_check_oom(zSql);
   28079       sqlite3_exec(p->db, zSql, 0, 0, 0);
   28080       sqlite3_free(zSql);
   28081     }
   28082 #ifndef SQLITE_OMIT_DESERIALIZE
   28083     else
   28084     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
   28085       int rc;
   28086       int nData = 0;
   28087       unsigned char *aData;
   28088       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
   28089         aData = (unsigned char*)readFile(zDbFilename, &nData);
   28090       }else{
   28091         aData = readHexDb(p, &nData);
   28092       }
   28093       if( aData==0 ){
   28094         return;
   28095       }
   28096       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
   28097                    SQLITE_DESERIALIZE_RESIZEABLE |
   28098                    SQLITE_DESERIALIZE_FREEONCLOSE);
   28099       if( rc ){
   28100         cli_printf(stderr,"Error: sqlite3_deserialize() returns %d\n", rc);
   28101       }
   28102       if( p->szMax>0 ){
   28103         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
   28104       }
   28105     }
   28106 #endif
   28107   }
   28108   if( p->db!=0 ){
   28109 #ifndef SQLITE_OMIT_AUTHORIZATION
   28110     if( p->bSafeModePersist ){
   28111       sqlite3_set_authorizer(p->db, safeModeAuth, p);
   28112     }
   28113 #endif
   28114     sqlite3_db_config(
   28115         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->mode.scanstatsOn, (int*)0
   28116     );
   28117   }
   28118 }
   28119 
   28120 /*
   28121 ** Attempt to close the database connection.  Report errors.
   28122 */
   28123 static void close_db(sqlite3 *db){
   28124   int rc = sqlite3_close(db);
   28125   if( rc ){
   28126     cli_printf(stderr,
   28127         "Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
   28128   }
   28129 }
   28130 
   28131 #if (HAVE_READLINE || HAVE_EDITLINE) \
   28132   && !defined(SQLITE_OMIT_READLINE_COMPLETION)
   28133 /*
   28134 ** Readline completion callbacks
   28135 */
   28136 static char *readline_completion_generator(const char *text, int state){
   28137   static sqlite3_stmt *pStmt = 0;
   28138   char *zRet;
   28139   if( state==0 ){
   28140     char *zSql;
   28141     sqlite3_finalize(pStmt);
   28142     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
   28143                            "  FROM completion(%Q) ORDER BY 1", text);
   28144     shell_check_oom(zSql);
   28145     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
   28146     sqlite3_free(zSql);
   28147   }
   28148   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   28149     const char *z = (const char*)sqlite3_column_text(pStmt,0);
   28150     zRet = z ? strdup(z) : 0;
   28151   }else{
   28152     sqlite3_finalize(pStmt);
   28153     pStmt = 0;
   28154     zRet = 0;
   28155   }
   28156   return zRet;
   28157 }
   28158 static char **readline_completion(const char *zText, int iStart, int iEnd){
   28159   (void)iStart;
   28160   (void)iEnd;
   28161   rl_attempted_completion_over = 1;
   28162   return rl_completion_matches(zText, readline_completion_generator);
   28163 }
   28164 
   28165 #elif HAVE_LINENOISE
   28166 /*
   28167 ** Linenoise completion callback. Note that the 3rd argument is from
   28168 ** the "msteveb" version of linenoise, not the "antirez" version.
   28169 */
   28170 static void linenoise_completion(
   28171   const char *zLine,
   28172   linenoiseCompletions *lc
   28173 #if HAVE_LINENOISE==2
   28174   ,void *pUserData
   28175 #endif
   28176 ){
   28177   i64 nLine = strlen(zLine);
   28178   i64 i, iStart;
   28179   sqlite3_stmt *pStmt = 0;
   28180   char *zSql;
   28181   char zBuf[1000];
   28182 
   28183 #if HAVE_LINENOISE==2
   28184   UNUSED_PARAMETER(pUserData);
   28185 #endif
   28186   if( nLine>(i64)sizeof(zBuf)-30 ) return;
   28187   if( zLine[0]=='.' || zLine[0]=='#') return;
   28188   for(i=nLine-1; i>=0 && (IsAlnum(zLine[i]) || zLine[i]=='_'); i--){}
   28189   if( i==nLine-1 ) return;
   28190   iStart = i+1;
   28191   memcpy(zBuf, zLine, iStart);
   28192   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
   28193                          "  FROM completion(%Q,%Q) ORDER BY 1",
   28194                          &zLine[iStart], zLine);
   28195   shell_check_oom(zSql);
   28196   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
   28197   sqlite3_free(zSql);
   28198   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
   28199   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   28200     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
   28201     int nCompletion = sqlite3_column_bytes(pStmt, 0);
   28202     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
   28203       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
   28204       linenoiseAddCompletion(lc, zBuf);
   28205     }
   28206   }
   28207   sqlite3_finalize(pStmt);
   28208 }
   28209 #endif
   28210 
   28211 /*
   28212 ** Do C-language style dequoting.
   28213 **
   28214 **    \a    -> alarm
   28215 **    \b    -> backspace
   28216 **    \t    -> tab
   28217 **    \n    -> newline
   28218 **    \v    -> vertical tab
   28219 **    \f    -> form feed
   28220 **    \r    -> carriage return
   28221 **    \s    -> space
   28222 **    \"    -> "
   28223 **    \'    -> '
   28224 **    \\    -> backslash
   28225 **    \NNN  -> ascii character NNN in octal
   28226 **    \xHH  -> ascii character HH in hexadecimal
   28227 */
   28228 static void resolve_backslashes(char *z){
   28229   int i, j;
   28230   char c;
   28231   while( *z && *z!='\\' ) z++;
   28232   for(i=j=0; (c = z[i])!=0; i++, j++){
   28233     if( c=='\\' && z[i+1]!=0 ){
   28234       c = z[++i];
   28235       if( c=='a' ){
   28236         c = '\a';
   28237       }else if( c=='b' ){
   28238         c = '\b';
   28239       }else if( c=='t' ){
   28240         c = '\t';
   28241       }else if( c=='n' ){
   28242         c = '\n';
   28243       }else if( c=='v' ){
   28244         c = '\v';
   28245       }else if( c=='f' ){
   28246         c = '\f';
   28247       }else if( c=='r' ){
   28248         c = '\r';
   28249       }else if( c=='"' ){
   28250         c = '"';
   28251       }else if( c=='\'' ){
   28252         c = '\'';
   28253       }else if( c=='\\' ){
   28254         c = '\\';
   28255       }else if( c=='x' ){
   28256         int nhd = 0, hdv;
   28257         u8 hv = 0;
   28258         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
   28259           hv = (u8)((hv<<4)|hdv);
   28260           ++nhd;
   28261         }
   28262         i += nhd;
   28263         c = (u8)hv;
   28264       }else if( c>='0' && c<='7' ){
   28265         c -= '0';
   28266         if( z[i+1]>='0' && z[i+1]<='7' ){
   28267           i++;
   28268           c = (c<<3) + z[i] - '0';
   28269           if( z[i+1]>='0' && z[i+1]<='7' ){
   28270             i++;
   28271             c = (c<<3) + z[i] - '0';
   28272           }
   28273         }
   28274       }
   28275     }
   28276     z[j] = c;
   28277   }
   28278   if( j<i ) z[j] = 0;
   28279 }
   28280 
   28281 /*
   28282 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
   28283 ** for TRUE and FALSE.  Return the integer value if appropriate.
   28284 */
   28285 static int booleanValue(const char *zArg){
   28286   int i;
   28287   if( zArg[0]=='0' && zArg[1]=='x' ){
   28288     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
   28289   }else{
   28290     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
   28291   }
   28292   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
   28293   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
   28294     return 1;
   28295   }
   28296   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
   28297     return 0;
   28298   }
   28299   cli_printf(stderr,
   28300        "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
   28301   return 0;
   28302 }
   28303 
   28304 /*
   28305 ** Set or clear a shell flag according to a boolean value.
   28306 */
   28307 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
   28308   if( booleanValue(zArg) ){
   28309     ShellSetFlag(p, mFlag);
   28310   }else{
   28311     ShellClearFlag(p, mFlag);
   28312   }
   28313 }
   28314 
   28315 /*
   28316 ** Close an output file, assuming it is not stderr or stdout
   28317 */
   28318 static void output_file_close(FILE *f){
   28319   if( f && f!=stdout && f!=stderr ) fclose(f);
   28320 }
   28321 
   28322 /*
   28323 ** Try to open an output file.   The names "stdout" and "stderr" are
   28324 ** recognized and do the right thing.  NULL is returned if the output
   28325 ** filename is "off".
   28326 */
   28327 static FILE *output_file_open(ShellState *p, const char *zFile){
   28328   FILE *f;
   28329   if( cli_strcmp(zFile,"stdout")==0 ){
   28330     f = stdout;
   28331   }else if( cli_strcmp(zFile, "stderr")==0 ){
   28332     f = stderr;
   28333   }else if( cli_strcmp(zFile, "off")==0 || p->bSafeMode ){
   28334     f = 0;
   28335   }else{
   28336     f = sqlite3_fopen(zFile, "w");
   28337     if( f==0 ){
   28338       cli_printf(stderr,"Error: cannot open \"%s\"\n", zFile);
   28339     }
   28340   }
   28341   return f;
   28342 }
   28343 
   28344 #ifndef SQLITE_OMIT_TRACE
   28345 /*
   28346 ** A routine for handling output from sqlite3_trace().
   28347 */
   28348 static int sql_trace_callback(
   28349   unsigned mType,         /* The trace type */
   28350   void *pArg,             /* The ShellState pointer */
   28351   void *pP,               /* Usually a pointer to sqlite_stmt */
   28352   void *pX                /* Auxiliary output */
   28353 ){
   28354   ShellState *p = (ShellState*)pArg;
   28355   sqlite3_stmt *pStmt;
   28356   const char *zSql;
   28357   i64 nSql;
   28358   if( p->traceOut==0 ) return 0;
   28359   if( mType==SQLITE_TRACE_CLOSE ){
   28360     sputz(p->traceOut, "-- closing database connection\n");
   28361     return 0;
   28362   }
   28363   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
   28364     zSql = (const char*)pX;
   28365   }else{
   28366     pStmt = (sqlite3_stmt*)pP;
   28367     switch( p->eTraceType ){
   28368       case SHELL_TRACE_EXPANDED: {
   28369         zSql = sqlite3_expanded_sql(pStmt);
   28370         break;
   28371       }
   28372 #ifdef SQLITE_ENABLE_NORMALIZE
   28373       case SHELL_TRACE_NORMALIZED: {
   28374         zSql = sqlite3_normalized_sql(pStmt);
   28375         break;
   28376       }
   28377 #endif
   28378       default: {
   28379         zSql = sqlite3_sql(pStmt);
   28380         break;
   28381       }
   28382     }
   28383   }
   28384   if( zSql==0 ) return 0;
   28385   nSql = strlen(zSql);
   28386   if( nSql>1000000000 ) nSql = 1000000000;
   28387   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
   28388   switch( mType ){
   28389     case SQLITE_TRACE_ROW:
   28390     case SQLITE_TRACE_STMT: {
   28391       cli_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
   28392       break;
   28393     }
   28394     case SQLITE_TRACE_PROFILE: {
   28395       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
   28396       cli_printf(p->traceOut,
   28397                       "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
   28398       break;
   28399     }
   28400   }
   28401   return 0;
   28402 }
   28403 #endif
   28404 
   28405 /*
   28406 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
   28407 ** a useful spot to set a debugger breakpoint.
   28408 **
   28409 ** This routine does not do anything practical.  The code are there simply
   28410 ** to prevent the compiler from optimizing this routine out.
   28411 */
   28412 static void test_breakpoint(void){
   28413   static unsigned int nCall = 0;
   28414   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
   28415 }
   28416 
   28417 /*
   28418 ** An object used to read a CSV and other files for import.
   28419 */
   28420 typedef struct ImportCtx ImportCtx;
   28421 struct ImportCtx {
   28422   const char *zFile;  /* Name of the input file */
   28423   FILE *in;           /* Read the CSV text from this input stream */
   28424   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
   28425   char *zIn;          /* Input text */
   28426   char *z;            /* Accumulated text for a field */
   28427   i64 nUsed;          /* Bytes of zIn[] used so far */
   28428   i64 n;              /* Number of bytes in z */
   28429   i64 nAlloc;         /* Space allocated for z[] */
   28430   int nLine;          /* Current line number */
   28431   int nRow;           /* Number of rows imported */
   28432   int nErr;           /* Number of errors encountered */
   28433   int bNotFirst;      /* True if one or more bytes already read */
   28434   int cTerm;          /* Character that terminated the most recent field */
   28435   int cColSep;        /* The column separator character.  (Usually ",") */
   28436   int cRowSep;        /* The row separator character.  (Usually "\n") */
   28437   int cQEscape;       /* Escape character with "...".  0 for none */
   28438   int cUQEscape;      /* Escape character not with "...".  0 for none */
   28439 };
   28440 
   28441 /* Clean up resourced used by an ImportCtx */
   28442 static void import_cleanup(ImportCtx *p){
   28443   if( p->in!=0 && p->xCloser!=0 ){
   28444     p->xCloser(p->in);
   28445     p->in = 0;
   28446   }
   28447   sqlite3_free(p->z);
   28448   p->z = 0;
   28449   if( p->zIn ){
   28450     sqlite3_free(p->zIn);
   28451     p->zIn = 0;
   28452   }
   28453 }
   28454 
   28455 /* Read a single character of the .import input text.  Return EOF
   28456 ** at end-of-file.
   28457 */
   28458 static int import_getc(ImportCtx *p){
   28459   if( p->in ){
   28460     return fgetc(p->in);
   28461   }else if( p->zIn && p->zIn[p->nUsed]!=0 ){
   28462     return p->zIn[p->nUsed++];
   28463   }else{
   28464     return EOF;
   28465   }
   28466 }
   28467 
   28468 /* Append a single byte to the field value begin constructed
   28469 ** in the p->z[] buffer
   28470 */
   28471 static void import_append_char(ImportCtx *p, int c){
   28472   if( p->n+1>=p->nAlloc ){
   28473     p->nAlloc += p->nAlloc + 100;
   28474     p->z = sqlite3_realloc64(p->z, p->nAlloc);
   28475     shell_check_oom(p->z);
   28476   }
   28477   p->z[p->n++] = (char)c;
   28478 }
   28479 
   28480 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
   28481 ** with the option of having a separator other than ",".
   28482 **
   28483 **   +  Input comes from p->in.
   28484 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
   28485 **      from sqlite3_malloc64().
   28486 **   +  Use p->cColSep as the column separator.  The default is ",".
   28487 **   +  Use p->cRowSep as the row separator.  The default is "\n".
   28488 **   +  Keep track of the line number in p->nLine.
   28489 **   +  Store the character that terminates the field in p->cTerm.  Store
   28490 **      EOF on end-of-file.
   28491 **   +  Report syntax errors on stderr
   28492 */
   28493 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
   28494   int c;
   28495   int cSep = (u8)p->cColSep;
   28496   int rSep = (u8)p->cRowSep;
   28497   p->n = 0;
   28498   c = import_getc(p);
   28499   if( c==EOF || seenInterrupt ){
   28500     p->cTerm = EOF;
   28501     return 0;
   28502   }
   28503   if( c=='"' ){
   28504     int pc, ppc;
   28505     int startLine = p->nLine;
   28506     int cQuote = c;
   28507     int cEsc = (u8)p->cQEscape;
   28508     pc = ppc = 0;
   28509     while( 1 ){
   28510       c = import_getc(p);
   28511       if( c==rSep ) p->nLine++;
   28512       if( c==cEsc && cEsc!=0 ){
   28513         c = import_getc(p);
   28514         import_append_char(p, c);
   28515         ppc = pc = 0;
   28516         continue;
   28517       }
   28518       if( c==cQuote ){
   28519         if( pc==cQuote ){
   28520           pc = 0;
   28521           continue;
   28522         }
   28523       }
   28524       if( (c==cSep && pc==cQuote)
   28525        || (c==rSep && pc==cQuote)
   28526        || (c==rSep && pc=='\r' && ppc==cQuote)
   28527        || (c==EOF && pc==cQuote)
   28528       ){
   28529         do{ p->n--; }while( p->z[p->n]!=cQuote );
   28530         p->cTerm = c;
   28531         break;
   28532       }
   28533       if( pc==cQuote && c!='\r' ){
   28534         cli_printf(stderr,"%s:%d: unescaped %c character\n",
   28535                    p->zFile, p->nLine, cQuote);
   28536       }
   28537       if( c==EOF ){
   28538         cli_printf(stderr,"%s:%d: unterminated %c-quoted field\n",
   28539               p->zFile, startLine, cQuote);
   28540         p->cTerm = c;
   28541         break;
   28542       }
   28543       import_append_char(p, c);
   28544       ppc = pc;
   28545       pc = c;
   28546     }
   28547   }else{
   28548     /* If this is the first field being parsed and it begins with the
   28549     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
   28550     int cEsc = p->cUQEscape;
   28551     if( (c&0xff)==0xef && p->bNotFirst==0 ){
   28552       import_append_char(p, c);
   28553       c = import_getc(p);
   28554       if( (c&0xff)==0xbb ){
   28555         import_append_char(p, c);
   28556         c = import_getc(p);
   28557         if( (c&0xff)==0xbf ){
   28558           p->bNotFirst = 1;
   28559           p->n = 0;
   28560           return csv_read_one_field(p);
   28561         }
   28562       }
   28563     }
   28564     while( c!=EOF && c!=cSep && c!=rSep ){
   28565       if( c==cEsc && cEsc!=0 ) c = import_getc(p);
   28566       import_append_char(p, c);
   28567       c = import_getc(p);
   28568     }
   28569     if( c==rSep ){
   28570       p->nLine++;
   28571       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
   28572     }
   28573     p->cTerm = c;
   28574   }
   28575   if( p->z ) p->z[p->n] = 0;
   28576   p->bNotFirst = 1;
   28577   return p->z;
   28578 }
   28579 
   28580 /* Read a single field of ASCII delimited text.
   28581 **
   28582 **   +  Input comes from p->in.
   28583 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
   28584 **      from sqlite3_malloc64().
   28585 **   +  Use p->cColSep as the column separator.  The default is "\x1F".
   28586 **   +  Use p->cRowSep as the row separator.  The default is "\x1E".
   28587 **   +  Keep track of the row number in p->nLine.
   28588 **   +  Store the character that terminates the field in p->cTerm.  Store
   28589 **      EOF on end-of-file.
   28590 **   +  Report syntax errors on stderr
   28591 */
   28592 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
   28593   int c;
   28594   int cSep = (u8)p->cColSep;
   28595   int rSep = (u8)p->cRowSep;
   28596   p->n = 0;
   28597   c = import_getc(p);
   28598   if( c==EOF || seenInterrupt ){
   28599     p->cTerm = EOF;
   28600     return 0;
   28601   }
   28602   while( c!=EOF && c!=cSep && c!=rSep ){
   28603     import_append_char(p, c);
   28604     c = import_getc(p);
   28605   }
   28606   if( c==rSep ){
   28607     p->nLine++;
   28608   }
   28609   p->cTerm = c;
   28610   if( p->z ) p->z[p->n] = 0;
   28611   return p->z;
   28612 }
   28613 
   28614 /*
   28615 ** Try to transfer data for table zTable.  If an error is seen while
   28616 ** moving forward, try to go backwards.  The backwards movement won't
   28617 ** work for WITHOUT ROWID tables.
   28618 */
   28619 static void tryToCloneData(
   28620   ShellState *p,
   28621   sqlite3 *newDb,
   28622   const char *zTable
   28623 ){
   28624   sqlite3_stmt *pQuery = 0;
   28625   sqlite3_stmt *pInsert = 0;
   28626   char *zQuery = 0;
   28627   char *zInsert = 0;
   28628   int rc;
   28629   int i, j, n;
   28630   int nTable = strlen30(zTable);
   28631   int k = 0;
   28632   int cnt = 0;
   28633   const int spinRate = 10000;
   28634 
   28635   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
   28636   shell_check_oom(zQuery);
   28637   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   28638   if( rc ){
   28639     cli_printf(stderr,"Error %d: %s on [%s]\n",
   28640           sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
   28641     goto end_data_xfer;
   28642   }
   28643   n = sqlite3_column_count(pQuery);
   28644   zInsert = sqlite3_malloc64(200 + nTable + n*3);
   28645   shell_check_oom(zInsert);
   28646   sqlite3_snprintf(200+nTable,zInsert,
   28647                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
   28648   i = strlen30(zInsert);
   28649   for(j=1; j<n; j++){
   28650     memcpy(zInsert+i, ",?", 2);
   28651     i += 2;
   28652   }
   28653   memcpy(zInsert+i, ");", 3);
   28654   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
   28655   if( rc ){
   28656     cli_printf(stderr,"Error %d: %s on [%s]\n",
   28657           sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
   28658     goto end_data_xfer;
   28659   }
   28660   for(k=0; k<2; k++){
   28661     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
   28662       for(i=0; i<n; i++){
   28663         switch( sqlite3_column_type(pQuery, i) ){
   28664           case SQLITE_NULL: {
   28665             sqlite3_bind_null(pInsert, i+1);
   28666             break;
   28667           }
   28668           case SQLITE_INTEGER: {
   28669             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
   28670             break;
   28671           }
   28672           case SQLITE_FLOAT: {
   28673             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
   28674             break;
   28675           }
   28676           case SQLITE_TEXT: {
   28677             sqlite3_bind_text(pInsert, i+1,
   28678                              (const char*)sqlite3_column_text(pQuery,i),
   28679                              -1, SQLITE_STATIC);
   28680             break;
   28681           }
   28682           case SQLITE_BLOB: {
   28683             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
   28684                                             sqlite3_column_bytes(pQuery,i),
   28685                                             SQLITE_STATIC);
   28686             break;
   28687           }
   28688         }
   28689       } /* End for */
   28690       rc = sqlite3_step(pInsert);
   28691       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   28692         cli_printf(stderr,"Error %d: %s\n",
   28693               sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
   28694       }
   28695       sqlite3_reset(pInsert);
   28696       cnt++;
   28697       if( (cnt%spinRate)==0 ){
   28698         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
   28699         fflush(stdout);
   28700       }
   28701     } /* End while */
   28702     if( rc==SQLITE_DONE ) break;
   28703     sqlite3_finalize(pQuery);
   28704     sqlite3_free(zQuery);
   28705     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
   28706                              zTable);
   28707     shell_check_oom(zQuery);
   28708     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   28709     if( rc ){
   28710       cli_printf(stderr,"Warning: cannot step \"%s\" backwards", zTable);
   28711       break;
   28712     }
   28713   } /* End for(k=0...) */
   28714 
   28715 end_data_xfer:
   28716   sqlite3_finalize(pQuery);
   28717   sqlite3_finalize(pInsert);
   28718   sqlite3_free(zQuery);
   28719   sqlite3_free(zInsert);
   28720 }
   28721 
   28722 
   28723 /*
   28724 ** Try to transfer all rows of the schema that match zWhere.  For
   28725 ** each row, invoke xForEach() on the object defined by that row.
   28726 ** If an error is encountered while moving forward through the
   28727 ** sqlite_schema table, try again moving backwards.
   28728 */
   28729 static void tryToCloneSchema(
   28730   ShellState *p,
   28731   sqlite3 *newDb,
   28732   const char *zWhere,
   28733   void (*xForEach)(ShellState*,sqlite3*,const char*)
   28734 ){
   28735   sqlite3_stmt *pQuery = 0;
   28736   char *zQuery = 0;
   28737   int rc;
   28738   const unsigned char *zName;
   28739   const unsigned char *zSql;
   28740   char *zErrMsg = 0;
   28741 
   28742   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
   28743                            " WHERE %s ORDER BY rowid ASC", zWhere);
   28744   shell_check_oom(zQuery);
   28745   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   28746   if( rc ){
   28747     cli_printf(stderr,
   28748           "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
   28749           sqlite3_errmsg(p->db), zQuery);
   28750     goto end_schema_xfer;
   28751   }
   28752   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
   28753     zName = sqlite3_column_text(pQuery, 0);
   28754     zSql = sqlite3_column_text(pQuery, 1);
   28755     if( zName==0 || zSql==0 ) continue;
   28756     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
   28757       cli_printf(stdout, "%s... ", zName); fflush(stdout);
   28758       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
   28759       if( zErrMsg ){
   28760         cli_printf(stderr,"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
   28761         sqlite3_free(zErrMsg);
   28762         zErrMsg = 0;
   28763       }
   28764     }
   28765     if( xForEach ){
   28766       xForEach(p, newDb, (const char*)zName);
   28767     }
   28768     sputz(stdout, "done\n");
   28769   }
   28770   if( rc!=SQLITE_DONE ){
   28771     sqlite3_finalize(pQuery);
   28772     sqlite3_free(zQuery);
   28773     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
   28774                              " WHERE %s ORDER BY rowid DESC", zWhere);
   28775     shell_check_oom(zQuery);
   28776     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   28777     if( rc ){
   28778       cli_printf(stderr,"Error: (%d) %s on [%s]\n",
   28779             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
   28780       goto end_schema_xfer;
   28781     }
   28782     while( sqlite3_step(pQuery)==SQLITE_ROW ){
   28783       zName = sqlite3_column_text(pQuery, 0);
   28784       zSql = sqlite3_column_text(pQuery, 1);
   28785       if( zName==0 || zSql==0 ) continue;
   28786       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
   28787       cli_printf(stdout, "%s... ", zName); fflush(stdout);
   28788       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
   28789       if( zErrMsg ){
   28790         cli_printf(stderr,"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
   28791         sqlite3_free(zErrMsg);
   28792         zErrMsg = 0;
   28793       }
   28794       if( xForEach ){
   28795         xForEach(p, newDb, (const char*)zName);
   28796       }
   28797       sputz(stdout, "done\n");
   28798     }
   28799   }
   28800 end_schema_xfer:
   28801   sqlite3_finalize(pQuery);
   28802   sqlite3_free(zQuery);
   28803 }
   28804 
   28805 /*
   28806 ** Open a new database file named "zNewDb".  Try to recover as much information
   28807 ** as possible out of the main database (which might be corrupt) and write it
   28808 ** into zNewDb.
   28809 */
   28810 static void tryToClone(ShellState *p, const char *zNewDb){
   28811   int rc;
   28812   sqlite3 *newDb = 0;
   28813   if( access(zNewDb,0)==0 ){
   28814     cli_printf(stderr,"File \"%s\" already exists.\n", zNewDb);
   28815     return;
   28816   }
   28817   rc = sqlite3_open(zNewDb, &newDb);
   28818   if( rc ){
   28819     cli_printf(stderr,
   28820         "Cannot create output database: %s\n", sqlite3_errmsg(newDb));
   28821   }else{
   28822     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
   28823     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
   28824     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
   28825     tryToCloneSchema(p, newDb, "type!='table'", 0);
   28826     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
   28827     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
   28828   }
   28829   close_db(newDb);
   28830 }
   28831 
   28832 #ifndef SQLITE_SHELL_FIDDLE
   28833 /*
   28834 ** Change the output stream (file or pipe or console) to something else.
   28835 */
   28836 static void output_redir(ShellState *p, FILE *pfNew){
   28837   if( p->out != stdout ){
   28838     cli_puts("Output already redirected.\n", stderr);
   28839   }else{
   28840     p->out = pfNew;
   28841     setCrlfMode(p);
   28842     if( p->mode.eMode==MODE_Www ){
   28843       cli_puts(
   28844         "<!DOCTYPE html>\n"
   28845         "<HTML><BODY><PRE>\n",
   28846         p->out
   28847       );
   28848     }
   28849   }
   28850 }
   28851 
   28852 /*
   28853 ** Change the output file back to stdout.
   28854 **
   28855 ** If the p->doXdgOpen flag is set, that means the output was being
   28856 ** redirected to a temporary file named by p->zTempFile.  In that case,
   28857 ** launch start/open/xdg-open on that temporary file.
   28858 */
   28859 static void output_reset(ShellState *p){
   28860   if( p->outfile[0]=='|' ){
   28861 #ifndef SQLITE_OMIT_POPEN
   28862     pclose(p->out);
   28863 #endif
   28864   }else{
   28865     if( p->mode.eMode==MODE_Www ){
   28866       cli_puts("</PRE></BODY></HTML>\n", p->out);
   28867     }
   28868     output_file_close(p->out);
   28869 #ifndef SQLITE_NOHAVE_SYSTEM
   28870     if( p->doXdgOpen ){
   28871       const char *zXdgOpenCmd =
   28872 #if defined(_WIN32)
   28873       "start";
   28874 #elif defined(__APPLE__)
   28875       "open";
   28876 #else
   28877       "xdg-open";
   28878 #endif
   28879       char *zCmd;
   28880       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
   28881       if( system(zCmd) ){
   28882         cli_printf(stderr,"Failed: [%s]\n", zCmd);
   28883       }else{
   28884         /* Give the start/open/xdg-open command some time to get
   28885         ** going before we continue, and potential delete the
   28886         ** p->zTempFile data file out from under it */
   28887         sqlite3_sleep(2000);
   28888       }
   28889       sqlite3_free(zCmd);
   28890       modePop(p);
   28891       p->doXdgOpen = 0;
   28892     }
   28893 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
   28894   }
   28895   p->outfile[0] = 0;
   28896   p->out = stdout;
   28897   setCrlfMode(p);
   28898   if( cli_output_capture ){
   28899     sqlite3_str_free(cli_output_capture);
   28900     cli_output_capture = 0;
   28901   }
   28902 }
   28903 #else
   28904 # define output_redir(SS,pfO)
   28905 # define output_reset(SS)
   28906 #endif
   28907 
   28908 /*
   28909 ** Run an SQL command and return the single integer result.
   28910 */
   28911 static int db_int(sqlite3 *db, const char *zSql, ...){
   28912   sqlite3_stmt *pStmt;
   28913   int res = 0;
   28914   char *z;
   28915   va_list ap;
   28916   va_start(ap, zSql);
   28917   z = sqlite3_vmprintf(zSql, ap);
   28918   va_end(ap);
   28919   sqlite3_prepare_v2(db, z, -1, &pStmt, 0);
   28920   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
   28921     res = sqlite3_column_int(pStmt,0);
   28922   }
   28923   sqlite3_finalize(pStmt);
   28924   sqlite3_free(z);
   28925   return res;
   28926 }
   28927 
   28928 #if SQLITE_SHELL_HAVE_RECOVER
   28929 /*
   28930 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
   28931 */
   28932 static unsigned int get2byteInt(unsigned char *a){
   28933   return ((unsigned int)a[0]<<8) + (unsigned int)a[1];
   28934 }
   28935 static unsigned int get4byteInt(unsigned char *a){
   28936   return ((unsigned int)a[0]<<24)
   28937        + ((unsigned int)a[1]<<16)
   28938        + ((unsigned int)a[2]<<8)
   28939        + (unsigned int)a[3];
   28940 }
   28941 
   28942 /*
   28943 ** Implementation of the ".dbinfo" command.
   28944 **
   28945 ** Return 1 on error, 2 to exit, and 0 otherwise.
   28946 */
   28947 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
   28948   static const struct { const char *zName; int ofst; } aField[] = {
   28949      { "file change counter:",  24  },
   28950      { "database page count:",  28  },
   28951      { "freelist page count:",  36  },
   28952      { "schema cookie:",        40  },
   28953      { "schema format:",        44  },
   28954      { "default cache size:",   48  },
   28955      { "autovacuum top root:",  52  },
   28956      { "incremental vacuum:",   64  },
   28957      { "text encoding:",        56  },
   28958      { "user version:",         60  },
   28959      { "application id:",       68  },
   28960      { "software version:",     96  },
   28961   };
   28962   static const struct { const char *zName; const char *zSql; } aQuery[] = {
   28963      { "number of tables:",
   28964        "SELECT count(*) FROM %s WHERE type='table'" },
   28965      { "number of indexes:",
   28966        "SELECT count(*) FROM %s WHERE type='index'" },
   28967      { "number of triggers:",
   28968        "SELECT count(*) FROM %s WHERE type='trigger'" },
   28969      { "number of views:",
   28970        "SELECT count(*) FROM %s WHERE type='view'" },
   28971      { "schema size:",
   28972        "SELECT total(length(sql)) FROM %s" },
   28973   };
   28974   int i, rc;
   28975   unsigned iDataVersion;
   28976   char *zSchemaTab;
   28977   char *zDb = nArg>=2 ? azArg[1] : "main";
   28978   sqlite3_stmt *pStmt = 0;
   28979   unsigned char aHdr[100];
   28980   open_db(p, 0);
   28981   if( p->db==0 ) return 1;
   28982   rc = sqlite3_prepare_v2(p->db,
   28983              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
   28984              -1, &pStmt, 0);
   28985   if( rc ){
   28986     cli_printf(stderr,"error: %s\n", sqlite3_errmsg(p->db));
   28987     sqlite3_finalize(pStmt);
   28988     return 1;
   28989   }
   28990   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
   28991   if( sqlite3_step(pStmt)==SQLITE_ROW
   28992    && sqlite3_column_bytes(pStmt,0)>100
   28993   ){
   28994     const u8 *pb = sqlite3_column_blob(pStmt,0);
   28995     shell_check_oom(pb);
   28996     memcpy(aHdr, pb, 100);
   28997     sqlite3_finalize(pStmt);
   28998   }else{
   28999     cli_puts("unable to read database header\n", stderr);
   29000     sqlite3_finalize(pStmt);
   29001     return 1;
   29002   }
   29003   i = get2byteInt(aHdr+16);
   29004   if( i==1 ) i = 65536;
   29005   cli_printf(p->out, "%-20s %d\n", "database page size:", i);
   29006   cli_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
   29007   cli_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
   29008   cli_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
   29009   for(i=0; i<ArraySize(aField); i++){
   29010     int ofst = aField[i].ofst;
   29011     unsigned int val = get4byteInt(aHdr + ofst);
   29012     cli_printf(p->out, "%-20s %u", aField[i].zName, val);
   29013     switch( ofst ){
   29014       case 56: {
   29015         if( val==1 ) cli_puts(" (utf8)", p->out);
   29016         if( val==2 ) cli_puts(" (utf16le)", p->out);
   29017         if( val==3 ) cli_puts(" (utf16be)", p->out);
   29018       }
   29019     }
   29020     cli_puts("\n", p->out);
   29021   }
   29022   if( zDb==0 ){
   29023     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
   29024   }else if( cli_strcmp(zDb,"temp")==0 ){
   29025     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
   29026   }else{
   29027     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
   29028   }
   29029   for(i=0; i<ArraySize(aQuery); i++){
   29030     int val = db_int(p->db, aQuery[i].zSql, zSchemaTab);
   29031     cli_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
   29032   }
   29033   sqlite3_free(zSchemaTab);
   29034   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
   29035   cli_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
   29036   return 0;
   29037 }
   29038 #endif /* SQLITE_SHELL_HAVE_RECOVER */
   29039 
   29040 /*
   29041 ** Implementation of the ".dbtotxt" command.
   29042 **
   29043 ** Return 1 on error, 2 to exit, and 0 otherwise.
   29044 */
   29045 static int shell_dbtotxt_command(ShellState *p, int nArg, char **azArg){
   29046   sqlite3_stmt *pStmt = 0;
   29047   sqlite3_int64 nPage = 0;
   29048   int pgSz = 0;
   29049   const char *zTail;
   29050   char *zName = 0;
   29051   int rc, i, j;
   29052   unsigned char bShow[256];   /* Characters ok to display */
   29053 
   29054   UNUSED_PARAMETER(nArg);
   29055   UNUSED_PARAMETER(azArg);
   29056   memset(bShow, '.', sizeof(bShow));
   29057   for(i=' '; i<='~'; i++){
   29058     if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = (unsigned char)i;
   29059   }
   29060   rc = sqlite3_prepare_v2(p->db, "PRAGMA page_size", -1, &pStmt, 0);
   29061   if( rc ) goto dbtotxt_error;
   29062   rc = 0;
   29063   if( sqlite3_step(pStmt)!=SQLITE_ROW ) goto dbtotxt_error;
   29064   pgSz = sqlite3_column_int(pStmt, 0);
   29065   sqlite3_finalize(pStmt);
   29066   pStmt = 0;
   29067   if( pgSz<512 || pgSz>65536 || (pgSz&(pgSz-1))!=0 ) goto dbtotxt_error;
   29068   rc = sqlite3_prepare_v2(p->db, "PRAGMA page_count", -1, &pStmt, 0);
   29069   if( rc ) goto dbtotxt_error;
   29070   rc = 0;
   29071   if( sqlite3_step(pStmt)!=SQLITE_ROW ) goto dbtotxt_error;
   29072   nPage = sqlite3_column_int64(pStmt, 0);
   29073   sqlite3_finalize(pStmt);
   29074   pStmt = 0;
   29075   if( nPage<1 ) goto dbtotxt_error;
   29076   rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
   29077   if( rc ) goto dbtotxt_error;
   29078   if( sqlite3_step(pStmt)!=SQLITE_ROW ){
   29079     zTail = "unk.db";
   29080   }else{
   29081     const char *zFilename = (const char*)sqlite3_column_text(pStmt, 2);
   29082     if( zFilename==0 || zFilename[0]==0 ) zFilename = "unk.db";
   29083     zTail = strrchr(zFilename, '/');
   29084 #if defined(_WIN32)
   29085     if( zTail==0 ) zTail = strrchr(zFilename, '\\');
   29086 #endif
   29087     if( zTail==0 ){
   29088       zTail = zFilename;
   29089     }else if( zTail[1]!=0 ){
   29090       zTail++;
   29091     }
   29092   }
   29093   zName = strdup(zTail);
   29094   shell_check_oom(zName);
   29095   cli_printf(p->out, "| size %lld pagesize %d filename %s\n",
   29096                   nPage*pgSz, pgSz, zName);
   29097   sqlite3_finalize(pStmt);
   29098   pStmt = 0;
   29099   rc = sqlite3_prepare_v2(p->db,
   29100            "SELECT pgno, data FROM sqlite_dbpage ORDER BY pgno", -1, &pStmt, 0);
   29101   if( rc ) goto dbtotxt_error;
   29102   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   29103     sqlite3_int64 pgno = sqlite3_column_int64(pStmt, 0);
   29104     const u8 *aData = sqlite3_column_blob(pStmt, 1);
   29105     int seenPageLabel = 0;
   29106     for(i=0; i<pgSz; i+=16){
   29107       const u8 *aLine = aData+i;
   29108       for(j=0; j<16 && aLine[j]==0; j++){}
   29109       if( j==16 ) continue;
   29110       if( !seenPageLabel ){
   29111         cli_printf(p->out, "| page %lld offset %lld\n",pgno,(pgno-1)*pgSz);
   29112         seenPageLabel = 1;
   29113       }
   29114       cli_printf(p->out, "|  %5d:", i);
   29115       for(j=0; j<16; j++) cli_printf(p->out, " %02x", aLine[j]);
   29116       cli_printf(p->out, "   ");
   29117       for(j=0; j<16; j++){
   29118         unsigned char c = (unsigned char)aLine[j];
   29119         cli_printf(p->out, "%c", bShow[c]);
   29120       }
   29121       cli_printf(p->out, "\n");
   29122     }
   29123   }
   29124   sqlite3_finalize(pStmt);
   29125   cli_printf(p->out, "| end %s\n", zName);
   29126   free(zName);
   29127   return 0;
   29128 
   29129 dbtotxt_error:
   29130   if( rc ){
   29131     cli_printf(stderr, "ERROR: %s\n", sqlite3_errmsg(p->db));
   29132   }
   29133   sqlite3_finalize(pStmt);
   29134   free(zName);
   29135   return 1;
   29136 }
   29137 
   29138 /*
   29139 ** Print the given string as an error message.
   29140 */
   29141 static void shellEmitError(const char *zErr){
   29142   cli_printf(stderr,"Error: %s\n", zErr);
   29143 }
   29144 /*
   29145 ** Print the current sqlite3_errmsg() value to stderr and return 1.
   29146 */
   29147 static int shellDatabaseError(sqlite3 *db){
   29148   shellEmitError(sqlite3_errmsg(db));
   29149   return 1;
   29150 }
   29151 
   29152 /*
   29153 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
   29154 ** if they match and FALSE (0) if they do not match.
   29155 **
   29156 ** Globbing rules:
   29157 **
   29158 **      '*'       Matches any sequence of zero or more characters.
   29159 **
   29160 **      '?'       Matches exactly one character.
   29161 **
   29162 **     [...]      Matches one character from the enclosed list of
   29163 **                characters.
   29164 **
   29165 **     [^...]     Matches one character not in the enclosed list.
   29166 **
   29167 **      '#'       Matches any sequence of one or more digits with an
   29168 **                optional + or - sign in front
   29169 **
   29170 **      ' '       Any span of whitespace matches any other span of
   29171 **                whitespace.
   29172 **
   29173 ** Extra whitespace at the end of z[] is ignored.
   29174 */
   29175 static int testcase_glob(const char *zGlob, const char *z){
   29176   int c, c2;
   29177   int invert;
   29178   int seen;
   29179 
   29180   while( (c = (*(zGlob++)))!=0 ){
   29181     if( IsSpace(c) ){
   29182       if( !IsSpace(*z) ) return 0;
   29183       while( IsSpace(*zGlob) ) zGlob++;
   29184       while( IsSpace(*z) ) z++;
   29185     }else if( c=='*' ){
   29186       while( (c=(*(zGlob++))) == '*' || c=='?' ){
   29187         if( c=='?' && (*(z++))==0 ) return 0;
   29188       }
   29189       if( c==0 ){
   29190         return 1;
   29191       }else if( c=='[' ){
   29192         while( *z && testcase_glob(zGlob-1,z)==0 ){
   29193           z++;
   29194         }
   29195         return (*z)!=0;
   29196       }
   29197       while( (c2 = (*(z++)))!=0 ){
   29198         while( c2!=c ){
   29199           c2 = *(z++);
   29200           if( c2==0 ) return 0;
   29201         }
   29202         if( testcase_glob(zGlob,z) ) return 1;
   29203       }
   29204       return 0;
   29205     }else if( c=='?' ){
   29206       if( (*(z++))==0 ) return 0;
   29207     }else if( c=='[' ){
   29208       int prior_c = 0;
   29209       seen = 0;
   29210       invert = 0;
   29211       c = *(z++);
   29212       if( c==0 ) return 0;
   29213       c2 = *(zGlob++);
   29214       if( c2=='^' ){
   29215         invert = 1;
   29216         c2 = *(zGlob++);
   29217       }
   29218       if( c2==']' ){
   29219         if( c==']' ) seen = 1;
   29220         c2 = *(zGlob++);
   29221       }
   29222       while( c2 && c2!=']' ){
   29223         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
   29224           c2 = *(zGlob++);
   29225           if( c>=prior_c && c<=c2 ) seen = 1;
   29226           prior_c = 0;
   29227         }else{
   29228           if( c==c2 ){
   29229             seen = 1;
   29230           }
   29231           prior_c = c2;
   29232         }
   29233         c2 = *(zGlob++);
   29234       }
   29235       if( c2==0 || (seen ^ invert)==0 ) return 0;
   29236     }else if( c=='#' ){
   29237       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
   29238       if( !IsDigit(z[0]) ) return 0;
   29239       z++;
   29240       while( IsDigit(z[0]) ){ z++; }
   29241     }else{
   29242       if( c!=(*(z++)) ) return 0;
   29243     }
   29244   }
   29245   while( IsSpace(*z) ){ z++; }
   29246   return *z==0;
   29247 }
   29248 
   29249 
   29250 /*
   29251 ** Compare the string as a command-line option with either one or two
   29252 ** initial "-" characters.
   29253 */
   29254 static int optionMatch(const char *zStr, const char *zOpt){
   29255   if( zStr[0]!='-' ) return 0;
   29256   zStr++;
   29257   if( zStr[0]=='-' ) zStr++;
   29258   return cli_strcmp(zStr, zOpt)==0;
   29259 }
   29260 
   29261 /*
   29262 ** The input zFN is guaranteed to start with "file:" and is thus a URI
   29263 ** filename.  Extract the actual filename and return a pointer to that
   29264 ** filename in spaced obtained from sqlite3_malloc().
   29265 **
   29266 ** The caller is responsible for freeing space using sqlite3_free() when
   29267 ** it has finished with the filename.
   29268 */
   29269 static char *shellFilenameFromUri(const char *zFN){
   29270   char *zOut;
   29271   int i, j, d1, d2;
   29272 
   29273   assert( cli_strncmp(zFN,"file:",5)==0 );
   29274   zOut = sqlite3_mprintf("%s", zFN+5);
   29275   shell_check_oom(zOut);
   29276   for(i=j=0; zOut[i]!=0 && zOut[i]!='?'; i++){
   29277     if( zOut[i]!='%' ){
   29278       zOut[j++] = zOut[i];
   29279       continue;
   29280     }
   29281     d1 = hexDigitValue(zOut[i+1]);
   29282     if( d1<0 ){
   29283       zOut[j] = 0;
   29284       break;
   29285     }
   29286     d2 = hexDigitValue(zOut[i+2]);
   29287     if( d2<0 ){
   29288       zOut[j] = 0;
   29289       break;
   29290     }
   29291     zOut[j++] = d1*16 + d2;
   29292     i += 2;
   29293   }
   29294   zOut[j] = 0;
   29295   return zOut;
   29296 }
   29297 
   29298 /*
   29299 ** Delete a file.
   29300 */
   29301 static int shellDeleteFile(const char *zFilename){
   29302   int rc;
   29303 #ifdef _WIN32
   29304   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
   29305   rc = _wunlink(z);
   29306   sqlite3_free(z);
   29307 #else
   29308   rc = unlink(zFilename);
   29309 #endif
   29310   return rc;
   29311 }
   29312 
   29313 /*
   29314 ** Try to delete the temporary file (if there is one) and free the
   29315 ** memory used to hold the name of the temp file.
   29316 */
   29317 static void clearTempFile(ShellState *p){
   29318   if( p->zTempFile==0 ) return;
   29319   if( p->doXdgOpen ) return;
   29320   if( shellDeleteFile(p->zTempFile) ) return;
   29321   sqlite3_free(p->zTempFile);
   29322   p->zTempFile = 0;
   29323 }
   29324 
   29325 /* Forward reference */
   29326 static char *find_home_dir(int clearFlag);
   29327 
   29328 /*
   29329 ** Create a new temp file name with the given suffix.
   29330 **
   29331 ** Because the classic temp folders like /tmp are no longer
   29332 ** accessible to web browsers, for security reasons, create the
   29333 ** temp file in the user's home directory.
   29334 */
   29335 static void newTempFile(ShellState *p, const char *zSuffix){
   29336   char *zHome;          /* Home directory */
   29337   int i;                /* Loop counter */
   29338   sqlite3_uint64 r = 0; /* Integer with 64 bits of randomness */
   29339   char zRand[32];       /* Text string with 160 bits of randomness */
   29340 #ifdef _WIN32
   29341   const char cDirSep = '\\';
   29342 #else
   29343   const char cDirSep = '/';
   29344 #endif
   29345 
   29346   for(i=0; i<31; i++){
   29347     if( (i%12)==0 ) sqlite3_randomness(sizeof(r),&r);
   29348     zRand[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[r%36];
   29349     r /= 36;
   29350   }
   29351   zRand[i] = 0;
   29352   clearTempFile(p);
   29353   sqlite3_free(p->zTempFile);
   29354   p->zTempFile = 0;
   29355   zHome = find_home_dir(0);
   29356   p->zTempFile = sqlite3_mprintf("%s%ctemp-%s.%s",
   29357                                  zHome,cDirSep,zRand,zSuffix);
   29358   shell_check_oom(p->zTempFile);
   29359 }
   29360 
   29361 /*
   29362 ** The implementation of SQL scalar function fkey_collate_clause(), used
   29363 ** by the ".lint fkey-indexes" command. This scalar function is always
   29364 ** called with four arguments - the parent table name, the parent column name,
   29365 ** the child table name and the child column name.
   29366 **
   29367 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
   29368 **
   29369 ** If either of the named tables or columns do not exist, this function
   29370 ** returns an empty string. An empty string is also returned if both tables
   29371 ** and columns exist but have the same default collation sequence. Or,
   29372 ** if both exist but the default collation sequences are different, this
   29373 ** function returns the string " COLLATE <parent-collation>", where
   29374 ** <parent-collation> is the default collation sequence of the parent column.
   29375 */
   29376 static void shellFkeyCollateClause(
   29377   sqlite3_context *pCtx,
   29378   int nVal,
   29379   sqlite3_value **apVal
   29380 ){
   29381   sqlite3 *db = sqlite3_context_db_handle(pCtx);
   29382   const char *zParent;
   29383   const char *zParentCol;
   29384   const char *zParentSeq;
   29385   const char *zChild;
   29386   const char *zChildCol;
   29387   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
   29388   int rc;
   29389 
   29390   assert( nVal==4 );
   29391   zParent = (const char*)sqlite3_value_text(apVal[0]);
   29392   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
   29393   zChild = (const char*)sqlite3_value_text(apVal[2]);
   29394   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
   29395 
   29396   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
   29397   rc = sqlite3_table_column_metadata(
   29398       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
   29399   );
   29400   if( rc==SQLITE_OK ){
   29401     rc = sqlite3_table_column_metadata(
   29402         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
   29403     );
   29404   }
   29405 
   29406   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
   29407     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
   29408     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
   29409     sqlite3_free(z);
   29410   }
   29411 }
   29412 
   29413 
   29414 /*
   29415 ** The implementation of dot-command ".lint fkey-indexes".
   29416 */
   29417 static int lintFkeyIndexes(
   29418   ShellState *pState,             /* Current shell tool state */
   29419   char **azArg,                   /* Array of arguments passed to dot command */
   29420   int nArg                        /* Number of entries in azArg[] */
   29421 ){
   29422   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
   29423   int bVerbose = 0;               /* If -verbose is present */
   29424   int bGroupByParent = 0;         /* If -groupbyparent is present */
   29425   int i;                          /* To iterate through azArg[] */
   29426   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
   29427   int rc;                         /* Return code */
   29428   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
   29429   FILE *out = pState->out;        /* Send output here */
   29430 
   29431   /*
   29432   ** This SELECT statement returns one row for each foreign key constraint
   29433   ** in the schema of the main database. The column values are:
   29434   **
   29435   ** 0. The text of an SQL statement similar to:
   29436   **
   29437   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
   29438   **
   29439   **    This SELECT is similar to the one that the foreign keys implementation
   29440   **    needs to run internally on child tables. If there is an index that can
   29441   **    be used to optimize this query, then it can also be used by the FK
   29442   **    implementation to optimize DELETE or UPDATE statements on the parent
   29443   **    table.
   29444   **
   29445   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
   29446   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
   29447   **    contains an index that can be used to optimize the query.
   29448   **
   29449   ** 2. Human readable text that describes the child table and columns. e.g.
   29450   **
   29451   **       "child_table(child_key1, child_key2)"
   29452   **
   29453   ** 3. Human readable text that describes the parent table and columns. e.g.
   29454   **
   29455   **       "parent_table(parent_key1, parent_key2)"
   29456   **
   29457   ** 4. A full CREATE INDEX statement for an index that could be used to
   29458   **    optimize DELETE or UPDATE statements on the parent table. e.g.
   29459   **
   29460   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
   29461   **
   29462   ** 5. The name of the parent table.
   29463   **
   29464   ** These six values are used by the C logic below to generate the report.
   29465   */
   29466   const char *zSql =
   29467   "SELECT "
   29468     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
   29469     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
   29470     "  || fkey_collate_clause("
   29471     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
   29472     ", "
   29473     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
   29474     "  || group_concat('*=?', ' AND ') || ')'"
   29475     ", "
   29476     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
   29477     ", "
   29478     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
   29479     ", "
   29480     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
   29481     "  || ' ON ' || quote(s.name) || '('"
   29482     "  || group_concat(quote(f.[from]) ||"
   29483     "        fkey_collate_clause("
   29484     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
   29485     "  || ');'"
   29486     ", "
   29487     "     f.[table] "
   29488     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
   29489     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
   29490     "GROUP BY s.name, f.id "
   29491     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
   29492   ;
   29493   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
   29494 
   29495   for(i=2; i<nArg; i++){
   29496     int n = strlen30(azArg[i]);
   29497     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
   29498       bVerbose = 1;
   29499     }
   29500     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
   29501       bGroupByParent = 1;
   29502       zIndent = "    ";
   29503     }
   29504     else{
   29505       cli_printf(stderr,
   29506            "Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
   29507       return SQLITE_ERROR;
   29508     }
   29509   }
   29510 
   29511   /* Register the fkey_collate_clause() SQL function */
   29512   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
   29513       0, shellFkeyCollateClause, 0, 0
   29514   );
   29515 
   29516 
   29517   if( rc==SQLITE_OK ){
   29518     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
   29519   }
   29520   if( rc==SQLITE_OK ){
   29521     sqlite3_bind_int(pSql, 1, bGroupByParent);
   29522   }
   29523 
   29524   if( rc==SQLITE_OK ){
   29525     int rc2;
   29526     char *zPrev = 0;
   29527     while( SQLITE_ROW==sqlite3_step(pSql) ){
   29528       int res = -1;
   29529       sqlite3_stmt *pExplain = 0;
   29530       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
   29531       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
   29532       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
   29533       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
   29534       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
   29535       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
   29536 
   29537       if( zEQP==0 ) continue;
   29538       if( zGlob==0 ) continue;
   29539       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
   29540       if( rc!=SQLITE_OK ) break;
   29541       if( SQLITE_ROW==sqlite3_step(pExplain) ){
   29542         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
   29543         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
   29544                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
   29545       }
   29546       rc = sqlite3_finalize(pExplain);
   29547       if( rc!=SQLITE_OK ) break;
   29548 
   29549       if( res<0 ){
   29550         cli_puts("Error: internal error", stderr);
   29551         break;
   29552       }else{
   29553         if( bGroupByParent
   29554         && (bVerbose || res==0)
   29555         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
   29556         ){
   29557           cli_printf(out, "-- Parent table %s\n", zParent);
   29558           sqlite3_free(zPrev);
   29559           zPrev = sqlite3_mprintf("%s", zParent);
   29560         }
   29561 
   29562         if( res==0 ){
   29563           cli_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
   29564         }else if( bVerbose ){
   29565           cli_printf(out,
   29566                 "%s/* no extra indexes required for %s -> %s */\n",
   29567                 zIndent, zFrom, zTarget
   29568           );
   29569         }
   29570       }
   29571     }
   29572     sqlite3_free(zPrev);
   29573 
   29574     if( rc!=SQLITE_OK ){
   29575       cli_printf(stderr,"%s\n", sqlite3_errmsg(db));
   29576     }
   29577 
   29578     rc2 = sqlite3_finalize(pSql);
   29579     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
   29580       rc = rc2;
   29581       cli_printf(stderr,"%s\n", sqlite3_errmsg(db));
   29582     }
   29583   }else{
   29584     cli_printf(stderr,"%s\n", sqlite3_errmsg(db));
   29585   }
   29586 
   29587   return rc;
   29588 }
   29589 
   29590 /*
   29591 ** Implementation of ".lint" dot command.
   29592 */
   29593 static int lintDotCommand(
   29594   ShellState *pState,             /* Current shell tool state */
   29595   char **azArg,                   /* Array of arguments passed to dot command */
   29596   int nArg                        /* Number of entries in azArg[] */
   29597 ){
   29598   int n;
   29599   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
   29600   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
   29601   return lintFkeyIndexes(pState, azArg, nArg);
   29602 
   29603  usage:
   29604   cli_printf(stderr,"Usage %s sub-command ?switches...?\n", azArg[0]);
   29605   cli_printf(stderr, "Where sub-commands are:\n");
   29606   cli_printf(stderr, "    fkey-indexes\n");
   29607   return SQLITE_ERROR;
   29608 }
   29609 
   29610 static void shellPrepare(
   29611   sqlite3 *db,
   29612   int *pRc,
   29613   const char *zSql,
   29614   sqlite3_stmt **ppStmt
   29615 ){
   29616   *ppStmt = 0;
   29617   if( *pRc==SQLITE_OK ){
   29618     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
   29619     if( rc!=SQLITE_OK ){
   29620       cli_printf(stderr,
   29621          "sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
   29622       *pRc = rc;
   29623     }
   29624   }
   29625 }
   29626 
   29627 /*
   29628 ** Create a prepared statement using printf-style arguments for the SQL.
   29629 */
   29630 static void shellPreparePrintf(
   29631   sqlite3 *db,
   29632   int *pRc,
   29633   sqlite3_stmt **ppStmt,
   29634   const char *zFmt,
   29635   ...
   29636 ){
   29637   *ppStmt = 0;
   29638   if( *pRc==SQLITE_OK ){
   29639     va_list ap;
   29640     char *z;
   29641     va_start(ap, zFmt);
   29642     z = sqlite3_vmprintf(zFmt, ap);
   29643     va_end(ap);
   29644     if( z==0 ){
   29645       *pRc = SQLITE_NOMEM;
   29646     }else{
   29647       shellPrepare(db, pRc, z, ppStmt);
   29648       sqlite3_free(z);
   29649     }
   29650   }
   29651 }
   29652 
   29653 /*
   29654 ** Finalize the prepared statement created using shellPreparePrintf().
   29655 */
   29656 static void shellFinalize(
   29657   int *pRc,
   29658   sqlite3_stmt *pStmt
   29659 ){
   29660   if( pStmt ){
   29661     sqlite3 *db = sqlite3_db_handle(pStmt);
   29662     int rc = sqlite3_finalize(pStmt);
   29663     if( *pRc==SQLITE_OK ){
   29664       if( rc!=SQLITE_OK ){
   29665         cli_printf(stderr,"SQL error: %s\n", sqlite3_errmsg(db));
   29666       }
   29667       *pRc = rc;
   29668     }
   29669   }
   29670 }
   29671 
   29672 #if !defined SQLITE_OMIT_VIRTUALTABLE
   29673 /* Reset the prepared statement created using shellPreparePrintf().
   29674 **
   29675 ** This routine is could be marked "static".  But it is not always used,
   29676 ** depending on compile-time options.  By omitting the "static", we avoid
   29677 ** nuisance compiler warnings about "defined but not used".
   29678 */
   29679 static void shellReset(
   29680   int *pRc,
   29681   sqlite3_stmt *pStmt
   29682 ){
   29683   int rc = sqlite3_reset(pStmt);
   29684   if( *pRc==SQLITE_OK ){
   29685     if( rc!=SQLITE_OK ){
   29686       sqlite3 *db = sqlite3_db_handle(pStmt);
   29687       cli_printf(stderr,"SQL error: %s\n", sqlite3_errmsg(db));
   29688     }
   29689     *pRc = rc;
   29690   }
   29691 }
   29692 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
   29693 
   29694 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
   29695 /******************************************************************************
   29696 ** The ".archive" or ".ar" command.
   29697 */
   29698 /*
   29699 ** Structure representing a single ".ar" command.
   29700 */
   29701 typedef struct ArCommand ArCommand;
   29702 struct ArCommand {
   29703   u8 eCmd;                        /* An AR_CMD_* value */
   29704   u8 bVerbose;                    /* True if --verbose */
   29705   u8 bZip;                        /* True if the archive is a ZIP */
   29706   u8 bDryRun;                     /* True if --dry-run */
   29707   u8 bAppend;                     /* True if --append */
   29708   u8 bGlob;                       /* True if --glob */
   29709   u8 fromCmdLine;                 /* Run from -A instead of .archive */
   29710   int nArg;                       /* Number of command arguments */
   29711   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
   29712   const char *zFile;              /* --file argument, or NULL */
   29713   const char *zDir;               /* --directory argument, or NULL */
   29714   char **azArg;                   /* Array of command arguments */
   29715   ShellState *p;                  /* Shell state */
   29716   FILE *out;                      /* Output to this stream */
   29717   sqlite3 *db;                    /* Database containing the archive */
   29718 };
   29719 
   29720 /*
   29721 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
   29722 */
   29723 static int arUsage(FILE *f){
   29724   showHelp(f,"archive");
   29725   return SQLITE_ERROR;
   29726 }
   29727 
   29728 /*
   29729 ** Print an error message for the .ar command to stderr and return
   29730 ** SQLITE_ERROR.
   29731 */
   29732 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
   29733   va_list ap;
   29734   char *z;
   29735   va_start(ap, zFmt);
   29736   z = sqlite3_vmprintf(zFmt, ap);
   29737   va_end(ap);
   29738   shellEmitError(z);
   29739   if( pAr->fromCmdLine ){
   29740     cli_puts("Use \"-A\" for more help\n", stderr);
   29741   }else{
   29742     cli_puts("Use \".archive --help\" for more help\n", stderr);
   29743   }
   29744   sqlite3_free(z);
   29745   return SQLITE_ERROR;
   29746 }
   29747 
   29748 /*
   29749 ** Values for ArCommand.eCmd.
   29750 */
   29751 #define AR_CMD_CREATE       1
   29752 #define AR_CMD_UPDATE       2
   29753 #define AR_CMD_INSERT       3
   29754 #define AR_CMD_EXTRACT      4
   29755 #define AR_CMD_LIST         5
   29756 #define AR_CMD_HELP         6
   29757 #define AR_CMD_REMOVE       7
   29758 
   29759 /*
   29760 ** Other (non-command) switches.
   29761 */
   29762 #define AR_SWITCH_VERBOSE     8
   29763 #define AR_SWITCH_FILE        9
   29764 #define AR_SWITCH_DIRECTORY  10
   29765 #define AR_SWITCH_APPEND     11
   29766 #define AR_SWITCH_DRYRUN     12
   29767 #define AR_SWITCH_GLOB       13
   29768 
   29769 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
   29770   switch( eSwitch ){
   29771     case AR_CMD_CREATE:
   29772     case AR_CMD_EXTRACT:
   29773     case AR_CMD_LIST:
   29774     case AR_CMD_REMOVE:
   29775     case AR_CMD_UPDATE:
   29776     case AR_CMD_INSERT:
   29777     case AR_CMD_HELP:
   29778       if( pAr->eCmd ){
   29779         return arErrorMsg(pAr, "multiple command options");
   29780       }
   29781       pAr->eCmd = eSwitch;
   29782       break;
   29783 
   29784     case AR_SWITCH_DRYRUN:
   29785       pAr->bDryRun = 1;
   29786       break;
   29787     case AR_SWITCH_GLOB:
   29788       pAr->bGlob = 1;
   29789       break;
   29790     case AR_SWITCH_VERBOSE:
   29791       pAr->bVerbose = 1;
   29792       break;
   29793     case AR_SWITCH_APPEND:
   29794       pAr->bAppend = 1;
   29795       deliberate_fall_through; /* FALLTHRU */
   29796     case AR_SWITCH_FILE:
   29797       pAr->zFile = zArg;
   29798       break;
   29799     case AR_SWITCH_DIRECTORY:
   29800       pAr->zDir = zArg;
   29801       break;
   29802   }
   29803 
   29804   return SQLITE_OK;
   29805 }
   29806 
   29807 /*
   29808 ** Parse the command line for an ".ar" command. The results are written into
   29809 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
   29810 ** successfully, otherwise an error message is written to stderr and
   29811 ** SQLITE_ERROR returned.
   29812 */
   29813 static int arParseCommand(
   29814   char **azArg,                   /* Array of arguments passed to dot command */
   29815   int nArg,                       /* Number of entries in azArg[] */
   29816   ArCommand *pAr                  /* Populate this object */
   29817 ){
   29818   struct ArSwitch {
   29819     const char *zLong;
   29820     char cShort;
   29821     u8 eSwitch;
   29822     u8 bArg;
   29823   } aSwitch[] = {
   29824     { "create",    'c', AR_CMD_CREATE,       0 },
   29825     { "extract",   'x', AR_CMD_EXTRACT,      0 },
   29826     { "insert",    'i', AR_CMD_INSERT,       0 },
   29827     { "list",      't', AR_CMD_LIST,         0 },
   29828     { "remove",    'r', AR_CMD_REMOVE,       0 },
   29829     { "update",    'u', AR_CMD_UPDATE,       0 },
   29830     { "help",      'h', AR_CMD_HELP,         0 },
   29831     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
   29832     { "file",      'f', AR_SWITCH_FILE,      1 },
   29833     { "append",    'a', AR_SWITCH_APPEND,    1 },
   29834     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
   29835     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
   29836     { "glob",      'g', AR_SWITCH_GLOB,      0 },
   29837   };
   29838   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
   29839   struct ArSwitch *pEnd = &aSwitch[nSwitch];
   29840 
   29841   if( nArg<=1 ){
   29842     cli_printf(stderr, "Wrong number of arguments.  Usage:\n");
   29843     return arUsage(stderr);
   29844   }else{
   29845     char *z = azArg[1];
   29846     if( z[0]!='-' ){
   29847       /* Traditional style [tar] invocation */
   29848       int i;
   29849       int iArg = 2;
   29850       for(i=0; z[i]; i++){
   29851         const char *zArg = 0;
   29852         struct ArSwitch *pOpt;
   29853         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
   29854           if( z[i]==pOpt->cShort ) break;
   29855         }
   29856         if( pOpt==pEnd ){
   29857           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
   29858         }
   29859         if( pOpt->bArg ){
   29860           if( iArg>=nArg ){
   29861             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
   29862           }
   29863           zArg = azArg[iArg++];
   29864         }
   29865         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
   29866       }
   29867       pAr->nArg = nArg-iArg;
   29868       if( pAr->nArg>0 ){
   29869         pAr->azArg = &azArg[iArg];
   29870       }
   29871     }else{
   29872       /* Non-traditional invocation */
   29873       int iArg;
   29874       for(iArg=1; iArg<nArg; iArg++){
   29875         int n;
   29876         z = azArg[iArg];
   29877         if( z[0]!='-' ){
   29878           /* All remaining command line words are command arguments. */
   29879           pAr->azArg = &azArg[iArg];
   29880           pAr->nArg = nArg-iArg;
   29881           break;
   29882         }
   29883         n = strlen30(z);
   29884 
   29885         if( z[1]!='-' ){
   29886           int i;
   29887           /* One or more short options */
   29888           for(i=1; i<n; i++){
   29889             const char *zArg = 0;
   29890             struct ArSwitch *pOpt;
   29891             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
   29892               if( z[i]==pOpt->cShort ) break;
   29893             }
   29894             if( pOpt==pEnd ){
   29895               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
   29896             }
   29897             if( pOpt->bArg ){
   29898               if( i<(n-1) ){
   29899                 zArg = &z[i+1];
   29900                 i = n;
   29901               }else{
   29902                 if( iArg>=(nArg-1) ){
   29903                   return arErrorMsg(pAr, "option requires an argument: %c",
   29904                                     z[i]);
   29905                 }
   29906                 zArg = azArg[++iArg];
   29907               }
   29908             }
   29909             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
   29910           }
   29911         }else if( z[2]=='\0' ){
   29912           /* A -- option, indicating that all remaining command line words
   29913           ** are command arguments.  */
   29914           pAr->azArg = &azArg[iArg+1];
   29915           pAr->nArg = nArg-iArg-1;
   29916           break;
   29917         }else{
   29918           /* A long option */
   29919           const char *zArg = 0;             /* Argument for option, if any */
   29920           struct ArSwitch *pMatch = 0;      /* Matching option */
   29921           struct ArSwitch *pOpt;            /* Iterator */
   29922           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
   29923             const char *zLong = pOpt->zLong;
   29924             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
   29925               if( pMatch ){
   29926                 return arErrorMsg(pAr, "ambiguous option: %s",z);
   29927               }else{
   29928                 pMatch = pOpt;
   29929               }
   29930             }
   29931           }
   29932 
   29933           if( pMatch==0 ){
   29934             return arErrorMsg(pAr, "unrecognized option: %s", z);
   29935           }
   29936           if( pMatch->bArg ){
   29937             if( iArg>=(nArg-1) ){
   29938               return arErrorMsg(pAr, "option requires an argument: %s", z);
   29939             }
   29940             zArg = azArg[++iArg];
   29941           }
   29942           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
   29943         }
   29944       }
   29945     }
   29946   }
   29947   if( pAr->eCmd==0 ){
   29948     cli_printf(stderr, "Required argument missing.  Usage:\n");
   29949     return arUsage(stderr);
   29950   }
   29951   return SQLITE_OK;
   29952 }
   29953 
   29954 /*
   29955 ** This function assumes that all arguments within the ArCommand.azArg[]
   29956 ** array refer to archive members, as for the --extract, --list or --remove
   29957 ** commands. It checks that each of them are "present". If any specified
   29958 ** file is not present in the archive, an error is printed to stderr and an
   29959 ** error code returned. Otherwise, if all specified arguments are present
   29960 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
   29961 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
   29962 ** when pAr->bGlob is true.
   29963 **
   29964 ** This function strips any trailing '/' characters from each argument.
   29965 ** This is consistent with the way the [tar] command seems to work on
   29966 ** Linux.
   29967 */
   29968 static int arCheckEntries(ArCommand *pAr){
   29969   int rc = SQLITE_OK;
   29970   if( pAr->nArg ){
   29971     int i, j;
   29972     sqlite3_stmt *pTest = 0;
   29973     const char *zSel = (pAr->bGlob)
   29974       ? "SELECT name FROM %s WHERE glob($name,name)"
   29975       : "SELECT name FROM %s WHERE name=$name";
   29976 
   29977     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
   29978     j = sqlite3_bind_parameter_index(pTest, "$name");
   29979     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
   29980       char *z = pAr->azArg[i];
   29981       int n = strlen30(z);
   29982       int bOk = 0;
   29983       while( n>0 && z[n-1]=='/' ) n--;
   29984       z[n] = '\0';
   29985       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
   29986       if( SQLITE_ROW==sqlite3_step(pTest) ){
   29987         bOk = 1;
   29988       }
   29989       shellReset(&rc, pTest);
   29990       if( rc==SQLITE_OK && bOk==0 ){
   29991         cli_printf(stderr,"not found in archive: %s\n", z);
   29992         rc = SQLITE_ERROR;
   29993       }
   29994     }
   29995     shellFinalize(&rc, pTest);
   29996   }
   29997   return rc;
   29998 }
   29999 
   30000 /*
   30001 ** Format a WHERE clause that can be used against the "sqlar" table to
   30002 ** identify all archive members that match the command arguments held
   30003 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
   30004 ** The caller is responsible for eventually calling sqlite3_free() on
   30005 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
   30006 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
   30007 */
   30008 static void arWhereClause(
   30009   int *pRc,
   30010   ArCommand *pAr,
   30011   char **pzWhere                  /* OUT: New WHERE clause */
   30012 ){
   30013   char *zWhere = 0;
   30014   if( *pRc==SQLITE_OK ){
   30015     if( pAr->nArg==0 ){
   30016       zWhere = sqlite3_mprintf("1");
   30017     }else{
   30018       char *z1 = sqlite3_mprintf(pAr->bGlob ? "" : "name IN(");
   30019       char *z2 = sqlite3_mprintf("");
   30020       const char *zSep1 = "";
   30021       const char *zSep2 = "";
   30022 
   30023       int i;
   30024       for(i=0; i<pAr->nArg && z1 && z2; i++){
   30025         const char *z = pAr->azArg[i];
   30026         int n = strlen30(z);
   30027 
   30028         if( pAr->bGlob ){
   30029           z1 = sqlite3_mprintf("%z%sname GLOB '%q'", z1, zSep2, z);
   30030           z2 = sqlite3_mprintf(
   30031               "%z%ssubstr(name,1,%d) GLOB '%q/'", z2, zSep2, n+1,z
   30032           );
   30033         }else{
   30034           z1 = sqlite3_mprintf("%z%s'%q'", z1, zSep1, z);
   30035           z2 = sqlite3_mprintf("%z%ssubstr(name,1,%d) = '%q/'",z2,zSep2,n+1,z);
   30036         }
   30037         zSep1 = ", ";
   30038         zSep2 = " OR ";
   30039       }
   30040       if( z1==0 || z2==0 ){
   30041         *pRc = SQLITE_NOMEM;
   30042       }else{
   30043         zWhere = sqlite3_mprintf("(%s%s OR (name GLOB '*/*' AND (%s))) ",
   30044             z1, pAr->bGlob==0 ? ")" : "", z2
   30045         );
   30046       }
   30047       sqlite3_free(z1);
   30048       sqlite3_free(z2);
   30049     }
   30050   }
   30051   *pzWhere = zWhere;
   30052 }
   30053 
   30054 /*
   30055 ** Implementation of .ar "lisT" command.
   30056 */
   30057 static int arListCommand(ArCommand *pAr){
   30058   const char *zSql = "SELECT %s FROM %s WHERE %s";
   30059   const char *azCols[] = {
   30060     "name",
   30061     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
   30062   };
   30063 
   30064   char *zWhere = 0;
   30065   sqlite3_stmt *pSql = 0;
   30066   int rc;
   30067 
   30068   rc = arCheckEntries(pAr);
   30069   arWhereClause(&rc, pAr, &zWhere);
   30070 
   30071   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
   30072                      pAr->zSrcTable, zWhere);
   30073   if( pAr->bDryRun ){
   30074     cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql));
   30075   }else{
   30076     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
   30077       if( pAr->bVerbose ){
   30078         cli_printf(pAr->out, "%s % 10d  %s  %s\n",
   30079               sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
   30080               sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
   30081       }else{
   30082         cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
   30083       }
   30084     }
   30085   }
   30086   shellFinalize(&rc, pSql);
   30087   sqlite3_free(zWhere);
   30088   return rc;
   30089 }
   30090 
   30091 /*
   30092 ** Implementation of .ar "Remove" command.
   30093 */
   30094 static int arRemoveCommand(ArCommand *pAr){
   30095   int rc = 0;
   30096   char *zSql = 0;
   30097   char *zWhere = 0;
   30098 
   30099   if( pAr->nArg ){
   30100     /* Verify that args actually exist within the archive before proceeding.
   30101     ** And formulate a WHERE clause to match them.  */
   30102     rc = arCheckEntries(pAr);
   30103     arWhereClause(&rc, pAr, &zWhere);
   30104   }
   30105   if( rc==SQLITE_OK ){
   30106     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
   30107                            pAr->zSrcTable, zWhere);
   30108     if( pAr->bDryRun ){
   30109       cli_printf(pAr->out, "%s\n", zSql);
   30110     }else{
   30111       char *zErr = 0;
   30112       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
   30113       if( rc==SQLITE_OK ){
   30114         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
   30115         if( rc!=SQLITE_OK ){
   30116           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
   30117         }else{
   30118           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
   30119         }
   30120       }
   30121       if( zErr ){
   30122         cli_printf(stdout, "ERROR: %s\n", zErr); /* stdout? */
   30123         sqlite3_free(zErr);
   30124       }
   30125     }
   30126   }
   30127   sqlite3_free(zWhere);
   30128   sqlite3_free(zSql);
   30129   return rc;
   30130 }
   30131 
   30132 /*
   30133 ** Implementation of .ar "eXtract" command.
   30134 */
   30135 static int arExtractCommand(ArCommand *pAr){
   30136   const char *zSql1 =
   30137     "WITH dest(dpath,dlen) AS (SELECT realpath($dir),length(realpath($dir)))\n"
   30138     "SELECT ($dir || name),\n"
   30139     "       CASE WHEN $dryrun THEN 0\n"
   30140     "            ELSE writefile($dir||name, %s, mode, mtime) END\n"
   30141     "  FROM dest CROSS JOIN %s\n"
   30142     " WHERE (%s)\n"
   30143     "   AND (data IS NULL OR $pass==0)\n"                /* Dirs both passes */
   30144     "   AND dpath=substr(realpath($dir||name),1,dlen)\n" /* No escapes */
   30145     "   AND name NOT GLOB '*..[/\\]*'\n";                /* No /../ in paths */
   30146 
   30147   const char *azExtraArg[] = {
   30148     "sqlar_uncompress(data, sz)",
   30149     "data"
   30150   };
   30151 
   30152   sqlite3_stmt *pSql = 0;
   30153   int rc = SQLITE_OK;
   30154   char *zDir = 0;
   30155   char *zWhere = 0;
   30156   int i, j;
   30157 
   30158   /* If arguments are specified, check that they actually exist within
   30159   ** the archive before proceeding. And formulate a WHERE clause to
   30160   ** match them.  */
   30161   rc = arCheckEntries(pAr);
   30162   arWhereClause(&rc, pAr, &zWhere);
   30163 
   30164   if( rc==SQLITE_OK ){
   30165     if( pAr->zDir ){
   30166       zDir = sqlite3_mprintf("%s/", pAr->zDir);
   30167     }else{
   30168       zDir = sqlite3_mprintf("");
   30169     }
   30170     if( zDir==0 ) rc = SQLITE_NOMEM;
   30171   }
   30172 
   30173   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
   30174       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
   30175   );
   30176 
   30177   if( rc==SQLITE_OK ){
   30178     j = sqlite3_bind_parameter_index(pSql, "$dir");
   30179     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
   30180     j = sqlite3_bind_parameter_index(pSql, "$dryrun");
   30181     sqlite3_bind_int(pSql, j, pAr->bDryRun);
   30182 
   30183     /* Run the SELECT statement twice
   30184     **   (0) writefile() all files and directories
   30185     **   (1) writefile() for directory again
   30186     ** The second pass is so that the timestamps for extracted directories
   30187     ** will be reset to the value in the archive, since populating them
   30188     ** in the first pass will have changed the timestamp. */
   30189     for(i=0; i<2; i++){
   30190       j = sqlite3_bind_parameter_index(pSql, "$pass");
   30191       sqlite3_bind_int(pSql, j, i);
   30192       if( pAr->bDryRun ){
   30193         cli_printf(pAr->out, "%s\n", sqlite3_sql(pSql));
   30194         if( pAr->bVerbose==0 ) break;
   30195       }
   30196       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
   30197         if( i==0 && pAr->bVerbose ){
   30198           cli_printf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0));
   30199         }
   30200       }
   30201       if( pAr->bDryRun ) break;
   30202       shellReset(&rc, pSql);
   30203     }
   30204     shellFinalize(&rc, pSql);
   30205   }
   30206 
   30207   sqlite3_free(zDir);
   30208   sqlite3_free(zWhere);
   30209   return rc;
   30210 }
   30211 
   30212 /*
   30213 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
   30214 */
   30215 static int arExecSql(ArCommand *pAr, const char *zSql){
   30216   int rc;
   30217   if( pAr->bDryRun ){
   30218     cli_printf(pAr->out, "%s\n", zSql);
   30219     rc = SQLITE_OK;
   30220   }else{
   30221     char *zErr = 0;
   30222     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
   30223     if( zErr ){
   30224       cli_printf(stdout, "ERROR: %s\n", zErr);
   30225       sqlite3_free(zErr);
   30226     }
   30227   }
   30228   return rc;
   30229 }
   30230 
   30231 
   30232 /*
   30233 ** Implementation of .ar "create", "insert", and "update" commands.
   30234 **
   30235 **     create    ->     Create a new SQL archive
   30236 **     insert    ->     Insert or reinsert all files listed
   30237 **     update    ->     Insert files that have changed or that were not
   30238 **                      previously in the archive
   30239 **
   30240 ** Create the "sqlar" table in the database if it does not already exist.
   30241 ** Then add each file in the azFile[] array to the archive. Directories
   30242 ** are added recursively. If argument bVerbose is non-zero, a message is
   30243 ** printed on stdout for each file archived.
   30244 **
   30245 ** The create command is the same as update, except that it drops
   30246 ** any existing "sqlar" table before beginning.  The "insert" command
   30247 ** always overwrites every file named on the command-line, where as
   30248 ** "update" only overwrites if the size or mtime or mode has changed.
   30249 */
   30250 static int arCreateOrUpdateCommand(
   30251   ArCommand *pAr,                 /* Command arguments and options */
   30252   int bUpdate,                    /* true for a --create. */
   30253   int bOnlyIfChanged              /* Only update if file has changed */
   30254 ){
   30255   const char *zCreate =
   30256       "CREATE TABLE IF NOT EXISTS sqlar(\n"
   30257       "  name TEXT PRIMARY KEY,  -- name of the file\n"
   30258       "  mode INT,               -- access permissions\n"
   30259       "  mtime INT,              -- last modification time\n"
   30260       "  sz INT,                 -- original file size\n"
   30261       "  data BLOB               -- compressed content\n"
   30262       ")";
   30263   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
   30264   const char *zInsertFmt[2] = {
   30265      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
   30266      "  SELECT\n"
   30267      "    %s,\n"
   30268      "    mode,\n"
   30269      "    mtime,\n"
   30270      "    CASE substr(lsmode(mode),1,1)\n"
   30271      "      WHEN '-' THEN length(data)\n"
   30272      "      WHEN 'd' THEN 0\n"
   30273      "      ELSE -1 END,\n"
   30274      "    sqlar_compress(data)\n"
   30275      "  FROM fsdir(%Q,%Q) AS disk\n"
   30276      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
   30277      ,
   30278      "REPLACE INTO %s(name,mode,mtime,data)\n"
   30279      "  SELECT\n"
   30280      "    %s,\n"
   30281      "    mode,\n"
   30282      "    mtime,\n"
   30283      "    data\n"
   30284      "  FROM fsdir(%Q,%Q) AS disk\n"
   30285      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
   30286   };
   30287   int i;                          /* For iterating through azFile[] */
   30288   int rc;                         /* Return code */
   30289   const char *zTab = 0;           /* SQL table into which to insert */
   30290   char *zSql;
   30291   char zTemp[50];
   30292   char *zExists = 0;
   30293 
   30294   arExecSql(pAr, "PRAGMA page_size=512");
   30295   rc = arExecSql(pAr, "SAVEPOINT ar;");
   30296   if( rc!=SQLITE_OK ) return rc;
   30297   zTemp[0] = 0;
   30298   if( pAr->bZip ){
   30299     /* Initialize the zipfile virtual table, if necessary */
   30300     if( pAr->zFile ){
   30301       sqlite3_uint64 r;
   30302       sqlite3_randomness(sizeof(r),&r);
   30303       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
   30304       zTab = zTemp;
   30305       zSql = sqlite3_mprintf(
   30306          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
   30307          zTab, pAr->zFile
   30308       );
   30309       rc = arExecSql(pAr, zSql);
   30310       sqlite3_free(zSql);
   30311     }else{
   30312       zTab = "zip";
   30313     }
   30314   }else{
   30315     /* Initialize the table for an SQLAR */
   30316     zTab = "sqlar";
   30317     if( bUpdate==0 ){
   30318       rc = arExecSql(pAr, zDrop);
   30319       if( rc!=SQLITE_OK ) goto end_ar_transaction;
   30320     }
   30321     rc = arExecSql(pAr, zCreate);
   30322   }
   30323   if( bOnlyIfChanged ){
   30324     zExists = sqlite3_mprintf(
   30325       " AND NOT EXISTS("
   30326           "SELECT 1 FROM %s AS mem"
   30327           " WHERE mem.name=disk.name"
   30328           " AND mem.mtime=disk.mtime"
   30329           " AND mem.mode=disk.mode)", zTab);
   30330   }else{
   30331     zExists = sqlite3_mprintf("");
   30332   }
   30333   if( zExists==0 ) rc = SQLITE_NOMEM;
   30334   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
   30335     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
   30336         pAr->bVerbose ? "shell_putsnl(name)" : "name",
   30337         pAr->azArg[i], pAr->zDir, zExists);
   30338     rc = arExecSql(pAr, zSql2);
   30339     sqlite3_free(zSql2);
   30340   }
   30341 end_ar_transaction:
   30342   if( rc!=SQLITE_OK ){
   30343     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
   30344   }else{
   30345     rc = arExecSql(pAr, "RELEASE ar;");
   30346     if( pAr->bZip && pAr->zFile ){
   30347       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
   30348       arExecSql(pAr, zSql);
   30349       sqlite3_free(zSql);
   30350     }
   30351   }
   30352   sqlite3_free(zExists);
   30353   return rc;
   30354 }
   30355 
   30356 /*
   30357 ** Implementation of ".ar" dot command.
   30358 */
   30359 static int arDotCommand(
   30360   ShellState *pState,          /* Current shell tool state */
   30361   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
   30362   char **azArg,                /* Array of arguments passed to dot command */
   30363   int nArg                     /* Number of entries in azArg[] */
   30364 ){
   30365   ArCommand cmd;
   30366   int rc;
   30367   memset(&cmd, 0, sizeof(cmd));
   30368   cmd.fromCmdLine = fromCmdLine;
   30369   rc = arParseCommand(azArg, nArg, &cmd);
   30370   if( rc==SQLITE_OK ){
   30371     int eDbType = SHELL_OPEN_UNSPEC;
   30372     cmd.p = pState;
   30373     cmd.out = pState->out;
   30374     cmd.db = pState->db;
   30375     if( cmd.zFile ){
   30376       eDbType = deduceDatabaseType(cmd.zFile, 1, 0);
   30377     }else{
   30378       eDbType = pState->openMode;
   30379     }
   30380     if( eDbType==SHELL_OPEN_ZIPFILE ){
   30381       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
   30382         if( cmd.zFile==0 ){
   30383           cmd.zSrcTable = sqlite3_mprintf("zip");
   30384         }else{
   30385           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
   30386         }
   30387       }
   30388       cmd.bZip = 1;
   30389     }else if( cmd.zFile ){
   30390       int flags;
   30391       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
   30392       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
   30393            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
   30394         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
   30395       }else{
   30396         flags = SQLITE_OPEN_READONLY;
   30397       }
   30398       cmd.db = 0;
   30399       if( cmd.bDryRun ){
   30400         cli_printf(cmd.out, "-- open database '%s'%s\n", cmd.zFile,
   30401               eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
   30402       }
   30403       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
   30404              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
   30405       if( rc!=SQLITE_OK ){
   30406         cli_printf(stderr, "cannot open file: %s (%s)\n",
   30407                         cmd.zFile, sqlite3_errmsg(cmd.db));
   30408         goto end_ar_command;
   30409       }
   30410       sqlite3_fileio_init(cmd.db, 0, 0);
   30411       sqlite3_sqlar_init(cmd.db, 0, 0);
   30412       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
   30413                               shellPutsFunc, 0, 0);
   30414 
   30415     }
   30416     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
   30417       if( cmd.eCmd!=AR_CMD_CREATE
   30418        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
   30419       ){
   30420         cli_printf(stderr, "database does not contain an 'sqlar' table\n");
   30421         rc = SQLITE_ERROR;
   30422         goto end_ar_command;
   30423       }
   30424       cmd.zSrcTable = sqlite3_mprintf("sqlar");
   30425     }
   30426 
   30427     switch( cmd.eCmd ){
   30428       case AR_CMD_CREATE:
   30429         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
   30430         break;
   30431 
   30432       case AR_CMD_EXTRACT:
   30433         rc = arExtractCommand(&cmd);
   30434         break;
   30435 
   30436       case AR_CMD_LIST:
   30437         rc = arListCommand(&cmd);
   30438         break;
   30439 
   30440       case AR_CMD_HELP:
   30441         arUsage(pState->out);
   30442         break;
   30443 
   30444       case AR_CMD_INSERT:
   30445         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
   30446         break;
   30447 
   30448       case AR_CMD_REMOVE:
   30449         rc = arRemoveCommand(&cmd);
   30450         break;
   30451 
   30452       default:
   30453         assert( cmd.eCmd==AR_CMD_UPDATE );
   30454         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
   30455         break;
   30456     }
   30457   }
   30458 end_ar_command:
   30459   if( cmd.db!=pState->db ){
   30460     close_db(cmd.db);
   30461   }
   30462   sqlite3_free(cmd.zSrcTable);
   30463 
   30464   return rc;
   30465 }
   30466 /* End of the ".archive" or ".ar" command logic
   30467 *******************************************************************************/
   30468 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
   30469 
   30470 #if SQLITE_SHELL_HAVE_RECOVER
   30471 
   30472 /*
   30473 ** This function is used as a callback by the recover extension. Simply
   30474 ** print the supplied SQL statement to stdout.
   30475 */
   30476 static int recoverSqlCb(void *pCtx, const char *zSql){
   30477   ShellState *pState = (ShellState*)pCtx;
   30478   cli_printf(pState->out, "%s;\n", zSql);
   30479   return SQLITE_OK;
   30480 }
   30481 
   30482 /*
   30483 ** This function is called to recover data from the database. A script
   30484 ** to construct a new database containing all recovered data is output
   30485 ** on stream pState->out.
   30486 */
   30487 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
   30488   int rc = SQLITE_OK;
   30489   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
   30490   const char *zLAF = "lost_and_found";
   30491   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
   30492   int bRowids = 1;                /* 0 if --no-rowids */
   30493   sqlite3_recover *p = 0;
   30494   int i = 0;
   30495 
   30496   for(i=1; i<nArg; i++){
   30497     char *z = azArg[i];
   30498     int n;
   30499     if( z[0]=='-' && z[1]=='-' ) z++;
   30500     n = strlen30(z);
   30501     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
   30502       bFreelist = 0;
   30503     }else
   30504     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
   30505       /* This option determines the name of the ATTACH-ed database used
   30506       ** internally by the recovery extension.  The default is "" which
   30507       ** means to use a temporary database that is automatically deleted
   30508       ** when closed.  This option is undocumented and might disappear at
   30509       ** any moment. */
   30510       i++;
   30511       zRecoveryDb = azArg[i];
   30512     }else
   30513     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
   30514       i++;
   30515       zLAF = azArg[i];
   30516     }else
   30517     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
   30518       bRowids = 0;
   30519     }
   30520     else{
   30521       cli_printf(stderr,"unexpected option: %s\n", azArg[i]);
   30522       showHelp(pState->out, azArg[0]);
   30523       return 1;
   30524     }
   30525   }
   30526 
   30527   p = sqlite3_recover_init_sql(
   30528       pState->db, "main", recoverSqlCb, (void*)pState
   30529   );
   30530 
   30531   if( !pState->bSafeMode ){
   30532     sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
   30533   }
   30534   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
   30535   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
   30536   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
   30537 
   30538   cli_printf(pState->out, ".dbconfig defensive off\n");
   30539   sqlite3_recover_run(p);
   30540   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
   30541     const char *zErr = sqlite3_recover_errmsg(p);
   30542     int errCode = sqlite3_recover_errcode(p);
   30543     cli_printf(stderr,"sql error: %s (%d)\n", zErr, errCode);
   30544   }
   30545   rc = sqlite3_recover_finish(p);
   30546   return rc;
   30547 }
   30548 #endif /* SQLITE_SHELL_HAVE_RECOVER */
   30549 
   30550 /*
   30551 ** Implementation of ".intck STEPS_PER_UNLOCK" command.
   30552 */
   30553 static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){
   30554   sqlite3_intck *p = 0;
   30555   int rc = SQLITE_OK;
   30556 
   30557   rc = sqlite3_intck_open(pState->db, "main", &p);
   30558   if( rc==SQLITE_OK ){
   30559     i64 nStep = 0;
   30560     i64 nError = 0;
   30561     const char *zErr = 0;
   30562     while( SQLITE_OK==sqlite3_intck_step(p) ){
   30563       const char *zMsg = sqlite3_intck_message(p);
   30564       if( zMsg ){
   30565         cli_printf(pState->out, "%s\n", zMsg);
   30566         nError++;
   30567       }
   30568       nStep++;
   30569       if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){
   30570         sqlite3_intck_unlock(p);
   30571       }
   30572     }
   30573     rc = sqlite3_intck_error(p, &zErr);
   30574     if( zErr ){
   30575       cli_printf(stderr,"%s\n", zErr);
   30576     }
   30577     sqlite3_intck_close(p);
   30578 
   30579     cli_printf(pState->out, "%lld steps, %lld errors\n", nStep, nError);
   30580   }
   30581 
   30582   return rc;
   30583 }
   30584 
   30585 /*
   30586  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
   30587  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
   30588  *   close db and set it to 0, and return the columns spec, to later
   30589  *   be sqlite3_free()'ed by the caller.
   30590  * The return is 0 when either:
   30591  *   (a) The db was not initialized and zCol==0 (There are no columns.)
   30592  *   (b) zCol!=0  (Column was added, db initialized as needed.)
   30593  * The 3rd argument, pRenamed, references an out parameter. If the
   30594  * pointer is non-zero, its referent will be set to a summary of renames
   30595  * done if renaming was necessary, or set to 0 if none was done. The out
   30596  * string (if any) must be sqlite3_free()'ed by the caller.
   30597  */
   30598 #ifdef SHELL_DEBUG
   30599 #define rc_err_oom_die(rc) \
   30600   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
   30601   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
   30602     cli_printf(stderr,"E:%d\n",rc), assert(0)
   30603 #else
   30604 static void rc_err_oom_die(int rc){
   30605   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
   30606   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
   30607 }
   30608 #endif
   30609 
   30610 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
   30611 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
   30612 #else  /* Otherwise, memory is faster/better for the transient DB. */
   30613 static const char *zCOL_DB = ":memory:";
   30614 #endif
   30615 
   30616 /* Define character (as C string) to separate generated column ordinal
   30617  * from protected part of incoming column names. This defaults to "_"
   30618  * so that incoming column identifiers that did not need not be quoted
   30619  * remain usable without being quoted. It must be one character.
   30620  */
   30621 #ifndef SHELL_AUTOCOLUMN_SEP
   30622 # define AUTOCOLUMN_SEP "_"
   30623 #else
   30624 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
   30625 #endif
   30626 
   30627 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
   30628   /* Queries and D{D,M}L used here */
   30629   static const char * const zTabMake = "\
   30630 CREATE TABLE ColNames(\
   30631  cpos INTEGER PRIMARY KEY,\
   30632  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
   30633 CREATE VIEW RepeatedNames AS \
   30634 SELECT DISTINCT t.name FROM ColNames t \
   30635 WHERE t.name COLLATE NOCASE IN (\
   30636  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
   30637 );\
   30638 ";
   30639   static const char * const zTabFill = "\
   30640 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
   30641  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
   30642 ";
   30643   static const char * const zHasDupes = "\
   30644 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
   30645  <count(name) FROM ColNames\
   30646 ";
   30647 #ifdef SHELL_COLUMN_RENAME_CLEAN
   30648   static const char * const zDedoctor = "\
   30649 UPDATE ColNames SET chop=iif(\
   30650   (substring(name,nlen,1) BETWEEN '0' AND '9')\
   30651   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
   30652  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
   30653  0\
   30654 )\
   30655 ";
   30656 #endif
   30657   static const char * const zSetReps = "\
   30658 UPDATE ColNames AS t SET reps=\
   30659 (SELECT count(*) FROM ColNames d \
   30660  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
   30661  COLLATE NOCASE\
   30662 )\
   30663 ";
   30664 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
   30665   static const char * const zColDigits = "\
   30666 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
   30667 ";
   30668 #else
   30669   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
   30670   static const char * const zColDigits = "\
   30671 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
   30672  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
   30673  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
   30674 ";
   30675 #endif
   30676   static const char * const zRenameRank =
   30677 #ifdef SHELL_COLUMN_RENAME_CLEAN
   30678     "UPDATE ColNames AS t SET suff="
   30679     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
   30680 #else /* ...RENAME_MINIMAL_ONE_PASS */
   30681 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
   30682 "  SELECT 0 AS nlz"
   30683 "  UNION"
   30684 "  SELECT nlz+1 AS nlz FROM Lzn"
   30685 "  WHERE EXISTS("
   30686 "   SELECT 1"
   30687 "   FROM ColNames t, ColNames o"
   30688 "   WHERE"
   30689 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
   30690 "     printf('%s"AUTOCOLUMN_SEP"%s',"
   30691 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
   30692 "     t.name"
   30693 "    )"
   30694 "    ="
   30695 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
   30696 "     printf('%s"AUTOCOLUMN_SEP"%s',"
   30697 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
   30698 "     o.name"
   30699 "    )"
   30700 "    COLLATE NOCASE"
   30701 "    AND o.cpos<>t.cpos"
   30702 "   GROUP BY t.cpos"
   30703 "  )"
   30704 ") UPDATE Colnames AS t SET"
   30705 " chop = 0," /* No chopping, never touch incoming names. */
   30706 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
   30707 "  printf('"AUTOCOLUMN_SEP"%s', substring("
   30708 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
   30709 "  ''"
   30710 " )"
   30711 #endif
   30712     ;
   30713   static const char * const zCollectVar = "\
   30714 SELECT\
   30715  '('||x'0a'\
   30716  || group_concat(\
   30717   cname||' ANY',\
   30718   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
   30719  ||')' AS ColsSpec \
   30720 FROM (\
   30721  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
   30722  FROM ColNames ORDER BY cpos\
   30723 )";
   30724   static const char * const zRenamesDone =
   30725     "SELECT group_concat("
   30726     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
   30727     " ','||x'0a')"
   30728     "FROM ColNames WHERE suff<>'' OR chop!=0"
   30729     ;
   30730   int rc;
   30731   sqlite3_stmt *pStmt = 0;
   30732   assert(pDb!=0);
   30733   if( zColNew ){
   30734     /* Add initial or additional column. Init db if necessary. */
   30735     if( *pDb==0 ){
   30736       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
   30737 #ifdef SHELL_COLFIX_DB
   30738       if(*zCOL_DB!=':')
   30739         sqlite3_exec(*pDb,"drop table if exists ColNames;"
   30740                      "drop view if exists RepeatedNames;",0,0,0);
   30741 #endif
   30742 #undef SHELL_COLFIX_DB
   30743       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
   30744       rc_err_oom_die(rc);
   30745     }
   30746     assert(*pDb!=0);
   30747     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
   30748     rc_err_oom_die(rc);
   30749     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
   30750     rc_err_oom_die(rc);
   30751     rc = sqlite3_step(pStmt);
   30752     rc_err_oom_die(rc);
   30753     sqlite3_finalize(pStmt);
   30754     return 0;
   30755   }else if( *pDb==0 ){
   30756     return 0;
   30757   }else{
   30758     /* Formulate the columns spec, close the DB, zero *pDb. */
   30759     char *zColsSpec = 0;
   30760     int hasDupes = db_int(*pDb, "%s", zHasDupes);
   30761     int nDigits = (hasDupes)? db_int(*pDb, "%s", zColDigits) : 0;
   30762     if( hasDupes ){
   30763 #ifdef SHELL_COLUMN_RENAME_CLEAN
   30764       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
   30765       rc_err_oom_die(rc);
   30766 #endif
   30767       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
   30768       rc_err_oom_die(rc);
   30769       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
   30770       rc_err_oom_die(rc);
   30771       sqlite3_bind_int(pStmt, 1, nDigits);
   30772       rc = sqlite3_step(pStmt);
   30773       sqlite3_finalize(pStmt);
   30774       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
   30775     }
   30776     assert(db_int(*pDb, "%s", zHasDupes)==0); /* Consider: remove this */
   30777     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
   30778     rc_err_oom_die(rc);
   30779     rc = sqlite3_step(pStmt);
   30780     if( rc==SQLITE_ROW ){
   30781       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
   30782     }else{
   30783       zColsSpec = 0;
   30784     }
   30785     if( pzRenamed!=0 ){
   30786       if( !hasDupes ) *pzRenamed = 0;
   30787       else{
   30788         sqlite3_finalize(pStmt);
   30789         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
   30790             && SQLITE_ROW==sqlite3_step(pStmt) ){
   30791           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
   30792         }else
   30793           *pzRenamed = 0;
   30794       }
   30795     }
   30796     sqlite3_finalize(pStmt);
   30797     sqlite3_close(*pDb);
   30798     *pDb = 0;
   30799     return zColsSpec;
   30800   }
   30801 }
   30802 
   30803 /*
   30804 ** Check if the sqlite_schema table contains one or more virtual tables. If
   30805 ** parameter zLike is not NULL, then it is an SQL expression that the
   30806 ** sqlite_schema row must also match. If one or more such rows are found,
   30807 ** print the following warning to the output:
   30808 **
   30809 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
   30810 */
   30811 static int outputDumpWarning(ShellState *p, const char *zLike){
   30812   int rc = SQLITE_OK;
   30813   sqlite3_stmt *pStmt = 0;
   30814   shellPreparePrintf(p->db, &rc, &pStmt,
   30815     "SELECT 1 FROM sqlite_schema o WHERE "
   30816     "sql LIKE 'CREATE VIRTUAL TABLE%%' AND (%s)", zLike ? zLike : "true"
   30817   );
   30818   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   30819     cli_puts("/* WARNING: "
   30820           "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n",
   30821           p->out
   30822     );
   30823   }
   30824   shellFinalize(&rc, pStmt);
   30825   return rc;
   30826 }
   30827 
   30828 /*
   30829 ** Fault-Simulator state and logic.
   30830 */
   30831 static struct {
   30832   int iId;           /* ID that triggers a simulated fault.  -1 means "any" */
   30833   int iErr;          /* The error code to return on a fault */
   30834   int iCnt;          /* Trigger the fault only if iCnt is already zero */
   30835   int iInterval;     /* Reset iCnt to this value after each fault */
   30836   int eVerbose;      /* When to print output */
   30837   int nHit;          /* Number of hits seen so far */
   30838   int nRepeat;       /* Turn off after this many hits.  0 for never */
   30839   int nSkip;         /* Skip this many before first fault */
   30840 } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
   30841 
   30842 /*
   30843 ** This is the fault-sim callback
   30844 */
   30845 static int faultsim_callback(int iArg){
   30846   if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
   30847     return SQLITE_OK;
   30848   }
   30849   if( faultsim_state.iCnt ){
   30850     if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--;
   30851     if( faultsim_state.eVerbose>=2 ){
   30852       cli_printf(stdout,
   30853          "FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
   30854     }
   30855     return SQLITE_OK;
   30856   }
   30857   if( faultsim_state.eVerbose>=1 ){
   30858     cli_printf(stdout,
   30859          "FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
   30860   }
   30861   faultsim_state.iCnt = faultsim_state.iInterval;
   30862   faultsim_state.nHit++;
   30863   if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){
   30864     faultsim_state.iCnt = -1;
   30865   }
   30866   return faultsim_state.iErr;
   30867 }
   30868 
   30869 /*
   30870 ** pickStr(zArg, &zErr, zS1, zS2, ..., "");
   30871 **
   30872 ** Try to match zArg against zS1, zS2, and so forth until the first
   30873 ** emptry string.  Return the index of the match or -1 if none is found.
   30874 ** If no match is found, and &zErr is not NULL, then write into
   30875 ** zErr a message describing the valid choices.
   30876 */
   30877 static int pickStr(const char *zArg, char **pzErr, ...){
   30878   int i, n;
   30879   const char *z;
   30880   sqlite3_str *pMsg;
   30881   va_list ap;
   30882   va_start(ap, pzErr);
   30883   i = 0;
   30884   while( (z = va_arg(ap,const char*))!=0 && z[0]!=0 ){
   30885     if( cli_strcmp(zArg, z)==0 ) return i;
   30886     i++;
   30887   }
   30888   va_end(ap);
   30889   if( pzErr==0 ) return -1;
   30890   n = i;
   30891   pMsg = sqlite3_str_new(0);
   30892   va_start(ap, pzErr);
   30893   sqlite3_str_appendall(pMsg, "should be");
   30894   i = 0;
   30895   while( (z = va_arg(ap, const char*))!=0 && z[0]!=0 ){
   30896     if( i==n-1 ){
   30897       sqlite3_str_append(pMsg,", or",4);
   30898     }else if( i>0 ){
   30899       sqlite3_str_append(pMsg, ",", 1);
   30900     }
   30901     sqlite3_str_appendf(pMsg, " %s", z);
   30902     i++;
   30903   }
   30904   va_end(ap);
   30905   *pzErr = sqlite3_str_finish(pMsg);
   30906   return -1;
   30907 }
   30908 
   30909 /*
   30910 ** DOT-COMMAND: .import
   30911 **
   30912 ** USAGE: .import [OPTIONS] FILE TABLE
   30913 **
   30914 ** Import CSV or similar text from FILE into TABLE.  If TABLE does
   30915 ** not exist, it is created using the first row of FILE as the column
   30916 ** names.  If FILE begins with "|" then it is a command that is run
   30917 ** and the output from the command is used as the input data.  If
   30918 ** FILE begins with "<<" followed by a label, then content is read from
   30919 ** the script until the first line that matches the label.
   30920 **
   30921 ** The content of FILE is interpreted using RFC-4180 ("CSV") quoting
   30922 ** rules unless the current mode is "ascii" or "tabs" or unless one
   30923 ** the --ascii option is used.
   30924 **
   30925 ** The column and row separators must be single ASCII characters.  If
   30926 ** multiple characters or a Unicode character are specified for the
   30927 ** separators, then only the first byte of the separator is used.  Except,
   30928 ** if the row separator is \n and the mode is not --ascii, then \r\n is
   30929 ** understood as a row separator too.
   30930 **
   30931 ** Options:
   30932 **   --ascii         Do not use RFC-4180 quoting.  Use \037 and \036
   30933 **                   as column and row separators on input, unless other
   30934 **                   delimiters are specified using --colsep and/or --rowsep
   30935 **   --colsep CHAR   Use CHAR as the column separator.
   30936 **   --csv           Input is standard RFC-4180 CSV.
   30937 **   --esc CHAR      Use CHAR as an escape character in unquoted CSV inputs.
   30938 **   --qesc CHAR     Use CHAR as an escape character in quoted CSV inputs.
   30939 **   --rowsep CHAR   Use CHAR as the row separator.
   30940 **   --schema S      When creating TABLE, put it in schema S
   30941 **   --skip N        Ignore the first N rows of input
   30942 **   -v              Verbose mode
   30943 */
   30944 static int dotCmdImport(ShellState *p){
   30945   int nArg = p->dot.nArg;     /* Number of arguments */
   30946   char **azArg = p->dot.azArg;/* Argument list */
   30947   char *zTable = 0;           /* Insert data into this table */
   30948   char *zSchema = 0;          /* Schema of zTable */
   30949   char *zFile = 0;            /* Name of file to extra content from */
   30950   sqlite3_stmt *pStmt = NULL; /* A statement */
   30951   int nCol;                   /* Number of columns in the table */
   30952   i64 nByte;                  /* Number of bytes in an SQL string */
   30953   int i, j;                   /* Loop counters */
   30954   int needCommit;             /* True to COMMIT or ROLLBACK at end */
   30955   char *zSql = 0;             /* An SQL statement */
   30956   ImportCtx sCtx;             /* Reader context */
   30957   char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
   30958   int eVerbose = 0;           /* Larger for more console output */
   30959   i64 nSkip = 0;              /* Initial lines to skip */
   30960   i64 iLineOffset = 0;        /* Offset to the first line of input */
   30961   char *zCreate = 0;          /* CREATE TABLE statement text */
   30962   int rc;                     /* Result code */
   30963 
   30964   failIfSafeMode(p, "cannot run .import in safe mode");
   30965   memset(&sCtx, 0, sizeof(sCtx));
   30966   if( p->mode.eMode==MODE_Ascii ){
   30967     xRead = ascii_read_one_field;
   30968   }else{
   30969     xRead = csv_read_one_field;
   30970   }
   30971   for(i=1; i<nArg; i++){
   30972     char *z = azArg[i];
   30973     if( z[0]=='-' && z[1]=='-' ) z++;
   30974     if( z[0]!='-' ){
   30975       if( zFile==0 ){
   30976         zFile = z;
   30977       }else if( zTable==0 ){
   30978         zTable = z;
   30979       }else{
   30980         dotCmdError(p, i, "unknown argument", 0);
   30981         return 1;
   30982       }
   30983     }else if( cli_strcmp(z,"-v")==0 ){
   30984       eVerbose++;
   30985     }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
   30986       zSchema = azArg[++i];
   30987     }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
   30988       nSkip = integerValue(azArg[++i]);
   30989     }else if( cli_strcmp(z,"-ascii")==0 ){
   30990       if( sCtx.cColSep==0 ) sCtx.cColSep = SEP_Unit[0];
   30991       if( sCtx.cRowSep==0 ) sCtx.cRowSep = SEP_Record[0];
   30992       xRead = ascii_read_one_field;
   30993     }else if( cli_strcmp(z,"-csv")==0 ){
   30994       if( sCtx.cColSep==0 ) sCtx.cColSep = ',';
   30995       if( sCtx.cRowSep==0 ) sCtx.cRowSep = '\n';
   30996       xRead = csv_read_one_field;
   30997     }else if( cli_strcmp(z,"-esc")==0 ){
   30998       sCtx.cUQEscape = azArg[++i][0];
   30999     }else if( cli_strcmp(z,"-qesc")==0 ){
   31000       sCtx.cQEscape = azArg[++i][0];
   31001     }else if( cli_strcmp(z,"-colsep")==0 ){
   31002       if( i==nArg-1 ){
   31003         dotCmdError(p, i, "missing argument", 0);
   31004         return 1;
   31005       }
   31006       i++;
   31007       sCtx.cColSep = azArg[i][0];
   31008     }else if( cli_strcmp(z,"-rowsep")==0 ){
   31009       if( i==nArg-1 ){
   31010         dotCmdError(p, i, "missing argument", 0);
   31011         return 1;
   31012       }
   31013       i++;
   31014       sCtx.cRowSep = azArg[i][0];
   31015     }else{
   31016       dotCmdError(p, i, "unknown option", 0);
   31017       return 1;
   31018     }
   31019   }
   31020   if( zTable==0 ){
   31021     dotCmdError(p, nArg, 0, "Missing %s argument\n",
   31022           zFile==0 ? "FILE" : "TABLE");
   31023     return 1;
   31024   }
   31025   seenInterrupt = 0;
   31026   open_db(p, 0);
   31027   if( sCtx.cColSep==0 ){
   31028     if( p->mode.spec.zColumnSep && p->mode.spec.zColumnSep[0]!=0 ){
   31029       sCtx.cColSep = p->mode.spec.zColumnSep[0];
   31030     }else{
   31031       sCtx.cColSep = ',';
   31032     }
   31033   }
   31034   if( (sCtx.cColSep & 0x80)!=0 ){
   31035     eputz("Error: .import column separator must be ASCII\n");
   31036     return 1;
   31037   }
   31038   if( sCtx.cRowSep==0 ){
   31039     if( p->mode.spec.zRowSep && p->mode.spec.zRowSep[0]!=0 ){
   31040       sCtx.cRowSep = p->mode.spec.zRowSep[0];
   31041     }else{
   31042       sCtx.cRowSep = '\n';
   31043     }
   31044   }
   31045   if( sCtx.cRowSep=='\r' && xRead!=ascii_read_one_field ){
   31046     sCtx.cRowSep = '\n';
   31047   }
   31048   if( (sCtx.cRowSep & 0x80)!=0 ){
   31049     eputz("Error: .import row separator must be ASCII\n");
   31050     return 1;
   31051   }
   31052   sCtx.zFile = zFile;
   31053   sCtx.nLine = 1;
   31054   if( sCtx.zFile[0]=='|' ){
   31055 #ifdef SQLITE_OMIT_POPEN
   31056     eputz("Error: pipes are not supported in this OS\n");
   31057     return 1;
   31058 #else
   31059     sCtx.in = sqlite3_popen(sCtx.zFile+1, "r");
   31060     sCtx.zFile = "<pipe>";
   31061     sCtx.xCloser = pclose;
   31062 #endif
   31063   }else if( sCtx.zFile[0]=='<' && sCtx.zFile[1]=='<' && sCtx.zFile[2]!=0 ){
   31064     /* Input text comes from subsequent lines of script until the zFile
   31065     ** delimiter */
   31066     int nEndMark = strlen30(zFile)-2;
   31067     char *zEndMark = &zFile[2];
   31068     sqlite3_str *pContent = sqlite3_str_new(p->db);
   31069     int ckEnd = 1;
   31070     i64 iStart = p->lineno;
   31071     char zLine[2000];
   31072     sCtx.zFile = p->zInFile;
   31073     sCtx.nLine = p->lineno+1;
   31074     iLineOffset = p->lineno;
   31075     while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
   31076       if( ckEnd && cli_strncmp(zLine,zEndMark,nEndMark)==0 ){
   31077         ckEnd = 2;
   31078         if( strchr(zLine,'\n') ) p->lineno++;
   31079         break;
   31080       }
   31081       if( strchr(zLine,'\n') ){
   31082         p->lineno++;
   31083         ckEnd = 1;
   31084       }else{
   31085         ckEnd = 0;
   31086       }
   31087       sqlite3_str_appendall(pContent, zLine);
   31088     }
   31089     sCtx.zIn = sqlite3_str_finish(pContent);
   31090     if( sCtx.zIn==0 ){
   31091       sCtx.zIn = sqlite3_mprintf("");
   31092     }
   31093     if( ckEnd<2 ){
   31094       i64 savedLn = p->lineno;
   31095       p->lineno = iStart;
   31096       dotCmdError(p, 0, 0,"Content terminator \"%s\" not found.",zEndMark);
   31097       p->lineno = savedLn;
   31098       import_cleanup(&sCtx);
   31099       return 1;
   31100     }
   31101   }else{
   31102     sCtx.in = sqlite3_fopen(sCtx.zFile, "rb");
   31103     sCtx.xCloser = fclose;
   31104   }
   31105   if( sCtx.in==0 && sCtx.zIn==0 ){
   31106     dotCmdError(p, 0, 0, "cannot open \"%s\"", zFile);
   31107     import_cleanup(&sCtx);
   31108     return 1;
   31109   }
   31110   if( eVerbose>=1 ){
   31111     char zSep[2];
   31112     zSep[1] = 0;
   31113     zSep[0] = sCtx.cColSep;
   31114     cli_puts("Column separator ", p->out);
   31115     output_c_string(p->out, zSep);
   31116     cli_puts(", row separator ", p->out);
   31117     zSep[0] = sCtx.cRowSep;
   31118     output_c_string(p->out, zSep);
   31119     cli_puts("\n", p->out);
   31120   }
   31121   sCtx.z = sqlite3_malloc64(120);
   31122   if( sCtx.z==0 ){
   31123     import_cleanup(&sCtx);
   31124     shell_out_of_memory();
   31125   }
   31126   /* Below, resources must be freed before exit. */
   31127   while( nSkip>0 ){
   31128     nSkip--;
   31129     while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
   31130   }
   31131   import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
   31132   if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0)
   31133    && 0==db_int(p->db, "SELECT count(*) FROM \"%w\".sqlite_schema"
   31134                        " WHERE name=%Q AND type='view'",
   31135                        zSchema ? zSchema : "main", zTable)
   31136   ){
   31137     /* Table does not exist.  Create it. */
   31138     sqlite3 *dbCols = 0;
   31139     char *zRenames = 0;
   31140     char *zColDefs;
   31141     zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
   31142                   zSchema ? zSchema : "main", zTable);
   31143     while( xRead(&sCtx) ){
   31144       zAutoColumn(sCtx.z, &dbCols, 0);
   31145       if( sCtx.cTerm!=sCtx.cColSep ) break;
   31146     }
   31147     zColDefs = zAutoColumn(0, &dbCols, &zRenames);
   31148     if( zRenames!=0 ){
   31149       cli_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
   31150             "Columns renamed during .import %s due to duplicates:\n"
   31151             "%s\n", sCtx.zFile, zRenames);
   31152       sqlite3_free(zRenames);
   31153     }
   31154     assert(dbCols==0);
   31155     if( zColDefs==0 ){
   31156       cli_printf(stderr,"%s: empty file\n", sCtx.zFile);
   31157       import_cleanup(&sCtx);
   31158       sqlite3_free(zCreate);
   31159       return 1;
   31160     }
   31161     zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
   31162     if( zCreate==0 ){
   31163       import_cleanup(&sCtx);
   31164       shell_out_of_memory();
   31165     }
   31166     if( eVerbose>=1 ){
   31167       cli_printf(p->out, "%s\n", zCreate);
   31168     }
   31169     rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
   31170     if( rc ){
   31171       cli_printf(stderr,
   31172            "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
   31173     }
   31174     sqlite3_free(zCreate);
   31175     zCreate = 0;
   31176     if( rc ){
   31177       import_cleanup(&sCtx);
   31178       return 1;
   31179     }
   31180   }
   31181   zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
   31182                          zTable, zSchema);
   31183   if( zSql==0 ){
   31184     import_cleanup(&sCtx);
   31185     shell_out_of_memory();
   31186   }
   31187   rc =  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   31188   sqlite3_free(zSql);
   31189   zSql = 0;
   31190   if( rc ){
   31191     if (pStmt) sqlite3_finalize(pStmt);
   31192     shellDatabaseError(p->db);
   31193     import_cleanup(&sCtx);
   31194     return 1;
   31195   }
   31196   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   31197     nCol = sqlite3_column_int(pStmt, 0);
   31198   }else{
   31199     nCol = 0;
   31200   }
   31201   sqlite3_finalize(pStmt);
   31202   pStmt = 0;
   31203   if( nCol==0 ) return 0; /* no columns, no error */
   31204 
   31205   nByte = 64                 /* space for "INSERT INTO", "VALUES(", ")\0" */
   31206         + (zSchema ? strlen(zSchema)*2 + 2: 0)  /* Quoted schema name */
   31207         + strlen(zTable)*2 + 2                  /* Quoted table name */
   31208         + nCol*2;            /* Space for ",?" for each column */
   31209   zSql = sqlite3_malloc64( nByte );
   31210   if( zSql==0 ){
   31211     import_cleanup(&sCtx);
   31212     shell_out_of_memory();
   31213   }
   31214   if( zSchema ){
   31215     sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?",
   31216                      zSchema, zTable);
   31217   }else{
   31218     sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
   31219   }
   31220   j = strlen30(zSql);
   31221   for(i=1; i<nCol; i++){
   31222     zSql[j++] = ',';
   31223     zSql[j++] = '?';
   31224   }
   31225   zSql[j++] = ')';
   31226   zSql[j] = 0;
   31227   assert( j<nByte );
   31228   if( eVerbose>=2 ){
   31229     cli_printf(p->out, "Insert using: %s\n", zSql);
   31230   }
   31231   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   31232   sqlite3_free(zSql);
   31233   zSql = 0;
   31234   if( rc ){
   31235     shellDatabaseError(p->db);
   31236     if (pStmt) sqlite3_finalize(pStmt);
   31237     import_cleanup(&sCtx);
   31238     return 1;
   31239   }
   31240   needCommit = sqlite3_get_autocommit(p->db);
   31241   if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
   31242   do{
   31243     int startLine = sCtx.nLine;
   31244     for(i=0; i<nCol; i++){
   31245       char *z = xRead(&sCtx);
   31246       /*
   31247       ** Did we reach end-of-file before finding any columns?
   31248       ** If so, stop instead of NULL filling the remaining columns.
   31249       */
   31250       if( z==0 && i==0 ) break;
   31251       /*
   31252       ** Did we reach end-of-file OR end-of-line before finding any
   31253       ** columns in ASCII mode?  If so, stop instead of NULL filling
   31254       ** the remaining columns.
   31255       */
   31256       if( p->mode.eMode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
   31257       /*
   31258       ** For CSV mode, per RFC 4180, accept EOF in lieu of final
   31259       ** record terminator but only for last field of multi-field row.
   31260       ** (If there are too few fields, it's not valid CSV anyway.)
   31261       */
   31262       if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
   31263         z = "";
   31264       }
   31265       sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
   31266       if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
   31267         if( i==0 && (strcmp(z,"\n")==0 || strcmp(z,"\r\n")==0) ){
   31268           /* Ignore trailing \n or \r\n when some other row separator */
   31269           break;
   31270         }
   31271         cli_printf(stderr,"%s:%d: expected %d columns but found %d"
   31272               " - filling the rest with NULL\n",
   31273               sCtx.zFile, startLine, nCol, i+1);
   31274         i += 2;
   31275         while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
   31276       }
   31277     }
   31278     if( sCtx.cTerm==sCtx.cColSep ){
   31279       do{
   31280         xRead(&sCtx);
   31281         i++;
   31282       }while( sCtx.cTerm==sCtx.cColSep );
   31283       cli_printf(stderr,
   31284             "%s:%d: expected %d columns but found %d - extras ignored\n",
   31285             sCtx.zFile, startLine, nCol, i);
   31286     }
   31287     if( i>=nCol ){
   31288       sqlite3_step(pStmt);
   31289       rc = sqlite3_reset(pStmt);
   31290       if( rc!=SQLITE_OK ){
   31291         cli_printf(stderr,"%s:%d: INSERT failed: %s\n",
   31292               sCtx.zFile, startLine, sqlite3_errmsg(p->db));
   31293         sCtx.nErr++;
   31294         if( bail_on_error ) break;
   31295       }else{
   31296         sCtx.nRow++;
   31297       }
   31298     }
   31299   }while( sCtx.cTerm!=EOF );
   31300 
   31301   import_cleanup(&sCtx);
   31302   sqlite3_finalize(pStmt);
   31303   if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
   31304   if( eVerbose>0 ){
   31305     cli_printf(p->out,
   31306           "Added %d rows with %d errors using %d lines of input\n",
   31307           sCtx.nRow, sCtx.nErr, sCtx.nLine-1-iLineOffset);
   31308   }
   31309   return sCtx.nErr ? 1 : 0;
   31310 }
   31311 
   31312 
   31313 /*
   31314 ** This function computes what to show the user about the configured
   31315 ** titles (or column-names).  Output is an integer between 0 and 3:
   31316 **
   31317 **    0:     The titles do not matter.  Never show anything.
   31318 **    1:     Show  "--titles off"
   31319 **    2:     Show  "--titles on"
   31320 **    3:     Show  "--title VALUE"  where VALUE is an encoding method
   31321 **             to use, one of: plain sql csv html tcl json
   31322 **
   31323 ** Inputs are:
   31324 **
   31325 **    spec.bTitles   (bT)     Whether or not to show the titles
   31326 **    spec.eTitle    (eT)     The actual encoding to be used for titles
   31327 **    ModeInfo.bHdr  (bH)     Default value for spec.bTitles
   31328 **    ModeInfo.eHdr  (eH)     Default value for spec.eTitle
   31329 **    bAll                    Whether the -v option is used
   31330 */
   31331 static int modeTitleDsply(ShellState *p, int bAll){
   31332   int eMode = p->mode.eMode;
   31333   const ModeInfo *pI = &aModeInfo[eMode];
   31334   int bT = p->mode.spec.bTitles;
   31335   int eT = p->mode.spec.eTitle;
   31336   int bH = pI->bHdr;
   31337   int eH = pI->eHdr;
   31338 
   31339   /* Variable "v" is the truth table that will determine the answer
   31340   **
   31341   **                   Actual encoding is different from default
   31342   **                            vvvvvvvv                                    */
   31343   sqlite3_uint64 v = UINT64_C(0x0133013311220102);
   31344   /*                            ^^^^    ^^^^
   31345   **                   Upper 2-byte groups for when ON/OFF disagrees with
   31346   **                   the default.                                         */
   31347 
   31348   if( bH==0 ) return 0;  /* Header not appliable.  Ex: off, count */
   31349 
   31350   if( eT==0 ) eT = eH;   /* Fill in missing spec.eTitle */
   31351   if( bT==0 ) bT = bH;   /* Fill in missing spec.bTitles */
   31352 
   31353   if( eT!=eH ) v >>= 32; /* Encoding disagree in upper 4-bytes */
   31354   if( bT!=bH ) v >>= 16; /* ON/OFF disagree in upper 2-byte pairs */
   31355   if( bT<2 ) v >>= 8;    /* ON in even bytes, OFF in odd bytes (1st byte 0) */
   31356   if( !bAll ) v >>= 4;   /* bAll values are in the lower half-byte */
   31357 
   31358   return v & 3;          /* Return the selected truth-table entry */
   31359 }
   31360 
   31361 /*
   31362 ** DOT-COMMAND:  .mode
   31363 **
   31364 ** USAGE: .mode [MODE] [OPTIONS]
   31365 **
   31366 ** Change the output mode to MODE and/or apply OPTIONS to the output mode.
   31367 ** Arguments are processed from left to right.  If no arguments, show the
   31368 ** current output mode and relevant options.
   31369 **
   31370 ** Options:
   31371 **   --align STRING           Set the alignment of text in columnar modes
   31372 **                            String consists of characters 'L', 'C', 'R'
   31373 **                            meaning "left", "centered", and "right", with
   31374 **                            one letter per column starting from the left.
   31375 **                            Unspecified alignment defaults to 'L'.
   31376 **   --blob-quote ARG         ARG can be "auto", "text", "sql", "hex", "tcl",
   31377 **                            "json", or "size".  Default is "auto".
   31378 **   --border on|off          Show outer border on "box" and "table" modes.
   31379 **   --charlimit N            Set the maximum number of output characters to
   31380 **                            show for any single SQL value to N. Longer values
   31381 **                            truncated. Zero means "no limit".
   31382 **   --colsep STRING          Use STRING as the column separator
   31383 **   --escape ESC             Enable/disable escaping of control characters
   31384 **                            found in the output. ESC can be "off", "ascii",
   31385 **                            or "symbol".
   31386 **   --linelimit N            Set the maximum number of output lines to show for
   31387 **                            any single SQL value to N. Longer values are
   31388 **                            truncated. Zero means "no limit". Only works
   31389 **                            in "line" mode and in columnar modes.
   31390 **   --limits L,C,T           Shorthand for "--linelimit L --charlimit C
   31391 **                            --titlelimit T". The ",T" can be omitted in which
   31392 **                            case the --titlelimit is unchanged.  The argument
   31393 **                            can also be "off" to mean "0,0,0" or "on" to
   31394 **                            mean "5,300,20".
   31395 **   --list                   List available modes
   31396 **   --multiinsert N          In "insert" mode, put multiple rows on a single
   31397 **                            INSERT statement until the size exceeds N bytes.
   31398 **   --null STRING            Render SQL NULL values as the given string
   31399 **   --once                   Setting changes to the right are reverted after
   31400 **                            the next SQL command.
   31401 **   --quote ARG              Enable/disable quoting of text. ARG can be
   31402 **                            "off", "on", "sql", "relaxed", "csv", "html",
   31403 **                            "tcl", or "json". "off" means show the text as-is.
   31404 **                            "on" is an alias for "sql".
   31405 **   --reset                  Changes all mode settings back to their default.
   31406 **   --rowsep STRING          Use STRING as the row separator
   31407 **   --sw|--screenwidth N     Declare the screen width of the output device
   31408 **                            to be N characters.  An attempt may be made to
   31409 **                            wrap output text to fit within this limit. Zero
   31410 **                            means "no limit".  Or N can be "auto" to set the
   31411 **                            width automatically.
   31412 **   --tablename NAME         Set the name of the table for "insert" mode.
   31413 **   --tag NAME               Save mode to the left as NAME.
   31414 **   --textjsonb BOOLEAN      If enabled, JSONB text is displayed as text JSON.
   31415 **   --title ARG              Whether or not to show column headers, and if so
   31416 **                            how to encode them.  ARG can be "off", "on",
   31417 **                            "sql", "csv", "html", "tcl", or "json".
   31418 **   --titlelimit N           Limit the length of column titles to N characters.
   31419 **   -v|--verbose             Verbose output
   31420 **   --widths LIST            Set the columns widths for columnar modes. The
   31421 **                            argument is a list of integers, one for each
   31422 **                            column. A "0" width means use a dynamic width
   31423 **                            based on the actual width of data. If there are
   31424 **                            fewer entries in LIST than columns, "0" is used
   31425 **                            for the unspecified widths.
   31426 **   --wordwrap BOOLEAN       Enable/disable word wrapping
   31427 **   --wrap N                 Wrap columns wider than N characters
   31428 **   --ww                     Shorthand for "--wordwrap on"
   31429 */
   31430 static int dotCmdMode(ShellState *p){
   31431   int nArg = p->dot.nArg;     /* Number of arguments */
   31432   char **azArg = p->dot.azArg;/* Argument list */
   31433   int eMode = -1;             /* New mode value, or -1 for none */
   31434   int iMode = -1;             /* Index of the argument that is the mode name */
   31435   int i;                      /* Loop counter */
   31436   int k;                      /* Misc index variable */
   31437   int chng = 0;               /* True if anything has changed */
   31438   int bAll = 0;               /* Show all details of the mode */
   31439 
   31440   for(i=1; i<nArg; i++){
   31441     const char *z = azArg[i];
   31442     if( z[0]=='-' && z[1]=='-' ) z++;
   31443     if( z[0]!='-'
   31444      && iMode<0
   31445      && (eMode = modeFind(p, azArg[i]))>=0
   31446      && eMode!=MODE_Www
   31447     ){
   31448       iMode = i;
   31449       modeChange(p, eMode);
   31450       /* (Legacy) If the mode is MODE_Insert and the next argument
   31451       ** is not an option, then the next argument must be the table
   31452       ** name.
   31453       */
   31454       if( i+1<nArg && azArg[i+1][0]!='-' ){
   31455         i++;
   31456         modeSetStr(&p->mode.spec.zTableName, azArg[i]);
   31457       }
   31458       chng = 1;
   31459     }else if( optionMatch(z,"align") ){
   31460       char *zAlign;
   31461       int nAlign;
   31462       int nErr = 0;
   31463       if( i+1>=nArg ){
   31464         dotCmdError(p, i, "missing argument", 0);
   31465         return 1;
   31466       }
   31467       i++;
   31468       zAlign = azArg[i];
   31469       nAlign = 0x3fff & strlen(zAlign);
   31470       free(p->mode.spec.aAlign);
   31471       p->mode.spec.aAlign = malloc(nAlign);
   31472       shell_check_oom(p->mode.spec.aAlign);
   31473       for(k=0; k<nAlign; k++){
   31474         unsigned char c = 0;
   31475         switch( zAlign[k] ){
   31476           case 'l': case 'L':   c = QRF_ALIGN_Left;   break;
   31477           case 'c': case 'C':   c = QRF_ALIGN_Center; break;
   31478           case 'r': case 'R':   c = QRF_ALIGN_Right;  break;
   31479           default:  nErr++; break;
   31480         }
   31481         p->mode.spec.aAlign[k] = c;
   31482       }
   31483       p->mode.spec.nAlign = nAlign;
   31484       chng = 1;
   31485       if( nErr ){
   31486         dotCmdError(p, i, "bad alignment string",
   31487              "Should contain only characters L, C, and R.");
   31488         return 1;
   31489       }
   31490     }else if( pickStr(z,0,"-blob","-blob-quote","")>=0 ){
   31491       if( (++i)>=nArg ){
   31492         dotCmdError(p, i-1, "missing argument", 0);
   31493         return 1;
   31494       }
   31495       k = pickStr(azArg[i], 0,
   31496                     "auto", "text", "sql", "hex", "tcl", "json", "size", "");
   31497         /*           0       1       2      3      4      5       6
   31498         ** Must match QRF_BLOB_xxxx values.  See also tag-20251124a */
   31499       if( k>=0 ){
   31500         p->mode.spec.eBlob = k & 0xff;
   31501       }
   31502       chng = 1;
   31503     }else if( optionMatch(z,"border") ){
   31504       if( (++i)>=nArg ){
   31505         dotCmdError(p, i-1, "missing argument", 0);
   31506         return 1;
   31507       }
   31508       k = pickStr(azArg[i], 0, "auto", "off", "on", "");
   31509       if( k>=0 ){
   31510         p->mode.spec.bBorder = k & 0x3;
   31511       }
   31512       chng = 1;
   31513     }else if( 0<=(k=pickStr(z,0,
   31514                   "-charlimit","-linelimit","-titlelimit","-multiinsert","")) ){
   31515       int w;   /*  0            1            2             3 */
   31516       if( i+1>=nArg ){
   31517         dotCmdError(p, i, "missing argument", 0);
   31518         return 1;
   31519       }
   31520       w = integerValue(azArg[++i]);
   31521       switch( k ){
   31522         case 0:   p->mode.spec.nCharLimit = w;    break;
   31523         case 1:   p->mode.spec.nLineLimit = w;    break;
   31524         case 2:   p->mode.spec.nTitleLimit = w;   break;
   31525         default:  p->mode.spec.nMultiInsert = w;  break;
   31526       }
   31527       chng = 1;
   31528     }else if( 0<=(k=pickStr(z,0,"-tablename","-rowsep","-colsep","-null","")) ){
   31529                             /*   0            1         2         3 */
   31530       if( i+1>=nArg ){
   31531         dotCmdError(p, i, "missing argument", 0);
   31532         return 1;
   31533       }
   31534       i++;
   31535       switch( k ){
   31536         case 0: modeSetStr(&p->mode.spec.zTableName, azArg[i]); break;
   31537         case 1: modeSetStr(&p->mode.spec.zRowSep, azArg[i]);    break;
   31538         case 2: modeSetStr(&p->mode.spec.zColumnSep, azArg[i]); break;
   31539         case 3: modeSetStr(&p->mode.spec.zNull, azArg[i]);      break;
   31540       }
   31541       chng = 1;
   31542     }else if( optionMatch(z,"escape") ){
   31543       /* See similar code at tag-20250224-1 */
   31544       char *zErr = 0;
   31545       if( (++i)>=nArg ){
   31546         dotCmdError(p, i-1, "missing argument", 0);
   31547         return 1;
   31548       }                       /*  0     1       2  <-- One less than QRF_ESC_ */
   31549       k = pickStr(azArg[i],&zErr,"off","ascii","symbol","");
   31550       if( k<0 ){
   31551         dotCmdError(p, i, "unknown escape type", "%s", zErr);
   31552         sqlite3_free(zErr);
   31553         return 1;
   31554       }
   31555       p->mode.spec.eEsc = k+1;
   31556       chng = 1;
   31557     }else if( optionMatch(z,"limits") ){
   31558       if( (++i)>=nArg ){
   31559         dotCmdError(p, i-1, "missing argument", 0);
   31560         return 1;
   31561       }
   31562       k = pickStr(azArg[i],0,"on","off","");
   31563       if( k==0 ){
   31564         p->mode.spec.nLineLimit = DFLT_LINE_LIMIT;
   31565         p->mode.spec.nCharLimit = DFLT_CHAR_LIMIT;
   31566         p->mode.spec.nTitleLimit = DFLT_TITLE_LIMIT;
   31567       }else if( k==1 ){
   31568         p->mode.spec.nLineLimit = 0;
   31569         p->mode.spec.nCharLimit = 0;
   31570         p->mode.spec.nTitleLimit = 0;
   31571       }else{
   31572         int L, C, T = 0;
   31573         int nNum = sscanf(azArg[i], "%d,%d,%d", &L, &C, &T);
   31574         if( nNum<2 || L<0 || C<0 || T<0){
   31575           dotCmdError(p, i, "bad argument", "Should be \"L,C,T\" where L, C"
   31576                             " and T are unsigned integers");
   31577           return 1;
   31578         }
   31579         p->mode.spec.nLineLimit = L;
   31580         p->mode.spec.nCharLimit = C;
   31581         if( nNum==3 ) p->mode.spec.nTitleLimit = T;
   31582       }
   31583       chng = 1;
   31584     }else if( optionMatch(z,"list") ){
   31585       int ii;
   31586       cli_puts("available modes:", p->out);
   31587       for(ii=0; ii<ArraySize(aModeInfo); ii++){
   31588         if( ii==MODE_Www ) continue;
   31589         cli_printf(p->out, " %s", aModeInfo[ii].zName);
   31590       }
   31591       for(ii=0; ii<p->nSavedModes; ii++){
   31592         cli_printf(p->out, " %s", p->aSavedModes[ii].zTag);
   31593       }
   31594       cli_puts(" batch tty\n", p->out);
   31595       chng = 1;  /* Not really a change, but we still want to suppress the
   31596                  ** "current mode" output */
   31597     }else if( optionMatch(z,"once") ){
   31598       p->nPopMode = 0;
   31599       modePush(p);
   31600       p->nPopMode = 1;
   31601     }else if( optionMatch(z,"noquote") ){
   31602       /* (undocumented legacy) --noquote always turns quoting off */
   31603       p->mode.spec.eText = QRF_TEXT_Plain;
   31604       p->mode.spec.eBlob = QRF_BLOB_Auto;
   31605       chng = 1;
   31606     }else if( optionMatch(z,"quote") ){
   31607       if( i+1<nArg
   31608        && azArg[i+1][0]!='-'
   31609        && (iMode>0 || strcmp(azArg[i+1],"off")==0 || modeFind(p, azArg[i+1])<0)
   31610       ){
   31611         /* --quote is followed by an argument other that is not an option
   31612         ** or a mode name.  See it must be a boolean or a keyword to describe
   31613         ** how to set quoting. */
   31614         i++;
   31615         if( (k = pickStr(azArg[i],0,"no","yes","0","1",""))>=0 ){
   31616           k &= 1;   /* 0 for "off".  1 for "on". */
   31617         }else{
   31618           char *zErr = 0;
   31619           k = pickStr(azArg[i],&zErr,
   31620                  "off","on","sql","csv","html","tcl","json","relaxed","");
   31621               /*  0     1    2     3     4      5     6      7   */
   31622           if( k<0 ){
   31623             dotCmdError(p, i, "unknown", "%z", zErr);
   31624             return 1;
   31625           }
   31626         }
   31627       }else{
   31628         /* (Legacy) no following boolean argument.  Turn quoting on */
   31629         k = 1;
   31630       }
   31631       switch( k ){
   31632         case 1:  /* on */
   31633           modeSetStr(&p->mode.spec.zNull, "NULL");
   31634           /* Fall through */
   31635         case 2:  /* sql */
   31636           p->mode.spec.eText = QRF_TEXT_Sql;
   31637           break;
   31638         case 3:  /* csv */
   31639           p->mode.spec.eText = QRF_TEXT_Csv;
   31640           break;
   31641         case 4:  /* html */
   31642           p->mode.spec.eText = QRF_TEXT_Html;
   31643           break;
   31644         case 5:  /* tcl */
   31645           p->mode.spec.eText = QRF_TEXT_Tcl;
   31646           break;
   31647         case 6:  /* json */
   31648           p->mode.spec.eText = QRF_TEXT_Json;
   31649           break;
   31650         case 7:  /* relaxed */
   31651           p->mode.spec.eText = QRF_TEXT_Relaxed;
   31652           break;
   31653         default: /* off */
   31654           p->mode.spec.eText = QRF_TEXT_Plain;
   31655           break;
   31656       }
   31657       chng = 1;
   31658     }else if( optionMatch(z,"reset") ){
   31659       int saved_eMode = p->mode.eMode;
   31660       modeFree(&p->mode);
   31661       modeChange(p, saved_eMode);
   31662     }else if( optionMatch(z,"screenwidth") || optionMatch(z,"sw") ){
   31663       if( (++i)>=nArg ){
   31664         dotCmdError(p, i-1, "missing argument", 0);
   31665         return 1;
   31666       }
   31667       k = pickStr(azArg[i],0,"off","auto","");
   31668       if( k==0 ){
   31669         p->mode.bAutoScreenWidth = 0;
   31670         p->mode.spec.nScreenWidth = 0;
   31671       }else if( k==1 ){
   31672         p->mode.bAutoScreenWidth = 1;
   31673       }else{
   31674         i64 w = integerValue(azArg[i]);
   31675         p->mode.bAutoScreenWidth = 0;
   31676         if( w<0 ) w = 0;
   31677         if( w>QRF_MAX_WIDTH ) w = QRF_MAX_WIDTH;
   31678         p->mode.spec.nScreenWidth = w;
   31679       }
   31680       chng = 1;
   31681     }else if( optionMatch(z,"tag") ){
   31682       size_t nByte;
   31683       int n;
   31684       const char *zTag;
   31685       if( i+1>=nArg ){
   31686         dotCmdError(p, i, "missing argument", 0);
   31687         return 1;
   31688       }
   31689       zTag = azArg[++i];
   31690       if( modeFind(p, zTag)>=0 ){
   31691         dotCmdError(p, i, "mode already exists", 0);
   31692         return 1;
   31693       }
   31694       if( p->nSavedModes > MODE_N_USER ){
   31695         dotCmdError(p, i-1, "cannot add more modes", 0);
   31696         return 1;
   31697       }
   31698       n = p->nSavedModes++;
   31699       nByte = sizeof(p->aSavedModes[0]);
   31700       nByte *= n+1;
   31701       p->aSavedModes = realloc( p->aSavedModes, nByte );
   31702       shell_check_oom(p->aSavedModes);
   31703       p->aSavedModes[n].zTag = strdup(zTag);
   31704       shell_check_oom(p->aSavedModes[n].zTag);
   31705       modeDup(&p->aSavedModes[n].mode, &p->mode);
   31706       chng = 1;
   31707     }else if( optionMatch(z,"textjsonb") ){
   31708       if( i+1>=nArg ){
   31709         dotCmdError(p, i, "missing argument", 0);
   31710         return 1;
   31711       }
   31712       p->mode.spec.bTextJsonb = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
   31713       chng = 1;
   31714     }else if( optionMatch(z,"titles") || optionMatch(z,"title") ){
   31715       char *zErr = 0;
   31716       if( i+1>=nArg ){
   31717         dotCmdError(p, i, "missing argument", 0);
   31718         return 1;
   31719       }
   31720       k = pickStr(azArg[++i],&zErr,
   31721               "off","on","plain","sql","csv","html","tcl","json","");
   31722           /*   0     1    2       3     4     5     6      7 */
   31723       if( k<0 ){
   31724         dotCmdError(p, i, "bad --titles value","%z", zErr);
   31725         return 1;
   31726       }
   31727       p->mode.spec.bTitles = k>=1 ? QRF_Yes : QRF_No;
   31728       p->mode.mFlags &= ~MFLG_HDR;
   31729       p->mode.spec.eTitle = k>1 ? k-1 : aModeInfo[p->mode.eMode].eHdr;
   31730       chng = 1;
   31731     }else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
   31732       int nWidth = 0;
   31733       short int *aWidth;
   31734       const char *zW;
   31735       if( i+1>=nArg ){
   31736         dotCmdError(p, i, "missing argument", 0);
   31737         return 1;
   31738       }
   31739       zW = azArg[++i];
   31740       /* Every width value takes at least 2 bytes in the input string to
   31741       ** specify, so strlen(zW) bytes should be plenty of space to hold the
   31742       ** result. */
   31743       aWidth = malloc( strlen(zW) );
   31744       while( IsSpace(zW[0]) ) zW++;
   31745       while( zW[0] ){
   31746         int w = 0;
   31747         int nDigit = 0;
   31748         k = zW[0]=='-' && IsDigit(zW[1]);
   31749         while( IsDigit(zW[k]) ){
   31750           w = w*10 + zW[k] - '0';
   31751           if( w>QRF_MAX_WIDTH ){
   31752             dotCmdError(p,i+1,"width too big",
   31753                         "Maximum column width is %d", QRF_MAX_WIDTH);
   31754             free(aWidth);
   31755             return 1;
   31756           }
   31757           nDigit++;
   31758           k++;
   31759         }
   31760         if( nDigit==0 ){
   31761           dotCmdError(p,i+1,"syntax error",
   31762                       "should be a comma-separated list if integers");
   31763           free(aWidth);
   31764           return 1;
   31765         }
   31766         if( zW[0]=='-' ) w = -w;
   31767         aWidth[nWidth++] = w;
   31768         zW += k;
   31769         if( zW[0]==',' ) zW++;
   31770         while( IsSpace(zW[0]) ) zW++;
   31771       }
   31772       free(p->mode.spec.aWidth);
   31773       p->mode.spec.aWidth = aWidth;
   31774       p->mode.spec.nWidth = nWidth;
   31775       chng = 1;
   31776     }else if( optionMatch(z,"wrap") ){
   31777       int w;
   31778       if( i+1>=nArg ){
   31779         dotCmdError(p, i, "missing argument", 0);
   31780         return 1;
   31781       }
   31782       w = integerValue(azArg[++i]);
   31783       if( w<(-QRF_MAX_WIDTH) ) w = -QRF_MAX_WIDTH;
   31784       if( w>QRF_MAX_WIDTH ) w = QRF_MAX_WIDTH;
   31785       p->mode.spec.nWrap = w;
   31786       chng = 1;
   31787     }else if( optionMatch(z,"ww") ){
   31788       p->mode.spec.bWordWrap = QRF_Yes;
   31789       chng = 1;
   31790     }else if( optionMatch(z,"wordwrap") ){
   31791       if( i+1>=nArg ){
   31792         dotCmdError(p, i, "missing argument", 0);
   31793         return 1;
   31794       }
   31795       p->mode.spec.bWordWrap = (u8)booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
   31796       chng = 1;
   31797     }else if( optionMatch(z,"v") || optionMatch(z,"verbose") ){
   31798       bAll = 1;
   31799     }else if( z[0]=='-' ){
   31800       dotCmdError(p, i, "bad option", "Use \".help .mode\" for more info");
   31801       return 1;
   31802     }else{
   31803       dotCmdError(p, i, iMode>0?"bad argument":"unknown mode",
   31804                   "Use \".help .mode\" for more info");
   31805       return 1;
   31806     }
   31807   }
   31808   if( !chng || bAll ){
   31809     const ModeInfo *pI = aModeInfo + p->mode.eMode;
   31810     sqlite3_str *pDesc = sqlite3_str_new(p->db);
   31811     char *zDesc;
   31812     const char *zSetting;
   31813 
   31814     if( p->nPopMode ) sqlite3_str_appendall(pDesc, "--once ");
   31815     sqlite3_str_appendall(pDesc,pI->zName);
   31816     if( bAll || (p->mode.spec.nAlign && pI->eCx==2) ){
   31817       int ii;
   31818       sqlite3_str_appendall(pDesc, " --align \"");
   31819       for(ii=0; ii<p->mode.spec.nAlign; ii++){
   31820         unsigned char a = p->mode.spec.aAlign[ii];
   31821         sqlite3_str_appendchar(pDesc, 1, "LLCR"[a&3]);
   31822       }
   31823       sqlite3_str_append(pDesc, "\"", 1);
   31824     }
   31825     if( bAll
   31826      || (p->mode.spec.bBorder==QRF_No) != ((pI->mFlg&1)!=0)
   31827     ){
   31828       sqlite3_str_appendf(pDesc," --border %s",
   31829              p->mode.spec.bBorder==QRF_No ? "off" : "on");
   31830     }
   31831     if( bAll || p->mode.spec.eBlob!=QRF_BLOB_Auto ){
   31832       const char *azBQuote[] =
   31833            { "auto", "text", "sql", "hex", "tcl", "json", "size" };
   31834       /*      0       1       2      3      4      5       6
   31835       ** Must match QRF_BLOB_xxxx values.  See all instances of tag-20251124a */
   31836       u8 e = p->mode.spec.eBlob;
   31837       sqlite3_str_appendf(pDesc, " --blob-quote %s", azBQuote[e]);
   31838     }
   31839     zSetting = aModeStr[pI->eCSep];
   31840     if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zColumnSep)!=0) ){
   31841       sqlite3_str_appendf(pDesc, " --colsep ");
   31842       append_c_string(pDesc, p->mode.spec.zColumnSep);
   31843     }
   31844     if( bAll || p->mode.spec.eEsc!=QRF_Auto ){
   31845       sqlite3_str_appendf(pDesc, " --escape %s",qrfEscNames[p->mode.spec.eEsc]);
   31846     }
   31847     if( bAll
   31848      || (p->mode.spec.nLineLimit>0 && pI->eCx>0)
   31849      || p->mode.spec.nCharLimit>0
   31850      || (p->mode.spec.nTitleLimit>0 && pI->eCx>0)
   31851     ){
   31852       if( p->mode.spec.nLineLimit==0
   31853        && p->mode.spec.nCharLimit==0
   31854        && p->mode.spec.nTitleLimit==0
   31855       ){
   31856         sqlite3_str_appendf(pDesc, " --limits off");
   31857       }else if( p->mode.spec.nLineLimit==DFLT_LINE_LIMIT
   31858        && p->mode.spec.nCharLimit==DFLT_CHAR_LIMIT
   31859        && p->mode.spec.nTitleLimit==DFLT_TITLE_LIMIT
   31860       ){
   31861         sqlite3_str_appendf(pDesc, " --limits on");
   31862       }else{
   31863         sqlite3_str_appendf(pDesc, " --limits %d,%d,%d",
   31864            p->mode.spec.nLineLimit, p->mode.spec.nCharLimit,
   31865            p->mode.spec.nTitleLimit);
   31866       }
   31867     }
   31868     if( bAll
   31869      || (p->mode.spec.nMultiInsert && p->mode.spec.eStyle==QRF_STYLE_Insert)
   31870     ){
   31871       sqlite3_str_appendf(pDesc, " --multiinsert %u",
   31872                           p->mode.spec.nMultiInsert);
   31873     }
   31874     zSetting = aModeStr[pI->eNull];
   31875     if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zNull)!=0) ){
   31876       sqlite3_str_appendf(pDesc, " --null ");
   31877       append_c_string(pDesc, p->mode.spec.zNull);
   31878     }
   31879     if( bAll
   31880      || (pI->eText!=p->mode.spec.eText && (pI->eText>1 || p->mode.spec.eText>1))
   31881     ){
   31882       sqlite3_str_appendf(pDesc," --quote %s",qrfQuoteNames[p->mode.spec.eText]);
   31883     }
   31884     zSetting = aModeStr[pI->eRSep];
   31885     if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zRowSep)!=0) ){
   31886       sqlite3_str_appendf(pDesc, " --rowsep ");
   31887       append_c_string(pDesc, p->mode.spec.zRowSep);
   31888     }
   31889     if( bAll
   31890      || (pI->eCx && (p->mode.spec.nScreenWidth>0 || p->mode.bAutoScreenWidth))
   31891     ){
   31892       if( p->mode.bAutoScreenWidth ){
   31893         sqlite3_str_appendall(pDesc, " --sw auto");
   31894       }else{
   31895         sqlite3_str_appendf(pDesc," --sw %d",
   31896                             p->mode.spec.nScreenWidth);
   31897       }
   31898     }
   31899     if( bAll || p->mode.eMode==MODE_Insert ){
   31900       sqlite3_str_appendf(pDesc," --tablename ");
   31901       append_c_string(pDesc, p->mode.spec.zTableName);
   31902     }
   31903     if( bAll || p->mode.spec.bTextJsonb ){
   31904       sqlite3_str_appendf(pDesc," --textjsonb %s",
   31905              p->mode.spec.bTextJsonb==QRF_Yes ? "on" : "off");
   31906     }
   31907     k = modeTitleDsply(p, bAll);
   31908     if( k==1 ){
   31909       sqlite3_str_appendall(pDesc, " --titles off");
   31910     }else if( k==2 ){
   31911       sqlite3_str_appendall(pDesc, " --titles on");
   31912     }else if( k==3 ){
   31913       static const char *azTitle[] =
   31914           { "plain", "sql", "csv", "html", "tcl", "json"};
   31915       sqlite3_str_appendf(pDesc, " --titles %s",
   31916                    azTitle[p->mode.spec.eTitle-1]);
   31917     }
   31918     if( p->mode.spec.nWidth>0 && (bAll || pI->eCx==2) ){
   31919       int ii;
   31920       const char *zSep = " --widths ";
   31921       for(ii=0; ii<p->mode.spec.nWidth; ii++){
   31922         sqlite3_str_appendf(pDesc, "%s%d", zSep, (int)p->mode.spec.aWidth[ii]);
   31923         zSep = ",";
   31924       }
   31925     }else if( bAll ){
   31926       sqlite3_str_appendall(pDesc, " --widths \"\"");
   31927     }
   31928     if( bAll || (pI->eCx>0 && p->mode.spec.bWordWrap) ){
   31929       if( bAll ){
   31930         sqlite3_str_appendf(pDesc, " --wordwrap %s",
   31931           p->mode.spec.bWordWrap==QRF_Yes ? "on" : "off");
   31932       }
   31933       if( p->mode.spec.nWrap ){
   31934         sqlite3_str_appendf(pDesc, " --wrap %d", p->mode.spec.nWrap);
   31935       }
   31936       if( !bAll ) sqlite3_str_append(pDesc, " --ww", 5);
   31937     }
   31938     zDesc = sqlite3_str_finish(pDesc);
   31939     cli_printf(p->out, ".mode %s\n", zDesc);
   31940     fflush(p->out);
   31941     sqlite3_free(zDesc);
   31942   }
   31943   return 0;
   31944 }
   31945 
   31946 /*
   31947 ** DOT-COMMAND: .output
   31948 ** USAGE: .output [OPTIONS] [FILE]
   31949 **
   31950 ** Begin redirecting output to FILE.  Or if FILE is omitted, revert
   31951 ** to sending output to the console.  If FILE begins with "|" then
   31952 ** the remainder of file is taken as a pipe and output is directed
   31953 ** into that pipe.  If FILE is "memory" then output is captured in an
   31954 ** internal memory buffer.  If FILE is "off" then output is redirected
   31955 ** into /dev/null or the equivalent.
   31956 **
   31957 ** Options:
   31958 **   --bom             Prepend a byte-order mark to the output
   31959 **   -e                Accumulate output in a temporary text file then
   31960 **                     launch a text editor when the redirection ends.
   31961 **   --error-prefix X  Use X as the left-margin prefix for error messages.
   31962 **                     Set to an empty string to restore the default.
   31963 **   --keep            Keep redirecting output to its current destination.
   31964 **                     Use this option in combination with --show or
   31965 **                     with --error-prefix when you do not want to stop
   31966 **                     a current redirection.
   31967 **   --plain           Use plain text rather than HTML tables with -w
   31968 **   --show            Show output text captured by .testcase or by
   31969 **                     redirecting to "memory".
   31970 **   -w                Show the output in a web browser.  Output is
   31971 **                     written into a temporary HTML file until the
   31972 **                     redirect ends, then the web browser is launched.
   31973 **                     Query results  are shown as HTML tables, unless
   31974 **                     the --plain is used too.
   31975 **   -x                Show the output in a spreadsheet.  Output is
   31976 **                     written to a temp file as CSV then the spreadsheet
   31977 **                     is launched when
   31978 **
   31979 ** DOT-COMMAND: .once
   31980 ** USAGE: .once [OPTIONS] FILE ...
   31981 **
   31982 ** Write the output for the next line of SQL or the next dot-command into
   31983 ** FILE.  If FILE begins with "|" then it is a program into which output
   31984 ** is written. The FILE argument should be omitted if one of the -e, -w,
   31985 ** or -x options is used.
   31986 **
   31987 ** Options:
   31988 **   -e                Capture output into a temporary file then bring up
   31989 **                     a text editor on that temporary file.
   31990 **   --plain           Use plain text rather than HTML tables with -w
   31991 **   -w                Capture output into an HTML file then bring up that
   31992 **                     file in a web browser
   31993 **   -x                Show the output in a spreadsheet.  Output is
   31994 **                     written to a temp file as CSV then the spreadsheet
   31995 **                     is launched when
   31996 **
   31997 ** DOT-COMMAND: .excel
   31998 ** Shorthand for ".once -x"
   31999 **
   32000 ** DOT-COMMAND: .www [--plain]
   32001 ** Shorthand for ".once -w" or ".once --plain -w"
   32002 */
   32003 static int dotCmdOutput(ShellState *p){
   32004   int nArg = p->dot.nArg;        /* Number of arguments */
   32005   char **azArg = p->dot.azArg;   /* Text of the arguments */
   32006   char *zFile = 0;               /* The FILE argument */
   32007   int i;                  /* Loop counter */
   32008   int eMode = 0;          /* 0: .outout/.once, 'x'=.excel, 'w'=.www */
   32009   int bOnce = 0;          /* 0: .output, 1: .once, 2: .excel/.www */
   32010   int bPlain = 0;         /* --plain option */
   32011   int bKeep = 0;          /* Keep redirecting */
   32012   static const char *zBomUtf8 = "\357\273\277";
   32013   const char *zBom = 0;
   32014   char c = azArg[0][0];
   32015   int n = strlen30(azArg[0]);
   32016 
   32017   failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
   32018   if( c=='e' ){
   32019     eMode = 'x';
   32020     bOnce = 2;
   32021   }else if( c=='w' ){
   32022     eMode = 'w';
   32023     bOnce = 2;
   32024   }else if( n>=2 && cli_strncmp(azArg[0],"once",n)==0 ){
   32025     bOnce = 1;
   32026   }
   32027   for(i=1; i<nArg; i++){
   32028     char *z = azArg[i];
   32029     if( z[0]=='-' ){
   32030       if( z[1]=='-' ) z++;
   32031       if( cli_strcmp(z,"-bom")==0 ){
   32032         zBom = zBomUtf8;
   32033       }else if( cli_strcmp(z,"-plain")==0 ){
   32034         bPlain = 1;
   32035       }else if( c=='o' && z[0]=='1' && z[1]!=0 && z[2]==0
   32036              && (z[1]=='x' || z[1]=='e' || z[1]=='w') ){
   32037         if( bKeep || eMode ){
   32038           dotCmdError(p, i, "incompatible with prior options",0);
   32039           goto dotCmdOutput_error;
   32040         }
   32041         eMode = z[1];
   32042       }else if( cli_strcmp(z,"-show")==0 ){
   32043         if( cli_output_capture ){
   32044           sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
   32045         }
   32046       }else if( cli_strcmp(z,"-keep")==0 ){
   32047         bKeep = 1;
   32048       }else if( optionMatch(z,"error-prefix") ){
   32049         if( i+1>=nArg ){
   32050           dotCmdError(p, i, "missing argument", 0);
   32051           return 1;
   32052         }
   32053         free(p->zErrPrefix);
   32054         i++;
   32055         p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]);
   32056       }else{
   32057         dotCmdError(p, i, "unknown option", 0);
   32058         sqlite3_free(zFile);
   32059         return 1;
   32060       }
   32061     }else if( zFile==0 && eMode==0 ){
   32062       if( bKeep ){
   32063         dotCmdError(p, i, "incompatible with prior options",0);
   32064         goto dotCmdOutput_error;
   32065       }
   32066       if( cli_strcmp(z, "memory")==0 && bOnce ){
   32067         dotCmdError(p, 0, "cannot redirect to \"memory\"", 0);
   32068         goto dotCmdOutput_error;
   32069       }
   32070       if( cli_strcmp(z, "off")==0 ){
   32071 #ifdef _WIN32
   32072         zFile = sqlite3_mprintf("nul");
   32073 #else
   32074         zFile = sqlite3_mprintf("/dev/null");
   32075 #endif
   32076       }else{
   32077         zFile = sqlite3_mprintf("%s", z);
   32078       }
   32079       if( zFile && zFile[0]=='|' ){
   32080         while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
   32081         break;
   32082       }
   32083     }else{
   32084       dotCmdError(p, i, "surplus argument", 0);
   32085       sqlite3_free(zFile);
   32086       return 1;
   32087     }
   32088   }
   32089   if( zFile==0 && !bKeep ){
   32090     zFile = sqlite3_mprintf("stdout");
   32091     shell_check_oom(zFile);
   32092   }
   32093   if( bOnce ){
   32094     p->nPopOutput = 2;
   32095   }else{
   32096     p->nPopOutput = 0;
   32097   }
   32098   if( !bKeep ) output_reset(p);
   32099 #ifndef SQLITE_NOHAVE_SYSTEM
   32100   if( eMode=='e' || eMode=='x' || eMode=='w' ){
   32101     p->doXdgOpen = 1;
   32102     modePush(p);
   32103     if( eMode=='x' ){
   32104       /* spreadsheet mode.  Output as CSV. */
   32105       newTempFile(p, "csv");
   32106       p->mode.mFlags &= ~MFLG_ECHO;
   32107       p->mode.eMode = MODE_Csv;
   32108       modeSetStr(&p->mode.spec.zColumnSep, SEP_Comma);
   32109       modeSetStr(&p->mode.spec.zRowSep, SEP_CrLf);
   32110 #ifdef _WIN32
   32111       zBom = zBomUtf8;  /* Always include the BOM on Windows, as Excel does
   32112                         ** not work without it. */
   32113 #endif
   32114     }else if( eMode=='w' ){
   32115       /* web-browser mode. */
   32116       newTempFile(p, "html");
   32117       if( !bPlain ) p->mode.eMode = MODE_Www;
   32118     }else{
   32119       /* text editor mode */
   32120       newTempFile(p, "txt");
   32121     }
   32122     sqlite3_free(zFile);
   32123     zFile = sqlite3_mprintf("%s", p->zTempFile);
   32124   }
   32125 #endif /* SQLITE_NOHAVE_SYSTEM */
   32126   if( !bKeep ) shell_check_oom(zFile);
   32127   if( bKeep ){
   32128     /* no-op */
   32129   }else if( cli_strcmp(zFile,"memory")==0 ){
   32130     if( cli_output_capture ){
   32131       sqlite3_str_free(cli_output_capture);
   32132     }
   32133     cli_output_capture = sqlite3_str_new(0);
   32134   }else if( zFile[0]=='|' ){
   32135 #ifdef SQLITE_OMIT_POPEN
   32136     eputz("Error: pipes are not supported in this OS\n");
   32137     output_redir(p, stdout);
   32138     goto dotCmdOutput_error;
   32139 #else
   32140     FILE *pfPipe = sqlite3_popen(zFile + 1, "w");
   32141     if( pfPipe==0 ){
   32142       assert( stderr!=NULL );
   32143       cli_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
   32144       goto dotCmdOutput_error;
   32145     }else{
   32146       output_redir(p, pfPipe);
   32147       if( zBom ) cli_puts(zBom, pfPipe);
   32148       sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
   32149     }
   32150 #endif
   32151   }else{
   32152     FILE *pfFile = output_file_open(p, zFile);
   32153     if( pfFile==0 ){
   32154       if( cli_strcmp(zFile,"off")!=0 ){
   32155        assert( stderr!=NULL );
   32156        cli_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
   32157       }
   32158       goto dotCmdOutput_error;
   32159     } else {
   32160       output_redir(p, pfFile);
   32161       if( zBom ) cli_puts(zBom, pfFile);
   32162       if( bPlain && eMode=='w' ){
   32163         cli_puts(
   32164           "<!DOCTYPE html>\n<BODY>\n<PLAINTEXT>\n",
   32165           pfFile
   32166         );
   32167       }
   32168       sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
   32169     }
   32170   }
   32171   sqlite3_free(zFile);
   32172   return 0;
   32173 
   32174 dotCmdOutput_error:
   32175   sqlite3_free(zFile);
   32176   return 1;
   32177 }
   32178 
   32179 /*
   32180 ** DOT-COMMAND: .check
   32181 ** USAGE: .check [OPTIONS] PATTERN
   32182 **
   32183 ** Verify results of commands since the most recent .testcase command.
   32184 ** Restore output to the console, unless --keep is used.
   32185 **
   32186 ** If PATTERN starts with "<<ENDMARK" then the actual pattern is taken from
   32187 ** subsequent lines of text up to the first line that begins with ENDMARK.
   32188 ** All pattern lines and the ENDMARK are discarded.
   32189 **
   32190 ** Options:
   32191 **   --exact                Do an exact comparison including leading and
   32192 **                          trailing whitespace.
   32193 **   --glob                 Treat PATTERN as a GLOB
   32194 **   --keep                 Do not reset the testcase.  More .check commands
   32195 **                          will follow.
   32196 **   --notglob              Output should not match PATTERN
   32197 **   --show                 Write testcase output to the screen, for debugging.
   32198 */
   32199 static int dotCmdCheck(ShellState *p){
   32200   int nArg = p->dot.nArg;            /* Number of arguments */
   32201   char **azArg = p->dot.azArg;       /* Text of the arguments */
   32202   int i;                             /* Loop counter */
   32203   int k;                             /* Result of pickStr() */
   32204   char *zTest;                       /* Textcase result */
   32205   int bKeep = 0;                     /* --keep option */
   32206   char *zCheck = 0;                  /* PATTERN argument */
   32207   char *zPattern = 0;                /* Actual test pattern */
   32208   int eCheck = 0;                    /* 1: --glob,  2: --notglob,  3: --exact */
   32209   int isOk;                          /* True if results are OK */
   32210   sqlite3_int64 iStart = p->lineno;  /* Line number of .check statement */
   32211 
   32212   if( p->zTestcase[0]==0 ){
   32213     dotCmdError(p, 0, "no .testcase is active", 0);
   32214     return 1;
   32215   }
   32216   for(i=1; i<nArg; i++){
   32217     char *z = azArg[i];
   32218     if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
   32219     if( cli_strcmp(z,"-keep")==0 ){
   32220       bKeep = 1;
   32221     }else if( cli_strcmp(z,"-show")==0 ){
   32222       if( cli_output_capture ){
   32223         sqlite3_fprintf(stdout, "%s", sqlite3_str_value(cli_output_capture));
   32224       }
   32225       bKeep = 1;
   32226     }else if( z[0]=='-'
   32227           && (k = pickStr(&z[1],0,"glob","notglob","exact",""))>=0
   32228     ){
   32229       if( eCheck && eCheck!=k+1 ){
   32230         dotCmdError(p, i, "incompatible with prior options",0);
   32231         return 1;
   32232       }
   32233       eCheck = k+1;
   32234     }else if( zCheck ){
   32235       dotCmdError(p, i, "unknown option", 0);
   32236       return 1;
   32237     }else{
   32238       zCheck = azArg[i];
   32239     }
   32240   }
   32241   if( zCheck==0 ){
   32242     dotCmdError(p, 0, "no PATTERN specified", 0);
   32243     return 1;
   32244   }
   32245   if( cli_output_capture && sqlite3_str_length(cli_output_capture) ){
   32246     zTest = sqlite3_str_value(cli_output_capture);
   32247     shell_check_oom(zTest);
   32248   }else{
   32249     zTest = "";
   32250   }
   32251   p->nTestRun++;
   32252   if( zCheck[0]=='<' && zCheck[1]=='<' && zCheck[2]!=0 ){
   32253     int nCheck = strlen30(zCheck);
   32254     sqlite3_str *pPattern = sqlite3_str_new(p->db);
   32255     char zLine[2000];
   32256     while( sqlite3_fgets(zLine,sizeof(zLine),p->in) ){
   32257       if( strchr(zLine,'\n') ) p->lineno++;
   32258       if( cli_strncmp(&zCheck[2],zLine,nCheck-2)==0 ) break;
   32259       sqlite3_str_appendall(pPattern, zLine);
   32260     }
   32261     zPattern = sqlite3_str_finish(pPattern);
   32262     if( zPattern==0 ){
   32263       zPattern = sqlite3_mprintf("");
   32264     }
   32265   }else{
   32266     zPattern = zCheck;
   32267   }
   32268   shell_check_oom(zPattern);
   32269   switch( eCheck ){
   32270     case 1: {
   32271       char *zGlob = sqlite3_mprintf("*%s*", zPattern);
   32272       isOk = testcase_glob(zGlob, zTest)!=0;
   32273       sqlite3_free(zGlob);
   32274       break;
   32275     }
   32276     case 2: {
   32277       char *zGlob = sqlite3_mprintf("*%s*", zPattern);
   32278       isOk = testcase_glob(zGlob, zTest)==0;
   32279       sqlite3_free(zGlob);
   32280       break;
   32281     }
   32282     case 3: {
   32283       isOk = cli_strcmp(zTest,zPattern)==0;
   32284       break;
   32285     }
   32286     default: {
   32287       /* Skip leading and trailing \n and \r on both pattern and test output */
   32288       const char *z1 = zPattern;
   32289       const char *z2 = zTest;
   32290       size_t n1, n2;
   32291       while( z1[0]=='\n' || z1[0]=='\r' ) z1++;
   32292       n1 = strlen(z1);
   32293       while( n1>0 && (z1[n1-1]=='\n' || z1[n1-1]=='\r') ) n1--;
   32294       while( z2[0]=='\n' || z2[0]=='\r' ) z2++;
   32295       n2 = strlen(z2);
   32296       while( n2>0 && (z2[n2-1]=='\n' || z2[n2-1]=='\r') ) n2--;
   32297       isOk = n1==n2 && memcmp(z1,z2,n1)==0;
   32298       break;
   32299     }
   32300   }
   32301   if( !isOk ){
   32302     sqlite3_fprintf(stderr,
   32303           "%s:%lld: .check failed for testcase %s\n",
   32304         p->zInFile, iStart, p->zTestcase);
   32305     p->nTestErr++;
   32306     sqlite3_fprintf(stderr, "Expected: [%s]\n", zPattern);
   32307     sqlite3_fprintf(stderr, "Got:      [%s]\n", zTest);
   32308   }
   32309   if( zPattern!=zCheck ){
   32310     sqlite3_free(zPattern);
   32311   }
   32312   if( !bKeep ){
   32313     output_reset(p);
   32314     p->zTestcase[0] = 0;
   32315   }
   32316   return 0;
   32317 }
   32318 
   32319 /*
   32320 ** DOT-COMMAND: .testcase
   32321 ** USAGE: .testcase [OPTIONS] NAME
   32322 **
   32323 ** Start a new test case identified by NAME.  All output
   32324 ** through the next ".check" command is captured for comparison. See the
   32325 ** ".check" commandn for additional informatioon.
   32326 **
   32327 ** Options:
   32328 **   --error-prefix TEXT       Change error message prefix text to TEXT
   32329 */
   32330 static int dotCmdTestcase(ShellState *p){
   32331   int nArg = p->dot.nArg;        /* Number of arguments */
   32332   char **azArg = p->dot.azArg;   /* Text of the arguments */
   32333   int i;                         /* Loop counter */
   32334   const char *zName = 0;         /* Testcase name */
   32335 
   32336   for(i=1; i<nArg; i++){
   32337     char *z = azArg[i];
   32338     if( z[0]=='-' && z[1]=='-' && z[2]!=0 ) z++;
   32339     if( optionMatch(z,"error-prefix") ){
   32340       if( i+1>=nArg ){
   32341         dotCmdError(p, i, "missing argument", 0);
   32342         return 1;
   32343       }
   32344       free(p->zErrPrefix);
   32345       i++;
   32346       p->zErrPrefix = azArg[i][0]==0 ? 0 : strdup(azArg[i]);
   32347     }else if( zName ){
   32348       dotCmdError(p, i, "unknown option", 0);
   32349       return 1;
   32350     }else{
   32351       zName = azArg[i];
   32352     }
   32353   }
   32354   output_reset(p);
   32355   if( cli_output_capture ){
   32356     sqlite3_str_free(cli_output_capture);
   32357   }
   32358   cli_output_capture = sqlite3_str_new(0);
   32359   if( zName ){
   32360     sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", zName);
   32361   }else{
   32362     sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s:%lld",
   32363                      p->zInFile, p->lineno);
   32364   }
   32365   return 0;
   32366 }
   32367 
   32368 /*
   32369 ** Enlarge the space allocated in p->dot so that it can hold more
   32370 ** than nArg parsed command-line arguments.
   32371 */
   32372 static void parseDotRealloc(ShellState *p, int nArg){
   32373   p->dot.nAlloc = nArg+22;
   32374   p->dot.azArg = realloc(p->dot.azArg,p->dot.nAlloc*sizeof(char*));
   32375   shell_check_oom(p->dot.azArg);
   32376   p->dot.aiOfst = realloc(p->dot.aiOfst,p->dot.nAlloc*sizeof(int));
   32377   shell_check_oom(p->dot.aiOfst);
   32378   p->dot.abQuot = realloc(p->dot.abQuot,p->dot.nAlloc);
   32379   shell_check_oom(p->dot.abQuot);
   32380 }
   32381 
   32382 
   32383 /*
   32384 ** Parse input line zLine up into individual arguments.  Retain the
   32385 ** parse in the p->dot substructure.
   32386 */
   32387 static void parseDotCmdArgs(const char *zLine, ShellState *p){
   32388   char *z;
   32389   int h = 1;
   32390   int nArg = 0;
   32391   size_t szLine;
   32392 
   32393   p->dot.zOrig = zLine;
   32394   free(p->dot.zCopy);
   32395   z = p->dot.zCopy = strdup(zLine);
   32396   shell_check_oom(z);
   32397   szLine = strlen(z);
   32398   while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
   32399   if( szLine>0 && z[szLine-1]==';' ){
   32400     szLine--;
   32401     while( szLine>0 && IsSpace(z[szLine-1]) ) szLine--;
   32402   }
   32403   z[szLine] = 0;
   32404   parseDotRealloc(p, 2);
   32405   while( z[h] ){
   32406     while( IsSpace(z[h]) ){ h++; }
   32407     if( z[h]==0 ) break;
   32408     if( nArg+2>p->dot.nAlloc ){
   32409       parseDotRealloc(p, nArg);
   32410     }
   32411     if( z[h]=='\'' || z[h]=='"' ){
   32412       int delim = z[h++];
   32413       p->dot.abQuot[nArg] = 1;
   32414       p->dot.azArg[nArg] = &z[h];
   32415       p->dot.aiOfst[nArg] = h;
   32416       while( z[h] && z[h]!=delim ){
   32417         if( z[h]=='\\' && delim=='"' && z[h+1]!=0 ) h++;
   32418         h++;
   32419       }
   32420       if( z[h]==delim ){
   32421         z[h++] = 0;
   32422       }
   32423       if( delim=='"' ) resolve_backslashes(p->dot.azArg[nArg]);
   32424     }else{
   32425       p->dot.abQuot[nArg] = 0;
   32426       p->dot.azArg[nArg] = &z[h];
   32427       p->dot.aiOfst[nArg] = h;
   32428       while( z[h] && !IsSpace(z[h]) ){ h++; }
   32429       if( z[h] ) z[h++] = 0;
   32430     }
   32431     nArg++;
   32432   }
   32433   p->dot.nArg = nArg;
   32434   p->dot.azArg[nArg] = 0;
   32435 }
   32436 
   32437 /*
   32438 ** If an input line begins with "." then invoke this routine to
   32439 ** process that line.
   32440 **
   32441 ** Return 1 on error, 2 to exit, and 0 otherwise.
   32442 */
   32443 static int do_meta_command(const char *zLine, ShellState *p){
   32444   int nArg;
   32445   int n, c;
   32446   int rc = 0;
   32447   char **azArg;
   32448 
   32449 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   32450   if( p->expert.pExpert ){
   32451     expertFinish(p, 1, 0);
   32452   }
   32453 #endif
   32454 
   32455   /* Parse the input line into tokens stored in p->dot.
   32456   */
   32457   parseDotCmdArgs(zLine, p);
   32458   nArg = p->dot.nArg;
   32459   azArg = p->dot.azArg;
   32460 
   32461   /* Process the input line.
   32462   */
   32463   if( nArg==0 ) return 0; /* no tokens, no error */
   32464   n = strlen30(azArg[0]);
   32465   c = azArg[0][0];
   32466   clearTempFile(p);
   32467 
   32468 #ifndef SQLITE_OMIT_AUTHORIZATION
   32469   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
   32470     if( nArg!=2 ){
   32471       cli_printf(stderr, "Usage: .auth ON|OFF\n");
   32472       rc = 1;
   32473       goto meta_command_exit;
   32474     }
   32475     open_db(p, 0);
   32476     if( booleanValue(azArg[1]) ){
   32477       sqlite3_set_authorizer(p->db, shellAuth, p);
   32478     }else if( p->bSafeModePersist ){
   32479       sqlite3_set_authorizer(p->db, safeModeAuth, p);
   32480     }else{
   32481       sqlite3_set_authorizer(p->db, 0, 0);
   32482     }
   32483   }else
   32484 #endif
   32485 
   32486 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
   32487   && !defined(SQLITE_SHELL_FIDDLE)
   32488   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
   32489     open_db(p, 0);
   32490     failIfSafeMode(p, "cannot run .archive in safe mode");
   32491     rc = arDotCommand(p, 0, azArg, nArg);
   32492   }else
   32493 #endif
   32494 
   32495 #ifndef SQLITE_SHELL_FIDDLE
   32496   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
   32497    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
   32498   ){
   32499     const char *zDestFile = 0;
   32500     const char *zDb = 0;
   32501     sqlite3 *pDest;
   32502     sqlite3_backup *pBackup;
   32503     int j;
   32504     int bAsync = 0;
   32505     const char *zVfs = 0;
   32506     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
   32507     for(j=1; j<nArg; j++){
   32508       const char *z = azArg[j];
   32509       if( z[0]=='-' ){
   32510         if( z[1]=='-' ) z++;
   32511         if( cli_strcmp(z, "-append")==0 ){
   32512           zVfs = "apndvfs";
   32513         }else
   32514         if( cli_strcmp(z, "-async")==0 ){
   32515           bAsync = 1;
   32516         }else
   32517         {
   32518           dotCmdError(p, j, "unknown option", "should be -append or -async");
   32519           return 1;
   32520         }
   32521       }else if( zDestFile==0 ){
   32522         zDestFile = azArg[j];
   32523       }else if( zDb==0 ){
   32524         zDb = zDestFile;
   32525         zDestFile = azArg[j];
   32526       }else{
   32527         cli_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
   32528         return 1;
   32529       }
   32530     }
   32531     if( zDestFile==0 ){
   32532       cli_printf(stderr, "missing FILENAME argument on .backup\n");
   32533       return 1;
   32534     }
   32535     if( zDb==0 ) zDb = "main";
   32536     rc = sqlite3_open_v2(zDestFile, &pDest,
   32537                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
   32538     if( rc!=SQLITE_OK ){
   32539       cli_printf(stderr,"Error: cannot open \"%s\"\n", zDestFile);
   32540       close_db(pDest);
   32541       return 1;
   32542     }
   32543     if( bAsync ){
   32544       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
   32545                    0, 0, 0);
   32546     }
   32547     open_db(p, 0);
   32548     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
   32549     if( pBackup==0 ){
   32550       shellDatabaseError(pDest);
   32551       close_db(pDest);
   32552       return 1;
   32553     }
   32554     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
   32555     sqlite3_backup_finish(pBackup);
   32556     if( rc==SQLITE_DONE ){
   32557       rc = 0;
   32558     }else{
   32559       shellDatabaseError(pDest);
   32560       rc = 1;
   32561     }
   32562     close_db(pDest);
   32563   }else
   32564 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   32565 
   32566   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
   32567     if( nArg==2 ){
   32568       bail_on_error = booleanValue(azArg[1]);
   32569     }else{
   32570       eputz("Usage: .bail on|off\n");
   32571       rc = 1;
   32572     }
   32573   }else
   32574 
   32575   /* Undocumented.  Legacy only.  See "crlf" below */
   32576   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
   32577     eputz("The \".binary\" command is deprecated.\n");
   32578     rc = 1;
   32579   }else
   32580 
   32581   /* The undocumented ".breakpoint" command causes a call to the no-op
   32582   ** routine named test_breakpoint().
   32583   */
   32584   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
   32585     test_breakpoint();
   32586   }else
   32587 
   32588 #ifndef SQLITE_SHELL_FIDDLE
   32589   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
   32590     failIfSafeMode(p, "cannot run .cd in safe mode");
   32591     if( nArg==2 ){
   32592 #if defined(_WIN32) || defined(WIN32)
   32593       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
   32594       rc = !SetCurrentDirectoryW(z);
   32595       sqlite3_free(z);
   32596 #else
   32597       rc = chdir(azArg[1]);
   32598 #endif
   32599       if( rc ){
   32600         cli_printf(stderr,"Cannot change to directory \"%s\"\n", azArg[1]);
   32601         rc = 1;
   32602       }
   32603     }else{
   32604       eputz("Usage: .cd DIRECTORY\n");
   32605       rc = 1;
   32606     }
   32607   }else
   32608 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   32609 
   32610   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
   32611     if( nArg==2 ){
   32612       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
   32613     }else{
   32614       eputz("Usage: .changes on|off\n");
   32615       rc = 1;
   32616     }
   32617   }else
   32618 
   32619   /* Cancel output redirection, if it is currently set (by .testcase)
   32620   ** Then read the content of the testcase-out.txt file and compare against
   32621   ** azArg[1].  If there are differences, report an error and exit.
   32622   */
   32623   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
   32624     rc = dotCmdCheck(p);
   32625   }else
   32626 
   32627 #ifndef SQLITE_SHELL_FIDDLE
   32628   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
   32629     failIfSafeMode(p, "cannot run .clone in safe mode");
   32630     if( nArg==2 ){
   32631       tryToClone(p, azArg[1]);
   32632     }else{
   32633       eputz("Usage: .clone FILENAME\n");
   32634       rc = 1;
   32635     }
   32636   }else
   32637 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   32638 
   32639   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
   32640     if( nArg==1 ){
   32641       /* List available connections */
   32642       int i;
   32643       for(i=0; i<ArraySize(p->aAuxDb); i++){
   32644         const char *zFile = p->aAuxDb[i].zDbFilename;
   32645         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
   32646           zFile = "(not open)";
   32647         }else if( zFile==0 ){
   32648           zFile = "(memory)";
   32649         }else if( zFile[0]==0 ){
   32650           zFile = "(temporary-file)";
   32651         }
   32652         if( p->pAuxDb == &p->aAuxDb[i] ){
   32653           cli_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
   32654         }else if( p->aAuxDb[i].db!=0 ){
   32655           cli_printf(stdout, "       %d: %s\n", i, zFile);
   32656         }
   32657       }
   32658     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
   32659       int i = azArg[1][0] - '0';
   32660       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
   32661         p->pAuxDb->db = p->db;
   32662         p->pAuxDb = &p->aAuxDb[i];
   32663         globalDb = p->db = p->pAuxDb->db;
   32664         p->pAuxDb->db = 0;
   32665       }
   32666     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
   32667            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
   32668       int i = azArg[2][0] - '0';
   32669       if( i<0 || i>=ArraySize(p->aAuxDb) ){
   32670         /* No-op */
   32671       }else if( p->pAuxDb == &p->aAuxDb[i] ){
   32672         eputz("cannot close the active database connection\n");
   32673         rc = 1;
   32674       }else if( p->aAuxDb[i].db ){
   32675         session_close_all(p, i);
   32676         close_db(p->aAuxDb[i].db);
   32677         p->aAuxDb[i].db = 0;
   32678       }
   32679     }else{
   32680       eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
   32681       rc = 1;
   32682     }
   32683   }else
   32684 
   32685   if( c=='c' && n==4
   32686    && (cli_strncmp(azArg[0], "crlf", n)==0
   32687        || cli_strncmp(azArg[0], "crnl",n)==0)
   32688   ){
   32689     if( nArg==2 ){
   32690 #ifdef _WIN32
   32691       if( booleanValue(azArg[1]) ){
   32692         p->mode.mFlags |= MFLG_CRLF;
   32693       }else{
   32694         p->mode.mFlags &= ~MFLG_CRLF;
   32695       }
   32696 #else
   32697       p->mode.mFlags &= ~MFLG_CRLF;
   32698 #endif
   32699     }
   32700     cli_printf(stderr, "crlf is %s\n",
   32701        (p->mode.mFlags & MFLG_CRLF)!=0 ? "ON" : "OFF");
   32702   }else
   32703 
   32704   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
   32705     char **azName = 0;
   32706     int nName = 0;
   32707     sqlite3_stmt *pStmt;
   32708     int i;
   32709     open_db(p, 0);
   32710     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
   32711     if( rc ){
   32712       shellDatabaseError(p->db);
   32713       rc = 1;
   32714     }else{
   32715       while( sqlite3_step(pStmt)==SQLITE_ROW ){
   32716         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
   32717         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
   32718         if( zSchema==0 || zFile==0 ) continue;
   32719         azName = sqlite3_realloc64(azName, (nName+1)*2*sizeof(char*));
   32720         shell_check_oom(azName);
   32721         azName[nName*2] = strdup(zSchema);
   32722         azName[nName*2+1] = strdup(zFile);
   32723         nName++;
   32724       }
   32725     }
   32726     sqlite3_finalize(pStmt);
   32727     for(i=0; i<nName; i++){
   32728       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
   32729       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
   32730       const char *z = azName[i*2+1];
   32731       cli_printf(p->out, "%s: %s %s%s\n",
   32732             azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
   32733             eTxn==SQLITE_TXN_NONE ? "" :
   32734             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
   32735       free(azName[i*2]);
   32736       free(azName[i*2+1]);
   32737     }
   32738     sqlite3_free(azName);
   32739   }else
   32740 
   32741   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
   32742     static const struct DbConfigChoices {
   32743       const char *zName;
   32744       int op;
   32745     } aDbConfig[] = {
   32746         { "attach_create",      SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE  },
   32747         { "attach_write",       SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE   },
   32748         { "comments",           SQLITE_DBCONFIG_ENABLE_COMMENTS       },
   32749         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
   32750         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
   32751         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
   32752         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
   32753         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
   32754         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
   32755         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
   32756         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
   32757         { "fp_digits",          SQLITE_DBCONFIG_FP_DIGITS             },
   32758         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
   32759         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
   32760         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
   32761         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
   32762         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
   32763         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
   32764         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
   32765         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
   32766         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
   32767         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
   32768     };
   32769     int ii, v;
   32770     open_db(p, 0);
   32771     for(ii=0; ii<ArraySize(aDbConfig); ii++){
   32772       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
   32773       if( nArg>=3 ){
   32774         if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
   32775           sqlite3_db_config(p->db, aDbConfig[ii].op, atoi(azArg[2]), 0);
   32776         }else{
   32777           sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
   32778         }
   32779       }
   32780       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
   32781       if( aDbConfig[ii].op==SQLITE_DBCONFIG_FP_DIGITS ){
   32782         cli_printf(p->out, "%19s %d\n", aDbConfig[ii].zName, v);
   32783       }else{
   32784         cli_printf(p->out, "%19s %s\n",
   32785                         aDbConfig[ii].zName, v ? "on" : "off");
   32786       }
   32787       if( nArg>1 ) break;
   32788     }
   32789     if( nArg>1 && ii==ArraySize(aDbConfig) ){
   32790       dotCmdError(p, 1, "unknown dbconfig",
   32791          "Enter \".dbconfig\" with no arguments for a list");
   32792     }
   32793   }else
   32794 
   32795 #if SQLITE_SHELL_HAVE_RECOVER
   32796   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
   32797     rc = shell_dbinfo_command(p, nArg, azArg);
   32798   }else
   32799 
   32800   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
   32801     open_db(p, 0);
   32802     rc = recoverDatabaseCmd(p, nArg, azArg);
   32803   }else
   32804 #endif /* SQLITE_SHELL_HAVE_RECOVER */
   32805 
   32806   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
   32807     char *zLike = 0;
   32808     char *zSql;
   32809     int i;
   32810     int savedShellFlags = p->shellFlgs;
   32811     Mode saved_mode;
   32812     ShellClearFlag(p,
   32813        SHFLG_PreserveRowid|SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
   32814     for(i=1; i<nArg; i++){
   32815       if( azArg[i][0]=='-' ){
   32816         const char *z = azArg[i]+1;
   32817         if( z[0]=='-' ) z++;
   32818         if( cli_strcmp(z,"preserve-rowids")==0 ){
   32819 #ifdef SQLITE_OMIT_VIRTUALTABLE
   32820           dotCmdError(p, i, "unable",
   32821             "The --preserve-rowids option is not compatible"
   32822                 " with SQLITE_OMIT_VIRTUALTABLE");
   32823           rc = 1;
   32824           sqlite3_free(zLike);
   32825           goto meta_command_exit;
   32826 #else
   32827           ShellSetFlag(p, SHFLG_PreserveRowid);
   32828 #endif
   32829         }else
   32830         if( cli_strcmp(z,"newlines")==0 ){
   32831           /*ShellSetFlag(p, SHFLG_Newlines);*/
   32832         }else
   32833         if( cli_strcmp(z,"data-only")==0 ){
   32834           ShellSetFlag(p, SHFLG_DumpDataOnly);
   32835         }else
   32836         if( cli_strcmp(z,"nosys")==0 ){
   32837           ShellSetFlag(p, SHFLG_DumpNoSys);
   32838         }else
   32839         {
   32840           dotCmdError(p, i, "unknown option", 0);
   32841           rc = 1;
   32842           sqlite3_free(zLike);
   32843           goto meta_command_exit;
   32844         }
   32845       }else{
   32846         /* azArg[i] contains a LIKE pattern. This ".dump" request should
   32847         ** only dump data for tables for which either the table name matches
   32848         ** the LIKE pattern, or the table appears to be a shadow table of
   32849         ** a virtual table for which the name matches the LIKE pattern.
   32850         */
   32851         char *zExpr = sqlite3_mprintf(
   32852             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
   32853             "  SELECT 1 FROM sqlite_schema WHERE "
   32854             "    name LIKE %Q ESCAPE '\\' AND"
   32855             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
   32856             "    substr(o.name, 1, length(name)+1) == (name||'_')"
   32857             ")", azArg[i], azArg[i]
   32858         );
   32859 
   32860         if( zLike ){
   32861           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
   32862         }else{
   32863           zLike = zExpr;
   32864         }
   32865       }
   32866     }
   32867 
   32868     open_db(p, 0);
   32869 
   32870     modeDup(&saved_mode, &p->mode);
   32871     outputDumpWarning(p, zLike);
   32872     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
   32873       /* When playing back a "dump", the content might appear in an order
   32874       ** which causes immediate foreign key constraints to be violated.
   32875       ** So disable foreign-key constraint enforcement to prevent problems. */
   32876       cli_puts("PRAGMA foreign_keys=OFF;\n", p->out);
   32877       cli_puts("BEGIN TRANSACTION;\n", p->out);
   32878     }
   32879     p->writableSchema = 0;
   32880     p->mode.spec.bTitles = QRF_No;
   32881     /* Set writable_schema=ON since doing so forces SQLite to initialize
   32882     ** as much of the schema as it can even if the sqlite_schema table is
   32883     ** corrupt. */
   32884     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
   32885     p->nErr = 0;
   32886     if( zLike==0 ) zLike = sqlite3_mprintf("true");
   32887     zSql = sqlite3_mprintf(
   32888       "SELECT name, type, sql FROM sqlite_schema AS o "
   32889       "WHERE (%s) AND type=='table'"
   32890       "  AND sql NOT NULL"
   32891       " ORDER BY tbl_name='sqlite_sequence', rowid",
   32892       zLike
   32893     );
   32894     run_schema_dump_query(p,zSql);
   32895     sqlite3_free(zSql);
   32896     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
   32897       zSql = sqlite3_mprintf(
   32898         "SELECT sql FROM sqlite_schema AS o "
   32899         "WHERE (%s) AND sql NOT NULL"
   32900         "  AND type IN ('index','trigger','view') "
   32901         "ORDER BY type COLLATE NOCASE DESC",
   32902         zLike
   32903       );
   32904       run_table_dump_query(p, zSql);
   32905       sqlite3_free(zSql);
   32906     }
   32907     sqlite3_free(zLike);
   32908     if( p->writableSchema ){
   32909       cli_puts("PRAGMA writable_schema=OFF;\n", p->out);
   32910       p->writableSchema = 0;
   32911     }
   32912     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
   32913     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
   32914     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
   32915       cli_puts(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n", p->out);
   32916     }
   32917     p->shellFlgs = savedShellFlags;
   32918     modeFree(&p->mode);
   32919     p->mode = saved_mode;
   32920     rc = p->nErr>0;
   32921   }else
   32922 
   32923   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
   32924     if( nArg==2 ){
   32925       if( booleanValue(azArg[1]) ){
   32926         p->mode.mFlags |= MFLG_ECHO;
   32927       }else{
   32928         p->mode.mFlags &= ~MFLG_ECHO;
   32929       }
   32930     }else{
   32931       eputz("Usage: .echo on|off\n");
   32932       rc = 1;
   32933     }
   32934   }else
   32935 
   32936   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbtotxt", n)==0 ){
   32937     open_db(p, 0);
   32938     rc = shell_dbtotxt_command(p, nArg, azArg);
   32939   }else
   32940 
   32941   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
   32942     if( nArg==2 ){
   32943       if( p->mode.autoEQPtrace ){
   32944         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
   32945         p->mode.autoEQPtrace = 0;
   32946       }
   32947       if( cli_strcmp(azArg[1],"full")==0 ){
   32948         p->mode.autoEQP = AUTOEQP_full;
   32949       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
   32950         p->mode.autoEQP = AUTOEQP_trigger;
   32951 #ifdef SQLITE_DEBUG
   32952       }else if( cli_strcmp(azArg[1],"trace")==0 ){
   32953         p->mode.autoEQP = AUTOEQP_full;
   32954         p->mode.autoEQPtrace = 1;
   32955         open_db(p, 0);
   32956         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
   32957         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
   32958 #endif
   32959       }else{
   32960         p->mode.autoEQP = (u8)booleanValue(azArg[1]);
   32961       }
   32962     }else{
   32963       eputz("Usage: .eqp off|on|trace|trigger|full\n");
   32964       rc = 1;
   32965     }
   32966   }else
   32967 
   32968 #ifndef SQLITE_SHELL_FIDDLE
   32969   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
   32970     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) cli_exit(rc);
   32971     rc = 2;
   32972   }else
   32973 #endif
   32974 
   32975   /* The ".explain" command is automatic now.  It is largely pointless.  It
   32976   ** retained purely for backwards compatibility */
   32977   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
   32978     if( nArg>=2 ){
   32979       if( cli_strcmp(azArg[1],"auto")==0 ){
   32980         p->mode.autoExplain = 1;
   32981       }else{
   32982         p->mode.autoExplain = booleanValue(azArg[1]);
   32983       }
   32984     }
   32985   }else
   32986 
   32987 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   32988   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
   32989     if( p->bSafeMode ){
   32990       cli_printf(stderr,
   32991             "Cannot run experimental commands such as \"%s\" in safe mode\n",
   32992             azArg[0]);
   32993       rc = 1;
   32994     }else{
   32995       open_db(p, 0);
   32996       expertDotCommand(p, azArg, nArg);
   32997     }
   32998   }else
   32999 #endif
   33000 
   33001   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
   33002     static const struct {
   33003        const char *zCtrlName;   /* Name of a test-control option */
   33004        int ctrlCode;            /* Integer code for that option */
   33005        const char *zUsage;      /* Usage notes */
   33006     } aCtrl[] = {
   33007       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
   33008       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
   33009       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
   33010       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
   33011       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
   33012    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
   33013       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
   33014       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
   33015       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
   33016       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
   33017    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
   33018     };
   33019     int filectrl = -1;
   33020     int iCtrl = -1;
   33021     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
   33022     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
   33023     int n2, i;
   33024     const char *zCmd = 0;
   33025     const char *zSchema = 0;
   33026 
   33027     open_db(p, 0);
   33028     zCmd = nArg>=2 ? azArg[1] : "help";
   33029 
   33030     if( zCmd[0]=='-'
   33031      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
   33032      && nArg>=4
   33033     ){
   33034       zSchema = azArg[2];
   33035       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
   33036       nArg -= 2;
   33037       zCmd = azArg[1];
   33038     }
   33039 
   33040     /* The argument can optionally begin with "-" or "--" */
   33041     if( zCmd[0]=='-' && zCmd[1] ){
   33042       zCmd++;
   33043       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
   33044     }
   33045 
   33046     /* --help lists all file-controls */
   33047     if( cli_strcmp(zCmd,"help")==0 ){
   33048       cli_puts("Available file-controls:\n", p->out);
   33049       for(i=0; i<ArraySize(aCtrl); i++){
   33050         cli_printf(p->out,
   33051                "  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
   33052       }
   33053       rc = 1;
   33054       goto meta_command_exit;
   33055     }
   33056 
   33057     /* convert filectrl text option to value. allow any unique prefix
   33058     ** of the option name, or a numerical value. */
   33059     n2 = strlen30(zCmd);
   33060     for(i=0; i<ArraySize(aCtrl); i++){
   33061       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
   33062         if( filectrl<0 ){
   33063           filectrl = aCtrl[i].ctrlCode;
   33064           iCtrl = i;
   33065         }else{
   33066           cli_printf(stderr,"Error: ambiguous file-control: \"%s\"\n"
   33067                 "Use \".filectrl --help\" for help\n", zCmd);
   33068           rc = 1;
   33069           goto meta_command_exit;
   33070         }
   33071       }
   33072     }
   33073     if( filectrl<0 ){
   33074       cli_printf(stderr,"Error: unknown file-control: %s\n"
   33075             "Use \".filectrl --help\" for help\n", zCmd);
   33076     }else{
   33077       switch(filectrl){
   33078         case SQLITE_FCNTL_SIZE_LIMIT: {
   33079           if( nArg!=2 && nArg!=3 ) break;
   33080           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
   33081           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
   33082           isOk = 1;
   33083           break;
   33084         }
   33085         case SQLITE_FCNTL_LOCK_TIMEOUT:
   33086         case SQLITE_FCNTL_CHUNK_SIZE: {
   33087           int x;
   33088           if( nArg!=3 ) break;
   33089           x = (int)integerValue(azArg[2]);
   33090           sqlite3_file_control(p->db, zSchema, filectrl, &x);
   33091           isOk = 2;
   33092           break;
   33093         }
   33094         case SQLITE_FCNTL_PERSIST_WAL:
   33095         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   33096           int x;
   33097           if( nArg!=2 && nArg!=3 ) break;
   33098           x = nArg==3 ? booleanValue(azArg[2]) : -1;
   33099           sqlite3_file_control(p->db, zSchema, filectrl, &x);
   33100           iRes = x;
   33101           isOk = 1;
   33102           break;
   33103         }
   33104         case SQLITE_FCNTL_DATA_VERSION:
   33105         case SQLITE_FCNTL_HAS_MOVED: {
   33106           int x;
   33107           if( nArg!=2 ) break;
   33108           sqlite3_file_control(p->db, zSchema, filectrl, &x);
   33109           iRes = x;
   33110           isOk = 1;
   33111           break;
   33112         }
   33113         case SQLITE_FCNTL_TEMPFILENAME: {
   33114           char *z = 0;
   33115           if( nArg!=2 ) break;
   33116           sqlite3_file_control(p->db, zSchema, filectrl, &z);
   33117           if( z ){
   33118             cli_printf(p->out, "%s\n", z);
   33119             sqlite3_free(z);
   33120           }
   33121           isOk = 2;
   33122           break;
   33123         }
   33124         case SQLITE_FCNTL_RESERVE_BYTES: {
   33125           int x;
   33126           if( nArg>=3 ){
   33127             x = atoi(azArg[2]);
   33128             sqlite3_file_control(p->db, zSchema, filectrl, &x);
   33129           }
   33130           x = -1;
   33131           sqlite3_file_control(p->db, zSchema, filectrl, &x);
   33132           cli_printf(p->out, "%d\n", x);
   33133           isOk = 2;
   33134           break;
   33135         }
   33136       }
   33137     }
   33138     if( isOk==0 && iCtrl>=0 ){
   33139       cli_printf(p->out, "Usage: .filectrl %s %s\n",
   33140                       zCmd, aCtrl[iCtrl].zUsage);
   33141       rc = 1;
   33142     }else if( isOk==1 ){
   33143       char zBuf[100];
   33144       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
   33145       cli_printf(p->out, "%s\n", zBuf);
   33146     }
   33147   }else
   33148 
   33149   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
   33150     ShellState data;
   33151     int doStats = 0;
   33152     int hasStat[5];
   33153     int flgs = 0;
   33154     char *zSql;
   33155     if( nArg==2 && optionMatch(azArg[1], "indent") ){
   33156       nArg = 1;
   33157     }
   33158     if( nArg!=1 ){
   33159       eputz("Usage: .fullschema ?--indent?\n");
   33160       rc = 1;
   33161       goto meta_command_exit;
   33162     }
   33163     open_db(p, 0);
   33164     zSql = sqlite3_mprintf(
   33165        "SELECT shell_format_schema(sql,%d) FROM"
   33166        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
   33167        "     FROM sqlite_schema UNION ALL"
   33168        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
   33169        "WHERE type!='meta' AND sql NOTNULL"
   33170        "  AND name NOT LIKE 'sqlite__%%' ESCAPE '_' "
   33171        "ORDER BY x", flgs);
   33172     memcpy(&data, p, sizeof(data));
   33173     data.mode.spec.bTitles = QRF_No;
   33174     data.mode.eMode = MODE_List;
   33175     data.mode.spec.eText = QRF_TEXT_Plain;
   33176     data.mode.spec.nCharLimit = 0;
   33177     data.mode.spec.zRowSep = "\n";
   33178     rc = shell_exec(&data,zSql,0);
   33179     sqlite3_free(zSql);
   33180     if( rc==SQLITE_OK ){
   33181       sqlite3_stmt *pStmt;
   33182       memset(hasStat, 0, sizeof(hasStat));
   33183       rc = sqlite3_prepare_v2(p->db,
   33184                "SELECT substr(name,12,1) FROM sqlite_schema"
   33185                " WHERE name GLOB 'sqlite_stat[134]'",
   33186                -1, &pStmt, 0);
   33187       if( rc==SQLITE_OK ){
   33188         while( sqlite3_step(pStmt)==SQLITE_ROW ){
   33189           int k = sqlite3_column_int(pStmt,0);
   33190           assert( k==1 || k==3 || k==4 );
   33191           hasStat[k] = 1;
   33192           doStats = 1;
   33193         }
   33194       }
   33195       sqlite3_finalize(pStmt);
   33196     }
   33197     if( doStats==0 ){
   33198       cli_puts("/* No STAT tables available */\n", p->out);
   33199     }else{
   33200       cli_puts("ANALYZE sqlite_schema;\n", p->out);
   33201       data.mode.eMode = MODE_Insert;
   33202       if( hasStat[1] ){
   33203         data.mode.spec.zTableName = "sqlite_stat1";
   33204         shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
   33205       }
   33206       if( hasStat[4] ){
   33207         data.mode.spec.zTableName = "sqlite_stat4";
   33208         shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
   33209       }
   33210       cli_puts("ANALYZE sqlite_schema;\n", p->out);
   33211     }
   33212   }else
   33213 
   33214   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
   33215     if( nArg==2 ){
   33216       p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
   33217       p->mode.mFlags |= MFLG_HDR;
   33218       p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
   33219     }else{
   33220       eputz("Usage: .headers on|off\n");
   33221       rc = 1;
   33222     }
   33223   }else
   33224 
   33225   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
   33226     if( nArg>=2 ){
   33227       n = showHelp(p->out, azArg[1]);
   33228       if( n==0 ){
   33229         cli_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
   33230       }
   33231     }else{
   33232       showHelp(p->out, 0);
   33233     }
   33234   }else
   33235 
   33236 #ifndef SQLITE_SHELL_FIDDLE
   33237   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
   33238     rc = dotCmdImport(p);
   33239   }else
   33240 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   33241 
   33242 #ifndef SQLITE_UNTESTABLE
   33243   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
   33244     char *zSql;
   33245     char *zCollist = 0;
   33246     sqlite3_stmt *pStmt;
   33247     int tnum = 0;
   33248     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
   33249     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
   33250     int i;
   33251     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
   33252       eputz("Usage: .imposter INDEX IMPOSTER\n"
   33253             "       .imposter off\n");
   33254       /* Also allowed, but not documented:
   33255       **
   33256       **    .imposter TABLE IMPOSTER
   33257       **
   33258       ** where TABLE is a WITHOUT ROWID table.  In that case, the
   33259       ** imposter is another WITHOUT ROWID table with the columns in
   33260       ** storage order. */
   33261       rc = 1;
   33262       goto meta_command_exit;
   33263     }
   33264     open_db(p, 0);
   33265     if( nArg==2 ){
   33266       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
   33267       goto meta_command_exit;
   33268     }
   33269     zSql = sqlite3_mprintf(
   33270       "SELECT rootpage, 0 FROM sqlite_schema"
   33271       " WHERE type='index' AND lower(name)=lower('%q')"
   33272       "UNION ALL "
   33273       "SELECT rootpage, 1 FROM sqlite_schema"
   33274       " WHERE type='table' AND lower(name)=lower('%q')"
   33275       "   AND sql LIKE '%%without%%rowid%%'",
   33276       azArg[1], azArg[1]
   33277     );
   33278     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   33279     sqlite3_free(zSql);
   33280     if( sqlite3_step(pStmt)==SQLITE_ROW ){
   33281       tnum = sqlite3_column_int(pStmt, 0);
   33282       isWO = sqlite3_column_int(pStmt, 1);
   33283     }
   33284     sqlite3_finalize(pStmt);
   33285     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
   33286     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   33287     sqlite3_free(zSql);
   33288     i = 0;
   33289     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   33290       char zLabel[20];
   33291       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
   33292       i++;
   33293       if( zCol==0 ){
   33294         if( sqlite3_column_int(pStmt,1)==-1 ){
   33295           zCol = "_ROWID_";
   33296         }else{
   33297           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
   33298           zCol = zLabel;
   33299         }
   33300       }
   33301       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
   33302         lenPK = (int)strlen(zCollist);
   33303       }
   33304       if( zCollist==0 ){
   33305         zCollist = sqlite3_mprintf("\"%w\"", zCol);
   33306       }else{
   33307         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
   33308       }
   33309     }
   33310     sqlite3_finalize(pStmt);
   33311     if( i==0 || tnum==0 ){
   33312       cli_printf(stderr,"no such index: \"%s\"\n", azArg[1]);
   33313       rc = 1;
   33314       sqlite3_free(zCollist);
   33315       goto meta_command_exit;
   33316     }
   33317     if( lenPK==0 ) lenPK = 100000;
   33318     zSql = sqlite3_mprintf(
   33319           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
   33320           azArg[2], zCollist, lenPK, zCollist);
   33321     sqlite3_free(zCollist);
   33322     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 2, tnum);
   33323     if( rc==SQLITE_OK ){
   33324       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
   33325       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
   33326       if( rc ){
   33327         cli_printf(stderr,
   33328               "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
   33329       }else{
   33330         cli_printf(stdout, "%s;\n", zSql);
   33331       }
   33332     }else{
   33333       cli_printf(stderr,"SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
   33334       rc = 1;
   33335     }
   33336     sqlite3_free(zSql);
   33337   }else
   33338 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
   33339 
   33340   if( c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
   33341                  || cli_strncmp(azArg[0], "indexes", n)==0)
   33342   ){
   33343     sqlite3_str *pSql;
   33344     int i;
   33345     int allFlag = 0;
   33346     int sysFlag = 0;
   33347     int exprFlag = 0;
   33348     int debugFlag = 0;  /* Undocument --debug flag */
   33349     const char *zPattern = 0;
   33350     const char *zSep = "WHERE";
   33351 
   33352     for(i=1; i<nArg; i++){
   33353       if( azArg[i][0]=='-' ){
   33354         const char *z = azArg[i]+1;
   33355         if( z[0]=='-' ) z++;
   33356         if( cli_strcmp(z,"all")==0 || cli_strcmp(z,"a")==0 ){
   33357           allFlag = 1;
   33358         }else
   33359         if( cli_strcmp(z,"sys")==0 ){
   33360           sysFlag = 1;
   33361           allFlag = 0;
   33362         }else
   33363         if( cli_strcmp(z,"expr")==0 ){
   33364           exprFlag = 1;
   33365           allFlag = 0;
   33366         }else
   33367         if( cli_strcmp(z,"debug")==0 ){
   33368           debugFlag = 1;
   33369         }else
   33370         {
   33371           dotCmdError(p, i, "unknown option", 0);
   33372           rc = 1;
   33373           goto meta_command_exit;
   33374         }
   33375       }else if( zPattern==0 ){
   33376         zPattern = azArg[i];
   33377       }else{
   33378         dotCmdError(p, i, "unknown argument", 0);
   33379         rc = 1;
   33380         goto meta_command_exit;
   33381       }
   33382     }
   33383 
   33384     open_db(p, 0);
   33385     pSql = sqlite3_str_new(p->db);
   33386     sqlite3_str_appendf(pSql,
   33387       "SELECT if(t.schema='main',i.name,t.schema||'.'||i.name)\n"
   33388       "FROM pragma_table_list t, pragma_index_list(t.name,t.schema) i\n"
   33389     );
   33390     if( exprFlag ){
   33391       allFlag = 0;
   33392       sqlite3_str_appendf(pSql,
   33393         "%s (EXISTS(SELECT 1 FROM pragma_index_xinfo(i.name) WHERE cid=-2)\n"
   33394         "       OR\n"
   33395         "       EXISTS(SELECT cid FROM pragma_table_xinfo(t.name) WHERE hidden=2"
   33396         " INTERSECT "
   33397         " SELECT cid FROM pragma_index_info(i.name)))\n", zSep);
   33398       zSep = "AND";
   33399     }
   33400     if( sysFlag ){
   33401       sqlite3_str_appendf(pSql,
   33402            "%s i.name LIKE 'sqlite__autoindex__%%' ESCAPE '_'\n", zSep);
   33403       zSep = "AND";
   33404     }else if( !allFlag ){
   33405       sqlite3_str_appendf(pSql,
   33406            "%s i.name NOT LIKE 'sqlite__%%' ESCAPE '_'\n", zSep);
   33407       zSep = "AND";
   33408     }
   33409     if( zPattern ){
   33410       sqlite3_str_appendf(pSql, "%s i.name LIKE '%%%q%%'\n", zSep, zPattern);
   33411     }
   33412     sqlite3_str_appendf(pSql, "ORDER BY 1");
   33413 
   33414     /* Run the SQL statement in "split" mode. */
   33415     if( debugFlag ){
   33416       cli_printf(stdout,"%s;\n", sqlite3_str_value(pSql));
   33417     }else{
   33418       modePush(p);
   33419       modeChange(p, MODE_Split);
   33420       shell_exec(p, sqlite3_str_value(pSql), 0);
   33421       modePop(p);
   33422     }
   33423     sqlite3_str_free(pSql);
   33424   }else
   33425 
   33426   if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
   33427     i64 iArg = 0;
   33428     if( nArg==2 ){
   33429       iArg = integerValue(azArg[1]);
   33430       if( iArg==0 ) iArg = -1;
   33431     }
   33432     if( (nArg!=1 && nArg!=2) || iArg<0 ){
   33433       cli_printf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n");
   33434       rc = 1;
   33435       goto meta_command_exit;
   33436     }
   33437     open_db(p, 0);
   33438     rc = intckDatabaseCmd(p, iArg);
   33439   }else
   33440 
   33441 #ifdef SQLITE_ENABLE_IOTRACE
   33442   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
   33443     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
   33444     if( iotrace && iotrace!=stdout ) fclose(iotrace);
   33445     iotrace = 0;
   33446     if( nArg<2 ){
   33447       sqlite3IoTrace = 0;
   33448     }else if( cli_strcmp(azArg[1], "-")==0 ){
   33449       sqlite3IoTrace = iotracePrintf;
   33450       iotrace = stdout;
   33451     }else{
   33452       iotrace = sqlite3_fopen(azArg[1], "w");
   33453       if( iotrace==0 ){
   33454         cli_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
   33455         sqlite3IoTrace = 0;
   33456         rc = 1;
   33457       }else{
   33458         sqlite3IoTrace = iotracePrintf;
   33459       }
   33460     }
   33461   }else
   33462 #endif
   33463 
   33464   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
   33465     static const struct {
   33466        const char *zLimitName;   /* Name of a limit */
   33467        int limitCode;            /* Integer code for that limit */
   33468     } aLimit[] = {
   33469       { "length",                SQLITE_LIMIT_LENGTH                    },
   33470       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
   33471       { "column",                SQLITE_LIMIT_COLUMN                    },
   33472       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
   33473       { "parser_depth",          SQLITE_LIMIT_PARSER_DEPTH              },
   33474       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
   33475       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
   33476       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
   33477       { "attached",              SQLITE_LIMIT_ATTACHED                  },
   33478       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
   33479       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
   33480       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
   33481       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
   33482     };
   33483     int i, n2;
   33484     open_db(p, 0);
   33485     if( nArg==1 ){
   33486       for(i=0; i<ArraySize(aLimit); i++){
   33487         cli_printf(stdout, "%20s %d\n", aLimit[i].zLimitName,
   33488               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
   33489       }
   33490     }else if( nArg>3 ){
   33491       eputz("Usage: .limit NAME ?NEW-VALUE?\n");
   33492       rc = 1;
   33493       goto meta_command_exit;
   33494     }else{
   33495       int iLimit = -1;
   33496       n2 = strlen30(azArg[1]);
   33497       for(i=0; i<ArraySize(aLimit); i++){
   33498         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
   33499           if( iLimit<0 ){
   33500             iLimit = i;
   33501           }else{
   33502             cli_printf(stderr,"ambiguous limit: \"%s\"\n", azArg[1]);
   33503             rc = 1;
   33504             goto meta_command_exit;
   33505           }
   33506         }
   33507       }
   33508       if( iLimit<0 ){
   33509         cli_printf(stderr,"unknown limit: \"%s\"\n"
   33510               "enter \".limits\" with no arguments for a list.\n",
   33511               azArg[1]);
   33512         rc = 1;
   33513         goto meta_command_exit;
   33514       }
   33515       if( nArg==3 ){
   33516         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
   33517                       (int)integerValue(azArg[2]));
   33518       }else{
   33519         cli_printf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
   33520               sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
   33521       }
   33522     }
   33523   }else
   33524 
   33525   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
   33526     open_db(p, 0);
   33527     lintDotCommand(p, azArg, nArg);
   33528   }else
   33529 
   33530 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
   33531   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
   33532     const char *zFile, *zProc;
   33533     char *zErrMsg = 0;
   33534     failIfSafeMode(p, "cannot run .load in safe mode");
   33535     if( nArg<2 || azArg[1][0]==0 ){
   33536       /* Must have a non-empty FILE. (Will not load self.) */
   33537       eputz("Usage: .load FILE ?ENTRYPOINT?\n");
   33538       rc = 1;
   33539       goto meta_command_exit;
   33540     }
   33541     zFile = azArg[1];
   33542     zProc = nArg>=3 ? azArg[2] : 0;
   33543     open_db(p, 0);
   33544     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
   33545     if( rc!=SQLITE_OK ){
   33546       shellEmitError(zErrMsg);
   33547       sqlite3_free(zErrMsg);
   33548       rc = 1;
   33549     }
   33550   }else
   33551 #endif
   33552 
   33553   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
   33554     if( nArg!=2 ){
   33555       eputz("Usage: .log FILENAME\n");
   33556       rc = 1;
   33557     }else{
   33558       const char *zFile = azArg[1];
   33559       if( p->bSafeMode
   33560        && cli_strcmp(zFile,"on")!=0
   33561        && cli_strcmp(zFile,"off")!=0
   33562       ){
   33563         sputz(stdout, "cannot set .log to anything other"
   33564               " than \"on\" or \"off\"\n");
   33565         zFile = "off";
   33566       }
   33567       output_file_close(p->pLog);
   33568       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
   33569       p->pLog = output_file_open(p, zFile);
   33570     }
   33571   }else
   33572 
   33573   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
   33574     rc = dotCmdMode(p);
   33575   }else
   33576 
   33577 #ifndef SQLITE_SHELL_FIDDLE
   33578   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
   33579     if( nArg!=2 ){
   33580       eputz("Usage: .nonce NONCE\n");
   33581       rc = 1;
   33582     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
   33583       cli_printf(stderr,"line %lld: incorrect nonce: \"%s\"\n",
   33584             p->lineno, azArg[1]);
   33585       cli_exit(1);
   33586     }else{
   33587       p->bSafeMode = 0;
   33588       return 0;  /* Return immediately to bypass the safe mode reset
   33589                  ** at the end of this procedure */
   33590     }
   33591   }else
   33592 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   33593 
   33594   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
   33595     if( nArg==2 ){
   33596       modeSetStr(&p->mode.spec.zNull, azArg[1]);
   33597     }else{
   33598       eputz("Usage: .nullvalue STRING\n");
   33599       rc = 1;
   33600     }
   33601   }else
   33602 
   33603   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
   33604     const char *zFN = 0;     /* Pointer to constant filename */
   33605     char *zNewFilename = 0;  /* Name of the database file to open */
   33606     int iName = 1;           /* Index in azArg[] of the filename */
   33607     int newFlag = 0;         /* True to delete file before opening */
   33608     int openMode = SHELL_OPEN_UNSPEC;
   33609     int openFlags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
   33610 
   33611     if( p->bSafeMode ) openFlags = SQLITE_OPEN_READONLY;
   33612 
   33613     /* Check for command-line arguments */
   33614     for(iName=1; iName<nArg; iName++){
   33615       const char *z = azArg[iName];
   33616 #ifndef SQLITE_SHELL_FIDDLE
   33617       if( optionMatch(z,"new") ){
   33618         newFlag = 1;
   33619 #ifdef SQLITE_HAVE_ZLIB
   33620       }else if( optionMatch(z, "zip") && !p->bSafeMode ){
   33621         openMode = SHELL_OPEN_ZIPFILE;
   33622 #endif
   33623       }else if( optionMatch(z, "append") && !p->bSafeMode ){
   33624         openMode = SHELL_OPEN_APPENDVFS;
   33625       }else if( optionMatch(z, "readonly") ){
   33626         openFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   33627         openFlags |= SQLITE_OPEN_READONLY;
   33628       }else if( optionMatch(z, "exclusive") ){
   33629         openFlags |= SQLITE_OPEN_EXCLUSIVE;
   33630       }else if( optionMatch(z, "ifexists") ){
   33631         openFlags &= ~(SQLITE_OPEN_CREATE);
   33632       }else if( optionMatch(z, "nofollow") ){
   33633         openFlags |= SQLITE_OPEN_NOFOLLOW;
   33634 #ifndef SQLITE_OMIT_DESERIALIZE
   33635       }else if( optionMatch(z, "deserialize") ){
   33636         openMode = SHELL_OPEN_DESERIALIZE;
   33637       }else if( optionMatch(z, "hexdb") ){
   33638         openMode = SHELL_OPEN_HEXDB;
   33639       }else if( optionMatch(z, "normal") ){
   33640         openMode = SHELL_OPEN_NORMAL;
   33641       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
   33642         p->szMax = integerValue(azArg[++iName]);
   33643 #endif /* SQLITE_OMIT_DESERIALIZE */
   33644       }else
   33645 #endif /* !SQLITE_SHELL_FIDDLE */
   33646       if( z[0]=='-' ){
   33647         cli_printf(stderr,"unknown option: %s\n", z);
   33648         rc = 1;
   33649         goto meta_command_exit;
   33650       }else if( zFN ){
   33651         cli_printf(stderr,"extra argument: \"%s\"\n", z);
   33652         rc = 1;
   33653         goto meta_command_exit;
   33654       }else{
   33655         zFN = z;
   33656       }
   33657     }
   33658 
   33659     /* Close the existing database */
   33660     session_close_all(p, -1);
   33661     close_db(p->db);
   33662     p->db = 0;
   33663     p->pAuxDb->zDbFilename = 0;
   33664     sqlite3_free(p->pAuxDb->zFreeOnClose);
   33665     p->pAuxDb->zFreeOnClose = 0;
   33666     p->openMode = openMode;
   33667     p->openFlags = openFlags;
   33668     p->szMax = 0;
   33669 
   33670     /* If a filename is specified, try to open it first */
   33671     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
   33672       if( newFlag && zFN && !p->bSafeMode ){
   33673         if( cli_strncmp(zFN,"file:",5)==0 ){
   33674           char *zDel = shellFilenameFromUri(zFN);
   33675           shell_check_oom(zDel);
   33676           shellDeleteFile(zDel);
   33677           sqlite3_free(zDel);
   33678         }else{
   33679           shellDeleteFile(zFN);
   33680         }
   33681       }
   33682 #ifndef SQLITE_SHELL_FIDDLE
   33683       if( p->bSafeMode
   33684        && p->openMode!=SHELL_OPEN_HEXDB
   33685        && zFN
   33686        && cli_strcmp(zFN,":memory:")!=0
   33687       ){
   33688         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
   33689       }
   33690 #else
   33691       /* WASM mode has its own sandboxed pseudo-filesystem. */
   33692 #endif
   33693       if( zFN ){
   33694         zNewFilename = sqlite3_mprintf("%s", zFN);
   33695         shell_check_oom(zNewFilename);
   33696       }else{
   33697         zNewFilename = 0;
   33698       }
   33699       p->pAuxDb->zDbFilename = zNewFilename;
   33700       open_db(p, OPEN_DB_KEEPALIVE);
   33701       if( p->db==0 ){
   33702         cli_printf(stderr,"Error: cannot open '%s'\n", zNewFilename);
   33703         sqlite3_free(zNewFilename);
   33704       }else{
   33705         p->pAuxDb->zFreeOnClose = zNewFilename;
   33706       }
   33707     }
   33708     if( p->db==0 ){
   33709       /* As a fall-back open a TEMP database */
   33710       p->pAuxDb->zDbFilename = 0;
   33711       open_db(p, 0);
   33712     }
   33713   }else
   33714 
   33715 #ifndef SQLITE_SHELL_FIDDLE
   33716   if( (c=='o'
   33717         && (cli_strncmp(azArg[0], "output", n)==0
   33718             || cli_strncmp(azArg[0], "once", n)==0))
   33719    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
   33720    || (c=='w' && n==3 && cli_strcmp(azArg[0],"www")==0)
   33721   ){
   33722     rc = dotCmdOutput(p);
   33723   }else
   33724 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   33725 
   33726   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
   33727     open_db(p,0);
   33728     if( nArg<=1 ) goto parameter_syntax_error;
   33729 
   33730     /* .parameter clear
   33731     ** Clear all bind parameters by dropping the TEMP table that holds them.
   33732     */
   33733     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
   33734       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
   33735                    0, 0, 0);
   33736     }else
   33737 
   33738     /* .parameter list
   33739     ** List all bind parameters.
   33740     */
   33741     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
   33742       sqlite3_stmt *pStmt = 0;
   33743       int rx;
   33744       int len = 0;
   33745       rx = sqlite3_prepare_v2(p->db,
   33746              "SELECT max(length(key)) "
   33747              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
   33748       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   33749         len = sqlite3_column_int(pStmt, 0);
   33750         if( len>40 ) len = 40;
   33751       }
   33752       sqlite3_finalize(pStmt);
   33753       pStmt = 0;
   33754       if( len ){
   33755         rx = sqlite3_prepare_v2(p->db,
   33756              "SELECT key, quote(value) "
   33757              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
   33758         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   33759           cli_printf(p->out,
   33760                 "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
   33761                 sqlite3_column_text(pStmt,1));
   33762         }
   33763         sqlite3_finalize(pStmt);
   33764       }
   33765     }else
   33766 
   33767     /* .parameter init
   33768     ** Make sure the TEMP table used to hold bind parameters exists.
   33769     ** Create it if necessary.
   33770     */
   33771     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
   33772       bind_table_init(p);
   33773     }else
   33774 
   33775     /* .parameter set NAME VALUE
   33776     ** Set or reset a bind parameter.  NAME should be the full parameter
   33777     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
   33778     ** VALUE can be in either SQL literal notation, or if not it will be
   33779     ** understood to be a text string.
   33780     */
   33781     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
   33782       int rx;
   33783       char *zSql;
   33784       sqlite3_stmt *pStmt;
   33785       const char *zKey = azArg[2];
   33786       const char *zValue = azArg[3];
   33787       bind_table_init(p);
   33788       zSql = sqlite3_mprintf(
   33789                   "REPLACE INTO temp.sqlite_parameters(key,value)"
   33790                   "VALUES(%Q,%s);", zKey, zValue);
   33791       shell_check_oom(zSql);
   33792       pStmt = 0;
   33793       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   33794       sqlite3_free(zSql);
   33795       if( rx!=SQLITE_OK ){
   33796         sqlite3_finalize(pStmt);
   33797         pStmt = 0;
   33798         zSql = sqlite3_mprintf(
   33799                    "REPLACE INTO temp.sqlite_parameters(key,value)"
   33800                    "VALUES(%Q,%Q);", zKey, zValue);
   33801         shell_check_oom(zSql);
   33802         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   33803         sqlite3_free(zSql);
   33804         if( rx!=SQLITE_OK ){
   33805           cli_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
   33806           sqlite3_finalize(pStmt);
   33807           pStmt = 0;
   33808           rc = 1;
   33809         }
   33810       }
   33811       bind_prepared_stmt(p, pStmt);
   33812       sqlite3_step(pStmt);
   33813       sqlite3_finalize(pStmt);
   33814     }else
   33815 
   33816     /* .parameter unset NAME
   33817     ** Remove the NAME binding from the parameter binding table, if it
   33818     ** exists.
   33819     */
   33820     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
   33821       char *zSql = sqlite3_mprintf(
   33822           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
   33823       shell_check_oom(zSql);
   33824       sqlite3_exec(p->db, zSql, 0, 0, 0);
   33825       sqlite3_free(zSql);
   33826     }else
   33827     /* If no command name matches, show a syntax error */
   33828     parameter_syntax_error:
   33829     showHelp(p->out, "parameter");
   33830   }else
   33831 
   33832   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
   33833     int i;
   33834     for(i=1; i<nArg; i++){
   33835       if( i>1 ) cli_puts(" ", p->out);
   33836       cli_puts(azArg[i], p->out);
   33837     }
   33838     cli_puts("\n", p->out);
   33839   }else
   33840 
   33841 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   33842   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
   33843     int i;
   33844     int nn = 0;
   33845     p->flgProgress = 0;
   33846     p->mxProgress = 0;
   33847     p->nProgress = 0;
   33848     for(i=1; i<nArg; i++){
   33849       const char *z = azArg[i];
   33850       if( z[0]=='-' ){
   33851         z++;
   33852         if( z[0]=='-' ) z++;
   33853         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
   33854           p->flgProgress |= SHELL_PROGRESS_QUIET;
   33855           continue;
   33856         }
   33857         if( cli_strcmp(z,"reset")==0 ){
   33858           p->flgProgress |= SHELL_PROGRESS_RESET;
   33859           continue;
   33860         }
   33861         if( cli_strcmp(z,"once")==0 ){
   33862           p->flgProgress |= SHELL_PROGRESS_ONCE;
   33863           continue;
   33864         }
   33865         if( cli_strcmp(z,"timeout")==0 ){
   33866           if( i==nArg-1 ){
   33867             dotCmdError(p, i, "missing argument", 0);
   33868             return 1;
   33869           }
   33870           i++;
   33871           p->tmProgress = atof(azArg[i]);
   33872           if( p->tmProgress>0.0 ){
   33873             p->flgProgress = SHELL_PROGRESS_QUIET|SHELL_PROGRESS_TMOUT;
   33874             if( nn==0 ) nn = 100;
   33875           }
   33876           continue;
   33877         }
   33878         if( cli_strcmp(z,"limit")==0 ){
   33879           if( i+1>=nArg ){
   33880             eputz("Error: missing argument on --limit\n");
   33881             rc = 1;
   33882             goto meta_command_exit;
   33883           }else{
   33884             p->mxProgress = (int)integerValue(azArg[++i]);
   33885           }
   33886           continue;
   33887         }
   33888         cli_printf(stderr,"Error: unknown option: \"%s\"\n", azArg[i]);
   33889         rc = 1;
   33890         goto meta_command_exit;
   33891       }else{
   33892         nn = (int)integerValue(z);
   33893       }
   33894     }
   33895     open_db(p, 0);
   33896     sqlite3_progress_handler(p->db, nn, progress_handler, p);
   33897   }else
   33898 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
   33899 
   33900   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
   33901     if( nArg >= 2) {
   33902       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
   33903     }
   33904     if( nArg >= 3) {
   33905       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
   33906     }
   33907   }else
   33908 
   33909 #ifndef SQLITE_SHELL_FIDDLE
   33910   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
   33911     rc = 2;
   33912   }else
   33913 #endif
   33914 
   33915 #ifndef SQLITE_SHELL_FIDDLE
   33916   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
   33917     FILE *inSaved = p->in;
   33918     i64 savedLineno = p->lineno;
   33919     failIfSafeMode(p, "cannot run .read in safe mode");
   33920     if( nArg!=2 ){
   33921       eputz("Usage: .read FILE\n");
   33922       rc = 1;
   33923       goto meta_command_exit;
   33924     }
   33925     if( azArg[1][0]=='|' ){
   33926 #ifdef SQLITE_OMIT_POPEN
   33927       eputz("Error: pipes are not supported in this OS\n");
   33928       rc = 1;
   33929 #else
   33930       p->in = sqlite3_popen(azArg[1]+1, "r");
   33931       if( p->in==0 ){
   33932         cli_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
   33933         rc = 1;
   33934       }else{
   33935         rc = process_input(p, "<pipe>");
   33936         pclose(p->in);
   33937       }
   33938 #endif
   33939     }else if( (p->in = openChrSource(azArg[1]))==0 ){
   33940       cli_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
   33941       rc = 1;
   33942     }else{
   33943       char *zFilename = strdup(azArg[1]);
   33944       rc = process_input(p, zFilename);
   33945       free(zFilename);
   33946       fclose(p->in);
   33947     }
   33948     p->in = inSaved;
   33949     p->lineno = savedLineno;
   33950   }else
   33951 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   33952 
   33953 #ifndef SQLITE_SHELL_FIDDLE
   33954   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
   33955     const char *zSrcFile;
   33956     const char *zDb;
   33957     sqlite3 *pSrc;
   33958     sqlite3_backup *pBackup;
   33959     int nTimeout = 0;
   33960 
   33961     failIfSafeMode(p, "cannot run .restore in safe mode");
   33962     if( nArg==2 ){
   33963       zSrcFile = azArg[1];
   33964       zDb = "main";
   33965     }else if( nArg==3 ){
   33966       zSrcFile = azArg[2];
   33967       zDb = azArg[1];
   33968     }else{
   33969       eputz("Usage: .restore ?DB? FILE\n");
   33970       rc = 1;
   33971       goto meta_command_exit;
   33972     }
   33973     rc = sqlite3_open(zSrcFile, &pSrc);
   33974     if( rc!=SQLITE_OK ){
   33975       cli_printf(stderr,"Error: cannot open \"%s\"\n", zSrcFile);
   33976       close_db(pSrc);
   33977       return 1;
   33978     }
   33979     open_db(p, 0);
   33980     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
   33981     if( pBackup==0 ){
   33982       shellDatabaseError(p->db);
   33983       close_db(pSrc);
   33984       return 1;
   33985     }
   33986     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
   33987           || rc==SQLITE_BUSY  ){
   33988       if( rc==SQLITE_BUSY ){
   33989         if( nTimeout++ >= 3 ) break;
   33990         sqlite3_sleep(100);
   33991       }
   33992     }
   33993     sqlite3_backup_finish(pBackup);
   33994     if( rc==SQLITE_DONE ){
   33995       rc = 0;
   33996     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
   33997       eputz("Error: source database is busy\n");
   33998       rc = 1;
   33999     }else{
   34000       shellDatabaseError(p->db);
   34001       rc = 1;
   34002     }
   34003     close_db(pSrc);
   34004   }else
   34005 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
   34006 
   34007   if( c=='s' &&
   34008      (cli_strncmp(azArg[0], "scanstats",  n)==0 ||
   34009       cli_strncmp(azArg[0], "scanstatus", n)==0)
   34010   ){
   34011     if( nArg==2 ){
   34012       if( cli_strcmp(azArg[1], "vm")==0 ){
   34013         p->mode.scanstatsOn = 3;
   34014       }else
   34015       if( cli_strcmp(azArg[1], "est")==0 ){
   34016         p->mode.scanstatsOn = 2;
   34017       }else{
   34018         p->mode.scanstatsOn = (u8)booleanValue(azArg[1]);
   34019       }
   34020       open_db(p, 0);
   34021       sqlite3_db_config(
   34022           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->mode.scanstatsOn, (int*)0
   34023       );
   34024 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
   34025       eputz("Warning: .scanstats not available in this build.\n");
   34026 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
   34027       if( p->mode.scanstatsOn==3 ){
   34028         eputz("Warning: \".scanstats vm\" not available in this build.\n");
   34029       }
   34030 #endif
   34031     }else{
   34032       eputz("Usage: .scanstats on|off|est\n");
   34033       rc = 1;
   34034     }
   34035   }else
   34036 
   34037   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
   34038     ShellState data;
   34039     char *zErrMsg = 0;
   34040     const char *zDiv = "(";
   34041     const char *zName = 0;
   34042     int iSchema = 0;
   34043     int bDebug = 0;
   34044     int bNoSystemTabs = 0;
   34045     int bIndent = 0;
   34046     int ii;
   34047     sqlite3_str *pSql;
   34048     sqlite3_stmt *pStmt = 0;
   34049 
   34050     open_db(p, 0);
   34051     memcpy(&data, p, sizeof(data));
   34052     data.mode.spec.bTitles = QRF_No;
   34053     data.mode.eMode = MODE_List;
   34054     data.mode.spec.eText = QRF_TEXT_Plain;
   34055     data.mode.spec.nCharLimit = 0;
   34056     data.mode.spec.zRowSep = "\n";
   34057     for(ii=1; ii<nArg; ii++){
   34058       if( optionMatch(azArg[ii],"indent") ){
   34059         bIndent = 1;
   34060       }else if( optionMatch(azArg[ii],"debug") ){
   34061         bDebug = 1;
   34062       }else if( optionMatch(azArg[ii],"nosys") ){
   34063         bNoSystemTabs = 1;
   34064       }else if( azArg[ii][0]=='-' ){
   34065         cli_printf(stderr,"Unknown option: \"%s\"\n", azArg[ii]);
   34066         rc = 1;
   34067         goto meta_command_exit;
   34068       }else if( zName==0 ){
   34069         zName = azArg[ii];
   34070       }else{
   34071         eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
   34072         rc = 1;
   34073         goto meta_command_exit;
   34074       }
   34075     }
   34076     if( zName!=0 ){
   34077       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
   34078                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
   34079                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
   34080                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
   34081       if( isSchema ){
   34082         cli_printf(p->out,
   34083                       "CREATE TABLE %ssqlite_schema (\n"
   34084                       "  type text,\n"
   34085                       "  name text,\n"
   34086                       "  tbl_name text,\n"
   34087                       "  rootpage integer,\n"
   34088                       "  sql text\n"
   34089                       ");\n",
   34090                sqlite3_strlike("sqlite_t%",zName,0)==0 ? "temp." : ""
   34091         );
   34092       }
   34093     }
   34094     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
   34095     if( rc ){
   34096       shellDatabaseError(p->db);
   34097       sqlite3_finalize(pStmt);
   34098 
   34099       rc = 1;
   34100       goto meta_command_exit;
   34101     }
   34102     pSql = sqlite3_str_new(p->db);
   34103     sqlite3_str_appendf(pSql, "SELECT sql FROM", 0);
   34104     iSchema = 0;
   34105     while( sqlite3_step(pStmt)==SQLITE_ROW ){
   34106       const char *zDb = (const char*)sqlite3_column_text(pStmt, 1);
   34107       char zScNum[30];
   34108       sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
   34109       sqlite3_str_appendall(pSql, zDiv);
   34110       zDiv = " UNION ALL ";
   34111       if( sqlite3_stricmp(zDb, "main")==0 ){
   34112         sqlite3_str_appendf(pSql,
   34113             "SELECT shell_format_schema(shell_add_schema(sql,NULL,name),%d)",
   34114             bIndent);
   34115       }else{
   34116         sqlite3_str_appendf(pSql,
   34117             "SELECT shell_format_schema(shell_add_schema(sql,%Q,name),%d)",
   34118             zDb, bIndent);
   34119       }
   34120       sqlite3_str_appendf(pSql,
   34121          " AS sql, type, tbl_name, name, rowid, %d AS snum, %Q as sname",
   34122          ++iSchema, zDb);
   34123       sqlite3_str_appendf(pSql," FROM \"%w\".sqlite_schema", zDb);
   34124     }
   34125     sqlite3_finalize(pStmt);
   34126 #if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) \
   34127  && !defined(SQLITE_OMIT_VIRTUALTABLE)
   34128     if( zName ){
   34129       sqlite3_str_appendall(pSql,
   34130          " UNION ALL SELECT shell_module_schema(name),"
   34131          " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list");
   34132     }
   34133 #endif
   34134     sqlite3_str_appendf(pSql, ") WHERE ", 0);
   34135     if( zName ){
   34136       int bGlob;
   34137       bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
   34138               strchr(zName, '[') != 0;
   34139       if( strchr(zName, '.') ){
   34140         sqlite3_str_appendall(pSql, "lower(format('%%s.%%s',sname,tbl_name))");
   34141       }else{
   34142         sqlite3_str_appendall(pSql, "lower(tbl_name)");
   34143       }
   34144       if( bGlob ){
   34145         sqlite3_str_appendf(pSql, " GLOB %Q AND ", zName);
   34146       }else{
   34147         sqlite3_str_appendf(pSql, " LIKE %Q ESCAPE '\\' AND ", zName);
   34148       }
   34149     }
   34150     if( bNoSystemTabs ){
   34151       sqlite3_str_appendf(pSql, " name NOT LIKE 'sqlite__%%' ESCAPE '_' AND ");
   34152     }
   34153     sqlite3_str_appendf(pSql, "sql IS NOT NULL ORDER BY snum, rowid");
   34154     if( bDebug ){
   34155       cli_printf(p->out, "SQL: %s;\n", sqlite3_str_value(pSql));
   34156     }else{
   34157       rc = shell_exec(&data, sqlite3_str_value(pSql), &zErrMsg);
   34158     }
   34159     sqlite3_str_free(pSql);
   34160 
   34161     if( zErrMsg ){
   34162       shellEmitError(zErrMsg);
   34163       sqlite3_free(zErrMsg);
   34164       rc = 1;
   34165     }else if( rc != SQLITE_OK ){
   34166       eputz("Error: querying schema information\n");
   34167       rc = 1;
   34168     }else{
   34169       rc = 0;
   34170     }
   34171   }else
   34172 
   34173   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
   34174    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
   34175   ){
   34176     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
   34177     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
   34178   }else
   34179 
   34180 #if defined(SQLITE_ENABLE_SESSION)
   34181   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
   34182     struct AuxDb *pAuxDb = p->pAuxDb;
   34183     OpenSession *pSession = &pAuxDb->aSession[0];
   34184     char **azCmd = &azArg[1];
   34185     int iSes = 0;
   34186     int nCmd = nArg - 1;
   34187     int i;
   34188     if( nArg<=1 ) goto session_syntax_error;
   34189     open_db(p, 0);
   34190     if( nArg>=3 ){
   34191       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
   34192         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
   34193       }
   34194       if( iSes<pAuxDb->nSession ){
   34195         pSession = &pAuxDb->aSession[iSes];
   34196         azCmd++;
   34197         nCmd--;
   34198       }else{
   34199         pSession = &pAuxDb->aSession[0];
   34200         iSes = 0;
   34201       }
   34202     }
   34203 
   34204     /* .session attach TABLE
   34205     ** Invoke the sqlite3session_attach() interface to attach a particular
   34206     ** table so that it is never filtered.
   34207     */
   34208     if( cli_strcmp(azCmd[0],"attach")==0 ){
   34209       if( nCmd!=2 ) goto session_syntax_error;
   34210       if( pSession->p==0 ){
   34211         session_not_open:
   34212         eputz("ERROR: No sessions are open\n");
   34213       }else{
   34214         rc = sqlite3session_attach(pSession->p, azCmd[1]);
   34215         if( rc ){
   34216           cli_printf(stderr,
   34217                "ERROR: sqlite3session_attach() returns %d\n",rc);
   34218           rc = 0;
   34219         }
   34220       }
   34221     }else
   34222 
   34223     /* .session changeset FILE
   34224     ** .session patchset FILE
   34225     ** Write a changeset or patchset into a file.  The file is overwritten.
   34226     */
   34227     if( cli_strcmp(azCmd[0],"changeset")==0
   34228      || cli_strcmp(azCmd[0],"patchset")==0
   34229     ){
   34230       FILE *out = 0;
   34231       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
   34232       if( nCmd!=2 ) goto session_syntax_error;
   34233       if( pSession->p==0 ) goto session_not_open;
   34234       out = sqlite3_fopen(azCmd[1], "wb");
   34235       if( out==0 ){
   34236         cli_printf(stderr,"ERROR: cannot open \"%s\" for writing\n",
   34237               azCmd[1]);
   34238       }else{
   34239         int szChng;
   34240         void *pChng;
   34241         if( azCmd[0][0]=='c' ){
   34242           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
   34243         }else{
   34244           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
   34245         }
   34246         if( rc ){
   34247           cli_printf(stdout, "Error: error code %d\n", rc);
   34248           rc = 0;
   34249         }
   34250         if( pChng
   34251           && fwrite(pChng, szChng, 1, out)!=1 ){
   34252           cli_printf(stderr,
   34253               "ERROR: Failed to write entire %d-byte output\n", szChng);
   34254         }
   34255         sqlite3_free(pChng);
   34256         fclose(out);
   34257       }
   34258     }else
   34259 
   34260     /* .session close
   34261     ** Close the identified session
   34262     */
   34263     if( cli_strcmp(azCmd[0], "close")==0 ){
   34264       if( nCmd!=1 ) goto session_syntax_error;
   34265       if( pAuxDb->nSession ){
   34266         session_close(pSession);
   34267         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
   34268       }
   34269     }else
   34270 
   34271     /* .session enable ?BOOLEAN?
   34272     ** Query or set the enable flag
   34273     */
   34274     if( cli_strcmp(azCmd[0], "enable")==0 ){
   34275       int ii;
   34276       if( nCmd>2 ) goto session_syntax_error;
   34277       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
   34278       if( pAuxDb->nSession ){
   34279         ii = sqlite3session_enable(pSession->p, ii);
   34280         cli_printf(p->out,
   34281             "session %s enable flag = %d\n", pSession->zName, ii);
   34282       }
   34283     }else
   34284 
   34285     /* .session filter GLOB ....
   34286     ** Set a list of GLOB patterns of table names to be excluded.
   34287     */
   34288     if( cli_strcmp(azCmd[0], "filter")==0 ){
   34289       int ii;
   34290       i64 nByte;
   34291       if( nCmd<2 ) goto session_syntax_error;
   34292       if( pAuxDb->nSession ){
   34293         for(ii=0; ii<pSession->nFilter; ii++){
   34294           sqlite3_free(pSession->azFilter[ii]);
   34295         }
   34296         sqlite3_free(pSession->azFilter);
   34297         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
   34298         pSession->azFilter = sqlite3_malloc64( nByte );
   34299         shell_check_oom( pSession->azFilter );
   34300         for(ii=1; ii<nCmd; ii++){
   34301           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
   34302           shell_check_oom(x);
   34303         }
   34304         pSession->nFilter = ii-1;
   34305       }
   34306     }else
   34307 
   34308     /* .session indirect ?BOOLEAN?
   34309     ** Query or set the indirect flag
   34310     */
   34311     if( cli_strcmp(azCmd[0], "indirect")==0 ){
   34312       int ii;
   34313       if( nCmd>2 ) goto session_syntax_error;
   34314       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
   34315       if( pAuxDb->nSession ){
   34316         ii = sqlite3session_indirect(pSession->p, ii);
   34317         cli_printf(p->out,
   34318             "session %s indirect flag = %d\n", pSession->zName, ii);
   34319       }
   34320     }else
   34321 
   34322     /* .session isempty
   34323     ** Determine if the session is empty
   34324     */
   34325     if( cli_strcmp(azCmd[0], "isempty")==0 ){
   34326       int ii;
   34327       if( nCmd!=1 ) goto session_syntax_error;
   34328       if( pAuxDb->nSession ){
   34329         ii = sqlite3session_isempty(pSession->p);
   34330         cli_printf(p->out,
   34331              "session %s isempty flag = %d\n", pSession->zName, ii);
   34332       }
   34333     }else
   34334 
   34335     /* .session list
   34336     ** List all currently open sessions
   34337     */
   34338     if( cli_strcmp(azCmd[0],"list")==0 ){
   34339       for(i=0; i<pAuxDb->nSession; i++){
   34340         cli_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
   34341       }
   34342     }else
   34343 
   34344     /* .session open DB NAME
   34345     ** Open a new session called NAME on the attached database DB.
   34346     ** DB is normally "main".
   34347     */
   34348     if( cli_strcmp(azCmd[0],"open")==0 ){
   34349       char *zName;
   34350       if( nCmd!=3 ) goto session_syntax_error;
   34351       zName = azCmd[2];
   34352       if( zName[0]==0 ) goto session_syntax_error;
   34353       for(i=0; i<pAuxDb->nSession; i++){
   34354         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
   34355           cli_printf(stderr,"Session \"%s\" already exists\n", zName);
   34356           goto meta_command_exit;
   34357         }
   34358       }
   34359       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
   34360         cli_printf(stderr,
   34361            "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
   34362         goto meta_command_exit;
   34363       }
   34364       pSession = &pAuxDb->aSession[pAuxDb->nSession];
   34365       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
   34366       if( rc ){
   34367         cli_printf(stderr,"Cannot open session: error code=%d\n", rc);
   34368         rc = 0;
   34369         goto meta_command_exit;
   34370       }
   34371       pSession->nFilter = 0;
   34372       sqlite3session_table_filter(pSession->p, session_filter, pSession);
   34373       pAuxDb->nSession++;
   34374       pSession->zName = sqlite3_mprintf("%s", zName);
   34375       shell_check_oom(pSession->zName);
   34376     }else
   34377     /* If no command name matches, show a syntax error */
   34378     session_syntax_error:
   34379     showHelp(p->out, "session");
   34380   }else
   34381 #endif
   34382 
   34383 #ifdef SQLITE_DEBUG
   34384   /* Undocumented commands for internal testing.  Subject to change
   34385   ** without notice. */
   34386   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
   34387     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
   34388       int i, v;
   34389       for(i=1; i<nArg; i++){
   34390         v = booleanValue(azArg[i]);
   34391         cli_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
   34392       }
   34393     }
   34394     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
   34395       int i; sqlite3_int64 v;
   34396       for(i=1; i<nArg; i++){
   34397         char zBuf[200];
   34398         v = integerValue(azArg[i]);
   34399         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
   34400         cli_puts(zBuf, p->out);
   34401       }
   34402     }
   34403   }else
   34404 #endif
   34405 
   34406   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
   34407     int bIsInit = 0;         /* True to initialize the SELFTEST table */
   34408     int bVerbose = 0;        /* Verbose output */
   34409     int bSelftestExists;     /* True if SELFTEST already exists */
   34410     int i, k;                /* Loop counters */
   34411     int nTest = 0;           /* Number of tests runs */
   34412     int nErr = 0;            /* Number of errors seen */
   34413     ShellText str;           /* Answer for a query */
   34414     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
   34415 
   34416     open_db(p,0);
   34417     for(i=1; i<nArg; i++){
   34418       const char *z = azArg[i];
   34419       if( z[0]=='-' && z[1]=='-' ) z++;
   34420       if( cli_strcmp(z,"-init")==0 ){
   34421         bIsInit = 1;
   34422       }else
   34423       if( cli_strcmp(z,"-v")==0 ){
   34424         bVerbose++;
   34425       }else
   34426       {
   34427         cli_printf(stderr,
   34428               "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
   34429         cli_puts("Should be one of: --init -v\n", stderr);
   34430         rc = 1;
   34431         goto meta_command_exit;
   34432       }
   34433     }
   34434     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
   34435            != SQLITE_OK ){
   34436       bSelftestExists = 0;
   34437     }else{
   34438       bSelftestExists = 1;
   34439     }
   34440     if( bIsInit ){
   34441       createSelftestTable(p);
   34442       bSelftestExists = 1;
   34443     }
   34444     initText(&str);
   34445     appendText(&str, "x", 0);
   34446     for(k=bSelftestExists; k>=0; k--){
   34447       if( k==1 ){
   34448         rc = sqlite3_prepare_v2(p->db,
   34449             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
   34450             -1, &pStmt, 0);
   34451       }else{
   34452         rc = sqlite3_prepare_v2(p->db,
   34453           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
   34454           "      (1,'run','PRAGMA integrity_check','ok')",
   34455           -1, &pStmt, 0);
   34456       }
   34457       if( rc ){
   34458         eputz("Error querying the selftest table\n");
   34459         rc = 1;
   34460         sqlite3_finalize(pStmt);
   34461         goto meta_command_exit;
   34462       }
   34463       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
   34464         int tno = sqlite3_column_int(pStmt, 0);
   34465         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
   34466         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
   34467         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
   34468 
   34469         if( zOp==0 ) continue;
   34470         if( zSql==0 ) continue;
   34471         if( zAns==0 ) continue;
   34472         k = 0;
   34473         if( bVerbose>0 ){
   34474           cli_printf(stdout, "%d: %s %s\n", tno, zOp, zSql);
   34475         }
   34476         if( cli_strcmp(zOp,"memo")==0 ){
   34477           cli_printf(p->out, "%s\n", zSql);
   34478         }else
   34479         if( cli_strcmp(zOp,"run")==0 ){
   34480           char *zErrMsg = 0;
   34481           str.n = 0;
   34482           str.zTxt[0] = 0;
   34483           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
   34484           nTest++;
   34485           if( bVerbose ){
   34486             cli_printf(p->out, "Result: %s\n", str.zTxt);
   34487           }
   34488           if( rc || zErrMsg ){
   34489             nErr++;
   34490             rc = 1;
   34491             cli_printf(p->out, "%d: error-code-%d: %s\n", tno, rc,zErrMsg);
   34492             sqlite3_free(zErrMsg);
   34493           }else if( cli_strcmp(zAns,str.zTxt)!=0 ){
   34494             nErr++;
   34495             rc = 1;
   34496             cli_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
   34497             cli_printf(p->out, "%d:      Got: [%s]\n", tno, str.zTxt);
   34498           }
   34499         }
   34500         else{
   34501           cli_printf(stderr,
   34502                 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
   34503           rc = 1;
   34504           break;
   34505         }
   34506       } /* End loop over rows of content from SELFTEST */
   34507       sqlite3_finalize(pStmt);
   34508     } /* End loop over k */
   34509     freeText(&str);
   34510     cli_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
   34511   }else
   34512 
   34513   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
   34514     if( nArg<2 || nArg>3 ){
   34515       eputz("Usage: .separator COL ?ROW?\n");
   34516       rc = 1;
   34517     }
   34518     if( nArg>=2 ){
   34519       modeSetStr(&p->mode.spec.zColumnSep, azArg[1]);
   34520     }
   34521     if( nArg>=3 ){
   34522       modeSetStr(&p->mode.spec.zRowSep,azArg[2]);
   34523     }
   34524   }else
   34525 
   34526   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
   34527     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
   34528     int i;                   /* Loop counter */
   34529     int bSchema = 0;         /* Also hash the schema */
   34530     int bSeparate = 0;       /* Hash each table separately */
   34531     int iSize = 224;         /* Hash algorithm to use */
   34532     int bDebug = 0;          /* Only show the query that would have run */
   34533     sqlite3_stmt *pStmt;     /* For querying tables names */
   34534     char *zSql;              /* SQL to be run */
   34535     char *zSep;              /* Separator */
   34536     ShellText sSql;          /* Complete SQL for the query to run the hash */
   34537     ShellText sQuery;        /* Set of queries used to read all content */
   34538     open_db(p, 0);
   34539     for(i=1; i<nArg; i++){
   34540       const char *z = azArg[i];
   34541       if( z[0]=='-' ){
   34542         z++;
   34543         if( z[0]=='-' ) z++;
   34544         if( cli_strcmp(z,"schema")==0 ){
   34545           bSchema = 1;
   34546         }else
   34547         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
   34548          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
   34549         ){
   34550           iSize = atoi(&z[5]);
   34551         }else
   34552         if( cli_strcmp(z,"debug")==0 ){
   34553           bDebug = 1;
   34554         }else
   34555         {
   34556           cli_printf(stderr,
   34557                   "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
   34558           showHelp(p->out, azArg[0]);
   34559           rc = 1;
   34560           goto meta_command_exit;
   34561         }
   34562       }else if( zLike ){
   34563         eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
   34564         rc = 1;
   34565         goto meta_command_exit;
   34566       }else{
   34567         zLike = z;
   34568         bSeparate = 1;
   34569         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
   34570       }
   34571     }
   34572     if( bSchema ){
   34573       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
   34574              " WHERE type='table' AND coalesce(rootpage,0)>1"
   34575              " UNION ALL SELECT 'sqlite_schema'"
   34576              " ORDER BY 1 collate nocase";
   34577     }else{
   34578       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
   34579              " WHERE type='table' AND coalesce(rootpage,0)>1"
   34580              " AND name NOT LIKE 'sqlite__%' ESCAPE '_'"
   34581              " ORDER BY 1 collate nocase";
   34582     }
   34583     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   34584     initText(&sQuery);
   34585     initText(&sSql);
   34586     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
   34587     zSep = "VALUES(";
   34588     while( SQLITE_ROW==sqlite3_step(pStmt) ){
   34589       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
   34590       if( zTab==0 ) continue;
   34591       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
   34592       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
   34593         appendText(&sQuery,"SELECT * FROM ", 0);
   34594         appendText(&sQuery,zTab,'"');
   34595         appendText(&sQuery," NOT INDEXED;", 0);
   34596       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
   34597         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
   34598                            " ORDER BY name;", 0);
   34599       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
   34600         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
   34601                            " ORDER BY name;", 0);
   34602       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
   34603         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
   34604                            " ORDER BY tbl,idx;", 0);
   34605       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
   34606         appendText(&sQuery, "SELECT * FROM ", 0);
   34607         appendText(&sQuery, zTab, 0);
   34608         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
   34609       }
   34610       appendText(&sSql, zSep, 0);
   34611       appendText(&sSql, sQuery.zTxt, '\'');
   34612       sQuery.n = 0;
   34613       appendText(&sSql, ",", 0);
   34614       appendText(&sSql, zTab, '\'');
   34615       zSep = "),(";
   34616     }
   34617     sqlite3_finalize(pStmt);
   34618     if( bSeparate ){
   34619       zSql = sqlite3_mprintf(
   34620           "%s))"
   34621           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
   34622           "   FROM [sha3sum$query]",
   34623           sSql.zTxt, iSize);
   34624     }else{
   34625       zSql = sqlite3_mprintf(
   34626           "%s))"
   34627           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
   34628           "   FROM [sha3sum$query]",
   34629           sSql.zTxt, iSize);
   34630     }
   34631     shell_check_oom(zSql);
   34632     freeText(&sQuery);
   34633     freeText(&sSql);
   34634     if( bDebug ){
   34635       cli_printf(p->out, "%s\n", zSql);
   34636     }else{
   34637       shell_exec(p, zSql, 0);
   34638     }
   34639 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
   34640     {
   34641       int lrc;
   34642       char *zRevText = /* Query for reversible to-blob-to-text check */
   34643         "SELECT lower(name) as tname FROM sqlite_schema\n"
   34644         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
   34645         "AND name NOT LIKE 'sqlite__%%' ESCAPE '_'%s\n"
   34646         "ORDER BY 1 collate nocase";
   34647       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
   34648       zRevText = sqlite3_mprintf(
   34649           /* lower-case query is first run, producing upper-case query. */
   34650           "with tabcols as materialized(\n"
   34651           "select tname, cname\n"
   34652           "from ("
   34653           " select printf('\"%%w\"',ss.tname) as tname,"
   34654           " printf('\"%%w\"',ti.name) as cname\n"
   34655           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
   34656           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
   34657           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
   34658           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
   34659           "FROM '||tname||' WHERE '\n"
   34660           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
   34661           "|| ' AND typeof('||cname||')=''text'' ',\n"
   34662           "' OR ') as query, tname from tabcols group by tname)"
   34663           , zRevText);
   34664       shell_check_oom(zRevText);
   34665       if( bDebug ) cli_printf(p->out, "%s\n", zRevText);
   34666       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
   34667       if( lrc!=SQLITE_OK ){
   34668         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
   34669         ** user does cruel and unnatural things like ".limit expr_depth 0". */
   34670         rc = 1;
   34671       }else{
   34672         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
   34673         lrc = SQLITE_ROW==sqlite3_step(pStmt);
   34674         if( lrc ){
   34675           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
   34676           sqlite3_stmt *pCheckStmt;
   34677           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
   34678           if( bDebug ) cli_printf(p->out, "%s\n", zGenQuery);
   34679           if( lrc!=SQLITE_OK ){
   34680             rc = 1;
   34681           }else{
   34682             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
   34683               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
   34684               if( countIrreversible>0 ){
   34685                 int sz = (int)(countIrreversible + 0.5);
   34686                 cli_printf(stderr,
   34687                       "Digest includes %d invalidly encoded text field%s.\n",
   34688                       sz, (sz>1)? "s": "");
   34689               }
   34690             }
   34691             sqlite3_finalize(pCheckStmt);
   34692           }
   34693           sqlite3_finalize(pStmt);
   34694         }
   34695       }
   34696       if( rc ) eputz(".sha3sum failed.\n");
   34697       sqlite3_free(zRevText);
   34698     }
   34699 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
   34700     sqlite3_free(zSql);
   34701   }else
   34702 
   34703 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
   34704   if( c=='s'
   34705    && (cli_strncmp(azArg[0], "shell", n)==0
   34706        || cli_strncmp(azArg[0],"system",n)==0)
   34707   ){
   34708     char *zCmd;
   34709     int i, x;
   34710     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
   34711     if( nArg<2 ){
   34712       eputz("Usage: .system COMMAND\n");
   34713       rc = 1;
   34714       goto meta_command_exit;
   34715     }
   34716     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
   34717     for(i=2; i<nArg && zCmd!=0; i++){
   34718       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
   34719                              zCmd, azArg[i]);
   34720     }
   34721     /*consoleRestore();*/
   34722     x = zCmd!=0 ? system(zCmd) : 1;
   34723     /*consoleRenewSetup();*/
   34724     sqlite3_free(zCmd);
   34725     if( x ) cli_printf(stderr,"System command returns %d\n", x);
   34726   }else
   34727 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
   34728 
   34729   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
   34730     static const char *azBool[] = { "off", "on", "trigger", "full"};
   34731     const char *zOut;
   34732     int i;
   34733     if( nArg!=1 ){
   34734       eputz("Usage: .show\n");
   34735       rc = 1;
   34736       goto meta_command_exit;
   34737     }
   34738     cli_printf(p->out, "%12.12s: %s\n","echo",
   34739             azBool[(p->mode.mFlags & MFLG_ECHO)!=0]);
   34740     cli_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->mode.autoEQP&3]);
   34741     cli_printf(p->out, "%12.12s: %s\n","explain",
   34742                              p->mode.autoExplain ? "auto" : "off");
   34743     cli_printf(p->out, "%12.12s: %s\n","headers",
   34744           azBool[p->mode.spec.bTitles==QRF_Yes]);
   34745     if( p->mode.spec.eStyle==QRF_STYLE_Column
   34746      || p->mode.spec.eStyle==QRF_STYLE_Box
   34747      || p->mode.spec.eStyle==QRF_STYLE_Table
   34748      || p->mode.spec.eStyle==QRF_STYLE_Markdown
   34749     ){
   34750       cli_printf(p->out,
   34751             "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
   34752             aModeInfo[p->mode.eMode].zName, p->mode.spec.nWrap,
   34753             p->mode.spec.bWordWrap==QRF_Yes ? "on" : "off",
   34754             p->mode.spec.eText==QRF_TEXT_Sql ? "" : "no");
   34755     }else{
   34756       cli_printf(p->out, "%12.12s: %s\n","mode",
   34757                  aModeInfo[p->mode.eMode].zName);
   34758     }
   34759     cli_printf(p->out, "%12.12s: ", "nullvalue");
   34760     output_c_string(p->out, p->mode.spec.zNull);
   34761     cli_puts("\n", p->out);
   34762     cli_printf(p->out, "%12.12s: %s\n","output",
   34763           strlen30(p->outfile) ? p->outfile : "stdout");
   34764     cli_printf(p->out, "%12.12s: ", "colseparator");
   34765     output_c_string(p->out, p->mode.spec.zColumnSep);
   34766     cli_puts("\n", p->out);
   34767     cli_printf(p->out, "%12.12s: ", "rowseparator");
   34768     output_c_string(p->out, p->mode.spec.zRowSep);
   34769     cli_puts("\n", p->out);
   34770     switch( p->statsOn ){
   34771       case 0:  zOut = "off";     break;
   34772       default: zOut = "on";      break;
   34773       case 2:  zOut = "stmt";    break;
   34774       case 3:  zOut = "vmstep";  break;
   34775     }
   34776     cli_printf(p->out, "%12.12s: %s\n","stats", zOut);
   34777     cli_printf(p->out, "%12.12s: ", "width");
   34778     for(i=0; i<p->mode.spec.nWidth; i++){
   34779       cli_printf(p->out, "%d ", (int)p->mode.spec.aWidth[i]);
   34780     }
   34781     cli_puts("\n", p->out);
   34782     cli_printf(p->out, "%12.12s: %s\n", "filename",
   34783           p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
   34784   }else
   34785 
   34786   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
   34787     if( nArg==2 ){
   34788       if( cli_strcmp(azArg[1],"stmt")==0 ){
   34789         p->statsOn = 2;
   34790       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
   34791         p->statsOn = 3;
   34792       }else{
   34793         p->statsOn = (u8)booleanValue(azArg[1]);
   34794       }
   34795     }else if( nArg==1 ){
   34796       display_stats(p->db, p, 0);
   34797     }else{
   34798       eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
   34799       rc = 1;
   34800     }
   34801   }else
   34802 
   34803   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0) ){
   34804     sqlite3_stmt *pStmt;
   34805     sqlite3_str *pSql;
   34806     const char *zPattern = nArg>1 ? azArg[1] : 0;
   34807 
   34808     open_db(p, 0);
   34809     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
   34810     if( rc ){
   34811       sqlite3_finalize(pStmt);
   34812       return shellDatabaseError(p->db);
   34813     }
   34814 
   34815     pSql = sqlite3_str_new(p->db);
   34816     while( sqlite3_step(pStmt)==SQLITE_ROW ){
   34817       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
   34818       if( zDbName==0 ) continue;
   34819       if( sqlite3_str_length(pSql) ){
   34820         sqlite3_str_appendall(pSql, " UNION ALL ");
   34821       }
   34822       if( sqlite3_stricmp(zDbName, "main")==0 ){
   34823         sqlite3_str_appendall(pSql, "SELECT name FROM ");
   34824       }else{
   34825         sqlite3_str_appendf(pSql, "SELECT %Q||'.'||name FROM ", zDbName);
   34826       }
   34827       sqlite3_str_appendf(pSql, "\"%w\".sqlite_schema", zDbName);
   34828       sqlite3_str_appendf(pSql,
   34829           " WHERE type IN ('table','view')"
   34830           "   AND name NOT LIKE 'sqlite__%%' ESCAPE '_'"
   34831       );
   34832       if( zPattern ){
   34833         sqlite3_str_appendf(pSql," AND name LIKE %Q", zPattern);
   34834       }
   34835     }
   34836     rc = sqlite3_finalize(pStmt);
   34837     if( rc==SQLITE_OK ){
   34838       sqlite3_str_appendall(pSql, " ORDER BY 1");
   34839     }
   34840 
   34841     /* Run the SQL statement in "split" mode. */
   34842     modePush(p);
   34843     modeChange(p, MODE_Split);
   34844     shell_exec(p, sqlite3_str_value(pSql), 0);
   34845     sqlite3_str_free(pSql);
   34846     modePop(p);
   34847     if( rc ) return shellDatabaseError(p->db);
   34848   }else
   34849 
   34850   /* Set the p->zTestcase name and begin redirecting output into
   34851   ** the cli_output_capture sqlite3_str */
   34852   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
   34853     rc = dotCmdTestcase(p);
   34854   }else
   34855 
   34856 #ifndef SQLITE_UNTESTABLE
   34857   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
   34858     static const struct {
   34859        const char *zCtrlName;   /* Name of a test-control option */
   34860        int ctrlCode;            /* Integer code for that option */
   34861        int unSafe;              /* Not valid unless --unsafe-testing */
   34862        const char *zUsage;      /* Usage notes */
   34863     } aCtrl[] = {
   34864     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
   34865     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
   34866   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
   34867     {"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1, "SIZE INT-ARRAY"},
   34868     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
   34869     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
   34870     {"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..."       },
   34871     {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
   34872     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
   34873     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
   34874     {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
   34875     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
   34876     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
   34877     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK ..."},
   34878 #ifdef YYCOVERAGE
   34879     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
   34880 #endif
   34881     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,1, "OFFSET  "       },
   34882     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
   34883     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
   34884     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
   34885     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
   34886     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
   34887     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
   34888     };
   34889     int testctrl = -1;
   34890     int iCtrl = -1;
   34891     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
   34892     int isOk = 0;
   34893     int i, n2;
   34894     const char *zCmd = 0;
   34895 
   34896     open_db(p, 0);
   34897     zCmd = nArg>=2 ? azArg[1] : "help";
   34898 
   34899     /* The argument can optionally begin with "-" or "--" */
   34900     if( zCmd[0]=='-' && zCmd[1] ){
   34901       zCmd++;
   34902       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
   34903     }
   34904 
   34905     /* --help lists all test-controls */
   34906     if( cli_strcmp(zCmd,"help")==0 ){
   34907       cli_puts("Available test-controls:\n", p->out);
   34908       for(i=0; i<ArraySize(aCtrl); i++){
   34909         if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
   34910         cli_printf(p->out, "  .testctrl %s %s\n",
   34911               aCtrl[i].zCtrlName, aCtrl[i].zUsage);
   34912       }
   34913       rc = 1;
   34914       goto meta_command_exit;
   34915     }
   34916 
   34917     /* convert testctrl text option to value. allow any unique prefix
   34918     ** of the option name, or a numerical value. */
   34919     n2 = strlen30(zCmd);
   34920     for(i=0; i<ArraySize(aCtrl); i++){
   34921       if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
   34922       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
   34923         if( testctrl<0 ){
   34924           testctrl = aCtrl[i].ctrlCode;
   34925           iCtrl = i;
   34926         }else{
   34927           cli_printf(stderr,"Error: ambiguous test-control: \"%s\"\n"
   34928                 "Use \".testctrl --help\" for help\n", zCmd);
   34929           rc = 1;
   34930           goto meta_command_exit;
   34931         }
   34932       }
   34933     }
   34934     if( testctrl<0 ){
   34935       cli_printf(stderr,"Error: unknown test-control: %s\n"
   34936             "Use \".testctrl --help\" for help\n", zCmd);
   34937     }else{
   34938       switch(testctrl){
   34939 
   34940         /* Special processing for .testctrl opt MASK ...
   34941         ** Each MASK argument can be one of:
   34942         **
   34943         **      +LABEL       Enable the named optimization
   34944         **
   34945         **      -LABEL       Disable the named optimization
   34946         **
   34947         **      INTEGER      Mask of optimizations to disable
   34948         */
   34949         case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   34950           static const struct {
   34951              unsigned int mask;    /* Mask for this optimization */
   34952              unsigned int bDsply;  /* Display this on output */
   34953              const char *zLabel;   /* Name of optimization */
   34954           } aLabel[] = {
   34955             { 0x00000001, 1, "QueryFlattener" },
   34956             { 0x00000001, 0, "Flatten" },
   34957             { 0x00000002, 1, "WindowFunc" },
   34958             { 0x00000004, 1, "GroupByOrder" },
   34959             { 0x00000008, 1, "FactorOutConst" },
   34960             { 0x00000010, 1, "DistinctOpt" },
   34961             { 0x00000020, 1, "CoverIdxScan" },
   34962             { 0x00000040, 1, "OrderByIdxJoin" },
   34963             { 0x00000080, 1, "Transitive" },
   34964             { 0x00000100, 1, "OmitNoopJoin" },
   34965             { 0x00000200, 1, "CountOfView" },
   34966             { 0x00000400, 1, "CursorHints" },
   34967             { 0x00000800, 1, "Stat4" },
   34968             { 0x00001000, 1, "PushDown" },
   34969             { 0x00002000, 1, "SimplifyJoin" },
   34970             { 0x00004000, 1, "SkipScan" },
   34971             { 0x00008000, 1, "PropagateConst" },
   34972             { 0x00010000, 1, "MinMaxOpt" },
   34973             { 0x00020000, 1, "SeekScan" },
   34974             { 0x00040000, 1, "OmitOrderBy" },
   34975             { 0x00080000, 1, "BloomFilter" },
   34976             { 0x00100000, 1, "BloomPulldown" },
   34977             { 0x00200000, 1, "BalancedMerge" },
   34978             { 0x00400000, 1, "ReleaseReg" },
   34979             { 0x00800000, 1, "FlttnUnionAll" },
   34980             { 0x01000000, 1, "IndexedEXpr" },
   34981             { 0x02000000, 1, "Coroutines" },
   34982             { 0x04000000, 1, "NullUnusedCols" },
   34983             { 0x08000000, 1, "OnePass" },
   34984             { 0x10000000, 1, "OrderBySubq" },
   34985             { 0x20000000, 1, "StarQuery" },
   34986             { 0x40000000, 1, "ExistsToJoin" },
   34987             { 0xffffffff, 0, "All" },
   34988           };
   34989           unsigned int curOpt;
   34990           unsigned int newOpt;
   34991           unsigned int m;
   34992           int ii;
   34993           int nOff;
   34994           sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt);
   34995           newOpt = curOpt;
   34996           for(ii=2; ii<nArg; ii++){
   34997             const char *z = azArg[ii];
   34998             int useLabel = 0;
   34999             const char *zLabel = 0;
   35000             if( (z[0]=='+'|| z[0]=='-') && !IsDigit(z[1]) ){
   35001               useLabel = z[0];
   35002               zLabel = &z[1];
   35003             }else if( !IsDigit(z[0]) && z[0]!=0 && !IsDigit(z[1]) ){
   35004               useLabel = '+';
   35005               zLabel = z;
   35006             }else{
   35007               newOpt = (unsigned int)strtol(z,0,0);
   35008             }
   35009             if( useLabel ){
   35010               int jj;
   35011               for(jj=0; jj<ArraySize(aLabel); jj++){
   35012                 if( sqlite3_stricmp(zLabel, aLabel[jj].zLabel)==0 ) break;
   35013               }
   35014               if( jj>=ArraySize(aLabel) ){
   35015                 cli_printf(stderr,
   35016                     "Error: no such optimization: \"%s\"\n", zLabel);
   35017                 cli_puts("Should be one of:", stderr);
   35018                 for(jj=0; jj<ArraySize(aLabel); jj++){
   35019                   cli_printf(stderr," %s", aLabel[jj].zLabel);
   35020                 }
   35021                 cli_puts("\n", stderr);
   35022                 rc = 1;
   35023                 goto meta_command_exit;
   35024               }
   35025               if( useLabel=='+' ){
   35026                 newOpt &= ~aLabel[jj].mask;
   35027               }else{
   35028                 newOpt |= aLabel[jj].mask;
   35029               }
   35030             }
   35031           }
   35032           if( curOpt!=newOpt ){
   35033             sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt);
   35034           }
   35035           for(ii=nOff=0, m=1; ii<32; ii++, m <<= 1){
   35036             if( m & newOpt ) nOff++;
   35037           }
   35038           if( nOff<12 ){
   35039             cli_puts("+All", p->out);
   35040             for(ii=0; ii<ArraySize(aLabel); ii++){
   35041               if( !aLabel[ii].bDsply  ) continue;
   35042               if( (newOpt & aLabel[ii].mask)!=0 ){
   35043                 cli_printf(p->out, " -%s", aLabel[ii].zLabel);
   35044               }
   35045             }
   35046           }else{
   35047             cli_puts("-All", p->out);
   35048             for(ii=0; ii<ArraySize(aLabel); ii++){
   35049               if( !aLabel[ii].bDsply  ) continue;
   35050               if( (newOpt & aLabel[ii].mask)==0 ){
   35051                 cli_printf(p->out, " +%s", aLabel[ii].zLabel);
   35052               }
   35053             }
   35054           }
   35055           cli_puts("\n", p->out);
   35056           rc2 = isOk = 3;
   35057           break;
   35058         }
   35059 
   35060         /* sqlite3_test_control(int, db, int) */
   35061         case SQLITE_TESTCTRL_FK_NO_ACTION:
   35062           if( nArg==3 ){
   35063             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
   35064             rc2 = sqlite3_test_control(testctrl, p->db, opt);
   35065             isOk = 3;
   35066           }
   35067           break;
   35068 
   35069         /* sqlite3_test_control(int) */
   35070         case SQLITE_TESTCTRL_PRNG_SAVE:
   35071         case SQLITE_TESTCTRL_PRNG_RESTORE:
   35072         case SQLITE_TESTCTRL_BYTEORDER:
   35073           if( nArg==2 ){
   35074             rc2 = sqlite3_test_control(testctrl);
   35075             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
   35076           }
   35077           break;
   35078 
   35079         /* sqlite3_test_control(int, uint) */
   35080         case SQLITE_TESTCTRL_PENDING_BYTE:
   35081           if( nArg==3 ){
   35082             unsigned int opt = (unsigned int)integerValue(azArg[2]);
   35083             rc2 = sqlite3_test_control(testctrl, opt);
   35084             isOk = 3;
   35085           }
   35086           break;
   35087 
   35088         /* sqlite3_test_control(int, int, sqlite3*) */
   35089         case SQLITE_TESTCTRL_PRNG_SEED:
   35090           if( nArg==3 || nArg==4 ){
   35091             int ii = (int)integerValue(azArg[2]);
   35092             sqlite3 *db;
   35093             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
   35094               sqlite3_randomness(sizeof(ii),&ii);
   35095               cli_printf(stdout, "-- random seed: %d\n", ii);
   35096             }
   35097             if( nArg==3 ){
   35098               db = 0;
   35099             }else{
   35100               db = p->db;
   35101               /* Make sure the schema has been loaded */
   35102               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
   35103             }
   35104             rc2 = sqlite3_test_control(testctrl, ii, db);
   35105             isOk = 3;
   35106           }
   35107           break;
   35108 
   35109         /* sqlite3_test_control(int, int) */
   35110         case SQLITE_TESTCTRL_ASSERT:
   35111         case SQLITE_TESTCTRL_ALWAYS:
   35112           if( nArg==3 ){
   35113             int opt = booleanValue(azArg[2]);
   35114             rc2 = sqlite3_test_control(testctrl, opt);
   35115             isOk = 1;
   35116           }
   35117           break;
   35118 
   35119         /* sqlite3_test_control(int, int) */
   35120         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
   35121         case SQLITE_TESTCTRL_NEVER_CORRUPT:
   35122           if( nArg==3 ){
   35123             int opt = booleanValue(azArg[2]);
   35124             rc2 = sqlite3_test_control(testctrl, opt);
   35125             isOk = 3;
   35126           }
   35127           break;
   35128 
   35129         /* sqlite3_test_control(sqlite3*) */
   35130         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
   35131           rc2 = sqlite3_test_control(testctrl, p->db);
   35132           isOk = 3;
   35133           break;
   35134 
   35135         case SQLITE_TESTCTRL_IMPOSTER:
   35136           if( nArg==5 ){
   35137             rc2 = sqlite3_test_control(testctrl, p->db,
   35138                           azArg[2],
   35139                           integerValue(azArg[3]),
   35140                           integerValue(azArg[4]));
   35141             isOk = 3;
   35142           }
   35143           break;
   35144 
   35145         case SQLITE_TESTCTRL_SEEK_COUNT: {
   35146           u64 x = 0;
   35147           rc2 = sqlite3_test_control(testctrl, p->db, &x);
   35148           cli_printf(p->out, "%llu\n", x);
   35149           isOk = 3;
   35150           break;
   35151         }
   35152 
   35153 #ifdef YYCOVERAGE
   35154         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
   35155           if( nArg==2 ){
   35156             sqlite3_test_control(testctrl, p->out);
   35157             isOk = 3;
   35158           }
   35159           break;
   35160         }
   35161 #endif
   35162 #ifdef SQLITE_DEBUG
   35163         case SQLITE_TESTCTRL_TUNE: {
   35164           if( nArg==4 ){
   35165             int id = (int)integerValue(azArg[2]);
   35166             int val = (int)integerValue(azArg[3]);
   35167             sqlite3_test_control(testctrl, id, &val);
   35168             isOk = 3;
   35169           }else if( nArg==3 ){
   35170             int id = (int)integerValue(azArg[2]);
   35171             sqlite3_test_control(testctrl, -id, &rc2);
   35172             isOk = 1;
   35173           }else if( nArg==2 ){
   35174             int id = 1;
   35175             while(1){
   35176               int val = 0;
   35177               rc2 = sqlite3_test_control(testctrl, -id, &val);
   35178               if( rc2!=SQLITE_OK ) break;
   35179               if( id>1 ) cli_puts("  ", p->out);
   35180               cli_printf(p->out, "%d: %d", id, val);
   35181               id++;
   35182             }
   35183             if( id>1 ) cli_puts("\n", p->out);
   35184             isOk = 3;
   35185           }
   35186           break;
   35187         }
   35188 #endif
   35189         case SQLITE_TESTCTRL_SORTER_MMAP:
   35190           if( nArg==3 ){
   35191             int opt = (unsigned int)integerValue(azArg[2]);
   35192             rc2 = sqlite3_test_control(testctrl, p->db, opt);
   35193             isOk = 3;
   35194           }
   35195           break;
   35196         case SQLITE_TESTCTRL_JSON_SELFCHECK:
   35197           if( nArg==2 ){
   35198             rc2 = -1;
   35199             isOk = 1;
   35200           }else{
   35201             rc2 = booleanValue(azArg[2]);
   35202             isOk = 3;
   35203           }
   35204           sqlite3_test_control(testctrl, &rc2);
   35205           break;
   35206         case SQLITE_TESTCTRL_BITVEC_TEST: {
   35207           /* Examples:
   35208           **   .testctrl bitvec_test 100   6,1       -- Show BITVEC constants
   35209           **   .testctrl bitvec_test 1000  1,12,7,3  -- Simple test
   35210           **                         ----  --------
   35211           **      size of Bitvec -----^        ^---  aOp array. 0 added at end.
   35212           **
   35213           ** See comments on sqlite3BitvecBuiltinTest() for more information
   35214           ** about the aOp[] array.
   35215           */
   35216           int iSize;
   35217           const char *zTestArg;
   35218           int nOp;
   35219           int ii, jj, x;
   35220           int *aOp;
   35221           if( nArg!=4 ){
   35222             cli_printf(stderr,
   35223               "ERROR - should be:  \".testctrl bitvec_test SIZE  INT-ARRAY\"\n"
   35224             );
   35225             rc = 1;
   35226             goto meta_command_exit;
   35227           }
   35228           isOk = 3;
   35229           iSize = (int)integerValue(azArg[2]);
   35230           zTestArg = azArg[3];
   35231           nOp = (int)strlen(zTestArg)+1;
   35232           aOp = malloc( sizeof(int)*(nOp+1) );
   35233           shell_check_oom(aOp);
   35234           memset(aOp, 0, sizeof(int)*(nOp+1) );
   35235           for(ii = jj = x = 0; zTestArg[ii]!=0; ii++){
   35236             if( IsDigit(zTestArg[ii]) ){
   35237               x = x*10 + zTestArg[ii] - '0';
   35238             }else{
   35239               aOp[jj++] = x;
   35240               x = 0;
   35241             }
   35242           }
   35243           aOp[jj] = x;
   35244           x = sqlite3_test_control(testctrl, iSize, aOp);
   35245           cli_printf(p->out, "result: %d\n", x);
   35246           free(aOp);
   35247           break;
   35248         }
   35249         case SQLITE_TESTCTRL_FAULT_INSTALL: {
   35250           int kk;
   35251           int bShowHelp = nArg<=2;
   35252           isOk = 3;
   35253           for(kk=2; kk<nArg; kk++){
   35254             const char *z = azArg[kk];
   35255             if( z[0]=='-' && z[1]=='-' ) z++;
   35256             if( cli_strcmp(z,"off")==0 ){
   35257               sqlite3_test_control(testctrl, 0);
   35258             }else if( cli_strcmp(z,"on")==0 ){
   35259               faultsim_state.iCnt = faultsim_state.nSkip;
   35260               if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
   35261               faultsim_state.nHit = 0;
   35262               sqlite3_test_control(testctrl, faultsim_callback);
   35263             }else if( cli_strcmp(z,"reset")==0 ){
   35264               faultsim_state.iCnt = faultsim_state.nSkip;
   35265               faultsim_state.nHit = 0;
   35266               sqlite3_test_control(testctrl, faultsim_callback);
   35267             }else if( cli_strcmp(z,"status")==0 ){
   35268               cli_printf(p->out, "faultsim.iId:       %d\n",
   35269                               faultsim_state.iId);
   35270               cli_printf(p->out, "faultsim.iErr:      %d\n",
   35271                               faultsim_state.iErr);
   35272               cli_printf(p->out, "faultsim.iCnt:      %d\n",
   35273                               faultsim_state.iCnt);
   35274               cli_printf(p->out, "faultsim.nHit:      %d\n",
   35275                               faultsim_state.nHit);
   35276               cli_printf(p->out, "faultsim.iInterval: %d\n",
   35277                               faultsim_state.iInterval);
   35278               cli_printf(p->out, "faultsim.eVerbose:  %d\n",
   35279                               faultsim_state.eVerbose);
   35280               cli_printf(p->out, "faultsim.nRepeat:   %d\n",
   35281                               faultsim_state.nRepeat);
   35282               cli_printf(p->out, "faultsim.nSkip:     %d\n",
   35283                               faultsim_state.nSkip);
   35284             }else if( cli_strcmp(z,"-v")==0 ){
   35285               if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
   35286             }else if( cli_strcmp(z,"-q")==0 ){
   35287               if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
   35288             }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
   35289               faultsim_state.iId = atoi(azArg[++kk]);
   35290             }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
   35291               faultsim_state.iErr = atoi(azArg[++kk]);
   35292             }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
   35293               faultsim_state.iInterval = atoi(azArg[++kk]);
   35294             }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){
   35295               faultsim_state.nRepeat = atoi(azArg[++kk]);
   35296            }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){
   35297               faultsim_state.nSkip = atoi(azArg[++kk]);
   35298             }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
   35299               bShowHelp = 1;
   35300             }else{
   35301               cli_printf(stderr,
   35302                   "Unrecognized fault_install argument: \"%s\"\n",
   35303                   azArg[kk]);
   35304               rc = 1;
   35305               bShowHelp = 1;
   35306               break;
   35307             }
   35308           }
   35309           if( bShowHelp ){
   35310             cli_puts(
   35311                "Usage: .testctrl fault_install ARGS\n"
   35312                "Possible arguments:\n"
   35313                "   off               Disable faultsim\n"
   35314                "   on                Activate faultsim\n"
   35315                "   reset             Reset the trigger counter\n"
   35316                "   status            Show current status\n"
   35317                "   -v                Increase verbosity\n"
   35318                "   -q                Decrease verbosity\n"
   35319                "   --errcode N       When triggered, return N as error code\n"
   35320                "   --id ID           Trigger only for the ID specified\n"
   35321                "   --interval N      Trigger only after every N-th call\n"
   35322                "   --repeat N        Turn off after N hits.  0 means never\n"
   35323                "   --skip N          Skip the first N encounters\n"
   35324                ,p->out
   35325             );
   35326           }
   35327           break;
   35328         }
   35329       }
   35330     }
   35331     if( isOk==0 && iCtrl>=0 ){
   35332       cli_printf(p->out,
   35333           "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
   35334       rc = 1;
   35335     }else if( isOk==1 ){
   35336       cli_printf(p->out, "%d\n", rc2);
   35337     }else if( isOk==2 ){
   35338       cli_printf(p->out, "0x%08x\n", rc2);
   35339     }
   35340   }else
   35341 #endif /* !defined(SQLITE_UNTESTABLE) */
   35342 
   35343   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
   35344     open_db(p, 0);
   35345     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
   35346   }else
   35347 
   35348   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
   35349     if( nArg==2 ){
   35350       if( cli_strcmp(azArg[1],"once")==0 ){
   35351         p->enableTimer = 1;
   35352       }else{
   35353         p->enableTimer = 2*booleanValue(azArg[1]);
   35354       }
   35355       if( p->enableTimer && !HAS_TIMER ){
   35356         eputz("Error: timer not available on this system.\n");
   35357         p->enableTimer = 0;
   35358       }
   35359     }else{
   35360       eputz("Usage: .timer on|off|once\n");
   35361       rc = 1;
   35362     }
   35363   }else
   35364 
   35365 #ifndef SQLITE_OMIT_TRACE
   35366   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
   35367     int mType = 0;
   35368     int jj;
   35369     open_db(p, 0);
   35370     for(jj=1; jj<nArg; jj++){
   35371       const char *z = azArg[jj];
   35372       if( z[0]=='-' ){
   35373         if( optionMatch(z, "expanded") ){
   35374           p->eTraceType = SHELL_TRACE_EXPANDED;
   35375         }
   35376 #ifdef SQLITE_ENABLE_NORMALIZE
   35377         else if( optionMatch(z, "normalized") ){
   35378           p->eTraceType = SHELL_TRACE_NORMALIZED;
   35379         }
   35380 #endif
   35381         else if( optionMatch(z, "plain") ){
   35382           p->eTraceType = SHELL_TRACE_PLAIN;
   35383         }
   35384         else if( optionMatch(z, "profile") ){
   35385           mType |= SQLITE_TRACE_PROFILE;
   35386         }
   35387         else if( optionMatch(z, "row") ){
   35388           mType |= SQLITE_TRACE_ROW;
   35389         }
   35390         else if( optionMatch(z, "stmt") ){
   35391           mType |= SQLITE_TRACE_STMT;
   35392         }
   35393         else if( optionMatch(z, "close") ){
   35394           mType |= SQLITE_TRACE_CLOSE;
   35395         }
   35396         else {
   35397           cli_printf(stderr,"Unknown option \"%s\" on \".trace\"\n", z);
   35398           rc = 1;
   35399           goto meta_command_exit;
   35400         }
   35401       }else{
   35402         output_file_close(p->traceOut);
   35403         p->traceOut = output_file_open(p, z);
   35404       }
   35405     }
   35406     if( p->traceOut==0 ){
   35407       sqlite3_trace_v2(p->db, 0, 0, 0);
   35408     }else{
   35409       if( mType==0 ) mType = SQLITE_TRACE_STMT;
   35410       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
   35411     }
   35412   }else
   35413 #endif /* !defined(SQLITE_OMIT_TRACE) */
   35414 
   35415 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
   35416   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
   35417     int ii;
   35418     int lenOpt;
   35419     char *zOpt;
   35420     if( nArg<2 ){
   35421       eputz("Usage: .unmodule [--allexcept] NAME ...\n");
   35422       rc = 1;
   35423       goto meta_command_exit;
   35424     }
   35425     open_db(p, 0);
   35426     zOpt = azArg[1];
   35427     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
   35428     lenOpt = (int)strlen(zOpt);
   35429     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
   35430       assert( azArg[nArg]==0 );
   35431       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
   35432     }else{
   35433       for(ii=1; ii<nArg; ii++){
   35434         sqlite3_create_module(p->db, azArg[ii], 0, 0);
   35435       }
   35436     }
   35437   }else
   35438 #endif
   35439 
   35440   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
   35441     char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
   35442     cli_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
   35443           sqlite3_libversion(), sqlite3_sourceid());
   35444 #if SQLITE_HAVE_ZLIB
   35445     cli_printf(p->out, "zlib version %s\n", zlibVersion());
   35446 #endif
   35447 #define CTIMEOPT_VAL_(opt) #opt
   35448 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
   35449 #if defined(__clang__) && defined(__clang_major__)
   35450     cli_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
   35451           CTIMEOPT_VAL(__clang_minor__) "."
   35452           CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
   35453 #elif defined(_MSC_VER)
   35454     cli_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
   35455 #elif defined(__GNUC__) && defined(__VERSION__)
   35456     cli_printf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz);
   35457 #endif
   35458   }else
   35459 
   35460   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
   35461     const char *zDbName = nArg==2 ? azArg[1] : "main";
   35462     sqlite3_vfs *pVfs = 0;
   35463     if( p->db ){
   35464       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
   35465       if( pVfs ){
   35466         cli_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
   35467         cli_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
   35468         cli_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
   35469         cli_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
   35470       }
   35471     }
   35472   }else
   35473 
   35474   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
   35475     sqlite3_vfs *pVfs;
   35476     sqlite3_vfs *pCurrent = 0;
   35477     if( p->db ){
   35478       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
   35479     }
   35480     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
   35481       cli_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
   35482             pVfs==pCurrent ? "  <--- CURRENT" : "");
   35483       cli_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
   35484       cli_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
   35485       cli_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
   35486       if( pVfs->pNext ){
   35487         cli_puts("-----------------------------------\n", p->out);
   35488       }
   35489     }
   35490   }else
   35491 
   35492   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
   35493     const char *zDbName = nArg==2 ? azArg[1] : "main";
   35494     char *zVfsName = 0;
   35495     if( p->db ){
   35496       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
   35497       if( zVfsName ){
   35498         cli_printf(p->out, "%s\n", zVfsName);
   35499         sqlite3_free(zVfsName);
   35500       }
   35501     }
   35502   }else
   35503 
   35504   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
   35505     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
   35506     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
   35507   }else
   35508 
   35509   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
   35510     int j;
   35511     p->mode.spec.nWidth = nArg-1;
   35512     p->mode.spec.aWidth = realloc(p->mode.spec.aWidth,
   35513                                   (p->mode.spec.nWidth+1)*sizeof(short int));
   35514     shell_check_oom(p->mode.spec.aWidth);
   35515     for(j=1; j<nArg; j++){
   35516       i64 w = integerValue(azArg[j]);
   35517       if( w < -QRF_MAX_WIDTH ) w = -QRF_MAX_WIDTH;
   35518       if( w > QRF_MAX_WIDTH ) w = QRF_MAX_WIDTH;
   35519       p->mode.spec.aWidth[j-1] = (short int)w;
   35520     }
   35521   }else
   35522 
   35523   {
   35524     cli_printf(stderr,"Error: unknown command or invalid arguments: "
   35525           " \"%s\". Enter \".help\" for help\n", azArg[0]);
   35526     rc = 1;
   35527   }
   35528 
   35529 meta_command_exit:
   35530   if( p->nPopOutput ){
   35531     p->nPopOutput--;
   35532     if( p->nPopOutput==0 ) output_reset(p);
   35533   }
   35534   p->bSafeMode = p->bSafeModePersist;
   35535   p->dot.nArg = 0;
   35536   return rc;
   35537 }
   35538 
   35539 /* Line scan result and intermediate states (supporting scan resumption)
   35540 */
   35541 #ifndef CHAR_BIT
   35542 # define CHAR_BIT 8
   35543 #endif
   35544 typedef enum {
   35545   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
   35546   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
   35547   QSS_Start = 0
   35548 } QuickScanState;
   35549 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
   35550 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
   35551 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
   35552 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
   35553 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
   35554 
   35555 /*
   35556 ** Scan line for classification to guide shell's handling.
   35557 ** The scan is resumable for subsequent lines when prior
   35558 ** return values are passed as the 2nd argument.
   35559 */
   35560 static QuickScanState quickscan(char *zLine, QuickScanState qss,
   35561                                 SCAN_TRACKER_REFTYPE pst){
   35562   char cin;
   35563   char cWait = (char)qss; /* intentional narrowing loss */
   35564   if( cWait==0 ){
   35565   PlainScan:
   35566     while( (cin = *zLine++)!=0 ){
   35567       if( IsSpace(cin) )
   35568         continue;
   35569       switch (cin){
   35570       case '-':
   35571         if( *zLine!='-' )
   35572           break;
   35573         while((cin = *++zLine)!=0 )
   35574           if( cin=='\n')
   35575             goto PlainScan;
   35576         return qss;
   35577       case ';':
   35578         qss |= QSS_EndingSemi;
   35579         continue;
   35580       case '/':
   35581         if( *zLine=='*' ){
   35582           ++zLine;
   35583           cWait = '*';
   35584           CONTINUE_PROMPT_AWAITS(pst, "/*");
   35585           qss = QSS_SETV(qss, cWait);
   35586           goto TermScan;
   35587         }
   35588         break;
   35589       case '[':
   35590         cin = ']';
   35591         deliberate_fall_through; /* FALLTHRU */
   35592       case '`': case '\'': case '"':
   35593         cWait = cin;
   35594         qss = QSS_HasDark | cWait;
   35595         CONTINUE_PROMPT_AWAITC(pst, cin);
   35596         goto TermScan;
   35597       case '(':
   35598         CONTINUE_PAREN_INCR(pst, 1);
   35599         break;
   35600       case ')':
   35601         CONTINUE_PAREN_INCR(pst, -1);
   35602         break;
   35603       default:
   35604         break;
   35605       }
   35606       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
   35607     }
   35608   }else{
   35609   TermScan:
   35610     while( (cin = *zLine++)!=0 ){
   35611       if( cin==cWait ){
   35612         switch( cWait ){
   35613         case '*':
   35614           if( *zLine != '/' )
   35615             continue;
   35616           ++zLine;
   35617           CONTINUE_PROMPT_AWAITC(pst, 0);
   35618           qss = QSS_SETV(qss, 0);
   35619           goto PlainScan;
   35620         case '`': case '\'': case '"':
   35621           if(*zLine==cWait){
   35622             /* Swallow doubled end-delimiter.*/
   35623             ++zLine;
   35624             continue;
   35625           }
   35626           deliberate_fall_through; /* FALLTHRU */
   35627         case ']':
   35628           CONTINUE_PROMPT_AWAITC(pst, 0);
   35629           qss = QSS_SETV(qss, 0);
   35630           goto PlainScan;
   35631         default: assert(0);
   35632         }
   35633       }
   35634     }
   35635   }
   35636   return qss;
   35637 }
   35638 
   35639 /*
   35640 ** Return TRUE if the line typed in is an SQL command terminator other
   35641 ** than a semi-colon.  The SQL Server style "go" command is understood
   35642 ** as is the Oracle "/".
   35643 */
   35644 static int line_is_command_terminator(char *zLine){
   35645   while( IsSpace(zLine[0]) ){ zLine++; };
   35646   if( zLine[0]=='/' )
   35647     zLine += 1; /* Oracle */
   35648   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
   35649     zLine += 2; /* SQL Server */
   35650   else
   35651     return 0;
   35652   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
   35653 }
   35654 
   35655 /*
   35656 ** The CLI needs a working sqlite3_complete() to work properly.  So error
   35657 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
   35658 */
   35659 #ifdef SQLITE_OMIT_COMPLETE
   35660 # error the CLI application is incompatible with SQLITE_OMIT_COMPLETE.
   35661 #endif
   35662 
   35663 /*
   35664 ** Return true if zSql is a complete SQL statement.  Return false if it
   35665 ** ends in the middle of a string literal or C-style comment.
   35666 */
   35667 static int line_is_complete(char *zSql, int nSql){
   35668   int rc;
   35669   if( zSql==0 ) return 1;
   35670   zSql[nSql] = ';';
   35671   zSql[nSql+1] = 0;
   35672   rc = sqlite3_complete(zSql);
   35673   zSql[nSql] = 0;
   35674   return rc;
   35675 }
   35676 
   35677 /*
   35678 ** This function is called after processing each line of SQL in the
   35679 ** runOneSqlLine() function. Its purpose is to detect scenarios where
   35680 ** defensive mode should be automatically turned off. Specifically, when
   35681 **
   35682 **   1. The first line of input is "PRAGMA foreign_keys=OFF;",
   35683 **   2. The second line of input is "BEGIN TRANSACTION;",
   35684 **   3. The database is empty, and
   35685 **   4. The shell is not running in --safe mode.
   35686 **
   35687 ** The implementation uses the ShellState.eRestoreState to maintain state:
   35688 **
   35689 **    0: Have not seen any SQL.
   35690 **    1: Have seen "PRAGMA foreign_keys=OFF;".
   35691 **    2-6: Currently running .dump transaction. If the "2" bit is set,
   35692 **         disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
   35693 **    7: Nothing left to do. This function becomes a no-op.
   35694 */
   35695 static int doAutoDetectRestore(ShellState *p, const char *zSql){
   35696   int rc = SQLITE_OK;
   35697 
   35698   if( p->eRestoreState<7 ){
   35699     switch( p->eRestoreState ){
   35700       case 0: {
   35701         const char *zExpect = "PRAGMA foreign_keys=OFF;";
   35702         assert( strlen(zExpect)==24 );
   35703         if( p->bSafeMode==0
   35704          && strlen(zSql)>=24
   35705          && memcmp(zSql, zExpect, 25)==0
   35706         ){
   35707           p->eRestoreState = 1;
   35708         }else{
   35709           p->eRestoreState = 7;
   35710         }
   35711         break;
   35712       };
   35713 
   35714       case 1: {
   35715         int bIsDump = 0;
   35716         const char *zExpect = "BEGIN TRANSACTION;";
   35717         assert( strlen(zExpect)==18 );
   35718         if( memcmp(zSql, zExpect, 19)==0 ){
   35719           /* Now check if the database is empty. */
   35720           const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
   35721           sqlite3_stmt *pStmt = 0;
   35722 
   35723           bIsDump = 1;
   35724           shellPrepare(p->db, &rc, zQuery, &pStmt);
   35725           if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
   35726             bIsDump = 0;
   35727           }
   35728           shellFinalize(&rc, pStmt);
   35729         }
   35730         if( bIsDump && rc==SQLITE_OK ){
   35731           int bDefense = 0;
   35732           int bDqsDdl = 0;
   35733           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
   35734           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
   35735           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
   35736           sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
   35737           p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
   35738         }else{
   35739           p->eRestoreState = 7;
   35740         }
   35741         break;
   35742       }
   35743 
   35744       default: {
   35745         if( sqlite3_get_autocommit(p->db) ){
   35746           if( (p->eRestoreState & 2) ){
   35747             sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
   35748           }
   35749           if( (p->eRestoreState & 4) ){
   35750             sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
   35751           }
   35752           p->eRestoreState = 7;
   35753         }
   35754         break;
   35755       }
   35756     }
   35757   }
   35758 
   35759   return rc;
   35760 }
   35761 
   35762 /*
   35763 ** Run a single line of SQL.  Return the number of errors.
   35764 */
   35765 static int runOneSqlLine(
   35766   ShellState *p,            /* Execution context */
   35767   char *zSql,               /* SQL to be run */
   35768   const char *zFilename,    /* Source file of the sql */
   35769   int startline             /* linenumber */
   35770 ){
   35771   int rc;
   35772   char *zErrMsg = 0;
   35773 
   35774   open_db(p, 0);
   35775   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
   35776   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
   35777   BEGIN_TIMER(p);
   35778   rc = shell_exec(p, zSql, &zErrMsg);
   35779   END_TIMER(p);
   35780   if( rc || zErrMsg ){
   35781     char zPrefix[100];
   35782     const char *zErrorTail;
   35783     const char *zErrorType;
   35784     if( zErrMsg==0 ){
   35785       zErrorType = "Error";
   35786       zErrorTail = sqlite3_errmsg(p->db);
   35787     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
   35788       zErrorType = "Parse error";
   35789       zErrorTail = &zErrMsg[12];
   35790     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
   35791       zErrorType = "Runtime error";
   35792       zErrorTail = &zErrMsg[10];
   35793     }else{
   35794       zErrorType = "Error";
   35795       zErrorTail = zErrMsg;
   35796     }
   35797     if( zFilename || !stdin_is_interactive ){
   35798       if( cli_strcmp(zFilename,"cmdline")==0 ){
   35799         sqlite3_snprintf(sizeof(zPrefix), zPrefix,
   35800                   "%s in %r command line argument:", zErrorType, startline);
   35801       }else if( cli_strcmp(zFilename,"<stdin>")==0 ){
   35802         sqlite3_snprintf(sizeof(zPrefix), zPrefix,
   35803                   "%s near line %d:", zErrorType, startline);
   35804       }else{
   35805         sqlite3_snprintf(sizeof(zPrefix), zPrefix,
   35806                   "%s near line %d of %s:", zErrorType, startline, zFilename);
   35807       }
   35808     }else{
   35809       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
   35810     }
   35811     cli_printf(stderr,"%s %s\n", zPrefix, zErrorTail);
   35812     sqlite3_free(zErrMsg);
   35813     zErrMsg = 0;
   35814     return 1;
   35815   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
   35816     char zLineBuf[2000];
   35817     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
   35818             "changes: %lld   total_changes: %lld",
   35819             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
   35820     cli_printf(p->out, "%s\n", zLineBuf);
   35821   }
   35822 
   35823   if( doAutoDetectRestore(p, zSql) ) return 1;
   35824   return 0;
   35825 }
   35826 
   35827 static void echo_group_input(ShellState *p, const char *zDo){
   35828   if( p->mode.mFlags & MFLG_ECHO ){
   35829     cli_printf(p->out, "%s\n", zDo);
   35830     fflush(p->out);
   35831   }
   35832 }
   35833 
   35834 #ifdef SQLITE_SHELL_FIDDLE
   35835 /*
   35836 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
   35837 ** impl because we need the global shellState and cannot access it from that
   35838 ** function without moving lots of code around (creating a larger/messier diff).
   35839 */
   35840 static char *one_input_line(ShellState *p, char *zPrior, int isContinuation){
   35841   /* Parse the next line from shellState.wasm.zInput. */
   35842   const char *zBegin = shellState.wasm.zPos;
   35843   const char *z = zBegin;
   35844   char *zLine = 0;
   35845   i64 nZ = 0;
   35846   FILE *in = p->in;
   35847 
   35848   UNUSED_PARAMETER(in);
   35849   UNUSED_PARAMETER(isContinuation);
   35850   if(!z || !*z){
   35851     return 0;
   35852   }
   35853   while(*z && IsSpace(*z)) ++z;
   35854   zBegin = z;
   35855   for(; *z && '\n'!=*z; ++nZ, ++z){}
   35856   if(nZ>0 && '\r'==zBegin[nZ-1]){
   35857     --nZ;
   35858   }
   35859   shellState.wasm.zPos = z;
   35860   zLine = realloc(zPrior, nZ+1);
   35861   shell_check_oom(zLine);
   35862   memcpy(zLine, zBegin, nZ);
   35863   zLine[nZ] = 0;
   35864   return zLine;
   35865 }
   35866 #endif /* SQLITE_SHELL_FIDDLE */
   35867 
   35868 /*
   35869 ** Read input from *in and process it.  If *in==0 then input
   35870 ** is interactive - the user is typing it it.  Otherwise, input
   35871 ** is coming from a file or device.  A prompt is issued and history
   35872 ** is saved only if input is interactive.  An interrupt signal will
   35873 ** cause this routine to exit immediately, unless input is interactive.
   35874 **
   35875 ** Return the number of errors.
   35876 */
   35877 static int process_input(ShellState *p, const char *zSrc){
   35878   char *zLine = 0;          /* A single input line */
   35879   char *zSql = 0;           /* Accumulated SQL text */
   35880   i64 nLine;                /* Length of current line */
   35881   i64 nSql = 0;             /* Bytes of zSql[] used */
   35882   i64 nAlloc = 0;           /* Allocated zSql[] space */
   35883   int rc;                   /* Error code */
   35884   int errCnt = 0;           /* Number of errors seen */
   35885   i64 startline = 0;        /* Line number for start of current input */
   35886   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
   35887   const char *saved_zInFile;      /* Prior value of p->zInFile */
   35888   i64 saved_lineno;               /* Prior value of p->lineno */
   35889 
   35890   if( p->inputNesting==MAX_INPUT_NESTING ){
   35891     /* This will be more informative in a later version. */
   35892     cli_printf(stderr,"%s: Input nesting limit (%d) reached at line %lld."
   35893           " Check recursion.\n", zSrc, MAX_INPUT_NESTING, p->lineno);
   35894     return 1;
   35895   }
   35896   ++p->inputNesting;
   35897   saved_zInFile = p->zInFile;
   35898   p->zInFile = zSrc;
   35899   saved_lineno = p->lineno;
   35900   p->lineno = 0;
   35901   CONTINUE_PROMPT_RESET;
   35902   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
   35903     fflush(p->out);
   35904     zLine = one_input_line(p, zLine, nSql>0);
   35905     if( zLine==0 ){
   35906       /* End of input */
   35907       if( p->in==0 && stdin_is_interactive ) cli_puts("\n", p->out);
   35908       break;
   35909     }
   35910     if( seenInterrupt ){
   35911       if( p->in!=0 ) break;
   35912       seenInterrupt = 0;
   35913     }
   35914     p->lineno++;
   35915     if( QSS_INPLAIN(qss)
   35916         && line_is_command_terminator(zLine)
   35917         && line_is_complete(zSql, nSql) ){
   35918       memcpy(zLine,";",2);
   35919     }
   35920     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
   35921     if( QSS_PLAINWHITE(qss) && nSql==0 ){
   35922       /* Just swallow single-line whitespace */
   35923       echo_group_input(p, zLine);
   35924       qss = QSS_Start;
   35925       continue;
   35926     }
   35927     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
   35928       CONTINUE_PROMPT_RESET;
   35929       echo_group_input(p, zLine);
   35930       if( zLine[0]=='.' ){
   35931         rc = do_meta_command(zLine, p);
   35932         if( rc==2 ){ /* exit requested */
   35933           break;
   35934         }else if( rc ){
   35935           errCnt++;
   35936         }
   35937       }
   35938       qss = QSS_Start;
   35939       continue;
   35940     }
   35941     /* No single-line dispositions remain; accumulate line(s). */
   35942     nLine = strlen(zLine);
   35943     if( nSql+nLine+2>=nAlloc ){
   35944       /* Grow buffer by half-again increments when big. */
   35945       nAlloc = nSql+(nSql>>1)+nLine+100;
   35946       zSql = realloc(zSql, nAlloc);
   35947       shell_check_oom(zSql);
   35948     }
   35949     if( nSql==0 ){
   35950       i64 i;
   35951       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
   35952       assert( nAlloc>0 && zSql!=0 );
   35953       memcpy(zSql, zLine+i, nLine+1-i);
   35954       startline = p->lineno;
   35955       nSql = nLine-i;
   35956     }else{
   35957       zSql[nSql++] = '\n';
   35958       memcpy(zSql+nSql, zLine, nLine+1);
   35959       nSql += nLine;
   35960     }
   35961     if( nSql>0x7fff0000 ){
   35962       char zSize[100];
   35963       sqlite3_snprintf(sizeof(zSize),zSize,"%,lld",nSql);
   35964       cli_printf(stderr, "%s:%lld: Input SQL is too big: %s bytes\n",
   35965                       zSrc, startline, zSize);
   35966       nSql = 0;
   35967       errCnt++;
   35968       break;
   35969     }else if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
   35970       echo_group_input(p, zSql);
   35971       errCnt += runOneSqlLine(p, zSql, p->zInFile, startline);
   35972       CONTINUE_PROMPT_RESET;
   35973       nSql = 0;
   35974       if( p->nPopOutput ){
   35975         output_reset(p);
   35976         p->nPopOutput = 0;
   35977       }else{
   35978         clearTempFile(p);
   35979       }
   35980       if( p->nPopMode ){
   35981         modePop(p);
   35982         p->nPopMode = 0;
   35983       }
   35984       p->bSafeMode = p->bSafeModePersist;
   35985       qss = QSS_Start;
   35986     }else if( nSql && QSS_PLAINWHITE(qss) ){
   35987       echo_group_input(p, zSql);
   35988       nSql = 0;
   35989       qss = QSS_Start;
   35990     }
   35991   }
   35992   if( nSql ){
   35993     /* This may be incomplete. Let the SQL parser deal with that. */
   35994     echo_group_input(p, zSql);
   35995     errCnt += runOneSqlLine(p, zSql, p->zInFile, startline);
   35996     CONTINUE_PROMPT_RESET;
   35997   }
   35998   free(zSql);
   35999   free(zLine);
   36000   --p->inputNesting;
   36001   p->zInFile = saved_zInFile;
   36002   p->lineno = saved_lineno;
   36003   return errCnt>0;
   36004 }
   36005 
   36006 /*
   36007 ** Return a pathname which is the user's home directory.  A
   36008 ** 0 return indicates an error of some kind.
   36009 */
   36010 static char *find_home_dir(int clearFlag){
   36011   static char *home_dir = NULL;
   36012   if( clearFlag ){
   36013     free(home_dir);
   36014     home_dir = 0;
   36015     return 0;
   36016   }
   36017   if( home_dir ) return home_dir;
   36018 
   36019 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
   36020      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
   36021   {
   36022     struct passwd *pwent;
   36023     uid_t uid = getuid();
   36024     if( (pwent=getpwuid(uid)) != NULL) {
   36025       home_dir = pwent->pw_dir;
   36026     }
   36027   }
   36028 #endif
   36029 
   36030 #if defined(_WIN32_WCE)
   36031   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
   36032    */
   36033   home_dir = "/";
   36034 #else
   36035 
   36036 #if defined(_WIN32) || defined(WIN32)
   36037   if (!home_dir) {
   36038     home_dir = getenv("USERPROFILE");
   36039   }
   36040 #endif
   36041 
   36042   if (!home_dir) {
   36043     home_dir = getenv("HOME");
   36044   }
   36045 
   36046 #if defined(_WIN32) || defined(WIN32)
   36047   if (!home_dir) {
   36048     char *zDrive, *zPath;
   36049     int n;
   36050     zDrive = getenv("HOMEDRIVE");
   36051     zPath = getenv("HOMEPATH");
   36052     if( zDrive && zPath ){
   36053       n = strlen30(zDrive) + strlen30(zPath) + 1;
   36054       home_dir = malloc( n );
   36055       if( home_dir==0 ) return 0;
   36056       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
   36057       return home_dir;
   36058     }
   36059     home_dir = "c:\\";
   36060   }
   36061 #endif
   36062 
   36063 #endif /* !_WIN32_WCE */
   36064 
   36065   if( home_dir ){
   36066     i64 n = strlen(home_dir) + 1;
   36067     char *z = malloc( n );
   36068     if( z ) memcpy(z, home_dir, n);
   36069     home_dir = z;
   36070   }
   36071 
   36072   return home_dir;
   36073 }
   36074 
   36075 /*
   36076 ** On non-Windows platforms, look for:
   36077 **
   36078 ** - ${zEnvVar}/${zBaseName}
   36079 ** - ${HOME}/${zSubdir}/${zBaseName}
   36080 **
   36081 ** $zEnvVar is intended to be the name of an XDG_... environment
   36082 ** variable, e.g. XDG_CONFIG_HOME or XDG_STATE_HOME.  If zEnvVar is
   36083 ** NULL or getenv(zEnvVar) is NULL then fall back to the second
   36084 ** option. If the selected option is not found in the filesystem,
   36085 ** return 0.
   36086 **
   36087 ** zSubdir may be NULL or empty, in which case ${HOME}/${zBaseName}
   36088 ** becomes the fallback.
   36089 **
   36090 ** Both zSubdir and zBaseName may contain subdirectory parts. zSubdir
   36091 ** will conventionally be ".config" or ".local/state", which, not
   36092 ** coincidentally, is the typical subdir of the corresponding XDG_...
   36093 ** var with the XDG var's $HOME prefix.
   36094 **
   36095 ** The returned string is obtained from sqlite3_malloc() and should be
   36096 ** sqlite3_free()'d by the caller.
   36097 */
   36098 static char *find_xdg_file(const char *zEnvVar, const char *zSubdir,
   36099                            const char *zBaseName){
   36100 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
   36101      || defined(__RTP__) || defined(_WRS_KERNEL)
   36102   return 0;
   36103 #else
   36104   char *zConfigFile = 0;
   36105   const char *zXdgDir;
   36106 
   36107   zXdgDir = zEnvVar ? getenv(zEnvVar) : 0;
   36108   if( zXdgDir ){
   36109     zConfigFile = sqlite3_mprintf("%s/%s", zXdgDir, zBaseName);
   36110   }else{
   36111     const char * zHome = find_home_dir(0);
   36112     if( zHome==0 ) return 0;
   36113     zConfigFile = (zSubdir && *zSubdir)
   36114       ? sqlite3_mprintf("%s/%s/%s", zHome, zSubdir, zBaseName)
   36115       : sqlite3_mprintf("%s/%s", zHome, zBaseName);
   36116   }
   36117   shell_check_oom(zConfigFile);
   36118   if( access(zConfigFile,0)!=0 ){
   36119     sqlite3_free(zConfigFile);
   36120     zConfigFile = 0;
   36121   }
   36122   return zConfigFile;
   36123 #endif
   36124 }
   36125 
   36126 /*
   36127 ** Read input from the file sqliterc_override.  If that parameter is
   36128 ** NULL, take it from find_xdg_file(), if found, or fall back to
   36129 ** ~/.sqliterc.
   36130 **
   36131 ** Failure to read the config is only considered a failure if
   36132 ** sqliterc_override is not NULL, in which case this function may emit
   36133 ** a warning or, if ::bail_on_error is true, fail fatally if the file
   36134 ** named by sqliterc_override is not found.
   36135 */
   36136 static void process_sqliterc(
   36137   ShellState *p,                  /* Configuration data */
   36138   const char *sqliterc_override   /* Name of config file. NULL to use default */
   36139 ){
   36140   char *home_dir = NULL;
   36141   char *sqliterc = (char*)sqliterc_override;
   36142   FILE *inSaved = p->in;
   36143   i64 savedLineno = p->lineno;
   36144 
   36145   if( sqliterc == NULL ){
   36146     sqliterc = find_xdg_file("XDG_CONFIG_HOME",
   36147                              ".config",
   36148                              "sqlite3/sqliterc");
   36149   }
   36150   if( sqliterc == NULL ){
   36151     home_dir = find_home_dir(0);
   36152     if( home_dir==0 ){
   36153       eputz("-- warning: cannot find home directory;"
   36154             " cannot read ~/.sqliterc\n");
   36155       return;
   36156     }
   36157     sqliterc = sqlite3_mprintf("%s/.sqliterc",home_dir);
   36158     shell_check_oom(sqliterc);
   36159   }
   36160   p->in = sqliterc ? sqlite3_fopen(sqliterc,"rb") : 0;
   36161   if( p->in ){
   36162     if( stdin_is_interactive ){
   36163       cli_printf(stderr,"-- Loading resources from %s\n", sqliterc);
   36164     }
   36165     if( process_input(p, sqliterc) && bail_on_error ) cli_exit(1);
   36166     fclose(p->in);
   36167   }else if( sqliterc_override!=0 ){
   36168     cli_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
   36169     if( bail_on_error ) cli_exit(1);
   36170   }
   36171   p->in = inSaved;
   36172   p->lineno = savedLineno;
   36173   if( sqliterc != sqliterc_override ){
   36174     sqlite3_free(sqliterc);
   36175   }
   36176 }
   36177 
   36178 /*
   36179 ** Show available command line options
   36180 */
   36181 static const char zOptions[] =
   36182   "   --                   treat no subsequent arguments as options\n"
   36183 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
   36184   "   -A ARGS...           run \".archive ARGS\" and exit\n"
   36185 #endif
   36186   "   -append              append the database to the end of the file\n"
   36187   "   -ascii               set output mode to 'ascii'\n"
   36188   "   -bail                stop after hitting an error\n"
   36189   "   -batch               force batch I/O\n"
   36190   "   -box                 set output mode to 'box'\n"
   36191   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
   36192   "   -column              set output mode to 'column'\n"
   36193   "   -csv                 set output mode to 'csv'\n"
   36194 #if !defined(SQLITE_OMIT_DESERIALIZE)
   36195   "   -deserialize         open the database using sqlite3_deserialize()\n"
   36196 #endif
   36197   "   -echo                print inputs before execution\n"
   36198   "   -escape T            ctrl-char escape; T is one of: symbol, ascii, off\n"
   36199   "   -init FILENAME       read/process named file\n"
   36200   "   -[no]header          turn headers on or off\n"
   36201 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   36202   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
   36203 #endif
   36204   "   -help                show this message\n"
   36205   "   -html                set output mode to HTML\n"
   36206   "   -ifexists            only open if database already exists\n"
   36207   "   -interactive         force interactive I/O\n"
   36208   "   -json                set output mode to 'json'\n"
   36209   "   -line                set output mode to 'line'\n"
   36210   "   -list                set output mode to 'list'\n"
   36211   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
   36212   "   -markdown            set output mode to 'markdown'\n"
   36213 #if !defined(SQLITE_OMIT_DESERIALIZE)
   36214   "   -maxsize N           maximum size for a --deserialize database\n"
   36215 #endif
   36216   "   -memtrace            trace all memory allocations and deallocations\n"
   36217   "   -mmap N              default mmap size set to N\n"
   36218 #ifdef SQLITE_ENABLE_MULTIPLEX
   36219   "   -multiplex           enable the multiplexor VFS\n"
   36220 #endif
   36221   "   -newline SEP         set output row separator. Default: '\\n'\n"
   36222   "   -nofollow            refuse to open symbolic links to database files\n"
   36223   "   -noinit              Do not read the ~/.sqliterc file at startup\n"
   36224   "   -nonce STRING        set the safe-mode escape nonce\n"
   36225   "   -no-rowid-in-view    Disable rowid-in-view using sqlite3_config()\n"
   36226   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
   36227   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
   36228   "   -pcachetrace         trace all page cache operations\n"
   36229   "   -quote               set output mode to 'quote'\n"
   36230   "   -readonly            open the database read-only\n"
   36231   "   -safe                enable safe-mode\n"
   36232   "   -screenwidth N       use N as the default screenwidth \n"
   36233   "   -separator SEP       set output column separator. Default: '|'\n"
   36234 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
   36235   "   -sorterref SIZE      sorter references threshold size\n"
   36236 #endif
   36237   "   -stats               print memory stats before each finalize\n"
   36238   "   -table               set output mode to 'table'\n"
   36239   "   -tabs                set output mode to 'tabs'\n"
   36240   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
   36241   "   -version             show SQLite version\n"
   36242   "   -vfs NAME            use NAME as the default VFS\n"
   36243   "   -vfstrace            enable tracing of all VFS calls\n"
   36244 #ifdef SQLITE_HAVE_ZLIB
   36245   "   -zip                 open the file as a ZIP Archive\n"
   36246 #endif
   36247 ;
   36248 static void usage(int showDetail){
   36249   cli_printf(stderr,"Usage: %s [OPTIONS] [FILENAME [SQL...]]\n"
   36250        "FILENAME is the name of an SQLite database. A new database is created\n"
   36251        "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
   36252   if( showDetail ){
   36253     cli_printf(stderr,"OPTIONS include:\n%s", zOptions);
   36254   }else{
   36255     eputz("Use the -help option for additional information\n");
   36256   }
   36257   exit(0);
   36258 }
   36259 
   36260 /*
   36261 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
   36262 ** error message if it is initialized.
   36263 */
   36264 static void verify_uninitialized(void){
   36265   if( sqlite3_config(-1)==SQLITE_MISUSE ){
   36266     sputz(stdout, "WARNING: attempt to configure SQLite after"
   36267           " initialization.\n");
   36268   }
   36269 }
   36270 
   36271 /*
   36272 ** Initialize the state information in data
   36273 */
   36274 static void main_init(ShellState *p) {
   36275   memset(p, 0, sizeof(*p));
   36276   p->pAuxDb = &p->aAuxDb[0];
   36277   p->shellFlgs = SHFLG_Lookaside;
   36278   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, p);
   36279 #if !defined(SQLITE_SHELL_FIDDLE)
   36280   verify_uninitialized();
   36281 #endif
   36282   sqlite3_config(SQLITE_CONFIG_URI, 1);
   36283   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
   36284   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
   36285   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
   36286 }
   36287 
   36288 /*
   36289 ** Output text to the console in a font that attracts extra attention.
   36290 */
   36291 #if defined(_WIN32) || defined(WIN32)
   36292 static void printBold(const char *zText){
   36293   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
   36294   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
   36295   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
   36296   SetConsoleTextAttribute(out,
   36297          FOREGROUND_RED|FOREGROUND_INTENSITY
   36298   );
   36299   sputz(stdout, zText);
   36300   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
   36301 }
   36302 #else
   36303 static void printBold(const char *zText){
   36304   cli_printf(stdout, "\033[1m%s\033[0m", zText);
   36305 }
   36306 #endif
   36307 
   36308 /*
   36309 ** Get the argument to an --option.  Throw an error and die if no argument
   36310 ** is available.
   36311 */
   36312 static char *cmdline_option_value(int argc, char **argv, int i){
   36313   if( i==argc ){
   36314     cli_printf(stderr,
   36315             "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
   36316     cli_exit(1);
   36317   }
   36318   return argv[i];
   36319 }
   36320 
   36321 static void sayAbnormalExit(void){
   36322   if( seenInterrupt ) eputz("Program interrupted.\n");
   36323 }
   36324 
   36325 /* Routine to output from vfstrace
   36326 */
   36327 static int vfstraceOut(const char *z, void *pArg){
   36328   ShellState *p = (ShellState*)pArg;
   36329   cli_puts(z, p->out);
   36330   fflush(p->out);
   36331   return 1;
   36332 }
   36333 
   36334 #if defined(SQLITE_DEBUG) && !defined(SQLITE_SHELL_FIDDLE)
   36335 /* Ensure that sqlite3_reset_auto_extension() clears auto-extension
   36336 ** memory. https://sqlite.org/forum/forumpost/310cb231b07c80d1.
   36337 ** Testing this: if we (inadvertently) remove the
   36338 ** sqlite3_reset_auto_extension() call from main(), most shell tests
   36339 ** will fail because of a leak message in their output. */
   36340 static int auto_ext_leak_tester(
   36341   sqlite3 *db,
   36342   char **pzErrMsg,
   36343   const struct sqlite3_api_routines *pThunk
   36344 ){
   36345   (void)db; (void)pzErrMsg; (void)pThunk;
   36346   return SQLITE_OK;
   36347 }
   36348 #endif
   36349 
   36350 /* Alternative name to the entry point for Fiddle */
   36351 #ifdef SQLITE_SHELL_FIDDLE
   36352 #  define main fiddle_main
   36353 #endif
   36354 
   36355 /* Use the wmain() entry point on Windows.  Translate arguments to
   36356 ** UTF8, then invoke the traditional main() entry point which is
   36357 ** renamed using a #define to utf8_main() .
   36358 */
   36359 #if defined(_WIN32) && !defined(__MINGW32__) && !defined(main)
   36360 #  define main utf8_main                 /* Rename entry point to utf_main() */
   36361 int SQLITE_CDECL utf8_main(int,char**);  /* Forward declaration */
   36362 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
   36363   int rc, i;
   36364   char **argv = malloc( sizeof(char*) * (argc+1) );
   36365   char **orig = argv;
   36366   if( argv==0 ){
   36367     fprintf(stderr, "malloc failed\n");
   36368     exit(1);
   36369   }
   36370   for(i=0; i<argc; i++){
   36371     int nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, 0, 0, 0, 0);
   36372     if( nByte==0 ){
   36373       argv[i] = 0;
   36374     }else{
   36375       argv[i] = malloc( nByte );
   36376       if( argv[i]==0 ){
   36377         fprintf(stderr, "malloc failed\n");
   36378         exit(1);
   36379       }
   36380       nByte = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i],nByte,0,0);
   36381       if( nByte==0 ){
   36382         free(argv[i]);
   36383         argv[i] = 0;
   36384       }
   36385     }
   36386   }
   36387   argv[argc] = 0;
   36388   rc = utf8_main(argc, argv);
   36389   for(i=0; i<argc; i++) free(orig[i]);
   36390   free(argv);
   36391   return rc;
   36392 }
   36393 #endif /* WIN32 */
   36394 
   36395 /*
   36396 ** This is the main entry point for the process.  Everything starts here.
   36397 **
   36398 ** The "main" identifier may have been #defined to something else:
   36399 **
   36400 **     utf8_main            On Windows
   36401 **     fiddle_main          In Fiddle
   36402 **     sqlite3_shell        Other projects that use shell.c as a subroutine
   36403 */
   36404 int SQLITE_CDECL main(int argc, char **argv){
   36405 #ifdef SQLITE_DEBUG
   36406   sqlite3_int64 mem_main_enter = 0;
   36407 #endif
   36408 #ifdef SQLITE_SHELL_FIDDLE
   36409 #  define data shellState
   36410 #else
   36411   ShellState data;
   36412 #endif
   36413   const char *zInitFile = 0;
   36414   int i;
   36415   int rc = 0;
   36416   int warnInmemoryDb = 0;
   36417   int readStdin = 1;
   36418   int noInit = 0;                 /* Do not read ~/.sqliterc if true */
   36419   int nCmd = 0;
   36420   int nOptsEnd = argc;
   36421   int bEnableVfstrace = 0;
   36422   char **azCmd = 0;
   36423   int *aiCmd = 0;
   36424   const char *zVfs = 0;           /* Value of -vfs command-line option */
   36425   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
   36426 
   36427 #ifdef SQLITE_SHELL_FIDDLE
   36428   stdin_is_interactive = 0;
   36429   stdout_is_console = 1;
   36430   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
   36431 #else
   36432   stdin_is_interactive = isatty(0);
   36433   stdout_is_console = isatty(1);
   36434 #endif
   36435   atexit(sayAbnormalExit);
   36436 #ifdef SQLITE_DEBUG
   36437   mem_main_enter = sqlite3_memory_used();
   36438 #endif
   36439 #if !defined(_WIN32_WCE)
   36440   if( getenv("SQLITE_DEBUG_BREAK") ){
   36441     if( isatty(0) && isatty(2) ){
   36442       char zLine[100];
   36443       cli_printf(stderr,
   36444             "attach debugger to process %d and press ENTER to continue...",
   36445             GETPID());
   36446       if( sqlite3_fgets(zLine, sizeof(zLine), stdin)!=0
   36447        && cli_strcmp(zLine,"stop")==0
   36448       ){
   36449         exit(1);
   36450       }
   36451     }else{
   36452 #if defined(_WIN32) || defined(WIN32)
   36453       DebugBreak();
   36454 #elif defined(SIGTRAP)
   36455       raise(SIGTRAP);
   36456 #endif
   36457     }
   36458   }
   36459 #endif
   36460   /* Register a valid signal handler early, before much else is done. */
   36461 #ifdef SIGINT
   36462   signal(SIGINT, interrupt_handler);
   36463 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
   36464   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
   36465     eputz("No ^C handler.\n");
   36466   }
   36467 #endif
   36468 
   36469 #if USE_SYSTEM_SQLITE+0!=1
   36470   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
   36471     cli_printf(stderr,
   36472           "SQLite header and source version mismatch\n%s\n%s\n",
   36473           sqlite3_sourceid(), SQLITE_SOURCE_ID);
   36474     exit(1);
   36475   }
   36476 #endif
   36477   main_init(&data);
   36478 
   36479   assert( argc>=1 && argv && argv[0] );
   36480   Argv0 = argv[0];
   36481 
   36482 #ifdef SQLITE_SHELL_DBNAME_PROC
   36483   {
   36484     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
   36485     ** of a C-function that will provide the name of the database file.  Use
   36486     ** this compile-time option to embed this shell program in larger
   36487     ** applications. */
   36488     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
   36489     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
   36490     warnInmemoryDb = 0;
   36491   }
   36492 #endif
   36493 
   36494   /* Do an initial pass through the command-line arguments to locate
   36495   ** the name of the database file, the name of the initialization file,
   36496   ** the size of the alternative malloc heap, options affecting commands
   36497   ** or SQL run from the command line, and the first command to execute.
   36498   */
   36499 #ifndef SQLITE_SHELL_FIDDLE
   36500   verify_uninitialized();
   36501 #endif
   36502   for(i=1; i<argc; i++){
   36503     char *z;
   36504     z = argv[i];
   36505     if( z[0]!='-' || i>nOptsEnd ){
   36506       if( data.aAuxDb->zDbFilename==0 && !isScriptFile(z,1) ){
   36507         data.aAuxDb->zDbFilename = z;
   36508       }else{
   36509         /* Excess arguments are interpreted as SQL (or dot-commands) and
   36510         ** mean that nothing is read from stdin */
   36511         readStdin = 0;
   36512         stdin_is_interactive = 0;
   36513         nCmd++;
   36514         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
   36515         shell_check_oom(azCmd);
   36516         aiCmd = realloc(aiCmd, sizeof(aiCmd[0])*nCmd);
   36517         shell_check_oom(azCmd);
   36518         azCmd[nCmd-1] = z;
   36519         aiCmd[nCmd-1] = i;
   36520       }
   36521       continue;
   36522     }
   36523     if( z[1]=='-' ) z++;
   36524     if( cli_strcmp(z, "-")==0 ){
   36525       nOptsEnd = i;
   36526       continue;
   36527     }else if( cli_strcmp(z,"-separator")==0
   36528      || cli_strcmp(z,"-nullvalue")==0
   36529      || cli_strcmp(z,"-newline")==0
   36530      || cli_strcmp(z,"-cmd")==0
   36531     ){
   36532       (void)cmdline_option_value(argc, argv, ++i);
   36533     }else if( cli_strcmp(z,"-init")==0 ){
   36534       zInitFile = cmdline_option_value(argc, argv, ++i);
   36535     }else if( cli_strcmp(z,"-interactive")==0 ){
   36536     }else if( cli_strcmp(z,"-batch")==0 ){
   36537       /* Need to check for batch mode here to so we can avoid printing
   36538       ** informational messages (like from process_sqliterc) before
   36539       ** we do the actual processing of arguments later in a second pass.
   36540       */
   36541       stdin_is_interactive = 0;
   36542       stdout_is_console = 0;
   36543       modeChange(&data, MODE_BATCH);
   36544     }else if( cli_strcmp(z,"-screenwidth")==0 ){
   36545       int n = atoi(cmdline_option_value(argc, argv, ++i));
   36546       if( n<2 ){
   36547         sqlite3_fprintf(stderr,"minimum --screenwidth is 2\n");
   36548         exit(1);
   36549       }
   36550       stdout_tty_width = n;
   36551     }else if( cli_strcmp(z,"-utf8")==0 ){
   36552     }else if( cli_strcmp(z,"-no-utf8")==0 ){
   36553     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
   36554       int val = 0;
   36555       sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
   36556       assert( val==0 );
   36557     }else if( cli_strcmp(z,"-heap")==0 ){
   36558 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   36559       const char *zSize;
   36560       sqlite3_int64 szHeap;
   36561 
   36562       zSize = cmdline_option_value(argc, argv, ++i);
   36563       szHeap = integerValue(zSize);
   36564       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
   36565       verify_uninitialized();
   36566       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
   36567 #else
   36568       (void)cmdline_option_value(argc, argv, ++i);
   36569 #endif
   36570     }else if( cli_strcmp(z,"-pagecache")==0 ){
   36571       sqlite3_int64 n, sz;
   36572       sz = integerValue(cmdline_option_value(argc,argv,++i));
   36573       if( sz>65536 ) sz = 65536;
   36574       if( sz<0 ) sz = 0;
   36575       n = integerValue(cmdline_option_value(argc,argv,++i));
   36576       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
   36577         n = 0xffffffffffffLL/sz;
   36578       }
   36579       if( sz>0 && (sz & (sz-1))==0 ){
   36580         /* If SIZE is a power of two, round it up by the PCACHE_HDRSZ */
   36581         int szHdr = 0;
   36582         sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &szHdr);
   36583         sz += szHdr;
   36584         cli_printf(stdout, "Page cache size increased to %d to accommodate"
   36585                         " the %d-byte headers\n", (int)sz, szHdr);
   36586       }
   36587       verify_uninitialized();
   36588       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
   36589                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
   36590       data.shellFlgs |= SHFLG_Pagecache;
   36591     }else if( cli_strcmp(z,"-lookaside")==0 ){
   36592       int n, sz;
   36593       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
   36594       if( sz<0 ) sz = 0;
   36595       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
   36596       if( n<0 ) n = 0;
   36597       verify_uninitialized();
   36598       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
   36599       if( (i64)sz*(i64)n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
   36600     }else if( cli_strcmp(z,"-threadsafe")==0 ){
   36601       int n;
   36602       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
   36603       verify_uninitialized();
   36604       switch( n ){
   36605          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
   36606          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
   36607          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
   36608       }
   36609     }else if( cli_strcmp(z,"-vfstrace")==0 ){
   36610       bEnableVfstrace = 1;
   36611 #ifdef SQLITE_ENABLE_MULTIPLEX
   36612     }else if( cli_strcmp(z,"-multiplex")==0 ){
   36613       extern int sqlite3_multiplex_initialize(const char*,int);
   36614       sqlite3_multiplex_initialize(0, 1);
   36615 #endif
   36616     }else if( cli_strcmp(z,"-mmap")==0 ){
   36617       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
   36618       verify_uninitialized();
   36619       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
   36620 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
   36621     }else if( cli_strcmp(z,"-sorterref")==0 ){
   36622       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
   36623       verify_uninitialized();
   36624       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
   36625 #endif
   36626     }else if( cli_strcmp(z,"-vfs")==0 ){
   36627       zVfs = cmdline_option_value(argc, argv, ++i);
   36628 #ifdef SQLITE_HAVE_ZLIB
   36629     }else if( cli_strcmp(z,"-zip")==0 ){
   36630       data.openMode = SHELL_OPEN_ZIPFILE;
   36631 #endif
   36632     }else if( cli_strcmp(z,"-append")==0 ){
   36633       data.openMode = SHELL_OPEN_APPENDVFS;
   36634 #ifndef SQLITE_OMIT_DESERIALIZE
   36635     }else if( cli_strcmp(z,"-deserialize")==0 ){
   36636       data.openMode = SHELL_OPEN_DESERIALIZE;
   36637     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
   36638       data.szMax = integerValue(argv[++i]);
   36639 #endif
   36640     }else if( cli_strcmp(z,"-readonly")==0 ){
   36641       data.openFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   36642       data.openFlags |= SQLITE_OPEN_READONLY;
   36643     }else if( cli_strcmp(z,"-nofollow")==0 ){
   36644       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
   36645     }else if( cli_strcmp(z,"-noinit")==0 ){
   36646       noInit = 1;
   36647     }else if( cli_strcmp(z,"-exclusive")==0 ){  /* UNDOCUMENTED */
   36648       data.openFlags |= SQLITE_OPEN_EXCLUSIVE;
   36649     }else if( cli_strcmp(z,"-ifexists")==0 ){
   36650       data.openFlags &= ~(SQLITE_OPEN_CREATE);
   36651       if( data.openFlags==0 ) data.openFlags = SQLITE_OPEN_READWRITE;
   36652 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
   36653     }else if( cli_strncmp(z, "-A",2)==0 ){
   36654       /* All remaining command-line arguments are passed to the ".archive"
   36655       ** command, so ignore them */
   36656       break;
   36657 #endif
   36658     }else if( cli_strcmp(z, "-memtrace")==0 ){
   36659       sqlite3MemTraceActivate(stderr);
   36660     }else if( cli_strcmp(z, "-pcachetrace")==0 ){
   36661       sqlite3PcacheTraceActivate(stderr);
   36662     }else if( cli_strcmp(z,"-bail")==0 ){
   36663       bail_on_error = 1;
   36664     }else if( cli_strcmp(z,"-nonce")==0 ){
   36665       free(data.zNonce);
   36666       data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
   36667     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
   36668       ShellSetFlag(&data,SHFLG_TestingMode);
   36669     }else if( cli_strcmp(z,"-safe")==0 ){
   36670       /* no-op - catch this on the second pass */
   36671     }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
   36672       /* skip over the argument */
   36673       i++;
   36674     }else if( cli_strcmp(z,"-test-argv")==0 ){
   36675       /* Undocumented test option.  Print the values in argv[] and exit.
   36676       ** Use this to verify that any translation of the argv[], for example
   36677       ** on Windows that receives wargv[] from the OS and must convert
   36678       ** to UTF8 prior to calling this routine. */
   36679       int kk;
   36680       for(kk=0; kk<argc; kk++){
   36681         sqlite3_fprintf(stdout,"argv[%d] = \"%s\"\n", kk, argv[kk]);
   36682       }
   36683       return 0;
   36684     }
   36685   }
   36686 #ifndef SQLITE_SHELL_FIDDLE
   36687   if( !bEnableVfstrace ) verify_uninitialized();
   36688 #endif
   36689 
   36690 
   36691 #ifdef SQLITE_SHELL_INIT_PROC
   36692   {
   36693     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
   36694     ** of a C-function that will perform initialization actions on SQLite that
   36695     ** occur just before or after sqlite3_initialize(). Use this compile-time
   36696     ** option to embed this shell program in larger applications. */
   36697     extern void SQLITE_SHELL_INIT_PROC(void);
   36698     SQLITE_SHELL_INIT_PROC();
   36699   }
   36700 #else
   36701   /* All the sqlite3_config() calls have now been made. So it is safe
   36702   ** to call sqlite3_initialize() and process any command line -vfs option. */
   36703   sqlite3_initialize();
   36704 #endif
   36705 
   36706   if( zVfs ){
   36707     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
   36708     if( pVfs ){
   36709       sqlite3_vfs_register(pVfs, 1);
   36710     }
   36711 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
   36712     else if( access(zVfs,0)==0 ){
   36713       /* If the VFS name is not the name of an existing VFS, but it is
   36714       ** the name of a file, then try to load that file as an extension.
   36715       ** Presumably the extension implements the desired VFS. */
   36716       sqlite3 *db = 0;
   36717       char *zErr = 0;
   36718       sqlite3_open(":memory:", &db);
   36719       sqlite3_enable_load_extension(db, 1);
   36720       rc = sqlite3_load_extension(db, zVfs, 0, &zErr);
   36721       sqlite3_close(db);
   36722       if( (rc&0xff)!=SQLITE_OK ){
   36723         cli_printf(stderr, "could not load extension VFS \"%s\": %s\n",
   36724                    zVfs, zErr);
   36725         exit(1);
   36726       }
   36727     }
   36728 #endif
   36729     else{
   36730       cli_printf(stderr,"no such VFS: \"%s\"\n", zVfs);
   36731       exit(1);
   36732     }
   36733   }
   36734 
   36735   if( data.pAuxDb->zDbFilename==0 ){
   36736 #ifndef SQLITE_OMIT_MEMORYDB
   36737     data.pAuxDb->zDbFilename = ":memory:";
   36738     warnInmemoryDb = argc==1;
   36739 #else
   36740     cli_printf(stderr,
   36741                     "%s: Error: no database filename specified\n", Argv0);
   36742     rc = 1;
   36743     goto shell_main_exit;
   36744 #endif
   36745   }
   36746   data.out = stdout;
   36747   if( bEnableVfstrace ){
   36748     vfstrace_register("trace",0,vfstraceOut, &data, 1);
   36749   }
   36750 #ifndef SQLITE_SHELL_FIDDLE
   36751   sqlite3_appendvfs_init(0,0,0);
   36752 #ifdef SQLITE_DEBUG
   36753   sqlite3_auto_extension( (void (*)())auto_ext_leak_tester );
   36754 #endif
   36755 #endif
   36756   modeDefault(&data);
   36757 
   36758   /* Go ahead and open the database file if it already exists.  If the
   36759   ** file does not exist, delay opening it.  This prevents empty database
   36760   ** files from being created if a user mistypes the database name argument
   36761   ** to the sqlite command-line tool.
   36762   */
   36763   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
   36764     open_db(&data, 0);
   36765   }
   36766 
   36767   /* Process the initialization file if there is one.  If no -init option
   36768   ** is given on the command line, look for a file named ~/.sqliterc and
   36769   ** try to process it.
   36770   */
   36771   if( !noInit ) process_sqliterc(&data,zInitFile);
   36772 
   36773   /* Make a second pass through the command-line arguments and set
   36774   ** options.  This second pass is delayed until after the initialization
   36775   ** file is processed so that the command-line arguments will override
   36776   ** settings in the initialization file.
   36777   */
   36778   for(i=1; i<argc; i++){
   36779     char *z = argv[i];
   36780     if( z[0]!='-' || i>=nOptsEnd ) continue;
   36781     if( z[1]=='-' ){ z++; }
   36782     if( cli_strcmp(z,"-init")==0 ){
   36783       i++;
   36784     }else if( cli_strcmp(z,"-html")==0 ){
   36785       modeChange(&data, MODE_Html);
   36786     }else if( cli_strcmp(z,"-list")==0 ){
   36787       modeChange(&data, MODE_List);
   36788     }else if( cli_strcmp(z,"-quote")==0 ){
   36789       modeChange(&data, MODE_Quote);
   36790     }else if( cli_strcmp(z,"-line")==0 ){
   36791       modeChange(&data, MODE_Line);
   36792     }else if( cli_strcmp(z,"-column")==0 ){
   36793       modeChange(&data, MODE_Column);
   36794     }else if( cli_strcmp(z,"-json")==0 ){
   36795       modeChange(&data, MODE_Json);
   36796     }else if( cli_strcmp(z,"-markdown")==0 ){
   36797       modeChange(&data, MODE_Markdown);
   36798     }else if( cli_strcmp(z,"-table")==0 ){
   36799       modeChange(&data, MODE_Table);
   36800     }else if( cli_strcmp(z,"-psql")==0 ){
   36801       modeChange(&data, MODE_Psql);
   36802     }else if( cli_strcmp(z,"-box")==0 ){
   36803       modeChange(&data, MODE_Box);
   36804     }else if( cli_strcmp(z,"-csv")==0 ){
   36805       modeChange(&data, MODE_Csv);
   36806     }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
   36807       /* See similar code at tag-20250224-1 */
   36808       const char *zEsc = argv[++i];
   36809       int k;
   36810       for(k=0; k<ArraySize(qrfEscNames); k++){
   36811         if( sqlite3_stricmp(zEsc,qrfEscNames[k])==0 ){
   36812           data.mode.spec.eEsc = k;
   36813           break;
   36814         }
   36815       }
   36816       if( k>=ArraySize(qrfEscNames) ){
   36817         cli_printf(stderr, "unknown control character escape mode \"%s\""
   36818                                 " - choices:", zEsc);
   36819         for(k=0; k<ArraySize(qrfEscNames); k++){
   36820           cli_printf(stderr, " %s", qrfEscNames[k]);
   36821         }
   36822         cli_printf(stderr, "\n");
   36823         exit(1);
   36824       }
   36825 #ifdef SQLITE_HAVE_ZLIB
   36826     }else if( cli_strcmp(z,"-zip")==0 ){
   36827       data.openMode = SHELL_OPEN_ZIPFILE;
   36828 #endif
   36829     }else if( cli_strcmp(z,"-append")==0 ){
   36830       data.openMode = SHELL_OPEN_APPENDVFS;
   36831 #ifndef SQLITE_OMIT_DESERIALIZE
   36832     }else if( cli_strcmp(z,"-deserialize")==0 ){
   36833       data.openMode = SHELL_OPEN_DESERIALIZE;
   36834     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
   36835       data.szMax = integerValue(argv[++i]);
   36836 #endif
   36837     }else if( cli_strcmp(z,"-readonly")==0 ){
   36838       data.openFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   36839       data.openFlags |= SQLITE_OPEN_READONLY;
   36840     }else if( cli_strcmp(z,"-nofollow")==0 ){
   36841       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
   36842     }else if( cli_strcmp(z,"-noinit")==0 ){
   36843       /* No-op */
   36844     }else if( cli_strcmp(z,"-exclusive")==0 ){  /* UNDOCUMENTED */
   36845       data.openFlags |= SQLITE_OPEN_EXCLUSIVE;
   36846     }else if( cli_strcmp(z,"-ifexists")==0 ){
   36847       data.openFlags &= ~(SQLITE_OPEN_CREATE);
   36848       if( data.openFlags==0 ) data.openFlags = SQLITE_OPEN_READWRITE;
   36849     }else if( cli_strcmp(z,"-ascii")==0 ){
   36850       modeChange(&data, MODE_Ascii);
   36851     }else if( cli_strcmp(z,"-tabs")==0 ){
   36852       modeChange(&data, MODE_Tabs);
   36853     }else if( cli_strcmp(z,"-separator")==0 ){
   36854       modeSetStr(&data.mode.spec.zColumnSep,
   36855                        cmdline_option_value(argc,argv,++i));
   36856     }else if( cli_strcmp(z,"-newline")==0 ){
   36857       modeSetStr(&data.mode.spec.zRowSep,
   36858                        cmdline_option_value(argc,argv,++i));
   36859     }else if( cli_strcmp(z,"-nullvalue")==0 ){
   36860      modeSetStr(&data.mode.spec.zNull,
   36861                        cmdline_option_value(argc,argv,++i));
   36862     }else if( cli_strcmp(z,"-header")==0 ){
   36863       data.mode.spec.bTitles = QRF_Yes;
   36864      }else if( cli_strcmp(z,"-noheader")==0 ){
   36865       data.mode.spec.bTitles = QRF_No;
   36866     }else if( cli_strcmp(z,"-echo")==0 ){
   36867       data.mode.mFlags |= MFLG_ECHO;
   36868     }else if( cli_strcmp(z,"-eqp")==0 ){
   36869       data.mode.autoEQP = AUTOEQP_on;
   36870     }else if( cli_strcmp(z,"-eqpfull")==0 ){
   36871       data.mode.autoEQP = AUTOEQP_full;
   36872     }else if( cli_strcmp(z,"-stats")==0 ){
   36873       data.statsOn = 1;
   36874     }else if( cli_strcmp(z,"-scanstats")==0 ){
   36875       data.mode.scanstatsOn = 1;
   36876     }else if( cli_strcmp(z,"-backslash")==0 ){
   36877       /* Undocumented command-line option: -backslash
   36878       ** Causes C-style backslash escapes to be evaluated in SQL statements
   36879       ** prior to sending the SQL into SQLite.  Useful for injecting
   36880       ** crazy bytes in the middle of SQL statements for testing and debugging.
   36881       */
   36882       ShellSetFlag(&data, SHFLG_Backslash);
   36883     }else if( cli_strcmp(z,"-bail")==0 ){
   36884       /* No-op.  The bail_on_error flag should already be set. */
   36885     }else if( cli_strcmp(z,"-version")==0 ){
   36886       cli_printf(stdout, "%s %s (%d-bit)\n",
   36887             sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
   36888       rc = 0;
   36889       goto shell_main_exit;
   36890     }else if( cli_strcmp(z,"-interactive")==0 ){
   36891       /* Need to check for interactive override here to so that it can
   36892       ** affect console setup (for Windows only) and testing thereof.
   36893       */
   36894       stdin_is_interactive = 1;
   36895     }else if( cli_strcmp(z,"-batch")==0 ){
   36896       /* already handled */
   36897     }else if( cli_strcmp(z,"-screenwidth")==0 ){
   36898       i++;
   36899     }else if( cli_strcmp(z,"-utf8")==0 ){
   36900       /* already handled */
   36901     }else if( cli_strcmp(z,"-no-utf8")==0 ){
   36902       /* already handled */
   36903     }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
   36904       /* already handled */
   36905     }else if( cli_strcmp(z,"-heap")==0 ){
   36906       i++;
   36907     }else if( cli_strcmp(z,"-pagecache")==0 ){
   36908       i+=2;
   36909     }else if( cli_strcmp(z,"-lookaside")==0 ){
   36910       i+=2;
   36911     }else if( cli_strcmp(z,"-threadsafe")==0 ){
   36912       i+=2;
   36913     }else if( cli_strcmp(z,"-nonce")==0 ){
   36914       i += 2;
   36915     }else if( cli_strcmp(z,"-mmap")==0 ){
   36916       i++;
   36917     }else if( cli_strcmp(z,"-memtrace")==0 ){
   36918       i++;
   36919     }else if( cli_strcmp(z,"-pcachetrace")==0 ){
   36920       i++;
   36921 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
   36922     }else if( cli_strcmp(z,"-sorterref")==0 ){
   36923       i++;
   36924 #endif
   36925     }else if( cli_strcmp(z,"-vfs")==0 ){
   36926       i++;
   36927     }else if( cli_strcmp(z,"-vfstrace")==0 ){
   36928       i++;
   36929 #ifdef SQLITE_ENABLE_MULTIPLEX
   36930     }else if( cli_strcmp(z,"-multiplex")==0 ){
   36931       i++;
   36932 #endif
   36933     }else if( cli_strcmp(z,"-help")==0 ){
   36934       usage(1);
   36935     }else if( cli_strcmp(z,"-cmd")==0 ){
   36936       /* Run commands that follow -cmd first and separately from commands
   36937       ** that simply appear on the command-line.  This seems goofy.  It would
   36938       ** be better if all commands ran in the order that they appear.  But
   36939       ** we retain the goofy behavior for historical compatibility. */
   36940       if( i==argc-1 ) break;
   36941       z = cmdline_option_value(argc,argv,++i);
   36942       if( z[0]=='.' ){
   36943         rc = do_meta_command(z, &data);
   36944         if( rc && (bail_on_error || rc==2) ){
   36945           if( rc==2 ) rc = 0;
   36946           goto shell_main_exit;
   36947         }
   36948       }else{
   36949         rc = runOneSqlLine(&data, z, "cmdline", i);
   36950         if( bail_on_error ) goto shell_main_exit;
   36951       }
   36952 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
   36953     }else if( cli_strncmp(z, "-A", 2)==0 ){
   36954       if( nCmd>0 ){
   36955         cli_printf(stderr,"Error: cannot mix regular SQL or dot-commands"
   36956               " with \"%s\"\n", z);
   36957         rc = 1;
   36958         goto shell_main_exit;
   36959       }
   36960       open_db(&data, OPEN_DB_ZIPFILE);
   36961       if( z[2] ){
   36962         argv[i] = &z[2];
   36963         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
   36964       }else{
   36965         arDotCommand(&data, 1, argv+i, argc-i);
   36966       }
   36967       readStdin = 0;
   36968       stdin_is_interactive = 0;
   36969       break;
   36970 #endif
   36971     }else if( cli_strcmp(z,"-safe")==0 ){
   36972       data.bSafeMode = data.bSafeModePersist = 1;
   36973     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
   36974       /* Acted upon in first pass. */
   36975     }else{
   36976       cli_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
   36977       eputz("Use -help for a list of options.\n");
   36978       rc = 1;
   36979       goto shell_main_exit;
   36980     }
   36981   }
   36982 
   36983   if( !readStdin ){
   36984     /* Run all arguments that do not begin with '-' as if they were separate
   36985     ** command-line inputs, except for the argToSkip argument which contains
   36986     ** the database filename.
   36987     */
   36988     for(i=0; i<nCmd; i++){
   36989       echo_group_input(&data, azCmd[i]);
   36990       if( isScriptFile(azCmd[i],0) ){
   36991         FILE *inSaved = data.in;
   36992         i64 savedLineno = data.lineno;
   36993         int res = 1;
   36994         if( (data.in = openChrSource(azCmd[i]))!=0 ){
   36995           res = process_input(&data, azCmd[i]);
   36996           fclose(data.in);
   36997         }
   36998         data.in = inSaved;
   36999         data.lineno = savedLineno;
   37000         if( res ) i = nCmd;
   37001       }else if( azCmd[i][0]=='.' ){
   37002         char *zErrCtx = malloc( 64 );
   37003         shell_check_oom(zErrCtx);
   37004         sqlite3_snprintf(64,zErrCtx,"argv[%i]:",aiCmd[i]);
   37005         data.zInFile = "<cmdline>";
   37006         data.zErrPrefix = zErrCtx;
   37007         rc = do_meta_command(azCmd[i], &data);
   37008         free(data.zErrPrefix);
   37009         data.zErrPrefix = 0;
   37010         if( rc ){
   37011           if( rc==2 ) rc = 0;
   37012           goto shell_main_exit;
   37013         }
   37014       }else{
   37015         rc = runOneSqlLine(&data, azCmd[i], "cmdline", aiCmd[i]);
   37016         if( data.nPopMode ){
   37017           modePop(&data);
   37018           data.nPopMode = 0;
   37019         }
   37020       }
   37021       if( data.nPopOutput && azCmd[i][0]!='.' ){
   37022         output_reset(&data);
   37023         data.nPopOutput = 0;
   37024       }else{
   37025         clearTempFile(&data);
   37026       }
   37027     }
   37028   }else{
   37029     /* Run commands received from standard input
   37030     */
   37031     if( stdin_is_interactive ){
   37032       char *zHome;
   37033       char *zHistory;
   37034       cli_printf(stdout,
   37035             "SQLite version %s %.19s\n" /*extra-version-info*/
   37036             "Enter \".help\" for usage hints.\n",
   37037             sqlite3_libversion(), sqlite3_sourceid());
   37038       if( warnInmemoryDb ){
   37039         sputz(stdout, "Connected to a ");
   37040         printBold("transient in-memory database");
   37041         sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
   37042               " persistent database.\n");
   37043       }
   37044       zHistory = getenv("SQLITE_HISTORY");
   37045       if( zHistory ){
   37046         zHistory = sqlite3_mprintf("%s", zHistory);
   37047         shell_check_oom(zHistory);
   37048       }else{
   37049         zHistory = find_xdg_file("XDG_STATE_HOME",
   37050                                  ".local/state",
   37051                                  "sqlite_history");
   37052         if( 0==zHistory && (zHome = find_home_dir(0))!=0 ){
   37053           zHistory = sqlite3_mprintf("%s/.sqlite_history", zHome);
   37054           shell_check_oom(zHistory);
   37055         }
   37056       }
   37057       if( zHistory ){ shell_read_history(zHistory); }
   37058 #if (HAVE_READLINE || HAVE_EDITLINE) && !defined(SQLITE_OMIT_READLINE_COMPLETION)
   37059       rl_attempted_completion_function = readline_completion;
   37060 #elif HAVE_LINENOISE==1
   37061       linenoiseSetCompletionCallback(linenoise_completion);
   37062 #elif HAVE_LINENOISE==2
   37063       linenoiseSetCompletionCallback(linenoise_completion, NULL);
   37064 #endif
   37065       data.in = 0;
   37066       rc = process_input(&data, "<stdin>");
   37067       if( zHistory ){
   37068         shell_stifle_history(2000);
   37069         shell_write_history(zHistory);
   37070         sqlite3_free(zHistory);
   37071       }
   37072     }else{
   37073       data.in = stdin;
   37074       rc = process_input(&data, "<stdin>");
   37075     }
   37076   }
   37077 #ifndef SQLITE_SHELL_FIDDLE
   37078   /* In WASM mode we have to leave the db state in place so that
   37079   ** client code can "push" SQL into it after this call returns. */
   37080 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_AUTHORIZATION)
   37081   if( data.expert.pExpert ){
   37082     expertFinish(&data, 1, 0);
   37083   }
   37084 #endif
   37085  shell_main_exit:
   37086   free(azCmd);
   37087   free(aiCmd);
   37088   set_table_name(&data, 0);
   37089   if( data.db ){
   37090     session_close_all(&data, -1);
   37091     close_db(data.db);
   37092   }
   37093   for(i=0; i<ArraySize(data.aAuxDb); i++){
   37094     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
   37095     if( data.aAuxDb[i].db ){
   37096       session_close_all(&data, i);
   37097       close_db(data.aAuxDb[i].db);
   37098     }
   37099   }
   37100   find_home_dir(1);
   37101   output_reset(&data);
   37102   data.doXdgOpen = 0;
   37103   clearTempFile(&data);
   37104   modeFree(&data.mode);
   37105   if( data.nSavedModes ){
   37106     int ii;
   37107     for(ii=0; ii<data.nSavedModes; ii++){
   37108       modeFree(&data.aSavedModes[ii].mode);
   37109       free(data.aSavedModes[ii].zTag);
   37110     }
   37111     free(data.aSavedModes);
   37112   }
   37113   free(data.zErrPrefix);
   37114   free(data.zNonce);
   37115   free(data.dot.zCopy);
   37116   free(data.dot.azArg);
   37117   free(data.dot.aiOfst);
   37118   free(data.dot.abQuot);
   37119   if( data.nTestRun ){
   37120     sqlite3_fprintf(stdout, "%d test%s run with %d error%s\n",
   37121        data.nTestRun, data.nTestRun==1 ? "" : "s",
   37122        data.nTestErr, data.nTestErr==1 ? "" : "s");
   37123     fflush(stdout);
   37124     rc = data.nTestErr>0;
   37125   }
   37126   /* Clear the global data structure so that valgrind will detect memory
   37127   ** leaks */
   37128   memset(&data, 0, sizeof(data));
   37129   if( bEnableVfstrace ){
   37130     vfstrace_unregister("trace");
   37131   }
   37132   sqlite3_reset_auto_extension();
   37133 #ifdef SQLITE_DEBUG
   37134   if( sqlite3_memory_used()>mem_main_enter ){
   37135     cli_printf(stderr,"Memory leaked: %u bytes\n",
   37136           (unsigned int)(sqlite3_memory_used()-mem_main_enter));
   37137   }
   37138 #endif
   37139 #else /* SQLITE_SHELL_FIDDLE... */
   37140   shell_main_exit:
   37141 #endif
   37142   return rc;
   37143 }
   37144 
   37145 
   37146 #ifdef SQLITE_SHELL_FIDDLE
   37147 /* Only for emcc experimentation purposes. */
   37148 int fiddle_experiment(int a,int b){
   37149   return a + b;
   37150 }
   37151 
   37152 /*
   37153 ** Returns a pointer to the current DB handle.
   37154 */
   37155 sqlite3 * fiddle_db_handle(){
   37156   return globalDb;
   37157 }
   37158 
   37159 /*
   37160 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
   37161 ** "main" is assumed. Returns 0 if no db with the given name is
   37162 ** open.
   37163 */
   37164 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
   37165   sqlite3_vfs * pVfs = 0;
   37166   if(globalDb){
   37167     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
   37168                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
   37169   }
   37170   return pVfs;
   37171 }
   37172 
   37173 /* Only for emcc experimentation purposes. */
   37174 sqlite3 * fiddle_db_arg(sqlite3 *arg){
   37175     cli_printf(stdout, "fiddle_db_arg(%p)\n", (const void*)arg);
   37176     return arg;
   37177 }
   37178 
   37179 /*
   37180 ** Intended to be called via a SharedWorker() while a separate
   37181 ** SharedWorker() (which manages the wasm module) is performing work
   37182 ** which should be interrupted. Unfortunately, SharedWorker is not
   37183 ** portable enough to make real use of.
   37184 */
   37185 void fiddle_interrupt(void){
   37186   if( globalDb ) sqlite3_interrupt(globalDb);
   37187 }
   37188 
   37189 /*
   37190 ** Returns the filename of the given db name, assuming "main" if
   37191 ** zDbName is NULL. Returns NULL if globalDb is not opened.
   37192 */
   37193 const char * fiddle_db_filename(const char * zDbName){
   37194     return globalDb
   37195       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
   37196       : NULL;
   37197 }
   37198 
   37199 /*
   37200 ** Completely wipes out the contents of the currently-opened database
   37201 ** but leaves its storage intact for reuse. If any transactions are
   37202 ** active, they are forcibly rolled back.
   37203 */
   37204 void fiddle_reset_db(void){
   37205   if( globalDb ){
   37206     int rc;
   37207     while( sqlite3_txn_state(globalDb,0)>0 ){
   37208       /*
   37209       ** Resolve problem reported in
   37210       ** https://sqlite.org/forum/forumpost/0b41a25d65
   37211       */
   37212       cli_puts("Rolling back in-progress transaction.\n", stdout);
   37213       sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
   37214     }
   37215     rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
   37216     if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
   37217     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
   37218   }
   37219 }
   37220 
   37221 /*
   37222 ** Uses the current database's VFS xRead to stream the db file's
   37223 ** contents out to the given callback. The callback gets a single
   37224 ** chunk of size n (its 2nd argument) on each call and must return 0
   37225 ** on success, non-0 on error. This function returns 0 on success,
   37226 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
   37227 ** code from the callback. Note that this is not thread-friendly: it
   37228 ** expects that it will be the only thread reading the db file and
   37229 ** takes no measures to ensure that is the case.
   37230 */
   37231 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
   37232   sqlite3_int64 nSize = 0;
   37233   sqlite3_int64 nPos = 0;
   37234   sqlite3_file * pFile = 0;
   37235   unsigned char buf[1024 * 8];
   37236   int nBuf = (int)sizeof(buf);
   37237   int rc = shellState.db
   37238     ? sqlite3_file_control(shellState.db, "main",
   37239                            SQLITE_FCNTL_FILE_POINTER, &pFile)
   37240     : SQLITE_NOTFOUND;
   37241   if( rc ) return rc;
   37242   rc = pFile->pMethods->xFileSize(pFile, &nSize);
   37243   if( rc ) return rc;
   37244   if(nSize % nBuf){
   37245     /* DB size is not an even multiple of the buffer size. Reduce
   37246     ** buffer size so that we do not unduly inflate the db size when
   37247     ** exporting. */
   37248     if(0 == nSize % 4096) nBuf = 4096;
   37249     else if(0 == nSize % 2048) nBuf = 2048;
   37250     else if(0 == nSize % 1024) nBuf = 1024;
   37251     else nBuf = 512;
   37252   }
   37253   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
   37254     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
   37255     if(SQLITE_IOERR_SHORT_READ == rc){
   37256       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
   37257     }
   37258     if( 0==rc ) rc = xCallback(buf, nBuf);
   37259   }
   37260   return rc;
   37261 }
   37262 
   37263 /*
   37264 ** Trivial exportable function for emscripten. It processes zSql as if
   37265 ** it were input to the sqlite3 shell and redirects all output to the
   37266 ** wasm binding. fiddle_main() must have been called before this
   37267 ** is called, or results are undefined.
   37268 */
   37269 void fiddle_exec(const char * zSql){
   37270   if(zSql && *zSql){
   37271     if('.'==*zSql) puts(zSql);
   37272     shellState.wasm.zInput = zSql;
   37273     shellState.wasm.zPos = zSql;
   37274     process_input(&shellState, "<stdin>");
   37275     shellState.wasm.zInput = shellState.wasm.zPos = 0;
   37276   }
   37277 }
   37278 #endif /* SQLITE_SHELL_FIDDLE */
   37279 /************************* End src/shell.c.in ******************/
   37280