xref: /freebsd/contrib/sqlite3/shell.c (revision d4eeb02986980bf33dd56c41ceb9fc5f180c0d47)
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 
38 /*
39 ** Optionally #include a user-defined header, whereby compilation options
40 ** may be set prior to where they take effect, but after platform setup.
41 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
42 ** file. Note that this macro has a like effect on sqlite3.c compilation.
43 */
44 # define SHELL_STRINGIFY_(f) #f
45 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
46 #ifdef SQLITE_CUSTOM_INCLUDE
47 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
48 #endif
49 
50 /*
51 ** Determine if we are dealing with WinRT, which provides only a subset of
52 ** the full Win32 API.
53 */
54 #if !defined(SQLITE_OS_WINRT)
55 # define SQLITE_OS_WINRT 0
56 #endif
57 
58 /*
59 ** Warning pragmas copied from msvc.h in the core.
60 */
61 #if defined(_MSC_VER)
62 #pragma warning(disable : 4054)
63 #pragma warning(disable : 4055)
64 #pragma warning(disable : 4100)
65 #pragma warning(disable : 4127)
66 #pragma warning(disable : 4130)
67 #pragma warning(disable : 4152)
68 #pragma warning(disable : 4189)
69 #pragma warning(disable : 4206)
70 #pragma warning(disable : 4210)
71 #pragma warning(disable : 4232)
72 #pragma warning(disable : 4244)
73 #pragma warning(disable : 4305)
74 #pragma warning(disable : 4306)
75 #pragma warning(disable : 4702)
76 #pragma warning(disable : 4706)
77 #endif /* defined(_MSC_VER) */
78 
79 /*
80 ** No support for loadable extensions in VxWorks.
81 */
82 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
83 # define SQLITE_OMIT_LOAD_EXTENSION 1
84 #endif
85 
86 /*
87 ** Enable large-file support for fopen() and friends on unix.
88 */
89 #ifndef SQLITE_DISABLE_LFS
90 # define _LARGE_FILE       1
91 # ifndef _FILE_OFFSET_BITS
92 #   define _FILE_OFFSET_BITS 64
93 # endif
94 # define _LARGEFILE_SOURCE 1
95 #endif
96 
97 #include <stdlib.h>
98 #include <string.h>
99 #include <stdio.h>
100 #include <assert.h>
101 #include "sqlite3.h"
102 typedef sqlite3_int64 i64;
103 typedef sqlite3_uint64 u64;
104 typedef unsigned char u8;
105 #if SQLITE_USER_AUTHENTICATION
106 # include "sqlite3userauth.h"
107 #endif
108 #include <ctype.h>
109 #include <stdarg.h>
110 
111 #if !defined(_WIN32) && !defined(WIN32)
112 # include <signal.h>
113 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
114 #  include <pwd.h>
115 # endif
116 #endif
117 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
118 # include <unistd.h>
119 # include <dirent.h>
120 # define GETPID getpid
121 # if defined(__MINGW32__)
122 #  define DIRENT dirent
123 #  ifndef S_ISLNK
124 #   define S_ISLNK(mode) (0)
125 #  endif
126 # endif
127 #else
128 # define GETPID (int)GetCurrentProcessId
129 #endif
130 #include <sys/types.h>
131 #include <sys/stat.h>
132 
133 #if HAVE_READLINE
134 # include <readline/readline.h>
135 # include <readline/history.h>
136 #endif
137 
138 #if HAVE_EDITLINE
139 # include <editline/readline.h>
140 #endif
141 
142 #if HAVE_EDITLINE || HAVE_READLINE
143 
144 # define shell_add_history(X) add_history(X)
145 # define shell_read_history(X) read_history(X)
146 # define shell_write_history(X) write_history(X)
147 # define shell_stifle_history(X) stifle_history(X)
148 # define shell_readline(X) readline(X)
149 
150 #elif HAVE_LINENOISE
151 
152 # include "linenoise.h"
153 # define shell_add_history(X) linenoiseHistoryAdd(X)
154 # define shell_read_history(X) linenoiseHistoryLoad(X)
155 # define shell_write_history(X) linenoiseHistorySave(X)
156 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
157 # define shell_readline(X) linenoise(X)
158 
159 #else
160 
161 # define shell_read_history(X)
162 # define shell_write_history(X)
163 # define shell_stifle_history(X)
164 
165 # define SHELL_USE_LOCAL_GETLINE 1
166 #endif
167 
168 
169 #if defined(_WIN32) || defined(WIN32)
170 # if SQLITE_OS_WINRT
171 #  define SQLITE_OMIT_POPEN 1
172 # else
173 #  include <io.h>
174 #  include <fcntl.h>
175 #  define isatty(h) _isatty(h)
176 #  ifndef access
177 #   define access(f,m) _access((f),(m))
178 #  endif
179 #  ifndef unlink
180 #   define unlink _unlink
181 #  endif
182 #  ifndef strdup
183 #   define strdup _strdup
184 #  endif
185 #  undef popen
186 #  define popen _popen
187 #  undef pclose
188 #  define pclose _pclose
189 # endif
190 #else
191  /* Make sure isatty() has a prototype. */
192  extern int isatty(int);
193 
194 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
195   /* popen and pclose are not C89 functions and so are
196   ** sometimes omitted from the <stdio.h> header */
197    extern FILE *popen(const char*,const char*);
198    extern int pclose(FILE*);
199 # else
200 #  define SQLITE_OMIT_POPEN 1
201 # endif
202 #endif
203 
204 #if defined(_WIN32_WCE)
205 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
206  * thus we always assume that we have a console. That can be
207  * overridden with the -batch command line option.
208  */
209 #define isatty(x) 1
210 #endif
211 
212 /* ctype macros that work with signed characters */
213 #define IsSpace(X)  isspace((unsigned char)X)
214 #define IsDigit(X)  isdigit((unsigned char)X)
215 #define ToLower(X)  (char)tolower((unsigned char)X)
216 
217 #if defined(_WIN32) || defined(WIN32)
218 #if SQLITE_OS_WINRT
219 #include <intrin.h>
220 #endif
221 #include <windows.h>
222 
223 /* string conversion routines only needed on Win32 */
224 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
225 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
226 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
227 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
228 #endif
229 
230 /* On Windows, we normally run with output mode of TEXT so that \n characters
231 ** are automatically translated into \r\n.  However, this behavior needs
232 ** to be disabled in some cases (ex: when generating CSV output and when
233 ** rendering quoted strings that contain \n characters).  The following
234 ** routines take care of that.
235 */
236 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
237 static void setBinaryMode(FILE *file, int isOutput){
238   if( isOutput ) fflush(file);
239   _setmode(_fileno(file), _O_BINARY);
240 }
241 static void setTextMode(FILE *file, int isOutput){
242   if( isOutput ) fflush(file);
243   _setmode(_fileno(file), _O_TEXT);
244 }
245 #else
246 # define setBinaryMode(X,Y)
247 # define setTextMode(X,Y)
248 #endif
249 
250 /*
251 ** When compiling with emcc (a.k.a. emscripten), we're building a
252 ** WebAssembly (WASM) bundle and need to disable and rewire a few
253 ** things.
254 */
255 #ifdef __EMSCRIPTEN__
256 #define SQLITE_SHELL_WASM_MODE
257 #else
258 #undef SQLITE_SHELL_WASM_MODE
259 #endif
260 
261 /* True if the timer is enabled */
262 static int enableTimer = 0;
263 
264 /* Return the current wall-clock time */
265 static sqlite3_int64 timeOfDay(void){
266   static sqlite3_vfs *clockVfs = 0;
267   sqlite3_int64 t;
268   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
269   if( clockVfs==0 ) return 0;  /* Never actually happens */
270   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
271     clockVfs->xCurrentTimeInt64(clockVfs, &t);
272   }else{
273     double r;
274     clockVfs->xCurrentTime(clockVfs, &r);
275     t = (sqlite3_int64)(r*86400000.0);
276   }
277   return t;
278 }
279 
280 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
281 #include <sys/time.h>
282 #include <sys/resource.h>
283 
284 /* VxWorks does not support getrusage() as far as we can determine */
285 #if defined(_WRS_KERNEL) || defined(__RTP__)
286 struct rusage {
287   struct timeval ru_utime; /* user CPU time used */
288   struct timeval ru_stime; /* system CPU time used */
289 };
290 #define getrusage(A,B) memset(B,0,sizeof(*B))
291 #endif
292 
293 /* Saved resource information for the beginning of an operation */
294 static struct rusage sBegin;  /* CPU time at start */
295 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
296 
297 /*
298 ** Begin timing an operation
299 */
300 static void beginTimer(void){
301   if( enableTimer ){
302     getrusage(RUSAGE_SELF, &sBegin);
303     iBegin = timeOfDay();
304   }
305 }
306 
307 /* Return the difference of two time_structs in seconds */
308 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
309   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
310          (double)(pEnd->tv_sec - pStart->tv_sec);
311 }
312 
313 /*
314 ** Print the timing results.
315 */
316 static void endTimer(void){
317   if( enableTimer ){
318     sqlite3_int64 iEnd = timeOfDay();
319     struct rusage sEnd;
320     getrusage(RUSAGE_SELF, &sEnd);
321     printf("Run Time: real %.3f user %f sys %f\n",
322        (iEnd - iBegin)*0.001,
323        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
324        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
325   }
326 }
327 
328 #define BEGIN_TIMER beginTimer()
329 #define END_TIMER endTimer()
330 #define HAS_TIMER 1
331 
332 #elif (defined(_WIN32) || defined(WIN32))
333 
334 /* Saved resource information for the beginning of an operation */
335 static HANDLE hProcess;
336 static FILETIME ftKernelBegin;
337 static FILETIME ftUserBegin;
338 static sqlite3_int64 ftWallBegin;
339 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
340                                     LPFILETIME, LPFILETIME);
341 static GETPROCTIMES getProcessTimesAddr = NULL;
342 
343 /*
344 ** Check to see if we have timer support.  Return 1 if necessary
345 ** support found (or found previously).
346 */
347 static int hasTimer(void){
348   if( getProcessTimesAddr ){
349     return 1;
350   } else {
351 #if !SQLITE_OS_WINRT
352     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
353     ** versions. See if the version we are running on has it, and if it
354     ** does, save off a pointer to it and the current process handle.
355     */
356     hProcess = GetCurrentProcess();
357     if( hProcess ){
358       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
359       if( NULL != hinstLib ){
360         getProcessTimesAddr =
361             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
362         if( NULL != getProcessTimesAddr ){
363           return 1;
364         }
365         FreeLibrary(hinstLib);
366       }
367     }
368 #endif
369   }
370   return 0;
371 }
372 
373 /*
374 ** Begin timing an operation
375 */
376 static void beginTimer(void){
377   if( enableTimer && getProcessTimesAddr ){
378     FILETIME ftCreation, ftExit;
379     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
380                         &ftKernelBegin,&ftUserBegin);
381     ftWallBegin = timeOfDay();
382   }
383 }
384 
385 /* Return the difference of two FILETIME structs in seconds */
386 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
387   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
388   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
389   return (double) ((i64End - i64Start) / 10000000.0);
390 }
391 
392 /*
393 ** Print the timing results.
394 */
395 static void endTimer(void){
396   if( enableTimer && getProcessTimesAddr){
397     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
398     sqlite3_int64 ftWallEnd = timeOfDay();
399     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
400     printf("Run Time: real %.3f user %f sys %f\n",
401        (ftWallEnd - ftWallBegin)*0.001,
402        timeDiff(&ftUserBegin, &ftUserEnd),
403        timeDiff(&ftKernelBegin, &ftKernelEnd));
404   }
405 }
406 
407 #define BEGIN_TIMER beginTimer()
408 #define END_TIMER endTimer()
409 #define HAS_TIMER hasTimer()
410 
411 #else
412 #define BEGIN_TIMER
413 #define END_TIMER
414 #define HAS_TIMER 0
415 #endif
416 
417 /*
418 ** Used to prevent warnings about unused parameters
419 */
420 #define UNUSED_PARAMETER(x) (void)(x)
421 
422 /*
423 ** Number of elements in an array
424 */
425 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
426 
427 /*
428 ** If the following flag is set, then command execution stops
429 ** at an error if we are not interactive.
430 */
431 static int bail_on_error = 0;
432 
433 /*
434 ** Threat stdin as an interactive input if the following variable
435 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
436 */
437 static int stdin_is_interactive = 1;
438 
439 /*
440 ** On Windows systems we have to know if standard output is a console
441 ** in order to translate UTF-8 into MBCS.  The following variable is
442 ** true if translation is required.
443 */
444 static int stdout_is_console = 1;
445 
446 /*
447 ** The following is the open SQLite database.  We make a pointer
448 ** to this database a static variable so that it can be accessed
449 ** by the SIGINT handler to interrupt database processing.
450 */
451 static sqlite3 *globalDb = 0;
452 
453 /*
454 ** True if an interrupt (Control-C) has been received.
455 */
456 static volatile int seenInterrupt = 0;
457 
458 /*
459 ** This is the name of our program. It is set in main(), used
460 ** in a number of other places, mostly for error messages.
461 */
462 static char *Argv0;
463 
464 /*
465 ** Prompt strings. Initialized in main. Settable with
466 **   .prompt main continue
467 */
468 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
469 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
470 
471 /*
472 ** Render output like fprintf().  Except, if the output is going to the
473 ** console and if this is running on a Windows machine, translate the
474 ** output from UTF-8 into MBCS.
475 */
476 #if defined(_WIN32) || defined(WIN32)
477 void utf8_printf(FILE *out, const char *zFormat, ...){
478   va_list ap;
479   va_start(ap, zFormat);
480   if( stdout_is_console && (out==stdout || out==stderr) ){
481     char *z1 = sqlite3_vmprintf(zFormat, ap);
482     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
483     sqlite3_free(z1);
484     fputs(z2, out);
485     sqlite3_free(z2);
486   }else{
487     vfprintf(out, zFormat, ap);
488   }
489   va_end(ap);
490 }
491 #elif !defined(utf8_printf)
492 # define utf8_printf fprintf
493 #endif
494 
495 /*
496 ** Render output like fprintf().  This should not be used on anything that
497 ** includes string formatting (e.g. "%s").
498 */
499 #if !defined(raw_printf)
500 # define raw_printf fprintf
501 #endif
502 
503 /* Indicate out-of-memory and exit. */
504 static void shell_out_of_memory(void){
505   raw_printf(stderr,"Error: out of memory\n");
506   exit(1);
507 }
508 
509 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
510 ** out-of-memory error.
511 */
512 static void shell_check_oom(void *p){
513   if( p==0 ) shell_out_of_memory();
514 }
515 
516 /*
517 ** Write I/O traces to the following stream.
518 */
519 #ifdef SQLITE_ENABLE_IOTRACE
520 static FILE *iotrace = 0;
521 #endif
522 
523 /*
524 ** This routine works like printf in that its first argument is a
525 ** format string and subsequent arguments are values to be substituted
526 ** in place of % fields.  The result of formatting this string
527 ** is written to iotrace.
528 */
529 #ifdef SQLITE_ENABLE_IOTRACE
530 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
531   va_list ap;
532   char *z;
533   if( iotrace==0 ) return;
534   va_start(ap, zFormat);
535   z = sqlite3_vmprintf(zFormat, ap);
536   va_end(ap);
537   utf8_printf(iotrace, "%s", z);
538   sqlite3_free(z);
539 }
540 #endif
541 
542 /*
543 ** Output string zUtf to stream pOut as w characters.  If w is negative,
544 ** then right-justify the text.  W is the width in UTF-8 characters, not
545 ** in bytes.  This is different from the %*.*s specification in printf
546 ** since with %*.*s the width is measured in bytes, not characters.
547 */
548 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
549   int i;
550   int n;
551   int aw = w<0 ? -w : w;
552   for(i=n=0; zUtf[i]; i++){
553     if( (zUtf[i]&0xc0)!=0x80 ){
554       n++;
555       if( n==aw ){
556         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
557         break;
558       }
559     }
560   }
561   if( n>=aw ){
562     utf8_printf(pOut, "%.*s", i, zUtf);
563   }else if( w<0 ){
564     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
565   }else{
566     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
567   }
568 }
569 
570 
571 /*
572 ** Determines if a string is a number of not.
573 */
574 static int isNumber(const char *z, int *realnum){
575   if( *z=='-' || *z=='+' ) z++;
576   if( !IsDigit(*z) ){
577     return 0;
578   }
579   z++;
580   if( realnum ) *realnum = 0;
581   while( IsDigit(*z) ){ z++; }
582   if( *z=='.' ){
583     z++;
584     if( !IsDigit(*z) ) return 0;
585     while( IsDigit(*z) ){ z++; }
586     if( realnum ) *realnum = 1;
587   }
588   if( *z=='e' || *z=='E' ){
589     z++;
590     if( *z=='+' || *z=='-' ) z++;
591     if( !IsDigit(*z) ) return 0;
592     while( IsDigit(*z) ){ z++; }
593     if( realnum ) *realnum = 1;
594   }
595   return *z==0;
596 }
597 
598 /*
599 ** Compute a string length that is limited to what can be stored in
600 ** lower 30 bits of a 32-bit signed integer.
601 */
602 static int strlen30(const char *z){
603   const char *z2 = z;
604   while( *z2 ){ z2++; }
605   return 0x3fffffff & (int)(z2 - z);
606 }
607 
608 /*
609 ** Return the length of a string in characters.  Multibyte UTF8 characters
610 ** count as a single character.
611 */
612 static int strlenChar(const char *z){
613   int n = 0;
614   while( *z ){
615     if( (0xc0&*(z++))!=0x80 ) n++;
616   }
617   return n;
618 }
619 
620 /*
621 ** Return open FILE * if zFile exists, can be opened for read
622 ** and is an ordinary file or a character stream source.
623 ** Otherwise return 0.
624 */
625 static FILE * openChrSource(const char *zFile){
626 #ifdef _WIN32
627   struct _stat x = {0};
628 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
629   /* On Windows, open first, then check the stream nature. This order
630   ** is necessary because _stat() and sibs, when checking a named pipe,
631   ** effectively break the pipe as its supplier sees it. */
632   FILE *rv = fopen(zFile, "rb");
633   if( rv==0 ) return 0;
634   if( _fstat(_fileno(rv), &x) != 0
635       || !STAT_CHR_SRC(x.st_mode)){
636     fclose(rv);
637     rv = 0;
638   }
639   return rv;
640 #else
641   struct stat x = {0};
642   int rc = stat(zFile, &x);
643 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
644   if( rc!=0 ) return 0;
645   if( STAT_CHR_SRC(x.st_mode) ){
646     return fopen(zFile, "rb");
647   }else{
648     return 0;
649   }
650 #endif
651 #undef STAT_CHR_SRC
652 }
653 
654 /*
655 ** This routine reads a line of text from FILE in, stores
656 ** the text in memory obtained from malloc() and returns a pointer
657 ** to the text.  NULL is returned at end of file, or if malloc()
658 ** fails.
659 **
660 ** If zLine is not NULL then it is a malloced buffer returned from
661 ** a previous call to this routine that may be reused.
662 */
663 static char *local_getline(char *zLine, FILE *in){
664   int nLine = zLine==0 ? 0 : 100;
665   int n = 0;
666 
667   while( 1 ){
668     if( n+100>nLine ){
669       nLine = nLine*2 + 100;
670       zLine = realloc(zLine, nLine);
671       shell_check_oom(zLine);
672     }
673     if( fgets(&zLine[n], nLine - n, in)==0 ){
674       if( n==0 ){
675         free(zLine);
676         return 0;
677       }
678       zLine[n] = 0;
679       break;
680     }
681     while( zLine[n] ) n++;
682     if( n>0 && zLine[n-1]=='\n' ){
683       n--;
684       if( n>0 && zLine[n-1]=='\r' ) n--;
685       zLine[n] = 0;
686       break;
687     }
688   }
689 #if defined(_WIN32) || defined(WIN32)
690   /* For interactive input on Windows systems, translate the
691   ** multi-byte characterset characters into UTF-8. */
692   if( stdin_is_interactive && in==stdin ){
693     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
694     if( zTrans ){
695       int nTrans = strlen30(zTrans)+1;
696       if( nTrans>nLine ){
697         zLine = realloc(zLine, nTrans);
698         shell_check_oom(zLine);
699       }
700       memcpy(zLine, zTrans, nTrans);
701       sqlite3_free(zTrans);
702     }
703   }
704 #endif /* defined(_WIN32) || defined(WIN32) */
705   return zLine;
706 }
707 
708 /*
709 ** Retrieve a single line of input text.
710 **
711 ** If in==0 then read from standard input and prompt before each line.
712 ** If isContinuation is true, then a continuation prompt is appropriate.
713 ** If isContinuation is zero, then the main prompt should be used.
714 **
715 ** If zPrior is not NULL then it is a buffer from a prior call to this
716 ** routine that can be reused.
717 **
718 ** The result is stored in space obtained from malloc() and must either
719 ** be freed by the caller or else passed back into this routine via the
720 ** zPrior argument for reuse.
721 */
722 #ifndef SQLITE_SHELL_WASM_MODE
723 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
724   char *zPrompt;
725   char *zResult;
726   if( in!=0 ){
727     zResult = local_getline(zPrior, in);
728   }else{
729     zPrompt = isContinuation ? continuePrompt : mainPrompt;
730 #if SHELL_USE_LOCAL_GETLINE
731     printf("%s", zPrompt);
732     fflush(stdout);
733     zResult = local_getline(zPrior, stdin);
734 #else
735     free(zPrior);
736     zResult = shell_readline(zPrompt);
737     if( zResult && *zResult ) shell_add_history(zResult);
738 #endif
739   }
740   return zResult;
741 }
742 #endif /* !SQLITE_SHELL_WASM_MODE */
743 
744 /*
745 ** Return the value of a hexadecimal digit.  Return -1 if the input
746 ** is not a hex digit.
747 */
748 static int hexDigitValue(char c){
749   if( c>='0' && c<='9' ) return c - '0';
750   if( c>='a' && c<='f' ) return c - 'a' + 10;
751   if( c>='A' && c<='F' ) return c - 'A' + 10;
752   return -1;
753 }
754 
755 /*
756 ** Interpret zArg as an integer value, possibly with suffixes.
757 */
758 static sqlite3_int64 integerValue(const char *zArg){
759   sqlite3_int64 v = 0;
760   static const struct { char *zSuffix; int iMult; } aMult[] = {
761     { "KiB", 1024 },
762     { "MiB", 1024*1024 },
763     { "GiB", 1024*1024*1024 },
764     { "KB",  1000 },
765     { "MB",  1000000 },
766     { "GB",  1000000000 },
767     { "K",   1000 },
768     { "M",   1000000 },
769     { "G",   1000000000 },
770   };
771   int i;
772   int isNeg = 0;
773   if( zArg[0]=='-' ){
774     isNeg = 1;
775     zArg++;
776   }else if( zArg[0]=='+' ){
777     zArg++;
778   }
779   if( zArg[0]=='0' && zArg[1]=='x' ){
780     int x;
781     zArg += 2;
782     while( (x = hexDigitValue(zArg[0]))>=0 ){
783       v = (v<<4) + x;
784       zArg++;
785     }
786   }else{
787     while( IsDigit(zArg[0]) ){
788       v = v*10 + zArg[0] - '0';
789       zArg++;
790     }
791   }
792   for(i=0; i<ArraySize(aMult); i++){
793     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
794       v *= aMult[i].iMult;
795       break;
796     }
797   }
798   return isNeg? -v : v;
799 }
800 
801 /*
802 ** A variable length string to which one can append text.
803 */
804 typedef struct ShellText ShellText;
805 struct ShellText {
806   char *z;
807   int n;
808   int nAlloc;
809 };
810 
811 /*
812 ** Initialize and destroy a ShellText object
813 */
814 static void initText(ShellText *p){
815   memset(p, 0, sizeof(*p));
816 }
817 static void freeText(ShellText *p){
818   free(p->z);
819   initText(p);
820 }
821 
822 /* zIn is either a pointer to a NULL-terminated string in memory obtained
823 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
824 ** added to zIn, and the result returned in memory obtained from malloc().
825 ** zIn, if it was not NULL, is freed.
826 **
827 ** If the third argument, quote, is not '\0', then it is used as a
828 ** quote character for zAppend.
829 */
830 static void appendText(ShellText *p, const char *zAppend, char quote){
831   int len;
832   int i;
833   int nAppend = strlen30(zAppend);
834 
835   len = nAppend+p->n+1;
836   if( quote ){
837     len += 2;
838     for(i=0; i<nAppend; i++){
839       if( zAppend[i]==quote ) len++;
840     }
841   }
842 
843   if( p->z==0 || p->n+len>=p->nAlloc ){
844     p->nAlloc = p->nAlloc*2 + len + 20;
845     p->z = realloc(p->z, p->nAlloc);
846     shell_check_oom(p->z);
847   }
848 
849   if( quote ){
850     char *zCsr = p->z+p->n;
851     *zCsr++ = quote;
852     for(i=0; i<nAppend; i++){
853       *zCsr++ = zAppend[i];
854       if( zAppend[i]==quote ) *zCsr++ = quote;
855     }
856     *zCsr++ = quote;
857     p->n = (int)(zCsr - p->z);
858     *zCsr = '\0';
859   }else{
860     memcpy(p->z+p->n, zAppend, nAppend);
861     p->n += nAppend;
862     p->z[p->n] = '\0';
863   }
864 }
865 
866 /*
867 ** Attempt to determine if identifier zName needs to be quoted, either
868 ** because it contains non-alphanumeric characters, or because it is an
869 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
870 ** that quoting is required.
871 **
872 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
873 */
874 static char quoteChar(const char *zName){
875   int i;
876   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
877   for(i=0; zName[i]; i++){
878     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
879   }
880   return sqlite3_keyword_check(zName, i) ? '"' : 0;
881 }
882 
883 /*
884 ** Construct a fake object name and column list to describe the structure
885 ** of the view, virtual table, or table valued function zSchema.zName.
886 */
887 static char *shellFakeSchema(
888   sqlite3 *db,            /* The database connection containing the vtab */
889   const char *zSchema,    /* Schema of the database holding the vtab */
890   const char *zName       /* The name of the virtual table */
891 ){
892   sqlite3_stmt *pStmt = 0;
893   char *zSql;
894   ShellText s;
895   char cQuote;
896   char *zDiv = "(";
897   int nRow = 0;
898 
899   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
900                          zSchema ? zSchema : "main", zName);
901   shell_check_oom(zSql);
902   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
903   sqlite3_free(zSql);
904   initText(&s);
905   if( zSchema ){
906     cQuote = quoteChar(zSchema);
907     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
908     appendText(&s, zSchema, cQuote);
909     appendText(&s, ".", 0);
910   }
911   cQuote = quoteChar(zName);
912   appendText(&s, zName, cQuote);
913   while( sqlite3_step(pStmt)==SQLITE_ROW ){
914     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
915     nRow++;
916     appendText(&s, zDiv, 0);
917     zDiv = ",";
918     if( zCol==0 ) zCol = "";
919     cQuote = quoteChar(zCol);
920     appendText(&s, zCol, cQuote);
921   }
922   appendText(&s, ")", 0);
923   sqlite3_finalize(pStmt);
924   if( nRow==0 ){
925     freeText(&s);
926     s.z = 0;
927   }
928   return s.z;
929 }
930 
931 /*
932 ** SQL function:  shell_module_schema(X)
933 **
934 ** Return a fake schema for the table-valued function or eponymous virtual
935 ** table X.
936 */
937 static void shellModuleSchema(
938   sqlite3_context *pCtx,
939   int nVal,
940   sqlite3_value **apVal
941 ){
942   const char *zName;
943   char *zFake;
944   UNUSED_PARAMETER(nVal);
945   zName = (const char*)sqlite3_value_text(apVal[0]);
946   zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
947   if( zFake ){
948     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
949                         -1, sqlite3_free);
950     free(zFake);
951   }
952 }
953 
954 /*
955 ** SQL function:  shell_add_schema(S,X)
956 **
957 ** Add the schema name X to the CREATE statement in S and return the result.
958 ** Examples:
959 **
960 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
961 **
962 ** Also works on
963 **
964 **    CREATE INDEX
965 **    CREATE UNIQUE INDEX
966 **    CREATE VIEW
967 **    CREATE TRIGGER
968 **    CREATE VIRTUAL TABLE
969 **
970 ** This UDF is used by the .schema command to insert the schema name of
971 ** attached databases into the middle of the sqlite_schema.sql field.
972 */
973 static void shellAddSchemaName(
974   sqlite3_context *pCtx,
975   int nVal,
976   sqlite3_value **apVal
977 ){
978   static const char *aPrefix[] = {
979      "TABLE",
980      "INDEX",
981      "UNIQUE INDEX",
982      "VIEW",
983      "TRIGGER",
984      "VIRTUAL TABLE"
985   };
986   int i = 0;
987   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
988   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
989   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
990   sqlite3 *db = sqlite3_context_db_handle(pCtx);
991   UNUSED_PARAMETER(nVal);
992   if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
993     for(i=0; i<ArraySize(aPrefix); i++){
994       int n = strlen30(aPrefix[i]);
995       if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
996         char *z = 0;
997         char *zFake = 0;
998         if( zSchema ){
999           char cQuote = quoteChar(zSchema);
1000           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1001             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1002           }else{
1003             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1004           }
1005         }
1006         if( zName
1007          && aPrefix[i][0]=='V'
1008          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1009         ){
1010           if( z==0 ){
1011             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1012           }else{
1013             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1014           }
1015           free(zFake);
1016         }
1017         if( z ){
1018           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1019           return;
1020         }
1021       }
1022     }
1023   }
1024   sqlite3_result_value(pCtx, apVal[0]);
1025 }
1026 
1027 /*
1028 ** The source code for several run-time loadable extensions is inserted
1029 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1030 ** code, we need to override some macros to make the included program code
1031 ** work here in the middle of this regular program.
1032 */
1033 #define SQLITE_EXTENSION_INIT1
1034 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1035 
1036 #if defined(_WIN32) && defined(_MSC_VER)
1037 /************************* Begin test_windirent.h ******************/
1038 /*
1039 ** 2015 November 30
1040 **
1041 ** The author disclaims copyright to this source code.  In place of
1042 ** a legal notice, here is a blessing:
1043 **
1044 **    May you do good and not evil.
1045 **    May you find forgiveness for yourself and forgive others.
1046 **    May you share freely, never taking more than you give.
1047 **
1048 *************************************************************************
1049 ** This file contains declarations for most of the opendir() family of
1050 ** POSIX functions on Win32 using the MSVCRT.
1051 */
1052 
1053 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1054 #define SQLITE_WINDIRENT_H
1055 
1056 /*
1057 ** We need several data types from the Windows SDK header.
1058 */
1059 
1060 #ifndef WIN32_LEAN_AND_MEAN
1061 #define WIN32_LEAN_AND_MEAN
1062 #endif
1063 
1064 #include "windows.h"
1065 
1066 /*
1067 ** We need several support functions from the SQLite core.
1068 */
1069 
1070 /* #include "sqlite3.h" */
1071 
1072 /*
1073 ** We need several things from the ANSI and MSVCRT headers.
1074 */
1075 
1076 #include <stdio.h>
1077 #include <stdlib.h>
1078 #include <errno.h>
1079 #include <io.h>
1080 #include <limits.h>
1081 #include <sys/types.h>
1082 #include <sys/stat.h>
1083 
1084 /*
1085 ** We may need several defines that should have been in "sys/stat.h".
1086 */
1087 
1088 #ifndef S_ISREG
1089 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1090 #endif
1091 
1092 #ifndef S_ISDIR
1093 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1094 #endif
1095 
1096 #ifndef S_ISLNK
1097 #define S_ISLNK(mode) (0)
1098 #endif
1099 
1100 /*
1101 ** We may need to provide the "mode_t" type.
1102 */
1103 
1104 #ifndef MODE_T_DEFINED
1105   #define MODE_T_DEFINED
1106   typedef unsigned short mode_t;
1107 #endif
1108 
1109 /*
1110 ** We may need to provide the "ino_t" type.
1111 */
1112 
1113 #ifndef INO_T_DEFINED
1114   #define INO_T_DEFINED
1115   typedef unsigned short ino_t;
1116 #endif
1117 
1118 /*
1119 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1120 */
1121 
1122 #ifndef NAME_MAX
1123 #  ifdef FILENAME_MAX
1124 #    define NAME_MAX (FILENAME_MAX)
1125 #  else
1126 #    define NAME_MAX (260)
1127 #  endif
1128 #endif
1129 
1130 /*
1131 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1132 */
1133 
1134 #ifndef NULL_INTPTR_T
1135 #  define NULL_INTPTR_T ((intptr_t)(0))
1136 #endif
1137 
1138 #ifndef BAD_INTPTR_T
1139 #  define BAD_INTPTR_T ((intptr_t)(-1))
1140 #endif
1141 
1142 /*
1143 ** We need to provide the necessary structures and related types.
1144 */
1145 
1146 #ifndef DIRENT_DEFINED
1147 #define DIRENT_DEFINED
1148 typedef struct DIRENT DIRENT;
1149 typedef DIRENT *LPDIRENT;
1150 struct DIRENT {
1151   ino_t d_ino;               /* Sequence number, do not use. */
1152   unsigned d_attributes;     /* Win32 file attributes. */
1153   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1154 };
1155 #endif
1156 
1157 #ifndef DIR_DEFINED
1158 #define DIR_DEFINED
1159 typedef struct DIR DIR;
1160 typedef DIR *LPDIR;
1161 struct DIR {
1162   intptr_t d_handle; /* Value returned by "_findfirst". */
1163   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1164   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1165 };
1166 #endif
1167 
1168 /*
1169 ** Provide a macro, for use by the implementation, to determine if a
1170 ** particular directory entry should be skipped over when searching for
1171 ** the next directory entry that should be returned by the readdir() or
1172 ** readdir_r() functions.
1173 */
1174 
1175 #ifndef is_filtered
1176 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1177 #endif
1178 
1179 /*
1180 ** Provide the function prototype for the POSIX compatiable getenv()
1181 ** function.  This function is not thread-safe.
1182 */
1183 
1184 extern const char *windirent_getenv(const char *name);
1185 
1186 /*
1187 ** Finally, we can provide the function prototypes for the opendir(),
1188 ** readdir(), readdir_r(), and closedir() POSIX functions.
1189 */
1190 
1191 extern LPDIR opendir(const char *dirname);
1192 extern LPDIRENT readdir(LPDIR dirp);
1193 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1194 extern INT closedir(LPDIR dirp);
1195 
1196 #endif /* defined(WIN32) && defined(_MSC_VER) */
1197 
1198 /************************* End test_windirent.h ********************/
1199 /************************* Begin test_windirent.c ******************/
1200 /*
1201 ** 2015 November 30
1202 **
1203 ** The author disclaims copyright to this source code.  In place of
1204 ** a legal notice, here is a blessing:
1205 **
1206 **    May you do good and not evil.
1207 **    May you find forgiveness for yourself and forgive others.
1208 **    May you share freely, never taking more than you give.
1209 **
1210 *************************************************************************
1211 ** This file contains code to implement most of the opendir() family of
1212 ** POSIX functions on Win32 using the MSVCRT.
1213 */
1214 
1215 #if defined(_WIN32) && defined(_MSC_VER)
1216 /* #include "test_windirent.h" */
1217 
1218 /*
1219 ** Implementation of the POSIX getenv() function using the Win32 API.
1220 ** This function is not thread-safe.
1221 */
1222 const char *windirent_getenv(
1223   const char *name
1224 ){
1225   static char value[32768]; /* Maximum length, per MSDN */
1226   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1227   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1228 
1229   memset(value, 0, sizeof(value));
1230   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1231   if( dwRet==0 || dwRet>dwSize ){
1232     /*
1233     ** The function call to GetEnvironmentVariableA() failed -OR-
1234     ** the buffer is not large enough.  Either way, return NULL.
1235     */
1236     return 0;
1237   }else{
1238     /*
1239     ** The function call to GetEnvironmentVariableA() succeeded
1240     ** -AND- the buffer contains the entire value.
1241     */
1242     return value;
1243   }
1244 }
1245 
1246 /*
1247 ** Implementation of the POSIX opendir() function using the MSVCRT.
1248 */
1249 LPDIR opendir(
1250   const char *dirname
1251 ){
1252   struct _finddata_t data;
1253   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1254   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1255 
1256   if( dirp==NULL ) return NULL;
1257   memset(dirp, 0, sizeof(DIR));
1258 
1259   /* TODO: Remove this if Unix-style root paths are not used. */
1260   if( sqlite3_stricmp(dirname, "/")==0 ){
1261     dirname = windirent_getenv("SystemDrive");
1262   }
1263 
1264   memset(&data, 0, sizeof(struct _finddata_t));
1265   _snprintf(data.name, namesize, "%s\\*", dirname);
1266   dirp->d_handle = _findfirst(data.name, &data);
1267 
1268   if( dirp->d_handle==BAD_INTPTR_T ){
1269     closedir(dirp);
1270     return NULL;
1271   }
1272 
1273   /* TODO: Remove this block to allow hidden and/or system files. */
1274   if( is_filtered(data) ){
1275 next:
1276 
1277     memset(&data, 0, sizeof(struct _finddata_t));
1278     if( _findnext(dirp->d_handle, &data)==-1 ){
1279       closedir(dirp);
1280       return NULL;
1281     }
1282 
1283     /* TODO: Remove this block to allow hidden and/or system files. */
1284     if( is_filtered(data) ) goto next;
1285   }
1286 
1287   dirp->d_first.d_attributes = data.attrib;
1288   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1289   dirp->d_first.d_name[NAME_MAX] = '\0';
1290 
1291   return dirp;
1292 }
1293 
1294 /*
1295 ** Implementation of the POSIX readdir() function using the MSVCRT.
1296 */
1297 LPDIRENT readdir(
1298   LPDIR dirp
1299 ){
1300   struct _finddata_t data;
1301 
1302   if( dirp==NULL ) return NULL;
1303 
1304   if( dirp->d_first.d_ino==0 ){
1305     dirp->d_first.d_ino++;
1306     dirp->d_next.d_ino++;
1307 
1308     return &dirp->d_first;
1309   }
1310 
1311 next:
1312 
1313   memset(&data, 0, sizeof(struct _finddata_t));
1314   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1315 
1316   /* TODO: Remove this block to allow hidden and/or system files. */
1317   if( is_filtered(data) ) goto next;
1318 
1319   dirp->d_next.d_ino++;
1320   dirp->d_next.d_attributes = data.attrib;
1321   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1322   dirp->d_next.d_name[NAME_MAX] = '\0';
1323 
1324   return &dirp->d_next;
1325 }
1326 
1327 /*
1328 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1329 */
1330 INT readdir_r(
1331   LPDIR dirp,
1332   LPDIRENT entry,
1333   LPDIRENT *result
1334 ){
1335   struct _finddata_t data;
1336 
1337   if( dirp==NULL ) return EBADF;
1338 
1339   if( dirp->d_first.d_ino==0 ){
1340     dirp->d_first.d_ino++;
1341     dirp->d_next.d_ino++;
1342 
1343     entry->d_ino = dirp->d_first.d_ino;
1344     entry->d_attributes = dirp->d_first.d_attributes;
1345     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1346     entry->d_name[NAME_MAX] = '\0';
1347 
1348     *result = entry;
1349     return 0;
1350   }
1351 
1352 next:
1353 
1354   memset(&data, 0, sizeof(struct _finddata_t));
1355   if( _findnext(dirp->d_handle, &data)==-1 ){
1356     *result = NULL;
1357     return ENOENT;
1358   }
1359 
1360   /* TODO: Remove this block to allow hidden and/or system files. */
1361   if( is_filtered(data) ) goto next;
1362 
1363   entry->d_ino = (ino_t)-1; /* not available */
1364   entry->d_attributes = data.attrib;
1365   strncpy(entry->d_name, data.name, NAME_MAX);
1366   entry->d_name[NAME_MAX] = '\0';
1367 
1368   *result = entry;
1369   return 0;
1370 }
1371 
1372 /*
1373 ** Implementation of the POSIX closedir() function using the MSVCRT.
1374 */
1375 INT closedir(
1376   LPDIR dirp
1377 ){
1378   INT result = 0;
1379 
1380   if( dirp==NULL ) return EINVAL;
1381 
1382   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1383     result = _findclose(dirp->d_handle);
1384   }
1385 
1386   sqlite3_free(dirp);
1387   return result;
1388 }
1389 
1390 #endif /* defined(WIN32) && defined(_MSC_VER) */
1391 
1392 /************************* End test_windirent.c ********************/
1393 #define dirent DIRENT
1394 #endif
1395 /************************* Begin ../ext/misc/memtrace.c ******************/
1396 /*
1397 ** 2019-01-21
1398 **
1399 ** The author disclaims copyright to this source code.  In place of
1400 ** a legal notice, here is a blessing:
1401 **
1402 **    May you do good and not evil.
1403 **    May you find forgiveness for yourself and forgive others.
1404 **    May you share freely, never taking more than you give.
1405 **
1406 *************************************************************************
1407 **
1408 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
1409 ** mechanism to add a tracing layer on top of SQLite.  If this extension
1410 ** is registered prior to sqlite3_initialize(), it will cause all memory
1411 ** allocation activities to be logged on standard output, or to some other
1412 ** FILE specified by the initializer.
1413 **
1414 ** This file needs to be compiled into the application that uses it.
1415 **
1416 ** This extension is used to implement the --memtrace option of the
1417 ** command-line shell.
1418 */
1419 #include <assert.h>
1420 #include <string.h>
1421 #include <stdio.h>
1422 
1423 /* The original memory allocation routines */
1424 static sqlite3_mem_methods memtraceBase;
1425 static FILE *memtraceOut;
1426 
1427 /* Methods that trace memory allocations */
1428 static void *memtraceMalloc(int n){
1429   if( memtraceOut ){
1430     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
1431             memtraceBase.xRoundup(n));
1432   }
1433   return memtraceBase.xMalloc(n);
1434 }
1435 static void memtraceFree(void *p){
1436   if( p==0 ) return;
1437   if( memtraceOut ){
1438     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
1439   }
1440   memtraceBase.xFree(p);
1441 }
1442 static void *memtraceRealloc(void *p, int n){
1443   if( p==0 ) return memtraceMalloc(n);
1444   if( n==0 ){
1445     memtraceFree(p);
1446     return 0;
1447   }
1448   if( memtraceOut ){
1449     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
1450             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
1451   }
1452   return memtraceBase.xRealloc(p, n);
1453 }
1454 static int memtraceSize(void *p){
1455   return memtraceBase.xSize(p);
1456 }
1457 static int memtraceRoundup(int n){
1458   return memtraceBase.xRoundup(n);
1459 }
1460 static int memtraceInit(void *p){
1461   return memtraceBase.xInit(p);
1462 }
1463 static void memtraceShutdown(void *p){
1464   memtraceBase.xShutdown(p);
1465 }
1466 
1467 /* The substitute memory allocator */
1468 static sqlite3_mem_methods ersaztMethods = {
1469   memtraceMalloc,
1470   memtraceFree,
1471   memtraceRealloc,
1472   memtraceSize,
1473   memtraceRoundup,
1474   memtraceInit,
1475   memtraceShutdown,
1476   0
1477 };
1478 
1479 /* Begin tracing memory allocations to out. */
1480 int sqlite3MemTraceActivate(FILE *out){
1481   int rc = SQLITE_OK;
1482   if( memtraceBase.xMalloc==0 ){
1483     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
1484     if( rc==SQLITE_OK ){
1485       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
1486     }
1487   }
1488   memtraceOut = out;
1489   return rc;
1490 }
1491 
1492 /* Deactivate memory tracing */
1493 int sqlite3MemTraceDeactivate(void){
1494   int rc = SQLITE_OK;
1495   if( memtraceBase.xMalloc!=0 ){
1496     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
1497     if( rc==SQLITE_OK ){
1498       memset(&memtraceBase, 0, sizeof(memtraceBase));
1499     }
1500   }
1501   memtraceOut = 0;
1502   return rc;
1503 }
1504 
1505 /************************* End ../ext/misc/memtrace.c ********************/
1506 /************************* Begin ../ext/misc/shathree.c ******************/
1507 /*
1508 ** 2017-03-08
1509 **
1510 ** The author disclaims copyright to this source code.  In place of
1511 ** a legal notice, here is a blessing:
1512 **
1513 **    May you do good and not evil.
1514 **    May you find forgiveness for yourself and forgive others.
1515 **    May you share freely, never taking more than you give.
1516 **
1517 ******************************************************************************
1518 **
1519 ** This SQLite extension implements functions that compute SHA3 hashes.
1520 ** Two SQL functions are implemented:
1521 **
1522 **     sha3(X,SIZE)
1523 **     sha3_query(Y,SIZE)
1524 **
1525 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1526 ** X is NULL.
1527 **
1528 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
1529 ** and returns a hash of their results.
1530 **
1531 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1532 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1533 ** 384, or 512, to determine SHA3 hash variant that is computed.
1534 */
1535 /* #include "sqlite3ext.h" */
1536 SQLITE_EXTENSION_INIT1
1537 #include <assert.h>
1538 #include <string.h>
1539 #include <stdarg.h>
1540 
1541 #ifndef SQLITE_AMALGAMATION
1542 /* typedef sqlite3_uint64 u64; */
1543 #endif /* SQLITE_AMALGAMATION */
1544 
1545 /******************************************************************************
1546 ** The Hash Engine
1547 */
1548 /*
1549 ** Macros to determine whether the machine is big or little endian,
1550 ** and whether or not that determination is run-time or compile-time.
1551 **
1552 ** For best performance, an attempt is made to guess at the byte-order
1553 ** using C-preprocessor macros.  If that is unsuccessful, or if
1554 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1555 ** at run-time.
1556 */
1557 #ifndef SHA3_BYTEORDER
1558 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1559      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1560      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1561      defined(__arm__)
1562 #   define SHA3_BYTEORDER    1234
1563 # elif defined(sparc)    || defined(__ppc__)
1564 #   define SHA3_BYTEORDER    4321
1565 # else
1566 #   define SHA3_BYTEORDER 0
1567 # endif
1568 #endif
1569 
1570 
1571 /*
1572 ** State structure for a SHA3 hash in progress
1573 */
1574 typedef struct SHA3Context SHA3Context;
1575 struct SHA3Context {
1576   union {
1577     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1578     unsigned char x[1600];    /* ... or 1600 bytes */
1579   } u;
1580   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1581   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1582   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1583 };
1584 
1585 /*
1586 ** A single step of the Keccak mixing function for a 1600-bit state
1587 */
1588 static void KeccakF1600Step(SHA3Context *p){
1589   int i;
1590   u64 b0, b1, b2, b3, b4;
1591   u64 c0, c1, c2, c3, c4;
1592   u64 d0, d1, d2, d3, d4;
1593   static const u64 RC[] = {
1594     0x0000000000000001ULL,  0x0000000000008082ULL,
1595     0x800000000000808aULL,  0x8000000080008000ULL,
1596     0x000000000000808bULL,  0x0000000080000001ULL,
1597     0x8000000080008081ULL,  0x8000000000008009ULL,
1598     0x000000000000008aULL,  0x0000000000000088ULL,
1599     0x0000000080008009ULL,  0x000000008000000aULL,
1600     0x000000008000808bULL,  0x800000000000008bULL,
1601     0x8000000000008089ULL,  0x8000000000008003ULL,
1602     0x8000000000008002ULL,  0x8000000000000080ULL,
1603     0x000000000000800aULL,  0x800000008000000aULL,
1604     0x8000000080008081ULL,  0x8000000000008080ULL,
1605     0x0000000080000001ULL,  0x8000000080008008ULL
1606   };
1607 # define a00 (p->u.s[0])
1608 # define a01 (p->u.s[1])
1609 # define a02 (p->u.s[2])
1610 # define a03 (p->u.s[3])
1611 # define a04 (p->u.s[4])
1612 # define a10 (p->u.s[5])
1613 # define a11 (p->u.s[6])
1614 # define a12 (p->u.s[7])
1615 # define a13 (p->u.s[8])
1616 # define a14 (p->u.s[9])
1617 # define a20 (p->u.s[10])
1618 # define a21 (p->u.s[11])
1619 # define a22 (p->u.s[12])
1620 # define a23 (p->u.s[13])
1621 # define a24 (p->u.s[14])
1622 # define a30 (p->u.s[15])
1623 # define a31 (p->u.s[16])
1624 # define a32 (p->u.s[17])
1625 # define a33 (p->u.s[18])
1626 # define a34 (p->u.s[19])
1627 # define a40 (p->u.s[20])
1628 # define a41 (p->u.s[21])
1629 # define a42 (p->u.s[22])
1630 # define a43 (p->u.s[23])
1631 # define a44 (p->u.s[24])
1632 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1633 
1634   for(i=0; i<24; i+=4){
1635     c0 = a00^a10^a20^a30^a40;
1636     c1 = a01^a11^a21^a31^a41;
1637     c2 = a02^a12^a22^a32^a42;
1638     c3 = a03^a13^a23^a33^a43;
1639     c4 = a04^a14^a24^a34^a44;
1640     d0 = c4^ROL64(c1, 1);
1641     d1 = c0^ROL64(c2, 1);
1642     d2 = c1^ROL64(c3, 1);
1643     d3 = c2^ROL64(c4, 1);
1644     d4 = c3^ROL64(c0, 1);
1645 
1646     b0 = (a00^d0);
1647     b1 = ROL64((a11^d1), 44);
1648     b2 = ROL64((a22^d2), 43);
1649     b3 = ROL64((a33^d3), 21);
1650     b4 = ROL64((a44^d4), 14);
1651     a00 =   b0 ^((~b1)&  b2 );
1652     a00 ^= RC[i];
1653     a11 =   b1 ^((~b2)&  b3 );
1654     a22 =   b2 ^((~b3)&  b4 );
1655     a33 =   b3 ^((~b4)&  b0 );
1656     a44 =   b4 ^((~b0)&  b1 );
1657 
1658     b2 = ROL64((a20^d0), 3);
1659     b3 = ROL64((a31^d1), 45);
1660     b4 = ROL64((a42^d2), 61);
1661     b0 = ROL64((a03^d3), 28);
1662     b1 = ROL64((a14^d4), 20);
1663     a20 =   b0 ^((~b1)&  b2 );
1664     a31 =   b1 ^((~b2)&  b3 );
1665     a42 =   b2 ^((~b3)&  b4 );
1666     a03 =   b3 ^((~b4)&  b0 );
1667     a14 =   b4 ^((~b0)&  b1 );
1668 
1669     b4 = ROL64((a40^d0), 18);
1670     b0 = ROL64((a01^d1), 1);
1671     b1 = ROL64((a12^d2), 6);
1672     b2 = ROL64((a23^d3), 25);
1673     b3 = ROL64((a34^d4), 8);
1674     a40 =   b0 ^((~b1)&  b2 );
1675     a01 =   b1 ^((~b2)&  b3 );
1676     a12 =   b2 ^((~b3)&  b4 );
1677     a23 =   b3 ^((~b4)&  b0 );
1678     a34 =   b4 ^((~b0)&  b1 );
1679 
1680     b1 = ROL64((a10^d0), 36);
1681     b2 = ROL64((a21^d1), 10);
1682     b3 = ROL64((a32^d2), 15);
1683     b4 = ROL64((a43^d3), 56);
1684     b0 = ROL64((a04^d4), 27);
1685     a10 =   b0 ^((~b1)&  b2 );
1686     a21 =   b1 ^((~b2)&  b3 );
1687     a32 =   b2 ^((~b3)&  b4 );
1688     a43 =   b3 ^((~b4)&  b0 );
1689     a04 =   b4 ^((~b0)&  b1 );
1690 
1691     b3 = ROL64((a30^d0), 41);
1692     b4 = ROL64((a41^d1), 2);
1693     b0 = ROL64((a02^d2), 62);
1694     b1 = ROL64((a13^d3), 55);
1695     b2 = ROL64((a24^d4), 39);
1696     a30 =   b0 ^((~b1)&  b2 );
1697     a41 =   b1 ^((~b2)&  b3 );
1698     a02 =   b2 ^((~b3)&  b4 );
1699     a13 =   b3 ^((~b4)&  b0 );
1700     a24 =   b4 ^((~b0)&  b1 );
1701 
1702     c0 = a00^a20^a40^a10^a30;
1703     c1 = a11^a31^a01^a21^a41;
1704     c2 = a22^a42^a12^a32^a02;
1705     c3 = a33^a03^a23^a43^a13;
1706     c4 = a44^a14^a34^a04^a24;
1707     d0 = c4^ROL64(c1, 1);
1708     d1 = c0^ROL64(c2, 1);
1709     d2 = c1^ROL64(c3, 1);
1710     d3 = c2^ROL64(c4, 1);
1711     d4 = c3^ROL64(c0, 1);
1712 
1713     b0 = (a00^d0);
1714     b1 = ROL64((a31^d1), 44);
1715     b2 = ROL64((a12^d2), 43);
1716     b3 = ROL64((a43^d3), 21);
1717     b4 = ROL64((a24^d4), 14);
1718     a00 =   b0 ^((~b1)&  b2 );
1719     a00 ^= RC[i+1];
1720     a31 =   b1 ^((~b2)&  b3 );
1721     a12 =   b2 ^((~b3)&  b4 );
1722     a43 =   b3 ^((~b4)&  b0 );
1723     a24 =   b4 ^((~b0)&  b1 );
1724 
1725     b2 = ROL64((a40^d0), 3);
1726     b3 = ROL64((a21^d1), 45);
1727     b4 = ROL64((a02^d2), 61);
1728     b0 = ROL64((a33^d3), 28);
1729     b1 = ROL64((a14^d4), 20);
1730     a40 =   b0 ^((~b1)&  b2 );
1731     a21 =   b1 ^((~b2)&  b3 );
1732     a02 =   b2 ^((~b3)&  b4 );
1733     a33 =   b3 ^((~b4)&  b0 );
1734     a14 =   b4 ^((~b0)&  b1 );
1735 
1736     b4 = ROL64((a30^d0), 18);
1737     b0 = ROL64((a11^d1), 1);
1738     b1 = ROL64((a42^d2), 6);
1739     b2 = ROL64((a23^d3), 25);
1740     b3 = ROL64((a04^d4), 8);
1741     a30 =   b0 ^((~b1)&  b2 );
1742     a11 =   b1 ^((~b2)&  b3 );
1743     a42 =   b2 ^((~b3)&  b4 );
1744     a23 =   b3 ^((~b4)&  b0 );
1745     a04 =   b4 ^((~b0)&  b1 );
1746 
1747     b1 = ROL64((a20^d0), 36);
1748     b2 = ROL64((a01^d1), 10);
1749     b3 = ROL64((a32^d2), 15);
1750     b4 = ROL64((a13^d3), 56);
1751     b0 = ROL64((a44^d4), 27);
1752     a20 =   b0 ^((~b1)&  b2 );
1753     a01 =   b1 ^((~b2)&  b3 );
1754     a32 =   b2 ^((~b3)&  b4 );
1755     a13 =   b3 ^((~b4)&  b0 );
1756     a44 =   b4 ^((~b0)&  b1 );
1757 
1758     b3 = ROL64((a10^d0), 41);
1759     b4 = ROL64((a41^d1), 2);
1760     b0 = ROL64((a22^d2), 62);
1761     b1 = ROL64((a03^d3), 55);
1762     b2 = ROL64((a34^d4), 39);
1763     a10 =   b0 ^((~b1)&  b2 );
1764     a41 =   b1 ^((~b2)&  b3 );
1765     a22 =   b2 ^((~b3)&  b4 );
1766     a03 =   b3 ^((~b4)&  b0 );
1767     a34 =   b4 ^((~b0)&  b1 );
1768 
1769     c0 = a00^a40^a30^a20^a10;
1770     c1 = a31^a21^a11^a01^a41;
1771     c2 = a12^a02^a42^a32^a22;
1772     c3 = a43^a33^a23^a13^a03;
1773     c4 = a24^a14^a04^a44^a34;
1774     d0 = c4^ROL64(c1, 1);
1775     d1 = c0^ROL64(c2, 1);
1776     d2 = c1^ROL64(c3, 1);
1777     d3 = c2^ROL64(c4, 1);
1778     d4 = c3^ROL64(c0, 1);
1779 
1780     b0 = (a00^d0);
1781     b1 = ROL64((a21^d1), 44);
1782     b2 = ROL64((a42^d2), 43);
1783     b3 = ROL64((a13^d3), 21);
1784     b4 = ROL64((a34^d4), 14);
1785     a00 =   b0 ^((~b1)&  b2 );
1786     a00 ^= RC[i+2];
1787     a21 =   b1 ^((~b2)&  b3 );
1788     a42 =   b2 ^((~b3)&  b4 );
1789     a13 =   b3 ^((~b4)&  b0 );
1790     a34 =   b4 ^((~b0)&  b1 );
1791 
1792     b2 = ROL64((a30^d0), 3);
1793     b3 = ROL64((a01^d1), 45);
1794     b4 = ROL64((a22^d2), 61);
1795     b0 = ROL64((a43^d3), 28);
1796     b1 = ROL64((a14^d4), 20);
1797     a30 =   b0 ^((~b1)&  b2 );
1798     a01 =   b1 ^((~b2)&  b3 );
1799     a22 =   b2 ^((~b3)&  b4 );
1800     a43 =   b3 ^((~b4)&  b0 );
1801     a14 =   b4 ^((~b0)&  b1 );
1802 
1803     b4 = ROL64((a10^d0), 18);
1804     b0 = ROL64((a31^d1), 1);
1805     b1 = ROL64((a02^d2), 6);
1806     b2 = ROL64((a23^d3), 25);
1807     b3 = ROL64((a44^d4), 8);
1808     a10 =   b0 ^((~b1)&  b2 );
1809     a31 =   b1 ^((~b2)&  b3 );
1810     a02 =   b2 ^((~b3)&  b4 );
1811     a23 =   b3 ^((~b4)&  b0 );
1812     a44 =   b4 ^((~b0)&  b1 );
1813 
1814     b1 = ROL64((a40^d0), 36);
1815     b2 = ROL64((a11^d1), 10);
1816     b3 = ROL64((a32^d2), 15);
1817     b4 = ROL64((a03^d3), 56);
1818     b0 = ROL64((a24^d4), 27);
1819     a40 =   b0 ^((~b1)&  b2 );
1820     a11 =   b1 ^((~b2)&  b3 );
1821     a32 =   b2 ^((~b3)&  b4 );
1822     a03 =   b3 ^((~b4)&  b0 );
1823     a24 =   b4 ^((~b0)&  b1 );
1824 
1825     b3 = ROL64((a20^d0), 41);
1826     b4 = ROL64((a41^d1), 2);
1827     b0 = ROL64((a12^d2), 62);
1828     b1 = ROL64((a33^d3), 55);
1829     b2 = ROL64((a04^d4), 39);
1830     a20 =   b0 ^((~b1)&  b2 );
1831     a41 =   b1 ^((~b2)&  b3 );
1832     a12 =   b2 ^((~b3)&  b4 );
1833     a33 =   b3 ^((~b4)&  b0 );
1834     a04 =   b4 ^((~b0)&  b1 );
1835 
1836     c0 = a00^a30^a10^a40^a20;
1837     c1 = a21^a01^a31^a11^a41;
1838     c2 = a42^a22^a02^a32^a12;
1839     c3 = a13^a43^a23^a03^a33;
1840     c4 = a34^a14^a44^a24^a04;
1841     d0 = c4^ROL64(c1, 1);
1842     d1 = c0^ROL64(c2, 1);
1843     d2 = c1^ROL64(c3, 1);
1844     d3 = c2^ROL64(c4, 1);
1845     d4 = c3^ROL64(c0, 1);
1846 
1847     b0 = (a00^d0);
1848     b1 = ROL64((a01^d1), 44);
1849     b2 = ROL64((a02^d2), 43);
1850     b3 = ROL64((a03^d3), 21);
1851     b4 = ROL64((a04^d4), 14);
1852     a00 =   b0 ^((~b1)&  b2 );
1853     a00 ^= RC[i+3];
1854     a01 =   b1 ^((~b2)&  b3 );
1855     a02 =   b2 ^((~b3)&  b4 );
1856     a03 =   b3 ^((~b4)&  b0 );
1857     a04 =   b4 ^((~b0)&  b1 );
1858 
1859     b2 = ROL64((a10^d0), 3);
1860     b3 = ROL64((a11^d1), 45);
1861     b4 = ROL64((a12^d2), 61);
1862     b0 = ROL64((a13^d3), 28);
1863     b1 = ROL64((a14^d4), 20);
1864     a10 =   b0 ^((~b1)&  b2 );
1865     a11 =   b1 ^((~b2)&  b3 );
1866     a12 =   b2 ^((~b3)&  b4 );
1867     a13 =   b3 ^((~b4)&  b0 );
1868     a14 =   b4 ^((~b0)&  b1 );
1869 
1870     b4 = ROL64((a20^d0), 18);
1871     b0 = ROL64((a21^d1), 1);
1872     b1 = ROL64((a22^d2), 6);
1873     b2 = ROL64((a23^d3), 25);
1874     b3 = ROL64((a24^d4), 8);
1875     a20 =   b0 ^((~b1)&  b2 );
1876     a21 =   b1 ^((~b2)&  b3 );
1877     a22 =   b2 ^((~b3)&  b4 );
1878     a23 =   b3 ^((~b4)&  b0 );
1879     a24 =   b4 ^((~b0)&  b1 );
1880 
1881     b1 = ROL64((a30^d0), 36);
1882     b2 = ROL64((a31^d1), 10);
1883     b3 = ROL64((a32^d2), 15);
1884     b4 = ROL64((a33^d3), 56);
1885     b0 = ROL64((a34^d4), 27);
1886     a30 =   b0 ^((~b1)&  b2 );
1887     a31 =   b1 ^((~b2)&  b3 );
1888     a32 =   b2 ^((~b3)&  b4 );
1889     a33 =   b3 ^((~b4)&  b0 );
1890     a34 =   b4 ^((~b0)&  b1 );
1891 
1892     b3 = ROL64((a40^d0), 41);
1893     b4 = ROL64((a41^d1), 2);
1894     b0 = ROL64((a42^d2), 62);
1895     b1 = ROL64((a43^d3), 55);
1896     b2 = ROL64((a44^d4), 39);
1897     a40 =   b0 ^((~b1)&  b2 );
1898     a41 =   b1 ^((~b2)&  b3 );
1899     a42 =   b2 ^((~b3)&  b4 );
1900     a43 =   b3 ^((~b4)&  b0 );
1901     a44 =   b4 ^((~b0)&  b1 );
1902   }
1903 }
1904 
1905 /*
1906 ** Initialize a new hash.  iSize determines the size of the hash
1907 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1908 ** can be zero to use the default hash size of 256 bits.
1909 */
1910 static void SHA3Init(SHA3Context *p, int iSize){
1911   memset(p, 0, sizeof(*p));
1912   if( iSize>=128 && iSize<=512 ){
1913     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1914   }else{
1915     p->nRate = (1600 - 2*256)/8;
1916   }
1917 #if SHA3_BYTEORDER==1234
1918   /* Known to be little-endian at compile-time. No-op */
1919 #elif SHA3_BYTEORDER==4321
1920   p->ixMask = 7;  /* Big-endian */
1921 #else
1922   {
1923     static unsigned int one = 1;
1924     if( 1==*(unsigned char*)&one ){
1925       /* Little endian.  No byte swapping. */
1926       p->ixMask = 0;
1927     }else{
1928       /* Big endian.  Byte swap. */
1929       p->ixMask = 7;
1930     }
1931   }
1932 #endif
1933 }
1934 
1935 /*
1936 ** Make consecutive calls to the SHA3Update function to add new content
1937 ** to the hash
1938 */
1939 static void SHA3Update(
1940   SHA3Context *p,
1941   const unsigned char *aData,
1942   unsigned int nData
1943 ){
1944   unsigned int i = 0;
1945   if( aData==0 ) return;
1946 #if SHA3_BYTEORDER==1234
1947   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1948     for(; i+7<nData; i+=8){
1949       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1950       p->nLoaded += 8;
1951       if( p->nLoaded>=p->nRate ){
1952         KeccakF1600Step(p);
1953         p->nLoaded = 0;
1954       }
1955     }
1956   }
1957 #endif
1958   for(; i<nData; i++){
1959 #if SHA3_BYTEORDER==1234
1960     p->u.x[p->nLoaded] ^= aData[i];
1961 #elif SHA3_BYTEORDER==4321
1962     p->u.x[p->nLoaded^0x07] ^= aData[i];
1963 #else
1964     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1965 #endif
1966     p->nLoaded++;
1967     if( p->nLoaded==p->nRate ){
1968       KeccakF1600Step(p);
1969       p->nLoaded = 0;
1970     }
1971   }
1972 }
1973 
1974 /*
1975 ** After all content has been added, invoke SHA3Final() to compute
1976 ** the final hash.  The function returns a pointer to the binary
1977 ** hash value.
1978 */
1979 static unsigned char *SHA3Final(SHA3Context *p){
1980   unsigned int i;
1981   if( p->nLoaded==p->nRate-1 ){
1982     const unsigned char c1 = 0x86;
1983     SHA3Update(p, &c1, 1);
1984   }else{
1985     const unsigned char c2 = 0x06;
1986     const unsigned char c3 = 0x80;
1987     SHA3Update(p, &c2, 1);
1988     p->nLoaded = p->nRate - 1;
1989     SHA3Update(p, &c3, 1);
1990   }
1991   for(i=0; i<p->nRate; i++){
1992     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1993   }
1994   return &p->u.x[p->nRate];
1995 }
1996 /* End of the hashing logic
1997 *****************************************************************************/
1998 
1999 /*
2000 ** Implementation of the sha3(X,SIZE) function.
2001 **
2002 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
2003 ** size is 256.  If X is a BLOB, it is hashed as is.
2004 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2005 ** and the string is hashed without the trailing 0x00 terminator.  The hash
2006 ** of a NULL value is NULL.
2007 */
2008 static void sha3Func(
2009   sqlite3_context *context,
2010   int argc,
2011   sqlite3_value **argv
2012 ){
2013   SHA3Context cx;
2014   int eType = sqlite3_value_type(argv[0]);
2015   int nByte = sqlite3_value_bytes(argv[0]);
2016   int iSize;
2017   if( argc==1 ){
2018     iSize = 256;
2019   }else{
2020     iSize = sqlite3_value_int(argv[1]);
2021     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2022       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2023                                     "384 512", -1);
2024       return;
2025     }
2026   }
2027   if( eType==SQLITE_NULL ) return;
2028   SHA3Init(&cx, iSize);
2029   if( eType==SQLITE_BLOB ){
2030     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
2031   }else{
2032     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
2033   }
2034   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2035 }
2036 
2037 /* Compute a string using sqlite3_vsnprintf() with a maximum length
2038 ** of 50 bytes and add it to the hash.
2039 */
2040 static void hash_step_vformat(
2041   SHA3Context *p,                 /* Add content to this context */
2042   const char *zFormat,
2043   ...
2044 ){
2045   va_list ap;
2046   int n;
2047   char zBuf[50];
2048   va_start(ap, zFormat);
2049   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
2050   va_end(ap);
2051   n = (int)strlen(zBuf);
2052   SHA3Update(p, (unsigned char*)zBuf, n);
2053 }
2054 
2055 /*
2056 ** Implementation of the sha3_query(SQL,SIZE) function.
2057 **
2058 ** This function compiles and runs the SQL statement(s) given in the
2059 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
2060 ** size is 256.
2061 **
2062 ** The format of the byte stream that is hashed is summarized as follows:
2063 **
2064 **       S<n>:<sql>
2065 **       R
2066 **       N
2067 **       I<int>
2068 **       F<ieee-float>
2069 **       B<size>:<bytes>
2070 **       T<size>:<text>
2071 **
2072 ** <sql> is the original SQL text for each statement run and <n> is
2073 ** the size of that text.  The SQL text is UTF-8.  A single R character
2074 ** occurs before the start of each row.  N means a NULL value.
2075 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
2076 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
2077 ** B means blobs of <size> bytes.  T means text rendered as <size>
2078 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
2079 ** text integers.
2080 **
2081 ** For each SQL statement in the X input, there is one S segment.  Each
2082 ** S segment is followed by zero or more R segments, one for each row in the
2083 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
2084 ** one for each column in the result set.  Segments are concatentated directly
2085 ** with no delimiters of any kind.
2086 */
2087 static void sha3QueryFunc(
2088   sqlite3_context *context,
2089   int argc,
2090   sqlite3_value **argv
2091 ){
2092   sqlite3 *db = sqlite3_context_db_handle(context);
2093   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
2094   sqlite3_stmt *pStmt = 0;
2095   int nCol;                   /* Number of columns in the result set */
2096   int i;                      /* Loop counter */
2097   int rc;
2098   int n;
2099   const char *z;
2100   SHA3Context cx;
2101   int iSize;
2102 
2103   if( argc==1 ){
2104     iSize = 256;
2105   }else{
2106     iSize = sqlite3_value_int(argv[1]);
2107     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2108       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2109                                     "384 512", -1);
2110       return;
2111     }
2112   }
2113   if( zSql==0 ) return;
2114   SHA3Init(&cx, iSize);
2115   while( zSql[0] ){
2116     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2117     if( rc ){
2118       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2119                                    zSql, sqlite3_errmsg(db));
2120       sqlite3_finalize(pStmt);
2121       sqlite3_result_error(context, zMsg, -1);
2122       sqlite3_free(zMsg);
2123       return;
2124     }
2125     if( !sqlite3_stmt_readonly(pStmt) ){
2126       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2127       sqlite3_finalize(pStmt);
2128       sqlite3_result_error(context, zMsg, -1);
2129       sqlite3_free(zMsg);
2130       return;
2131     }
2132     nCol = sqlite3_column_count(pStmt);
2133     z = sqlite3_sql(pStmt);
2134     if( z ){
2135       n = (int)strlen(z);
2136       hash_step_vformat(&cx,"S%d:",n);
2137       SHA3Update(&cx,(unsigned char*)z,n);
2138     }
2139 
2140     /* Compute a hash over the result of the query */
2141     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2142       SHA3Update(&cx,(const unsigned char*)"R",1);
2143       for(i=0; i<nCol; i++){
2144         switch( sqlite3_column_type(pStmt,i) ){
2145           case SQLITE_NULL: {
2146             SHA3Update(&cx, (const unsigned char*)"N",1);
2147             break;
2148           }
2149           case SQLITE_INTEGER: {
2150             sqlite3_uint64 u;
2151             int j;
2152             unsigned char x[9];
2153             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2154             memcpy(&u, &v, 8);
2155             for(j=8; j>=1; j--){
2156               x[j] = u & 0xff;
2157               u >>= 8;
2158             }
2159             x[0] = 'I';
2160             SHA3Update(&cx, x, 9);
2161             break;
2162           }
2163           case SQLITE_FLOAT: {
2164             sqlite3_uint64 u;
2165             int j;
2166             unsigned char x[9];
2167             double r = sqlite3_column_double(pStmt,i);
2168             memcpy(&u, &r, 8);
2169             for(j=8; j>=1; j--){
2170               x[j] = u & 0xff;
2171               u >>= 8;
2172             }
2173             x[0] = 'F';
2174             SHA3Update(&cx,x,9);
2175             break;
2176           }
2177           case SQLITE_TEXT: {
2178             int n2 = sqlite3_column_bytes(pStmt, i);
2179             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2180             hash_step_vformat(&cx,"T%d:",n2);
2181             SHA3Update(&cx, z2, n2);
2182             break;
2183           }
2184           case SQLITE_BLOB: {
2185             int n2 = sqlite3_column_bytes(pStmt, i);
2186             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2187             hash_step_vformat(&cx,"B%d:",n2);
2188             SHA3Update(&cx, z2, n2);
2189             break;
2190           }
2191         }
2192       }
2193     }
2194     sqlite3_finalize(pStmt);
2195   }
2196   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2197 }
2198 
2199 
2200 #ifdef _WIN32
2201 
2202 #endif
2203 int sqlite3_shathree_init(
2204   sqlite3 *db,
2205   char **pzErrMsg,
2206   const sqlite3_api_routines *pApi
2207 ){
2208   int rc = SQLITE_OK;
2209   SQLITE_EXTENSION_INIT2(pApi);
2210   (void)pzErrMsg;  /* Unused parameter */
2211   rc = sqlite3_create_function(db, "sha3", 1,
2212                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2213                       0, sha3Func, 0, 0);
2214   if( rc==SQLITE_OK ){
2215     rc = sqlite3_create_function(db, "sha3", 2,
2216                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2217                       0, sha3Func, 0, 0);
2218   }
2219   if( rc==SQLITE_OK ){
2220     rc = sqlite3_create_function(db, "sha3_query", 1,
2221                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2222                       0, sha3QueryFunc, 0, 0);
2223   }
2224   if( rc==SQLITE_OK ){
2225     rc = sqlite3_create_function(db, "sha3_query", 2,
2226                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2227                       0, sha3QueryFunc, 0, 0);
2228   }
2229   return rc;
2230 }
2231 
2232 /************************* End ../ext/misc/shathree.c ********************/
2233 /************************* Begin ../ext/misc/uint.c ******************/
2234 /*
2235 ** 2020-04-14
2236 **
2237 ** The author disclaims copyright to this source code.  In place of
2238 ** a legal notice, here is a blessing:
2239 **
2240 **    May you do good and not evil.
2241 **    May you find forgiveness for yourself and forgive others.
2242 **    May you share freely, never taking more than you give.
2243 **
2244 ******************************************************************************
2245 **
2246 ** This SQLite extension implements the UINT collating sequence.
2247 **
2248 ** UINT works like BINARY for text, except that embedded strings
2249 ** of digits compare in numeric order.
2250 **
2251 **     *   Leading zeros are handled properly, in the sense that
2252 **         they do not mess of the maginitude comparison of embedded
2253 **         strings of digits.  "x00123y" is equal to "x123y".
2254 **
2255 **     *   Only unsigned integers are recognized.  Plus and minus
2256 **         signs are ignored.  Decimal points and exponential notation
2257 **         are ignored.
2258 **
2259 **     *   Embedded integers can be of arbitrary length.  Comparison
2260 **         is *not* limited integers that can be expressed as a
2261 **         64-bit machine integer.
2262 */
2263 /* #include "sqlite3ext.h" */
2264 SQLITE_EXTENSION_INIT1
2265 #include <assert.h>
2266 #include <string.h>
2267 #include <ctype.h>
2268 
2269 /*
2270 ** Compare text in lexicographic order, except strings of digits
2271 ** compare in numeric order.
2272 */
2273 static int uintCollFunc(
2274   void *notUsed,
2275   int nKey1, const void *pKey1,
2276   int nKey2, const void *pKey2
2277 ){
2278   const unsigned char *zA = (const unsigned char*)pKey1;
2279   const unsigned char *zB = (const unsigned char*)pKey2;
2280   int i=0, j=0, x;
2281   (void)notUsed;
2282   while( i<nKey1 && j<nKey2 ){
2283     x = zA[i] - zB[j];
2284     if( isdigit(zA[i]) ){
2285       int k;
2286       if( !isdigit(zB[j]) ) return x;
2287       while( i<nKey1 && zA[i]=='0' ){ i++; }
2288       while( j<nKey2 && zB[j]=='0' ){ j++; }
2289       k = 0;
2290       while( i+k<nKey1 && isdigit(zA[i+k])
2291              && j+k<nKey2 && isdigit(zB[j+k]) ){
2292         k++;
2293       }
2294       if( i+k<nKey1 && isdigit(zA[i+k]) ){
2295         return +1;
2296       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
2297         return -1;
2298       }else{
2299         x = memcmp(zA+i, zB+j, k);
2300         if( x ) return x;
2301         i += k;
2302         j += k;
2303       }
2304     }else if( x ){
2305       return x;
2306     }else{
2307       i++;
2308       j++;
2309     }
2310   }
2311   return (nKey1 - i) - (nKey2 - j);
2312 }
2313 
2314 #ifdef _WIN32
2315 
2316 #endif
2317 int sqlite3_uint_init(
2318   sqlite3 *db,
2319   char **pzErrMsg,
2320   const sqlite3_api_routines *pApi
2321 ){
2322   SQLITE_EXTENSION_INIT2(pApi);
2323   (void)pzErrMsg;  /* Unused parameter */
2324   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
2325 }
2326 
2327 /************************* End ../ext/misc/uint.c ********************/
2328 /************************* Begin ../ext/misc/decimal.c ******************/
2329 /*
2330 ** 2020-06-22
2331 **
2332 ** The author disclaims copyright to this source code.  In place of
2333 ** a legal notice, here is a blessing:
2334 **
2335 **    May you do good and not evil.
2336 **    May you find forgiveness for yourself and forgive others.
2337 **    May you share freely, never taking more than you give.
2338 **
2339 ******************************************************************************
2340 **
2341 ** Routines to implement arbitrary-precision decimal math.
2342 **
2343 ** The focus here is on simplicity and correctness, not performance.
2344 */
2345 /* #include "sqlite3ext.h" */
2346 SQLITE_EXTENSION_INIT1
2347 #include <assert.h>
2348 #include <string.h>
2349 #include <ctype.h>
2350 #include <stdlib.h>
2351 
2352 /* Mark a function parameter as unused, to suppress nuisance compiler
2353 ** warnings. */
2354 #ifndef UNUSED_PARAMETER
2355 # define UNUSED_PARAMETER(X)  (void)(X)
2356 #endif
2357 
2358 
2359 /* A decimal object */
2360 typedef struct Decimal Decimal;
2361 struct Decimal {
2362   char sign;        /* 0 for positive, 1 for negative */
2363   char oom;         /* True if an OOM is encountered */
2364   char isNull;      /* True if holds a NULL rather than a number */
2365   char isInit;      /* True upon initialization */
2366   int nDigit;       /* Total number of digits */
2367   int nFrac;        /* Number of digits to the right of the decimal point */
2368   signed char *a;   /* Array of digits.  Most significant first. */
2369 };
2370 
2371 /*
2372 ** Release memory held by a Decimal, but do not free the object itself.
2373 */
2374 static void decimal_clear(Decimal *p){
2375   sqlite3_free(p->a);
2376 }
2377 
2378 /*
2379 ** Destroy a Decimal object
2380 */
2381 static void decimal_free(Decimal *p){
2382   if( p ){
2383     decimal_clear(p);
2384     sqlite3_free(p);
2385   }
2386 }
2387 
2388 /*
2389 ** Allocate a new Decimal object.  Initialize it to the number given
2390 ** by the input string.
2391 */
2392 static Decimal *decimal_new(
2393   sqlite3_context *pCtx,
2394   sqlite3_value *pIn,
2395   int nAlt,
2396   const unsigned char *zAlt
2397 ){
2398   Decimal *p;
2399   int n, i;
2400   const unsigned char *zIn;
2401   int iExp = 0;
2402   p = sqlite3_malloc( sizeof(*p) );
2403   if( p==0 ) goto new_no_mem;
2404   p->sign = 0;
2405   p->oom = 0;
2406   p->isInit = 1;
2407   p->isNull = 0;
2408   p->nDigit = 0;
2409   p->nFrac = 0;
2410   if( zAlt ){
2411     n = nAlt,
2412     zIn = zAlt;
2413   }else{
2414     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
2415       p->a = 0;
2416       p->isNull = 1;
2417       return p;
2418     }
2419     n = sqlite3_value_bytes(pIn);
2420     zIn = sqlite3_value_text(pIn);
2421   }
2422   p->a = sqlite3_malloc64( n+1 );
2423   if( p->a==0 ) goto new_no_mem;
2424   for(i=0; isspace(zIn[i]); i++){}
2425   if( zIn[i]=='-' ){
2426     p->sign = 1;
2427     i++;
2428   }else if( zIn[i]=='+' ){
2429     i++;
2430   }
2431   while( i<n && zIn[i]=='0' ) i++;
2432   while( i<n ){
2433     char c = zIn[i];
2434     if( c>='0' && c<='9' ){
2435       p->a[p->nDigit++] = c - '0';
2436     }else if( c=='.' ){
2437       p->nFrac = p->nDigit + 1;
2438     }else if( c=='e' || c=='E' ){
2439       int j = i+1;
2440       int neg = 0;
2441       if( j>=n ) break;
2442       if( zIn[j]=='-' ){
2443         neg = 1;
2444         j++;
2445       }else if( zIn[j]=='+' ){
2446         j++;
2447       }
2448       while( j<n && iExp<1000000 ){
2449         if( zIn[j]>='0' && zIn[j]<='9' ){
2450           iExp = iExp*10 + zIn[j] - '0';
2451         }
2452         j++;
2453       }
2454       if( neg ) iExp = -iExp;
2455       break;
2456     }
2457     i++;
2458   }
2459   if( p->nFrac ){
2460     p->nFrac = p->nDigit - (p->nFrac - 1);
2461   }
2462   if( iExp>0 ){
2463     if( p->nFrac>0 ){
2464       if( iExp<=p->nFrac ){
2465         p->nFrac -= iExp;
2466         iExp = 0;
2467       }else{
2468         iExp -= p->nFrac;
2469         p->nFrac = 0;
2470       }
2471     }
2472     if( iExp>0 ){
2473       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2474       if( p->a==0 ) goto new_no_mem;
2475       memset(p->a+p->nDigit, 0, iExp);
2476       p->nDigit += iExp;
2477     }
2478   }else if( iExp<0 ){
2479     int nExtra;
2480     iExp = -iExp;
2481     nExtra = p->nDigit - p->nFrac - 1;
2482     if( nExtra ){
2483       if( nExtra>=iExp ){
2484         p->nFrac += iExp;
2485         iExp  = 0;
2486       }else{
2487         iExp -= nExtra;
2488         p->nFrac = p->nDigit - 1;
2489       }
2490     }
2491     if( iExp>0 ){
2492       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2493       if( p->a==0 ) goto new_no_mem;
2494       memmove(p->a+iExp, p->a, p->nDigit);
2495       memset(p->a, 0, iExp);
2496       p->nDigit += iExp;
2497       p->nFrac += iExp;
2498     }
2499   }
2500   return p;
2501 
2502 new_no_mem:
2503   if( pCtx ) sqlite3_result_error_nomem(pCtx);
2504   sqlite3_free(p);
2505   return 0;
2506 }
2507 
2508 /*
2509 ** Make the given Decimal the result.
2510 */
2511 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
2512   char *z;
2513   int i, j;
2514   int n;
2515   if( p==0 || p->oom ){
2516     sqlite3_result_error_nomem(pCtx);
2517     return;
2518   }
2519   if( p->isNull ){
2520     sqlite3_result_null(pCtx);
2521     return;
2522   }
2523   z = sqlite3_malloc( p->nDigit+4 );
2524   if( z==0 ){
2525     sqlite3_result_error_nomem(pCtx);
2526     return;
2527   }
2528   i = 0;
2529   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
2530     p->sign = 0;
2531   }
2532   if( p->sign ){
2533     z[0] = '-';
2534     i = 1;
2535   }
2536   n = p->nDigit - p->nFrac;
2537   if( n<=0 ){
2538     z[i++] = '0';
2539   }
2540   j = 0;
2541   while( n>1 && p->a[j]==0 ){
2542     j++;
2543     n--;
2544   }
2545   while( n>0  ){
2546     z[i++] = p->a[j] + '0';
2547     j++;
2548     n--;
2549   }
2550   if( p->nFrac ){
2551     z[i++] = '.';
2552     do{
2553       z[i++] = p->a[j] + '0';
2554       j++;
2555     }while( j<p->nDigit );
2556   }
2557   z[i] = 0;
2558   sqlite3_result_text(pCtx, z, i, sqlite3_free);
2559 }
2560 
2561 /*
2562 ** SQL Function:   decimal(X)
2563 **
2564 ** Convert input X into decimal and then back into text
2565 */
2566 static void decimalFunc(
2567   sqlite3_context *context,
2568   int argc,
2569   sqlite3_value **argv
2570 ){
2571   Decimal *p = decimal_new(context, argv[0], 0, 0);
2572   UNUSED_PARAMETER(argc);
2573   decimal_result(context, p);
2574   decimal_free(p);
2575 }
2576 
2577 /*
2578 ** Compare to Decimal objects.  Return negative, 0, or positive if the
2579 ** first object is less than, equal to, or greater than the second.
2580 **
2581 ** Preconditions for this routine:
2582 **
2583 **    pA!=0
2584 **    pA->isNull==0
2585 **    pB!=0
2586 **    pB->isNull==0
2587 */
2588 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
2589   int nASig, nBSig, rc, n;
2590   if( pA->sign!=pB->sign ){
2591     return pA->sign ? -1 : +1;
2592   }
2593   if( pA->sign ){
2594     const Decimal *pTemp = pA;
2595     pA = pB;
2596     pB = pTemp;
2597   }
2598   nASig = pA->nDigit - pA->nFrac;
2599   nBSig = pB->nDigit - pB->nFrac;
2600   if( nASig!=nBSig ){
2601     return nASig - nBSig;
2602   }
2603   n = pA->nDigit;
2604   if( n>pB->nDigit ) n = pB->nDigit;
2605   rc = memcmp(pA->a, pB->a, n);
2606   if( rc==0 ){
2607     rc = pA->nDigit - pB->nDigit;
2608   }
2609   return rc;
2610 }
2611 
2612 /*
2613 ** SQL Function:   decimal_cmp(X, Y)
2614 **
2615 ** Return negative, zero, or positive if X is less then, equal to, or
2616 ** greater than Y.
2617 */
2618 static void decimalCmpFunc(
2619   sqlite3_context *context,
2620   int argc,
2621   sqlite3_value **argv
2622 ){
2623   Decimal *pA = 0, *pB = 0;
2624   int rc;
2625 
2626   UNUSED_PARAMETER(argc);
2627   pA = decimal_new(context, argv[0], 0, 0);
2628   if( pA==0 || pA->isNull ) goto cmp_done;
2629   pB = decimal_new(context, argv[1], 0, 0);
2630   if( pB==0 || pB->isNull ) goto cmp_done;
2631   rc = decimal_cmp(pA, pB);
2632   if( rc<0 ) rc = -1;
2633   else if( rc>0 ) rc = +1;
2634   sqlite3_result_int(context, rc);
2635 cmp_done:
2636   decimal_free(pA);
2637   decimal_free(pB);
2638 }
2639 
2640 /*
2641 ** Expand the Decimal so that it has a least nDigit digits and nFrac
2642 ** digits to the right of the decimal point.
2643 */
2644 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
2645   int nAddSig;
2646   int nAddFrac;
2647   if( p==0 ) return;
2648   nAddFrac = nFrac - p->nFrac;
2649   nAddSig = (nDigit - p->nDigit) - nAddFrac;
2650   if( nAddFrac==0 && nAddSig==0 ) return;
2651   p->a = sqlite3_realloc64(p->a, nDigit+1);
2652   if( p->a==0 ){
2653     p->oom = 1;
2654     return;
2655   }
2656   if( nAddSig ){
2657     memmove(p->a+nAddSig, p->a, p->nDigit);
2658     memset(p->a, 0, nAddSig);
2659     p->nDigit += nAddSig;
2660   }
2661   if( nAddFrac ){
2662     memset(p->a+p->nDigit, 0, nAddFrac);
2663     p->nDigit += nAddFrac;
2664     p->nFrac += nAddFrac;
2665   }
2666 }
2667 
2668 /*
2669 ** Add the value pB into pA.
2670 **
2671 ** Both pA and pB might become denormalized by this routine.
2672 */
2673 static void decimal_add(Decimal *pA, Decimal *pB){
2674   int nSig, nFrac, nDigit;
2675   int i, rc;
2676   if( pA==0 ){
2677     return;
2678   }
2679   if( pA->oom || pB==0 || pB->oom ){
2680     pA->oom = 1;
2681     return;
2682   }
2683   if( pA->isNull || pB->isNull ){
2684     pA->isNull = 1;
2685     return;
2686   }
2687   nSig = pA->nDigit - pA->nFrac;
2688   if( nSig && pA->a[0]==0 ) nSig--;
2689   if( nSig<pB->nDigit-pB->nFrac ){
2690     nSig = pB->nDigit - pB->nFrac;
2691   }
2692   nFrac = pA->nFrac;
2693   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
2694   nDigit = nSig + nFrac + 1;
2695   decimal_expand(pA, nDigit, nFrac);
2696   decimal_expand(pB, nDigit, nFrac);
2697   if( pA->oom || pB->oom ){
2698     pA->oom = 1;
2699   }else{
2700     if( pA->sign==pB->sign ){
2701       int carry = 0;
2702       for(i=nDigit-1; i>=0; i--){
2703         int x = pA->a[i] + pB->a[i] + carry;
2704         if( x>=10 ){
2705           carry = 1;
2706           pA->a[i] = x - 10;
2707         }else{
2708           carry = 0;
2709           pA->a[i] = x;
2710         }
2711       }
2712     }else{
2713       signed char *aA, *aB;
2714       int borrow = 0;
2715       rc = memcmp(pA->a, pB->a, nDigit);
2716       if( rc<0 ){
2717         aA = pB->a;
2718         aB = pA->a;
2719         pA->sign = !pA->sign;
2720       }else{
2721         aA = pA->a;
2722         aB = pB->a;
2723       }
2724       for(i=nDigit-1; i>=0; i--){
2725         int x = aA[i] - aB[i] - borrow;
2726         if( x<0 ){
2727           pA->a[i] = x+10;
2728           borrow = 1;
2729         }else{
2730           pA->a[i] = x;
2731           borrow = 0;
2732         }
2733       }
2734     }
2735   }
2736 }
2737 
2738 /*
2739 ** Compare text in decimal order.
2740 */
2741 static int decimalCollFunc(
2742   void *notUsed,
2743   int nKey1, const void *pKey1,
2744   int nKey2, const void *pKey2
2745 ){
2746   const unsigned char *zA = (const unsigned char*)pKey1;
2747   const unsigned char *zB = (const unsigned char*)pKey2;
2748   Decimal *pA = decimal_new(0, 0, nKey1, zA);
2749   Decimal *pB = decimal_new(0, 0, nKey2, zB);
2750   int rc;
2751   UNUSED_PARAMETER(notUsed);
2752   if( pA==0 || pB==0 ){
2753     rc = 0;
2754   }else{
2755     rc = decimal_cmp(pA, pB);
2756   }
2757   decimal_free(pA);
2758   decimal_free(pB);
2759   return rc;
2760 }
2761 
2762 
2763 /*
2764 ** SQL Function:   decimal_add(X, Y)
2765 **                 decimal_sub(X, Y)
2766 **
2767 ** Return the sum or difference of X and Y.
2768 */
2769 static void decimalAddFunc(
2770   sqlite3_context *context,
2771   int argc,
2772   sqlite3_value **argv
2773 ){
2774   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2775   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2776   UNUSED_PARAMETER(argc);
2777   decimal_add(pA, pB);
2778   decimal_result(context, pA);
2779   decimal_free(pA);
2780   decimal_free(pB);
2781 }
2782 static void decimalSubFunc(
2783   sqlite3_context *context,
2784   int argc,
2785   sqlite3_value **argv
2786 ){
2787   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2788   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2789   UNUSED_PARAMETER(argc);
2790   if( pB ){
2791     pB->sign = !pB->sign;
2792     decimal_add(pA, pB);
2793     decimal_result(context, pA);
2794   }
2795   decimal_free(pA);
2796   decimal_free(pB);
2797 }
2798 
2799 /* Aggregate funcion:   decimal_sum(X)
2800 **
2801 ** Works like sum() except that it uses decimal arithmetic for unlimited
2802 ** precision.
2803 */
2804 static void decimalSumStep(
2805   sqlite3_context *context,
2806   int argc,
2807   sqlite3_value **argv
2808 ){
2809   Decimal *p;
2810   Decimal *pArg;
2811   UNUSED_PARAMETER(argc);
2812   p = sqlite3_aggregate_context(context, sizeof(*p));
2813   if( p==0 ) return;
2814   if( !p->isInit ){
2815     p->isInit = 1;
2816     p->a = sqlite3_malloc(2);
2817     if( p->a==0 ){
2818       p->oom = 1;
2819     }else{
2820       p->a[0] = 0;
2821     }
2822     p->nDigit = 1;
2823     p->nFrac = 0;
2824   }
2825   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2826   pArg = decimal_new(context, argv[0], 0, 0);
2827   decimal_add(p, pArg);
2828   decimal_free(pArg);
2829 }
2830 static void decimalSumInverse(
2831   sqlite3_context *context,
2832   int argc,
2833   sqlite3_value **argv
2834 ){
2835   Decimal *p;
2836   Decimal *pArg;
2837   UNUSED_PARAMETER(argc);
2838   p = sqlite3_aggregate_context(context, sizeof(*p));
2839   if( p==0 ) return;
2840   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2841   pArg = decimal_new(context, argv[0], 0, 0);
2842   if( pArg ) pArg->sign = !pArg->sign;
2843   decimal_add(p, pArg);
2844   decimal_free(pArg);
2845 }
2846 static void decimalSumValue(sqlite3_context *context){
2847   Decimal *p = sqlite3_aggregate_context(context, 0);
2848   if( p==0 ) return;
2849   decimal_result(context, p);
2850 }
2851 static void decimalSumFinalize(sqlite3_context *context){
2852   Decimal *p = sqlite3_aggregate_context(context, 0);
2853   if( p==0 ) return;
2854   decimal_result(context, p);
2855   decimal_clear(p);
2856 }
2857 
2858 /*
2859 ** SQL Function:   decimal_mul(X, Y)
2860 **
2861 ** Return the product of X and Y.
2862 **
2863 ** All significant digits after the decimal point are retained.
2864 ** Trailing zeros after the decimal point are omitted as long as
2865 ** the number of digits after the decimal point is no less than
2866 ** either the number of digits in either input.
2867 */
2868 static void decimalMulFunc(
2869   sqlite3_context *context,
2870   int argc,
2871   sqlite3_value **argv
2872 ){
2873   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2874   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2875   signed char *acc = 0;
2876   int i, j, k;
2877   int minFrac;
2878   UNUSED_PARAMETER(argc);
2879   if( pA==0 || pA->oom || pA->isNull
2880    || pB==0 || pB->oom || pB->isNull
2881   ){
2882     goto mul_end;
2883   }
2884   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
2885   if( acc==0 ){
2886     sqlite3_result_error_nomem(context);
2887     goto mul_end;
2888   }
2889   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
2890   minFrac = pA->nFrac;
2891   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
2892   for(i=pA->nDigit-1; i>=0; i--){
2893     signed char f = pA->a[i];
2894     int carry = 0, x;
2895     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
2896       x = acc[k] + f*pB->a[j] + carry;
2897       acc[k] = x%10;
2898       carry = x/10;
2899     }
2900     x = acc[k] + carry;
2901     acc[k] = x%10;
2902     acc[k-1] += x/10;
2903   }
2904   sqlite3_free(pA->a);
2905   pA->a = acc;
2906   acc = 0;
2907   pA->nDigit += pB->nDigit + 2;
2908   pA->nFrac += pB->nFrac;
2909   pA->sign ^= pB->sign;
2910   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
2911     pA->nFrac--;
2912     pA->nDigit--;
2913   }
2914   decimal_result(context, pA);
2915 
2916 mul_end:
2917   sqlite3_free(acc);
2918   decimal_free(pA);
2919   decimal_free(pB);
2920 }
2921 
2922 #ifdef _WIN32
2923 
2924 #endif
2925 int sqlite3_decimal_init(
2926   sqlite3 *db,
2927   char **pzErrMsg,
2928   const sqlite3_api_routines *pApi
2929 ){
2930   int rc = SQLITE_OK;
2931   static const struct {
2932     const char *zFuncName;
2933     int nArg;
2934     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2935   } aFunc[] = {
2936     { "decimal",       1,   decimalFunc        },
2937     { "decimal_cmp",   2,   decimalCmpFunc     },
2938     { "decimal_add",   2,   decimalAddFunc     },
2939     { "decimal_sub",   2,   decimalSubFunc     },
2940     { "decimal_mul",   2,   decimalMulFunc     },
2941   };
2942   unsigned int i;
2943   (void)pzErrMsg;  /* Unused parameter */
2944 
2945   SQLITE_EXTENSION_INIT2(pApi);
2946 
2947   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2948     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
2949                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
2950                    0, aFunc[i].xFunc, 0, 0);
2951   }
2952   if( rc==SQLITE_OK ){
2953     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
2954                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
2955                    decimalSumStep, decimalSumFinalize,
2956                    decimalSumValue, decimalSumInverse, 0);
2957   }
2958   if( rc==SQLITE_OK ){
2959     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
2960                                   0, decimalCollFunc);
2961   }
2962   return rc;
2963 }
2964 
2965 /************************* End ../ext/misc/decimal.c ********************/
2966 /************************* Begin ../ext/misc/ieee754.c ******************/
2967 /*
2968 ** 2013-04-17
2969 **
2970 ** The author disclaims copyright to this source code.  In place of
2971 ** a legal notice, here is a blessing:
2972 **
2973 **    May you do good and not evil.
2974 **    May you find forgiveness for yourself and forgive others.
2975 **    May you share freely, never taking more than you give.
2976 **
2977 ******************************************************************************
2978 **
2979 ** This SQLite extension implements functions for the exact display
2980 ** and input of IEEE754 Binary64 floating-point numbers.
2981 **
2982 **   ieee754(X)
2983 **   ieee754(Y,Z)
2984 **
2985 ** In the first form, the value X should be a floating-point number.
2986 ** The function will return a string of the form 'ieee754(Y,Z)' where
2987 ** Y and Z are integers such that X==Y*pow(2,Z).
2988 **
2989 ** In the second form, Y and Z are integers which are the mantissa and
2990 ** base-2 exponent of a new floating point number.  The function returns
2991 ** a floating-point value equal to Y*pow(2,Z).
2992 **
2993 ** Examples:
2994 **
2995 **     ieee754(2.0)             ->     'ieee754(2,0)'
2996 **     ieee754(45.25)           ->     'ieee754(181,-2)'
2997 **     ieee754(2, 0)            ->     2.0
2998 **     ieee754(181, -2)         ->     45.25
2999 **
3000 ** Two additional functions break apart the one-argument ieee754()
3001 ** result into separate integer values:
3002 **
3003 **     ieee754_mantissa(45.25)  ->     181
3004 **     ieee754_exponent(45.25)  ->     -2
3005 **
3006 ** These functions convert binary64 numbers into blobs and back again.
3007 **
3008 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
3009 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
3010 **
3011 ** In all single-argument functions, if the argument is an 8-byte blob
3012 ** then that blob is interpreted as a big-endian binary64 value.
3013 **
3014 **
3015 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
3016 ** -----------------------------------------------
3017 **
3018 ** This extension in combination with the separate 'decimal' extension
3019 ** can be used to compute the exact decimal representation of binary64
3020 ** values.  To begin, first compute a table of exponent values:
3021 **
3022 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
3023 **    WITH RECURSIVE c(x,v) AS (
3024 **      VALUES(0,'1')
3025 **      UNION ALL
3026 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
3027 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
3028 **    WITH RECURSIVE c(x,v) AS (
3029 **      VALUES(-1,'0.5')
3030 **      UNION ALL
3031 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
3032 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
3033 **
3034 ** Then, to compute the exact decimal representation of a floating
3035 ** point value (the value 47.49 is used in the example) do:
3036 **
3037 **    WITH c(n) AS (VALUES(47.49))
3038 **          ---------------^^^^^---- Replace with whatever you want
3039 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
3040 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
3041 **
3042 ** Here is a query to show various boundry values for the binary64
3043 ** number format:
3044 **
3045 **    WITH c(name,bin) AS (VALUES
3046 **       ('minimum positive value',        x'0000000000000001'),
3047 **       ('maximum subnormal value',       x'000fffffffffffff'),
3048 **       ('mininum positive nornal value', x'0010000000000000'),
3049 **       ('maximum value',                 x'7fefffffffffffff'))
3050 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
3051 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
3052 **
3053 */
3054 /* #include "sqlite3ext.h" */
3055 SQLITE_EXTENSION_INIT1
3056 #include <assert.h>
3057 #include <string.h>
3058 
3059 /* Mark a function parameter as unused, to suppress nuisance compiler
3060 ** warnings. */
3061 #ifndef UNUSED_PARAMETER
3062 # define UNUSED_PARAMETER(X)  (void)(X)
3063 #endif
3064 
3065 /*
3066 ** Implementation of the ieee754() function
3067 */
3068 static void ieee754func(
3069   sqlite3_context *context,
3070   int argc,
3071   sqlite3_value **argv
3072 ){
3073   if( argc==1 ){
3074     sqlite3_int64 m, a;
3075     double r;
3076     int e;
3077     int isNeg;
3078     char zResult[100];
3079     assert( sizeof(m)==sizeof(r) );
3080     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
3081      && sqlite3_value_bytes(argv[0])==sizeof(r)
3082     ){
3083       const unsigned char *x = sqlite3_value_blob(argv[0]);
3084       unsigned int i;
3085       sqlite3_uint64 v = 0;
3086       for(i=0; i<sizeof(r); i++){
3087         v = (v<<8) | x[i];
3088       }
3089       memcpy(&r, &v, sizeof(r));
3090     }else{
3091       r = sqlite3_value_double(argv[0]);
3092     }
3093     if( r<0.0 ){
3094       isNeg = 1;
3095       r = -r;
3096     }else{
3097       isNeg = 0;
3098     }
3099     memcpy(&a,&r,sizeof(a));
3100     if( a==0 ){
3101       e = 0;
3102       m = 0;
3103     }else{
3104       e = a>>52;
3105       m = a & ((((sqlite3_int64)1)<<52)-1);
3106       if( e==0 ){
3107         m <<= 1;
3108       }else{
3109         m |= ((sqlite3_int64)1)<<52;
3110       }
3111       while( e<1075 && m>0 && (m&1)==0 ){
3112         m >>= 1;
3113         e++;
3114       }
3115       if( isNeg ) m = -m;
3116     }
3117     switch( *(int*)sqlite3_user_data(context) ){
3118       case 0:
3119         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
3120                          m, e-1075);
3121         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
3122         break;
3123       case 1:
3124         sqlite3_result_int64(context, m);
3125         break;
3126       case 2:
3127         sqlite3_result_int(context, e-1075);
3128         break;
3129     }
3130   }else{
3131     sqlite3_int64 m, e, a;
3132     double r;
3133     int isNeg = 0;
3134     m = sqlite3_value_int64(argv[0]);
3135     e = sqlite3_value_int64(argv[1]);
3136 
3137     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
3138     if( e>10000 ){
3139       e = 10000;
3140     }else if( e<-10000 ){
3141       e = -10000;
3142     }
3143 
3144     if( m<0 ){
3145       isNeg = 1;
3146       m = -m;
3147       if( m<0 ) return;
3148     }else if( m==0 && e>-1000 && e<1000 ){
3149       sqlite3_result_double(context, 0.0);
3150       return;
3151     }
3152     while( (m>>32)&0xffe00000 ){
3153       m >>= 1;
3154       e++;
3155     }
3156     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
3157       m <<= 1;
3158       e--;
3159     }
3160     e += 1075;
3161     if( e<=0 ){
3162       /* Subnormal */
3163       if( 1-e >= 64 ){
3164         m = 0;
3165       }else{
3166         m >>= 1-e;
3167       }
3168       e = 0;
3169     }else if( e>0x7ff ){
3170       e = 0x7ff;
3171     }
3172     a = m & ((((sqlite3_int64)1)<<52)-1);
3173     a |= e<<52;
3174     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
3175     memcpy(&r, &a, sizeof(r));
3176     sqlite3_result_double(context, r);
3177   }
3178 }
3179 
3180 /*
3181 ** Functions to convert between blobs and floats.
3182 */
3183 static void ieee754func_from_blob(
3184   sqlite3_context *context,
3185   int argc,
3186   sqlite3_value **argv
3187 ){
3188   UNUSED_PARAMETER(argc);
3189   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
3190    && sqlite3_value_bytes(argv[0])==sizeof(double)
3191   ){
3192     double r;
3193     const unsigned char *x = sqlite3_value_blob(argv[0]);
3194     unsigned int i;
3195     sqlite3_uint64 v = 0;
3196     for(i=0; i<sizeof(r); i++){
3197       v = (v<<8) | x[i];
3198     }
3199     memcpy(&r, &v, sizeof(r));
3200     sqlite3_result_double(context, r);
3201   }
3202 }
3203 static void ieee754func_to_blob(
3204   sqlite3_context *context,
3205   int argc,
3206   sqlite3_value **argv
3207 ){
3208   UNUSED_PARAMETER(argc);
3209   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
3210    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
3211   ){
3212     double r = sqlite3_value_double(argv[0]);
3213     sqlite3_uint64 v;
3214     unsigned char a[sizeof(r)];
3215     unsigned int i;
3216     memcpy(&v, &r, sizeof(r));
3217     for(i=1; i<=sizeof(r); i++){
3218       a[sizeof(r)-i] = v&0xff;
3219       v >>= 8;
3220     }
3221     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
3222   }
3223 }
3224 
3225 
3226 #ifdef _WIN32
3227 
3228 #endif
3229 int sqlite3_ieee_init(
3230   sqlite3 *db,
3231   char **pzErrMsg,
3232   const sqlite3_api_routines *pApi
3233 ){
3234   static const struct {
3235     char *zFName;
3236     int nArg;
3237     int iAux;
3238     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3239   } aFunc[] = {
3240     { "ieee754",           1,   0, ieee754func },
3241     { "ieee754",           2,   0, ieee754func },
3242     { "ieee754_mantissa",  1,   1, ieee754func },
3243     { "ieee754_exponent",  1,   2, ieee754func },
3244     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
3245     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
3246 
3247   };
3248   unsigned int i;
3249   int rc = SQLITE_OK;
3250   SQLITE_EXTENSION_INIT2(pApi);
3251   (void)pzErrMsg;  /* Unused parameter */
3252   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
3253     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
3254                                SQLITE_UTF8|SQLITE_INNOCUOUS,
3255                                (void*)&aFunc[i].iAux,
3256                                aFunc[i].xFunc, 0, 0);
3257   }
3258   return rc;
3259 }
3260 
3261 /************************* End ../ext/misc/ieee754.c ********************/
3262 /************************* Begin ../ext/misc/series.c ******************/
3263 /*
3264 ** 2015-08-18
3265 **
3266 ** The author disclaims copyright to this source code.  In place of
3267 ** a legal notice, here is a blessing:
3268 **
3269 **    May you do good and not evil.
3270 **    May you find forgiveness for yourself and forgive others.
3271 **    May you share freely, never taking more than you give.
3272 **
3273 *************************************************************************
3274 **
3275 ** This file demonstrates how to create a table-valued-function using
3276 ** a virtual table.  This demo implements the generate_series() function
3277 ** which gives similar results to the eponymous function in PostgreSQL.
3278 ** Examples:
3279 **
3280 **      SELECT * FROM generate_series(0,100,5);
3281 **
3282 ** The query above returns integers from 0 through 100 counting by steps
3283 ** of 5.
3284 **
3285 **      SELECT * FROM generate_series(0,100);
3286 **
3287 ** Integers from 0 through 100 with a step size of 1.
3288 **
3289 **      SELECT * FROM generate_series(20) LIMIT 10;
3290 **
3291 ** Integers 20 through 29.
3292 **
3293 ** HOW IT WORKS
3294 **
3295 ** The generate_series "function" is really a virtual table with the
3296 ** following schema:
3297 **
3298 **     CREATE TABLE generate_series(
3299 **       value,
3300 **       start HIDDEN,
3301 **       stop HIDDEN,
3302 **       step HIDDEN
3303 **     );
3304 **
3305 ** Function arguments in queries against this virtual table are translated
3306 ** into equality constraints against successive hidden columns.  In other
3307 ** words, the following pairs of queries are equivalent to each other:
3308 **
3309 **    SELECT * FROM generate_series(0,100,5);
3310 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
3311 **
3312 **    SELECT * FROM generate_series(0,100);
3313 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
3314 **
3315 **    SELECT * FROM generate_series(20) LIMIT 10;
3316 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
3317 **
3318 ** The generate_series virtual table implementation leaves the xCreate method
3319 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
3320 ** TABLE command with "generate_series" as the USING argument.  Instead, there
3321 ** is a single generate_series virtual table that is always available without
3322 ** having to be created first.
3323 **
3324 ** The xBestIndex method looks for equality constraints against the hidden
3325 ** start, stop, and step columns, and if present, it uses those constraints
3326 ** to bound the sequence of generated values.  If the equality constraints
3327 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
3328 ** xBestIndex returns a small cost when both start and stop are available,
3329 ** and a very large cost if either start or stop are unavailable.  This
3330 ** encourages the query planner to order joins such that the bounds of the
3331 ** series are well-defined.
3332 */
3333 /* #include "sqlite3ext.h" */
3334 SQLITE_EXTENSION_INIT1
3335 #include <assert.h>
3336 #include <string.h>
3337 
3338 #ifndef SQLITE_OMIT_VIRTUALTABLE
3339 
3340 
3341 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
3342 ** serve as the underlying representation of a cursor that scans
3343 ** over rows of the result
3344 */
3345 typedef struct series_cursor series_cursor;
3346 struct series_cursor {
3347   sqlite3_vtab_cursor base;  /* Base class - must be first */
3348   int isDesc;                /* True to count down rather than up */
3349   sqlite3_int64 iRowid;      /* The rowid */
3350   sqlite3_int64 iValue;      /* Current value ("value") */
3351   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
3352   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
3353   sqlite3_int64 iStep;       /* Increment ("step") */
3354 };
3355 
3356 /*
3357 ** The seriesConnect() method is invoked to create a new
3358 ** series_vtab that describes the generate_series virtual table.
3359 **
3360 ** Think of this routine as the constructor for series_vtab objects.
3361 **
3362 ** All this routine needs to do is:
3363 **
3364 **    (1) Allocate the series_vtab object and initialize all fields.
3365 **
3366 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3367 **        result set of queries against generate_series will look like.
3368 */
3369 static int seriesConnect(
3370   sqlite3 *db,
3371   void *pUnused,
3372   int argcUnused, const char *const*argvUnused,
3373   sqlite3_vtab **ppVtab,
3374   char **pzErrUnused
3375 ){
3376   sqlite3_vtab *pNew;
3377   int rc;
3378 
3379 /* Column numbers */
3380 #define SERIES_COLUMN_VALUE 0
3381 #define SERIES_COLUMN_START 1
3382 #define SERIES_COLUMN_STOP  2
3383 #define SERIES_COLUMN_STEP  3
3384 
3385   (void)pUnused;
3386   (void)argcUnused;
3387   (void)argvUnused;
3388   (void)pzErrUnused;
3389   rc = sqlite3_declare_vtab(db,
3390      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
3391   if( rc==SQLITE_OK ){
3392     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
3393     if( pNew==0 ) return SQLITE_NOMEM;
3394     memset(pNew, 0, sizeof(*pNew));
3395     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
3396   }
3397   return rc;
3398 }
3399 
3400 /*
3401 ** This method is the destructor for series_cursor objects.
3402 */
3403 static int seriesDisconnect(sqlite3_vtab *pVtab){
3404   sqlite3_free(pVtab);
3405   return SQLITE_OK;
3406 }
3407 
3408 /*
3409 ** Constructor for a new series_cursor object.
3410 */
3411 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
3412   series_cursor *pCur;
3413   (void)pUnused;
3414   pCur = sqlite3_malloc( sizeof(*pCur) );
3415   if( pCur==0 ) return SQLITE_NOMEM;
3416   memset(pCur, 0, sizeof(*pCur));
3417   *ppCursor = &pCur->base;
3418   return SQLITE_OK;
3419 }
3420 
3421 /*
3422 ** Destructor for a series_cursor.
3423 */
3424 static int seriesClose(sqlite3_vtab_cursor *cur){
3425   sqlite3_free(cur);
3426   return SQLITE_OK;
3427 }
3428 
3429 
3430 /*
3431 ** Advance a series_cursor to its next row of output.
3432 */
3433 static int seriesNext(sqlite3_vtab_cursor *cur){
3434   series_cursor *pCur = (series_cursor*)cur;
3435   if( pCur->isDesc ){
3436     pCur->iValue -= pCur->iStep;
3437   }else{
3438     pCur->iValue += pCur->iStep;
3439   }
3440   pCur->iRowid++;
3441   return SQLITE_OK;
3442 }
3443 
3444 /*
3445 ** Return values of columns for the row at which the series_cursor
3446 ** is currently pointing.
3447 */
3448 static int seriesColumn(
3449   sqlite3_vtab_cursor *cur,   /* The cursor */
3450   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
3451   int i                       /* Which column to return */
3452 ){
3453   series_cursor *pCur = (series_cursor*)cur;
3454   sqlite3_int64 x = 0;
3455   switch( i ){
3456     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
3457     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
3458     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
3459     default:                   x = pCur->iValue;  break;
3460   }
3461   sqlite3_result_int64(ctx, x);
3462   return SQLITE_OK;
3463 }
3464 
3465 /*
3466 ** Return the rowid for the current row. In this implementation, the
3467 ** first row returned is assigned rowid value 1, and each subsequent
3468 ** row a value 1 more than that of the previous.
3469 */
3470 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3471   series_cursor *pCur = (series_cursor*)cur;
3472   *pRowid = pCur->iRowid;
3473   return SQLITE_OK;
3474 }
3475 
3476 /*
3477 ** Return TRUE if the cursor has been moved off of the last
3478 ** row of output.
3479 */
3480 static int seriesEof(sqlite3_vtab_cursor *cur){
3481   series_cursor *pCur = (series_cursor*)cur;
3482   if( pCur->isDesc ){
3483     return pCur->iValue < pCur->mnValue;
3484   }else{
3485     return pCur->iValue > pCur->mxValue;
3486   }
3487 }
3488 
3489 /* True to cause run-time checking of the start=, stop=, and/or step=
3490 ** parameters.  The only reason to do this is for testing the
3491 ** constraint checking logic for virtual tables in the SQLite core.
3492 */
3493 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
3494 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
3495 #endif
3496 
3497 /*
3498 ** This method is called to "rewind" the series_cursor object back
3499 ** to the first row of output.  This method is always called at least
3500 ** once prior to any call to seriesColumn() or seriesRowid() or
3501 ** seriesEof().
3502 **
3503 ** The query plan selected by seriesBestIndex is passed in the idxNum
3504 ** parameter.  (idxStr is not used in this implementation.)  idxNum
3505 ** is a bitmask showing which constraints are available:
3506 **
3507 **    1:    start=VALUE
3508 **    2:    stop=VALUE
3509 **    4:    step=VALUE
3510 **
3511 ** Also, if bit 8 is set, that means that the series should be output
3512 ** in descending order rather than in ascending order.  If bit 16 is
3513 ** set, then output must appear in ascending order.
3514 **
3515 ** This routine should initialize the cursor and position it so that it
3516 ** is pointing at the first row, or pointing off the end of the table
3517 ** (so that seriesEof() will return true) if the table is empty.
3518 */
3519 static int seriesFilter(
3520   sqlite3_vtab_cursor *pVtabCursor,
3521   int idxNum, const char *idxStrUnused,
3522   int argc, sqlite3_value **argv
3523 ){
3524   series_cursor *pCur = (series_cursor *)pVtabCursor;
3525   int i = 0;
3526   (void)idxStrUnused;
3527   if( idxNum & 1 ){
3528     pCur->mnValue = sqlite3_value_int64(argv[i++]);
3529   }else{
3530     pCur->mnValue = 0;
3531   }
3532   if( idxNum & 2 ){
3533     pCur->mxValue = sqlite3_value_int64(argv[i++]);
3534   }else{
3535     pCur->mxValue = 0xffffffff;
3536   }
3537   if( idxNum & 4 ){
3538     pCur->iStep = sqlite3_value_int64(argv[i++]);
3539     if( pCur->iStep==0 ){
3540       pCur->iStep = 1;
3541     }else if( pCur->iStep<0 ){
3542       pCur->iStep = -pCur->iStep;
3543       if( (idxNum & 16)==0 ) idxNum |= 8;
3544     }
3545   }else{
3546     pCur->iStep = 1;
3547   }
3548   for(i=0; i<argc; i++){
3549     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
3550       /* If any of the constraints have a NULL value, then return no rows.
3551       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
3552       pCur->mnValue = 1;
3553       pCur->mxValue = 0;
3554       break;
3555     }
3556   }
3557   if( idxNum & 8 ){
3558     pCur->isDesc = 1;
3559     pCur->iValue = pCur->mxValue;
3560     if( pCur->iStep>0 ){
3561       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
3562     }
3563   }else{
3564     pCur->isDesc = 0;
3565     pCur->iValue = pCur->mnValue;
3566   }
3567   pCur->iRowid = 1;
3568   return SQLITE_OK;
3569 }
3570 
3571 /*
3572 ** SQLite will invoke this method one or more times while planning a query
3573 ** that uses the generate_series virtual table.  This routine needs to create
3574 ** a query plan for each invocation and compute an estimated cost for that
3575 ** plan.
3576 **
3577 ** In this implementation idxNum is used to represent the
3578 ** query plan.  idxStr is unused.
3579 **
3580 ** The query plan is represented by bits in idxNum:
3581 **
3582 **  (1)  start = $value  -- constraint exists
3583 **  (2)  stop = $value   -- constraint exists
3584 **  (4)  step = $value   -- constraint exists
3585 **  (8)  output in descending order
3586 */
3587 static int seriesBestIndex(
3588   sqlite3_vtab *pVTab,
3589   sqlite3_index_info *pIdxInfo
3590 ){
3591   int i, j;              /* Loop over constraints */
3592   int idxNum = 0;        /* The query plan bitmask */
3593   int bStartSeen = 0;    /* EQ constraint seen on the START column */
3594   int unusableMask = 0;  /* Mask of unusable constraints */
3595   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
3596   int aIdx[3];           /* Constraints on start, stop, and step */
3597   const struct sqlite3_index_constraint *pConstraint;
3598 
3599   /* This implementation assumes that the start, stop, and step columns
3600   ** are the last three columns in the virtual table. */
3601   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
3602   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
3603 
3604   aIdx[0] = aIdx[1] = aIdx[2] = -1;
3605   pConstraint = pIdxInfo->aConstraint;
3606   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3607     int iCol;    /* 0 for start, 1 for stop, 2 for step */
3608     int iMask;   /* bitmask for those column */
3609     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
3610     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
3611     assert( iCol>=0 && iCol<=2 );
3612     iMask = 1 << iCol;
3613     if( iCol==0 ) bStartSeen = 1;
3614     if( pConstraint->usable==0 ){
3615       unusableMask |=  iMask;
3616       continue;
3617     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
3618       idxNum |= iMask;
3619       aIdx[iCol] = i;
3620     }
3621   }
3622   for(i=0; i<3; i++){
3623     if( (j = aIdx[i])>=0 ){
3624       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
3625       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
3626     }
3627   }
3628   /* The current generate_column() implementation requires at least one
3629   ** argument (the START value).  Legacy versions assumed START=0 if the
3630   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
3631   ** to obtain the legacy behavior */
3632 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
3633   if( !bStartSeen ){
3634     sqlite3_free(pVTab->zErrMsg);
3635     pVTab->zErrMsg = sqlite3_mprintf(
3636         "first argument to \"generate_series()\" missing or unusable");
3637     return SQLITE_ERROR;
3638   }
3639 #endif
3640   if( (unusableMask & ~idxNum)!=0 ){
3641     /* The start, stop, and step columns are inputs.  Therefore if there
3642     ** are unusable constraints on any of start, stop, or step then
3643     ** this plan is unusable */
3644     return SQLITE_CONSTRAINT;
3645   }
3646   if( (idxNum & 3)==3 ){
3647     /* Both start= and stop= boundaries are available.  This is the
3648     ** the preferred case */
3649     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
3650     pIdxInfo->estimatedRows = 1000;
3651     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
3652       if( pIdxInfo->aOrderBy[0].desc ){
3653         idxNum |= 8;
3654       }else{
3655         idxNum |= 16;
3656       }
3657       pIdxInfo->orderByConsumed = 1;
3658     }
3659   }else{
3660     /* If either boundary is missing, we have to generate a huge span
3661     ** of numbers.  Make this case very expensive so that the query
3662     ** planner will work hard to avoid it. */
3663     pIdxInfo->estimatedRows = 2147483647;
3664   }
3665   pIdxInfo->idxNum = idxNum;
3666   return SQLITE_OK;
3667 }
3668 
3669 /*
3670 ** This following structure defines all the methods for the
3671 ** generate_series virtual table.
3672 */
3673 static sqlite3_module seriesModule = {
3674   0,                         /* iVersion */
3675   0,                         /* xCreate */
3676   seriesConnect,             /* xConnect */
3677   seriesBestIndex,           /* xBestIndex */
3678   seriesDisconnect,          /* xDisconnect */
3679   0,                         /* xDestroy */
3680   seriesOpen,                /* xOpen - open a cursor */
3681   seriesClose,               /* xClose - close a cursor */
3682   seriesFilter,              /* xFilter - configure scan constraints */
3683   seriesNext,                /* xNext - advance a cursor */
3684   seriesEof,                 /* xEof - check for end of scan */
3685   seriesColumn,              /* xColumn - read data */
3686   seriesRowid,               /* xRowid - read data */
3687   0,                         /* xUpdate */
3688   0,                         /* xBegin */
3689   0,                         /* xSync */
3690   0,                         /* xCommit */
3691   0,                         /* xRollback */
3692   0,                         /* xFindMethod */
3693   0,                         /* xRename */
3694   0,                         /* xSavepoint */
3695   0,                         /* xRelease */
3696   0,                         /* xRollbackTo */
3697   0                          /* xShadowName */
3698 };
3699 
3700 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3701 
3702 #ifdef _WIN32
3703 
3704 #endif
3705 int sqlite3_series_init(
3706   sqlite3 *db,
3707   char **pzErrMsg,
3708   const sqlite3_api_routines *pApi
3709 ){
3710   int rc = SQLITE_OK;
3711   SQLITE_EXTENSION_INIT2(pApi);
3712 #ifndef SQLITE_OMIT_VIRTUALTABLE
3713   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
3714     *pzErrMsg = sqlite3_mprintf(
3715         "generate_series() requires SQLite 3.8.12 or later");
3716     return SQLITE_ERROR;
3717   }
3718   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
3719 #endif
3720   return rc;
3721 }
3722 
3723 /************************* End ../ext/misc/series.c ********************/
3724 /************************* Begin ../ext/misc/regexp.c ******************/
3725 /*
3726 ** 2012-11-13
3727 **
3728 ** The author disclaims copyright to this source code.  In place of
3729 ** a legal notice, here is a blessing:
3730 **
3731 **    May you do good and not evil.
3732 **    May you find forgiveness for yourself and forgive others.
3733 **    May you share freely, never taking more than you give.
3734 **
3735 ******************************************************************************
3736 **
3737 ** The code in this file implements a compact but reasonably
3738 ** efficient regular-expression matcher for posix extended regular
3739 ** expressions against UTF8 text.
3740 **
3741 ** This file is an SQLite extension.  It registers a single function
3742 ** named "regexp(A,B)" where A is the regular expression and B is the
3743 ** string to be matched.  By registering this function, SQLite will also
3744 ** then implement the "B regexp A" operator.  Note that with the function
3745 ** the regular expression comes first, but with the operator it comes
3746 ** second.
3747 **
3748 **  The following regular expression syntax is supported:
3749 **
3750 **     X*      zero or more occurrences of X
3751 **     X+      one or more occurrences of X
3752 **     X?      zero or one occurrences of X
3753 **     X{p,q}  between p and q occurrences of X
3754 **     (X)     match X
3755 **     X|Y     X or Y
3756 **     ^X      X occurring at the beginning of the string
3757 **     X$      X occurring at the end of the string
3758 **     .       Match any single character
3759 **     \c      Character c where c is one of \{}()[]|*+?.
3760 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
3761 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
3762 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
3763 **     [abc]   Any single character from the set abc
3764 **     [^abc]  Any single character not in the set abc
3765 **     [a-z]   Any single character in the range a-z
3766 **     [^a-z]  Any single character not in the range a-z
3767 **     \b      Word boundary
3768 **     \w      Word character.  [A-Za-z0-9_]
3769 **     \W      Non-word character
3770 **     \d      Digit
3771 **     \D      Non-digit
3772 **     \s      Whitespace character
3773 **     \S      Non-whitespace character
3774 **
3775 ** A nondeterministic finite automaton (NFA) is used for matching, so the
3776 ** performance is bounded by O(N*M) where N is the size of the regular
3777 ** expression and M is the size of the input string.  The matcher never
3778 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
3779 ** to p copies of X following by q-p copies of X? and that the size of the
3780 ** regular expression in the O(N*M) performance bound is computed after
3781 ** this expansion.
3782 */
3783 #include <string.h>
3784 #include <stdlib.h>
3785 /* #include "sqlite3ext.h" */
3786 SQLITE_EXTENSION_INIT1
3787 
3788 /*
3789 ** The following #defines change the names of some functions implemented in
3790 ** this file to prevent name collisions with C-library functions of the
3791 ** same name.
3792 */
3793 #define re_match   sqlite3re_match
3794 #define re_compile sqlite3re_compile
3795 #define re_free    sqlite3re_free
3796 
3797 /* The end-of-input character */
3798 #define RE_EOF            0    /* End of input */
3799 
3800 /* The NFA is implemented as sequence of opcodes taken from the following
3801 ** set.  Each opcode has a single integer argument.
3802 */
3803 #define RE_OP_MATCH       1    /* Match the one character in the argument */
3804 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
3805 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
3806 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
3807 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
3808 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
3809 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
3810 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
3811 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
3812 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
3813 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
3814 #define RE_OP_NOTWORD    12    /* Not a perl word character */
3815 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
3816 #define RE_OP_NOTDIGIT   14    /* Not a digit */
3817 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
3818 #define RE_OP_NOTSPACE   16    /* Not a digit */
3819 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
3820 
3821 /* Each opcode is a "state" in the NFA */
3822 typedef unsigned short ReStateNumber;
3823 
3824 /* Because this is an NFA and not a DFA, multiple states can be active at
3825 ** once.  An instance of the following object records all active states in
3826 ** the NFA.  The implementation is optimized for the common case where the
3827 ** number of actives states is small.
3828 */
3829 typedef struct ReStateSet {
3830   unsigned nState;            /* Number of current states */
3831   ReStateNumber *aState;      /* Current states */
3832 } ReStateSet;
3833 
3834 /* An input string read one character at a time.
3835 */
3836 typedef struct ReInput ReInput;
3837 struct ReInput {
3838   const unsigned char *z;  /* All text */
3839   int i;                   /* Next byte to read */
3840   int mx;                  /* EOF when i>=mx */
3841 };
3842 
3843 /* A compiled NFA (or an NFA that is in the process of being compiled) is
3844 ** an instance of the following object.
3845 */
3846 typedef struct ReCompiled ReCompiled;
3847 struct ReCompiled {
3848   ReInput sIn;                /* Regular expression text */
3849   const char *zErr;           /* Error message to return */
3850   char *aOp;                  /* Operators for the virtual machine */
3851   int *aArg;                  /* Arguments to each operator */
3852   unsigned (*xNextChar)(ReInput*);  /* Next character function */
3853   unsigned char zInit[12];    /* Initial text to match */
3854   int nInit;                  /* Number of characters in zInit */
3855   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
3856   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
3857 };
3858 
3859 /* Add a state to the given state set if it is not already there */
3860 static void re_add_state(ReStateSet *pSet, int newState){
3861   unsigned i;
3862   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
3863   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
3864 }
3865 
3866 /* Extract the next unicode character from *pzIn and return it.  Advance
3867 ** *pzIn to the first byte past the end of the character returned.  To
3868 ** be clear:  this routine converts utf8 to unicode.  This routine is
3869 ** optimized for the common case where the next character is a single byte.
3870 */
3871 static unsigned re_next_char(ReInput *p){
3872   unsigned c;
3873   if( p->i>=p->mx ) return 0;
3874   c = p->z[p->i++];
3875   if( c>=0x80 ){
3876     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
3877       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
3878       if( c<0x80 ) c = 0xfffd;
3879     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
3880            && (p->z[p->i+1]&0xc0)==0x80 ){
3881       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
3882       p->i += 2;
3883       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
3884     }else if( (c&0xf8)==0xf0 && p->i+3<p->mx && (p->z[p->i]&0xc0)==0x80
3885            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
3886       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
3887                        | (p->z[p->i+2]&0x3f);
3888       p->i += 3;
3889       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
3890     }else{
3891       c = 0xfffd;
3892     }
3893   }
3894   return c;
3895 }
3896 static unsigned re_next_char_nocase(ReInput *p){
3897   unsigned c = re_next_char(p);
3898   if( c>='A' && c<='Z' ) c += 'a' - 'A';
3899   return c;
3900 }
3901 
3902 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
3903 static int re_word_char(int c){
3904   return (c>='0' && c<='9') || (c>='a' && c<='z')
3905       || (c>='A' && c<='Z') || c=='_';
3906 }
3907 
3908 /* Return true if c is a "digit" character:  [0-9] */
3909 static int re_digit_char(int c){
3910   return (c>='0' && c<='9');
3911 }
3912 
3913 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
3914 static int re_space_char(int c){
3915   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
3916 }
3917 
3918 /* Run a compiled regular expression on the zero-terminated input
3919 ** string zIn[].  Return true on a match and false if there is no match.
3920 */
3921 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
3922   ReStateSet aStateSet[2], *pThis, *pNext;
3923   ReStateNumber aSpace[100];
3924   ReStateNumber *pToFree;
3925   unsigned int i = 0;
3926   unsigned int iSwap = 0;
3927   int c = RE_EOF+1;
3928   int cPrev = 0;
3929   int rc = 0;
3930   ReInput in;
3931 
3932   in.z = zIn;
3933   in.i = 0;
3934   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
3935 
3936   /* Look for the initial prefix match, if there is one. */
3937   if( pRe->nInit ){
3938     unsigned char x = pRe->zInit[0];
3939     while( in.i+pRe->nInit<=in.mx
3940      && (zIn[in.i]!=x ||
3941          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
3942     ){
3943       in.i++;
3944     }
3945     if( in.i+pRe->nInit>in.mx ) return 0;
3946   }
3947 
3948   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
3949     pToFree = 0;
3950     aStateSet[0].aState = aSpace;
3951   }else{
3952     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
3953     if( pToFree==0 ) return -1;
3954     aStateSet[0].aState = pToFree;
3955   }
3956   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
3957   pNext = &aStateSet[1];
3958   pNext->nState = 0;
3959   re_add_state(pNext, 0);
3960   while( c!=RE_EOF && pNext->nState>0 ){
3961     cPrev = c;
3962     c = pRe->xNextChar(&in);
3963     pThis = pNext;
3964     pNext = &aStateSet[iSwap];
3965     iSwap = 1 - iSwap;
3966     pNext->nState = 0;
3967     for(i=0; i<pThis->nState; i++){
3968       int x = pThis->aState[i];
3969       switch( pRe->aOp[x] ){
3970         case RE_OP_MATCH: {
3971           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
3972           break;
3973         }
3974         case RE_OP_ANY: {
3975           if( c!=0 ) re_add_state(pNext, x+1);
3976           break;
3977         }
3978         case RE_OP_WORD: {
3979           if( re_word_char(c) ) re_add_state(pNext, x+1);
3980           break;
3981         }
3982         case RE_OP_NOTWORD: {
3983           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
3984           break;
3985         }
3986         case RE_OP_DIGIT: {
3987           if( re_digit_char(c) ) re_add_state(pNext, x+1);
3988           break;
3989         }
3990         case RE_OP_NOTDIGIT: {
3991           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
3992           break;
3993         }
3994         case RE_OP_SPACE: {
3995           if( re_space_char(c) ) re_add_state(pNext, x+1);
3996           break;
3997         }
3998         case RE_OP_NOTSPACE: {
3999           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
4000           break;
4001         }
4002         case RE_OP_BOUNDARY: {
4003           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
4004           break;
4005         }
4006         case RE_OP_ANYSTAR: {
4007           re_add_state(pNext, x);
4008           re_add_state(pThis, x+1);
4009           break;
4010         }
4011         case RE_OP_FORK: {
4012           re_add_state(pThis, x+pRe->aArg[x]);
4013           re_add_state(pThis, x+1);
4014           break;
4015         }
4016         case RE_OP_GOTO: {
4017           re_add_state(pThis, x+pRe->aArg[x]);
4018           break;
4019         }
4020         case RE_OP_ACCEPT: {
4021           rc = 1;
4022           goto re_match_end;
4023         }
4024         case RE_OP_CC_EXC: {
4025           if( c==0 ) break;
4026           /* fall-through */ goto re_op_cc_inc;
4027         }
4028         case RE_OP_CC_INC: re_op_cc_inc: {
4029           int j = 1;
4030           int n = pRe->aArg[x];
4031           int hit = 0;
4032           for(j=1; j>0 && j<n; j++){
4033             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
4034               if( pRe->aArg[x+j]==c ){
4035                 hit = 1;
4036                 j = -1;
4037               }
4038             }else{
4039               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
4040                 hit = 1;
4041                 j = -1;
4042               }else{
4043                 j++;
4044               }
4045             }
4046           }
4047           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
4048           if( hit ) re_add_state(pNext, x+n);
4049           break;
4050         }
4051       }
4052     }
4053   }
4054   for(i=0; i<pNext->nState; i++){
4055     if( pRe->aOp[pNext->aState[i]]==RE_OP_ACCEPT ){ rc = 1; break; }
4056   }
4057 re_match_end:
4058   sqlite3_free(pToFree);
4059   return rc;
4060 }
4061 
4062 /* Resize the opcode and argument arrays for an RE under construction.
4063 */
4064 static int re_resize(ReCompiled *p, int N){
4065   char *aOp;
4066   int *aArg;
4067   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
4068   if( aOp==0 ) return 1;
4069   p->aOp = aOp;
4070   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
4071   if( aArg==0 ) return 1;
4072   p->aArg = aArg;
4073   p->nAlloc = N;
4074   return 0;
4075 }
4076 
4077 /* Insert a new opcode and argument into an RE under construction.  The
4078 ** insertion point is just prior to existing opcode iBefore.
4079 */
4080 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
4081   int i;
4082   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
4083   for(i=p->nState; i>iBefore; i--){
4084     p->aOp[i] = p->aOp[i-1];
4085     p->aArg[i] = p->aArg[i-1];
4086   }
4087   p->nState++;
4088   p->aOp[iBefore] = (char)op;
4089   p->aArg[iBefore] = arg;
4090   return iBefore;
4091 }
4092 
4093 /* Append a new opcode and argument to the end of the RE under construction.
4094 */
4095 static int re_append(ReCompiled *p, int op, int arg){
4096   return re_insert(p, p->nState, op, arg);
4097 }
4098 
4099 /* Make a copy of N opcodes starting at iStart onto the end of the RE
4100 ** under construction.
4101 */
4102 static void re_copy(ReCompiled *p, int iStart, int N){
4103   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
4104   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
4105   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
4106   p->nState += N;
4107 }
4108 
4109 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
4110 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
4111 ** c is not a hex digit *pV is unchanged.
4112 */
4113 static int re_hex(int c, int *pV){
4114   if( c>='0' && c<='9' ){
4115     c -= '0';
4116   }else if( c>='a' && c<='f' ){
4117     c -= 'a' - 10;
4118   }else if( c>='A' && c<='F' ){
4119     c -= 'A' - 10;
4120   }else{
4121     return 0;
4122   }
4123   *pV = (*pV)*16 + (c & 0xff);
4124   return 1;
4125 }
4126 
4127 /* A backslash character has been seen, read the next character and
4128 ** return its interpretation.
4129 */
4130 static unsigned re_esc_char(ReCompiled *p){
4131   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
4132   static const char zTrans[] = "\a\f\n\r\t\v";
4133   int i, v = 0;
4134   char c;
4135   if( p->sIn.i>=p->sIn.mx ) return 0;
4136   c = p->sIn.z[p->sIn.i];
4137   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
4138     const unsigned char *zIn = p->sIn.z + p->sIn.i;
4139     if( re_hex(zIn[1],&v)
4140      && re_hex(zIn[2],&v)
4141      && re_hex(zIn[3],&v)
4142      && re_hex(zIn[4],&v)
4143     ){
4144       p->sIn.i += 5;
4145       return v;
4146     }
4147   }
4148   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
4149     const unsigned char *zIn = p->sIn.z + p->sIn.i;
4150     if( re_hex(zIn[1],&v)
4151      && re_hex(zIn[2],&v)
4152     ){
4153       p->sIn.i += 3;
4154       return v;
4155     }
4156   }
4157   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
4158   if( zEsc[i] ){
4159     if( i<6 ) c = zTrans[i];
4160     p->sIn.i++;
4161   }else{
4162     p->zErr = "unknown \\ escape";
4163   }
4164   return c;
4165 }
4166 
4167 /* Forward declaration */
4168 static const char *re_subcompile_string(ReCompiled*);
4169 
4170 /* Peek at the next byte of input */
4171 static unsigned char rePeek(ReCompiled *p){
4172   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
4173 }
4174 
4175 /* Compile RE text into a sequence of opcodes.  Continue up to the
4176 ** first unmatched ")" character, then return.  If an error is found,
4177 ** return a pointer to the error message string.
4178 */
4179 static const char *re_subcompile_re(ReCompiled *p){
4180   const char *zErr;
4181   int iStart, iEnd, iGoto;
4182   iStart = p->nState;
4183   zErr = re_subcompile_string(p);
4184   if( zErr ) return zErr;
4185   while( rePeek(p)=='|' ){
4186     iEnd = p->nState;
4187     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
4188     iGoto = re_append(p, RE_OP_GOTO, 0);
4189     p->sIn.i++;
4190     zErr = re_subcompile_string(p);
4191     if( zErr ) return zErr;
4192     p->aArg[iGoto] = p->nState - iGoto;
4193   }
4194   return 0;
4195 }
4196 
4197 /* Compile an element of regular expression text (anything that can be
4198 ** an operand to the "|" operator).  Return NULL on success or a pointer
4199 ** to the error message if there is a problem.
4200 */
4201 static const char *re_subcompile_string(ReCompiled *p){
4202   int iPrev = -1;
4203   int iStart;
4204   unsigned c;
4205   const char *zErr;
4206   while( (c = p->xNextChar(&p->sIn))!=0 ){
4207     iStart = p->nState;
4208     switch( c ){
4209       case '|':
4210       case '$':
4211       case ')': {
4212         p->sIn.i--;
4213         return 0;
4214       }
4215       case '(': {
4216         zErr = re_subcompile_re(p);
4217         if( zErr ) return zErr;
4218         if( rePeek(p)!=')' ) return "unmatched '('";
4219         p->sIn.i++;
4220         break;
4221       }
4222       case '.': {
4223         if( rePeek(p)=='*' ){
4224           re_append(p, RE_OP_ANYSTAR, 0);
4225           p->sIn.i++;
4226         }else{
4227           re_append(p, RE_OP_ANY, 0);
4228         }
4229         break;
4230       }
4231       case '*': {
4232         if( iPrev<0 ) return "'*' without operand";
4233         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
4234         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
4235         break;
4236       }
4237       case '+': {
4238         if( iPrev<0 ) return "'+' without operand";
4239         re_append(p, RE_OP_FORK, iPrev - p->nState);
4240         break;
4241       }
4242       case '?': {
4243         if( iPrev<0 ) return "'?' without operand";
4244         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
4245         break;
4246       }
4247       case '{': {
4248         int m = 0, n = 0;
4249         int sz, j;
4250         if( iPrev<0 ) return "'{m,n}' without operand";
4251         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
4252         n = m;
4253         if( c==',' ){
4254           p->sIn.i++;
4255           n = 0;
4256           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
4257         }
4258         if( c!='}' ) return "unmatched '{'";
4259         if( n>0 && n<m ) return "n less than m in '{m,n}'";
4260         p->sIn.i++;
4261         sz = p->nState - iPrev;
4262         if( m==0 ){
4263           if( n==0 ) return "both m and n are zero in '{m,n}'";
4264           re_insert(p, iPrev, RE_OP_FORK, sz+1);
4265           n--;
4266         }else{
4267           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
4268         }
4269         for(j=m; j<n; j++){
4270           re_append(p, RE_OP_FORK, sz+1);
4271           re_copy(p, iPrev, sz);
4272         }
4273         if( n==0 && m>0 ){
4274           re_append(p, RE_OP_FORK, -sz);
4275         }
4276         break;
4277       }
4278       case '[': {
4279         int iFirst = p->nState;
4280         if( rePeek(p)=='^' ){
4281           re_append(p, RE_OP_CC_EXC, 0);
4282           p->sIn.i++;
4283         }else{
4284           re_append(p, RE_OP_CC_INC, 0);
4285         }
4286         while( (c = p->xNextChar(&p->sIn))!=0 ){
4287           if( c=='[' && rePeek(p)==':' ){
4288             return "POSIX character classes not supported";
4289           }
4290           if( c=='\\' ) c = re_esc_char(p);
4291           if( rePeek(p)=='-' ){
4292             re_append(p, RE_OP_CC_RANGE, c);
4293             p->sIn.i++;
4294             c = p->xNextChar(&p->sIn);
4295             if( c=='\\' ) c = re_esc_char(p);
4296             re_append(p, RE_OP_CC_RANGE, c);
4297           }else{
4298             re_append(p, RE_OP_CC_VALUE, c);
4299           }
4300           if( rePeek(p)==']' ){ p->sIn.i++; break; }
4301         }
4302         if( c==0 ) return "unclosed '['";
4303         p->aArg[iFirst] = p->nState - iFirst;
4304         break;
4305       }
4306       case '\\': {
4307         int specialOp = 0;
4308         switch( rePeek(p) ){
4309           case 'b': specialOp = RE_OP_BOUNDARY;   break;
4310           case 'd': specialOp = RE_OP_DIGIT;      break;
4311           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
4312           case 's': specialOp = RE_OP_SPACE;      break;
4313           case 'S': specialOp = RE_OP_NOTSPACE;   break;
4314           case 'w': specialOp = RE_OP_WORD;       break;
4315           case 'W': specialOp = RE_OP_NOTWORD;    break;
4316         }
4317         if( specialOp ){
4318           p->sIn.i++;
4319           re_append(p, specialOp, 0);
4320         }else{
4321           c = re_esc_char(p);
4322           re_append(p, RE_OP_MATCH, c);
4323         }
4324         break;
4325       }
4326       default: {
4327         re_append(p, RE_OP_MATCH, c);
4328         break;
4329       }
4330     }
4331     iPrev = iStart;
4332   }
4333   return 0;
4334 }
4335 
4336 /* Free and reclaim all the memory used by a previously compiled
4337 ** regular expression.  Applications should invoke this routine once
4338 ** for every call to re_compile() to avoid memory leaks.
4339 */
4340 static void re_free(ReCompiled *pRe){
4341   if( pRe ){
4342     sqlite3_free(pRe->aOp);
4343     sqlite3_free(pRe->aArg);
4344     sqlite3_free(pRe);
4345   }
4346 }
4347 
4348 /*
4349 ** Compile a textual regular expression in zIn[] into a compiled regular
4350 ** expression suitable for us by re_match() and return a pointer to the
4351 ** compiled regular expression in *ppRe.  Return NULL on success or an
4352 ** error message if something goes wrong.
4353 */
4354 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
4355   ReCompiled *pRe;
4356   const char *zErr;
4357   int i, j;
4358 
4359   *ppRe = 0;
4360   pRe = sqlite3_malloc( sizeof(*pRe) );
4361   if( pRe==0 ){
4362     return "out of memory";
4363   }
4364   memset(pRe, 0, sizeof(*pRe));
4365   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
4366   if( re_resize(pRe, 30) ){
4367     re_free(pRe);
4368     return "out of memory";
4369   }
4370   if( zIn[0]=='^' ){
4371     zIn++;
4372   }else{
4373     re_append(pRe, RE_OP_ANYSTAR, 0);
4374   }
4375   pRe->sIn.z = (unsigned char*)zIn;
4376   pRe->sIn.i = 0;
4377   pRe->sIn.mx = (int)strlen(zIn);
4378   zErr = re_subcompile_re(pRe);
4379   if( zErr ){
4380     re_free(pRe);
4381     return zErr;
4382   }
4383   if( rePeek(pRe)=='$' && pRe->sIn.i+1>=pRe->sIn.mx ){
4384     re_append(pRe, RE_OP_MATCH, RE_EOF);
4385     re_append(pRe, RE_OP_ACCEPT, 0);
4386     *ppRe = pRe;
4387   }else if( pRe->sIn.i>=pRe->sIn.mx ){
4388     re_append(pRe, RE_OP_ACCEPT, 0);
4389     *ppRe = pRe;
4390   }else{
4391     re_free(pRe);
4392     return "unrecognized character";
4393   }
4394 
4395   /* The following is a performance optimization.  If the regex begins with
4396   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
4397   ** one or more matching characters, enter those matching characters into
4398   ** zInit[].  The re_match() routine can then search ahead in the input
4399   ** string looking for the initial match without having to run the whole
4400   ** regex engine over the string.  Do not worry able trying to match
4401   ** unicode characters beyond plane 0 - those are very rare and this is
4402   ** just an optimization. */
4403   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
4404     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
4405       unsigned x = pRe->aArg[i];
4406       if( x<=127 ){
4407         pRe->zInit[j++] = (unsigned char)x;
4408       }else if( x<=0xfff ){
4409         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
4410         pRe->zInit[j++] = 0x80 | (x&0x3f);
4411       }else if( x<=0xffff ){
4412         pRe->zInit[j++] = (unsigned char)(0xd0 | (x>>12));
4413         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
4414         pRe->zInit[j++] = 0x80 | (x&0x3f);
4415       }else{
4416         break;
4417       }
4418     }
4419     if( j>0 && pRe->zInit[j-1]==0 ) j--;
4420     pRe->nInit = j;
4421   }
4422   return pRe->zErr;
4423 }
4424 
4425 /*
4426 ** Implementation of the regexp() SQL function.  This function implements
4427 ** the build-in REGEXP operator.  The first argument to the function is the
4428 ** pattern and the second argument is the string.  So, the SQL statements:
4429 **
4430 **       A REGEXP B
4431 **
4432 ** is implemented as regexp(B,A).
4433 */
4434 static void re_sql_func(
4435   sqlite3_context *context,
4436   int argc,
4437   sqlite3_value **argv
4438 ){
4439   ReCompiled *pRe;          /* Compiled regular expression */
4440   const char *zPattern;     /* The regular expression */
4441   const unsigned char *zStr;/* String being searched */
4442   const char *zErr;         /* Compile error message */
4443   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
4444 
4445   (void)argc;  /* Unused */
4446   pRe = sqlite3_get_auxdata(context, 0);
4447   if( pRe==0 ){
4448     zPattern = (const char*)sqlite3_value_text(argv[0]);
4449     if( zPattern==0 ) return;
4450     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
4451     if( zErr ){
4452       re_free(pRe);
4453       sqlite3_result_error(context, zErr, -1);
4454       return;
4455     }
4456     if( pRe==0 ){
4457       sqlite3_result_error_nomem(context);
4458       return;
4459     }
4460     setAux = 1;
4461   }
4462   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
4463   if( zStr!=0 ){
4464     sqlite3_result_int(context, re_match(pRe, zStr, -1));
4465   }
4466   if( setAux ){
4467     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
4468   }
4469 }
4470 
4471 /*
4472 ** Invoke this routine to register the regexp() function with the
4473 ** SQLite database connection.
4474 */
4475 #ifdef _WIN32
4476 
4477 #endif
4478 int sqlite3_regexp_init(
4479   sqlite3 *db,
4480   char **pzErrMsg,
4481   const sqlite3_api_routines *pApi
4482 ){
4483   int rc = SQLITE_OK;
4484   SQLITE_EXTENSION_INIT2(pApi);
4485   (void)pzErrMsg;  /* Unused */
4486   rc = sqlite3_create_function(db, "regexp", 2,
4487                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4488                             0, re_sql_func, 0, 0);
4489   if( rc==SQLITE_OK ){
4490     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
4491     ** of regexp(PATTERN,STRING). */
4492     rc = sqlite3_create_function(db, "regexpi", 2,
4493                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4494                             (void*)db, re_sql_func, 0, 0);
4495   }
4496   return rc;
4497 }
4498 
4499 /************************* End ../ext/misc/regexp.c ********************/
4500 #ifndef SQLITE_SHELL_WASM_MODE
4501 /************************* Begin ../ext/misc/fileio.c ******************/
4502 /*
4503 ** 2014-06-13
4504 **
4505 ** The author disclaims copyright to this source code.  In place of
4506 ** a legal notice, here is a blessing:
4507 **
4508 **    May you do good and not evil.
4509 **    May you find forgiveness for yourself and forgive others.
4510 **    May you share freely, never taking more than you give.
4511 **
4512 ******************************************************************************
4513 **
4514 ** This SQLite extension implements SQL functions readfile() and
4515 ** writefile(), and eponymous virtual type "fsdir".
4516 **
4517 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
4518 **
4519 **   If neither of the optional arguments is present, then this UDF
4520 **   function writes blob DATA to file FILE. If successful, the number
4521 **   of bytes written is returned. If an error occurs, NULL is returned.
4522 **
4523 **   If the first option argument - MODE - is present, then it must
4524 **   be passed an integer value that corresponds to a POSIX mode
4525 **   value (file type + permissions, as returned in the stat.st_mode
4526 **   field by the stat() system call). Three types of files may
4527 **   be written/created:
4528 **
4529 **     regular files:  (mode & 0170000)==0100000
4530 **     symbolic links: (mode & 0170000)==0120000
4531 **     directories:    (mode & 0170000)==0040000
4532 **
4533 **   For a directory, the DATA is ignored. For a symbolic link, it is
4534 **   interpreted as text and used as the target of the link. For a
4535 **   regular file, it is interpreted as a blob and written into the
4536 **   named file. Regardless of the type of file, its permissions are
4537 **   set to (mode & 0777) before returning.
4538 **
4539 **   If the optional MTIME argument is present, then it is interpreted
4540 **   as an integer - the number of seconds since the unix epoch. The
4541 **   modification-time of the target file is set to this value before
4542 **   returning.
4543 **
4544 **   If three or more arguments are passed to this function and an
4545 **   error is encountered, an exception is raised.
4546 **
4547 ** READFILE(FILE):
4548 **
4549 **   Read and return the contents of file FILE (type blob) from disk.
4550 **
4551 ** FSDIR:
4552 **
4553 **   Used as follows:
4554 **
4555 **     SELECT * FROM fsdir($path [, $dir]);
4556 **
4557 **   Parameter $path is an absolute or relative pathname. If the file that it
4558 **   refers to does not exist, it is an error. If the path refers to a regular
4559 **   file or symbolic link, it returns a single row. Or, if the path refers
4560 **   to a directory, it returns one row for the directory, and one row for each
4561 **   file within the hierarchy rooted at $path.
4562 **
4563 **   Each row has the following columns:
4564 **
4565 **     name:  Path to file or directory (text value).
4566 **     mode:  Value of stat.st_mode for directory entry (an integer).
4567 **     mtime: Value of stat.st_mtime for directory entry (an integer).
4568 **     data:  For a regular file, a blob containing the file data. For a
4569 **            symlink, a text value containing the text of the link. For a
4570 **            directory, NULL.
4571 **
4572 **   If a non-NULL value is specified for the optional $dir parameter and
4573 **   $path is a relative path, then $path is interpreted relative to $dir.
4574 **   And the paths returned in the "name" column of the table are also
4575 **   relative to directory $dir.
4576 **
4577 ** Notes on building this extension for Windows:
4578 **   Unless linked statically with the SQLite library, a preprocessor
4579 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
4580 **   DLL form of this extension for WIN32. See its use below for details.
4581 */
4582 /* #include "sqlite3ext.h" */
4583 SQLITE_EXTENSION_INIT1
4584 #include <stdio.h>
4585 #include <string.h>
4586 #include <assert.h>
4587 
4588 #include <sys/types.h>
4589 #include <sys/stat.h>
4590 #include <fcntl.h>
4591 #if !defined(_WIN32) && !defined(WIN32)
4592 #  include <unistd.h>
4593 #  include <dirent.h>
4594 #  include <utime.h>
4595 #  include <sys/time.h>
4596 #else
4597 #  include "windows.h"
4598 #  include <io.h>
4599 #  include <direct.h>
4600 /* #  include "test_windirent.h" */
4601 #  define dirent DIRENT
4602 #  ifndef chmod
4603 #    define chmod _chmod
4604 #  endif
4605 #  ifndef stat
4606 #    define stat _stat
4607 #  endif
4608 #  define mkdir(path,mode) _mkdir(path)
4609 #  define lstat(path,buf) stat(path,buf)
4610 #endif
4611 #include <time.h>
4612 #include <errno.h>
4613 
4614 
4615 /*
4616 ** Structure of the fsdir() table-valued function
4617 */
4618                  /*    0    1    2     3    4           5             */
4619 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
4620 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
4621 #define FSDIR_COLUMN_MODE     1     /* Access mode */
4622 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
4623 #define FSDIR_COLUMN_DATA     3     /* File content */
4624 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
4625 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
4626 
4627 
4628 /*
4629 ** Set the result stored by context ctx to a blob containing the
4630 ** contents of file zName.  Or, leave the result unchanged (NULL)
4631 ** if the file does not exist or is unreadable.
4632 **
4633 ** If the file exceeds the SQLite blob size limit, through an
4634 ** SQLITE_TOOBIG error.
4635 **
4636 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
4637 ** off of disk.
4638 */
4639 static void readFileContents(sqlite3_context *ctx, const char *zName){
4640   FILE *in;
4641   sqlite3_int64 nIn;
4642   void *pBuf;
4643   sqlite3 *db;
4644   int mxBlob;
4645 
4646   in = fopen(zName, "rb");
4647   if( in==0 ){
4648     /* File does not exist or is unreadable. Leave the result set to NULL. */
4649     return;
4650   }
4651   fseek(in, 0, SEEK_END);
4652   nIn = ftell(in);
4653   rewind(in);
4654   db = sqlite3_context_db_handle(ctx);
4655   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
4656   if( nIn>mxBlob ){
4657     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
4658     fclose(in);
4659     return;
4660   }
4661   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
4662   if( pBuf==0 ){
4663     sqlite3_result_error_nomem(ctx);
4664     fclose(in);
4665     return;
4666   }
4667   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
4668     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
4669   }else{
4670     sqlite3_result_error_code(ctx, SQLITE_IOERR);
4671     sqlite3_free(pBuf);
4672   }
4673   fclose(in);
4674 }
4675 
4676 /*
4677 ** Implementation of the "readfile(X)" SQL function.  The entire content
4678 ** of the file named X is read and returned as a BLOB.  NULL is returned
4679 ** if the file does not exist or is unreadable.
4680 */
4681 static void readfileFunc(
4682   sqlite3_context *context,
4683   int argc,
4684   sqlite3_value **argv
4685 ){
4686   const char *zName;
4687   (void)(argc);  /* Unused parameter */
4688   zName = (const char*)sqlite3_value_text(argv[0]);
4689   if( zName==0 ) return;
4690   readFileContents(context, zName);
4691 }
4692 
4693 /*
4694 ** Set the error message contained in context ctx to the results of
4695 ** vprintf(zFmt, ...).
4696 */
4697 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
4698   char *zMsg = 0;
4699   va_list ap;
4700   va_start(ap, zFmt);
4701   zMsg = sqlite3_vmprintf(zFmt, ap);
4702   sqlite3_result_error(ctx, zMsg, -1);
4703   sqlite3_free(zMsg);
4704   va_end(ap);
4705 }
4706 
4707 #if defined(_WIN32)
4708 /*
4709 ** This function is designed to convert a Win32 FILETIME structure into the
4710 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
4711 */
4712 static sqlite3_uint64 fileTimeToUnixTime(
4713   LPFILETIME pFileTime
4714 ){
4715   SYSTEMTIME epochSystemTime;
4716   ULARGE_INTEGER epochIntervals;
4717   FILETIME epochFileTime;
4718   ULARGE_INTEGER fileIntervals;
4719 
4720   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
4721   epochSystemTime.wYear = 1970;
4722   epochSystemTime.wMonth = 1;
4723   epochSystemTime.wDay = 1;
4724   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
4725   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
4726   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
4727 
4728   fileIntervals.LowPart = pFileTime->dwLowDateTime;
4729   fileIntervals.HighPart = pFileTime->dwHighDateTime;
4730 
4731   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
4732 }
4733 
4734 
4735 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
4736 #  /* To allow a standalone DLL, use this next replacement function: */
4737 #  undef sqlite3_win32_utf8_to_unicode
4738 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
4739 #
4740 LPWSTR utf8_to_utf16(const char *z){
4741   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
4742   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
4743   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
4744     return rv;
4745   sqlite3_free(rv);
4746   return 0;
4747 }
4748 #endif
4749 
4750 /*
4751 ** This function attempts to normalize the time values found in the stat()
4752 ** buffer to UTC.  This is necessary on Win32, where the runtime library
4753 ** appears to return these values as local times.
4754 */
4755 static void statTimesToUtc(
4756   const char *zPath,
4757   struct stat *pStatBuf
4758 ){
4759   HANDLE hFindFile;
4760   WIN32_FIND_DATAW fd;
4761   LPWSTR zUnicodeName;
4762   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
4763   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
4764   if( zUnicodeName ){
4765     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
4766     hFindFile = FindFirstFileW(zUnicodeName, &fd);
4767     if( hFindFile!=NULL ){
4768       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
4769       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
4770       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
4771       FindClose(hFindFile);
4772     }
4773     sqlite3_free(zUnicodeName);
4774   }
4775 }
4776 #endif
4777 
4778 /*
4779 ** This function is used in place of stat().  On Windows, special handling
4780 ** is required in order for the included time to be returned as UTC.  On all
4781 ** other systems, this function simply calls stat().
4782 */
4783 static int fileStat(
4784   const char *zPath,
4785   struct stat *pStatBuf
4786 ){
4787 #if defined(_WIN32)
4788   int rc = stat(zPath, pStatBuf);
4789   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
4790   return rc;
4791 #else
4792   return stat(zPath, pStatBuf);
4793 #endif
4794 }
4795 
4796 /*
4797 ** This function is used in place of lstat().  On Windows, special handling
4798 ** is required in order for the included time to be returned as UTC.  On all
4799 ** other systems, this function simply calls lstat().
4800 */
4801 static int fileLinkStat(
4802   const char *zPath,
4803   struct stat *pStatBuf
4804 ){
4805 #if defined(_WIN32)
4806   int rc = lstat(zPath, pStatBuf);
4807   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
4808   return rc;
4809 #else
4810   return lstat(zPath, pStatBuf);
4811 #endif
4812 }
4813 
4814 /*
4815 ** Argument zFile is the name of a file that will be created and/or written
4816 ** by SQL function writefile(). This function ensures that the directory
4817 ** zFile will be written to exists, creating it if required. The permissions
4818 ** for any path components created by this function are set in accordance
4819 ** with the current umask.
4820 **
4821 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
4822 ** SQLITE_OK is returned if the directory is successfully created, or
4823 ** SQLITE_ERROR otherwise.
4824 */
4825 static int makeDirectory(
4826   const char *zFile
4827 ){
4828   char *zCopy = sqlite3_mprintf("%s", zFile);
4829   int rc = SQLITE_OK;
4830 
4831   if( zCopy==0 ){
4832     rc = SQLITE_NOMEM;
4833   }else{
4834     int nCopy = (int)strlen(zCopy);
4835     int i = 1;
4836 
4837     while( rc==SQLITE_OK ){
4838       struct stat sStat;
4839       int rc2;
4840 
4841       for(; zCopy[i]!='/' && i<nCopy; i++);
4842       if( i==nCopy ) break;
4843       zCopy[i] = '\0';
4844 
4845       rc2 = fileStat(zCopy, &sStat);
4846       if( rc2!=0 ){
4847         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
4848       }else{
4849         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
4850       }
4851       zCopy[i] = '/';
4852       i++;
4853     }
4854 
4855     sqlite3_free(zCopy);
4856   }
4857 
4858   return rc;
4859 }
4860 
4861 /*
4862 ** This function does the work for the writefile() UDF. Refer to
4863 ** header comments at the top of this file for details.
4864 */
4865 static int writeFile(
4866   sqlite3_context *pCtx,          /* Context to return bytes written in */
4867   const char *zFile,              /* File to write */
4868   sqlite3_value *pData,           /* Data to write */
4869   mode_t mode,                    /* MODE parameter passed to writefile() */
4870   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
4871 ){
4872   if( zFile==0 ) return 1;
4873 #if !defined(_WIN32) && !defined(WIN32)
4874   if( S_ISLNK(mode) ){
4875     const char *zTo = (const char*)sqlite3_value_text(pData);
4876     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
4877   }else
4878 #endif
4879   {
4880     if( S_ISDIR(mode) ){
4881       if( mkdir(zFile, mode) ){
4882         /* The mkdir() call to create the directory failed. This might not
4883         ** be an error though - if there is already a directory at the same
4884         ** path and either the permissions already match or can be changed
4885         ** to do so using chmod(), it is not an error.  */
4886         struct stat sStat;
4887         if( errno!=EEXIST
4888          || 0!=fileStat(zFile, &sStat)
4889          || !S_ISDIR(sStat.st_mode)
4890          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
4891         ){
4892           return 1;
4893         }
4894       }
4895     }else{
4896       sqlite3_int64 nWrite = 0;
4897       const char *z;
4898       int rc = 0;
4899       FILE *out = fopen(zFile, "wb");
4900       if( out==0 ) return 1;
4901       z = (const char*)sqlite3_value_blob(pData);
4902       if( z ){
4903         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
4904         nWrite = sqlite3_value_bytes(pData);
4905         if( nWrite!=n ){
4906           rc = 1;
4907         }
4908       }
4909       fclose(out);
4910       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
4911         rc = 1;
4912       }
4913       if( rc ) return 2;
4914       sqlite3_result_int64(pCtx, nWrite);
4915     }
4916   }
4917 
4918   if( mtime>=0 ){
4919 #if defined(_WIN32)
4920 #if !SQLITE_OS_WINRT
4921     /* Windows */
4922     FILETIME lastAccess;
4923     FILETIME lastWrite;
4924     SYSTEMTIME currentTime;
4925     LONGLONG intervals;
4926     HANDLE hFile;
4927     LPWSTR zUnicodeName;
4928     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
4929 
4930     GetSystemTime(&currentTime);
4931     SystemTimeToFileTime(&currentTime, &lastAccess);
4932     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
4933     lastWrite.dwLowDateTime = (DWORD)intervals;
4934     lastWrite.dwHighDateTime = intervals >> 32;
4935     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
4936     if( zUnicodeName==0 ){
4937       return 1;
4938     }
4939     hFile = CreateFileW(
4940       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
4941       FILE_FLAG_BACKUP_SEMANTICS, NULL
4942     );
4943     sqlite3_free(zUnicodeName);
4944     if( hFile!=INVALID_HANDLE_VALUE ){
4945       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
4946       CloseHandle(hFile);
4947       return !bResult;
4948     }else{
4949       return 1;
4950     }
4951 #endif
4952 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
4953     /* Recent unix */
4954     struct timespec times[2];
4955     times[0].tv_nsec = times[1].tv_nsec = 0;
4956     times[0].tv_sec = time(0);
4957     times[1].tv_sec = mtime;
4958     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
4959       return 1;
4960     }
4961 #else
4962     /* Legacy unix */
4963     struct timeval times[2];
4964     times[0].tv_usec = times[1].tv_usec = 0;
4965     times[0].tv_sec = time(0);
4966     times[1].tv_sec = mtime;
4967     if( utimes(zFile, times) ){
4968       return 1;
4969     }
4970 #endif
4971   }
4972 
4973   return 0;
4974 }
4975 
4976 /*
4977 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
4978 ** Refer to header comments at the top of this file for details.
4979 */
4980 static void writefileFunc(
4981   sqlite3_context *context,
4982   int argc,
4983   sqlite3_value **argv
4984 ){
4985   const char *zFile;
4986   mode_t mode = 0;
4987   int res;
4988   sqlite3_int64 mtime = -1;
4989 
4990   if( argc<2 || argc>4 ){
4991     sqlite3_result_error(context,
4992         "wrong number of arguments to function writefile()", -1
4993     );
4994     return;
4995   }
4996 
4997   zFile = (const char*)sqlite3_value_text(argv[0]);
4998   if( zFile==0 ) return;
4999   if( argc>=3 ){
5000     mode = (mode_t)sqlite3_value_int(argv[2]);
5001   }
5002   if( argc==4 ){
5003     mtime = sqlite3_value_int64(argv[3]);
5004   }
5005 
5006   res = writeFile(context, zFile, argv[1], mode, mtime);
5007   if( res==1 && errno==ENOENT ){
5008     if( makeDirectory(zFile)==SQLITE_OK ){
5009       res = writeFile(context, zFile, argv[1], mode, mtime);
5010     }
5011   }
5012 
5013   if( argc>2 && res!=0 ){
5014     if( S_ISLNK(mode) ){
5015       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
5016     }else if( S_ISDIR(mode) ){
5017       ctxErrorMsg(context, "failed to create directory: %s", zFile);
5018     }else{
5019       ctxErrorMsg(context, "failed to write file: %s", zFile);
5020     }
5021   }
5022 }
5023 
5024 /*
5025 ** SQL function:   lsmode(MODE)
5026 **
5027 ** Given a numberic st_mode from stat(), convert it into a human-readable
5028 ** text string in the style of "ls -l".
5029 */
5030 static void lsModeFunc(
5031   sqlite3_context *context,
5032   int argc,
5033   sqlite3_value **argv
5034 ){
5035   int i;
5036   int iMode = sqlite3_value_int(argv[0]);
5037   char z[16];
5038   (void)argc;
5039   if( S_ISLNK(iMode) ){
5040     z[0] = 'l';
5041   }else if( S_ISREG(iMode) ){
5042     z[0] = '-';
5043   }else if( S_ISDIR(iMode) ){
5044     z[0] = 'd';
5045   }else{
5046     z[0] = '?';
5047   }
5048   for(i=0; i<3; i++){
5049     int m = (iMode >> ((2-i)*3));
5050     char *a = &z[1 + i*3];
5051     a[0] = (m & 0x4) ? 'r' : '-';
5052     a[1] = (m & 0x2) ? 'w' : '-';
5053     a[2] = (m & 0x1) ? 'x' : '-';
5054   }
5055   z[10] = '\0';
5056   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
5057 }
5058 
5059 #ifndef SQLITE_OMIT_VIRTUALTABLE
5060 
5061 /*
5062 ** Cursor type for recursively iterating through a directory structure.
5063 */
5064 typedef struct fsdir_cursor fsdir_cursor;
5065 typedef struct FsdirLevel FsdirLevel;
5066 
5067 struct FsdirLevel {
5068   DIR *pDir;                 /* From opendir() */
5069   char *zDir;                /* Name of directory (nul-terminated) */
5070 };
5071 
5072 struct fsdir_cursor {
5073   sqlite3_vtab_cursor base;  /* Base class - must be first */
5074 
5075   int nLvl;                  /* Number of entries in aLvl[] array */
5076   int iLvl;                  /* Index of current entry */
5077   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
5078 
5079   const char *zBase;
5080   int nBase;
5081 
5082   struct stat sStat;         /* Current lstat() results */
5083   char *zPath;               /* Path to current entry */
5084   sqlite3_int64 iRowid;      /* Current rowid */
5085 };
5086 
5087 typedef struct fsdir_tab fsdir_tab;
5088 struct fsdir_tab {
5089   sqlite3_vtab base;         /* Base class - must be first */
5090 };
5091 
5092 /*
5093 ** Construct a new fsdir virtual table object.
5094 */
5095 static int fsdirConnect(
5096   sqlite3 *db,
5097   void *pAux,
5098   int argc, const char *const*argv,
5099   sqlite3_vtab **ppVtab,
5100   char **pzErr
5101 ){
5102   fsdir_tab *pNew = 0;
5103   int rc;
5104   (void)pAux;
5105   (void)argc;
5106   (void)argv;
5107   (void)pzErr;
5108   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
5109   if( rc==SQLITE_OK ){
5110     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
5111     if( pNew==0 ) return SQLITE_NOMEM;
5112     memset(pNew, 0, sizeof(*pNew));
5113     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
5114   }
5115   *ppVtab = (sqlite3_vtab*)pNew;
5116   return rc;
5117 }
5118 
5119 /*
5120 ** This method is the destructor for fsdir vtab objects.
5121 */
5122 static int fsdirDisconnect(sqlite3_vtab *pVtab){
5123   sqlite3_free(pVtab);
5124   return SQLITE_OK;
5125 }
5126 
5127 /*
5128 ** Constructor for a new fsdir_cursor object.
5129 */
5130 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
5131   fsdir_cursor *pCur;
5132   (void)p;
5133   pCur = sqlite3_malloc( sizeof(*pCur) );
5134   if( pCur==0 ) return SQLITE_NOMEM;
5135   memset(pCur, 0, sizeof(*pCur));
5136   pCur->iLvl = -1;
5137   *ppCursor = &pCur->base;
5138   return SQLITE_OK;
5139 }
5140 
5141 /*
5142 ** Reset a cursor back to the state it was in when first returned
5143 ** by fsdirOpen().
5144 */
5145 static void fsdirResetCursor(fsdir_cursor *pCur){
5146   int i;
5147   for(i=0; i<=pCur->iLvl; i++){
5148     FsdirLevel *pLvl = &pCur->aLvl[i];
5149     if( pLvl->pDir ) closedir(pLvl->pDir);
5150     sqlite3_free(pLvl->zDir);
5151   }
5152   sqlite3_free(pCur->zPath);
5153   sqlite3_free(pCur->aLvl);
5154   pCur->aLvl = 0;
5155   pCur->zPath = 0;
5156   pCur->zBase = 0;
5157   pCur->nBase = 0;
5158   pCur->nLvl = 0;
5159   pCur->iLvl = -1;
5160   pCur->iRowid = 1;
5161 }
5162 
5163 /*
5164 ** Destructor for an fsdir_cursor.
5165 */
5166 static int fsdirClose(sqlite3_vtab_cursor *cur){
5167   fsdir_cursor *pCur = (fsdir_cursor*)cur;
5168 
5169   fsdirResetCursor(pCur);
5170   sqlite3_free(pCur);
5171   return SQLITE_OK;
5172 }
5173 
5174 /*
5175 ** Set the error message for the virtual table associated with cursor
5176 ** pCur to the results of vprintf(zFmt, ...).
5177 */
5178 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
5179   va_list ap;
5180   va_start(ap, zFmt);
5181   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
5182   va_end(ap);
5183 }
5184 
5185 
5186 /*
5187 ** Advance an fsdir_cursor to its next row of output.
5188 */
5189 static int fsdirNext(sqlite3_vtab_cursor *cur){
5190   fsdir_cursor *pCur = (fsdir_cursor*)cur;
5191   mode_t m = pCur->sStat.st_mode;
5192 
5193   pCur->iRowid++;
5194   if( S_ISDIR(m) ){
5195     /* Descend into this directory */
5196     int iNew = pCur->iLvl + 1;
5197     FsdirLevel *pLvl;
5198     if( iNew>=pCur->nLvl ){
5199       int nNew = iNew+1;
5200       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
5201       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
5202       if( aNew==0 ) return SQLITE_NOMEM;
5203       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
5204       pCur->aLvl = aNew;
5205       pCur->nLvl = nNew;
5206     }
5207     pCur->iLvl = iNew;
5208     pLvl = &pCur->aLvl[iNew];
5209 
5210     pLvl->zDir = pCur->zPath;
5211     pCur->zPath = 0;
5212     pLvl->pDir = opendir(pLvl->zDir);
5213     if( pLvl->pDir==0 ){
5214       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
5215       return SQLITE_ERROR;
5216     }
5217   }
5218 
5219   while( pCur->iLvl>=0 ){
5220     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
5221     struct dirent *pEntry = readdir(pLvl->pDir);
5222     if( pEntry ){
5223       if( pEntry->d_name[0]=='.' ){
5224        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
5225        if( pEntry->d_name[1]=='\0' ) continue;
5226       }
5227       sqlite3_free(pCur->zPath);
5228       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
5229       if( pCur->zPath==0 ) return SQLITE_NOMEM;
5230       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
5231         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
5232         return SQLITE_ERROR;
5233       }
5234       return SQLITE_OK;
5235     }
5236     closedir(pLvl->pDir);
5237     sqlite3_free(pLvl->zDir);
5238     pLvl->pDir = 0;
5239     pLvl->zDir = 0;
5240     pCur->iLvl--;
5241   }
5242 
5243   /* EOF */
5244   sqlite3_free(pCur->zPath);
5245   pCur->zPath = 0;
5246   return SQLITE_OK;
5247 }
5248 
5249 /*
5250 ** Return values of columns for the row at which the series_cursor
5251 ** is currently pointing.
5252 */
5253 static int fsdirColumn(
5254   sqlite3_vtab_cursor *cur,   /* The cursor */
5255   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5256   int i                       /* Which column to return */
5257 ){
5258   fsdir_cursor *pCur = (fsdir_cursor*)cur;
5259   switch( i ){
5260     case FSDIR_COLUMN_NAME: {
5261       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
5262       break;
5263     }
5264 
5265     case FSDIR_COLUMN_MODE:
5266       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
5267       break;
5268 
5269     case FSDIR_COLUMN_MTIME:
5270       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
5271       break;
5272 
5273     case FSDIR_COLUMN_DATA: {
5274       mode_t m = pCur->sStat.st_mode;
5275       if( S_ISDIR(m) ){
5276         sqlite3_result_null(ctx);
5277 #if !defined(_WIN32) && !defined(WIN32)
5278       }else if( S_ISLNK(m) ){
5279         char aStatic[64];
5280         char *aBuf = aStatic;
5281         sqlite3_int64 nBuf = 64;
5282         int n;
5283 
5284         while( 1 ){
5285           n = readlink(pCur->zPath, aBuf, nBuf);
5286           if( n<nBuf ) break;
5287           if( aBuf!=aStatic ) sqlite3_free(aBuf);
5288           nBuf = nBuf*2;
5289           aBuf = sqlite3_malloc64(nBuf);
5290           if( aBuf==0 ){
5291             sqlite3_result_error_nomem(ctx);
5292             return SQLITE_NOMEM;
5293           }
5294         }
5295 
5296         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
5297         if( aBuf!=aStatic ) sqlite3_free(aBuf);
5298 #endif
5299       }else{
5300         readFileContents(ctx, pCur->zPath);
5301       }
5302     }
5303     case FSDIR_COLUMN_PATH:
5304     default: {
5305       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
5306       ** always return their values as NULL */
5307       break;
5308     }
5309   }
5310   return SQLITE_OK;
5311 }
5312 
5313 /*
5314 ** Return the rowid for the current row. In this implementation, the
5315 ** first row returned is assigned rowid value 1, and each subsequent
5316 ** row a value 1 more than that of the previous.
5317 */
5318 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5319   fsdir_cursor *pCur = (fsdir_cursor*)cur;
5320   *pRowid = pCur->iRowid;
5321   return SQLITE_OK;
5322 }
5323 
5324 /*
5325 ** Return TRUE if the cursor has been moved off of the last
5326 ** row of output.
5327 */
5328 static int fsdirEof(sqlite3_vtab_cursor *cur){
5329   fsdir_cursor *pCur = (fsdir_cursor*)cur;
5330   return (pCur->zPath==0);
5331 }
5332 
5333 /*
5334 ** xFilter callback.
5335 **
5336 ** idxNum==1   PATH parameter only
5337 ** idxNum==2   Both PATH and DIR supplied
5338 */
5339 static int fsdirFilter(
5340   sqlite3_vtab_cursor *cur,
5341   int idxNum, const char *idxStr,
5342   int argc, sqlite3_value **argv
5343 ){
5344   const char *zDir = 0;
5345   fsdir_cursor *pCur = (fsdir_cursor*)cur;
5346   (void)idxStr;
5347   fsdirResetCursor(pCur);
5348 
5349   if( idxNum==0 ){
5350     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
5351     return SQLITE_ERROR;
5352   }
5353 
5354   assert( argc==idxNum && (argc==1 || argc==2) );
5355   zDir = (const char*)sqlite3_value_text(argv[0]);
5356   if( zDir==0 ){
5357     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
5358     return SQLITE_ERROR;
5359   }
5360   if( argc==2 ){
5361     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
5362   }
5363   if( pCur->zBase ){
5364     pCur->nBase = (int)strlen(pCur->zBase)+1;
5365     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
5366   }else{
5367     pCur->zPath = sqlite3_mprintf("%s", zDir);
5368   }
5369 
5370   if( pCur->zPath==0 ){
5371     return SQLITE_NOMEM;
5372   }
5373   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
5374     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
5375     return SQLITE_ERROR;
5376   }
5377 
5378   return SQLITE_OK;
5379 }
5380 
5381 /*
5382 ** SQLite will invoke this method one or more times while planning a query
5383 ** that uses the generate_series virtual table.  This routine needs to create
5384 ** a query plan for each invocation and compute an estimated cost for that
5385 ** plan.
5386 **
5387 ** In this implementation idxNum is used to represent the
5388 ** query plan.  idxStr is unused.
5389 **
5390 ** The query plan is represented by values of idxNum:
5391 **
5392 **  (1)  The path value is supplied by argv[0]
5393 **  (2)  Path is in argv[0] and dir is in argv[1]
5394 */
5395 static int fsdirBestIndex(
5396   sqlite3_vtab *tab,
5397   sqlite3_index_info *pIdxInfo
5398 ){
5399   int i;                 /* Loop over constraints */
5400   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
5401   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
5402   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
5403   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
5404   const struct sqlite3_index_constraint *pConstraint;
5405 
5406   (void)tab;
5407   pConstraint = pIdxInfo->aConstraint;
5408   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
5409     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
5410     switch( pConstraint->iColumn ){
5411       case FSDIR_COLUMN_PATH: {
5412         if( pConstraint->usable ){
5413           idxPath = i;
5414           seenPath = 0;
5415         }else if( idxPath<0 ){
5416           seenPath = 1;
5417         }
5418         break;
5419       }
5420       case FSDIR_COLUMN_DIR: {
5421         if( pConstraint->usable ){
5422           idxDir = i;
5423           seenDir = 0;
5424         }else if( idxDir<0 ){
5425           seenDir = 1;
5426         }
5427         break;
5428       }
5429     }
5430   }
5431   if( seenPath || seenDir ){
5432     /* If input parameters are unusable, disallow this plan */
5433     return SQLITE_CONSTRAINT;
5434   }
5435 
5436   if( idxPath<0 ){
5437     pIdxInfo->idxNum = 0;
5438     /* The pIdxInfo->estimatedCost should have been initialized to a huge
5439     ** number.  Leave it unchanged. */
5440     pIdxInfo->estimatedRows = 0x7fffffff;
5441   }else{
5442     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
5443     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
5444     if( idxDir>=0 ){
5445       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
5446       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
5447       pIdxInfo->idxNum = 2;
5448       pIdxInfo->estimatedCost = 10.0;
5449     }else{
5450       pIdxInfo->idxNum = 1;
5451       pIdxInfo->estimatedCost = 100.0;
5452     }
5453   }
5454 
5455   return SQLITE_OK;
5456 }
5457 
5458 /*
5459 ** Register the "fsdir" virtual table.
5460 */
5461 static int fsdirRegister(sqlite3 *db){
5462   static sqlite3_module fsdirModule = {
5463     0,                         /* iVersion */
5464     0,                         /* xCreate */
5465     fsdirConnect,              /* xConnect */
5466     fsdirBestIndex,            /* xBestIndex */
5467     fsdirDisconnect,           /* xDisconnect */
5468     0,                         /* xDestroy */
5469     fsdirOpen,                 /* xOpen - open a cursor */
5470     fsdirClose,                /* xClose - close a cursor */
5471     fsdirFilter,               /* xFilter - configure scan constraints */
5472     fsdirNext,                 /* xNext - advance a cursor */
5473     fsdirEof,                  /* xEof - check for end of scan */
5474     fsdirColumn,               /* xColumn - read data */
5475     fsdirRowid,                /* xRowid - read data */
5476     0,                         /* xUpdate */
5477     0,                         /* xBegin */
5478     0,                         /* xSync */
5479     0,                         /* xCommit */
5480     0,                         /* xRollback */
5481     0,                         /* xFindMethod */
5482     0,                         /* xRename */
5483     0,                         /* xSavepoint */
5484     0,                         /* xRelease */
5485     0,                         /* xRollbackTo */
5486     0,                         /* xShadowName */
5487   };
5488 
5489   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
5490   return rc;
5491 }
5492 #else         /* SQLITE_OMIT_VIRTUALTABLE */
5493 # define fsdirRegister(x) SQLITE_OK
5494 #endif
5495 
5496 #ifdef _WIN32
5497 
5498 #endif
5499 int sqlite3_fileio_init(
5500   sqlite3 *db,
5501   char **pzErrMsg,
5502   const sqlite3_api_routines *pApi
5503 ){
5504   int rc = SQLITE_OK;
5505   SQLITE_EXTENSION_INIT2(pApi);
5506   (void)pzErrMsg;  /* Unused parameter */
5507   rc = sqlite3_create_function(db, "readfile", 1,
5508                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
5509                                readfileFunc, 0, 0);
5510   if( rc==SQLITE_OK ){
5511     rc = sqlite3_create_function(db, "writefile", -1,
5512                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
5513                                  writefileFunc, 0, 0);
5514   }
5515   if( rc==SQLITE_OK ){
5516     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
5517                                  lsModeFunc, 0, 0);
5518   }
5519   if( rc==SQLITE_OK ){
5520     rc = fsdirRegister(db);
5521   }
5522   return rc;
5523 }
5524 
5525 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
5526 /* To allow a standalone DLL, make test_windirent.c use the same
5527  * redefined SQLite API calls as the above extension code does.
5528  * Just pull in this .c to accomplish this. As a beneficial side
5529  * effect, this extension becomes a single translation unit. */
5530 #  include "test_windirent.c"
5531 #endif
5532 
5533 /************************* End ../ext/misc/fileio.c ********************/
5534 /************************* Begin ../ext/misc/completion.c ******************/
5535 /*
5536 ** 2017-07-10
5537 **
5538 ** The author disclaims copyright to this source code.  In place of
5539 ** a legal notice, here is a blessing:
5540 **
5541 **    May you do good and not evil.
5542 **    May you find forgiveness for yourself and forgive others.
5543 **    May you share freely, never taking more than you give.
5544 **
5545 *************************************************************************
5546 **
5547 ** This file implements an eponymous virtual table that returns suggested
5548 ** completions for a partial SQL input.
5549 **
5550 ** Suggested usage:
5551 **
5552 **     SELECT DISTINCT candidate COLLATE nocase
5553 **       FROM completion($prefix,$wholeline)
5554 **      ORDER BY 1;
5555 **
5556 ** The two query parameters are optional.  $prefix is the text of the
5557 ** current word being typed and that is to be completed.  $wholeline is
5558 ** the complete input line, used for context.
5559 **
5560 ** The raw completion() table might return the same candidate multiple
5561 ** times, for example if the same column name is used to two or more
5562 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
5563 ** the DISTINCT and ORDER BY are recommended.
5564 **
5565 ** This virtual table operates at the speed of human typing, and so there
5566 ** is no attempt to make it fast.  Even a slow implementation will be much
5567 ** faster than any human can type.
5568 **
5569 */
5570 /* #include "sqlite3ext.h" */
5571 SQLITE_EXTENSION_INIT1
5572 #include <assert.h>
5573 #include <string.h>
5574 #include <ctype.h>
5575 
5576 #ifndef SQLITE_OMIT_VIRTUALTABLE
5577 
5578 /* completion_vtab is a subclass of sqlite3_vtab which will
5579 ** serve as the underlying representation of a completion virtual table
5580 */
5581 typedef struct completion_vtab completion_vtab;
5582 struct completion_vtab {
5583   sqlite3_vtab base;  /* Base class - must be first */
5584   sqlite3 *db;        /* Database connection for this completion vtab */
5585 };
5586 
5587 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
5588 ** serve as the underlying representation of a cursor that scans
5589 ** over rows of the result
5590 */
5591 typedef struct completion_cursor completion_cursor;
5592 struct completion_cursor {
5593   sqlite3_vtab_cursor base;  /* Base class - must be first */
5594   sqlite3 *db;               /* Database connection for this cursor */
5595   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
5596   char *zPrefix;             /* The prefix for the word we want to complete */
5597   char *zLine;               /* The whole that we want to complete */
5598   const char *zCurrentRow;   /* Current output row */
5599   int szRow;                 /* Length of the zCurrentRow string */
5600   sqlite3_stmt *pStmt;       /* Current statement */
5601   sqlite3_int64 iRowid;      /* The rowid */
5602   int ePhase;                /* Current phase */
5603   int j;                     /* inter-phase counter */
5604 };
5605 
5606 /* Values for ePhase:
5607 */
5608 #define COMPLETION_FIRST_PHASE   1
5609 #define COMPLETION_KEYWORDS      1
5610 #define COMPLETION_PRAGMAS       2
5611 #define COMPLETION_FUNCTIONS     3
5612 #define COMPLETION_COLLATIONS    4
5613 #define COMPLETION_INDEXES       5
5614 #define COMPLETION_TRIGGERS      6
5615 #define COMPLETION_DATABASES     7
5616 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
5617 #define COMPLETION_COLUMNS       9
5618 #define COMPLETION_MODULES       10
5619 #define COMPLETION_EOF           11
5620 
5621 /*
5622 ** The completionConnect() method is invoked to create a new
5623 ** completion_vtab that describes the completion virtual table.
5624 **
5625 ** Think of this routine as the constructor for completion_vtab objects.
5626 **
5627 ** All this routine needs to do is:
5628 **
5629 **    (1) Allocate the completion_vtab object and initialize all fields.
5630 **
5631 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5632 **        result set of queries against completion will look like.
5633 */
5634 static int completionConnect(
5635   sqlite3 *db,
5636   void *pAux,
5637   int argc, const char *const*argv,
5638   sqlite3_vtab **ppVtab,
5639   char **pzErr
5640 ){
5641   completion_vtab *pNew;
5642   int rc;
5643 
5644   (void)(pAux);    /* Unused parameter */
5645   (void)(argc);    /* Unused parameter */
5646   (void)(argv);    /* Unused parameter */
5647   (void)(pzErr);   /* Unused parameter */
5648 
5649 /* Column numbers */
5650 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
5651 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
5652 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
5653 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
5654 
5655   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5656   rc = sqlite3_declare_vtab(db,
5657       "CREATE TABLE x("
5658       "  candidate TEXT,"
5659       "  prefix TEXT HIDDEN,"
5660       "  wholeline TEXT HIDDEN,"
5661       "  phase INT HIDDEN"        /* Used for debugging only */
5662       ")");
5663   if( rc==SQLITE_OK ){
5664     pNew = sqlite3_malloc( sizeof(*pNew) );
5665     *ppVtab = (sqlite3_vtab*)pNew;
5666     if( pNew==0 ) return SQLITE_NOMEM;
5667     memset(pNew, 0, sizeof(*pNew));
5668     pNew->db = db;
5669   }
5670   return rc;
5671 }
5672 
5673 /*
5674 ** This method is the destructor for completion_cursor objects.
5675 */
5676 static int completionDisconnect(sqlite3_vtab *pVtab){
5677   sqlite3_free(pVtab);
5678   return SQLITE_OK;
5679 }
5680 
5681 /*
5682 ** Constructor for a new completion_cursor object.
5683 */
5684 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
5685   completion_cursor *pCur;
5686   pCur = sqlite3_malloc( sizeof(*pCur) );
5687   if( pCur==0 ) return SQLITE_NOMEM;
5688   memset(pCur, 0, sizeof(*pCur));
5689   pCur->db = ((completion_vtab*)p)->db;
5690   *ppCursor = &pCur->base;
5691   return SQLITE_OK;
5692 }
5693 
5694 /*
5695 ** Reset the completion_cursor.
5696 */
5697 static void completionCursorReset(completion_cursor *pCur){
5698   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
5699   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
5700   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
5701   pCur->j = 0;
5702 }
5703 
5704 /*
5705 ** Destructor for a completion_cursor.
5706 */
5707 static int completionClose(sqlite3_vtab_cursor *cur){
5708   completionCursorReset((completion_cursor*)cur);
5709   sqlite3_free(cur);
5710   return SQLITE_OK;
5711 }
5712 
5713 /*
5714 ** Advance a completion_cursor to its next row of output.
5715 **
5716 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
5717 ** record the current state of the scan.  This routine sets ->zCurrentRow
5718 ** to the current row of output and then returns.  If no more rows remain,
5719 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
5720 ** table that has reached the end of its scan.
5721 **
5722 ** The current implementation just lists potential identifiers and
5723 ** keywords and filters them by zPrefix.  Future enhancements should
5724 ** take zLine into account to try to restrict the set of identifiers and
5725 ** keywords based on what would be legal at the current point of input.
5726 */
5727 static int completionNext(sqlite3_vtab_cursor *cur){
5728   completion_cursor *pCur = (completion_cursor*)cur;
5729   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
5730   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
5731   pCur->iRowid++;
5732   while( pCur->ePhase!=COMPLETION_EOF ){
5733     switch( pCur->ePhase ){
5734       case COMPLETION_KEYWORDS: {
5735         if( pCur->j >= sqlite3_keyword_count() ){
5736           pCur->zCurrentRow = 0;
5737           pCur->ePhase = COMPLETION_DATABASES;
5738         }else{
5739           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
5740         }
5741         iCol = -1;
5742         break;
5743       }
5744       case COMPLETION_DATABASES: {
5745         if( pCur->pStmt==0 ){
5746           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
5747                              &pCur->pStmt, 0);
5748         }
5749         iCol = 1;
5750         eNextPhase = COMPLETION_TABLES;
5751         break;
5752       }
5753       case COMPLETION_TABLES: {
5754         if( pCur->pStmt==0 ){
5755           sqlite3_stmt *pS2;
5756           char *zSql = 0;
5757           const char *zSep = "";
5758           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
5759           while( sqlite3_step(pS2)==SQLITE_ROW ){
5760             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
5761             zSql = sqlite3_mprintf(
5762                "%z%s"
5763                "SELECT name FROM \"%w\".sqlite_schema",
5764                zSql, zSep, zDb
5765             );
5766             if( zSql==0 ) return SQLITE_NOMEM;
5767             zSep = " UNION ";
5768           }
5769           sqlite3_finalize(pS2);
5770           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
5771           sqlite3_free(zSql);
5772         }
5773         iCol = 0;
5774         eNextPhase = COMPLETION_COLUMNS;
5775         break;
5776       }
5777       case COMPLETION_COLUMNS: {
5778         if( pCur->pStmt==0 ){
5779           sqlite3_stmt *pS2;
5780           char *zSql = 0;
5781           const char *zSep = "";
5782           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
5783           while( sqlite3_step(pS2)==SQLITE_ROW ){
5784             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
5785             zSql = sqlite3_mprintf(
5786                "%z%s"
5787                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
5788                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
5789                " WHERE sm.type='table'",
5790                zSql, zSep, zDb, zDb
5791             );
5792             if( zSql==0 ) return SQLITE_NOMEM;
5793             zSep = " UNION ";
5794           }
5795           sqlite3_finalize(pS2);
5796           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
5797           sqlite3_free(zSql);
5798         }
5799         iCol = 0;
5800         eNextPhase = COMPLETION_EOF;
5801         break;
5802       }
5803     }
5804     if( iCol<0 ){
5805       /* This case is when the phase presets zCurrentRow */
5806       if( pCur->zCurrentRow==0 ) continue;
5807     }else{
5808       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
5809         /* Extract the next row of content */
5810         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
5811         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
5812       }else{
5813         /* When all rows are finished, advance to the next phase */
5814         sqlite3_finalize(pCur->pStmt);
5815         pCur->pStmt = 0;
5816         pCur->ePhase = eNextPhase;
5817         continue;
5818       }
5819     }
5820     if( pCur->nPrefix==0 ) break;
5821     if( pCur->nPrefix<=pCur->szRow
5822      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
5823     ){
5824       break;
5825     }
5826   }
5827 
5828   return SQLITE_OK;
5829 }
5830 
5831 /*
5832 ** Return values of columns for the row at which the completion_cursor
5833 ** is currently pointing.
5834 */
5835 static int completionColumn(
5836   sqlite3_vtab_cursor *cur,   /* The cursor */
5837   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5838   int i                       /* Which column to return */
5839 ){
5840   completion_cursor *pCur = (completion_cursor*)cur;
5841   switch( i ){
5842     case COMPLETION_COLUMN_CANDIDATE: {
5843       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
5844       break;
5845     }
5846     case COMPLETION_COLUMN_PREFIX: {
5847       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
5848       break;
5849     }
5850     case COMPLETION_COLUMN_WHOLELINE: {
5851       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
5852       break;
5853     }
5854     case COMPLETION_COLUMN_PHASE: {
5855       sqlite3_result_int(ctx, pCur->ePhase);
5856       break;
5857     }
5858   }
5859   return SQLITE_OK;
5860 }
5861 
5862 /*
5863 ** Return the rowid for the current row.  In this implementation, the
5864 ** rowid is the same as the output value.
5865 */
5866 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5867   completion_cursor *pCur = (completion_cursor*)cur;
5868   *pRowid = pCur->iRowid;
5869   return SQLITE_OK;
5870 }
5871 
5872 /*
5873 ** Return TRUE if the cursor has been moved off of the last
5874 ** row of output.
5875 */
5876 static int completionEof(sqlite3_vtab_cursor *cur){
5877   completion_cursor *pCur = (completion_cursor*)cur;
5878   return pCur->ePhase >= COMPLETION_EOF;
5879 }
5880 
5881 /*
5882 ** This method is called to "rewind" the completion_cursor object back
5883 ** to the first row of output.  This method is always called at least
5884 ** once prior to any call to completionColumn() or completionRowid() or
5885 ** completionEof().
5886 */
5887 static int completionFilter(
5888   sqlite3_vtab_cursor *pVtabCursor,
5889   int idxNum, const char *idxStr,
5890   int argc, sqlite3_value **argv
5891 ){
5892   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
5893   int iArg = 0;
5894   (void)(idxStr);   /* Unused parameter */
5895   (void)(argc);     /* Unused parameter */
5896   completionCursorReset(pCur);
5897   if( idxNum & 1 ){
5898     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
5899     if( pCur->nPrefix>0 ){
5900       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
5901       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
5902     }
5903     iArg = 1;
5904   }
5905   if( idxNum & 2 ){
5906     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
5907     if( pCur->nLine>0 ){
5908       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
5909       if( pCur->zLine==0 ) return SQLITE_NOMEM;
5910     }
5911   }
5912   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
5913     int i = pCur->nLine;
5914     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
5915       i--;
5916     }
5917     pCur->nPrefix = pCur->nLine - i;
5918     if( pCur->nPrefix>0 ){
5919       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
5920       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
5921     }
5922   }
5923   pCur->iRowid = 0;
5924   pCur->ePhase = COMPLETION_FIRST_PHASE;
5925   return completionNext(pVtabCursor);
5926 }
5927 
5928 /*
5929 ** SQLite will invoke this method one or more times while planning a query
5930 ** that uses the completion virtual table.  This routine needs to create
5931 ** a query plan for each invocation and compute an estimated cost for that
5932 ** plan.
5933 **
5934 ** There are two hidden parameters that act as arguments to the table-valued
5935 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
5936 ** is available and bit 1 is set if "wholeline" is available.
5937 */
5938 static int completionBestIndex(
5939   sqlite3_vtab *tab,
5940   sqlite3_index_info *pIdxInfo
5941 ){
5942   int i;                 /* Loop over constraints */
5943   int idxNum = 0;        /* The query plan bitmask */
5944   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
5945   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
5946   int nArg = 0;          /* Number of arguments that completeFilter() expects */
5947   const struct sqlite3_index_constraint *pConstraint;
5948 
5949   (void)(tab);    /* Unused parameter */
5950   pConstraint = pIdxInfo->aConstraint;
5951   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
5952     if( pConstraint->usable==0 ) continue;
5953     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
5954     switch( pConstraint->iColumn ){
5955       case COMPLETION_COLUMN_PREFIX:
5956         prefixIdx = i;
5957         idxNum |= 1;
5958         break;
5959       case COMPLETION_COLUMN_WHOLELINE:
5960         wholelineIdx = i;
5961         idxNum |= 2;
5962         break;
5963     }
5964   }
5965   if( prefixIdx>=0 ){
5966     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
5967     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
5968   }
5969   if( wholelineIdx>=0 ){
5970     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
5971     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
5972   }
5973   pIdxInfo->idxNum = idxNum;
5974   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
5975   pIdxInfo->estimatedRows = 500 - 100*nArg;
5976   return SQLITE_OK;
5977 }
5978 
5979 /*
5980 ** This following structure defines all the methods for the
5981 ** completion virtual table.
5982 */
5983 static sqlite3_module completionModule = {
5984   0,                         /* iVersion */
5985   0,                         /* xCreate */
5986   completionConnect,         /* xConnect */
5987   completionBestIndex,       /* xBestIndex */
5988   completionDisconnect,      /* xDisconnect */
5989   0,                         /* xDestroy */
5990   completionOpen,            /* xOpen - open a cursor */
5991   completionClose,           /* xClose - close a cursor */
5992   completionFilter,          /* xFilter - configure scan constraints */
5993   completionNext,            /* xNext - advance a cursor */
5994   completionEof,             /* xEof - check for end of scan */
5995   completionColumn,          /* xColumn - read data */
5996   completionRowid,           /* xRowid - read data */
5997   0,                         /* xUpdate */
5998   0,                         /* xBegin */
5999   0,                         /* xSync */
6000   0,                         /* xCommit */
6001   0,                         /* xRollback */
6002   0,                         /* xFindMethod */
6003   0,                         /* xRename */
6004   0,                         /* xSavepoint */
6005   0,                         /* xRelease */
6006   0,                         /* xRollbackTo */
6007   0                          /* xShadowName */
6008 };
6009 
6010 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6011 
6012 int sqlite3CompletionVtabInit(sqlite3 *db){
6013   int rc = SQLITE_OK;
6014 #ifndef SQLITE_OMIT_VIRTUALTABLE
6015   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
6016 #endif
6017   return rc;
6018 }
6019 
6020 #ifdef _WIN32
6021 
6022 #endif
6023 int sqlite3_completion_init(
6024   sqlite3 *db,
6025   char **pzErrMsg,
6026   const sqlite3_api_routines *pApi
6027 ){
6028   int rc = SQLITE_OK;
6029   SQLITE_EXTENSION_INIT2(pApi);
6030   (void)(pzErrMsg);  /* Unused parameter */
6031 #ifndef SQLITE_OMIT_VIRTUALTABLE
6032   rc = sqlite3CompletionVtabInit(db);
6033 #endif
6034   return rc;
6035 }
6036 
6037 /************************* End ../ext/misc/completion.c ********************/
6038 /************************* Begin ../ext/misc/appendvfs.c ******************/
6039 /*
6040 ** 2017-10-20
6041 **
6042 ** The author disclaims copyright to this source code.  In place of
6043 ** a legal notice, here is a blessing:
6044 **
6045 **    May you do good and not evil.
6046 **    May you find forgiveness for yourself and forgive others.
6047 **    May you share freely, never taking more than you give.
6048 **
6049 ******************************************************************************
6050 **
6051 ** This file implements a VFS shim that allows an SQLite database to be
6052 ** appended onto the end of some other file, such as an executable.
6053 **
6054 ** A special record must appear at the end of the file that identifies the
6055 ** file as an appended database and provides the offset to the first page
6056 ** of the exposed content. (Or, it is the length of the content prefix.)
6057 ** For best performance page 1 should be located at a disk page boundary,
6058 ** though that is not required.
6059 **
6060 ** When opening a database using this VFS, the connection might treat
6061 ** the file as an ordinary SQLite database, or it might treat it as a
6062 ** database appended onto some other file.  The decision is made by
6063 ** applying the following rules in order:
6064 **
6065 **  (1)  An empty file is an ordinary database.
6066 **
6067 **  (2)  If the file ends with the appendvfs trailer string
6068 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
6069 **
6070 **  (3)  If the file begins with the standard SQLite prefix string
6071 **       "SQLite format 3", that file is an ordinary database.
6072 **
6073 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
6074 **       set, then a new database is appended to the already existing file.
6075 **
6076 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
6077 **
6078 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
6079 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
6080 ** This VFS will not read or write past the 1GiB mark.  This restriction
6081 ** might be lifted in future versions.  For now, if you need a larger
6082 ** database, then keep it in a separate file.
6083 **
6084 ** If the file being opened is a plain database (not an appended one), then
6085 ** this shim is a pass-through into the default underlying VFS. (rule 3)
6086 **/
6087 /* #include "sqlite3ext.h" */
6088 SQLITE_EXTENSION_INIT1
6089 #include <string.h>
6090 #include <assert.h>
6091 
6092 /* The append mark at the end of the database is:
6093 **
6094 **     Start-Of-SQLite3-NNNNNNNN
6095 **     123456789 123456789 12345
6096 **
6097 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
6098 ** the offset to page 1, and also the length of the prefix content.
6099 */
6100 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
6101 #define APND_MARK_PREFIX_SZ  17
6102 #define APND_MARK_FOS_SZ      8
6103 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
6104 
6105 /*
6106 ** Maximum size of the combined prefix + database + append-mark.  This
6107 ** must be less than 0x40000000 to avoid locking issues on Windows.
6108 */
6109 #define APND_MAX_SIZE  (0x40000000)
6110 
6111 /*
6112 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
6113 */
6114 #ifndef APND_ROUNDUP
6115 #define APND_ROUNDUP 4096
6116 #endif
6117 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
6118 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
6119 
6120 /*
6121 ** Forward declaration of objects used by this utility
6122 */
6123 typedef struct sqlite3_vfs ApndVfs;
6124 typedef struct ApndFile ApndFile;
6125 
6126 /* Access to a lower-level VFS that (might) implement dynamic loading,
6127 ** access to randomness, etc.
6128 */
6129 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
6130 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
6131 
6132 /* An open appendvfs file
6133 **
6134 ** An instance of this structure describes the appended database file.
6135 ** A separate sqlite3_file object is always appended. The appended
6136 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
6137 ** the entire file, including the prefix, the database, and the
6138 ** append-mark.
6139 **
6140 ** The structure of an AppendVFS database is like this:
6141 **
6142 **   +-------------+---------+----------+-------------+
6143 **   | prefix-file | padding | database | append-mark |
6144 **   +-------------+---------+----------+-------------+
6145 **                           ^          ^
6146 **                           |          |
6147 **                         iPgOne      iMark
6148 **
6149 **
6150 ** "prefix file" -  file onto which the database has been appended.
6151 ** "padding"     -  zero or more bytes inserted so that "database"
6152 **                  starts on an APND_ROUNDUP boundary
6153 ** "database"    -  The SQLite database file
6154 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
6155 **                  the offset from the start of prefix-file to the start
6156 **                  of "database".
6157 **
6158 ** The size of the database is iMark - iPgOne.
6159 **
6160 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
6161 ** of iPgOne stored as a big-ending 64-bit integer.
6162 **
6163 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
6164 ** Or, iMark is -1 to indicate that it has not yet been written.
6165 */
6166 struct ApndFile {
6167   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
6168   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
6169   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
6170   /* Always followed by another sqlite3_file that describes the whole file */
6171 };
6172 
6173 /*
6174 ** Methods for ApndFile
6175 */
6176 static int apndClose(sqlite3_file*);
6177 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
6178 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
6179 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
6180 static int apndSync(sqlite3_file*, int flags);
6181 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
6182 static int apndLock(sqlite3_file*, int);
6183 static int apndUnlock(sqlite3_file*, int);
6184 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
6185 static int apndFileControl(sqlite3_file*, int op, void *pArg);
6186 static int apndSectorSize(sqlite3_file*);
6187 static int apndDeviceCharacteristics(sqlite3_file*);
6188 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
6189 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
6190 static void apndShmBarrier(sqlite3_file*);
6191 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
6192 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
6193 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
6194 
6195 /*
6196 ** Methods for ApndVfs
6197 */
6198 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
6199 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
6200 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
6201 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
6202 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
6203 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
6204 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
6205 static void apndDlClose(sqlite3_vfs*, void*);
6206 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
6207 static int apndSleep(sqlite3_vfs*, int microseconds);
6208 static int apndCurrentTime(sqlite3_vfs*, double*);
6209 static int apndGetLastError(sqlite3_vfs*, int, char *);
6210 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
6211 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
6212 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
6213 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
6214 
6215 static sqlite3_vfs apnd_vfs = {
6216   3,                            /* iVersion (set when registered) */
6217   0,                            /* szOsFile (set when registered) */
6218   1024,                         /* mxPathname */
6219   0,                            /* pNext */
6220   "apndvfs",                    /* zName */
6221   0,                            /* pAppData (set when registered) */
6222   apndOpen,                     /* xOpen */
6223   apndDelete,                   /* xDelete */
6224   apndAccess,                   /* xAccess */
6225   apndFullPathname,             /* xFullPathname */
6226   apndDlOpen,                   /* xDlOpen */
6227   apndDlError,                  /* xDlError */
6228   apndDlSym,                    /* xDlSym */
6229   apndDlClose,                  /* xDlClose */
6230   apndRandomness,               /* xRandomness */
6231   apndSleep,                    /* xSleep */
6232   apndCurrentTime,              /* xCurrentTime */
6233   apndGetLastError,             /* xGetLastError */
6234   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
6235   apndSetSystemCall,            /* xSetSystemCall */
6236   apndGetSystemCall,            /* xGetSystemCall */
6237   apndNextSystemCall            /* xNextSystemCall */
6238 };
6239 
6240 static const sqlite3_io_methods apnd_io_methods = {
6241   3,                              /* iVersion */
6242   apndClose,                      /* xClose */
6243   apndRead,                       /* xRead */
6244   apndWrite,                      /* xWrite */
6245   apndTruncate,                   /* xTruncate */
6246   apndSync,                       /* xSync */
6247   apndFileSize,                   /* xFileSize */
6248   apndLock,                       /* xLock */
6249   apndUnlock,                     /* xUnlock */
6250   apndCheckReservedLock,          /* xCheckReservedLock */
6251   apndFileControl,                /* xFileControl */
6252   apndSectorSize,                 /* xSectorSize */
6253   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
6254   apndShmMap,                     /* xShmMap */
6255   apndShmLock,                    /* xShmLock */
6256   apndShmBarrier,                 /* xShmBarrier */
6257   apndShmUnmap,                   /* xShmUnmap */
6258   apndFetch,                      /* xFetch */
6259   apndUnfetch                     /* xUnfetch */
6260 };
6261 
6262 /*
6263 ** Close an apnd-file.
6264 */
6265 static int apndClose(sqlite3_file *pFile){
6266   pFile = ORIGFILE(pFile);
6267   return pFile->pMethods->xClose(pFile);
6268 }
6269 
6270 /*
6271 ** Read data from an apnd-file.
6272 */
6273 static int apndRead(
6274   sqlite3_file *pFile,
6275   void *zBuf,
6276   int iAmt,
6277   sqlite_int64 iOfst
6278 ){
6279   ApndFile *paf = (ApndFile *)pFile;
6280   pFile = ORIGFILE(pFile);
6281   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
6282 }
6283 
6284 /*
6285 ** Add the append-mark onto what should become the end of the file.
6286 *  If and only if this succeeds, internal ApndFile.iMark is updated.
6287 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
6288 */
6289 static int apndWriteMark(
6290   ApndFile *paf,
6291   sqlite3_file *pFile,
6292   sqlite_int64 iWriteEnd
6293 ){
6294   sqlite_int64 iPgOne = paf->iPgOne;
6295   unsigned char a[APND_MARK_SIZE];
6296   int i = APND_MARK_FOS_SZ;
6297   int rc;
6298   assert(pFile == ORIGFILE(paf));
6299   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
6300   while( --i >= 0 ){
6301     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
6302     iPgOne >>= 8;
6303   }
6304   iWriteEnd += paf->iPgOne;
6305   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
6306                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
6307     paf->iMark = iWriteEnd;
6308   }
6309   return rc;
6310 }
6311 
6312 /*
6313 ** Write data to an apnd-file.
6314 */
6315 static int apndWrite(
6316   sqlite3_file *pFile,
6317   const void *zBuf,
6318   int iAmt,
6319   sqlite_int64 iOfst
6320 ){
6321   ApndFile *paf = (ApndFile *)pFile;
6322   sqlite_int64 iWriteEnd = iOfst + iAmt;
6323   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
6324   pFile = ORIGFILE(pFile);
6325   /* If append-mark is absent or will be overwritten, write it. */
6326   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
6327     int rc = apndWriteMark(paf, pFile, iWriteEnd);
6328     if( SQLITE_OK!=rc ) return rc;
6329   }
6330   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
6331 }
6332 
6333 /*
6334 ** Truncate an apnd-file.
6335 */
6336 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
6337   ApndFile *paf = (ApndFile *)pFile;
6338   pFile = ORIGFILE(pFile);
6339   /* The append mark goes out first so truncate failure does not lose it. */
6340   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
6341   /* Truncate underlying file just past append mark */
6342   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
6343 }
6344 
6345 /*
6346 ** Sync an apnd-file.
6347 */
6348 static int apndSync(sqlite3_file *pFile, int flags){
6349   pFile = ORIGFILE(pFile);
6350   return pFile->pMethods->xSync(pFile, flags);
6351 }
6352 
6353 /*
6354 ** Return the current file-size of an apnd-file.
6355 ** If the append mark is not yet there, the file-size is 0.
6356 */
6357 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
6358   ApndFile *paf = (ApndFile *)pFile;
6359   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
6360   return SQLITE_OK;
6361 }
6362 
6363 /*
6364 ** Lock an apnd-file.
6365 */
6366 static int apndLock(sqlite3_file *pFile, int eLock){
6367   pFile = ORIGFILE(pFile);
6368   return pFile->pMethods->xLock(pFile, eLock);
6369 }
6370 
6371 /*
6372 ** Unlock an apnd-file.
6373 */
6374 static int apndUnlock(sqlite3_file *pFile, int eLock){
6375   pFile = ORIGFILE(pFile);
6376   return pFile->pMethods->xUnlock(pFile, eLock);
6377 }
6378 
6379 /*
6380 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
6381 */
6382 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
6383   pFile = ORIGFILE(pFile);
6384   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
6385 }
6386 
6387 /*
6388 ** File control method. For custom operations on an apnd-file.
6389 */
6390 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
6391   ApndFile *paf = (ApndFile *)pFile;
6392   int rc;
6393   pFile = ORIGFILE(pFile);
6394   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
6395   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
6396   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
6397     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
6398   }
6399   return rc;
6400 }
6401 
6402 /*
6403 ** Return the sector-size in bytes for an apnd-file.
6404 */
6405 static int apndSectorSize(sqlite3_file *pFile){
6406   pFile = ORIGFILE(pFile);
6407   return pFile->pMethods->xSectorSize(pFile);
6408 }
6409 
6410 /*
6411 ** Return the device characteristic flags supported by an apnd-file.
6412 */
6413 static int apndDeviceCharacteristics(sqlite3_file *pFile){
6414   pFile = ORIGFILE(pFile);
6415   return pFile->pMethods->xDeviceCharacteristics(pFile);
6416 }
6417 
6418 /* Create a shared memory file mapping */
6419 static int apndShmMap(
6420   sqlite3_file *pFile,
6421   int iPg,
6422   int pgsz,
6423   int bExtend,
6424   void volatile **pp
6425 ){
6426   pFile = ORIGFILE(pFile);
6427   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
6428 }
6429 
6430 /* Perform locking on a shared-memory segment */
6431 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
6432   pFile = ORIGFILE(pFile);
6433   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
6434 }
6435 
6436 /* Memory barrier operation on shared memory */
6437 static void apndShmBarrier(sqlite3_file *pFile){
6438   pFile = ORIGFILE(pFile);
6439   pFile->pMethods->xShmBarrier(pFile);
6440 }
6441 
6442 /* Unmap a shared memory segment */
6443 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
6444   pFile = ORIGFILE(pFile);
6445   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
6446 }
6447 
6448 /* Fetch a page of a memory-mapped file */
6449 static int apndFetch(
6450   sqlite3_file *pFile,
6451   sqlite3_int64 iOfst,
6452   int iAmt,
6453   void **pp
6454 ){
6455   ApndFile *p = (ApndFile *)pFile;
6456   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
6457     return SQLITE_IOERR; /* Cannot read what is not yet there. */
6458   }
6459   pFile = ORIGFILE(pFile);
6460   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
6461 }
6462 
6463 /* Release a memory-mapped page */
6464 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
6465   ApndFile *p = (ApndFile *)pFile;
6466   pFile = ORIGFILE(pFile);
6467   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
6468 }
6469 
6470 /*
6471 ** Try to read the append-mark off the end of a file.  Return the
6472 ** start of the appended database if the append-mark is present.
6473 ** If there is no valid append-mark, return -1;
6474 **
6475 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
6476 ** indicates that the appended database contains at least one page.  The
6477 ** start-of-database value must be a multiple of 512.
6478 */
6479 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
6480   int rc, i;
6481   sqlite3_int64 iMark;
6482   int msbs = 8 * (APND_MARK_FOS_SZ-1);
6483   unsigned char a[APND_MARK_SIZE];
6484 
6485   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
6486   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
6487   if( rc ) return -1;
6488   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
6489   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
6490   for(i=1; i<8; i++){
6491     msbs -= 8;
6492     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
6493   }
6494   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
6495   if( iMark & 0x1ff ) return -1;
6496   return iMark;
6497 }
6498 
6499 static const char apvfsSqliteHdr[] = "SQLite format 3";
6500 /*
6501 ** Check to see if the file is an appendvfs SQLite database file.
6502 ** Return true iff it is such. Parameter sz is the file's size.
6503 */
6504 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
6505   int rc;
6506   char zHdr[16];
6507   sqlite3_int64 iMark = apndReadMark(sz, pFile);
6508   if( iMark>=0 ){
6509     /* If file has the correct end-marker, the expected odd size, and the
6510     ** SQLite DB type marker where the end-marker puts it, then it
6511     ** is an appendvfs database.
6512     */
6513     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
6514     if( SQLITE_OK==rc
6515      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
6516      && (sz & 0x1ff) == APND_MARK_SIZE
6517      && sz>=512+APND_MARK_SIZE
6518     ){
6519       return 1; /* It's an appendvfs database */
6520     }
6521   }
6522   return 0;
6523 }
6524 
6525 /*
6526 ** Check to see if the file is an ordinary SQLite database file.
6527 ** Return true iff so. Parameter sz is the file's size.
6528 */
6529 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
6530   char zHdr[16];
6531   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
6532    || (sz & 0x1ff) != 0
6533    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
6534    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
6535   ){
6536     return 0;
6537   }else{
6538     return 1;
6539   }
6540 }
6541 
6542 /*
6543 ** Open an apnd file handle.
6544 */
6545 static int apndOpen(
6546   sqlite3_vfs *pApndVfs,
6547   const char *zName,
6548   sqlite3_file *pFile,
6549   int flags,
6550   int *pOutFlags
6551 ){
6552   ApndFile *pApndFile = (ApndFile*)pFile;
6553   sqlite3_file *pBaseFile = ORIGFILE(pFile);
6554   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
6555   int rc;
6556   sqlite3_int64 sz = 0;
6557   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
6558     /* The appendvfs is not to be used for transient or temporary databases.
6559     ** Just use the base VFS open to initialize the given file object and
6560     ** open the underlying file. (Appendvfs is then unused for this file.)
6561     */
6562     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
6563   }
6564   memset(pApndFile, 0, sizeof(ApndFile));
6565   pFile->pMethods = &apnd_io_methods;
6566   pApndFile->iMark = -1;    /* Append mark not yet written */
6567 
6568   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
6569   if( rc==SQLITE_OK ){
6570     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
6571     if( rc ){
6572       pBaseFile->pMethods->xClose(pBaseFile);
6573     }
6574   }
6575   if( rc ){
6576     pFile->pMethods = 0;
6577     return rc;
6578   }
6579   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
6580     /* The file being opened appears to be just an ordinary DB. Copy
6581     ** the base dispatch-table so this instance mimics the base VFS.
6582     */
6583     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
6584     return SQLITE_OK;
6585   }
6586   pApndFile->iPgOne = apndReadMark(sz, pFile);
6587   if( pApndFile->iPgOne>=0 ){
6588     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
6589     return SQLITE_OK;
6590   }
6591   if( (flags & SQLITE_OPEN_CREATE)==0 ){
6592     pBaseFile->pMethods->xClose(pBaseFile);
6593     rc = SQLITE_CANTOPEN;
6594     pFile->pMethods = 0;
6595   }else{
6596     /* Round newly added appendvfs location to #define'd page boundary.
6597     ** Note that nothing has yet been written to the underlying file.
6598     ** The append mark will be written along with first content write.
6599     ** Until then, paf->iMark value indicates it is not yet written.
6600     */
6601     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
6602   }
6603   return rc;
6604 }
6605 
6606 /*
6607 ** Delete an apnd file.
6608 ** For an appendvfs, this could mean delete the appendvfs portion,
6609 ** leaving the appendee as it was before it gained an appendvfs.
6610 ** For now, this code deletes the underlying file too.
6611 */
6612 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
6613   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
6614 }
6615 
6616 /*
6617 ** All other VFS methods are pass-thrus.
6618 */
6619 static int apndAccess(
6620   sqlite3_vfs *pVfs,
6621   const char *zPath,
6622   int flags,
6623   int *pResOut
6624 ){
6625   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
6626 }
6627 static int apndFullPathname(
6628   sqlite3_vfs *pVfs,
6629   const char *zPath,
6630   int nOut,
6631   char *zOut
6632 ){
6633   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
6634 }
6635 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
6636   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
6637 }
6638 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
6639   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
6640 }
6641 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
6642   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
6643 }
6644 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
6645   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
6646 }
6647 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
6648   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
6649 }
6650 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
6651   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
6652 }
6653 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
6654   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
6655 }
6656 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
6657   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
6658 }
6659 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
6660   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
6661 }
6662 static int apndSetSystemCall(
6663   sqlite3_vfs *pVfs,
6664   const char *zName,
6665   sqlite3_syscall_ptr pCall
6666 ){
6667   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
6668 }
6669 static sqlite3_syscall_ptr apndGetSystemCall(
6670   sqlite3_vfs *pVfs,
6671   const char *zName
6672 ){
6673   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
6674 }
6675 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
6676   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
6677 }
6678 
6679 
6680 #ifdef _WIN32
6681 
6682 #endif
6683 /*
6684 ** This routine is called when the extension is loaded.
6685 ** Register the new VFS.
6686 */
6687 int sqlite3_appendvfs_init(
6688   sqlite3 *db,
6689   char **pzErrMsg,
6690   const sqlite3_api_routines *pApi
6691 ){
6692   int rc = SQLITE_OK;
6693   sqlite3_vfs *pOrig;
6694   SQLITE_EXTENSION_INIT2(pApi);
6695   (void)pzErrMsg;
6696   (void)db;
6697   pOrig = sqlite3_vfs_find(0);
6698   if( pOrig==0 ) return SQLITE_ERROR;
6699   apnd_vfs.iVersion = pOrig->iVersion;
6700   apnd_vfs.pAppData = pOrig;
6701   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
6702   rc = sqlite3_vfs_register(&apnd_vfs, 0);
6703 #ifdef APPENDVFS_TEST
6704   if( rc==SQLITE_OK ){
6705     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
6706   }
6707 #endif
6708   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
6709   return rc;
6710 }
6711 
6712 /************************* End ../ext/misc/appendvfs.c ********************/
6713 #endif
6714 #ifdef SQLITE_HAVE_ZLIB
6715 /************************* Begin ../ext/misc/zipfile.c ******************/
6716 /*
6717 ** 2017-12-26
6718 **
6719 ** The author disclaims copyright to this source code.  In place of
6720 ** a legal notice, here is a blessing:
6721 **
6722 **    May you do good and not evil.
6723 **    May you find forgiveness for yourself and forgive others.
6724 **    May you share freely, never taking more than you give.
6725 **
6726 ******************************************************************************
6727 **
6728 ** This file implements a virtual table for reading and writing ZIP archive
6729 ** files.
6730 **
6731 ** Usage example:
6732 **
6733 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
6734 **
6735 ** Current limitations:
6736 **
6737 **    *  No support for encryption
6738 **    *  No support for ZIP archives spanning multiple files
6739 **    *  No support for zip64 extensions
6740 **    *  Only the "inflate/deflate" (zlib) compression method is supported
6741 */
6742 /* #include "sqlite3ext.h" */
6743 SQLITE_EXTENSION_INIT1
6744 #include <stdio.h>
6745 #include <string.h>
6746 #include <assert.h>
6747 
6748 #include <zlib.h>
6749 
6750 #ifndef SQLITE_OMIT_VIRTUALTABLE
6751 
6752 #ifndef SQLITE_AMALGAMATION
6753 
6754 #ifndef UINT32_TYPE
6755 # ifdef HAVE_UINT32_T
6756 #  define UINT32_TYPE uint32_t
6757 # else
6758 #  define UINT32_TYPE unsigned int
6759 # endif
6760 #endif
6761 #ifndef UINT16_TYPE
6762 # ifdef HAVE_UINT16_T
6763 #  define UINT16_TYPE uint16_t
6764 # else
6765 #  define UINT16_TYPE unsigned short int
6766 # endif
6767 #endif
6768 /* typedef sqlite3_int64 i64; */
6769 /* typedef unsigned char u8; */
6770 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6771 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6772 #define MIN(a,b) ((a)<(b) ? (a) : (b))
6773 
6774 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
6775 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
6776 #endif
6777 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
6778 # define ALWAYS(X)      (1)
6779 # define NEVER(X)       (0)
6780 #elif !defined(NDEBUG)
6781 # define ALWAYS(X)      ((X)?1:(assert(0),0))
6782 # define NEVER(X)       ((X)?(assert(0),1):0)
6783 #else
6784 # define ALWAYS(X)      (X)
6785 # define NEVER(X)       (X)
6786 #endif
6787 
6788 #endif   /* SQLITE_AMALGAMATION */
6789 
6790 /*
6791 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
6792 **
6793 ** In some ways it would be better to obtain these values from system
6794 ** header files. But, the dependency is undesirable and (a) these
6795 ** have been stable for decades, (b) the values are part of POSIX and
6796 ** are also made explicit in [man stat], and (c) are part of the
6797 ** file format for zip archives.
6798 */
6799 #ifndef S_IFDIR
6800 # define S_IFDIR 0040000
6801 #endif
6802 #ifndef S_IFREG
6803 # define S_IFREG 0100000
6804 #endif
6805 #ifndef S_IFLNK
6806 # define S_IFLNK 0120000
6807 #endif
6808 
6809 static const char ZIPFILE_SCHEMA[] =
6810   "CREATE TABLE y("
6811     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
6812     "mode,"              /* 1: POSIX mode for file */
6813     "mtime,"             /* 2: Last modification time (secs since 1970)*/
6814     "sz,"                /* 3: Size of object */
6815     "rawdata,"           /* 4: Raw data */
6816     "data,"              /* 5: Uncompressed data */
6817     "method,"            /* 6: Compression method (integer) */
6818     "z HIDDEN"           /* 7: Name of zip file */
6819   ") WITHOUT ROWID;";
6820 
6821 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
6822 #define ZIPFILE_BUFFER_SIZE (64*1024)
6823 
6824 
6825 /*
6826 ** Magic numbers used to read and write zip files.
6827 **
6828 ** ZIPFILE_NEWENTRY_MADEBY:
6829 **   Use this value for the "version-made-by" field in new zip file
6830 **   entries. The upper byte indicates "unix", and the lower byte
6831 **   indicates that the zip file matches pkzip specification 3.0.
6832 **   This is what info-zip seems to do.
6833 **
6834 ** ZIPFILE_NEWENTRY_REQUIRED:
6835 **   Value for "version-required-to-extract" field of new entries.
6836 **   Version 2.0 is required to support folders and deflate compression.
6837 **
6838 ** ZIPFILE_NEWENTRY_FLAGS:
6839 **   Value for "general-purpose-bit-flags" field of new entries. Bit
6840 **   11 means "utf-8 filename and comment".
6841 **
6842 ** ZIPFILE_SIGNATURE_CDS:
6843 **   First 4 bytes of a valid CDS record.
6844 **
6845 ** ZIPFILE_SIGNATURE_LFH:
6846 **   First 4 bytes of a valid LFH record.
6847 **
6848 ** ZIPFILE_SIGNATURE_EOCD
6849 **   First 4 bytes of a valid EOCD record.
6850 */
6851 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
6852 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
6853 #define ZIPFILE_NEWENTRY_REQUIRED 20
6854 #define ZIPFILE_NEWENTRY_FLAGS    0x800
6855 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
6856 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
6857 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
6858 
6859 /*
6860 ** The sizes of the fixed-size part of each of the three main data
6861 ** structures in a zip archive.
6862 */
6863 #define ZIPFILE_LFH_FIXED_SZ      30
6864 #define ZIPFILE_EOCD_FIXED_SZ     22
6865 #define ZIPFILE_CDS_FIXED_SZ      46
6866 
6867 /*
6868 *** 4.3.16  End of central directory record:
6869 ***
6870 ***   end of central dir signature    4 bytes  (0x06054b50)
6871 ***   number of this disk             2 bytes
6872 ***   number of the disk with the
6873 ***   start of the central directory  2 bytes
6874 ***   total number of entries in the
6875 ***   central directory on this disk  2 bytes
6876 ***   total number of entries in
6877 ***   the central directory           2 bytes
6878 ***   size of the central directory   4 bytes
6879 ***   offset of start of central
6880 ***   directory with respect to
6881 ***   the starting disk number        4 bytes
6882 ***   .ZIP file comment length        2 bytes
6883 ***   .ZIP file comment       (variable size)
6884 */
6885 typedef struct ZipfileEOCD ZipfileEOCD;
6886 struct ZipfileEOCD {
6887   u16 iDisk;
6888   u16 iFirstDisk;
6889   u16 nEntry;
6890   u16 nEntryTotal;
6891   u32 nSize;
6892   u32 iOffset;
6893 };
6894 
6895 /*
6896 *** 4.3.12  Central directory structure:
6897 ***
6898 *** ...
6899 ***
6900 ***   central file header signature   4 bytes  (0x02014b50)
6901 ***   version made by                 2 bytes
6902 ***   version needed to extract       2 bytes
6903 ***   general purpose bit flag        2 bytes
6904 ***   compression method              2 bytes
6905 ***   last mod file time              2 bytes
6906 ***   last mod file date              2 bytes
6907 ***   crc-32                          4 bytes
6908 ***   compressed size                 4 bytes
6909 ***   uncompressed size               4 bytes
6910 ***   file name length                2 bytes
6911 ***   extra field length              2 bytes
6912 ***   file comment length             2 bytes
6913 ***   disk number start               2 bytes
6914 ***   internal file attributes        2 bytes
6915 ***   external file attributes        4 bytes
6916 ***   relative offset of local header 4 bytes
6917 */
6918 typedef struct ZipfileCDS ZipfileCDS;
6919 struct ZipfileCDS {
6920   u16 iVersionMadeBy;
6921   u16 iVersionExtract;
6922   u16 flags;
6923   u16 iCompression;
6924   u16 mTime;
6925   u16 mDate;
6926   u32 crc32;
6927   u32 szCompressed;
6928   u32 szUncompressed;
6929   u16 nFile;
6930   u16 nExtra;
6931   u16 nComment;
6932   u16 iDiskStart;
6933   u16 iInternalAttr;
6934   u32 iExternalAttr;
6935   u32 iOffset;
6936   char *zFile;                    /* Filename (sqlite3_malloc()) */
6937 };
6938 
6939 /*
6940 *** 4.3.7  Local file header:
6941 ***
6942 ***   local file header signature     4 bytes  (0x04034b50)
6943 ***   version needed to extract       2 bytes
6944 ***   general purpose bit flag        2 bytes
6945 ***   compression method              2 bytes
6946 ***   last mod file time              2 bytes
6947 ***   last mod file date              2 bytes
6948 ***   crc-32                          4 bytes
6949 ***   compressed size                 4 bytes
6950 ***   uncompressed size               4 bytes
6951 ***   file name length                2 bytes
6952 ***   extra field length              2 bytes
6953 ***
6954 */
6955 typedef struct ZipfileLFH ZipfileLFH;
6956 struct ZipfileLFH {
6957   u16 iVersionExtract;
6958   u16 flags;
6959   u16 iCompression;
6960   u16 mTime;
6961   u16 mDate;
6962   u32 crc32;
6963   u32 szCompressed;
6964   u32 szUncompressed;
6965   u16 nFile;
6966   u16 nExtra;
6967 };
6968 
6969 typedef struct ZipfileEntry ZipfileEntry;
6970 struct ZipfileEntry {
6971   ZipfileCDS cds;            /* Parsed CDS record */
6972   u32 mUnixTime;             /* Modification time, in UNIX format */
6973   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
6974   i64 iDataOff;              /* Offset to data in file (if aData==0) */
6975   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
6976   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
6977 };
6978 
6979 /*
6980 ** Cursor type for zipfile tables.
6981 */
6982 typedef struct ZipfileCsr ZipfileCsr;
6983 struct ZipfileCsr {
6984   sqlite3_vtab_cursor base;  /* Base class - must be first */
6985   i64 iId;                   /* Cursor ID */
6986   u8 bEof;                   /* True when at EOF */
6987   u8 bNoop;                  /* If next xNext() call is no-op */
6988 
6989   /* Used outside of write transactions */
6990   FILE *pFile;               /* Zip file */
6991   i64 iNextOff;              /* Offset of next record in central directory */
6992   ZipfileEOCD eocd;          /* Parse of central directory record */
6993 
6994   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
6995   ZipfileEntry *pCurrent;    /* Current entry */
6996   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
6997 };
6998 
6999 typedef struct ZipfileTab ZipfileTab;
7000 struct ZipfileTab {
7001   sqlite3_vtab base;         /* Base class - must be first */
7002   char *zFile;               /* Zip file this table accesses (may be NULL) */
7003   sqlite3 *db;               /* Host database connection */
7004   u8 *aBuffer;               /* Temporary buffer used for various tasks */
7005 
7006   ZipfileCsr *pCsrList;      /* List of cursors */
7007   i64 iNextCsrid;
7008 
7009   /* The following are used by write transactions only */
7010   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
7011   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
7012   FILE *pWriteFd;            /* File handle open on zip archive */
7013   i64 szCurrent;             /* Current size of zip archive */
7014   i64 szOrig;                /* Size of archive at start of transaction */
7015 };
7016 
7017 /*
7018 ** Set the error message contained in context ctx to the results of
7019 ** vprintf(zFmt, ...).
7020 */
7021 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7022   char *zMsg = 0;
7023   va_list ap;
7024   va_start(ap, zFmt);
7025   zMsg = sqlite3_vmprintf(zFmt, ap);
7026   sqlite3_result_error(ctx, zMsg, -1);
7027   sqlite3_free(zMsg);
7028   va_end(ap);
7029 }
7030 
7031 /*
7032 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
7033 ** is not quoted, do nothing.
7034 */
7035 static void zipfileDequote(char *zIn){
7036   char q = zIn[0];
7037   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
7038     int iIn = 1;
7039     int iOut = 0;
7040     if( q=='[' ) q = ']';
7041     while( ALWAYS(zIn[iIn]) ){
7042       char c = zIn[iIn++];
7043       if( c==q && zIn[iIn++]!=q ) break;
7044       zIn[iOut++] = c;
7045     }
7046     zIn[iOut] = '\0';
7047   }
7048 }
7049 
7050 /*
7051 ** Construct a new ZipfileTab virtual table object.
7052 **
7053 **   argv[0]   -> module name  ("zipfile")
7054 **   argv[1]   -> database name
7055 **   argv[2]   -> table name
7056 **   argv[...] -> "column name" and other module argument fields.
7057 */
7058 static int zipfileConnect(
7059   sqlite3 *db,
7060   void *pAux,
7061   int argc, const char *const*argv,
7062   sqlite3_vtab **ppVtab,
7063   char **pzErr
7064 ){
7065   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
7066   int nFile = 0;
7067   const char *zFile = 0;
7068   ZipfileTab *pNew = 0;
7069   int rc;
7070 
7071   /* If the table name is not "zipfile", require that the argument be
7072   ** specified. This stops zipfile tables from being created as:
7073   **
7074   **   CREATE VIRTUAL TABLE zzz USING zipfile();
7075   **
7076   ** It does not prevent:
7077   **
7078   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
7079   */
7080   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
7081   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
7082     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
7083     return SQLITE_ERROR;
7084   }
7085 
7086   if( argc>3 ){
7087     zFile = argv[3];
7088     nFile = (int)strlen(zFile)+1;
7089   }
7090 
7091   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
7092   if( rc==SQLITE_OK ){
7093     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
7094     if( pNew==0 ) return SQLITE_NOMEM;
7095     memset(pNew, 0, nByte+nFile);
7096     pNew->db = db;
7097     pNew->aBuffer = (u8*)&pNew[1];
7098     if( zFile ){
7099       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
7100       memcpy(pNew->zFile, zFile, nFile);
7101       zipfileDequote(pNew->zFile);
7102     }
7103   }
7104   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7105   *ppVtab = (sqlite3_vtab*)pNew;
7106   return rc;
7107 }
7108 
7109 /*
7110 ** Free the ZipfileEntry structure indicated by the only argument.
7111 */
7112 static void zipfileEntryFree(ZipfileEntry *p){
7113   if( p ){
7114     sqlite3_free(p->cds.zFile);
7115     sqlite3_free(p);
7116   }
7117 }
7118 
7119 /*
7120 ** Release resources that should be freed at the end of a write
7121 ** transaction.
7122 */
7123 static void zipfileCleanupTransaction(ZipfileTab *pTab){
7124   ZipfileEntry *pEntry;
7125   ZipfileEntry *pNext;
7126 
7127   if( pTab->pWriteFd ){
7128     fclose(pTab->pWriteFd);
7129     pTab->pWriteFd = 0;
7130   }
7131   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
7132     pNext = pEntry->pNext;
7133     zipfileEntryFree(pEntry);
7134   }
7135   pTab->pFirstEntry = 0;
7136   pTab->pLastEntry = 0;
7137   pTab->szCurrent = 0;
7138   pTab->szOrig = 0;
7139 }
7140 
7141 /*
7142 ** This method is the destructor for zipfile vtab objects.
7143 */
7144 static int zipfileDisconnect(sqlite3_vtab *pVtab){
7145   zipfileCleanupTransaction((ZipfileTab*)pVtab);
7146   sqlite3_free(pVtab);
7147   return SQLITE_OK;
7148 }
7149 
7150 /*
7151 ** Constructor for a new ZipfileCsr object.
7152 */
7153 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
7154   ZipfileTab *pTab = (ZipfileTab*)p;
7155   ZipfileCsr *pCsr;
7156   pCsr = sqlite3_malloc(sizeof(*pCsr));
7157   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
7158   if( pCsr==0 ){
7159     return SQLITE_NOMEM;
7160   }
7161   memset(pCsr, 0, sizeof(*pCsr));
7162   pCsr->iId = ++pTab->iNextCsrid;
7163   pCsr->pCsrNext = pTab->pCsrList;
7164   pTab->pCsrList = pCsr;
7165   return SQLITE_OK;
7166 }
7167 
7168 /*
7169 ** Reset a cursor back to the state it was in when first returned
7170 ** by zipfileOpen().
7171 */
7172 static void zipfileResetCursor(ZipfileCsr *pCsr){
7173   ZipfileEntry *p;
7174   ZipfileEntry *pNext;
7175 
7176   pCsr->bEof = 0;
7177   if( pCsr->pFile ){
7178     fclose(pCsr->pFile);
7179     pCsr->pFile = 0;
7180     zipfileEntryFree(pCsr->pCurrent);
7181     pCsr->pCurrent = 0;
7182   }
7183 
7184   for(p=pCsr->pFreeEntry; p; p=pNext){
7185     pNext = p->pNext;
7186     zipfileEntryFree(p);
7187   }
7188 }
7189 
7190 /*
7191 ** Destructor for an ZipfileCsr.
7192 */
7193 static int zipfileClose(sqlite3_vtab_cursor *cur){
7194   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7195   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
7196   ZipfileCsr **pp;
7197   zipfileResetCursor(pCsr);
7198 
7199   /* Remove this cursor from the ZipfileTab.pCsrList list. */
7200   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
7201   *pp = pCsr->pCsrNext;
7202 
7203   sqlite3_free(pCsr);
7204   return SQLITE_OK;
7205 }
7206 
7207 /*
7208 ** Set the error message for the virtual table associated with cursor
7209 ** pCsr to the results of vprintf(zFmt, ...).
7210 */
7211 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
7212   va_list ap;
7213   va_start(ap, zFmt);
7214   sqlite3_free(pTab->base.zErrMsg);
7215   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
7216   va_end(ap);
7217 }
7218 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
7219   va_list ap;
7220   va_start(ap, zFmt);
7221   sqlite3_free(pCsr->base.pVtab->zErrMsg);
7222   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7223   va_end(ap);
7224 }
7225 
7226 /*
7227 ** Read nRead bytes of data from offset iOff of file pFile into buffer
7228 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
7229 ** otherwise.
7230 **
7231 ** If an error does occur, output variable (*pzErrmsg) may be set to point
7232 ** to an English language error message. It is the responsibility of the
7233 ** caller to eventually free this buffer using
7234 ** sqlite3_free().
7235 */
7236 static int zipfileReadData(
7237   FILE *pFile,                    /* Read from this file */
7238   u8 *aRead,                      /* Read into this buffer */
7239   int nRead,                      /* Number of bytes to read */
7240   i64 iOff,                       /* Offset to read from */
7241   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
7242 ){
7243   size_t n;
7244   fseek(pFile, (long)iOff, SEEK_SET);
7245   n = fread(aRead, 1, nRead, pFile);
7246   if( (int)n!=nRead ){
7247     *pzErrmsg = sqlite3_mprintf("error in fread()");
7248     return SQLITE_ERROR;
7249   }
7250   return SQLITE_OK;
7251 }
7252 
7253 static int zipfileAppendData(
7254   ZipfileTab *pTab,
7255   const u8 *aWrite,
7256   int nWrite
7257 ){
7258   if( nWrite>0 ){
7259     size_t n = nWrite;
7260     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
7261     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
7262     if( (int)n!=nWrite ){
7263       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
7264       return SQLITE_ERROR;
7265     }
7266     pTab->szCurrent += nWrite;
7267   }
7268   return SQLITE_OK;
7269 }
7270 
7271 /*
7272 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
7273 */
7274 static u16 zipfileGetU16(const u8 *aBuf){
7275   return (aBuf[1] << 8) + aBuf[0];
7276 }
7277 
7278 /*
7279 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
7280 */
7281 static u32 zipfileGetU32(const u8 *aBuf){
7282   if( aBuf==0 ) return 0;
7283   return ((u32)(aBuf[3]) << 24)
7284        + ((u32)(aBuf[2]) << 16)
7285        + ((u32)(aBuf[1]) <<  8)
7286        + ((u32)(aBuf[0]) <<  0);
7287 }
7288 
7289 /*
7290 ** Write a 16-bit little endiate integer into buffer aBuf.
7291 */
7292 static void zipfilePutU16(u8 *aBuf, u16 val){
7293   aBuf[0] = val & 0xFF;
7294   aBuf[1] = (val>>8) & 0xFF;
7295 }
7296 
7297 /*
7298 ** Write a 32-bit little endiate integer into buffer aBuf.
7299 */
7300 static void zipfilePutU32(u8 *aBuf, u32 val){
7301   aBuf[0] = val & 0xFF;
7302   aBuf[1] = (val>>8) & 0xFF;
7303   aBuf[2] = (val>>16) & 0xFF;
7304   aBuf[3] = (val>>24) & 0xFF;
7305 }
7306 
7307 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
7308 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
7309 
7310 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
7311 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
7312 
7313 /*
7314 ** Magic numbers used to read CDS records.
7315 */
7316 #define ZIPFILE_CDS_NFILE_OFF        28
7317 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
7318 
7319 /*
7320 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
7321 ** if the record is not well-formed, or SQLITE_OK otherwise.
7322 */
7323 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
7324   u8 *aRead = aBuf;
7325   u32 sig = zipfileRead32(aRead);
7326   int rc = SQLITE_OK;
7327   if( sig!=ZIPFILE_SIGNATURE_CDS ){
7328     rc = SQLITE_ERROR;
7329   }else{
7330     pCDS->iVersionMadeBy = zipfileRead16(aRead);
7331     pCDS->iVersionExtract = zipfileRead16(aRead);
7332     pCDS->flags = zipfileRead16(aRead);
7333     pCDS->iCompression = zipfileRead16(aRead);
7334     pCDS->mTime = zipfileRead16(aRead);
7335     pCDS->mDate = zipfileRead16(aRead);
7336     pCDS->crc32 = zipfileRead32(aRead);
7337     pCDS->szCompressed = zipfileRead32(aRead);
7338     pCDS->szUncompressed = zipfileRead32(aRead);
7339     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
7340     pCDS->nFile = zipfileRead16(aRead);
7341     pCDS->nExtra = zipfileRead16(aRead);
7342     pCDS->nComment = zipfileRead16(aRead);
7343     pCDS->iDiskStart = zipfileRead16(aRead);
7344     pCDS->iInternalAttr = zipfileRead16(aRead);
7345     pCDS->iExternalAttr = zipfileRead32(aRead);
7346     pCDS->iOffset = zipfileRead32(aRead);
7347     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
7348   }
7349 
7350   return rc;
7351 }
7352 
7353 /*
7354 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
7355 ** if the record is not well-formed, or SQLITE_OK otherwise.
7356 */
7357 static int zipfileReadLFH(
7358   u8 *aBuffer,
7359   ZipfileLFH *pLFH
7360 ){
7361   u8 *aRead = aBuffer;
7362   int rc = SQLITE_OK;
7363 
7364   u32 sig = zipfileRead32(aRead);
7365   if( sig!=ZIPFILE_SIGNATURE_LFH ){
7366     rc = SQLITE_ERROR;
7367   }else{
7368     pLFH->iVersionExtract = zipfileRead16(aRead);
7369     pLFH->flags = zipfileRead16(aRead);
7370     pLFH->iCompression = zipfileRead16(aRead);
7371     pLFH->mTime = zipfileRead16(aRead);
7372     pLFH->mDate = zipfileRead16(aRead);
7373     pLFH->crc32 = zipfileRead32(aRead);
7374     pLFH->szCompressed = zipfileRead32(aRead);
7375     pLFH->szUncompressed = zipfileRead32(aRead);
7376     pLFH->nFile = zipfileRead16(aRead);
7377     pLFH->nExtra = zipfileRead16(aRead);
7378   }
7379   return rc;
7380 }
7381 
7382 
7383 /*
7384 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
7385 ** Scan through this buffer to find an "extra-timestamp" field. If one
7386 ** exists, extract the 32-bit modification-timestamp from it and store
7387 ** the value in output parameter *pmTime.
7388 **
7389 ** Zero is returned if no extra-timestamp record could be found (and so
7390 ** *pmTime is left unchanged), or non-zero otherwise.
7391 **
7392 ** The general format of an extra field is:
7393 **
7394 **   Header ID    2 bytes
7395 **   Data Size    2 bytes
7396 **   Data         N bytes
7397 */
7398 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
7399   int ret = 0;
7400   u8 *p = aExtra;
7401   u8 *pEnd = &aExtra[nExtra];
7402 
7403   while( p<pEnd ){
7404     u16 id = zipfileRead16(p);
7405     u16 nByte = zipfileRead16(p);
7406 
7407     switch( id ){
7408       case ZIPFILE_EXTRA_TIMESTAMP: {
7409         u8 b = p[0];
7410         if( b & 0x01 ){     /* 0x01 -> modtime is present */
7411           *pmTime = zipfileGetU32(&p[1]);
7412           ret = 1;
7413         }
7414         break;
7415       }
7416     }
7417 
7418     p += nByte;
7419   }
7420   return ret;
7421 }
7422 
7423 /*
7424 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
7425 ** fields of the CDS structure passed as the only argument to a 32-bit
7426 ** UNIX seconds-since-the-epoch timestamp. Return the result.
7427 **
7428 ** "Standard" MS-DOS time format:
7429 **
7430 **   File modification time:
7431 **     Bits 00-04: seconds divided by 2
7432 **     Bits 05-10: minute
7433 **     Bits 11-15: hour
7434 **   File modification date:
7435 **     Bits 00-04: day
7436 **     Bits 05-08: month (1-12)
7437 **     Bits 09-15: years from 1980
7438 **
7439 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
7440 */
7441 static u32 zipfileMtime(ZipfileCDS *pCDS){
7442   int Y,M,D,X1,X2,A,B,sec,min,hr;
7443   i64 JDsec;
7444   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
7445   M = ((pCDS->mDate >> 5) & 0x0F);
7446   D = (pCDS->mDate & 0x1F);
7447   sec = (pCDS->mTime & 0x1F)*2;
7448   min = (pCDS->mTime >> 5) & 0x3F;
7449   hr = (pCDS->mTime >> 11) & 0x1F;
7450   if( M<=2 ){
7451     Y--;
7452     M += 12;
7453   }
7454   X1 = 36525*(Y+4716)/100;
7455   X2 = 306001*(M+1)/10000;
7456   A = Y/100;
7457   B = 2 - A + (A/4);
7458   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
7459   return (u32)(JDsec - (i64)24405875*(i64)8640);
7460 }
7461 
7462 /*
7463 ** The opposite of zipfileMtime(). This function populates the mTime and
7464 ** mDate fields of the CDS structure passed as the first argument according
7465 ** to the UNIX timestamp value passed as the second.
7466 */
7467 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
7468   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
7469   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
7470 
7471   int A, B, C, D, E;
7472   int yr, mon, day;
7473   int hr, min, sec;
7474 
7475   A = (int)((JD - 1867216.25)/36524.25);
7476   A = (int)(JD + 1 + A - (A/4));
7477   B = A + 1524;
7478   C = (int)((B - 122.1)/365.25);
7479   D = (36525*(C&32767))/100;
7480   E = (int)((B-D)/30.6001);
7481 
7482   day = B - D - (int)(30.6001*E);
7483   mon = (E<14 ? E-1 : E-13);
7484   yr = mon>2 ? C-4716 : C-4715;
7485 
7486   hr = (mUnixTime % (24*60*60)) / (60*60);
7487   min = (mUnixTime % (60*60)) / 60;
7488   sec = (mUnixTime % 60);
7489 
7490   if( yr>=1980 ){
7491     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
7492     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
7493   }else{
7494     pCds->mDate = pCds->mTime = 0;
7495   }
7496 
7497   assert( mUnixTime<315507600
7498        || mUnixTime==zipfileMtime(pCds)
7499        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
7500        /* || (mUnixTime % 2) */
7501   );
7502 }
7503 
7504 /*
7505 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
7506 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
7507 ** then pFile is a file-handle open on a zip file. In either case, this
7508 ** function creates a ZipfileEntry object based on the zip archive entry
7509 ** for which the CDS record is at offset iOff.
7510 **
7511 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
7512 ** the new object. Otherwise, an SQLite error code is returned and the
7513 ** final value of (*ppEntry) undefined.
7514 */
7515 static int zipfileGetEntry(
7516   ZipfileTab *pTab,               /* Store any error message here */
7517   const u8 *aBlob,                /* Pointer to in-memory file image */
7518   int nBlob,                      /* Size of aBlob[] in bytes */
7519   FILE *pFile,                    /* If aBlob==0, read from this file */
7520   i64 iOff,                       /* Offset of CDS record */
7521   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
7522 ){
7523   u8 *aRead;
7524   char **pzErr = &pTab->base.zErrMsg;
7525   int rc = SQLITE_OK;
7526 
7527   if( aBlob==0 ){
7528     aRead = pTab->aBuffer;
7529     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
7530   }else{
7531     aRead = (u8*)&aBlob[iOff];
7532   }
7533 
7534   if( rc==SQLITE_OK ){
7535     sqlite3_int64 nAlloc;
7536     ZipfileEntry *pNew;
7537 
7538     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
7539     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
7540     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
7541 
7542     nAlloc = sizeof(ZipfileEntry) + nExtra;
7543     if( aBlob ){
7544       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
7545     }
7546 
7547     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
7548     if( pNew==0 ){
7549       rc = SQLITE_NOMEM;
7550     }else{
7551       memset(pNew, 0, sizeof(ZipfileEntry));
7552       rc = zipfileReadCDS(aRead, &pNew->cds);
7553       if( rc!=SQLITE_OK ){
7554         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
7555       }else if( aBlob==0 ){
7556         rc = zipfileReadData(
7557             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
7558         );
7559       }else{
7560         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
7561       }
7562     }
7563 
7564     if( rc==SQLITE_OK ){
7565       u32 *pt = &pNew->mUnixTime;
7566       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
7567       pNew->aExtra = (u8*)&pNew[1];
7568       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
7569       if( pNew->cds.zFile==0 ){
7570         rc = SQLITE_NOMEM;
7571       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
7572         pNew->mUnixTime = zipfileMtime(&pNew->cds);
7573       }
7574     }
7575 
7576     if( rc==SQLITE_OK ){
7577       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
7578       ZipfileLFH lfh;
7579       if( pFile ){
7580         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
7581       }else{
7582         aRead = (u8*)&aBlob[pNew->cds.iOffset];
7583       }
7584 
7585       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
7586       if( rc==SQLITE_OK ){
7587         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
7588         pNew->iDataOff += lfh.nFile + lfh.nExtra;
7589         if( aBlob && pNew->cds.szCompressed ){
7590           pNew->aData = &pNew->aExtra[nExtra];
7591           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
7592         }
7593       }else{
7594         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
7595             (int)pNew->cds.iOffset
7596         );
7597       }
7598     }
7599 
7600     if( rc!=SQLITE_OK ){
7601       zipfileEntryFree(pNew);
7602     }else{
7603       *ppEntry = pNew;
7604     }
7605   }
7606 
7607   return rc;
7608 }
7609 
7610 /*
7611 ** Advance an ZipfileCsr to its next row of output.
7612 */
7613 static int zipfileNext(sqlite3_vtab_cursor *cur){
7614   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7615   int rc = SQLITE_OK;
7616 
7617   if( pCsr->pFile ){
7618     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
7619     zipfileEntryFree(pCsr->pCurrent);
7620     pCsr->pCurrent = 0;
7621     if( pCsr->iNextOff>=iEof ){
7622       pCsr->bEof = 1;
7623     }else{
7624       ZipfileEntry *p = 0;
7625       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
7626       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
7627       if( rc==SQLITE_OK ){
7628         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
7629         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
7630       }
7631       pCsr->pCurrent = p;
7632     }
7633   }else{
7634     if( !pCsr->bNoop ){
7635       pCsr->pCurrent = pCsr->pCurrent->pNext;
7636     }
7637     if( pCsr->pCurrent==0 ){
7638       pCsr->bEof = 1;
7639     }
7640   }
7641 
7642   pCsr->bNoop = 0;
7643   return rc;
7644 }
7645 
7646 static void zipfileFree(void *p) {
7647   sqlite3_free(p);
7648 }
7649 
7650 /*
7651 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
7652 ** size is nOut bytes. This function uncompresses the data and sets the
7653 ** return value in context pCtx to the result (a blob).
7654 **
7655 ** If an error occurs, an error code is left in pCtx instead.
7656 */
7657 static void zipfileInflate(
7658   sqlite3_context *pCtx,          /* Store result here */
7659   const u8 *aIn,                  /* Compressed data */
7660   int nIn,                        /* Size of buffer aIn[] in bytes */
7661   int nOut                        /* Expected output size */
7662 ){
7663   u8 *aRes = sqlite3_malloc(nOut);
7664   if( aRes==0 ){
7665     sqlite3_result_error_nomem(pCtx);
7666   }else{
7667     int err;
7668     z_stream str;
7669     memset(&str, 0, sizeof(str));
7670 
7671     str.next_in = (Byte*)aIn;
7672     str.avail_in = nIn;
7673     str.next_out = (Byte*)aRes;
7674     str.avail_out = nOut;
7675 
7676     err = inflateInit2(&str, -15);
7677     if( err!=Z_OK ){
7678       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
7679     }else{
7680       err = inflate(&str, Z_NO_FLUSH);
7681       if( err!=Z_STREAM_END ){
7682         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
7683       }else{
7684         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
7685         aRes = 0;
7686       }
7687     }
7688     sqlite3_free(aRes);
7689     inflateEnd(&str);
7690   }
7691 }
7692 
7693 /*
7694 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
7695 ** compresses it and sets (*ppOut) to point to a buffer containing the
7696 ** compressed data. The caller is responsible for eventually calling
7697 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
7698 ** is set to the size of buffer (*ppOut) in bytes.
7699 **
7700 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
7701 ** code is returned and an error message left in virtual-table handle
7702 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
7703 ** case.
7704 */
7705 static int zipfileDeflate(
7706   const u8 *aIn, int nIn,         /* Input */
7707   u8 **ppOut, int *pnOut,         /* Output */
7708   char **pzErr                    /* OUT: Error message */
7709 ){
7710   int rc = SQLITE_OK;
7711   sqlite3_int64 nAlloc;
7712   z_stream str;
7713   u8 *aOut;
7714 
7715   memset(&str, 0, sizeof(str));
7716   str.next_in = (Bytef*)aIn;
7717   str.avail_in = nIn;
7718   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
7719 
7720   nAlloc = deflateBound(&str, nIn);
7721   aOut = (u8*)sqlite3_malloc64(nAlloc);
7722   if( aOut==0 ){
7723     rc = SQLITE_NOMEM;
7724   }else{
7725     int res;
7726     str.next_out = aOut;
7727     str.avail_out = nAlloc;
7728     res = deflate(&str, Z_FINISH);
7729     if( res==Z_STREAM_END ){
7730       *ppOut = aOut;
7731       *pnOut = (int)str.total_out;
7732     }else{
7733       sqlite3_free(aOut);
7734       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
7735       rc = SQLITE_ERROR;
7736     }
7737     deflateEnd(&str);
7738   }
7739 
7740   return rc;
7741 }
7742 
7743 
7744 /*
7745 ** Return values of columns for the row at which the series_cursor
7746 ** is currently pointing.
7747 */
7748 static int zipfileColumn(
7749   sqlite3_vtab_cursor *cur,   /* The cursor */
7750   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7751   int i                       /* Which column to return */
7752 ){
7753   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7754   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
7755   int rc = SQLITE_OK;
7756   switch( i ){
7757     case 0:   /* name */
7758       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
7759       break;
7760     case 1:   /* mode */
7761       /* TODO: Whether or not the following is correct surely depends on
7762       ** the platform on which the archive was created.  */
7763       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
7764       break;
7765     case 2: { /* mtime */
7766       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
7767       break;
7768     }
7769     case 3: { /* sz */
7770       if( sqlite3_vtab_nochange(ctx)==0 ){
7771         sqlite3_result_int64(ctx, pCDS->szUncompressed);
7772       }
7773       break;
7774     }
7775     case 4:   /* rawdata */
7776       if( sqlite3_vtab_nochange(ctx) ) break;
7777     case 5: { /* data */
7778       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
7779         int sz = pCDS->szCompressed;
7780         int szFinal = pCDS->szUncompressed;
7781         if( szFinal>0 ){
7782           u8 *aBuf;
7783           u8 *aFree = 0;
7784           if( pCsr->pCurrent->aData ){
7785             aBuf = pCsr->pCurrent->aData;
7786           }else{
7787             aBuf = aFree = sqlite3_malloc64(sz);
7788             if( aBuf==0 ){
7789               rc = SQLITE_NOMEM;
7790             }else{
7791               FILE *pFile = pCsr->pFile;
7792               if( pFile==0 ){
7793                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
7794               }
7795               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
7796                   &pCsr->base.pVtab->zErrMsg
7797               );
7798             }
7799           }
7800           if( rc==SQLITE_OK ){
7801             if( i==5 && pCDS->iCompression ){
7802               zipfileInflate(ctx, aBuf, sz, szFinal);
7803             }else{
7804               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
7805             }
7806           }
7807           sqlite3_free(aFree);
7808         }else{
7809           /* Figure out if this is a directory or a zero-sized file. Consider
7810           ** it to be a directory either if the mode suggests so, or if
7811           ** the final character in the name is '/'.  */
7812           u32 mode = pCDS->iExternalAttr >> 16;
7813           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
7814             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
7815           }
7816         }
7817       }
7818       break;
7819     }
7820     case 6:   /* method */
7821       sqlite3_result_int(ctx, pCDS->iCompression);
7822       break;
7823     default:  /* z */
7824       assert( i==7 );
7825       sqlite3_result_int64(ctx, pCsr->iId);
7826       break;
7827   }
7828 
7829   return rc;
7830 }
7831 
7832 /*
7833 ** Return TRUE if the cursor is at EOF.
7834 */
7835 static int zipfileEof(sqlite3_vtab_cursor *cur){
7836   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7837   return pCsr->bEof;
7838 }
7839 
7840 /*
7841 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
7842 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
7843 ** is guaranteed to be a file-handle open on a zip file.
7844 **
7845 ** This function attempts to locate the EOCD record within the zip archive
7846 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
7847 ** returned if successful. Otherwise, an SQLite error code is returned and
7848 ** an English language error message may be left in virtual-table pTab.
7849 */
7850 static int zipfileReadEOCD(
7851   ZipfileTab *pTab,               /* Return errors here */
7852   const u8 *aBlob,                /* Pointer to in-memory file image */
7853   int nBlob,                      /* Size of aBlob[] in bytes */
7854   FILE *pFile,                    /* Read from this file if aBlob==0 */
7855   ZipfileEOCD *pEOCD              /* Object to populate */
7856 ){
7857   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
7858   int nRead;                      /* Bytes to read from file */
7859   int rc = SQLITE_OK;
7860 
7861   memset(pEOCD, 0, sizeof(ZipfileEOCD));
7862   if( aBlob==0 ){
7863     i64 iOff;                     /* Offset to read from */
7864     i64 szFile;                   /* Total size of file in bytes */
7865     fseek(pFile, 0, SEEK_END);
7866     szFile = (i64)ftell(pFile);
7867     if( szFile==0 ){
7868       return SQLITE_OK;
7869     }
7870     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
7871     iOff = szFile - nRead;
7872     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
7873   }else{
7874     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
7875     aRead = (u8*)&aBlob[nBlob-nRead];
7876   }
7877 
7878   if( rc==SQLITE_OK ){
7879     int i;
7880 
7881     /* Scan backwards looking for the signature bytes */
7882     for(i=nRead-20; i>=0; i--){
7883       if( aRead[i]==0x50 && aRead[i+1]==0x4b
7884        && aRead[i+2]==0x05 && aRead[i+3]==0x06
7885       ){
7886         break;
7887       }
7888     }
7889     if( i<0 ){
7890       pTab->base.zErrMsg = sqlite3_mprintf(
7891           "cannot find end of central directory record"
7892       );
7893       return SQLITE_ERROR;
7894     }
7895 
7896     aRead += i+4;
7897     pEOCD->iDisk = zipfileRead16(aRead);
7898     pEOCD->iFirstDisk = zipfileRead16(aRead);
7899     pEOCD->nEntry = zipfileRead16(aRead);
7900     pEOCD->nEntryTotal = zipfileRead16(aRead);
7901     pEOCD->nSize = zipfileRead32(aRead);
7902     pEOCD->iOffset = zipfileRead32(aRead);
7903   }
7904 
7905   return rc;
7906 }
7907 
7908 /*
7909 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
7910 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
7911 ** to the end of the list. Otherwise, it is added to the list immediately
7912 ** before pBefore (which is guaranteed to be a part of said list).
7913 */
7914 static void zipfileAddEntry(
7915   ZipfileTab *pTab,
7916   ZipfileEntry *pBefore,
7917   ZipfileEntry *pNew
7918 ){
7919   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
7920   assert( pNew->pNext==0 );
7921   if( pBefore==0 ){
7922     if( pTab->pFirstEntry==0 ){
7923       pTab->pFirstEntry = pTab->pLastEntry = pNew;
7924     }else{
7925       assert( pTab->pLastEntry->pNext==0 );
7926       pTab->pLastEntry->pNext = pNew;
7927       pTab->pLastEntry = pNew;
7928     }
7929   }else{
7930     ZipfileEntry **pp;
7931     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
7932     pNew->pNext = pBefore;
7933     *pp = pNew;
7934   }
7935 }
7936 
7937 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
7938   ZipfileEOCD eocd;
7939   int rc;
7940   int i;
7941   i64 iOff;
7942 
7943   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
7944   iOff = eocd.iOffset;
7945   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
7946     ZipfileEntry *pNew = 0;
7947     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
7948 
7949     if( rc==SQLITE_OK ){
7950       zipfileAddEntry(pTab, 0, pNew);
7951       iOff += ZIPFILE_CDS_FIXED_SZ;
7952       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
7953     }
7954   }
7955   return rc;
7956 }
7957 
7958 /*
7959 ** xFilter callback.
7960 */
7961 static int zipfileFilter(
7962   sqlite3_vtab_cursor *cur,
7963   int idxNum, const char *idxStr,
7964   int argc, sqlite3_value **argv
7965 ){
7966   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
7967   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
7968   const char *zFile = 0;          /* Zip file to scan */
7969   int rc = SQLITE_OK;             /* Return Code */
7970   int bInMemory = 0;              /* True for an in-memory zipfile */
7971 
7972   zipfileResetCursor(pCsr);
7973 
7974   if( pTab->zFile ){
7975     zFile = pTab->zFile;
7976   }else if( idxNum==0 ){
7977     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
7978     return SQLITE_ERROR;
7979   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
7980     static const u8 aEmptyBlob = 0;
7981     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
7982     int nBlob = sqlite3_value_bytes(argv[0]);
7983     assert( pTab->pFirstEntry==0 );
7984     if( aBlob==0 ){
7985       aBlob = &aEmptyBlob;
7986       nBlob = 0;
7987     }
7988     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
7989     pCsr->pFreeEntry = pTab->pFirstEntry;
7990     pTab->pFirstEntry = pTab->pLastEntry = 0;
7991     if( rc!=SQLITE_OK ) return rc;
7992     bInMemory = 1;
7993   }else{
7994     zFile = (const char*)sqlite3_value_text(argv[0]);
7995   }
7996 
7997   if( 0==pTab->pWriteFd && 0==bInMemory ){
7998     pCsr->pFile = fopen(zFile, "rb");
7999     if( pCsr->pFile==0 ){
8000       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
8001       rc = SQLITE_ERROR;
8002     }else{
8003       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
8004       if( rc==SQLITE_OK ){
8005         if( pCsr->eocd.nEntry==0 ){
8006           pCsr->bEof = 1;
8007         }else{
8008           pCsr->iNextOff = pCsr->eocd.iOffset;
8009           rc = zipfileNext(cur);
8010         }
8011       }
8012     }
8013   }else{
8014     pCsr->bNoop = 1;
8015     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
8016     rc = zipfileNext(cur);
8017   }
8018 
8019   return rc;
8020 }
8021 
8022 /*
8023 ** xBestIndex callback.
8024 */
8025 static int zipfileBestIndex(
8026   sqlite3_vtab *tab,
8027   sqlite3_index_info *pIdxInfo
8028 ){
8029   int i;
8030   int idx = -1;
8031   int unusable = 0;
8032 
8033   for(i=0; i<pIdxInfo->nConstraint; i++){
8034     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
8035     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
8036     if( pCons->usable==0 ){
8037       unusable = 1;
8038     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
8039       idx = i;
8040     }
8041   }
8042   pIdxInfo->estimatedCost = 1000.0;
8043   if( idx>=0 ){
8044     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
8045     pIdxInfo->aConstraintUsage[idx].omit = 1;
8046     pIdxInfo->idxNum = 1;
8047   }else if( unusable ){
8048     return SQLITE_CONSTRAINT;
8049   }
8050   return SQLITE_OK;
8051 }
8052 
8053 static ZipfileEntry *zipfileNewEntry(const char *zPath){
8054   ZipfileEntry *pNew;
8055   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
8056   if( pNew ){
8057     memset(pNew, 0, sizeof(ZipfileEntry));
8058     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
8059     if( pNew->cds.zFile==0 ){
8060       sqlite3_free(pNew);
8061       pNew = 0;
8062     }
8063   }
8064   return pNew;
8065 }
8066 
8067 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
8068   ZipfileCDS *pCds = &pEntry->cds;
8069   u8 *a = aBuf;
8070 
8071   pCds->nExtra = 9;
8072 
8073   /* Write the LFH itself */
8074   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
8075   zipfileWrite16(a, pCds->iVersionExtract);
8076   zipfileWrite16(a, pCds->flags);
8077   zipfileWrite16(a, pCds->iCompression);
8078   zipfileWrite16(a, pCds->mTime);
8079   zipfileWrite16(a, pCds->mDate);
8080   zipfileWrite32(a, pCds->crc32);
8081   zipfileWrite32(a, pCds->szCompressed);
8082   zipfileWrite32(a, pCds->szUncompressed);
8083   zipfileWrite16(a, (u16)pCds->nFile);
8084   zipfileWrite16(a, pCds->nExtra);
8085   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
8086 
8087   /* Add the file name */
8088   memcpy(a, pCds->zFile, (int)pCds->nFile);
8089   a += (int)pCds->nFile;
8090 
8091   /* The "extra" data */
8092   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
8093   zipfileWrite16(a, 5);
8094   *a++ = 0x01;
8095   zipfileWrite32(a, pEntry->mUnixTime);
8096 
8097   return a-aBuf;
8098 }
8099 
8100 static int zipfileAppendEntry(
8101   ZipfileTab *pTab,
8102   ZipfileEntry *pEntry,
8103   const u8 *pData,
8104   int nData
8105 ){
8106   u8 *aBuf = pTab->aBuffer;
8107   int nBuf;
8108   int rc;
8109 
8110   nBuf = zipfileSerializeLFH(pEntry, aBuf);
8111   rc = zipfileAppendData(pTab, aBuf, nBuf);
8112   if( rc==SQLITE_OK ){
8113     pEntry->iDataOff = pTab->szCurrent;
8114     rc = zipfileAppendData(pTab, pData, nData);
8115   }
8116 
8117   return rc;
8118 }
8119 
8120 static int zipfileGetMode(
8121   sqlite3_value *pVal,
8122   int bIsDir,                     /* If true, default to directory */
8123   u32 *pMode,                     /* OUT: Mode value */
8124   char **pzErr                    /* OUT: Error message */
8125 ){
8126   const char *z = (const char*)sqlite3_value_text(pVal);
8127   u32 mode = 0;
8128   if( z==0 ){
8129     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
8130   }else if( z[0]>='0' && z[0]<='9' ){
8131     mode = (unsigned int)sqlite3_value_int(pVal);
8132   }else{
8133     const char zTemplate[11] = "-rwxrwxrwx";
8134     int i;
8135     if( strlen(z)!=10 ) goto parse_error;
8136     switch( z[0] ){
8137       case '-': mode |= S_IFREG; break;
8138       case 'd': mode |= S_IFDIR; break;
8139       case 'l': mode |= S_IFLNK; break;
8140       default: goto parse_error;
8141     }
8142     for(i=1; i<10; i++){
8143       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
8144       else if( z[i]!='-' ) goto parse_error;
8145     }
8146   }
8147   if( ((mode & S_IFDIR)==0)==bIsDir ){
8148     /* The "mode" attribute is a directory, but data has been specified.
8149     ** Or vice-versa - no data but "mode" is a file or symlink.  */
8150     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
8151     return SQLITE_CONSTRAINT;
8152   }
8153   *pMode = mode;
8154   return SQLITE_OK;
8155 
8156  parse_error:
8157   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
8158   return SQLITE_ERROR;
8159 }
8160 
8161 /*
8162 ** Both (const char*) arguments point to nul-terminated strings. Argument
8163 ** nB is the value of strlen(zB). This function returns 0 if the strings are
8164 ** identical, ignoring any trailing '/' character in either path.  */
8165 static int zipfileComparePath(const char *zA, const char *zB, int nB){
8166   int nA = (int)strlen(zA);
8167   if( nA>0 && zA[nA-1]=='/' ) nA--;
8168   if( nB>0 && zB[nB-1]=='/' ) nB--;
8169   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
8170   return 1;
8171 }
8172 
8173 static int zipfileBegin(sqlite3_vtab *pVtab){
8174   ZipfileTab *pTab = (ZipfileTab*)pVtab;
8175   int rc = SQLITE_OK;
8176 
8177   assert( pTab->pWriteFd==0 );
8178   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
8179     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
8180     return SQLITE_ERROR;
8181   }
8182 
8183   /* Open a write fd on the file. Also load the entire central directory
8184   ** structure into memory. During the transaction any new file data is
8185   ** appended to the archive file, but the central directory is accumulated
8186   ** in main-memory until the transaction is committed.  */
8187   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
8188   if( pTab->pWriteFd==0 ){
8189     pTab->base.zErrMsg = sqlite3_mprintf(
8190         "zipfile: failed to open file %s for writing", pTab->zFile
8191         );
8192     rc = SQLITE_ERROR;
8193   }else{
8194     fseek(pTab->pWriteFd, 0, SEEK_END);
8195     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
8196     rc = zipfileLoadDirectory(pTab, 0, 0);
8197   }
8198 
8199   if( rc!=SQLITE_OK ){
8200     zipfileCleanupTransaction(pTab);
8201   }
8202 
8203   return rc;
8204 }
8205 
8206 /*
8207 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
8208 ** time(2)).
8209 */
8210 static u32 zipfileTime(void){
8211   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
8212   u32 ret;
8213   if( pVfs==0 ) return 0;
8214   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
8215     i64 ms;
8216     pVfs->xCurrentTimeInt64(pVfs, &ms);
8217     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
8218   }else{
8219     double day;
8220     pVfs->xCurrentTime(pVfs, &day);
8221     ret = (u32)((day - 2440587.5) * 86400);
8222   }
8223   return ret;
8224 }
8225 
8226 /*
8227 ** Return a 32-bit timestamp in UNIX epoch format.
8228 **
8229 ** If the value passed as the only argument is either NULL or an SQL NULL,
8230 ** return the current time. Otherwise, return the value stored in (*pVal)
8231 ** cast to a 32-bit unsigned integer.
8232 */
8233 static u32 zipfileGetTime(sqlite3_value *pVal){
8234   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
8235     return zipfileTime();
8236   }
8237   return (u32)sqlite3_value_int64(pVal);
8238 }
8239 
8240 /*
8241 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
8242 ** linked list.  Remove it from the list and free the object.
8243 */
8244 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
8245   if( pOld ){
8246     ZipfileEntry **pp;
8247     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
8248     *pp = (*pp)->pNext;
8249     zipfileEntryFree(pOld);
8250   }
8251 }
8252 
8253 /*
8254 ** xUpdate method.
8255 */
8256 static int zipfileUpdate(
8257   sqlite3_vtab *pVtab,
8258   int nVal,
8259   sqlite3_value **apVal,
8260   sqlite_int64 *pRowid
8261 ){
8262   ZipfileTab *pTab = (ZipfileTab*)pVtab;
8263   int rc = SQLITE_OK;             /* Return Code */
8264   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
8265 
8266   u32 mode = 0;                   /* Mode for new entry */
8267   u32 mTime = 0;                  /* Modification time for new entry */
8268   i64 sz = 0;                     /* Uncompressed size */
8269   const char *zPath = 0;          /* Path for new entry */
8270   int nPath = 0;                  /* strlen(zPath) */
8271   const u8 *pData = 0;            /* Pointer to buffer containing content */
8272   int nData = 0;                  /* Size of pData buffer in bytes */
8273   int iMethod = 0;                /* Compression method for new entry */
8274   u8 *pFree = 0;                  /* Free this */
8275   char *zFree = 0;                /* Also free this */
8276   ZipfileEntry *pOld = 0;
8277   ZipfileEntry *pOld2 = 0;
8278   int bUpdate = 0;                /* True for an update that modifies "name" */
8279   int bIsDir = 0;
8280   u32 iCrc32 = 0;
8281 
8282   if( pTab->pWriteFd==0 ){
8283     rc = zipfileBegin(pVtab);
8284     if( rc!=SQLITE_OK ) return rc;
8285   }
8286 
8287   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
8288   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
8289     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
8290     int nDelete = (int)strlen(zDelete);
8291     if( nVal>1 ){
8292       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
8293       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
8294         bUpdate = 1;
8295       }
8296     }
8297     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
8298       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
8299         break;
8300       }
8301       assert( pOld->pNext );
8302     }
8303   }
8304 
8305   if( nVal>1 ){
8306     /* Check that "sz" and "rawdata" are both NULL: */
8307     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
8308       zipfileTableErr(pTab, "sz must be NULL");
8309       rc = SQLITE_CONSTRAINT;
8310     }
8311     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
8312       zipfileTableErr(pTab, "rawdata must be NULL");
8313       rc = SQLITE_CONSTRAINT;
8314     }
8315 
8316     if( rc==SQLITE_OK ){
8317       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
8318         /* data=NULL. A directory */
8319         bIsDir = 1;
8320       }else{
8321         /* Value specified for "data", and possibly "method". This must be
8322         ** a regular file or a symlink. */
8323         const u8 *aIn = sqlite3_value_blob(apVal[7]);
8324         int nIn = sqlite3_value_bytes(apVal[7]);
8325         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
8326 
8327         iMethod = sqlite3_value_int(apVal[8]);
8328         sz = nIn;
8329         pData = aIn;
8330         nData = nIn;
8331         if( iMethod!=0 && iMethod!=8 ){
8332           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
8333           rc = SQLITE_CONSTRAINT;
8334         }else{
8335           if( bAuto || iMethod ){
8336             int nCmp;
8337             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
8338             if( rc==SQLITE_OK ){
8339               if( iMethod || nCmp<nIn ){
8340                 iMethod = 8;
8341                 pData = pFree;
8342                 nData = nCmp;
8343               }
8344             }
8345           }
8346           iCrc32 = crc32(0, aIn, nIn);
8347         }
8348       }
8349     }
8350 
8351     if( rc==SQLITE_OK ){
8352       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
8353     }
8354 
8355     if( rc==SQLITE_OK ){
8356       zPath = (const char*)sqlite3_value_text(apVal[2]);
8357       if( zPath==0 ) zPath = "";
8358       nPath = (int)strlen(zPath);
8359       mTime = zipfileGetTime(apVal[4]);
8360     }
8361 
8362     if( rc==SQLITE_OK && bIsDir ){
8363       /* For a directory, check that the last character in the path is a
8364       ** '/'. This appears to be required for compatibility with info-zip
8365       ** (the unzip command on unix). It does not create directories
8366       ** otherwise.  */
8367       if( nPath<=0 || zPath[nPath-1]!='/' ){
8368         zFree = sqlite3_mprintf("%s/", zPath);
8369         zPath = (const char*)zFree;
8370         if( zFree==0 ){
8371           rc = SQLITE_NOMEM;
8372           nPath = 0;
8373         }else{
8374           nPath = (int)strlen(zPath);
8375         }
8376       }
8377     }
8378 
8379     /* Check that we're not inserting a duplicate entry -OR- updating an
8380     ** entry with a path, thereby making it into a duplicate. */
8381     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
8382       ZipfileEntry *p;
8383       for(p=pTab->pFirstEntry; p; p=p->pNext){
8384         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
8385           switch( sqlite3_vtab_on_conflict(pTab->db) ){
8386             case SQLITE_IGNORE: {
8387               goto zipfile_update_done;
8388             }
8389             case SQLITE_REPLACE: {
8390               pOld2 = p;
8391               break;
8392             }
8393             default: {
8394               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
8395               rc = SQLITE_CONSTRAINT;
8396               break;
8397             }
8398           }
8399           break;
8400         }
8401       }
8402     }
8403 
8404     if( rc==SQLITE_OK ){
8405       /* Create the new CDS record. */
8406       pNew = zipfileNewEntry(zPath);
8407       if( pNew==0 ){
8408         rc = SQLITE_NOMEM;
8409       }else{
8410         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
8411         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
8412         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
8413         pNew->cds.iCompression = (u16)iMethod;
8414         zipfileMtimeToDos(&pNew->cds, mTime);
8415         pNew->cds.crc32 = iCrc32;
8416         pNew->cds.szCompressed = nData;
8417         pNew->cds.szUncompressed = (u32)sz;
8418         pNew->cds.iExternalAttr = (mode<<16);
8419         pNew->cds.iOffset = (u32)pTab->szCurrent;
8420         pNew->cds.nFile = (u16)nPath;
8421         pNew->mUnixTime = (u32)mTime;
8422         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
8423         zipfileAddEntry(pTab, pOld, pNew);
8424       }
8425     }
8426   }
8427 
8428   if( rc==SQLITE_OK && (pOld || pOld2) ){
8429     ZipfileCsr *pCsr;
8430     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
8431       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
8432         pCsr->pCurrent = pCsr->pCurrent->pNext;
8433         pCsr->bNoop = 1;
8434       }
8435     }
8436 
8437     zipfileRemoveEntryFromList(pTab, pOld);
8438     zipfileRemoveEntryFromList(pTab, pOld2);
8439   }
8440 
8441 zipfile_update_done:
8442   sqlite3_free(pFree);
8443   sqlite3_free(zFree);
8444   return rc;
8445 }
8446 
8447 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
8448   u8 *a = aBuf;
8449   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
8450   zipfileWrite16(a, p->iDisk);
8451   zipfileWrite16(a, p->iFirstDisk);
8452   zipfileWrite16(a, p->nEntry);
8453   zipfileWrite16(a, p->nEntryTotal);
8454   zipfileWrite32(a, p->nSize);
8455   zipfileWrite32(a, p->iOffset);
8456   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
8457 
8458   return a-aBuf;
8459 }
8460 
8461 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
8462   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
8463   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
8464   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
8465 }
8466 
8467 /*
8468 ** Serialize the CDS structure into buffer aBuf[]. Return the number
8469 ** of bytes written.
8470 */
8471 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
8472   u8 *a = aBuf;
8473   ZipfileCDS *pCDS = &pEntry->cds;
8474 
8475   if( pEntry->aExtra==0 ){
8476     pCDS->nExtra = 9;
8477   }
8478 
8479   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
8480   zipfileWrite16(a, pCDS->iVersionMadeBy);
8481   zipfileWrite16(a, pCDS->iVersionExtract);
8482   zipfileWrite16(a, pCDS->flags);
8483   zipfileWrite16(a, pCDS->iCompression);
8484   zipfileWrite16(a, pCDS->mTime);
8485   zipfileWrite16(a, pCDS->mDate);
8486   zipfileWrite32(a, pCDS->crc32);
8487   zipfileWrite32(a, pCDS->szCompressed);
8488   zipfileWrite32(a, pCDS->szUncompressed);
8489   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
8490   zipfileWrite16(a, pCDS->nFile);
8491   zipfileWrite16(a, pCDS->nExtra);
8492   zipfileWrite16(a, pCDS->nComment);
8493   zipfileWrite16(a, pCDS->iDiskStart);
8494   zipfileWrite16(a, pCDS->iInternalAttr);
8495   zipfileWrite32(a, pCDS->iExternalAttr);
8496   zipfileWrite32(a, pCDS->iOffset);
8497 
8498   memcpy(a, pCDS->zFile, pCDS->nFile);
8499   a += pCDS->nFile;
8500 
8501   if( pEntry->aExtra ){
8502     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
8503     memcpy(a, pEntry->aExtra, n);
8504     a += n;
8505   }else{
8506     assert( pCDS->nExtra==9 );
8507     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
8508     zipfileWrite16(a, 5);
8509     *a++ = 0x01;
8510     zipfileWrite32(a, pEntry->mUnixTime);
8511   }
8512 
8513   return a-aBuf;
8514 }
8515 
8516 static int zipfileCommit(sqlite3_vtab *pVtab){
8517   ZipfileTab *pTab = (ZipfileTab*)pVtab;
8518   int rc = SQLITE_OK;
8519   if( pTab->pWriteFd ){
8520     i64 iOffset = pTab->szCurrent;
8521     ZipfileEntry *p;
8522     ZipfileEOCD eocd;
8523     int nEntry = 0;
8524 
8525     /* Write out all entries */
8526     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
8527       int n = zipfileSerializeCDS(p, pTab->aBuffer);
8528       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
8529       nEntry++;
8530     }
8531 
8532     /* Write out the EOCD record */
8533     eocd.iDisk = 0;
8534     eocd.iFirstDisk = 0;
8535     eocd.nEntry = (u16)nEntry;
8536     eocd.nEntryTotal = (u16)nEntry;
8537     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
8538     eocd.iOffset = (u32)iOffset;
8539     rc = zipfileAppendEOCD(pTab, &eocd);
8540 
8541     zipfileCleanupTransaction(pTab);
8542   }
8543   return rc;
8544 }
8545 
8546 static int zipfileRollback(sqlite3_vtab *pVtab){
8547   return zipfileCommit(pVtab);
8548 }
8549 
8550 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
8551   ZipfileCsr *pCsr;
8552   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
8553     if( iId==pCsr->iId ) break;
8554   }
8555   return pCsr;
8556 }
8557 
8558 static void zipfileFunctionCds(
8559   sqlite3_context *context,
8560   int argc,
8561   sqlite3_value **argv
8562 ){
8563   ZipfileCsr *pCsr;
8564   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
8565   assert( argc>0 );
8566 
8567   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
8568   if( pCsr ){
8569     ZipfileCDS *p = &pCsr->pCurrent->cds;
8570     char *zRes = sqlite3_mprintf("{"
8571         "\"version-made-by\" : %u, "
8572         "\"version-to-extract\" : %u, "
8573         "\"flags\" : %u, "
8574         "\"compression\" : %u, "
8575         "\"time\" : %u, "
8576         "\"date\" : %u, "
8577         "\"crc32\" : %u, "
8578         "\"compressed-size\" : %u, "
8579         "\"uncompressed-size\" : %u, "
8580         "\"file-name-length\" : %u, "
8581         "\"extra-field-length\" : %u, "
8582         "\"file-comment-length\" : %u, "
8583         "\"disk-number-start\" : %u, "
8584         "\"internal-attr\" : %u, "
8585         "\"external-attr\" : %u, "
8586         "\"offset\" : %u }",
8587         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
8588         (u32)p->flags, (u32)p->iCompression,
8589         (u32)p->mTime, (u32)p->mDate,
8590         (u32)p->crc32, (u32)p->szCompressed,
8591         (u32)p->szUncompressed, (u32)p->nFile,
8592         (u32)p->nExtra, (u32)p->nComment,
8593         (u32)p->iDiskStart, (u32)p->iInternalAttr,
8594         (u32)p->iExternalAttr, (u32)p->iOffset
8595     );
8596 
8597     if( zRes==0 ){
8598       sqlite3_result_error_nomem(context);
8599     }else{
8600       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
8601       sqlite3_free(zRes);
8602     }
8603   }
8604 }
8605 
8606 /*
8607 ** xFindFunction method.
8608 */
8609 static int zipfileFindFunction(
8610   sqlite3_vtab *pVtab,            /* Virtual table handle */
8611   int nArg,                       /* Number of SQL function arguments */
8612   const char *zName,              /* Name of SQL function */
8613   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
8614   void **ppArg                    /* OUT: User data for *pxFunc */
8615 ){
8616   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
8617     *pxFunc = zipfileFunctionCds;
8618     *ppArg = (void*)pVtab;
8619     return 1;
8620   }
8621   return 0;
8622 }
8623 
8624 typedef struct ZipfileBuffer ZipfileBuffer;
8625 struct ZipfileBuffer {
8626   u8 *a;                          /* Pointer to buffer */
8627   int n;                          /* Size of buffer in bytes */
8628   int nAlloc;                     /* Byte allocated at a[] */
8629 };
8630 
8631 typedef struct ZipfileCtx ZipfileCtx;
8632 struct ZipfileCtx {
8633   int nEntry;
8634   ZipfileBuffer body;
8635   ZipfileBuffer cds;
8636 };
8637 
8638 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
8639   if( pBuf->n+nByte>pBuf->nAlloc ){
8640     u8 *aNew;
8641     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
8642     int nReq = pBuf->n + nByte;
8643 
8644     while( nNew<nReq ) nNew = nNew*2;
8645     aNew = sqlite3_realloc64(pBuf->a, nNew);
8646     if( aNew==0 ) return SQLITE_NOMEM;
8647     pBuf->a = aNew;
8648     pBuf->nAlloc = (int)nNew;
8649   }
8650   return SQLITE_OK;
8651 }
8652 
8653 /*
8654 ** xStep() callback for the zipfile() aggregate. This can be called in
8655 ** any of the following ways:
8656 **
8657 **   SELECT zipfile(name,data) ...
8658 **   SELECT zipfile(name,mode,mtime,data) ...
8659 **   SELECT zipfile(name,mode,mtime,data,method) ...
8660 */
8661 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
8662   ZipfileCtx *p;                  /* Aggregate function context */
8663   ZipfileEntry e;                 /* New entry to add to zip archive */
8664 
8665   sqlite3_value *pName = 0;
8666   sqlite3_value *pMode = 0;
8667   sqlite3_value *pMtime = 0;
8668   sqlite3_value *pData = 0;
8669   sqlite3_value *pMethod = 0;
8670 
8671   int bIsDir = 0;
8672   u32 mode;
8673   int rc = SQLITE_OK;
8674   char *zErr = 0;
8675 
8676   int iMethod = -1;               /* Compression method to use (0 or 8) */
8677 
8678   const u8 *aData = 0;            /* Possibly compressed data for new entry */
8679   int nData = 0;                  /* Size of aData[] in bytes */
8680   int szUncompressed = 0;         /* Size of data before compression */
8681   u8 *aFree = 0;                  /* Free this before returning */
8682   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
8683 
8684   char *zName = 0;                /* Path (name) of new entry */
8685   int nName = 0;                  /* Size of zName in bytes */
8686   char *zFree = 0;                /* Free this before returning */
8687   int nByte;
8688 
8689   memset(&e, 0, sizeof(e));
8690   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
8691   if( p==0 ) return;
8692 
8693   /* Martial the arguments into stack variables */
8694   if( nVal!=2 && nVal!=4 && nVal!=5 ){
8695     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
8696     rc = SQLITE_ERROR;
8697     goto zipfile_step_out;
8698   }
8699   pName = apVal[0];
8700   if( nVal==2 ){
8701     pData = apVal[1];
8702   }else{
8703     pMode = apVal[1];
8704     pMtime = apVal[2];
8705     pData = apVal[3];
8706     if( nVal==5 ){
8707       pMethod = apVal[4];
8708     }
8709   }
8710 
8711   /* Check that the 'name' parameter looks ok. */
8712   zName = (char*)sqlite3_value_text(pName);
8713   nName = sqlite3_value_bytes(pName);
8714   if( zName==0 ){
8715     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
8716     rc = SQLITE_ERROR;
8717     goto zipfile_step_out;
8718   }
8719 
8720   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
8721   ** deflate compression) or NULL (choose automatically).  */
8722   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
8723     iMethod = (int)sqlite3_value_int64(pMethod);
8724     if( iMethod!=0 && iMethod!=8 ){
8725       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
8726       rc = SQLITE_ERROR;
8727       goto zipfile_step_out;
8728     }
8729   }
8730 
8731   /* Now inspect the data. If this is NULL, then the new entry must be a
8732   ** directory.  Otherwise, figure out whether or not the data should
8733   ** be deflated or simply stored in the zip archive. */
8734   if( sqlite3_value_type(pData)==SQLITE_NULL ){
8735     bIsDir = 1;
8736     iMethod = 0;
8737   }else{
8738     aData = sqlite3_value_blob(pData);
8739     szUncompressed = nData = sqlite3_value_bytes(pData);
8740     iCrc32 = crc32(0, aData, nData);
8741     if( iMethod<0 || iMethod==8 ){
8742       int nOut = 0;
8743       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
8744       if( rc!=SQLITE_OK ){
8745         goto zipfile_step_out;
8746       }
8747       if( iMethod==8 || nOut<nData ){
8748         aData = aFree;
8749         nData = nOut;
8750         iMethod = 8;
8751       }else{
8752         iMethod = 0;
8753       }
8754     }
8755   }
8756 
8757   /* Decode the "mode" argument. */
8758   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
8759   if( rc ) goto zipfile_step_out;
8760 
8761   /* Decode the "mtime" argument. */
8762   e.mUnixTime = zipfileGetTime(pMtime);
8763 
8764   /* If this is a directory entry, ensure that there is exactly one '/'
8765   ** at the end of the path. Or, if this is not a directory and the path
8766   ** ends in '/' it is an error. */
8767   if( bIsDir==0 ){
8768     if( nName>0 && zName[nName-1]=='/' ){
8769       zErr = sqlite3_mprintf("non-directory name must not end with /");
8770       rc = SQLITE_ERROR;
8771       goto zipfile_step_out;
8772     }
8773   }else{
8774     if( nName==0 || zName[nName-1]!='/' ){
8775       zName = zFree = sqlite3_mprintf("%s/", zName);
8776       if( zName==0 ){
8777         rc = SQLITE_NOMEM;
8778         goto zipfile_step_out;
8779       }
8780       nName = (int)strlen(zName);
8781     }else{
8782       while( nName>1 && zName[nName-2]=='/' ) nName--;
8783     }
8784   }
8785 
8786   /* Assemble the ZipfileEntry object for the new zip archive entry */
8787   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
8788   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
8789   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
8790   e.cds.iCompression = (u16)iMethod;
8791   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
8792   e.cds.crc32 = iCrc32;
8793   e.cds.szCompressed = nData;
8794   e.cds.szUncompressed = szUncompressed;
8795   e.cds.iExternalAttr = (mode<<16);
8796   e.cds.iOffset = p->body.n;
8797   e.cds.nFile = (u16)nName;
8798   e.cds.zFile = zName;
8799 
8800   /* Append the LFH to the body of the new archive */
8801   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
8802   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
8803   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
8804 
8805   /* Append the data to the body of the new archive */
8806   if( nData>0 ){
8807     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
8808     memcpy(&p->body.a[p->body.n], aData, nData);
8809     p->body.n += nData;
8810   }
8811 
8812   /* Append the CDS record to the directory of the new archive */
8813   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
8814   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
8815   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
8816 
8817   /* Increment the count of entries in the archive */
8818   p->nEntry++;
8819 
8820  zipfile_step_out:
8821   sqlite3_free(aFree);
8822   sqlite3_free(zFree);
8823   if( rc ){
8824     if( zErr ){
8825       sqlite3_result_error(pCtx, zErr, -1);
8826     }else{
8827       sqlite3_result_error_code(pCtx, rc);
8828     }
8829   }
8830   sqlite3_free(zErr);
8831 }
8832 
8833 /*
8834 ** xFinalize() callback for zipfile aggregate function.
8835 */
8836 static void zipfileFinal(sqlite3_context *pCtx){
8837   ZipfileCtx *p;
8838   ZipfileEOCD eocd;
8839   sqlite3_int64 nZip;
8840   u8 *aZip;
8841 
8842   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
8843   if( p==0 ) return;
8844   if( p->nEntry>0 ){
8845     memset(&eocd, 0, sizeof(eocd));
8846     eocd.nEntry = (u16)p->nEntry;
8847     eocd.nEntryTotal = (u16)p->nEntry;
8848     eocd.nSize = p->cds.n;
8849     eocd.iOffset = p->body.n;
8850 
8851     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
8852     aZip = (u8*)sqlite3_malloc64(nZip);
8853     if( aZip==0 ){
8854       sqlite3_result_error_nomem(pCtx);
8855     }else{
8856       memcpy(aZip, p->body.a, p->body.n);
8857       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
8858       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
8859       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
8860     }
8861   }
8862 
8863   sqlite3_free(p->body.a);
8864   sqlite3_free(p->cds.a);
8865 }
8866 
8867 
8868 /*
8869 ** Register the "zipfile" virtual table.
8870 */
8871 static int zipfileRegister(sqlite3 *db){
8872   static sqlite3_module zipfileModule = {
8873     1,                         /* iVersion */
8874     zipfileConnect,            /* xCreate */
8875     zipfileConnect,            /* xConnect */
8876     zipfileBestIndex,          /* xBestIndex */
8877     zipfileDisconnect,         /* xDisconnect */
8878     zipfileDisconnect,         /* xDestroy */
8879     zipfileOpen,               /* xOpen - open a cursor */
8880     zipfileClose,              /* xClose - close a cursor */
8881     zipfileFilter,             /* xFilter - configure scan constraints */
8882     zipfileNext,               /* xNext - advance a cursor */
8883     zipfileEof,                /* xEof - check for end of scan */
8884     zipfileColumn,             /* xColumn - read data */
8885     0,                         /* xRowid - read data */
8886     zipfileUpdate,             /* xUpdate */
8887     zipfileBegin,              /* xBegin */
8888     0,                         /* xSync */
8889     zipfileCommit,             /* xCommit */
8890     zipfileRollback,           /* xRollback */
8891     zipfileFindFunction,       /* xFindMethod */
8892     0,                         /* xRename */
8893     0,                         /* xSavepoint */
8894     0,                         /* xRelease */
8895     0,                         /* xRollback */
8896     0                          /* xShadowName */
8897   };
8898 
8899   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
8900   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
8901   if( rc==SQLITE_OK ){
8902     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
8903         zipfileStep, zipfileFinal
8904     );
8905   }
8906   assert( sizeof(i64)==8 );
8907   assert( sizeof(u32)==4 );
8908   assert( sizeof(u16)==2 );
8909   assert( sizeof(u8)==1 );
8910   return rc;
8911 }
8912 #else         /* SQLITE_OMIT_VIRTUALTABLE */
8913 # define zipfileRegister(x) SQLITE_OK
8914 #endif
8915 
8916 #ifdef _WIN32
8917 
8918 #endif
8919 int sqlite3_zipfile_init(
8920   sqlite3 *db,
8921   char **pzErrMsg,
8922   const sqlite3_api_routines *pApi
8923 ){
8924   SQLITE_EXTENSION_INIT2(pApi);
8925   (void)pzErrMsg;  /* Unused parameter */
8926   return zipfileRegister(db);
8927 }
8928 
8929 /************************* End ../ext/misc/zipfile.c ********************/
8930 /************************* Begin ../ext/misc/sqlar.c ******************/
8931 /*
8932 ** 2017-12-17
8933 **
8934 ** The author disclaims copyright to this source code.  In place of
8935 ** a legal notice, here is a blessing:
8936 **
8937 **    May you do good and not evil.
8938 **    May you find forgiveness for yourself and forgive others.
8939 **    May you share freely, never taking more than you give.
8940 **
8941 ******************************************************************************
8942 **
8943 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
8944 ** for working with sqlar archives and used by the shell tool's built-in
8945 ** sqlar support.
8946 */
8947 /* #include "sqlite3ext.h" */
8948 SQLITE_EXTENSION_INIT1
8949 #include <zlib.h>
8950 #include <assert.h>
8951 
8952 /*
8953 ** Implementation of the "sqlar_compress(X)" SQL function.
8954 **
8955 ** If the type of X is SQLITE_BLOB, and compressing that blob using
8956 ** zlib utility function compress() yields a smaller blob, return the
8957 ** compressed blob. Otherwise, return a copy of X.
8958 **
8959 ** SQLar uses the "zlib format" for compressed content.  The zlib format
8960 ** contains a two-byte identification header and a four-byte checksum at
8961 ** the end.  This is different from ZIP which uses the raw deflate format.
8962 **
8963 ** Future enhancements to SQLar might add support for new compression formats.
8964 ** If so, those new formats will be identified by alternative headers in the
8965 ** compressed data.
8966 */
8967 static void sqlarCompressFunc(
8968   sqlite3_context *context,
8969   int argc,
8970   sqlite3_value **argv
8971 ){
8972   assert( argc==1 );
8973   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
8974     const Bytef *pData = sqlite3_value_blob(argv[0]);
8975     uLong nData = sqlite3_value_bytes(argv[0]);
8976     uLongf nOut = compressBound(nData);
8977     Bytef *pOut;
8978 
8979     pOut = (Bytef*)sqlite3_malloc(nOut);
8980     if( pOut==0 ){
8981       sqlite3_result_error_nomem(context);
8982       return;
8983     }else{
8984       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
8985         sqlite3_result_error(context, "error in compress()", -1);
8986       }else if( nOut<nData ){
8987         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
8988       }else{
8989         sqlite3_result_value(context, argv[0]);
8990       }
8991       sqlite3_free(pOut);
8992     }
8993   }else{
8994     sqlite3_result_value(context, argv[0]);
8995   }
8996 }
8997 
8998 /*
8999 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
9000 **
9001 ** Parameter SZ is interpreted as an integer. If it is less than or
9002 ** equal to zero, then this function returns a copy of X. Or, if
9003 ** SZ is equal to the size of X when interpreted as a blob, also
9004 ** return a copy of X. Otherwise, decompress blob X using zlib
9005 ** utility function uncompress() and return the results (another
9006 ** blob).
9007 */
9008 static void sqlarUncompressFunc(
9009   sqlite3_context *context,
9010   int argc,
9011   sqlite3_value **argv
9012 ){
9013   uLong nData;
9014   uLongf sz;
9015 
9016   assert( argc==2 );
9017   sz = sqlite3_value_int(argv[1]);
9018 
9019   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
9020     sqlite3_result_value(context, argv[0]);
9021   }else{
9022     const Bytef *pData= sqlite3_value_blob(argv[0]);
9023     Bytef *pOut = sqlite3_malloc(sz);
9024     if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
9025       sqlite3_result_error(context, "error in uncompress()", -1);
9026     }else{
9027       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
9028     }
9029     sqlite3_free(pOut);
9030   }
9031 }
9032 
9033 
9034 #ifdef _WIN32
9035 
9036 #endif
9037 int sqlite3_sqlar_init(
9038   sqlite3 *db,
9039   char **pzErrMsg,
9040   const sqlite3_api_routines *pApi
9041 ){
9042   int rc = SQLITE_OK;
9043   SQLITE_EXTENSION_INIT2(pApi);
9044   (void)pzErrMsg;  /* Unused parameter */
9045   rc = sqlite3_create_function(db, "sqlar_compress", 1,
9046                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
9047                                sqlarCompressFunc, 0, 0);
9048   if( rc==SQLITE_OK ){
9049     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
9050                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
9051                                  sqlarUncompressFunc, 0, 0);
9052   }
9053   return rc;
9054 }
9055 
9056 /************************* End ../ext/misc/sqlar.c ********************/
9057 #endif
9058 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
9059 /*
9060 ** 2017 April 07
9061 **
9062 ** The author disclaims copyright to this source code.  In place of
9063 ** a legal notice, here is a blessing:
9064 **
9065 **    May you do good and not evil.
9066 **    May you find forgiveness for yourself and forgive others.
9067 **    May you share freely, never taking more than you give.
9068 **
9069 *************************************************************************
9070 */
9071 #if !defined(SQLITEEXPERT_H)
9072 #define SQLITEEXPERT_H 1
9073 /* #include "sqlite3.h" */
9074 
9075 typedef struct sqlite3expert sqlite3expert;
9076 
9077 /*
9078 ** Create a new sqlite3expert object.
9079 **
9080 ** If successful, a pointer to the new object is returned and (*pzErr) set
9081 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
9082 ** an English-language error message. In this case it is the responsibility
9083 ** of the caller to eventually free the error message buffer using
9084 ** sqlite3_free().
9085 */
9086 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
9087 
9088 /*
9089 ** Configure an sqlite3expert object.
9090 **
9091 ** EXPERT_CONFIG_SAMPLE:
9092 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
9093 **   each candidate index. This involves scanning and sorting the entire
9094 **   contents of each user database table once for each candidate index
9095 **   associated with the table. For large databases, this can be
9096 **   prohibitively slow. This option allows the sqlite3expert object to
9097 **   be configured so that sqlite_stat1 data is instead generated based on a
9098 **   subset of each table, or so that no sqlite_stat1 data is used at all.
9099 **
9100 **   A single integer argument is passed to this option. If the value is less
9101 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
9102 **   the analysis - indexes are recommended based on the database schema only.
9103 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
9104 **   generated for each candidate index (this is the default). Finally, if the
9105 **   value falls between 0 and 100, then it represents the percentage of user
9106 **   table rows that should be considered when generating sqlite_stat1 data.
9107 **
9108 **   Examples:
9109 **
9110 **     // Do not generate any sqlite_stat1 data
9111 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
9112 **
9113 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
9114 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
9115 */
9116 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
9117 
9118 #define EXPERT_CONFIG_SAMPLE 1    /* int */
9119 
9120 /*
9121 ** Specify zero or more SQL statements to be included in the analysis.
9122 **
9123 ** Buffer zSql must contain zero or more complete SQL statements. This
9124 ** function parses all statements contained in the buffer and adds them
9125 ** to the internal list of statements to analyze. If successful, SQLITE_OK
9126 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
9127 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
9128 ** may be set to point to an English language error message. In this case
9129 ** the caller is responsible for eventually freeing the error message buffer
9130 ** using sqlite3_free().
9131 **
9132 ** If an error does occur while processing one of the statements in the
9133 ** buffer passed as the second argument, none of the statements in the
9134 ** buffer are added to the analysis.
9135 **
9136 ** This function must be called before sqlite3_expert_analyze(). If a call
9137 ** to this function is made on an sqlite3expert object that has already
9138 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
9139 ** immediately and no statements are added to the analysis.
9140 */
9141 int sqlite3_expert_sql(
9142   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
9143   const char *zSql,               /* SQL statement(s) to add */
9144   char **pzErr                    /* OUT: Error message (if any) */
9145 );
9146 
9147 
9148 /*
9149 ** This function is called after the sqlite3expert object has been configured
9150 ** with all SQL statements using sqlite3_expert_sql() to actually perform
9151 ** the analysis. Once this function has been called, it is not possible to
9152 ** add further SQL statements to the analysis.
9153 **
9154 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
9155 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
9156 ** point to a buffer containing an English language error message. In this
9157 ** case it is the responsibility of the caller to eventually free the buffer
9158 ** using sqlite3_free().
9159 **
9160 ** If an error does occur within this function, the sqlite3expert object
9161 ** is no longer useful for any purpose. At that point it is no longer
9162 ** possible to add further SQL statements to the object or to re-attempt
9163 ** the analysis. The sqlite3expert object must still be freed using a call
9164 ** sqlite3_expert_destroy().
9165 */
9166 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
9167 
9168 /*
9169 ** Return the total number of statements loaded using sqlite3_expert_sql().
9170 ** The total number of SQL statements may be different from the total number
9171 ** to calls to sqlite3_expert_sql().
9172 */
9173 int sqlite3_expert_count(sqlite3expert*);
9174 
9175 /*
9176 ** Return a component of the report.
9177 **
9178 ** This function is called after sqlite3_expert_analyze() to extract the
9179 ** results of the analysis. Each call to this function returns either a
9180 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
9181 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
9182 ** #define constants defined below.
9183 **
9184 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
9185 ** information relating to a specific SQL statement. In these cases that
9186 ** SQL statement is identified by the value passed as the second argument.
9187 ** SQL statements are numbered from 0 in the order in which they are parsed.
9188 ** If an out-of-range value (less than zero or equal to or greater than the
9189 ** value returned by sqlite3_expert_count()) is passed as the second argument
9190 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
9191 **
9192 ** EXPERT_REPORT_SQL:
9193 **   Return the text of SQL statement iStmt.
9194 **
9195 ** EXPERT_REPORT_INDEXES:
9196 **   Return a buffer containing the CREATE INDEX statements for all recommended
9197 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
9198 **   is returned.
9199 **
9200 ** EXPERT_REPORT_PLAN:
9201 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
9202 **   iStmt after the proposed indexes have been added to the database schema.
9203 **
9204 ** EXPERT_REPORT_CANDIDATES:
9205 **   Return a pointer to a buffer containing the CREATE INDEX statements
9206 **   for all indexes that were tested (for all SQL statements). The iStmt
9207 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
9208 */
9209 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
9210 
9211 /*
9212 ** Values for the third argument passed to sqlite3_expert_report().
9213 */
9214 #define EXPERT_REPORT_SQL        1
9215 #define EXPERT_REPORT_INDEXES    2
9216 #define EXPERT_REPORT_PLAN       3
9217 #define EXPERT_REPORT_CANDIDATES 4
9218 
9219 /*
9220 ** Free an (sqlite3expert*) handle and all associated resources. There
9221 ** should be one call to this function for each successful call to
9222 ** sqlite3-expert_new().
9223 */
9224 void sqlite3_expert_destroy(sqlite3expert*);
9225 
9226 #endif  /* !defined(SQLITEEXPERT_H) */
9227 
9228 /************************* End ../ext/expert/sqlite3expert.h ********************/
9229 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
9230 /*
9231 ** 2017 April 09
9232 **
9233 ** The author disclaims copyright to this source code.  In place of
9234 ** a legal notice, here is a blessing:
9235 **
9236 **    May you do good and not evil.
9237 **    May you find forgiveness for yourself and forgive others.
9238 **    May you share freely, never taking more than you give.
9239 **
9240 *************************************************************************
9241 */
9242 /* #include "sqlite3expert.h" */
9243 #include <assert.h>
9244 #include <string.h>
9245 #include <stdio.h>
9246 
9247 #if !defined(SQLITE_AMALGAMATION)
9248 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
9249 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
9250 #endif
9251 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
9252 # define ALWAYS(X)      (1)
9253 # define NEVER(X)       (0)
9254 #elif !defined(NDEBUG)
9255 # define ALWAYS(X)      ((X)?1:(assert(0),0))
9256 # define NEVER(X)       ((X)?(assert(0),1):0)
9257 #else
9258 # define ALWAYS(X)      (X)
9259 # define NEVER(X)       (X)
9260 #endif
9261 #endif /* !defined(SQLITE_AMALGAMATION) */
9262 
9263 
9264 #ifndef SQLITE_OMIT_VIRTUALTABLE
9265 
9266 /* typedef sqlite3_int64 i64; */
9267 /* typedef sqlite3_uint64 u64; */
9268 
9269 typedef struct IdxColumn IdxColumn;
9270 typedef struct IdxConstraint IdxConstraint;
9271 typedef struct IdxScan IdxScan;
9272 typedef struct IdxStatement IdxStatement;
9273 typedef struct IdxTable IdxTable;
9274 typedef struct IdxWrite IdxWrite;
9275 
9276 #define STRLEN  (int)strlen
9277 
9278 /*
9279 ** A temp table name that we assume no user database will actually use.
9280 ** If this assumption proves incorrect triggers on the table with the
9281 ** conflicting name will be ignored.
9282 */
9283 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
9284 
9285 /*
9286 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
9287 ** any other type of single-ended range constraint on a column).
9288 **
9289 ** pLink:
9290 **   Used to temporarily link IdxConstraint objects into lists while
9291 **   creating candidate indexes.
9292 */
9293 struct IdxConstraint {
9294   char *zColl;                    /* Collation sequence */
9295   int bRange;                     /* True for range, false for eq */
9296   int iCol;                       /* Constrained table column */
9297   int bFlag;                      /* Used by idxFindCompatible() */
9298   int bDesc;                      /* True if ORDER BY <expr> DESC */
9299   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
9300   IdxConstraint *pLink;           /* See above */
9301 };
9302 
9303 /*
9304 ** A single scan of a single table.
9305 */
9306 struct IdxScan {
9307   IdxTable *pTab;                 /* Associated table object */
9308   int iDb;                        /* Database containing table zTable */
9309   i64 covering;                   /* Mask of columns required for cov. index */
9310   IdxConstraint *pOrder;          /* ORDER BY columns */
9311   IdxConstraint *pEq;             /* List of == constraints */
9312   IdxConstraint *pRange;          /* List of < constraints */
9313   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
9314 };
9315 
9316 /*
9317 ** Information regarding a single database table. Extracted from
9318 ** "PRAGMA table_info" by function idxGetTableInfo().
9319 */
9320 struct IdxColumn {
9321   char *zName;
9322   char *zColl;
9323   int iPk;
9324 };
9325 struct IdxTable {
9326   int nCol;
9327   char *zName;                    /* Table name */
9328   IdxColumn *aCol;
9329   IdxTable *pNext;                /* Next table in linked list of all tables */
9330 };
9331 
9332 /*
9333 ** An object of the following type is created for each unique table/write-op
9334 ** seen. The objects are stored in a singly-linked list beginning at
9335 ** sqlite3expert.pWrite.
9336 */
9337 struct IdxWrite {
9338   IdxTable *pTab;
9339   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
9340   IdxWrite *pNext;
9341 };
9342 
9343 /*
9344 ** Each statement being analyzed is represented by an instance of this
9345 ** structure.
9346 */
9347 struct IdxStatement {
9348   int iId;                        /* Statement number */
9349   char *zSql;                     /* SQL statement */
9350   char *zIdx;                     /* Indexes */
9351   char *zEQP;                     /* Plan */
9352   IdxStatement *pNext;
9353 };
9354 
9355 
9356 /*
9357 ** A hash table for storing strings. With space for a payload string
9358 ** with each entry. Methods are:
9359 **
9360 **   idxHashInit()
9361 **   idxHashClear()
9362 **   idxHashAdd()
9363 **   idxHashSearch()
9364 */
9365 #define IDX_HASH_SIZE 1023
9366 typedef struct IdxHashEntry IdxHashEntry;
9367 typedef struct IdxHash IdxHash;
9368 struct IdxHashEntry {
9369   char *zKey;                     /* nul-terminated key */
9370   char *zVal;                     /* nul-terminated value string */
9371   char *zVal2;                    /* nul-terminated value string 2 */
9372   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
9373   IdxHashEntry *pNext;            /* Next entry in hash */
9374 };
9375 struct IdxHash {
9376   IdxHashEntry *pFirst;
9377   IdxHashEntry *aHash[IDX_HASH_SIZE];
9378 };
9379 
9380 /*
9381 ** sqlite3expert object.
9382 */
9383 struct sqlite3expert {
9384   int iSample;                    /* Percentage of tables to sample for stat1 */
9385   sqlite3 *db;                    /* User database */
9386   sqlite3 *dbm;                   /* In-memory db for this analysis */
9387   sqlite3 *dbv;                   /* Vtab schema for this analysis */
9388   IdxTable *pTable;               /* List of all IdxTable objects */
9389   IdxScan *pScan;                 /* List of scan objects */
9390   IdxWrite *pWrite;               /* List of write objects */
9391   IdxStatement *pStatement;       /* List of IdxStatement objects */
9392   int bRun;                       /* True once analysis has run */
9393   char **pzErrmsg;
9394   int rc;                         /* Error code from whereinfo hook */
9395   IdxHash hIdx;                   /* Hash containing all candidate indexes */
9396   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
9397 };
9398 
9399 
9400 /*
9401 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
9402 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
9403 */
9404 static void *idxMalloc(int *pRc, int nByte){
9405   void *pRet;
9406   assert( *pRc==SQLITE_OK );
9407   assert( nByte>0 );
9408   pRet = sqlite3_malloc(nByte);
9409   if( pRet ){
9410     memset(pRet, 0, nByte);
9411   }else{
9412     *pRc = SQLITE_NOMEM;
9413   }
9414   return pRet;
9415 }
9416 
9417 /*
9418 ** Initialize an IdxHash hash table.
9419 */
9420 static void idxHashInit(IdxHash *pHash){
9421   memset(pHash, 0, sizeof(IdxHash));
9422 }
9423 
9424 /*
9425 ** Reset an IdxHash hash table.
9426 */
9427 static void idxHashClear(IdxHash *pHash){
9428   int i;
9429   for(i=0; i<IDX_HASH_SIZE; i++){
9430     IdxHashEntry *pEntry;
9431     IdxHashEntry *pNext;
9432     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
9433       pNext = pEntry->pHashNext;
9434       sqlite3_free(pEntry->zVal2);
9435       sqlite3_free(pEntry);
9436     }
9437   }
9438   memset(pHash, 0, sizeof(IdxHash));
9439 }
9440 
9441 /*
9442 ** Return the index of the hash bucket that the string specified by the
9443 ** arguments to this function belongs.
9444 */
9445 static int idxHashString(const char *z, int n){
9446   unsigned int ret = 0;
9447   int i;
9448   for(i=0; i<n; i++){
9449     ret += (ret<<3) + (unsigned char)(z[i]);
9450   }
9451   return (int)(ret % IDX_HASH_SIZE);
9452 }
9453 
9454 /*
9455 ** If zKey is already present in the hash table, return non-zero and do
9456 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
9457 ** the hash table passed as the second argument.
9458 */
9459 static int idxHashAdd(
9460   int *pRc,
9461   IdxHash *pHash,
9462   const char *zKey,
9463   const char *zVal
9464 ){
9465   int nKey = STRLEN(zKey);
9466   int iHash = idxHashString(zKey, nKey);
9467   int nVal = (zVal ? STRLEN(zVal) : 0);
9468   IdxHashEntry *pEntry;
9469   assert( iHash>=0 );
9470   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
9471     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
9472       return 1;
9473     }
9474   }
9475   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
9476   if( pEntry ){
9477     pEntry->zKey = (char*)&pEntry[1];
9478     memcpy(pEntry->zKey, zKey, nKey);
9479     if( zVal ){
9480       pEntry->zVal = &pEntry->zKey[nKey+1];
9481       memcpy(pEntry->zVal, zVal, nVal);
9482     }
9483     pEntry->pHashNext = pHash->aHash[iHash];
9484     pHash->aHash[iHash] = pEntry;
9485 
9486     pEntry->pNext = pHash->pFirst;
9487     pHash->pFirst = pEntry;
9488   }
9489   return 0;
9490 }
9491 
9492 /*
9493 ** If zKey/nKey is present in the hash table, return a pointer to the
9494 ** hash-entry object.
9495 */
9496 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
9497   int iHash;
9498   IdxHashEntry *pEntry;
9499   if( nKey<0 ) nKey = STRLEN(zKey);
9500   iHash = idxHashString(zKey, nKey);
9501   assert( iHash>=0 );
9502   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
9503     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
9504       return pEntry;
9505     }
9506   }
9507   return 0;
9508 }
9509 
9510 /*
9511 ** If the hash table contains an entry with a key equal to the string
9512 ** passed as the final two arguments to this function, return a pointer
9513 ** to the payload string. Otherwise, if zKey/nKey is not present in the
9514 ** hash table, return NULL.
9515 */
9516 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
9517   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
9518   if( pEntry ) return pEntry->zVal;
9519   return 0;
9520 }
9521 
9522 /*
9523 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
9524 ** variable to point to a copy of nul-terminated string zColl.
9525 */
9526 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
9527   IdxConstraint *pNew;
9528   int nColl = STRLEN(zColl);
9529 
9530   assert( *pRc==SQLITE_OK );
9531   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
9532   if( pNew ){
9533     pNew->zColl = (char*)&pNew[1];
9534     memcpy(pNew->zColl, zColl, nColl+1);
9535   }
9536   return pNew;
9537 }
9538 
9539 /*
9540 ** An error associated with database handle db has just occurred. Pass
9541 ** the error message to callback function xOut.
9542 */
9543 static void idxDatabaseError(
9544   sqlite3 *db,                    /* Database handle */
9545   char **pzErrmsg                 /* Write error here */
9546 ){
9547   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
9548 }
9549 
9550 /*
9551 ** Prepare an SQL statement.
9552 */
9553 static int idxPrepareStmt(
9554   sqlite3 *db,                    /* Database handle to compile against */
9555   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
9556   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
9557   const char *zSql                /* SQL statement to compile */
9558 ){
9559   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
9560   if( rc!=SQLITE_OK ){
9561     *ppStmt = 0;
9562     idxDatabaseError(db, pzErrmsg);
9563   }
9564   return rc;
9565 }
9566 
9567 /*
9568 ** Prepare an SQL statement using the results of a printf() formatting.
9569 */
9570 static int idxPrintfPrepareStmt(
9571   sqlite3 *db,                    /* Database handle to compile against */
9572   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
9573   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
9574   const char *zFmt,               /* printf() format of SQL statement */
9575   ...                             /* Trailing printf() arguments */
9576 ){
9577   va_list ap;
9578   int rc;
9579   char *zSql;
9580   va_start(ap, zFmt);
9581   zSql = sqlite3_vmprintf(zFmt, ap);
9582   if( zSql==0 ){
9583     rc = SQLITE_NOMEM;
9584   }else{
9585     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
9586     sqlite3_free(zSql);
9587   }
9588   va_end(ap);
9589   return rc;
9590 }
9591 
9592 
9593 /*************************************************************************
9594 ** Beginning of virtual table implementation.
9595 */
9596 typedef struct ExpertVtab ExpertVtab;
9597 struct ExpertVtab {
9598   sqlite3_vtab base;
9599   IdxTable *pTab;
9600   sqlite3expert *pExpert;
9601 };
9602 
9603 typedef struct ExpertCsr ExpertCsr;
9604 struct ExpertCsr {
9605   sqlite3_vtab_cursor base;
9606   sqlite3_stmt *pData;
9607 };
9608 
9609 static char *expertDequote(const char *zIn){
9610   int n = STRLEN(zIn);
9611   char *zRet = sqlite3_malloc(n);
9612 
9613   assert( zIn[0]=='\'' );
9614   assert( zIn[n-1]=='\'' );
9615 
9616   if( zRet ){
9617     int iOut = 0;
9618     int iIn = 0;
9619     for(iIn=1; iIn<(n-1); iIn++){
9620       if( zIn[iIn]=='\'' ){
9621         assert( zIn[iIn+1]=='\'' );
9622         iIn++;
9623       }
9624       zRet[iOut++] = zIn[iIn];
9625     }
9626     zRet[iOut] = '\0';
9627   }
9628 
9629   return zRet;
9630 }
9631 
9632 /*
9633 ** This function is the implementation of both the xConnect and xCreate
9634 ** methods of the r-tree virtual table.
9635 **
9636 **   argv[0]   -> module name
9637 **   argv[1]   -> database name
9638 **   argv[2]   -> table name
9639 **   argv[...] -> column names...
9640 */
9641 static int expertConnect(
9642   sqlite3 *db,
9643   void *pAux,
9644   int argc, const char *const*argv,
9645   sqlite3_vtab **ppVtab,
9646   char **pzErr
9647 ){
9648   sqlite3expert *pExpert = (sqlite3expert*)pAux;
9649   ExpertVtab *p = 0;
9650   int rc;
9651 
9652   if( argc!=4 ){
9653     *pzErr = sqlite3_mprintf("internal error!");
9654     rc = SQLITE_ERROR;
9655   }else{
9656     char *zCreateTable = expertDequote(argv[3]);
9657     if( zCreateTable ){
9658       rc = sqlite3_declare_vtab(db, zCreateTable);
9659       if( rc==SQLITE_OK ){
9660         p = idxMalloc(&rc, sizeof(ExpertVtab));
9661       }
9662       if( rc==SQLITE_OK ){
9663         p->pExpert = pExpert;
9664         p->pTab = pExpert->pTable;
9665         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
9666       }
9667       sqlite3_free(zCreateTable);
9668     }else{
9669       rc = SQLITE_NOMEM;
9670     }
9671   }
9672 
9673   *ppVtab = (sqlite3_vtab*)p;
9674   return rc;
9675 }
9676 
9677 static int expertDisconnect(sqlite3_vtab *pVtab){
9678   ExpertVtab *p = (ExpertVtab*)pVtab;
9679   sqlite3_free(p);
9680   return SQLITE_OK;
9681 }
9682 
9683 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
9684   ExpertVtab *p = (ExpertVtab*)pVtab;
9685   int rc = SQLITE_OK;
9686   int n = 0;
9687   IdxScan *pScan;
9688   const int opmask =
9689     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
9690     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
9691     SQLITE_INDEX_CONSTRAINT_LE;
9692 
9693   pScan = idxMalloc(&rc, sizeof(IdxScan));
9694   if( pScan ){
9695     int i;
9696 
9697     /* Link the new scan object into the list */
9698     pScan->pTab = p->pTab;
9699     pScan->pNextScan = p->pExpert->pScan;
9700     p->pExpert->pScan = pScan;
9701 
9702     /* Add the constraints to the IdxScan object */
9703     for(i=0; i<pIdxInfo->nConstraint; i++){
9704       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
9705       if( pCons->usable
9706        && pCons->iColumn>=0
9707        && p->pTab->aCol[pCons->iColumn].iPk==0
9708        && (pCons->op & opmask)
9709       ){
9710         IdxConstraint *pNew;
9711         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
9712         pNew = idxNewConstraint(&rc, zColl);
9713         if( pNew ){
9714           pNew->iCol = pCons->iColumn;
9715           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9716             pNew->pNext = pScan->pEq;
9717             pScan->pEq = pNew;
9718           }else{
9719             pNew->bRange = 1;
9720             pNew->pNext = pScan->pRange;
9721             pScan->pRange = pNew;
9722           }
9723         }
9724         n++;
9725         pIdxInfo->aConstraintUsage[i].argvIndex = n;
9726       }
9727     }
9728 
9729     /* Add the ORDER BY to the IdxScan object */
9730     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
9731       int iCol = pIdxInfo->aOrderBy[i].iColumn;
9732       if( iCol>=0 ){
9733         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
9734         if( pNew ){
9735           pNew->iCol = iCol;
9736           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
9737           pNew->pNext = pScan->pOrder;
9738           pNew->pLink = pScan->pOrder;
9739           pScan->pOrder = pNew;
9740           n++;
9741         }
9742       }
9743     }
9744   }
9745 
9746   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
9747   return rc;
9748 }
9749 
9750 static int expertUpdate(
9751   sqlite3_vtab *pVtab,
9752   int nData,
9753   sqlite3_value **azData,
9754   sqlite_int64 *pRowid
9755 ){
9756   (void)pVtab;
9757   (void)nData;
9758   (void)azData;
9759   (void)pRowid;
9760   return SQLITE_OK;
9761 }
9762 
9763 /*
9764 ** Virtual table module xOpen method.
9765 */
9766 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
9767   int rc = SQLITE_OK;
9768   ExpertCsr *pCsr;
9769   (void)pVTab;
9770   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
9771   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
9772   return rc;
9773 }
9774 
9775 /*
9776 ** Virtual table module xClose method.
9777 */
9778 static int expertClose(sqlite3_vtab_cursor *cur){
9779   ExpertCsr *pCsr = (ExpertCsr*)cur;
9780   sqlite3_finalize(pCsr->pData);
9781   sqlite3_free(pCsr);
9782   return SQLITE_OK;
9783 }
9784 
9785 /*
9786 ** Virtual table module xEof method.
9787 **
9788 ** Return non-zero if the cursor does not currently point to a valid
9789 ** record (i.e if the scan has finished), or zero otherwise.
9790 */
9791 static int expertEof(sqlite3_vtab_cursor *cur){
9792   ExpertCsr *pCsr = (ExpertCsr*)cur;
9793   return pCsr->pData==0;
9794 }
9795 
9796 /*
9797 ** Virtual table module xNext method.
9798 */
9799 static int expertNext(sqlite3_vtab_cursor *cur){
9800   ExpertCsr *pCsr = (ExpertCsr*)cur;
9801   int rc = SQLITE_OK;
9802 
9803   assert( pCsr->pData );
9804   rc = sqlite3_step(pCsr->pData);
9805   if( rc!=SQLITE_ROW ){
9806     rc = sqlite3_finalize(pCsr->pData);
9807     pCsr->pData = 0;
9808   }else{
9809     rc = SQLITE_OK;
9810   }
9811 
9812   return rc;
9813 }
9814 
9815 /*
9816 ** Virtual table module xRowid method.
9817 */
9818 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
9819   (void)cur;
9820   *pRowid = 0;
9821   return SQLITE_OK;
9822 }
9823 
9824 /*
9825 ** Virtual table module xColumn method.
9826 */
9827 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
9828   ExpertCsr *pCsr = (ExpertCsr*)cur;
9829   sqlite3_value *pVal;
9830   pVal = sqlite3_column_value(pCsr->pData, i);
9831   if( pVal ){
9832     sqlite3_result_value(ctx, pVal);
9833   }
9834   return SQLITE_OK;
9835 }
9836 
9837 /*
9838 ** Virtual table module xFilter method.
9839 */
9840 static int expertFilter(
9841   sqlite3_vtab_cursor *cur,
9842   int idxNum, const char *idxStr,
9843   int argc, sqlite3_value **argv
9844 ){
9845   ExpertCsr *pCsr = (ExpertCsr*)cur;
9846   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
9847   sqlite3expert *pExpert = pVtab->pExpert;
9848   int rc;
9849 
9850   (void)idxNum;
9851   (void)idxStr;
9852   (void)argc;
9853   (void)argv;
9854   rc = sqlite3_finalize(pCsr->pData);
9855   pCsr->pData = 0;
9856   if( rc==SQLITE_OK ){
9857     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
9858         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
9859     );
9860   }
9861 
9862   if( rc==SQLITE_OK ){
9863     rc = expertNext(cur);
9864   }
9865   return rc;
9866 }
9867 
9868 static int idxRegisterVtab(sqlite3expert *p){
9869   static sqlite3_module expertModule = {
9870     2,                            /* iVersion */
9871     expertConnect,                /* xCreate - create a table */
9872     expertConnect,                /* xConnect - connect to an existing table */
9873     expertBestIndex,              /* xBestIndex - Determine search strategy */
9874     expertDisconnect,             /* xDisconnect - Disconnect from a table */
9875     expertDisconnect,             /* xDestroy - Drop a table */
9876     expertOpen,                   /* xOpen - open a cursor */
9877     expertClose,                  /* xClose - close a cursor */
9878     expertFilter,                 /* xFilter - configure scan constraints */
9879     expertNext,                   /* xNext - advance a cursor */
9880     expertEof,                    /* xEof */
9881     expertColumn,                 /* xColumn - read data */
9882     expertRowid,                  /* xRowid - read data */
9883     expertUpdate,                 /* xUpdate - write data */
9884     0,                            /* xBegin - begin transaction */
9885     0,                            /* xSync - sync transaction */
9886     0,                            /* xCommit - commit transaction */
9887     0,                            /* xRollback - rollback transaction */
9888     0,                            /* xFindFunction - function overloading */
9889     0,                            /* xRename - rename the table */
9890     0,                            /* xSavepoint */
9891     0,                            /* xRelease */
9892     0,                            /* xRollbackTo */
9893     0,                            /* xShadowName */
9894   };
9895 
9896   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
9897 }
9898 /*
9899 ** End of virtual table implementation.
9900 *************************************************************************/
9901 /*
9902 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
9903 ** is called, set it to the return value of sqlite3_finalize() before
9904 ** returning. Otherwise, discard the sqlite3_finalize() return value.
9905 */
9906 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
9907   int rc = sqlite3_finalize(pStmt);
9908   if( *pRc==SQLITE_OK ) *pRc = rc;
9909 }
9910 
9911 /*
9912 ** Attempt to allocate an IdxTable structure corresponding to table zTab
9913 ** in the main database of connection db. If successful, set (*ppOut) to
9914 ** point to the new object and return SQLITE_OK. Otherwise, return an
9915 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
9916 ** set to point to an error string.
9917 **
9918 ** It is the responsibility of the caller to eventually free either the
9919 ** IdxTable object or error message using sqlite3_free().
9920 */
9921 static int idxGetTableInfo(
9922   sqlite3 *db,                    /* Database connection to read details from */
9923   const char *zTab,               /* Table name */
9924   IdxTable **ppOut,               /* OUT: New object (if successful) */
9925   char **pzErrmsg                 /* OUT: Error message (if not) */
9926 ){
9927   sqlite3_stmt *p1 = 0;
9928   int nCol = 0;
9929   int nTab;
9930   int nByte;
9931   IdxTable *pNew = 0;
9932   int rc, rc2;
9933   char *pCsr = 0;
9934   int nPk = 0;
9935 
9936   *ppOut = 0;
9937   if( zTab==0 ) return SQLITE_ERROR;
9938   nTab = STRLEN(zTab);
9939   nByte = sizeof(IdxTable) + nTab + 1;
9940   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
9941   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
9942     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
9943     const char *zColSeq = 0;
9944     if( zCol==0 ){
9945       rc = SQLITE_ERROR;
9946       break;
9947     }
9948     nByte += 1 + STRLEN(zCol);
9949     rc = sqlite3_table_column_metadata(
9950         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
9951     );
9952     if( zColSeq==0 ) zColSeq = "binary";
9953     nByte += 1 + STRLEN(zColSeq);
9954     nCol++;
9955     nPk += (sqlite3_column_int(p1, 5)>0);
9956   }
9957   rc2 = sqlite3_reset(p1);
9958   if( rc==SQLITE_OK ) rc = rc2;
9959 
9960   nByte += sizeof(IdxColumn) * nCol;
9961   if( rc==SQLITE_OK ){
9962     pNew = idxMalloc(&rc, nByte);
9963   }
9964   if( rc==SQLITE_OK ){
9965     pNew->aCol = (IdxColumn*)&pNew[1];
9966     pNew->nCol = nCol;
9967     pCsr = (char*)&pNew->aCol[nCol];
9968   }
9969 
9970   nCol = 0;
9971   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
9972     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
9973     const char *zColSeq = 0;
9974     int nCopy;
9975     if( zCol==0 ) continue;
9976     nCopy = STRLEN(zCol) + 1;
9977     pNew->aCol[nCol].zName = pCsr;
9978     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
9979     memcpy(pCsr, zCol, nCopy);
9980     pCsr += nCopy;
9981 
9982     rc = sqlite3_table_column_metadata(
9983         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
9984     );
9985     if( rc==SQLITE_OK ){
9986       if( zColSeq==0 ) zColSeq = "binary";
9987       nCopy = STRLEN(zColSeq) + 1;
9988       pNew->aCol[nCol].zColl = pCsr;
9989       memcpy(pCsr, zColSeq, nCopy);
9990       pCsr += nCopy;
9991     }
9992 
9993     nCol++;
9994   }
9995   idxFinalize(&rc, p1);
9996 
9997   if( rc!=SQLITE_OK ){
9998     sqlite3_free(pNew);
9999     pNew = 0;
10000   }else if( ALWAYS(pNew!=0) ){
10001     pNew->zName = pCsr;
10002     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
10003   }
10004 
10005   *ppOut = pNew;
10006   return rc;
10007 }
10008 
10009 /*
10010 ** This function is a no-op if *pRc is set to anything other than
10011 ** SQLITE_OK when it is called.
10012 **
10013 ** If *pRc is initially set to SQLITE_OK, then the text specified by
10014 ** the printf() style arguments is appended to zIn and the result returned
10015 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
10016 ** zIn before returning.
10017 */
10018 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
10019   va_list ap;
10020   char *zAppend = 0;
10021   char *zRet = 0;
10022   int nIn = zIn ? STRLEN(zIn) : 0;
10023   int nAppend = 0;
10024   va_start(ap, zFmt);
10025   if( *pRc==SQLITE_OK ){
10026     zAppend = sqlite3_vmprintf(zFmt, ap);
10027     if( zAppend ){
10028       nAppend = STRLEN(zAppend);
10029       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
10030     }
10031     if( zAppend && zRet ){
10032       if( nIn ) memcpy(zRet, zIn, nIn);
10033       memcpy(&zRet[nIn], zAppend, nAppend+1);
10034     }else{
10035       sqlite3_free(zRet);
10036       zRet = 0;
10037       *pRc = SQLITE_NOMEM;
10038     }
10039     sqlite3_free(zAppend);
10040     sqlite3_free(zIn);
10041   }
10042   va_end(ap);
10043   return zRet;
10044 }
10045 
10046 /*
10047 ** Return true if zId must be quoted in order to use it as an SQL
10048 ** identifier, or false otherwise.
10049 */
10050 static int idxIdentifierRequiresQuotes(const char *zId){
10051   int i;
10052   for(i=0; zId[i]; i++){
10053     if( !(zId[i]=='_')
10054      && !(zId[i]>='0' && zId[i]<='9')
10055      && !(zId[i]>='a' && zId[i]<='z')
10056      && !(zId[i]>='A' && zId[i]<='Z')
10057     ){
10058       return 1;
10059     }
10060   }
10061   return 0;
10062 }
10063 
10064 /*
10065 ** This function appends an index column definition suitable for constraint
10066 ** pCons to the string passed as zIn and returns the result.
10067 */
10068 static char *idxAppendColDefn(
10069   int *pRc,                       /* IN/OUT: Error code */
10070   char *zIn,                      /* Column defn accumulated so far */
10071   IdxTable *pTab,                 /* Table index will be created on */
10072   IdxConstraint *pCons
10073 ){
10074   char *zRet = zIn;
10075   IdxColumn *p = &pTab->aCol[pCons->iCol];
10076   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
10077 
10078   if( idxIdentifierRequiresQuotes(p->zName) ){
10079     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
10080   }else{
10081     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
10082   }
10083 
10084   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
10085     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
10086       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
10087     }else{
10088       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
10089     }
10090   }
10091 
10092   if( pCons->bDesc ){
10093     zRet = idxAppendText(pRc, zRet, " DESC");
10094   }
10095   return zRet;
10096 }
10097 
10098 /*
10099 ** Search database dbm for an index compatible with the one idxCreateFromCons()
10100 ** would create from arguments pScan, pEq and pTail. If no error occurs and
10101 ** such an index is found, return non-zero. Or, if no such index is found,
10102 ** return zero.
10103 **
10104 ** If an error occurs, set *pRc to an SQLite error code and return zero.
10105 */
10106 static int idxFindCompatible(
10107   int *pRc,                       /* OUT: Error code */
10108   sqlite3* dbm,                   /* Database to search */
10109   IdxScan *pScan,                 /* Scan for table to search for index on */
10110   IdxConstraint *pEq,             /* List of == constraints */
10111   IdxConstraint *pTail            /* List of range constraints */
10112 ){
10113   const char *zTbl = pScan->pTab->zName;
10114   sqlite3_stmt *pIdxList = 0;
10115   IdxConstraint *pIter;
10116   int nEq = 0;                    /* Number of elements in pEq */
10117   int rc;
10118 
10119   /* Count the elements in list pEq */
10120   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
10121 
10122   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
10123   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
10124     int bMatch = 1;
10125     IdxConstraint *pT = pTail;
10126     sqlite3_stmt *pInfo = 0;
10127     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
10128     if( zIdx==0 ) continue;
10129 
10130     /* Zero the IdxConstraint.bFlag values in the pEq list */
10131     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
10132 
10133     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
10134     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
10135       int iIdx = sqlite3_column_int(pInfo, 0);
10136       int iCol = sqlite3_column_int(pInfo, 1);
10137       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
10138 
10139       if( iIdx<nEq ){
10140         for(pIter=pEq; pIter; pIter=pIter->pLink){
10141           if( pIter->bFlag ) continue;
10142           if( pIter->iCol!=iCol ) continue;
10143           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
10144           pIter->bFlag = 1;
10145           break;
10146         }
10147         if( pIter==0 ){
10148           bMatch = 0;
10149           break;
10150         }
10151       }else{
10152         if( pT ){
10153           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
10154             bMatch = 0;
10155             break;
10156           }
10157           pT = pT->pLink;
10158         }
10159       }
10160     }
10161     idxFinalize(&rc, pInfo);
10162 
10163     if( rc==SQLITE_OK && bMatch ){
10164       sqlite3_finalize(pIdxList);
10165       return 1;
10166     }
10167   }
10168   idxFinalize(&rc, pIdxList);
10169 
10170   *pRc = rc;
10171   return 0;
10172 }
10173 
10174 /* Callback for sqlite3_exec() with query with leading count(*) column.
10175  * The first argument is expected to be an int*, referent to be incremented
10176  * if that leading column is not exactly '0'.
10177  */
10178 static int countNonzeros(void* pCount, int nc,
10179                          char* azResults[], char* azColumns[]){
10180   (void)azColumns;  /* Suppress unused parameter warning */
10181   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
10182     *((int *)pCount) += 1;
10183   }
10184   return 0;
10185 }
10186 
10187 static int idxCreateFromCons(
10188   sqlite3expert *p,
10189   IdxScan *pScan,
10190   IdxConstraint *pEq,
10191   IdxConstraint *pTail
10192 ){
10193   sqlite3 *dbm = p->dbm;
10194   int rc = SQLITE_OK;
10195   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
10196     IdxTable *pTab = pScan->pTab;
10197     char *zCols = 0;
10198     char *zIdx = 0;
10199     IdxConstraint *pCons;
10200     unsigned int h = 0;
10201     const char *zFmt;
10202 
10203     for(pCons=pEq; pCons; pCons=pCons->pLink){
10204       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
10205     }
10206     for(pCons=pTail; pCons; pCons=pCons->pLink){
10207       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
10208     }
10209 
10210     if( rc==SQLITE_OK ){
10211       /* Hash the list of columns to come up with a name for the index */
10212       const char *zTable = pScan->pTab->zName;
10213       int quoteTable = idxIdentifierRequiresQuotes(zTable);
10214       char *zName = 0;          /* Index name */
10215       int collisions = 0;
10216       do{
10217         int i;
10218         char *zFind;
10219         for(i=0; zCols[i]; i++){
10220           h += ((h<<3) + zCols[i]);
10221         }
10222         sqlite3_free(zName);
10223         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
10224         if( zName==0 ) break;
10225         /* Is is unique among table, view and index names? */
10226         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
10227           " AND type in ('index','table','view')";
10228         zFind = sqlite3_mprintf(zFmt, zName);
10229         i = 0;
10230         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
10231         assert(rc==SQLITE_OK);
10232         sqlite3_free(zFind);
10233         if( i==0 ){
10234           collisions = 0;
10235           break;
10236         }
10237         ++collisions;
10238       }while( collisions<50 && zName!=0 );
10239       if( collisions ){
10240         /* This return means "Gave up trying to find a unique index name." */
10241         rc = SQLITE_BUSY_TIMEOUT;
10242       }else if( zName==0 ){
10243         rc = SQLITE_NOMEM;
10244       }else{
10245         if( quoteTable ){
10246           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
10247         }else{
10248           zFmt = "CREATE INDEX %s ON %s(%s)";
10249         }
10250         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
10251         if( !zIdx ){
10252           rc = SQLITE_NOMEM;
10253         }else{
10254           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
10255           if( rc!=SQLITE_OK ){
10256             rc = SQLITE_BUSY_TIMEOUT;
10257           }else{
10258             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
10259           }
10260         }
10261         sqlite3_free(zName);
10262         sqlite3_free(zIdx);
10263       }
10264     }
10265 
10266     sqlite3_free(zCols);
10267   }
10268   return rc;
10269 }
10270 
10271 /*
10272 ** Return true if list pList (linked by IdxConstraint.pLink) contains
10273 ** a constraint compatible with *p. Otherwise return false.
10274 */
10275 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
10276   IdxConstraint *pCmp;
10277   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
10278     if( p->iCol==pCmp->iCol ) return 1;
10279   }
10280   return 0;
10281 }
10282 
10283 static int idxCreateFromWhere(
10284   sqlite3expert *p,
10285   IdxScan *pScan,                 /* Create indexes for this scan */
10286   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
10287 ){
10288   IdxConstraint *p1 = 0;
10289   IdxConstraint *pCon;
10290   int rc;
10291 
10292   /* Gather up all the == constraints. */
10293   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
10294     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
10295       pCon->pLink = p1;
10296       p1 = pCon;
10297     }
10298   }
10299 
10300   /* Create an index using the == constraints collected above. And the
10301   ** range constraint/ORDER BY terms passed in by the caller, if any. */
10302   rc = idxCreateFromCons(p, pScan, p1, pTail);
10303 
10304   /* If no range/ORDER BY passed by the caller, create a version of the
10305   ** index for each range constraint.  */
10306   if( pTail==0 ){
10307     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
10308       assert( pCon->pLink==0 );
10309       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
10310         rc = idxCreateFromCons(p, pScan, p1, pCon);
10311       }
10312     }
10313   }
10314 
10315   return rc;
10316 }
10317 
10318 /*
10319 ** Create candidate indexes in database [dbm] based on the data in
10320 ** linked-list pScan.
10321 */
10322 static int idxCreateCandidates(sqlite3expert *p){
10323   int rc = SQLITE_OK;
10324   IdxScan *pIter;
10325 
10326   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
10327     rc = idxCreateFromWhere(p, pIter, 0);
10328     if( rc==SQLITE_OK && pIter->pOrder ){
10329       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
10330     }
10331   }
10332 
10333   return rc;
10334 }
10335 
10336 /*
10337 ** Free all elements of the linked list starting at pConstraint.
10338 */
10339 static void idxConstraintFree(IdxConstraint *pConstraint){
10340   IdxConstraint *pNext;
10341   IdxConstraint *p;
10342 
10343   for(p=pConstraint; p; p=pNext){
10344     pNext = p->pNext;
10345     sqlite3_free(p);
10346   }
10347 }
10348 
10349 /*
10350 ** Free all elements of the linked list starting from pScan up until pLast
10351 ** (pLast is not freed).
10352 */
10353 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
10354   IdxScan *p;
10355   IdxScan *pNext;
10356   for(p=pScan; p!=pLast; p=pNext){
10357     pNext = p->pNextScan;
10358     idxConstraintFree(p->pOrder);
10359     idxConstraintFree(p->pEq);
10360     idxConstraintFree(p->pRange);
10361     sqlite3_free(p);
10362   }
10363 }
10364 
10365 /*
10366 ** Free all elements of the linked list starting from pStatement up
10367 ** until pLast (pLast is not freed).
10368 */
10369 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
10370   IdxStatement *p;
10371   IdxStatement *pNext;
10372   for(p=pStatement; p!=pLast; p=pNext){
10373     pNext = p->pNext;
10374     sqlite3_free(p->zEQP);
10375     sqlite3_free(p->zIdx);
10376     sqlite3_free(p);
10377   }
10378 }
10379 
10380 /*
10381 ** Free the linked list of IdxTable objects starting at pTab.
10382 */
10383 static void idxTableFree(IdxTable *pTab){
10384   IdxTable *pIter;
10385   IdxTable *pNext;
10386   for(pIter=pTab; pIter; pIter=pNext){
10387     pNext = pIter->pNext;
10388     sqlite3_free(pIter);
10389   }
10390 }
10391 
10392 /*
10393 ** Free the linked list of IdxWrite objects starting at pTab.
10394 */
10395 static void idxWriteFree(IdxWrite *pTab){
10396   IdxWrite *pIter;
10397   IdxWrite *pNext;
10398   for(pIter=pTab; pIter; pIter=pNext){
10399     pNext = pIter->pNext;
10400     sqlite3_free(pIter);
10401   }
10402 }
10403 
10404 
10405 
10406 /*
10407 ** This function is called after candidate indexes have been created. It
10408 ** runs all the queries to see which indexes they prefer, and populates
10409 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
10410 */
10411 static int idxFindIndexes(
10412   sqlite3expert *p,
10413   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
10414 ){
10415   IdxStatement *pStmt;
10416   sqlite3 *dbm = p->dbm;
10417   int rc = SQLITE_OK;
10418 
10419   IdxHash hIdx;
10420   idxHashInit(&hIdx);
10421 
10422   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
10423     IdxHashEntry *pEntry;
10424     sqlite3_stmt *pExplain = 0;
10425     idxHashClear(&hIdx);
10426     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
10427         "EXPLAIN QUERY PLAN %s", pStmt->zSql
10428     );
10429     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
10430       /* int iId = sqlite3_column_int(pExplain, 0); */
10431       /* int iParent = sqlite3_column_int(pExplain, 1); */
10432       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
10433       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
10434       int nDetail;
10435       int i;
10436 
10437       if( !zDetail ) continue;
10438       nDetail = STRLEN(zDetail);
10439 
10440       for(i=0; i<nDetail; i++){
10441         const char *zIdx = 0;
10442         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
10443           zIdx = &zDetail[i+13];
10444         }else if( i+22<nDetail
10445             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
10446         ){
10447           zIdx = &zDetail[i+22];
10448         }
10449         if( zIdx ){
10450           const char *zSql;
10451           int nIdx = 0;
10452           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
10453             nIdx++;
10454           }
10455           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
10456           if( zSql ){
10457             idxHashAdd(&rc, &hIdx, zSql, 0);
10458             if( rc ) goto find_indexes_out;
10459           }
10460           break;
10461         }
10462       }
10463 
10464       if( zDetail[0]!='-' ){
10465         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
10466       }
10467     }
10468 
10469     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
10470       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
10471     }
10472 
10473     idxFinalize(&rc, pExplain);
10474   }
10475 
10476  find_indexes_out:
10477   idxHashClear(&hIdx);
10478   return rc;
10479 }
10480 
10481 static int idxAuthCallback(
10482   void *pCtx,
10483   int eOp,
10484   const char *z3,
10485   const char *z4,
10486   const char *zDb,
10487   const char *zTrigger
10488 ){
10489   int rc = SQLITE_OK;
10490   (void)z4;
10491   (void)zTrigger;
10492   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
10493     if( sqlite3_stricmp(zDb, "main")==0 ){
10494       sqlite3expert *p = (sqlite3expert*)pCtx;
10495       IdxTable *pTab;
10496       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
10497         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
10498       }
10499       if( pTab ){
10500         IdxWrite *pWrite;
10501         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
10502           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
10503         }
10504         if( pWrite==0 ){
10505           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
10506           if( rc==SQLITE_OK ){
10507             pWrite->pTab = pTab;
10508             pWrite->eOp = eOp;
10509             pWrite->pNext = p->pWrite;
10510             p->pWrite = pWrite;
10511           }
10512         }
10513       }
10514     }
10515   }
10516   return rc;
10517 }
10518 
10519 static int idxProcessOneTrigger(
10520   sqlite3expert *p,
10521   IdxWrite *pWrite,
10522   char **pzErr
10523 ){
10524   static const char *zInt = UNIQUE_TABLE_NAME;
10525   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
10526   IdxTable *pTab = pWrite->pTab;
10527   const char *zTab = pTab->zName;
10528   const char *zSql =
10529     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
10530     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
10531     "ORDER BY type;";
10532   sqlite3_stmt *pSelect = 0;
10533   int rc = SQLITE_OK;
10534   char *zWrite = 0;
10535 
10536   /* Create the table and its triggers in the temp schema */
10537   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
10538   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
10539     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
10540     if( zCreate==0 ) continue;
10541     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
10542   }
10543   idxFinalize(&rc, pSelect);
10544 
10545   /* Rename the table in the temp schema to zInt */
10546   if( rc==SQLITE_OK ){
10547     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
10548     if( z==0 ){
10549       rc = SQLITE_NOMEM;
10550     }else{
10551       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
10552       sqlite3_free(z);
10553     }
10554   }
10555 
10556   switch( pWrite->eOp ){
10557     case SQLITE_INSERT: {
10558       int i;
10559       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
10560       for(i=0; i<pTab->nCol; i++){
10561         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
10562       }
10563       zWrite = idxAppendText(&rc, zWrite, ")");
10564       break;
10565     }
10566     case SQLITE_UPDATE: {
10567       int i;
10568       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
10569       for(i=0; i<pTab->nCol; i++){
10570         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
10571             pTab->aCol[i].zName
10572         );
10573       }
10574       break;
10575     }
10576     default: {
10577       assert( pWrite->eOp==SQLITE_DELETE );
10578       if( rc==SQLITE_OK ){
10579         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
10580         if( zWrite==0 ) rc = SQLITE_NOMEM;
10581       }
10582     }
10583   }
10584 
10585   if( rc==SQLITE_OK ){
10586     sqlite3_stmt *pX = 0;
10587     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
10588     idxFinalize(&rc, pX);
10589     if( rc!=SQLITE_OK ){
10590       idxDatabaseError(p->dbv, pzErr);
10591     }
10592   }
10593   sqlite3_free(zWrite);
10594 
10595   if( rc==SQLITE_OK ){
10596     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
10597   }
10598 
10599   return rc;
10600 }
10601 
10602 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
10603   int rc = SQLITE_OK;
10604   IdxWrite *pEnd = 0;
10605   IdxWrite *pFirst = p->pWrite;
10606 
10607   while( rc==SQLITE_OK && pFirst!=pEnd ){
10608     IdxWrite *pIter;
10609     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
10610       rc = idxProcessOneTrigger(p, pIter, pzErr);
10611     }
10612     pEnd = pFirst;
10613     pFirst = p->pWrite;
10614   }
10615 
10616   return rc;
10617 }
10618 
10619 
10620 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
10621   int rc = idxRegisterVtab(p);
10622   sqlite3_stmt *pSchema = 0;
10623 
10624   /* For each table in the main db schema:
10625   **
10626   **   1) Add an entry to the p->pTable list, and
10627   **   2) Create the equivalent virtual table in dbv.
10628   */
10629   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
10630       "SELECT type, name, sql, 1 FROM sqlite_schema "
10631       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
10632       " UNION ALL "
10633       "SELECT type, name, sql, 2 FROM sqlite_schema "
10634       "WHERE type = 'trigger'"
10635       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
10636       "ORDER BY 4, 1"
10637   );
10638   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
10639     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
10640     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
10641     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
10642 
10643     if( zType==0 || zName==0 ) continue;
10644     if( zType[0]=='v' || zType[1]=='r' ){
10645       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
10646     }else{
10647       IdxTable *pTab;
10648       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
10649       if( rc==SQLITE_OK ){
10650         int i;
10651         char *zInner = 0;
10652         char *zOuter = 0;
10653         pTab->pNext = p->pTable;
10654         p->pTable = pTab;
10655 
10656         /* The statement the vtab will pass to sqlite3_declare_vtab() */
10657         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
10658         for(i=0; i<pTab->nCol; i++){
10659           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
10660               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
10661           );
10662         }
10663         zInner = idxAppendText(&rc, zInner, ")");
10664 
10665         /* The CVT statement to create the vtab */
10666         zOuter = idxAppendText(&rc, 0,
10667             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
10668         );
10669         if( rc==SQLITE_OK ){
10670           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
10671         }
10672         sqlite3_free(zInner);
10673         sqlite3_free(zOuter);
10674       }
10675     }
10676   }
10677   idxFinalize(&rc, pSchema);
10678   return rc;
10679 }
10680 
10681 struct IdxSampleCtx {
10682   int iTarget;
10683   double target;                  /* Target nRet/nRow value */
10684   double nRow;                    /* Number of rows seen */
10685   double nRet;                    /* Number of rows returned */
10686 };
10687 
10688 static void idxSampleFunc(
10689   sqlite3_context *pCtx,
10690   int argc,
10691   sqlite3_value **argv
10692 ){
10693   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
10694   int bRet;
10695 
10696   (void)argv;
10697   assert( argc==0 );
10698   if( p->nRow==0.0 ){
10699     bRet = 1;
10700   }else{
10701     bRet = (p->nRet / p->nRow) <= p->target;
10702     if( bRet==0 ){
10703       unsigned short rnd;
10704       sqlite3_randomness(2, (void*)&rnd);
10705       bRet = ((int)rnd % 100) <= p->iTarget;
10706     }
10707   }
10708 
10709   sqlite3_result_int(pCtx, bRet);
10710   p->nRow += 1.0;
10711   p->nRet += (double)bRet;
10712 }
10713 
10714 struct IdxRemCtx {
10715   int nSlot;
10716   struct IdxRemSlot {
10717     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
10718     i64 iVal;                     /* SQLITE_INTEGER value */
10719     double rVal;                  /* SQLITE_FLOAT value */
10720     int nByte;                    /* Bytes of space allocated at z */
10721     int n;                        /* Size of buffer z */
10722     char *z;                      /* SQLITE_TEXT/BLOB value */
10723   } aSlot[1];
10724 };
10725 
10726 /*
10727 ** Implementation of scalar function rem().
10728 */
10729 static void idxRemFunc(
10730   sqlite3_context *pCtx,
10731   int argc,
10732   sqlite3_value **argv
10733 ){
10734   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
10735   struct IdxRemSlot *pSlot;
10736   int iSlot;
10737   assert( argc==2 );
10738 
10739   iSlot = sqlite3_value_int(argv[0]);
10740   assert( iSlot<=p->nSlot );
10741   pSlot = &p->aSlot[iSlot];
10742 
10743   switch( pSlot->eType ){
10744     case SQLITE_NULL:
10745       /* no-op */
10746       break;
10747 
10748     case SQLITE_INTEGER:
10749       sqlite3_result_int64(pCtx, pSlot->iVal);
10750       break;
10751 
10752     case SQLITE_FLOAT:
10753       sqlite3_result_double(pCtx, pSlot->rVal);
10754       break;
10755 
10756     case SQLITE_BLOB:
10757       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
10758       break;
10759 
10760     case SQLITE_TEXT:
10761       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
10762       break;
10763   }
10764 
10765   pSlot->eType = sqlite3_value_type(argv[1]);
10766   switch( pSlot->eType ){
10767     case SQLITE_NULL:
10768       /* no-op */
10769       break;
10770 
10771     case SQLITE_INTEGER:
10772       pSlot->iVal = sqlite3_value_int64(argv[1]);
10773       break;
10774 
10775     case SQLITE_FLOAT:
10776       pSlot->rVal = sqlite3_value_double(argv[1]);
10777       break;
10778 
10779     case SQLITE_BLOB:
10780     case SQLITE_TEXT: {
10781       int nByte = sqlite3_value_bytes(argv[1]);
10782       const void *pData = 0;
10783       if( nByte>pSlot->nByte ){
10784         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
10785         if( zNew==0 ){
10786           sqlite3_result_error_nomem(pCtx);
10787           return;
10788         }
10789         pSlot->nByte = nByte*2;
10790         pSlot->z = zNew;
10791       }
10792       pSlot->n = nByte;
10793       if( pSlot->eType==SQLITE_BLOB ){
10794         pData = sqlite3_value_blob(argv[1]);
10795         if( pData ) memcpy(pSlot->z, pData, nByte);
10796       }else{
10797         pData = sqlite3_value_text(argv[1]);
10798         memcpy(pSlot->z, pData, nByte);
10799       }
10800       break;
10801     }
10802   }
10803 }
10804 
10805 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
10806   int rc = SQLITE_OK;
10807   const char *zMax =
10808     "SELECT max(i.seqno) FROM "
10809     "  sqlite_schema AS s, "
10810     "  pragma_index_list(s.name) AS l, "
10811     "  pragma_index_info(l.name) AS i "
10812     "WHERE s.type = 'table'";
10813   sqlite3_stmt *pMax = 0;
10814 
10815   *pnMax = 0;
10816   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
10817   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
10818     *pnMax = sqlite3_column_int(pMax, 0) + 1;
10819   }
10820   idxFinalize(&rc, pMax);
10821 
10822   return rc;
10823 }
10824 
10825 static int idxPopulateOneStat1(
10826   sqlite3expert *p,
10827   sqlite3_stmt *pIndexXInfo,
10828   sqlite3_stmt *pWriteStat,
10829   const char *zTab,
10830   const char *zIdx,
10831   char **pzErr
10832 ){
10833   char *zCols = 0;
10834   char *zOrder = 0;
10835   char *zQuery = 0;
10836   int nCol = 0;
10837   int i;
10838   sqlite3_stmt *pQuery = 0;
10839   int *aStat = 0;
10840   int rc = SQLITE_OK;
10841 
10842   assert( p->iSample>0 );
10843 
10844   /* Formulate the query text */
10845   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
10846   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
10847     const char *zComma = zCols==0 ? "" : ", ";
10848     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
10849     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
10850     zCols = idxAppendText(&rc, zCols,
10851         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
10852     );
10853     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
10854   }
10855   sqlite3_reset(pIndexXInfo);
10856   if( rc==SQLITE_OK ){
10857     if( p->iSample==100 ){
10858       zQuery = sqlite3_mprintf(
10859           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
10860       );
10861     }else{
10862       zQuery = sqlite3_mprintf(
10863           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
10864       );
10865     }
10866   }
10867   sqlite3_free(zCols);
10868   sqlite3_free(zOrder);
10869 
10870   /* Formulate the query text */
10871   if( rc==SQLITE_OK ){
10872     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
10873     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
10874   }
10875   sqlite3_free(zQuery);
10876 
10877   if( rc==SQLITE_OK ){
10878     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
10879   }
10880   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
10881     IdxHashEntry *pEntry;
10882     char *zStat = 0;
10883     for(i=0; i<=nCol; i++) aStat[i] = 1;
10884     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
10885       aStat[0]++;
10886       for(i=0; i<nCol; i++){
10887         if( sqlite3_column_int(pQuery, i)==0 ) break;
10888       }
10889       for(/*no-op*/; i<nCol; i++){
10890         aStat[i+1]++;
10891       }
10892     }
10893 
10894     if( rc==SQLITE_OK ){
10895       int s0 = aStat[0];
10896       zStat = sqlite3_mprintf("%d", s0);
10897       if( zStat==0 ) rc = SQLITE_NOMEM;
10898       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
10899         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
10900       }
10901     }
10902 
10903     if( rc==SQLITE_OK ){
10904       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
10905       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
10906       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
10907       sqlite3_step(pWriteStat);
10908       rc = sqlite3_reset(pWriteStat);
10909     }
10910 
10911     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
10912     if( pEntry ){
10913       assert( pEntry->zVal2==0 );
10914       pEntry->zVal2 = zStat;
10915     }else{
10916       sqlite3_free(zStat);
10917     }
10918   }
10919   sqlite3_free(aStat);
10920   idxFinalize(&rc, pQuery);
10921 
10922   return rc;
10923 }
10924 
10925 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
10926   int rc;
10927   char *zSql;
10928 
10929   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
10930   if( rc!=SQLITE_OK ) return rc;
10931 
10932   zSql = sqlite3_mprintf(
10933       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
10934   );
10935   if( zSql==0 ) return SQLITE_NOMEM;
10936   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
10937   sqlite3_free(zSql);
10938 
10939   return rc;
10940 }
10941 
10942 /*
10943 ** This function is called as part of sqlite3_expert_analyze(). Candidate
10944 ** indexes have already been created in database sqlite3expert.dbm, this
10945 ** function populates sqlite_stat1 table in the same database.
10946 **
10947 ** The stat1 data is generated by querying the
10948 */
10949 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
10950   int rc = SQLITE_OK;
10951   int nMax =0;
10952   struct IdxRemCtx *pCtx = 0;
10953   struct IdxSampleCtx samplectx;
10954   int i;
10955   i64 iPrev = -100000;
10956   sqlite3_stmt *pAllIndex = 0;
10957   sqlite3_stmt *pIndexXInfo = 0;
10958   sqlite3_stmt *pWrite = 0;
10959 
10960   const char *zAllIndex =
10961     "SELECT s.rowid, s.name, l.name FROM "
10962     "  sqlite_schema AS s, "
10963     "  pragma_index_list(s.name) AS l "
10964     "WHERE s.type = 'table'";
10965   const char *zIndexXInfo =
10966     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
10967   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
10968 
10969   /* If iSample==0, no sqlite_stat1 data is required. */
10970   if( p->iSample==0 ) return SQLITE_OK;
10971 
10972   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
10973   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
10974 
10975   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
10976 
10977   if( rc==SQLITE_OK ){
10978     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
10979     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
10980   }
10981 
10982   if( rc==SQLITE_OK ){
10983     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
10984     rc = sqlite3_create_function(
10985         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
10986     );
10987   }
10988   if( rc==SQLITE_OK ){
10989     rc = sqlite3_create_function(
10990         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
10991     );
10992   }
10993 
10994   if( rc==SQLITE_OK ){
10995     pCtx->nSlot = nMax+1;
10996     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
10997   }
10998   if( rc==SQLITE_OK ){
10999     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
11000   }
11001   if( rc==SQLITE_OK ){
11002     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
11003   }
11004 
11005   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
11006     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
11007     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
11008     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
11009     if( zTab==0 || zIdx==0 ) continue;
11010     if( p->iSample<100 && iPrev!=iRowid ){
11011       samplectx.target = (double)p->iSample / 100.0;
11012       samplectx.iTarget = p->iSample;
11013       samplectx.nRow = 0.0;
11014       samplectx.nRet = 0.0;
11015       rc = idxBuildSampleTable(p, zTab);
11016       if( rc!=SQLITE_OK ) break;
11017     }
11018     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
11019     iPrev = iRowid;
11020   }
11021   if( rc==SQLITE_OK && p->iSample<100 ){
11022     rc = sqlite3_exec(p->dbv,
11023         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
11024     );
11025   }
11026 
11027   idxFinalize(&rc, pAllIndex);
11028   idxFinalize(&rc, pIndexXInfo);
11029   idxFinalize(&rc, pWrite);
11030 
11031   if( pCtx ){
11032     for(i=0; i<pCtx->nSlot; i++){
11033       sqlite3_free(pCtx->aSlot[i].z);
11034     }
11035     sqlite3_free(pCtx);
11036   }
11037 
11038   if( rc==SQLITE_OK ){
11039     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
11040   }
11041 
11042   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
11043   return rc;
11044 }
11045 
11046 /*
11047 ** Allocate a new sqlite3expert object.
11048 */
11049 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
11050   int rc = SQLITE_OK;
11051   sqlite3expert *pNew;
11052 
11053   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
11054 
11055   /* Open two in-memory databases to work with. The "vtab database" (dbv)
11056   ** will contain a virtual table corresponding to each real table in
11057   ** the user database schema, and a copy of each view. It is used to
11058   ** collect information regarding the WHERE, ORDER BY and other clauses
11059   ** of the user's query.
11060   */
11061   if( rc==SQLITE_OK ){
11062     pNew->db = db;
11063     pNew->iSample = 100;
11064     rc = sqlite3_open(":memory:", &pNew->dbv);
11065   }
11066   if( rc==SQLITE_OK ){
11067     rc = sqlite3_open(":memory:", &pNew->dbm);
11068     if( rc==SQLITE_OK ){
11069       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
11070     }
11071   }
11072 
11073 
11074   /* Copy the entire schema of database [db] into [dbm]. */
11075   if( rc==SQLITE_OK ){
11076     sqlite3_stmt *pSql = 0;
11077     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
11078         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
11079         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
11080     );
11081     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
11082       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
11083       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
11084     }
11085     idxFinalize(&rc, pSql);
11086   }
11087 
11088   /* Create the vtab schema */
11089   if( rc==SQLITE_OK ){
11090     rc = idxCreateVtabSchema(pNew, pzErrmsg);
11091   }
11092 
11093   /* Register the auth callback with dbv */
11094   if( rc==SQLITE_OK ){
11095     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
11096   }
11097 
11098   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
11099   ** return the new sqlite3expert handle.  */
11100   if( rc!=SQLITE_OK ){
11101     sqlite3_expert_destroy(pNew);
11102     pNew = 0;
11103   }
11104   return pNew;
11105 }
11106 
11107 /*
11108 ** Configure an sqlite3expert object.
11109 */
11110 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
11111   int rc = SQLITE_OK;
11112   va_list ap;
11113   va_start(ap, op);
11114   switch( op ){
11115     case EXPERT_CONFIG_SAMPLE: {
11116       int iVal = va_arg(ap, int);
11117       if( iVal<0 ) iVal = 0;
11118       if( iVal>100 ) iVal = 100;
11119       p->iSample = iVal;
11120       break;
11121     }
11122     default:
11123       rc = SQLITE_NOTFOUND;
11124       break;
11125   }
11126 
11127   va_end(ap);
11128   return rc;
11129 }
11130 
11131 /*
11132 ** Add an SQL statement to the analysis.
11133 */
11134 int sqlite3_expert_sql(
11135   sqlite3expert *p,               /* From sqlite3_expert_new() */
11136   const char *zSql,               /* SQL statement to add */
11137   char **pzErr                    /* OUT: Error message (if any) */
11138 ){
11139   IdxScan *pScanOrig = p->pScan;
11140   IdxStatement *pStmtOrig = p->pStatement;
11141   int rc = SQLITE_OK;
11142   const char *zStmt = zSql;
11143 
11144   if( p->bRun ) return SQLITE_MISUSE;
11145 
11146   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
11147     sqlite3_stmt *pStmt = 0;
11148     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
11149     if( rc==SQLITE_OK ){
11150       if( pStmt ){
11151         IdxStatement *pNew;
11152         const char *z = sqlite3_sql(pStmt);
11153         int n = STRLEN(z);
11154         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
11155         if( rc==SQLITE_OK ){
11156           pNew->zSql = (char*)&pNew[1];
11157           memcpy(pNew->zSql, z, n+1);
11158           pNew->pNext = p->pStatement;
11159           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
11160           p->pStatement = pNew;
11161         }
11162         sqlite3_finalize(pStmt);
11163       }
11164     }else{
11165       idxDatabaseError(p->dbv, pzErr);
11166     }
11167   }
11168 
11169   if( rc!=SQLITE_OK ){
11170     idxScanFree(p->pScan, pScanOrig);
11171     idxStatementFree(p->pStatement, pStmtOrig);
11172     p->pScan = pScanOrig;
11173     p->pStatement = pStmtOrig;
11174   }
11175 
11176   return rc;
11177 }
11178 
11179 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
11180   int rc;
11181   IdxHashEntry *pEntry;
11182 
11183   /* Do trigger processing to collect any extra IdxScan structures */
11184   rc = idxProcessTriggers(p, pzErr);
11185 
11186   /* Create candidate indexes within the in-memory database file */
11187   if( rc==SQLITE_OK ){
11188     rc = idxCreateCandidates(p);
11189   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
11190     if( pzErr )
11191       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
11192     return rc;
11193   }
11194 
11195   /* Generate the stat1 data */
11196   if( rc==SQLITE_OK ){
11197     rc = idxPopulateStat1(p, pzErr);
11198   }
11199 
11200   /* Formulate the EXPERT_REPORT_CANDIDATES text */
11201   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
11202     p->zCandidates = idxAppendText(&rc, p->zCandidates,
11203         "%s;%s%s\n", pEntry->zVal,
11204         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
11205     );
11206   }
11207 
11208   /* Figure out which of the candidate indexes are preferred by the query
11209   ** planner and report the results to the user.  */
11210   if( rc==SQLITE_OK ){
11211     rc = idxFindIndexes(p, pzErr);
11212   }
11213 
11214   if( rc==SQLITE_OK ){
11215     p->bRun = 1;
11216   }
11217   return rc;
11218 }
11219 
11220 /*
11221 ** Return the total number of statements that have been added to this
11222 ** sqlite3expert using sqlite3_expert_sql().
11223 */
11224 int sqlite3_expert_count(sqlite3expert *p){
11225   int nRet = 0;
11226   if( p->pStatement ) nRet = p->pStatement->iId+1;
11227   return nRet;
11228 }
11229 
11230 /*
11231 ** Return a component of the report.
11232 */
11233 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
11234   const char *zRet = 0;
11235   IdxStatement *pStmt;
11236 
11237   if( p->bRun==0 ) return 0;
11238   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
11239   switch( eReport ){
11240     case EXPERT_REPORT_SQL:
11241       if( pStmt ) zRet = pStmt->zSql;
11242       break;
11243     case EXPERT_REPORT_INDEXES:
11244       if( pStmt ) zRet = pStmt->zIdx;
11245       break;
11246     case EXPERT_REPORT_PLAN:
11247       if( pStmt ) zRet = pStmt->zEQP;
11248       break;
11249     case EXPERT_REPORT_CANDIDATES:
11250       zRet = p->zCandidates;
11251       break;
11252   }
11253   return zRet;
11254 }
11255 
11256 /*
11257 ** Free an sqlite3expert object.
11258 */
11259 void sqlite3_expert_destroy(sqlite3expert *p){
11260   if( p ){
11261     sqlite3_close(p->dbm);
11262     sqlite3_close(p->dbv);
11263     idxScanFree(p->pScan, 0);
11264     idxStatementFree(p->pStatement, 0);
11265     idxTableFree(p->pTable);
11266     idxWriteFree(p->pWrite);
11267     idxHashClear(&p->hIdx);
11268     sqlite3_free(p->zCandidates);
11269     sqlite3_free(p);
11270   }
11271 }
11272 
11273 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
11274 
11275 /************************* End ../ext/expert/sqlite3expert.c ********************/
11276 
11277 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
11278 /************************* Begin ../ext/misc/dbdata.c ******************/
11279 /*
11280 ** 2019-04-17
11281 **
11282 ** The author disclaims copyright to this source code.  In place of
11283 ** a legal notice, here is a blessing:
11284 **
11285 **    May you do good and not evil.
11286 **    May you find forgiveness for yourself and forgive others.
11287 **    May you share freely, never taking more than you give.
11288 **
11289 ******************************************************************************
11290 **
11291 ** This file contains an implementation of two eponymous virtual tables,
11292 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
11293 ** "sqlite_dbpage" eponymous virtual table be available.
11294 **
11295 ** SQLITE_DBDATA:
11296 **   sqlite_dbdata is used to extract data directly from a database b-tree
11297 **   page and its associated overflow pages, bypassing the b-tree layer.
11298 **   The table schema is equivalent to:
11299 **
11300 **     CREATE TABLE sqlite_dbdata(
11301 **       pgno INTEGER,
11302 **       cell INTEGER,
11303 **       field INTEGER,
11304 **       value ANY,
11305 **       schema TEXT HIDDEN
11306 **     );
11307 **
11308 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
11309 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
11310 **   "schema".
11311 **
11312 **   Each page of the database is inspected. If it cannot be interpreted as
11313 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
11314 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
11315 **   table contains one row for each field in the record associated with
11316 **   each cell on the page. For intkey b-trees, the key value is stored in
11317 **   field -1.
11318 **
11319 **   For example, for the database:
11320 **
11321 **     CREATE TABLE t1(a, b);     -- root page is page 2
11322 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
11323 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
11324 **
11325 **   the sqlite_dbdata table contains, as well as from entries related to
11326 **   page 1, content equivalent to:
11327 **
11328 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
11329 **         (2, 0, -1, 5     ),
11330 **         (2, 0,  0, 'v'   ),
11331 **         (2, 0,  1, 'five'),
11332 **         (2, 1, -1, 10    ),
11333 **         (2, 1,  0, 'x'   ),
11334 **         (2, 1,  1, 'ten' );
11335 **
11336 **   If database corruption is encountered, this module does not report an
11337 **   error. Instead, it attempts to extract as much data as possible and
11338 **   ignores the corruption.
11339 **
11340 ** SQLITE_DBPTR:
11341 **   The sqlite_dbptr table has the following schema:
11342 **
11343 **     CREATE TABLE sqlite_dbptr(
11344 **       pgno INTEGER,
11345 **       child INTEGER,
11346 **       schema TEXT HIDDEN
11347 **     );
11348 **
11349 **   It contains one entry for each b-tree pointer between a parent and
11350 **   child page in the database.
11351 */
11352 #if !defined(SQLITEINT_H)
11353 /* #include "sqlite3ext.h" */
11354 
11355 /* typedef unsigned char u8; */
11356 
11357 #endif
11358 SQLITE_EXTENSION_INIT1
11359 #include <string.h>
11360 #include <assert.h>
11361 
11362 #define DBDATA_PADDING_BYTES 100
11363 
11364 typedef struct DbdataTable DbdataTable;
11365 typedef struct DbdataCursor DbdataCursor;
11366 
11367 /* Cursor object */
11368 struct DbdataCursor {
11369   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
11370   sqlite3_stmt *pStmt;            /* For fetching database pages */
11371 
11372   int iPgno;                      /* Current page number */
11373   u8 *aPage;                      /* Buffer containing page */
11374   int nPage;                      /* Size of aPage[] in bytes */
11375   int nCell;                      /* Number of cells on aPage[] */
11376   int iCell;                      /* Current cell number */
11377   int bOnePage;                   /* True to stop after one page */
11378   int szDb;
11379   sqlite3_int64 iRowid;
11380 
11381   /* Only for the sqlite_dbdata table */
11382   u8 *pRec;                       /* Buffer containing current record */
11383   int nRec;                       /* Size of pRec[] in bytes */
11384   int nHdr;                       /* Size of header in bytes */
11385   int iField;                     /* Current field number */
11386   u8 *pHdrPtr;
11387   u8 *pPtr;
11388 
11389   sqlite3_int64 iIntkey;          /* Integer key value */
11390 };
11391 
11392 /* Table object */
11393 struct DbdataTable {
11394   sqlite3_vtab base;              /* Base class.  Must be first */
11395   sqlite3 *db;                    /* The database connection */
11396   sqlite3_stmt *pStmt;            /* For fetching database pages */
11397   int bPtr;                       /* True for sqlite3_dbptr table */
11398 };
11399 
11400 /* Column and schema definitions for sqlite_dbdata */
11401 #define DBDATA_COLUMN_PGNO        0
11402 #define DBDATA_COLUMN_CELL        1
11403 #define DBDATA_COLUMN_FIELD       2
11404 #define DBDATA_COLUMN_VALUE       3
11405 #define DBDATA_COLUMN_SCHEMA      4
11406 #define DBDATA_SCHEMA             \
11407       "CREATE TABLE x("           \
11408       "  pgno INTEGER,"           \
11409       "  cell INTEGER,"           \
11410       "  field INTEGER,"          \
11411       "  value ANY,"              \
11412       "  schema TEXT HIDDEN"      \
11413       ")"
11414 
11415 /* Column and schema definitions for sqlite_dbptr */
11416 #define DBPTR_COLUMN_PGNO         0
11417 #define DBPTR_COLUMN_CHILD        1
11418 #define DBPTR_COLUMN_SCHEMA       2
11419 #define DBPTR_SCHEMA              \
11420       "CREATE TABLE x("           \
11421       "  pgno INTEGER,"           \
11422       "  child INTEGER,"          \
11423       "  schema TEXT HIDDEN"      \
11424       ")"
11425 
11426 /*
11427 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
11428 ** table.
11429 */
11430 static int dbdataConnect(
11431   sqlite3 *db,
11432   void *pAux,
11433   int argc, const char *const*argv,
11434   sqlite3_vtab **ppVtab,
11435   char **pzErr
11436 ){
11437   DbdataTable *pTab = 0;
11438   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
11439 
11440   if( rc==SQLITE_OK ){
11441     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
11442     if( pTab==0 ){
11443       rc = SQLITE_NOMEM;
11444     }else{
11445       memset(pTab, 0, sizeof(DbdataTable));
11446       pTab->db = db;
11447       pTab->bPtr = (pAux!=0);
11448     }
11449   }
11450 
11451   *ppVtab = (sqlite3_vtab*)pTab;
11452   return rc;
11453 }
11454 
11455 /*
11456 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
11457 */
11458 static int dbdataDisconnect(sqlite3_vtab *pVtab){
11459   DbdataTable *pTab = (DbdataTable*)pVtab;
11460   if( pTab ){
11461     sqlite3_finalize(pTab->pStmt);
11462     sqlite3_free(pVtab);
11463   }
11464   return SQLITE_OK;
11465 }
11466 
11467 /*
11468 ** This function interprets two types of constraints:
11469 **
11470 **       schema=?
11471 **       pgno=?
11472 **
11473 ** If neither are present, idxNum is set to 0. If schema=? is present,
11474 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
11475 ** in idxNum is set.
11476 **
11477 ** If both parameters are present, schema is in position 0 and pgno in
11478 ** position 1.
11479 */
11480 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
11481   DbdataTable *pTab = (DbdataTable*)tab;
11482   int i;
11483   int iSchema = -1;
11484   int iPgno = -1;
11485   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
11486 
11487   for(i=0; i<pIdx->nConstraint; i++){
11488     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
11489     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
11490       if( p->iColumn==colSchema ){
11491         if( p->usable==0 ) return SQLITE_CONSTRAINT;
11492         iSchema = i;
11493       }
11494       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
11495         iPgno = i;
11496       }
11497     }
11498   }
11499 
11500   if( iSchema>=0 ){
11501     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
11502     pIdx->aConstraintUsage[iSchema].omit = 1;
11503   }
11504   if( iPgno>=0 ){
11505     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
11506     pIdx->aConstraintUsage[iPgno].omit = 1;
11507     pIdx->estimatedCost = 100;
11508     pIdx->estimatedRows =  50;
11509 
11510     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
11511       int iCol = pIdx->aOrderBy[0].iColumn;
11512       if( pIdx->nOrderBy==1 ){
11513         pIdx->orderByConsumed = (iCol==0 || iCol==1);
11514       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
11515         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
11516       }
11517     }
11518 
11519   }else{
11520     pIdx->estimatedCost = 100000000;
11521     pIdx->estimatedRows = 1000000000;
11522   }
11523   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
11524   return SQLITE_OK;
11525 }
11526 
11527 /*
11528 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
11529 */
11530 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
11531   DbdataCursor *pCsr;
11532 
11533   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
11534   if( pCsr==0 ){
11535     return SQLITE_NOMEM;
11536   }else{
11537     memset(pCsr, 0, sizeof(DbdataCursor));
11538     pCsr->base.pVtab = pVTab;
11539   }
11540 
11541   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
11542   return SQLITE_OK;
11543 }
11544 
11545 /*
11546 ** Restore a cursor object to the state it was in when first allocated
11547 ** by dbdataOpen().
11548 */
11549 static void dbdataResetCursor(DbdataCursor *pCsr){
11550   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
11551   if( pTab->pStmt==0 ){
11552     pTab->pStmt = pCsr->pStmt;
11553   }else{
11554     sqlite3_finalize(pCsr->pStmt);
11555   }
11556   pCsr->pStmt = 0;
11557   pCsr->iPgno = 1;
11558   pCsr->iCell = 0;
11559   pCsr->iField = 0;
11560   pCsr->bOnePage = 0;
11561   sqlite3_free(pCsr->aPage);
11562   sqlite3_free(pCsr->pRec);
11563   pCsr->pRec = 0;
11564   pCsr->aPage = 0;
11565 }
11566 
11567 /*
11568 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
11569 */
11570 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
11571   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11572   dbdataResetCursor(pCsr);
11573   sqlite3_free(pCsr);
11574   return SQLITE_OK;
11575 }
11576 
11577 /*
11578 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
11579 */
11580 static unsigned int get_uint16(unsigned char *a){
11581   return (a[0]<<8)|a[1];
11582 }
11583 static unsigned int get_uint32(unsigned char *a){
11584   return ((unsigned int)a[0]<<24)
11585        | ((unsigned int)a[1]<<16)
11586        | ((unsigned int)a[2]<<8)
11587        | ((unsigned int)a[3]);
11588 }
11589 
11590 /*
11591 ** Load page pgno from the database via the sqlite_dbpage virtual table.
11592 ** If successful, set (*ppPage) to point to a buffer containing the page
11593 ** data, (*pnPage) to the size of that buffer in bytes and return
11594 ** SQLITE_OK. In this case it is the responsibility of the caller to
11595 ** eventually free the buffer using sqlite3_free().
11596 **
11597 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
11598 ** return an SQLite error code.
11599 */
11600 static int dbdataLoadPage(
11601   DbdataCursor *pCsr,             /* Cursor object */
11602   unsigned int pgno,              /* Page number of page to load */
11603   u8 **ppPage,                    /* OUT: pointer to page buffer */
11604   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
11605 ){
11606   int rc2;
11607   int rc = SQLITE_OK;
11608   sqlite3_stmt *pStmt = pCsr->pStmt;
11609 
11610   *ppPage = 0;
11611   *pnPage = 0;
11612   sqlite3_bind_int64(pStmt, 2, pgno);
11613   if( SQLITE_ROW==sqlite3_step(pStmt) ){
11614     int nCopy = sqlite3_column_bytes(pStmt, 0);
11615     if( nCopy>0 ){
11616       u8 *pPage;
11617       pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
11618       if( pPage==0 ){
11619         rc = SQLITE_NOMEM;
11620       }else{
11621         const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
11622         memcpy(pPage, pCopy, nCopy);
11623         memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
11624       }
11625       *ppPage = pPage;
11626       *pnPage = nCopy;
11627     }
11628   }
11629   rc2 = sqlite3_reset(pStmt);
11630   if( rc==SQLITE_OK ) rc = rc2;
11631 
11632   return rc;
11633 }
11634 
11635 /*
11636 ** Read a varint.  Put the value in *pVal and return the number of bytes.
11637 */
11638 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
11639   sqlite3_int64 v = 0;
11640   int i;
11641   for(i=0; i<8; i++){
11642     v = (v<<7) + (z[i]&0x7f);
11643     if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; }
11644   }
11645   v = (v<<8) + (z[i]&0xff);
11646   *pVal = v;
11647   return 9;
11648 }
11649 
11650 /*
11651 ** Return the number of bytes of space used by an SQLite value of type
11652 ** eType.
11653 */
11654 static int dbdataValueBytes(int eType){
11655   switch( eType ){
11656     case 0: case 8: case 9:
11657     case 10: case 11:
11658       return 0;
11659     case 1:
11660       return 1;
11661     case 2:
11662       return 2;
11663     case 3:
11664       return 3;
11665     case 4:
11666       return 4;
11667     case 5:
11668       return 6;
11669     case 6:
11670     case 7:
11671       return 8;
11672     default:
11673       if( eType>0 ){
11674         return ((eType-12) / 2);
11675       }
11676       return 0;
11677   }
11678 }
11679 
11680 /*
11681 ** Load a value of type eType from buffer pData and use it to set the
11682 ** result of context object pCtx.
11683 */
11684 static void dbdataValue(
11685   sqlite3_context *pCtx,
11686   int eType,
11687   u8 *pData,
11688   int nData
11689 ){
11690   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
11691     switch( eType ){
11692       case 0:
11693       case 10:
11694       case 11:
11695         sqlite3_result_null(pCtx);
11696         break;
11697 
11698       case 8:
11699         sqlite3_result_int(pCtx, 0);
11700         break;
11701       case 9:
11702         sqlite3_result_int(pCtx, 1);
11703         break;
11704 
11705       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
11706         sqlite3_uint64 v = (signed char)pData[0];
11707         pData++;
11708         switch( eType ){
11709           case 7:
11710           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
11711           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
11712           case 4:  v = (v<<8) + pData[0];  pData++;
11713           case 3:  v = (v<<8) + pData[0];  pData++;
11714           case 2:  v = (v<<8) + pData[0];  pData++;
11715         }
11716 
11717         if( eType==7 ){
11718           double r;
11719           memcpy(&r, &v, sizeof(r));
11720           sqlite3_result_double(pCtx, r);
11721         }else{
11722           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
11723         }
11724         break;
11725       }
11726 
11727       default: {
11728         int n = ((eType-12) / 2);
11729         if( eType % 2 ){
11730           sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT);
11731         }else{
11732           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
11733         }
11734       }
11735     }
11736   }
11737 }
11738 
11739 /*
11740 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
11741 */
11742 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
11743   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11744   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11745 
11746   pCsr->iRowid++;
11747   while( 1 ){
11748     int rc;
11749     int iOff = (pCsr->iPgno==1 ? 100 : 0);
11750     int bNextPage = 0;
11751 
11752     if( pCsr->aPage==0 ){
11753       while( 1 ){
11754         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
11755         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
11756         if( rc!=SQLITE_OK ) return rc;
11757         if( pCsr->aPage ) break;
11758         pCsr->iPgno++;
11759       }
11760       pCsr->iCell = pTab->bPtr ? -2 : 0;
11761       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
11762     }
11763 
11764     if( pTab->bPtr ){
11765       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
11766         pCsr->iCell = pCsr->nCell;
11767       }
11768       pCsr->iCell++;
11769       if( pCsr->iCell>=pCsr->nCell ){
11770         sqlite3_free(pCsr->aPage);
11771         pCsr->aPage = 0;
11772         if( pCsr->bOnePage ) return SQLITE_OK;
11773         pCsr->iPgno++;
11774       }else{
11775         return SQLITE_OK;
11776       }
11777     }else{
11778       /* If there is no record loaded, load it now. */
11779       if( pCsr->pRec==0 ){
11780         int bHasRowid = 0;
11781         int nPointer = 0;
11782         sqlite3_int64 nPayload = 0;
11783         sqlite3_int64 nHdr = 0;
11784         int iHdr;
11785         int U, X;
11786         int nLocal;
11787 
11788         switch( pCsr->aPage[iOff] ){
11789           case 0x02:
11790             nPointer = 4;
11791             break;
11792           case 0x0a:
11793             break;
11794           case 0x0d:
11795             bHasRowid = 1;
11796             break;
11797           default:
11798             /* This is not a b-tree page with records on it. Continue. */
11799             pCsr->iCell = pCsr->nCell;
11800             break;
11801         }
11802 
11803         if( pCsr->iCell>=pCsr->nCell ){
11804           bNextPage = 1;
11805         }else{
11806 
11807           iOff += 8 + nPointer + pCsr->iCell*2;
11808           if( iOff>pCsr->nPage ){
11809             bNextPage = 1;
11810           }else{
11811             iOff = get_uint16(&pCsr->aPage[iOff]);
11812           }
11813 
11814           /* For an interior node cell, skip past the child-page number */
11815           iOff += nPointer;
11816 
11817           /* Load the "byte of payload including overflow" field */
11818           if( bNextPage || iOff>pCsr->nPage ){
11819             bNextPage = 1;
11820           }else{
11821             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload);
11822           }
11823 
11824           /* If this is a leaf intkey cell, load the rowid */
11825           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
11826             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
11827           }
11828 
11829           /* Figure out how much data to read from the local page */
11830           U = pCsr->nPage;
11831           if( bHasRowid ){
11832             X = U-35;
11833           }else{
11834             X = ((U-12)*64/255)-23;
11835           }
11836           if( nPayload<=X ){
11837             nLocal = nPayload;
11838           }else{
11839             int M, K;
11840             M = ((U-12)*32/255)-23;
11841             K = M+((nPayload-M)%(U-4));
11842             if( K<=X ){
11843               nLocal = K;
11844             }else{
11845               nLocal = M;
11846             }
11847           }
11848 
11849           if( bNextPage || nLocal+iOff>pCsr->nPage ){
11850             bNextPage = 1;
11851           }else{
11852 
11853             /* Allocate space for payload. And a bit more to catch small buffer
11854             ** overruns caused by attempting to read a varint or similar from
11855             ** near the end of a corrupt record.  */
11856             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
11857             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
11858             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
11859             pCsr->nRec = nPayload;
11860 
11861             /* Load the nLocal bytes of payload */
11862             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
11863             iOff += nLocal;
11864 
11865             /* Load content from overflow pages */
11866             if( nPayload>nLocal ){
11867               sqlite3_int64 nRem = nPayload - nLocal;
11868               unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
11869               while( nRem>0 ){
11870                 u8 *aOvfl = 0;
11871                 int nOvfl = 0;
11872                 int nCopy;
11873                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
11874                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
11875                 if( rc!=SQLITE_OK ) return rc;
11876                 if( aOvfl==0 ) break;
11877 
11878                 nCopy = U-4;
11879                 if( nCopy>nRem ) nCopy = nRem;
11880                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
11881                 nRem -= nCopy;
11882 
11883                 pgnoOvfl = get_uint32(aOvfl);
11884                 sqlite3_free(aOvfl);
11885               }
11886             }
11887 
11888             iHdr = dbdataGetVarint(pCsr->pRec, &nHdr);
11889             pCsr->nHdr = nHdr;
11890             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
11891             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
11892             pCsr->iField = (bHasRowid ? -1 : 0);
11893           }
11894         }
11895       }else{
11896         pCsr->iField++;
11897         if( pCsr->iField>0 ){
11898           sqlite3_int64 iType;
11899           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
11900             bNextPage = 1;
11901           }else{
11902             pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType);
11903             pCsr->pPtr += dbdataValueBytes(iType);
11904           }
11905         }
11906       }
11907 
11908       if( bNextPage ){
11909         sqlite3_free(pCsr->aPage);
11910         sqlite3_free(pCsr->pRec);
11911         pCsr->aPage = 0;
11912         pCsr->pRec = 0;
11913         if( pCsr->bOnePage ) return SQLITE_OK;
11914         pCsr->iPgno++;
11915       }else{
11916         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
11917           return SQLITE_OK;
11918         }
11919 
11920         /* Advance to the next cell. The next iteration of the loop will load
11921         ** the record and so on. */
11922         sqlite3_free(pCsr->pRec);
11923         pCsr->pRec = 0;
11924         pCsr->iCell++;
11925       }
11926     }
11927   }
11928 
11929   assert( !"can't get here" );
11930   return SQLITE_OK;
11931 }
11932 
11933 /*
11934 ** Return true if the cursor is at EOF.
11935 */
11936 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
11937   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11938   return pCsr->aPage==0;
11939 }
11940 
11941 /*
11942 ** Determine the size in pages of database zSchema (where zSchema is
11943 ** "main", "temp" or the name of an attached database) and set
11944 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
11945 ** an SQLite error code.
11946 */
11947 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
11948   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
11949   char *zSql = 0;
11950   int rc, rc2;
11951   sqlite3_stmt *pStmt = 0;
11952 
11953   zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
11954   if( zSql==0 ) return SQLITE_NOMEM;
11955   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
11956   sqlite3_free(zSql);
11957   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
11958     pCsr->szDb = sqlite3_column_int(pStmt, 0);
11959   }
11960   rc2 = sqlite3_finalize(pStmt);
11961   if( rc==SQLITE_OK ) rc = rc2;
11962   return rc;
11963 }
11964 
11965 /*
11966 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
11967 */
11968 static int dbdataFilter(
11969   sqlite3_vtab_cursor *pCursor,
11970   int idxNum, const char *idxStr,
11971   int argc, sqlite3_value **argv
11972 ){
11973   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
11974   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
11975   int rc = SQLITE_OK;
11976   const char *zSchema = "main";
11977 
11978   dbdataResetCursor(pCsr);
11979   assert( pCsr->iPgno==1 );
11980   if( idxNum & 0x01 ){
11981     zSchema = (const char*)sqlite3_value_text(argv[0]);
11982   }
11983   if( idxNum & 0x02 ){
11984     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
11985     pCsr->bOnePage = 1;
11986   }else{
11987     pCsr->nPage = dbdataDbsize(pCsr, zSchema);
11988     rc = dbdataDbsize(pCsr, zSchema);
11989   }
11990 
11991   if( rc==SQLITE_OK ){
11992     if( pTab->pStmt ){
11993       pCsr->pStmt = pTab->pStmt;
11994       pTab->pStmt = 0;
11995     }else{
11996       rc = sqlite3_prepare_v2(pTab->db,
11997           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
11998           &pCsr->pStmt, 0
11999       );
12000     }
12001   }
12002   if( rc==SQLITE_OK ){
12003     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
12004   }else{
12005     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
12006   }
12007   if( rc==SQLITE_OK ){
12008     rc = dbdataNext(pCursor);
12009   }
12010   return rc;
12011 }
12012 
12013 /*
12014 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
12015 */
12016 static int dbdataColumn(
12017   sqlite3_vtab_cursor *pCursor,
12018   sqlite3_context *ctx,
12019   int i
12020 ){
12021   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
12022   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
12023   if( pTab->bPtr ){
12024     switch( i ){
12025       case DBPTR_COLUMN_PGNO:
12026         sqlite3_result_int64(ctx, pCsr->iPgno);
12027         break;
12028       case DBPTR_COLUMN_CHILD: {
12029         int iOff = pCsr->iPgno==1 ? 100 : 0;
12030         if( pCsr->iCell<0 ){
12031           iOff += 8;
12032         }else{
12033           iOff += 12 + pCsr->iCell*2;
12034           if( iOff>pCsr->nPage ) return SQLITE_OK;
12035           iOff = get_uint16(&pCsr->aPage[iOff]);
12036         }
12037         if( iOff<=pCsr->nPage ){
12038           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
12039         }
12040         break;
12041       }
12042     }
12043   }else{
12044     switch( i ){
12045       case DBDATA_COLUMN_PGNO:
12046         sqlite3_result_int64(ctx, pCsr->iPgno);
12047         break;
12048       case DBDATA_COLUMN_CELL:
12049         sqlite3_result_int(ctx, pCsr->iCell);
12050         break;
12051       case DBDATA_COLUMN_FIELD:
12052         sqlite3_result_int(ctx, pCsr->iField);
12053         break;
12054       case DBDATA_COLUMN_VALUE: {
12055         if( pCsr->iField<0 ){
12056           sqlite3_result_int64(ctx, pCsr->iIntkey);
12057         }else{
12058           sqlite3_int64 iType;
12059           dbdataGetVarint(pCsr->pHdrPtr, &iType);
12060           dbdataValue(
12061               ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
12062           );
12063         }
12064         break;
12065       }
12066     }
12067   }
12068   return SQLITE_OK;
12069 }
12070 
12071 /*
12072 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
12073 */
12074 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
12075   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
12076   *pRowid = pCsr->iRowid;
12077   return SQLITE_OK;
12078 }
12079 
12080 
12081 /*
12082 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
12083 */
12084 static int sqlite3DbdataRegister(sqlite3 *db){
12085   static sqlite3_module dbdata_module = {
12086     0,                            /* iVersion */
12087     0,                            /* xCreate */
12088     dbdataConnect,                /* xConnect */
12089     dbdataBestIndex,              /* xBestIndex */
12090     dbdataDisconnect,             /* xDisconnect */
12091     0,                            /* xDestroy */
12092     dbdataOpen,                   /* xOpen - open a cursor */
12093     dbdataClose,                  /* xClose - close a cursor */
12094     dbdataFilter,                 /* xFilter - configure scan constraints */
12095     dbdataNext,                   /* xNext - advance a cursor */
12096     dbdataEof,                    /* xEof - check for end of scan */
12097     dbdataColumn,                 /* xColumn - read data */
12098     dbdataRowid,                  /* xRowid - read data */
12099     0,                            /* xUpdate */
12100     0,                            /* xBegin */
12101     0,                            /* xSync */
12102     0,                            /* xCommit */
12103     0,                            /* xRollback */
12104     0,                            /* xFindMethod */
12105     0,                            /* xRename */
12106     0,                            /* xSavepoint */
12107     0,                            /* xRelease */
12108     0,                            /* xRollbackTo */
12109     0                             /* xShadowName */
12110   };
12111 
12112   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
12113   if( rc==SQLITE_OK ){
12114     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
12115   }
12116   return rc;
12117 }
12118 
12119 #ifdef _WIN32
12120 
12121 #endif
12122 int sqlite3_dbdata_init(
12123   sqlite3 *db,
12124   char **pzErrMsg,
12125   const sqlite3_api_routines *pApi
12126 ){
12127   SQLITE_EXTENSION_INIT2(pApi);
12128   return sqlite3DbdataRegister(db);
12129 }
12130 
12131 /************************* End ../ext/misc/dbdata.c ********************/
12132 #endif
12133 
12134 #if defined(SQLITE_ENABLE_SESSION)
12135 /*
12136 ** State information for a single open session
12137 */
12138 typedef struct OpenSession OpenSession;
12139 struct OpenSession {
12140   char *zName;             /* Symbolic name for this session */
12141   int nFilter;             /* Number of xFilter rejection GLOB patterns */
12142   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
12143   sqlite3_session *p;      /* The open session */
12144 };
12145 #endif
12146 
12147 typedef struct ExpertInfo ExpertInfo;
12148 struct ExpertInfo {
12149   sqlite3expert *pExpert;
12150   int bVerbose;
12151 };
12152 
12153 /* A single line in the EQP output */
12154 typedef struct EQPGraphRow EQPGraphRow;
12155 struct EQPGraphRow {
12156   int iEqpId;           /* ID for this row */
12157   int iParentId;        /* ID of the parent row */
12158   EQPGraphRow *pNext;   /* Next row in sequence */
12159   char zText[1];        /* Text to display for this row */
12160 };
12161 
12162 /* All EQP output is collected into an instance of the following */
12163 typedef struct EQPGraph EQPGraph;
12164 struct EQPGraph {
12165   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
12166   EQPGraphRow *pLast;   /* Last element of the pRow list */
12167   char zPrefix[100];    /* Graph prefix */
12168 };
12169 
12170 /* Parameters affecting columnar mode result display (defaulting together) */
12171 typedef struct ColModeOpts {
12172   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
12173   u8 bQuote;            /* Quote results for .mode box and table */
12174   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
12175 } ColModeOpts;
12176 #define ColModeOpts_default { 60, 0, 0 }
12177 #define ColModeOpts_default_qbox { 60, 1, 0 }
12178 
12179 /*
12180 ** State information about the database connection is contained in an
12181 ** instance of the following structure.
12182 */
12183 typedef struct ShellState ShellState;
12184 struct ShellState {
12185   sqlite3 *db;           /* The database */
12186   u8 autoExplain;        /* Automatically turn on .explain mode */
12187   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
12188   u8 autoEQPtest;        /* autoEQP is in test mode */
12189   u8 autoEQPtrace;       /* autoEQP is in trace mode */
12190   u8 scanstatsOn;        /* True to display scan stats before each finalize */
12191   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
12192   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
12193   u8 nEqpLevel;          /* Depth of the EQP output graph */
12194   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
12195   u8 bSafeMode;          /* True to prohibit unsafe operations */
12196   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
12197   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
12198   unsigned statsOn;      /* True to display memory stats before each finalize */
12199   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
12200   int inputNesting;      /* Track nesting level of .read and other redirects */
12201   int outCount;          /* Revert to stdout when reaching zero */
12202   int cnt;               /* Number of records displayed so far */
12203   int lineno;            /* Line number of last line read from in */
12204   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
12205   FILE *in;              /* Read commands from this stream */
12206   FILE *out;             /* Write results here */
12207   FILE *traceOut;        /* Output for sqlite3_trace() */
12208   int nErr;              /* Number of errors seen */
12209   int mode;              /* An output mode setting */
12210   int modePrior;         /* Saved mode */
12211   int cMode;             /* temporary output mode for the current query */
12212   int normalMode;        /* Output mode before ".explain on" */
12213   int writableSchema;    /* True if PRAGMA writable_schema=ON */
12214   int showHeader;        /* True to show column names in List or Column mode */
12215   int nCheck;            /* Number of ".check" commands run */
12216   unsigned nProgress;    /* Number of progress callbacks encountered */
12217   unsigned mxProgress;   /* Maximum progress callbacks before failing */
12218   unsigned flgProgress;  /* Flags for the progress callback */
12219   unsigned shellFlgs;    /* Various flags */
12220   unsigned priorShFlgs;  /* Saved copy of flags */
12221   sqlite3_int64 szMax;   /* --maxsize argument to .open */
12222   char *zDestTable;      /* Name of destination table when MODE_Insert */
12223   char *zTempFile;       /* Temporary file that might need deleting */
12224   char zTestcase[30];    /* Name of current test case */
12225   char colSeparator[20]; /* Column separator character for several modes */
12226   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
12227   char colSepPrior[20];  /* Saved column separator */
12228   char rowSepPrior[20];  /* Saved row separator */
12229   int *colWidth;         /* Requested width of each column in columnar modes */
12230   int *actualWidth;      /* Actual width of each column */
12231   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
12232   char nullValue[20];    /* The text to print when a NULL comes back from
12233                          ** the database */
12234   char outfile[FILENAME_MAX]; /* Filename for *out */
12235   sqlite3_stmt *pStmt;   /* Current statement if any. */
12236   FILE *pLog;            /* Write log output here */
12237   struct AuxDb {         /* Storage space for auxiliary database connections */
12238     sqlite3 *db;               /* Connection pointer */
12239     const char *zDbFilename;   /* Filename used to open the connection */
12240     char *zFreeOnClose;        /* Free this memory allocation on close */
12241 #if defined(SQLITE_ENABLE_SESSION)
12242     int nSession;              /* Number of active sessions */
12243     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
12244 #endif
12245   } aAuxDb[5],           /* Array of all database connections */
12246     *pAuxDb;             /* Currently active database connection */
12247   int *aiIndent;         /* Array of indents used in MODE_Explain */
12248   int nIndent;           /* Size of array aiIndent[] */
12249   int iIndent;           /* Index of current op in aiIndent[] */
12250   char *zNonce;          /* Nonce for temporary safe-mode excapes */
12251   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
12252   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
12253 #ifdef SQLITE_SHELL_WASM_MODE
12254   struct {
12255     const char * zInput; /* Input string from wasm/JS proxy */
12256     const char * zPos;   /* Cursor pos into zInput */
12257   } wasm;
12258 #endif
12259 };
12260 
12261 #ifdef SQLITE_SHELL_WASM_MODE
12262 static ShellState shellState;
12263 #endif
12264 
12265 
12266 /* Allowed values for ShellState.autoEQP
12267 */
12268 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
12269 #define AUTOEQP_on       1           /* Automatic EQP is on */
12270 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
12271 #define AUTOEQP_full     3           /* Show full EXPLAIN */
12272 
12273 /* Allowed values for ShellState.openMode
12274 */
12275 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
12276 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
12277 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
12278 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
12279 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
12280 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
12281 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
12282 
12283 /* Allowed values for ShellState.eTraceType
12284 */
12285 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
12286 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
12287 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
12288 
12289 /* Bits in the ShellState.flgProgress variable */
12290 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
12291 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
12292                                    ** callback limit is reached, and for each
12293                                    ** top-level SQL statement */
12294 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
12295 
12296 /*
12297 ** These are the allowed shellFlgs values
12298 */
12299 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
12300 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
12301 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
12302 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
12303 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
12304 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
12305 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
12306 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
12307 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
12308 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
12309 
12310 /*
12311 ** Macros for testing and setting shellFlgs
12312 */
12313 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
12314 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
12315 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
12316 
12317 /*
12318 ** These are the allowed modes.
12319 */
12320 #define MODE_Line     0  /* One column per line.  Blank line between records */
12321 #define MODE_Column   1  /* One record per line in neat columns */
12322 #define MODE_List     2  /* One record per line with a separator */
12323 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
12324 #define MODE_Html     4  /* Generate an XHTML table */
12325 #define MODE_Insert   5  /* Generate SQL "insert" statements */
12326 #define MODE_Quote    6  /* Quote values as for SQL */
12327 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
12328 #define MODE_Csv      8  /* Quote strings, numbers are plain */
12329 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
12330 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
12331 #define MODE_Pretty  11  /* Pretty-print schemas */
12332 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
12333 #define MODE_Json    13  /* Output JSON */
12334 #define MODE_Markdown 14 /* Markdown formatting */
12335 #define MODE_Table   15  /* MySQL-style table formatting */
12336 #define MODE_Box     16  /* Unicode box-drawing characters */
12337 #define MODE_Count   17  /* Output only a count of the rows of output */
12338 #define MODE_Off     18  /* No query output shown */
12339 
12340 static const char *modeDescr[] = {
12341   "line",
12342   "column",
12343   "list",
12344   "semi",
12345   "html",
12346   "insert",
12347   "quote",
12348   "tcl",
12349   "csv",
12350   "explain",
12351   "ascii",
12352   "prettyprint",
12353   "eqp",
12354   "json",
12355   "markdown",
12356   "table",
12357   "box",
12358   "count",
12359   "off"
12360 };
12361 
12362 /*
12363 ** These are the column/row/line separators used by the various
12364 ** import/export modes.
12365 */
12366 #define SEP_Column    "|"
12367 #define SEP_Row       "\n"
12368 #define SEP_Tab       "\t"
12369 #define SEP_Space     " "
12370 #define SEP_Comma     ","
12371 #define SEP_CrLf      "\r\n"
12372 #define SEP_Unit      "\x1F"
12373 #define SEP_Record    "\x1E"
12374 
12375 /*
12376 ** Limit input nesting via .read or any other input redirect.
12377 ** It's not too expensive, so a generous allowance can be made.
12378 */
12379 #define MAX_INPUT_NESTING 25
12380 
12381 /*
12382 ** A callback for the sqlite3_log() interface.
12383 */
12384 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
12385   ShellState *p = (ShellState*)pArg;
12386   if( p->pLog==0 ) return;
12387   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
12388   fflush(p->pLog);
12389 }
12390 
12391 /*
12392 ** SQL function:  shell_putsnl(X)
12393 **
12394 ** Write the text X to the screen (or whatever output is being directed)
12395 ** adding a newline at the end, and then return X.
12396 */
12397 static void shellPutsFunc(
12398   sqlite3_context *pCtx,
12399   int nVal,
12400   sqlite3_value **apVal
12401 ){
12402   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
12403   (void)nVal;
12404   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
12405   sqlite3_result_value(pCtx, apVal[0]);
12406 }
12407 
12408 /*
12409 ** If in safe mode, print an error message described by the arguments
12410 ** and exit immediately.
12411 */
12412 static void failIfSafeMode(
12413   ShellState *p,
12414   const char *zErrMsg,
12415   ...
12416 ){
12417   if( p->bSafeMode ){
12418     va_list ap;
12419     char *zMsg;
12420     va_start(ap, zErrMsg);
12421     zMsg = sqlite3_vmprintf(zErrMsg, ap);
12422     va_end(ap);
12423     raw_printf(stderr, "line %d: ", p->lineno);
12424     utf8_printf(stderr, "%s\n", zMsg);
12425     exit(1);
12426   }
12427 }
12428 
12429 /*
12430 ** SQL function:   edit(VALUE)
12431 **                 edit(VALUE,EDITOR)
12432 **
12433 ** These steps:
12434 **
12435 **     (1) Write VALUE into a temporary file.
12436 **     (2) Run program EDITOR on that temporary file.
12437 **     (3) Read the temporary file back and return its content as the result.
12438 **     (4) Delete the temporary file
12439 **
12440 ** If the EDITOR argument is omitted, use the value in the VISUAL
12441 ** environment variable.  If still there is no EDITOR, through an error.
12442 **
12443 ** Also throw an error if the EDITOR program returns a non-zero exit code.
12444 */
12445 #ifndef SQLITE_NOHAVE_SYSTEM
12446 static void editFunc(
12447   sqlite3_context *context,
12448   int argc,
12449   sqlite3_value **argv
12450 ){
12451   const char *zEditor;
12452   char *zTempFile = 0;
12453   sqlite3 *db;
12454   char *zCmd = 0;
12455   int bBin;
12456   int rc;
12457   int hasCRNL = 0;
12458   FILE *f = 0;
12459   sqlite3_int64 sz;
12460   sqlite3_int64 x;
12461   unsigned char *p = 0;
12462 
12463   if( argc==2 ){
12464     zEditor = (const char*)sqlite3_value_text(argv[1]);
12465   }else{
12466     zEditor = getenv("VISUAL");
12467   }
12468   if( zEditor==0 ){
12469     sqlite3_result_error(context, "no editor for edit()", -1);
12470     return;
12471   }
12472   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
12473     sqlite3_result_error(context, "NULL input to edit()", -1);
12474     return;
12475   }
12476   db = sqlite3_context_db_handle(context);
12477   zTempFile = 0;
12478   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
12479   if( zTempFile==0 ){
12480     sqlite3_uint64 r = 0;
12481     sqlite3_randomness(sizeof(r), &r);
12482     zTempFile = sqlite3_mprintf("temp%llx", r);
12483     if( zTempFile==0 ){
12484       sqlite3_result_error_nomem(context);
12485       return;
12486     }
12487   }
12488   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
12489   /* When writing the file to be edited, do \n to \r\n conversions on systems
12490   ** that want \r\n line endings */
12491   f = fopen(zTempFile, bBin ? "wb" : "w");
12492   if( f==0 ){
12493     sqlite3_result_error(context, "edit() cannot open temp file", -1);
12494     goto edit_func_end;
12495   }
12496   sz = sqlite3_value_bytes(argv[0]);
12497   if( bBin ){
12498     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
12499   }else{
12500     const char *z = (const char*)sqlite3_value_text(argv[0]);
12501     /* Remember whether or not the value originally contained \r\n */
12502     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
12503     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
12504   }
12505   fclose(f);
12506   f = 0;
12507   if( x!=sz ){
12508     sqlite3_result_error(context, "edit() could not write the whole file", -1);
12509     goto edit_func_end;
12510   }
12511   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
12512   if( zCmd==0 ){
12513     sqlite3_result_error_nomem(context);
12514     goto edit_func_end;
12515   }
12516   rc = system(zCmd);
12517   sqlite3_free(zCmd);
12518   if( rc ){
12519     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
12520     goto edit_func_end;
12521   }
12522   f = fopen(zTempFile, "rb");
12523   if( f==0 ){
12524     sqlite3_result_error(context,
12525       "edit() cannot reopen temp file after edit", -1);
12526     goto edit_func_end;
12527   }
12528   fseek(f, 0, SEEK_END);
12529   sz = ftell(f);
12530   rewind(f);
12531   p = sqlite3_malloc64( sz+1 );
12532   if( p==0 ){
12533     sqlite3_result_error_nomem(context);
12534     goto edit_func_end;
12535   }
12536   x = fread(p, 1, (size_t)sz, f);
12537   fclose(f);
12538   f = 0;
12539   if( x!=sz ){
12540     sqlite3_result_error(context, "could not read back the whole file", -1);
12541     goto edit_func_end;
12542   }
12543   if( bBin ){
12544     sqlite3_result_blob64(context, p, sz, sqlite3_free);
12545   }else{
12546     sqlite3_int64 i, j;
12547     if( hasCRNL ){
12548       /* If the original contains \r\n then do no conversions back to \n */
12549     }else{
12550       /* If the file did not originally contain \r\n then convert any new
12551       ** \r\n back into \n */
12552       for(i=j=0; i<sz; i++){
12553         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
12554         p[j++] = p[i];
12555       }
12556       sz = j;
12557       p[sz] = 0;
12558     }
12559     sqlite3_result_text64(context, (const char*)p, sz,
12560                           sqlite3_free, SQLITE_UTF8);
12561   }
12562   p = 0;
12563 
12564 edit_func_end:
12565   if( f ) fclose(f);
12566   unlink(zTempFile);
12567   sqlite3_free(zTempFile);
12568   sqlite3_free(p);
12569 }
12570 #endif /* SQLITE_NOHAVE_SYSTEM */
12571 
12572 /*
12573 ** Save or restore the current output mode
12574 */
12575 static void outputModePush(ShellState *p){
12576   p->modePrior = p->mode;
12577   p->priorShFlgs = p->shellFlgs;
12578   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
12579   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
12580 }
12581 static void outputModePop(ShellState *p){
12582   p->mode = p->modePrior;
12583   p->shellFlgs = p->priorShFlgs;
12584   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
12585   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
12586 }
12587 
12588 /*
12589 ** Output the given string as a hex-encoded blob (eg. X'1234' )
12590 */
12591 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
12592   int i;
12593   char *zBlob = (char *)pBlob;
12594   raw_printf(out,"X'");
12595   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
12596   raw_printf(out,"'");
12597 }
12598 
12599 /*
12600 ** Find a string that is not found anywhere in z[].  Return a pointer
12601 ** to that string.
12602 **
12603 ** Try to use zA and zB first.  If both of those are already found in z[]
12604 ** then make up some string and store it in the buffer zBuf.
12605 */
12606 static const char *unused_string(
12607   const char *z,                    /* Result must not appear anywhere in z */
12608   const char *zA, const char *zB,   /* Try these first */
12609   char *zBuf                        /* Space to store a generated string */
12610 ){
12611   unsigned i = 0;
12612   if( strstr(z, zA)==0 ) return zA;
12613   if( strstr(z, zB)==0 ) return zB;
12614   do{
12615     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
12616   }while( strstr(z,zBuf)!=0 );
12617   return zBuf;
12618 }
12619 
12620 /*
12621 ** Output the given string as a quoted string using SQL quoting conventions.
12622 **
12623 ** See also: output_quoted_escaped_string()
12624 */
12625 static void output_quoted_string(FILE *out, const char *z){
12626   int i;
12627   char c;
12628   setBinaryMode(out, 1);
12629   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
12630   if( c==0 ){
12631     utf8_printf(out,"'%s'",z);
12632   }else{
12633     raw_printf(out, "'");
12634     while( *z ){
12635       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
12636       if( c=='\'' ) i++;
12637       if( i ){
12638         utf8_printf(out, "%.*s", i, z);
12639         z += i;
12640       }
12641       if( c=='\'' ){
12642         raw_printf(out, "'");
12643         continue;
12644       }
12645       if( c==0 ){
12646         break;
12647       }
12648       z++;
12649     }
12650     raw_printf(out, "'");
12651   }
12652   setTextMode(out, 1);
12653 }
12654 
12655 /*
12656 ** Output the given string as a quoted string using SQL quoting conventions.
12657 ** Additionallly , escape the "\n" and "\r" characters so that they do not
12658 ** get corrupted by end-of-line translation facilities in some operating
12659 ** systems.
12660 **
12661 ** This is like output_quoted_string() but with the addition of the \r\n
12662 ** escape mechanism.
12663 */
12664 static void output_quoted_escaped_string(FILE *out, const char *z){
12665   int i;
12666   char c;
12667   setBinaryMode(out, 1);
12668   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
12669   if( c==0 ){
12670     utf8_printf(out,"'%s'",z);
12671   }else{
12672     const char *zNL = 0;
12673     const char *zCR = 0;
12674     int nNL = 0;
12675     int nCR = 0;
12676     char zBuf1[20], zBuf2[20];
12677     for(i=0; z[i]; i++){
12678       if( z[i]=='\n' ) nNL++;
12679       if( z[i]=='\r' ) nCR++;
12680     }
12681     if( nNL ){
12682       raw_printf(out, "replace(");
12683       zNL = unused_string(z, "\\n", "\\012", zBuf1);
12684     }
12685     if( nCR ){
12686       raw_printf(out, "replace(");
12687       zCR = unused_string(z, "\\r", "\\015", zBuf2);
12688     }
12689     raw_printf(out, "'");
12690     while( *z ){
12691       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
12692       if( c=='\'' ) i++;
12693       if( i ){
12694         utf8_printf(out, "%.*s", i, z);
12695         z += i;
12696       }
12697       if( c=='\'' ){
12698         raw_printf(out, "'");
12699         continue;
12700       }
12701       if( c==0 ){
12702         break;
12703       }
12704       z++;
12705       if( c=='\n' ){
12706         raw_printf(out, "%s", zNL);
12707         continue;
12708       }
12709       raw_printf(out, "%s", zCR);
12710     }
12711     raw_printf(out, "'");
12712     if( nCR ){
12713       raw_printf(out, ",'%s',char(13))", zCR);
12714     }
12715     if( nNL ){
12716       raw_printf(out, ",'%s',char(10))", zNL);
12717     }
12718   }
12719   setTextMode(out, 1);
12720 }
12721 
12722 /*
12723 ** Output the given string as a quoted according to C or TCL quoting rules.
12724 */
12725 static void output_c_string(FILE *out, const char *z){
12726   unsigned int c;
12727   fputc('"', out);
12728   while( (c = *(z++))!=0 ){
12729     if( c=='\\' ){
12730       fputc(c, out);
12731       fputc(c, out);
12732     }else if( c=='"' ){
12733       fputc('\\', out);
12734       fputc('"', out);
12735     }else if( c=='\t' ){
12736       fputc('\\', out);
12737       fputc('t', out);
12738     }else if( c=='\n' ){
12739       fputc('\\', out);
12740       fputc('n', out);
12741     }else if( c=='\r' ){
12742       fputc('\\', out);
12743       fputc('r', out);
12744     }else if( !isprint(c&0xff) ){
12745       raw_printf(out, "\\%03o", c&0xff);
12746     }else{
12747       fputc(c, out);
12748     }
12749   }
12750   fputc('"', out);
12751 }
12752 
12753 /*
12754 ** Output the given string as a quoted according to JSON quoting rules.
12755 */
12756 static void output_json_string(FILE *out, const char *z, int n){
12757   unsigned int c;
12758   if( n<0 ) n = (int)strlen(z);
12759   fputc('"', out);
12760   while( n-- ){
12761     c = *(z++);
12762     if( c=='\\' || c=='"' ){
12763       fputc('\\', out);
12764       fputc(c, out);
12765     }else if( c<=0x1f ){
12766       fputc('\\', out);
12767       if( c=='\b' ){
12768         fputc('b', out);
12769       }else if( c=='\f' ){
12770         fputc('f', out);
12771       }else if( c=='\n' ){
12772         fputc('n', out);
12773       }else if( c=='\r' ){
12774         fputc('r', out);
12775       }else if( c=='\t' ){
12776         fputc('t', out);
12777       }else{
12778          raw_printf(out, "u%04x",c);
12779       }
12780     }else{
12781       fputc(c, out);
12782     }
12783   }
12784   fputc('"', out);
12785 }
12786 
12787 /*
12788 ** Output the given string with characters that are special to
12789 ** HTML escaped.
12790 */
12791 static void output_html_string(FILE *out, const char *z){
12792   int i;
12793   if( z==0 ) z = "";
12794   while( *z ){
12795     for(i=0;   z[i]
12796             && z[i]!='<'
12797             && z[i]!='&'
12798             && z[i]!='>'
12799             && z[i]!='\"'
12800             && z[i]!='\'';
12801         i++){}
12802     if( i>0 ){
12803       utf8_printf(out,"%.*s",i,z);
12804     }
12805     if( z[i]=='<' ){
12806       raw_printf(out,"&lt;");
12807     }else if( z[i]=='&' ){
12808       raw_printf(out,"&amp;");
12809     }else if( z[i]=='>' ){
12810       raw_printf(out,"&gt;");
12811     }else if( z[i]=='\"' ){
12812       raw_printf(out,"&quot;");
12813     }else if( z[i]=='\'' ){
12814       raw_printf(out,"&#39;");
12815     }else{
12816       break;
12817     }
12818     z += i + 1;
12819   }
12820 }
12821 
12822 /*
12823 ** If a field contains any character identified by a 1 in the following
12824 ** array, then the string must be quoted for CSV.
12825 */
12826 static const char needCsvQuote[] = {
12827   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12828   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12829   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
12830   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12831   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12832   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12833   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
12834   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
12835   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12836   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12837   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12838   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12839   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12840   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12841   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12842   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
12843 };
12844 
12845 /*
12846 ** Output a single term of CSV.  Actually, p->colSeparator is used for
12847 ** the separator, which may or may not be a comma.  p->nullValue is
12848 ** the null value.  Strings are quoted if necessary.  The separator
12849 ** is only issued if bSep is true.
12850 */
12851 static void output_csv(ShellState *p, const char *z, int bSep){
12852   FILE *out = p->out;
12853   if( z==0 ){
12854     utf8_printf(out,"%s",p->nullValue);
12855   }else{
12856     unsigned i;
12857     for(i=0; z[i]; i++){
12858       if( needCsvQuote[((unsigned char*)z)[i]] ){
12859         i = 0;
12860         break;
12861       }
12862     }
12863     if( i==0 || strstr(z, p->colSeparator)!=0 ){
12864       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
12865       shell_check_oom(zQuoted);
12866       utf8_printf(out, "%s", zQuoted);
12867       sqlite3_free(zQuoted);
12868     }else{
12869       utf8_printf(out, "%s", z);
12870     }
12871   }
12872   if( bSep ){
12873     utf8_printf(p->out, "%s", p->colSeparator);
12874   }
12875 }
12876 
12877 /*
12878 ** This routine runs when the user presses Ctrl-C
12879 */
12880 static void interrupt_handler(int NotUsed){
12881   UNUSED_PARAMETER(NotUsed);
12882   seenInterrupt++;
12883   if( seenInterrupt>2 ) exit(1);
12884   if( globalDb ) sqlite3_interrupt(globalDb);
12885 }
12886 
12887 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12888 /*
12889 ** This routine runs for console events (e.g. Ctrl-C) on Win32
12890 */
12891 static BOOL WINAPI ConsoleCtrlHandler(
12892   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
12893 ){
12894   if( dwCtrlType==CTRL_C_EVENT ){
12895     interrupt_handler(0);
12896     return TRUE;
12897   }
12898   return FALSE;
12899 }
12900 #endif
12901 
12902 #ifndef SQLITE_OMIT_AUTHORIZATION
12903 /*
12904 ** This authorizer runs in safe mode.
12905 */
12906 static int safeModeAuth(
12907   void *pClientData,
12908   int op,
12909   const char *zA1,
12910   const char *zA2,
12911   const char *zA3,
12912   const char *zA4
12913 ){
12914   ShellState *p = (ShellState*)pClientData;
12915   static const char *azProhibitedFunctions[] = {
12916     "edit",
12917     "fts3_tokenizer",
12918     "load_extension",
12919     "readfile",
12920     "writefile",
12921     "zipfile",
12922     "zipfile_cds",
12923   };
12924   UNUSED_PARAMETER(zA2);
12925   UNUSED_PARAMETER(zA3);
12926   UNUSED_PARAMETER(zA4);
12927   switch( op ){
12928     case SQLITE_ATTACH: {
12929 #ifndef SQLITE_SHELL_WASM_MODE
12930       /* In WASM builds the filesystem is a virtual sandbox, so
12931       ** there's no harm in using ATTACH. */
12932       failIfSafeMode(p, "cannot run ATTACH in safe mode");
12933 #endif
12934       break;
12935     }
12936     case SQLITE_FUNCTION: {
12937       int i;
12938       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
12939         if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
12940           failIfSafeMode(p, "cannot use the %s() function in safe mode",
12941                          azProhibitedFunctions[i]);
12942         }
12943       }
12944       break;
12945     }
12946   }
12947   return SQLITE_OK;
12948 }
12949 
12950 /*
12951 ** When the ".auth ON" is set, the following authorizer callback is
12952 ** invoked.  It always returns SQLITE_OK.
12953 */
12954 static int shellAuth(
12955   void *pClientData,
12956   int op,
12957   const char *zA1,
12958   const char *zA2,
12959   const char *zA3,
12960   const char *zA4
12961 ){
12962   ShellState *p = (ShellState*)pClientData;
12963   static const char *azAction[] = { 0,
12964      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
12965      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
12966      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
12967      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
12968      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
12969      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
12970      "PRAGMA",               "READ",                 "SELECT",
12971      "TRANSACTION",          "UPDATE",               "ATTACH",
12972      "DETACH",               "ALTER_TABLE",          "REINDEX",
12973      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
12974      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
12975   };
12976   int i;
12977   const char *az[4];
12978   az[0] = zA1;
12979   az[1] = zA2;
12980   az[2] = zA3;
12981   az[3] = zA4;
12982   utf8_printf(p->out, "authorizer: %s", azAction[op]);
12983   for(i=0; i<4; i++){
12984     raw_printf(p->out, " ");
12985     if( az[i] ){
12986       output_c_string(p->out, az[i]);
12987     }else{
12988       raw_printf(p->out, "NULL");
12989     }
12990   }
12991   raw_printf(p->out, "\n");
12992   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
12993   return SQLITE_OK;
12994 }
12995 #endif
12996 
12997 /*
12998 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
12999 **
13000 ** This routine converts some CREATE TABLE statements for shadow tables
13001 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
13002 */
13003 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
13004   if( z==0 ) return;
13005   if( zTail==0 ) return;
13006   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
13007     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
13008   }else{
13009     utf8_printf(out, "%s%s", z, zTail);
13010   }
13011 }
13012 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
13013   char c = z[n];
13014   z[n] = 0;
13015   printSchemaLine(out, z, zTail);
13016   z[n] = c;
13017 }
13018 
13019 /*
13020 ** Return true if string z[] has nothing but whitespace and comments to the
13021 ** end of the first line.
13022 */
13023 static int wsToEol(const char *z){
13024   int i;
13025   for(i=0; z[i]; i++){
13026     if( z[i]=='\n' ) return 1;
13027     if( IsSpace(z[i]) ) continue;
13028     if( z[i]=='-' && z[i+1]=='-' ) return 1;
13029     return 0;
13030   }
13031   return 1;
13032 }
13033 
13034 /*
13035 ** Add a new entry to the EXPLAIN QUERY PLAN data
13036 */
13037 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
13038   EQPGraphRow *pNew;
13039   int nText = strlen30(zText);
13040   if( p->autoEQPtest ){
13041     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
13042   }
13043   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
13044   shell_check_oom(pNew);
13045   pNew->iEqpId = iEqpId;
13046   pNew->iParentId = p2;
13047   memcpy(pNew->zText, zText, nText+1);
13048   pNew->pNext = 0;
13049   if( p->sGraph.pLast ){
13050     p->sGraph.pLast->pNext = pNew;
13051   }else{
13052     p->sGraph.pRow = pNew;
13053   }
13054   p->sGraph.pLast = pNew;
13055 }
13056 
13057 /*
13058 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
13059 ** in p->sGraph.
13060 */
13061 static void eqp_reset(ShellState *p){
13062   EQPGraphRow *pRow, *pNext;
13063   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
13064     pNext = pRow->pNext;
13065     sqlite3_free(pRow);
13066   }
13067   memset(&p->sGraph, 0, sizeof(p->sGraph));
13068 }
13069 
13070 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
13071 ** pOld, or return the first such line if pOld is NULL
13072 */
13073 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
13074   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
13075   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
13076   return pRow;
13077 }
13078 
13079 /* Render a single level of the graph that has iEqpId as its parent.  Called
13080 ** recursively to render sublevels.
13081 */
13082 static void eqp_render_level(ShellState *p, int iEqpId){
13083   EQPGraphRow *pRow, *pNext;
13084   int n = strlen30(p->sGraph.zPrefix);
13085   char *z;
13086   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
13087     pNext = eqp_next_row(p, iEqpId, pRow);
13088     z = pRow->zText;
13089     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
13090                 pNext ? "|--" : "`--", z);
13091     if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
13092       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
13093       eqp_render_level(p, pRow->iEqpId);
13094       p->sGraph.zPrefix[n] = 0;
13095     }
13096   }
13097 }
13098 
13099 /*
13100 ** Display and reset the EXPLAIN QUERY PLAN data
13101 */
13102 static void eqp_render(ShellState *p){
13103   EQPGraphRow *pRow = p->sGraph.pRow;
13104   if( pRow ){
13105     if( pRow->zText[0]=='-' ){
13106       if( pRow->pNext==0 ){
13107         eqp_reset(p);
13108         return;
13109       }
13110       utf8_printf(p->out, "%s\n", pRow->zText+3);
13111       p->sGraph.pRow = pRow->pNext;
13112       sqlite3_free(pRow);
13113     }else{
13114       utf8_printf(p->out, "QUERY PLAN\n");
13115     }
13116     p->sGraph.zPrefix[0] = 0;
13117     eqp_render_level(p, 0);
13118     eqp_reset(p);
13119   }
13120 }
13121 
13122 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
13123 /*
13124 ** Progress handler callback.
13125 */
13126 static int progress_handler(void *pClientData) {
13127   ShellState *p = (ShellState*)pClientData;
13128   p->nProgress++;
13129   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
13130     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
13131     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
13132     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
13133     return 1;
13134   }
13135   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
13136     raw_printf(p->out, "Progress %u\n", p->nProgress);
13137   }
13138   return 0;
13139 }
13140 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
13141 
13142 /*
13143 ** Print N dashes
13144 */
13145 static void print_dashes(FILE *out, int N){
13146   const char zDash[] = "--------------------------------------------------";
13147   const int nDash = sizeof(zDash) - 1;
13148   while( N>nDash ){
13149     fputs(zDash, out);
13150     N -= nDash;
13151   }
13152   raw_printf(out, "%.*s", N, zDash);
13153 }
13154 
13155 /*
13156 ** Print a markdown or table-style row separator using ascii-art
13157 */
13158 static void print_row_separator(
13159   ShellState *p,
13160   int nArg,
13161   const char *zSep
13162 ){
13163   int i;
13164   if( nArg>0 ){
13165     fputs(zSep, p->out);
13166     print_dashes(p->out, p->actualWidth[0]+2);
13167     for(i=1; i<nArg; i++){
13168       fputs(zSep, p->out);
13169       print_dashes(p->out, p->actualWidth[i]+2);
13170     }
13171     fputs(zSep, p->out);
13172   }
13173   fputs("\n", p->out);
13174 }
13175 
13176 /*
13177 ** This is the callback routine that the shell
13178 ** invokes for each row of a query result.
13179 */
13180 static int shell_callback(
13181   void *pArg,
13182   int nArg,        /* Number of result columns */
13183   char **azArg,    /* Text of each result column */
13184   char **azCol,    /* Column names */
13185   int *aiType      /* Column types.  Might be NULL */
13186 ){
13187   int i;
13188   ShellState *p = (ShellState*)pArg;
13189 
13190   if( azArg==0 ) return 0;
13191   switch( p->cMode ){
13192     case MODE_Count:
13193     case MODE_Off: {
13194       break;
13195     }
13196     case MODE_Line: {
13197       int w = 5;
13198       if( azArg==0 ) break;
13199       for(i=0; i<nArg; i++){
13200         int len = strlen30(azCol[i] ? azCol[i] : "");
13201         if( len>w ) w = len;
13202       }
13203       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
13204       for(i=0; i<nArg; i++){
13205         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
13206                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
13207       }
13208       break;
13209     }
13210     case MODE_Explain: {
13211       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
13212       if( nArg>ArraySize(aExplainWidth) ){
13213         nArg = ArraySize(aExplainWidth);
13214       }
13215       if( p->cnt++==0 ){
13216         for(i=0; i<nArg; i++){
13217           int w = aExplainWidth[i];
13218           utf8_width_print(p->out, w, azCol[i]);
13219           fputs(i==nArg-1 ? "\n" : "  ", p->out);
13220         }
13221         for(i=0; i<nArg; i++){
13222           int w = aExplainWidth[i];
13223           print_dashes(p->out, w);
13224           fputs(i==nArg-1 ? "\n" : "  ", p->out);
13225         }
13226       }
13227       if( azArg==0 ) break;
13228       for(i=0; i<nArg; i++){
13229         int w = aExplainWidth[i];
13230         if( i==nArg-1 ) w = 0;
13231         if( azArg[i] && strlenChar(azArg[i])>w ){
13232           w = strlenChar(azArg[i]);
13233         }
13234         if( i==1 && p->aiIndent && p->pStmt ){
13235           if( p->iIndent<p->nIndent ){
13236             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
13237           }
13238           p->iIndent++;
13239         }
13240         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
13241         fputs(i==nArg-1 ? "\n" : "  ", p->out);
13242       }
13243       break;
13244     }
13245     case MODE_Semi: {   /* .schema and .fullschema output */
13246       printSchemaLine(p->out, azArg[0], ";\n");
13247       break;
13248     }
13249     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
13250       char *z;
13251       int j;
13252       int nParen = 0;
13253       char cEnd = 0;
13254       char c;
13255       int nLine = 0;
13256       assert( nArg==1 );
13257       if( azArg[0]==0 ) break;
13258       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
13259        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
13260       ){
13261         utf8_printf(p->out, "%s;\n", azArg[0]);
13262         break;
13263       }
13264       z = sqlite3_mprintf("%s", azArg[0]);
13265       shell_check_oom(z);
13266       j = 0;
13267       for(i=0; IsSpace(z[i]); i++){}
13268       for(; (c = z[i])!=0; i++){
13269         if( IsSpace(c) ){
13270           if( z[j-1]=='\r' ) z[j-1] = '\n';
13271           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
13272         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
13273           j--;
13274         }
13275         z[j++] = c;
13276       }
13277       while( j>0 && IsSpace(z[j-1]) ){ j--; }
13278       z[j] = 0;
13279       if( strlen30(z)>=79 ){
13280         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
13281           if( c==cEnd ){
13282             cEnd = 0;
13283           }else if( c=='"' || c=='\'' || c=='`' ){
13284             cEnd = c;
13285           }else if( c=='[' ){
13286             cEnd = ']';
13287           }else if( c=='-' && z[i+1]=='-' ){
13288             cEnd = '\n';
13289           }else if( c=='(' ){
13290             nParen++;
13291           }else if( c==')' ){
13292             nParen--;
13293             if( nLine>0 && nParen==0 && j>0 ){
13294               printSchemaLineN(p->out, z, j, "\n");
13295               j = 0;
13296             }
13297           }
13298           z[j++] = c;
13299           if( nParen==1 && cEnd==0
13300            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
13301           ){
13302             if( c=='\n' ) j--;
13303             printSchemaLineN(p->out, z, j, "\n  ");
13304             j = 0;
13305             nLine++;
13306             while( IsSpace(z[i+1]) ){ i++; }
13307           }
13308         }
13309         z[j] = 0;
13310       }
13311       printSchemaLine(p->out, z, ";\n");
13312       sqlite3_free(z);
13313       break;
13314     }
13315     case MODE_List: {
13316       if( p->cnt++==0 && p->showHeader ){
13317         for(i=0; i<nArg; i++){
13318           utf8_printf(p->out,"%s%s",azCol[i],
13319                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
13320         }
13321       }
13322       if( azArg==0 ) break;
13323       for(i=0; i<nArg; i++){
13324         char *z = azArg[i];
13325         if( z==0 ) z = p->nullValue;
13326         utf8_printf(p->out, "%s", z);
13327         if( i<nArg-1 ){
13328           utf8_printf(p->out, "%s", p->colSeparator);
13329         }else{
13330           utf8_printf(p->out, "%s", p->rowSeparator);
13331         }
13332       }
13333       break;
13334     }
13335     case MODE_Html: {
13336       if( p->cnt++==0 && p->showHeader ){
13337         raw_printf(p->out,"<TR>");
13338         for(i=0; i<nArg; i++){
13339           raw_printf(p->out,"<TH>");
13340           output_html_string(p->out, azCol[i]);
13341           raw_printf(p->out,"</TH>\n");
13342         }
13343         raw_printf(p->out,"</TR>\n");
13344       }
13345       if( azArg==0 ) break;
13346       raw_printf(p->out,"<TR>");
13347       for(i=0; i<nArg; i++){
13348         raw_printf(p->out,"<TD>");
13349         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
13350         raw_printf(p->out,"</TD>\n");
13351       }
13352       raw_printf(p->out,"</TR>\n");
13353       break;
13354     }
13355     case MODE_Tcl: {
13356       if( p->cnt++==0 && p->showHeader ){
13357         for(i=0; i<nArg; i++){
13358           output_c_string(p->out,azCol[i] ? azCol[i] : "");
13359           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
13360         }
13361         utf8_printf(p->out, "%s", p->rowSeparator);
13362       }
13363       if( azArg==0 ) break;
13364       for(i=0; i<nArg; i++){
13365         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
13366         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
13367       }
13368       utf8_printf(p->out, "%s", p->rowSeparator);
13369       break;
13370     }
13371     case MODE_Csv: {
13372       setBinaryMode(p->out, 1);
13373       if( p->cnt++==0 && p->showHeader ){
13374         for(i=0; i<nArg; i++){
13375           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
13376         }
13377         utf8_printf(p->out, "%s", p->rowSeparator);
13378       }
13379       if( nArg>0 ){
13380         for(i=0; i<nArg; i++){
13381           output_csv(p, azArg[i], i<nArg-1);
13382         }
13383         utf8_printf(p->out, "%s", p->rowSeparator);
13384       }
13385       setTextMode(p->out, 1);
13386       break;
13387     }
13388     case MODE_Insert: {
13389       if( azArg==0 ) break;
13390       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
13391       if( p->showHeader ){
13392         raw_printf(p->out,"(");
13393         for(i=0; i<nArg; i++){
13394           if( i>0 ) raw_printf(p->out, ",");
13395           if( quoteChar(azCol[i]) ){
13396             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
13397             shell_check_oom(z);
13398             utf8_printf(p->out, "%s", z);
13399             sqlite3_free(z);
13400           }else{
13401             raw_printf(p->out, "%s", azCol[i]);
13402           }
13403         }
13404         raw_printf(p->out,")");
13405       }
13406       p->cnt++;
13407       for(i=0; i<nArg; i++){
13408         raw_printf(p->out, i>0 ? "," : " VALUES(");
13409         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
13410           utf8_printf(p->out,"NULL");
13411         }else if( aiType && aiType[i]==SQLITE_TEXT ){
13412           if( ShellHasFlag(p, SHFLG_Newlines) ){
13413             output_quoted_string(p->out, azArg[i]);
13414           }else{
13415             output_quoted_escaped_string(p->out, azArg[i]);
13416           }
13417         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
13418           utf8_printf(p->out,"%s", azArg[i]);
13419         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
13420           char z[50];
13421           double r = sqlite3_column_double(p->pStmt, i);
13422           sqlite3_uint64 ur;
13423           memcpy(&ur,&r,sizeof(r));
13424           if( ur==0x7ff0000000000000LL ){
13425             raw_printf(p->out, "1e999");
13426           }else if( ur==0xfff0000000000000LL ){
13427             raw_printf(p->out, "-1e999");
13428           }else{
13429             sqlite3_int64 ir = (sqlite3_int64)r;
13430             if( r==(double)ir ){
13431               sqlite3_snprintf(50,z,"%lld.0", ir);
13432             }else{
13433               sqlite3_snprintf(50,z,"%!.20g", r);
13434             }
13435             raw_printf(p->out, "%s", z);
13436           }
13437         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
13438           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
13439           int nBlob = sqlite3_column_bytes(p->pStmt, i);
13440           output_hex_blob(p->out, pBlob, nBlob);
13441         }else if( isNumber(azArg[i], 0) ){
13442           utf8_printf(p->out,"%s", azArg[i]);
13443         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
13444           output_quoted_string(p->out, azArg[i]);
13445         }else{
13446           output_quoted_escaped_string(p->out, azArg[i]);
13447         }
13448       }
13449       raw_printf(p->out,");\n");
13450       break;
13451     }
13452     case MODE_Json: {
13453       if( azArg==0 ) break;
13454       if( p->cnt==0 ){
13455         fputs("[{", p->out);
13456       }else{
13457         fputs(",\n{", p->out);
13458       }
13459       p->cnt++;
13460       for(i=0; i<nArg; i++){
13461         output_json_string(p->out, azCol[i], -1);
13462         putc(':', p->out);
13463         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
13464           fputs("null",p->out);
13465         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
13466           char z[50];
13467           double r = sqlite3_column_double(p->pStmt, i);
13468           sqlite3_uint64 ur;
13469           memcpy(&ur,&r,sizeof(r));
13470           if( ur==0x7ff0000000000000LL ){
13471             raw_printf(p->out, "1e999");
13472           }else if( ur==0xfff0000000000000LL ){
13473             raw_printf(p->out, "-1e999");
13474           }else{
13475             sqlite3_snprintf(50,z,"%!.20g", r);
13476             raw_printf(p->out, "%s", z);
13477           }
13478         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
13479           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
13480           int nBlob = sqlite3_column_bytes(p->pStmt, i);
13481           output_json_string(p->out, pBlob, nBlob);
13482         }else if( aiType && aiType[i]==SQLITE_TEXT ){
13483           output_json_string(p->out, azArg[i], -1);
13484         }else{
13485           utf8_printf(p->out,"%s", azArg[i]);
13486         }
13487         if( i<nArg-1 ){
13488           putc(',', p->out);
13489         }
13490       }
13491       putc('}', p->out);
13492       break;
13493     }
13494     case MODE_Quote: {
13495       if( azArg==0 ) break;
13496       if( p->cnt==0 && p->showHeader ){
13497         for(i=0; i<nArg; i++){
13498           if( i>0 ) fputs(p->colSeparator, p->out);
13499           output_quoted_string(p->out, azCol[i]);
13500         }
13501         fputs(p->rowSeparator, p->out);
13502       }
13503       p->cnt++;
13504       for(i=0; i<nArg; i++){
13505         if( i>0 ) fputs(p->colSeparator, p->out);
13506         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
13507           utf8_printf(p->out,"NULL");
13508         }else if( aiType && aiType[i]==SQLITE_TEXT ){
13509           output_quoted_string(p->out, azArg[i]);
13510         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
13511           utf8_printf(p->out,"%s", azArg[i]);
13512         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
13513           char z[50];
13514           double r = sqlite3_column_double(p->pStmt, i);
13515           sqlite3_snprintf(50,z,"%!.20g", r);
13516           raw_printf(p->out, "%s", z);
13517         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
13518           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
13519           int nBlob = sqlite3_column_bytes(p->pStmt, i);
13520           output_hex_blob(p->out, pBlob, nBlob);
13521         }else if( isNumber(azArg[i], 0) ){
13522           utf8_printf(p->out,"%s", azArg[i]);
13523         }else{
13524           output_quoted_string(p->out, azArg[i]);
13525         }
13526       }
13527       fputs(p->rowSeparator, p->out);
13528       break;
13529     }
13530     case MODE_Ascii: {
13531       if( p->cnt++==0 && p->showHeader ){
13532         for(i=0; i<nArg; i++){
13533           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
13534           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
13535         }
13536         utf8_printf(p->out, "%s", p->rowSeparator);
13537       }
13538       if( azArg==0 ) break;
13539       for(i=0; i<nArg; i++){
13540         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
13541         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
13542       }
13543       utf8_printf(p->out, "%s", p->rowSeparator);
13544       break;
13545     }
13546     case MODE_EQP: {
13547       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
13548       break;
13549     }
13550   }
13551   return 0;
13552 }
13553 
13554 /*
13555 ** This is the callback routine that the SQLite library
13556 ** invokes for each row of a query result.
13557 */
13558 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
13559   /* since we don't have type info, call the shell_callback with a NULL value */
13560   return shell_callback(pArg, nArg, azArg, azCol, NULL);
13561 }
13562 
13563 /*
13564 ** This is the callback routine from sqlite3_exec() that appends all
13565 ** output onto the end of a ShellText object.
13566 */
13567 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
13568   ShellText *p = (ShellText*)pArg;
13569   int i;
13570   UNUSED_PARAMETER(az);
13571   if( azArg==0 ) return 0;
13572   if( p->n ) appendText(p, "|", 0);
13573   for(i=0; i<nArg; i++){
13574     if( i ) appendText(p, ",", 0);
13575     if( azArg[i] ) appendText(p, azArg[i], 0);
13576   }
13577   return 0;
13578 }
13579 
13580 /*
13581 ** Generate an appropriate SELFTEST table in the main database.
13582 */
13583 static void createSelftestTable(ShellState *p){
13584   char *zErrMsg = 0;
13585   sqlite3_exec(p->db,
13586     "SAVEPOINT selftest_init;\n"
13587     "CREATE TABLE IF NOT EXISTS selftest(\n"
13588     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
13589     "  op TEXT,\n"                   /* Operator:  memo run */
13590     "  cmd TEXT,\n"                  /* Command text */
13591     "  ans TEXT\n"                   /* Desired answer */
13592     ");"
13593     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
13594     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
13595     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
13596     "         'memo','Tests generated by --init');\n"
13597     "INSERT INTO [_shell$self]\n"
13598     "  SELECT 'run',\n"
13599     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
13600                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
13601     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
13602                           "FROM sqlite_schema ORDER BY 2',224));\n"
13603     "INSERT INTO [_shell$self]\n"
13604     "  SELECT 'run',"
13605     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
13606     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
13607     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
13608     "  FROM (\n"
13609     "    SELECT name FROM sqlite_schema\n"
13610     "     WHERE type='table'\n"
13611     "       AND name<>'selftest'\n"
13612     "       AND coalesce(rootpage,0)>0\n"
13613     "  )\n"
13614     " ORDER BY name;\n"
13615     "INSERT INTO [_shell$self]\n"
13616     "  VALUES('run','PRAGMA integrity_check','ok');\n"
13617     "INSERT INTO selftest(tno,op,cmd,ans)"
13618     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
13619     "DROP TABLE [_shell$self];"
13620     ,0,0,&zErrMsg);
13621   if( zErrMsg ){
13622     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
13623     sqlite3_free(zErrMsg);
13624   }
13625   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
13626 }
13627 
13628 
13629 /*
13630 ** Set the destination table field of the ShellState structure to
13631 ** the name of the table given.  Escape any quote characters in the
13632 ** table name.
13633 */
13634 static void set_table_name(ShellState *p, const char *zName){
13635   int i, n;
13636   char cQuote;
13637   char *z;
13638 
13639   if( p->zDestTable ){
13640     free(p->zDestTable);
13641     p->zDestTable = 0;
13642   }
13643   if( zName==0 ) return;
13644   cQuote = quoteChar(zName);
13645   n = strlen30(zName);
13646   if( cQuote ) n += n+2;
13647   z = p->zDestTable = malloc( n+1 );
13648   shell_check_oom(z);
13649   n = 0;
13650   if( cQuote ) z[n++] = cQuote;
13651   for(i=0; zName[i]; i++){
13652     z[n++] = zName[i];
13653     if( zName[i]==cQuote ) z[n++] = cQuote;
13654   }
13655   if( cQuote ) z[n++] = cQuote;
13656   z[n] = 0;
13657 }
13658 
13659 /*
13660 ** Maybe construct two lines of text that point out the position of a
13661 ** syntax error.  Return a pointer to the text, in memory obtained from
13662 ** sqlite3_malloc().  Or, if the most recent error does not involve a
13663 ** specific token that we can point to, return an empty string.
13664 **
13665 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
13666 ** and should be released by the caller invoking sqlite3_free().
13667 */
13668 static char *shell_error_context(const char *zSql, sqlite3 *db){
13669   int iOffset;
13670   size_t len;
13671   char *zCode;
13672   char *zMsg;
13673   int i;
13674   if( db==0
13675    || zSql==0
13676    || (iOffset = sqlite3_error_offset(db))<0
13677   ){
13678     return sqlite3_mprintf("");
13679   }
13680   while( iOffset>50 ){
13681     iOffset--;
13682     zSql++;
13683     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
13684   }
13685   len = strlen(zSql);
13686   if( len>78 ){
13687     len = 78;
13688     while( (zSql[len]&0xc0)==0x80 ) len--;
13689   }
13690   zCode = sqlite3_mprintf("%.*s", len, zSql);
13691   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
13692   if( iOffset<25 ){
13693     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
13694   }else{
13695     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
13696   }
13697   return zMsg;
13698 }
13699 
13700 
13701 /*
13702 ** Execute a query statement that will generate SQL output.  Print
13703 ** the result columns, comma-separated, on a line and then add a
13704 ** semicolon terminator to the end of that line.
13705 **
13706 ** If the number of columns is 1 and that column contains text "--"
13707 ** then write the semicolon on a separate line.  That way, if a
13708 ** "--" comment occurs at the end of the statement, the comment
13709 ** won't consume the semicolon terminator.
13710 */
13711 static int run_table_dump_query(
13712   ShellState *p,           /* Query context */
13713   const char *zSelect      /* SELECT statement to extract content */
13714 ){
13715   sqlite3_stmt *pSelect;
13716   int rc;
13717   int nResult;
13718   int i;
13719   const char *z;
13720   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
13721   if( rc!=SQLITE_OK || !pSelect ){
13722     char *zContext = shell_error_context(zSelect, p->db);
13723     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
13724                 sqlite3_errmsg(p->db), zContext);
13725     sqlite3_free(zContext);
13726     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
13727     return rc;
13728   }
13729   rc = sqlite3_step(pSelect);
13730   nResult = sqlite3_column_count(pSelect);
13731   while( rc==SQLITE_ROW ){
13732     z = (const char*)sqlite3_column_text(pSelect, 0);
13733     utf8_printf(p->out, "%s", z);
13734     for(i=1; i<nResult; i++){
13735       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
13736     }
13737     if( z==0 ) z = "";
13738     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
13739     if( z[0] ){
13740       raw_printf(p->out, "\n;\n");
13741     }else{
13742       raw_printf(p->out, ";\n");
13743     }
13744     rc = sqlite3_step(pSelect);
13745   }
13746   rc = sqlite3_finalize(pSelect);
13747   if( rc!=SQLITE_OK ){
13748     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
13749                 sqlite3_errmsg(p->db));
13750     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
13751   }
13752   return rc;
13753 }
13754 
13755 /*
13756 ** Allocate space and save off string indicating current error.
13757 */
13758 static char *save_err_msg(
13759   sqlite3 *db,           /* Database to query */
13760   const char *zPhase,    /* When the error occcurs */
13761   int rc,                /* Error code returned from API */
13762   const char *zSql       /* SQL string, or NULL */
13763 ){
13764   char *zErr;
13765   char *zContext;
13766   sqlite3_str *pStr = sqlite3_str_new(0);
13767   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
13768   if( rc>1 ){
13769     sqlite3_str_appendf(pStr, " (%d)", rc);
13770   }
13771   zContext = shell_error_context(zSql, db);
13772   if( zContext ){
13773     sqlite3_str_appendall(pStr, zContext);
13774     sqlite3_free(zContext);
13775   }
13776   zErr = sqlite3_str_finish(pStr);
13777   shell_check_oom(zErr);
13778   return zErr;
13779 }
13780 
13781 #ifdef __linux__
13782 /*
13783 ** Attempt to display I/O stats on Linux using /proc/PID/io
13784 */
13785 static void displayLinuxIoStats(FILE *out){
13786   FILE *in;
13787   char z[200];
13788   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
13789   in = fopen(z, "rb");
13790   if( in==0 ) return;
13791   while( fgets(z, sizeof(z), in)!=0 ){
13792     static const struct {
13793       const char *zPattern;
13794       const char *zDesc;
13795     } aTrans[] = {
13796       { "rchar: ",                  "Bytes received by read():" },
13797       { "wchar: ",                  "Bytes sent to write():"    },
13798       { "syscr: ",                  "Read() system calls:"      },
13799       { "syscw: ",                  "Write() system calls:"     },
13800       { "read_bytes: ",             "Bytes read from storage:"  },
13801       { "write_bytes: ",            "Bytes written to storage:" },
13802       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
13803     };
13804     int i;
13805     for(i=0; i<ArraySize(aTrans); i++){
13806       int n = strlen30(aTrans[i].zPattern);
13807       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
13808         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
13809         break;
13810       }
13811     }
13812   }
13813   fclose(in);
13814 }
13815 #endif
13816 
13817 /*
13818 ** Display a single line of status using 64-bit values.
13819 */
13820 static void displayStatLine(
13821   ShellState *p,            /* The shell context */
13822   char *zLabel,             /* Label for this one line */
13823   char *zFormat,            /* Format for the result */
13824   int iStatusCtrl,          /* Which status to display */
13825   int bReset                /* True to reset the stats */
13826 ){
13827   sqlite3_int64 iCur = -1;
13828   sqlite3_int64 iHiwtr = -1;
13829   int i, nPercent;
13830   char zLine[200];
13831   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
13832   for(i=0, nPercent=0; zFormat[i]; i++){
13833     if( zFormat[i]=='%' ) nPercent++;
13834   }
13835   if( nPercent>1 ){
13836     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
13837   }else{
13838     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
13839   }
13840   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
13841 }
13842 
13843 /*
13844 ** Display memory stats.
13845 */
13846 static int display_stats(
13847   sqlite3 *db,                /* Database to query */
13848   ShellState *pArg,           /* Pointer to ShellState */
13849   int bReset                  /* True to reset the stats */
13850 ){
13851   int iCur;
13852   int iHiwtr;
13853   FILE *out;
13854   if( pArg==0 || pArg->out==0 ) return 0;
13855   out = pArg->out;
13856 
13857   if( pArg->pStmt && pArg->statsOn==2 ){
13858     int nCol, i, x;
13859     sqlite3_stmt *pStmt = pArg->pStmt;
13860     char z[100];
13861     nCol = sqlite3_column_count(pStmt);
13862     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
13863     for(i=0; i<nCol; i++){
13864       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
13865       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
13866 #ifndef SQLITE_OMIT_DECLTYPE
13867       sqlite3_snprintf(30, z+x, "declared type:");
13868       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
13869 #endif
13870 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13871       sqlite3_snprintf(30, z+x, "database name:");
13872       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
13873       sqlite3_snprintf(30, z+x, "table name:");
13874       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
13875       sqlite3_snprintf(30, z+x, "origin name:");
13876       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
13877 #endif
13878     }
13879   }
13880 
13881   if( pArg->statsOn==3 ){
13882     if( pArg->pStmt ){
13883       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
13884       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
13885     }
13886     return 0;
13887   }
13888 
13889   displayStatLine(pArg, "Memory Used:",
13890      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
13891   displayStatLine(pArg, "Number of Outstanding Allocations:",
13892      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
13893   if( pArg->shellFlgs & SHFLG_Pagecache ){
13894     displayStatLine(pArg, "Number of Pcache Pages Used:",
13895        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
13896   }
13897   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
13898      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
13899   displayStatLine(pArg, "Largest Allocation:",
13900      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
13901   displayStatLine(pArg, "Largest Pcache Allocation:",
13902      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
13903 #ifdef YYTRACKMAXSTACKDEPTH
13904   displayStatLine(pArg, "Deepest Parser Stack:",
13905      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
13906 #endif
13907 
13908   if( db ){
13909     if( pArg->shellFlgs & SHFLG_Lookaside ){
13910       iHiwtr = iCur = -1;
13911       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
13912                         &iCur, &iHiwtr, bReset);
13913       raw_printf(pArg->out,
13914               "Lookaside Slots Used:                %d (max %d)\n",
13915               iCur, iHiwtr);
13916       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
13917                         &iCur, &iHiwtr, bReset);
13918       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
13919               iHiwtr);
13920       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
13921                         &iCur, &iHiwtr, bReset);
13922       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
13923               iHiwtr);
13924       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
13925                         &iCur, &iHiwtr, bReset);
13926       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
13927               iHiwtr);
13928     }
13929     iHiwtr = iCur = -1;
13930     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
13931     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
13932             iCur);
13933     iHiwtr = iCur = -1;
13934     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
13935     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
13936     iHiwtr = iCur = -1;
13937     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
13938     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
13939     iHiwtr = iCur = -1;
13940     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
13941     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
13942     iHiwtr = iCur = -1;
13943     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
13944     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
13945     iHiwtr = iCur = -1;
13946     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
13947     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
13948             iCur);
13949     iHiwtr = iCur = -1;
13950     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
13951     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
13952             iCur);
13953   }
13954 
13955   if( pArg->pStmt ){
13956     int iHit, iMiss;
13957     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
13958                                bReset);
13959     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
13960     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
13961     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
13962     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
13963     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
13964     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
13965     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
13966     if( iHit || iMiss ){
13967       raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
13968             iHit, iHit+iMiss);
13969     }
13970     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
13971     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
13972     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
13973     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
13974     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
13975     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
13976     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
13977     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
13978   }
13979 
13980 #ifdef __linux__
13981   displayLinuxIoStats(pArg->out);
13982 #endif
13983 
13984   /* Do not remove this machine readable comment: extra-stats-output-here */
13985 
13986   return 0;
13987 }
13988 
13989 /*
13990 ** Display scan stats.
13991 */
13992 static void display_scanstats(
13993   sqlite3 *db,                    /* Database to query */
13994   ShellState *pArg                /* Pointer to ShellState */
13995 ){
13996 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
13997   UNUSED_PARAMETER(db);
13998   UNUSED_PARAMETER(pArg);
13999 #else
14000   int i, k, n, mx;
14001   raw_printf(pArg->out, "-------- scanstats --------\n");
14002   mx = 0;
14003   for(k=0; k<=mx; k++){
14004     double rEstLoop = 1.0;
14005     for(i=n=0; 1; i++){
14006       sqlite3_stmt *p = pArg->pStmt;
14007       sqlite3_int64 nLoop, nVisit;
14008       double rEst;
14009       int iSid;
14010       const char *zExplain;
14011       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
14012         break;
14013       }
14014       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
14015       if( iSid>mx ) mx = iSid;
14016       if( iSid!=k ) continue;
14017       if( n==0 ){
14018         rEstLoop = (double)nLoop;
14019         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
14020       }
14021       n++;
14022       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
14023       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
14024       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
14025       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
14026       rEstLoop *= rEst;
14027       raw_printf(pArg->out,
14028           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
14029           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
14030       );
14031     }
14032   }
14033   raw_printf(pArg->out, "---------------------------\n");
14034 #endif
14035 }
14036 
14037 /*
14038 ** Parameter azArray points to a zero-terminated array of strings. zStr
14039 ** points to a single nul-terminated string. Return non-zero if zStr
14040 ** is equal, according to strcmp(), to any of the strings in the array.
14041 ** Otherwise, return zero.
14042 */
14043 static int str_in_array(const char *zStr, const char **azArray){
14044   int i;
14045   for(i=0; azArray[i]; i++){
14046     if( 0==strcmp(zStr, azArray[i]) ) return 1;
14047   }
14048   return 0;
14049 }
14050 
14051 /*
14052 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
14053 ** and populate the ShellState.aiIndent[] array with the number of
14054 ** spaces each opcode should be indented before it is output.
14055 **
14056 ** The indenting rules are:
14057 **
14058 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
14059 **       all opcodes that occur between the p2 jump destination and the opcode
14060 **       itself by 2 spaces.
14061 **
14062 **     * Do the previous for "Return" instructions for when P2 is positive.
14063 **       See tag-20220407a in wherecode.c and vdbe.c.
14064 **
14065 **     * For each "Goto", if the jump destination is earlier in the program
14066 **       and ends on one of:
14067 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
14068 **       or if the P1 parameter is one instead of zero,
14069 **       then indent all opcodes between the earlier instruction
14070 **       and "Goto" by 2 spaces.
14071 */
14072 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
14073   const char *zSql;               /* The text of the SQL statement */
14074   const char *z;                  /* Used to check if this is an EXPLAIN */
14075   int *abYield = 0;               /* True if op is an OP_Yield */
14076   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
14077   int iOp;                        /* Index of operation in p->aiIndent[] */
14078 
14079   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
14080                            "Return", 0 };
14081   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
14082                             "Rewind", 0 };
14083   const char *azGoto[] = { "Goto", 0 };
14084 
14085   /* Try to figure out if this is really an EXPLAIN statement. If this
14086   ** cannot be verified, return early.  */
14087   if( sqlite3_column_count(pSql)!=8 ){
14088     p->cMode = p->mode;
14089     return;
14090   }
14091   zSql = sqlite3_sql(pSql);
14092   if( zSql==0 ) return;
14093   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
14094   if( sqlite3_strnicmp(z, "explain", 7) ){
14095     p->cMode = p->mode;
14096     return;
14097   }
14098 
14099   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
14100     int i;
14101     int iAddr = sqlite3_column_int(pSql, 0);
14102     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
14103 
14104     /* Set p2 to the P2 field of the current opcode. Then, assuming that
14105     ** p2 is an instruction address, set variable p2op to the index of that
14106     ** instruction in the aiIndent[] array. p2 and p2op may be different if
14107     ** the current instruction is part of a sub-program generated by an
14108     ** SQL trigger or foreign key.  */
14109     int p2 = sqlite3_column_int(pSql, 3);
14110     int p2op = (p2 + (iOp-iAddr));
14111 
14112     /* Grow the p->aiIndent array as required */
14113     if( iOp>=nAlloc ){
14114       if( iOp==0 ){
14115         /* Do further verfication that this is explain output.  Abort if
14116         ** it is not */
14117         static const char *explainCols[] = {
14118            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
14119         int jj;
14120         for(jj=0; jj<ArraySize(explainCols); jj++){
14121           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
14122             p->cMode = p->mode;
14123             sqlite3_reset(pSql);
14124             return;
14125           }
14126         }
14127       }
14128       nAlloc += 100;
14129       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
14130       shell_check_oom(p->aiIndent);
14131       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
14132       shell_check_oom(abYield);
14133     }
14134     abYield[iOp] = str_in_array(zOp, azYield);
14135     p->aiIndent[iOp] = 0;
14136     p->nIndent = iOp+1;
14137 
14138     if( str_in_array(zOp, azNext) && p2op>0 ){
14139       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
14140     }
14141     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
14142      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
14143     ){
14144       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
14145     }
14146   }
14147 
14148   p->iIndent = 0;
14149   sqlite3_free(abYield);
14150   sqlite3_reset(pSql);
14151 }
14152 
14153 /*
14154 ** Free the array allocated by explain_data_prepare().
14155 */
14156 static void explain_data_delete(ShellState *p){
14157   sqlite3_free(p->aiIndent);
14158   p->aiIndent = 0;
14159   p->nIndent = 0;
14160   p->iIndent = 0;
14161 }
14162 
14163 /*
14164 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
14165 */
14166 static unsigned int savedSelectTrace;
14167 static unsigned int savedWhereTrace;
14168 static void disable_debug_trace_modes(void){
14169   unsigned int zero = 0;
14170   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
14171   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
14172   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
14173   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
14174 }
14175 static void restore_debug_trace_modes(void){
14176   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
14177   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
14178 }
14179 
14180 /* Create the TEMP table used to store parameter bindings */
14181 static void bind_table_init(ShellState *p){
14182   int wrSchema = 0;
14183   int defensiveMode = 0;
14184   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
14185   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
14186   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
14187   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
14188   sqlite3_exec(p->db,
14189     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
14190     "  key TEXT PRIMARY KEY,\n"
14191     "  value\n"
14192     ") WITHOUT ROWID;",
14193     0, 0, 0);
14194   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
14195   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
14196 }
14197 
14198 /*
14199 ** Bind parameters on a prepared statement.
14200 **
14201 ** Parameter bindings are taken from a TEMP table of the form:
14202 **
14203 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
14204 **    WITHOUT ROWID;
14205 **
14206 ** No bindings occur if this table does not exist.  The name of the table
14207 ** begins with "sqlite_" so that it will not collide with ordinary application
14208 ** tables.  The table must be in the TEMP schema.
14209 */
14210 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
14211   int nVar;
14212   int i;
14213   int rc;
14214   sqlite3_stmt *pQ = 0;
14215 
14216   nVar = sqlite3_bind_parameter_count(pStmt);
14217   if( nVar==0 ) return;  /* Nothing to do */
14218   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
14219                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
14220     return; /* Parameter table does not exist */
14221   }
14222   rc = sqlite3_prepare_v2(pArg->db,
14223           "SELECT value FROM temp.sqlite_parameters"
14224           " WHERE key=?1", -1, &pQ, 0);
14225   if( rc || pQ==0 ) return;
14226   for(i=1; i<=nVar; i++){
14227     char zNum[30];
14228     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
14229     if( zVar==0 ){
14230       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
14231       zVar = zNum;
14232     }
14233     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
14234     if( sqlite3_step(pQ)==SQLITE_ROW ){
14235       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
14236     }else{
14237       sqlite3_bind_null(pStmt, i);
14238     }
14239     sqlite3_reset(pQ);
14240   }
14241   sqlite3_finalize(pQ);
14242 }
14243 
14244 /*
14245 ** UTF8 box-drawing characters.  Imagine box lines like this:
14246 **
14247 **           1
14248 **           |
14249 **       4 --+-- 2
14250 **           |
14251 **           3
14252 **
14253 ** Each box characters has between 2 and 4 of the lines leading from
14254 ** the center.  The characters are here identified by the numbers of
14255 ** their corresponding lines.
14256 */
14257 #define BOX_24   "\342\224\200"  /* U+2500 --- */
14258 #define BOX_13   "\342\224\202"  /* U+2502  |  */
14259 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
14260 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
14261 #define BOX_12   "\342\224\224"  /* U+2514  '- */
14262 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
14263 #define BOX_123  "\342\224\234"  /* U+251c  |- */
14264 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
14265 #define BOX_234  "\342\224\254"  /* U+252c -,- */
14266 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
14267 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
14268 
14269 /* Draw horizontal line N characters long using unicode box
14270 ** characters
14271 */
14272 static void print_box_line(FILE *out, int N){
14273   const char zDash[] =
14274       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
14275       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
14276   const int nDash = sizeof(zDash) - 1;
14277   N *= 3;
14278   while( N>nDash ){
14279     utf8_printf(out, zDash);
14280     N -= nDash;
14281   }
14282   utf8_printf(out, "%.*s", N, zDash);
14283 }
14284 
14285 /*
14286 ** Draw a horizontal separator for a MODE_Box table.
14287 */
14288 static void print_box_row_separator(
14289   ShellState *p,
14290   int nArg,
14291   const char *zSep1,
14292   const char *zSep2,
14293   const char *zSep3
14294 ){
14295   int i;
14296   if( nArg>0 ){
14297     utf8_printf(p->out, "%s", zSep1);
14298     print_box_line(p->out, p->actualWidth[0]+2);
14299     for(i=1; i<nArg; i++){
14300       utf8_printf(p->out, "%s", zSep2);
14301       print_box_line(p->out, p->actualWidth[i]+2);
14302     }
14303     utf8_printf(p->out, "%s", zSep3);
14304   }
14305   fputs("\n", p->out);
14306 }
14307 
14308 /*
14309 ** z[] is a line of text that is to be displayed the .mode box or table or
14310 ** similar tabular formats.  z[] might contain control characters such
14311 ** as \n, \t, \f, or \r.
14312 **
14313 ** Compute characters to display on the first line of z[].  Stop at the
14314 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
14315 ** from malloc()) of that first line, which caller should free sometime.
14316 ** Write anything to display on the next line into *pzTail.  If this is
14317 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
14318 */
14319 static char *translateForDisplayAndDup(
14320   const unsigned char *z,            /* Input text to be transformed */
14321   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
14322   int mxWidth,                       /* Max width.  0 means no limit */
14323   u8 bWordWrap                       /* If true, avoid breaking mid-word */
14324 ){
14325   int i;                 /* Input bytes consumed */
14326   int j;                 /* Output bytes generated */
14327   int k;                 /* Input bytes to be displayed */
14328   int n;                 /* Output column number */
14329   unsigned char *zOut;   /* Output text */
14330 
14331   if( z==0 ){
14332     *pzTail = 0;
14333     return 0;
14334   }
14335   if( mxWidth<0 ) mxWidth = -mxWidth;
14336   if( mxWidth==0 ) mxWidth = 1000000;
14337   i = j = n = 0;
14338   while( n<mxWidth ){
14339     if( z[i]>=' ' ){
14340       n++;
14341       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
14342       continue;
14343     }
14344     if( z[i]=='\t' ){
14345       do{
14346         n++;
14347         j++;
14348       }while( (n&7)!=0 && n<mxWidth );
14349       i++;
14350       continue;
14351     }
14352     break;
14353   }
14354   if( n>=mxWidth && bWordWrap  ){
14355     /* Perhaps try to back up to a better place to break the line */
14356     for(k=i; k>i/2; k--){
14357       if( isspace(z[k-1]) ) break;
14358     }
14359     if( k<=i/2 ){
14360       for(k=i; k>i/2; k--){
14361         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
14362       }
14363     }
14364     if( k<=i/2 ){
14365       k = i;
14366     }else{
14367       i = k;
14368       while( z[i]==' ' ) i++;
14369     }
14370   }else{
14371     k = i;
14372   }
14373   if( n>=mxWidth && z[i]>=' ' ){
14374    *pzTail = &z[i];
14375   }else if( z[i]=='\r' && z[i+1]=='\n' ){
14376     *pzTail = z[i+2] ? &z[i+2] : 0;
14377   }else if( z[i]==0 || z[i+1]==0 ){
14378     *pzTail = 0;
14379   }else{
14380     *pzTail = &z[i+1];
14381   }
14382   zOut = malloc( j+1 );
14383   shell_check_oom(zOut);
14384   i = j = n = 0;
14385   while( i<k ){
14386     if( z[i]>=' ' ){
14387       n++;
14388       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
14389       continue;
14390     }
14391     if( z[i]=='\t' ){
14392       do{
14393         n++;
14394         zOut[j++] = ' ';
14395       }while( (n&7)!=0 && n<mxWidth );
14396       i++;
14397       continue;
14398     }
14399     break;
14400   }
14401   zOut[j] = 0;
14402   return (char*)zOut;
14403 }
14404 
14405 /* Extract the value of the i-th current column for pStmt as an SQL literal
14406 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
14407 ** the caller.
14408 */
14409 static char *quoted_column(sqlite3_stmt *pStmt, int i){
14410   switch( sqlite3_column_type(pStmt, i) ){
14411     case SQLITE_NULL: {
14412       return sqlite3_mprintf("NULL");
14413     }
14414     case SQLITE_INTEGER:
14415     case SQLITE_FLOAT: {
14416       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
14417     }
14418     case SQLITE_TEXT: {
14419       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
14420     }
14421     case SQLITE_BLOB: {
14422       int j;
14423       sqlite3_str *pStr = sqlite3_str_new(0);
14424       const unsigned char *a = sqlite3_column_blob(pStmt,i);
14425       int n = sqlite3_column_bytes(pStmt,i);
14426       sqlite3_str_append(pStr, "x'", 2);
14427       for(j=0; j<n; j++){
14428         sqlite3_str_appendf(pStr, "%02x", a[j]);
14429       }
14430       sqlite3_str_append(pStr, "'", 1);
14431       return sqlite3_str_finish(pStr);
14432     }
14433   }
14434   return 0; /* Not reached */
14435 }
14436 
14437 /*
14438 ** Run a prepared statement and output the result in one of the
14439 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
14440 ** or MODE_Box.
14441 **
14442 ** This is different from ordinary exec_prepared_stmt() in that
14443 ** it has to run the entire query and gather the results into memory
14444 ** first, in order to determine column widths, before providing
14445 ** any output.
14446 */
14447 static void exec_prepared_stmt_columnar(
14448   ShellState *p,                        /* Pointer to ShellState */
14449   sqlite3_stmt *pStmt                   /* Statment to run */
14450 ){
14451   sqlite3_int64 nRow = 0;
14452   int nColumn = 0;
14453   char **azData = 0;
14454   sqlite3_int64 nAlloc = 0;
14455   char *abRowDiv = 0;
14456   const unsigned char *uz;
14457   const char *z;
14458   char **azQuoted = 0;
14459   int rc;
14460   sqlite3_int64 i, nData;
14461   int j, nTotal, w, n;
14462   const char *colSep = 0;
14463   const char *rowSep = 0;
14464   const unsigned char **azNextLine = 0;
14465   int bNextLine = 0;
14466   int bMultiLineRowExists = 0;
14467   int bw = p->cmOpts.bWordWrap;
14468   const char *zEmpty = "";
14469   const char *zShowNull = p->nullValue;
14470 
14471   rc = sqlite3_step(pStmt);
14472   if( rc!=SQLITE_ROW ) return;
14473   nColumn = sqlite3_column_count(pStmt);
14474   nAlloc = nColumn*4;
14475   if( nAlloc<=0 ) nAlloc = 1;
14476   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
14477   shell_check_oom(azData);
14478   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
14479   shell_check_oom((void*)azNextLine);
14480   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
14481   if( p->cmOpts.bQuote ){
14482     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
14483     shell_check_oom(azQuoted);
14484     memset(azQuoted, 0, nColumn*sizeof(char*) );
14485   }
14486   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
14487   shell_check_oom(abRowDiv);
14488   if( nColumn>p->nWidth ){
14489     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
14490     shell_check_oom(p->colWidth);
14491     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
14492     p->nWidth = nColumn;
14493     p->actualWidth = &p->colWidth[nColumn];
14494   }
14495   memset(p->actualWidth, 0, nColumn*sizeof(int));
14496   for(i=0; i<nColumn; i++){
14497     w = p->colWidth[i];
14498     if( w<0 ) w = -w;
14499     p->actualWidth[i] = w;
14500   }
14501   for(i=0; i<nColumn; i++){
14502     const unsigned char *zNotUsed;
14503     int wx = p->colWidth[i];
14504     if( wx==0 ){
14505       wx = p->cmOpts.iWrap;
14506     }
14507     if( wx<0 ) wx = -wx;
14508     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
14509     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
14510   }
14511   do{
14512     int useNextLine = bNextLine;
14513     bNextLine = 0;
14514     if( (nRow+2)*nColumn >= nAlloc ){
14515       nAlloc *= 2;
14516       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
14517       shell_check_oom(azData);
14518       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
14519       shell_check_oom(abRowDiv);
14520     }
14521     abRowDiv[nRow] = 1;
14522     nRow++;
14523     for(i=0; i<nColumn; i++){
14524       int wx = p->colWidth[i];
14525       if( wx==0 ){
14526         wx = p->cmOpts.iWrap;
14527       }
14528       if( wx<0 ) wx = -wx;
14529       if( useNextLine ){
14530         uz = azNextLine[i];
14531         if( uz==0 ) uz = (u8*)zEmpty;
14532       }else if( p->cmOpts.bQuote ){
14533         sqlite3_free(azQuoted[i]);
14534         azQuoted[i] = quoted_column(pStmt,i);
14535         uz = (const unsigned char*)azQuoted[i];
14536       }else{
14537         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
14538         if( uz==0 ) uz = (u8*)zShowNull;
14539       }
14540       azData[nRow*nColumn + i]
14541         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
14542       if( azNextLine[i] ){
14543         bNextLine = 1;
14544         abRowDiv[nRow-1] = 0;
14545         bMultiLineRowExists = 1;
14546       }
14547     }
14548   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
14549   nTotal = nColumn*(nRow+1);
14550   for(i=0; i<nTotal; i++){
14551     z = azData[i];
14552     if( z==0 ) z = (char*)zEmpty;
14553     n = strlenChar(z);
14554     j = i%nColumn;
14555     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
14556   }
14557   if( seenInterrupt ) goto columnar_end;
14558   if( nColumn==0 ) goto columnar_end;
14559   switch( p->cMode ){
14560     case MODE_Column: {
14561       colSep = "  ";
14562       rowSep = "\n";
14563       if( p->showHeader ){
14564         for(i=0; i<nColumn; i++){
14565           w = p->actualWidth[i];
14566           if( p->colWidth[i]<0 ) w = -w;
14567           utf8_width_print(p->out, w, azData[i]);
14568           fputs(i==nColumn-1?"\n":"  ", p->out);
14569         }
14570         for(i=0; i<nColumn; i++){
14571           print_dashes(p->out, p->actualWidth[i]);
14572           fputs(i==nColumn-1?"\n":"  ", p->out);
14573         }
14574       }
14575       break;
14576     }
14577     case MODE_Table: {
14578       colSep = " | ";
14579       rowSep = " |\n";
14580       print_row_separator(p, nColumn, "+");
14581       fputs("| ", p->out);
14582       for(i=0; i<nColumn; i++){
14583         w = p->actualWidth[i];
14584         n = strlenChar(azData[i]);
14585         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
14586         fputs(i==nColumn-1?" |\n":" | ", p->out);
14587       }
14588       print_row_separator(p, nColumn, "+");
14589       break;
14590     }
14591     case MODE_Markdown: {
14592       colSep = " | ";
14593       rowSep = " |\n";
14594       fputs("| ", p->out);
14595       for(i=0; i<nColumn; i++){
14596         w = p->actualWidth[i];
14597         n = strlenChar(azData[i]);
14598         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
14599         fputs(i==nColumn-1?" |\n":" | ", p->out);
14600       }
14601       print_row_separator(p, nColumn, "|");
14602       break;
14603     }
14604     case MODE_Box: {
14605       colSep = " " BOX_13 " ";
14606       rowSep = " " BOX_13 "\n";
14607       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
14608       utf8_printf(p->out, BOX_13 " ");
14609       for(i=0; i<nColumn; i++){
14610         w = p->actualWidth[i];
14611         n = strlenChar(azData[i]);
14612         utf8_printf(p->out, "%*s%s%*s%s",
14613             (w-n)/2, "", azData[i], (w-n+1)/2, "",
14614             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
14615       }
14616       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
14617       break;
14618     }
14619   }
14620   for(i=nColumn, j=0; i<nTotal; i++, j++){
14621     if( j==0 && p->cMode!=MODE_Column ){
14622       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
14623     }
14624     z = azData[i];
14625     if( z==0 ) z = p->nullValue;
14626     w = p->actualWidth[j];
14627     if( p->colWidth[j]<0 ) w = -w;
14628     utf8_width_print(p->out, w, z);
14629     if( j==nColumn-1 ){
14630       utf8_printf(p->out, "%s", rowSep);
14631       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
14632         if( p->cMode==MODE_Table ){
14633           print_row_separator(p, nColumn, "+");
14634         }else if( p->cMode==MODE_Box ){
14635           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
14636         }else if( p->cMode==MODE_Column ){
14637           raw_printf(p->out, "\n");
14638         }
14639       }
14640       j = -1;
14641       if( seenInterrupt ) goto columnar_end;
14642     }else{
14643       utf8_printf(p->out, "%s", colSep);
14644     }
14645   }
14646   if( p->cMode==MODE_Table ){
14647     print_row_separator(p, nColumn, "+");
14648   }else if( p->cMode==MODE_Box ){
14649     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
14650   }
14651 columnar_end:
14652   if( seenInterrupt ){
14653     utf8_printf(p->out, "Interrupt\n");
14654   }
14655   nData = (nRow+1)*nColumn;
14656   for(i=0; i<nData; i++){
14657     z = azData[i];
14658     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
14659   }
14660   sqlite3_free(azData);
14661   sqlite3_free((void*)azNextLine);
14662   sqlite3_free(abRowDiv);
14663   if( azQuoted ){
14664     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
14665     sqlite3_free(azQuoted);
14666   }
14667 }
14668 
14669 /*
14670 ** Run a prepared statement
14671 */
14672 static void exec_prepared_stmt(
14673   ShellState *pArg,                                /* Pointer to ShellState */
14674   sqlite3_stmt *pStmt                              /* Statment to run */
14675 ){
14676   int rc;
14677   sqlite3_uint64 nRow = 0;
14678 
14679   if( pArg->cMode==MODE_Column
14680    || pArg->cMode==MODE_Table
14681    || pArg->cMode==MODE_Box
14682    || pArg->cMode==MODE_Markdown
14683   ){
14684     exec_prepared_stmt_columnar(pArg, pStmt);
14685     return;
14686   }
14687 
14688   /* perform the first step.  this will tell us if we
14689   ** have a result set or not and how wide it is.
14690   */
14691   rc = sqlite3_step(pStmt);
14692   /* if we have a result set... */
14693   if( SQLITE_ROW == rc ){
14694     /* allocate space for col name ptr, value ptr, and type */
14695     int nCol = sqlite3_column_count(pStmt);
14696     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
14697     if( !pData ){
14698       shell_out_of_memory();
14699     }else{
14700       char **azCols = (char **)pData;      /* Names of result columns */
14701       char **azVals = &azCols[nCol];       /* Results */
14702       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
14703       int i, x;
14704       assert(sizeof(int) <= sizeof(char *));
14705       /* save off ptrs to column names */
14706       for(i=0; i<nCol; i++){
14707         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
14708       }
14709       do{
14710         nRow++;
14711         /* extract the data and data types */
14712         for(i=0; i<nCol; i++){
14713           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
14714           if( x==SQLITE_BLOB
14715            && pArg
14716            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
14717           ){
14718             azVals[i] = "";
14719           }else{
14720             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
14721           }
14722           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
14723             rc = SQLITE_NOMEM;
14724             break; /* from for */
14725           }
14726         } /* end for */
14727 
14728         /* if data and types extracted successfully... */
14729         if( SQLITE_ROW == rc ){
14730           /* call the supplied callback with the result row data */
14731           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
14732             rc = SQLITE_ABORT;
14733           }else{
14734             rc = sqlite3_step(pStmt);
14735           }
14736         }
14737       } while( SQLITE_ROW == rc );
14738       sqlite3_free(pData);
14739       if( pArg->cMode==MODE_Json ){
14740         fputs("]\n", pArg->out);
14741       }else if( pArg->cMode==MODE_Count ){
14742         char zBuf[200];
14743         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
14744                          nRow, nRow!=1 ? "s" : "");
14745         printf("%s", zBuf);
14746       }
14747     }
14748   }
14749 }
14750 
14751 #ifndef SQLITE_OMIT_VIRTUALTABLE
14752 /*
14753 ** This function is called to process SQL if the previous shell command
14754 ** was ".expert". It passes the SQL in the second argument directly to
14755 ** the sqlite3expert object.
14756 **
14757 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
14758 ** code. In this case, (*pzErr) may be set to point to a buffer containing
14759 ** an English language error message. It is the responsibility of the
14760 ** caller to eventually free this buffer using sqlite3_free().
14761 */
14762 static int expertHandleSQL(
14763   ShellState *pState,
14764   const char *zSql,
14765   char **pzErr
14766 ){
14767   assert( pState->expert.pExpert );
14768   assert( pzErr==0 || *pzErr==0 );
14769   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
14770 }
14771 
14772 /*
14773 ** This function is called either to silently clean up the object
14774 ** created by the ".expert" command (if bCancel==1), or to generate a
14775 ** report from it and then clean it up (if bCancel==0).
14776 **
14777 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
14778 ** code. In this case, (*pzErr) may be set to point to a buffer containing
14779 ** an English language error message. It is the responsibility of the
14780 ** caller to eventually free this buffer using sqlite3_free().
14781 */
14782 static int expertFinish(
14783   ShellState *pState,
14784   int bCancel,
14785   char **pzErr
14786 ){
14787   int rc = SQLITE_OK;
14788   sqlite3expert *p = pState->expert.pExpert;
14789   assert( p );
14790   assert( bCancel || pzErr==0 || *pzErr==0 );
14791   if( bCancel==0 ){
14792     FILE *out = pState->out;
14793     int bVerbose = pState->expert.bVerbose;
14794 
14795     rc = sqlite3_expert_analyze(p, pzErr);
14796     if( rc==SQLITE_OK ){
14797       int nQuery = sqlite3_expert_count(p);
14798       int i;
14799 
14800       if( bVerbose ){
14801         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
14802         raw_printf(out, "-- Candidates -----------------------------\n");
14803         raw_printf(out, "%s\n", zCand);
14804       }
14805       for(i=0; i<nQuery; i++){
14806         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
14807         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
14808         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
14809         if( zIdx==0 ) zIdx = "(no new indexes)\n";
14810         if( bVerbose ){
14811           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
14812           raw_printf(out, "%s\n\n", zSql);
14813         }
14814         raw_printf(out, "%s\n", zIdx);
14815         raw_printf(out, "%s\n", zEQP);
14816       }
14817     }
14818   }
14819   sqlite3_expert_destroy(p);
14820   pState->expert.pExpert = 0;
14821   return rc;
14822 }
14823 
14824 /*
14825 ** Implementation of ".expert" dot command.
14826 */
14827 static int expertDotCommand(
14828   ShellState *pState,             /* Current shell tool state */
14829   char **azArg,                   /* Array of arguments passed to dot command */
14830   int nArg                        /* Number of entries in azArg[] */
14831 ){
14832   int rc = SQLITE_OK;
14833   char *zErr = 0;
14834   int i;
14835   int iSample = 0;
14836 
14837   assert( pState->expert.pExpert==0 );
14838   memset(&pState->expert, 0, sizeof(ExpertInfo));
14839 
14840   for(i=1; rc==SQLITE_OK && i<nArg; i++){
14841     char *z = azArg[i];
14842     int n;
14843     if( z[0]=='-' && z[1]=='-' ) z++;
14844     n = strlen30(z);
14845     if( n>=2 && 0==strncmp(z, "-verbose", n) ){
14846       pState->expert.bVerbose = 1;
14847     }
14848     else if( n>=2 && 0==strncmp(z, "-sample", n) ){
14849       if( i==(nArg-1) ){
14850         raw_printf(stderr, "option requires an argument: %s\n", z);
14851         rc = SQLITE_ERROR;
14852       }else{
14853         iSample = (int)integerValue(azArg[++i]);
14854         if( iSample<0 || iSample>100 ){
14855           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
14856           rc = SQLITE_ERROR;
14857         }
14858       }
14859     }
14860     else{
14861       raw_printf(stderr, "unknown option: %s\n", z);
14862       rc = SQLITE_ERROR;
14863     }
14864   }
14865 
14866   if( rc==SQLITE_OK ){
14867     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
14868     if( pState->expert.pExpert==0 ){
14869       raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
14870       rc = SQLITE_ERROR;
14871     }else{
14872       sqlite3_expert_config(
14873           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
14874       );
14875     }
14876   }
14877   sqlite3_free(zErr);
14878 
14879   return rc;
14880 }
14881 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
14882 
14883 /*
14884 ** Execute a statement or set of statements.  Print
14885 ** any result rows/columns depending on the current mode
14886 ** set via the supplied callback.
14887 **
14888 ** This is very similar to SQLite's built-in sqlite3_exec()
14889 ** function except it takes a slightly different callback
14890 ** and callback data argument.
14891 */
14892 static int shell_exec(
14893   ShellState *pArg,                         /* Pointer to ShellState */
14894   const char *zSql,                         /* SQL to be evaluated */
14895   char **pzErrMsg                           /* Error msg written here */
14896 ){
14897   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
14898   int rc = SQLITE_OK;             /* Return Code */
14899   int rc2;
14900   const char *zLeftover;          /* Tail of unprocessed SQL */
14901   sqlite3 *db = pArg->db;
14902 
14903   if( pzErrMsg ){
14904     *pzErrMsg = NULL;
14905   }
14906 
14907 #ifndef SQLITE_OMIT_VIRTUALTABLE
14908   if( pArg->expert.pExpert ){
14909     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
14910     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
14911   }
14912 #endif
14913 
14914   while( zSql[0] && (SQLITE_OK == rc) ){
14915     static const char *zStmtSql;
14916     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
14917     if( SQLITE_OK != rc ){
14918       if( pzErrMsg ){
14919         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
14920       }
14921     }else{
14922       if( !pStmt ){
14923         /* this happens for a comment or white-space */
14924         zSql = zLeftover;
14925         while( IsSpace(zSql[0]) ) zSql++;
14926         continue;
14927       }
14928       zStmtSql = sqlite3_sql(pStmt);
14929       if( zStmtSql==0 ) zStmtSql = "";
14930       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
14931 
14932       /* save off the prepared statment handle and reset row count */
14933       if( pArg ){
14934         pArg->pStmt = pStmt;
14935         pArg->cnt = 0;
14936       }
14937 
14938       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
14939       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
14940         sqlite3_stmt *pExplain;
14941         char *zEQP;
14942         int triggerEQP = 0;
14943         disable_debug_trace_modes();
14944         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
14945         if( pArg->autoEQP>=AUTOEQP_trigger ){
14946           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
14947         }
14948         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
14949         shell_check_oom(zEQP);
14950         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
14951         if( rc==SQLITE_OK ){
14952           while( sqlite3_step(pExplain)==SQLITE_ROW ){
14953             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
14954             int iEqpId = sqlite3_column_int(pExplain, 0);
14955             int iParentId = sqlite3_column_int(pExplain, 1);
14956             if( zEQPLine==0 ) zEQPLine = "";
14957             if( zEQPLine[0]=='-' ) eqp_render(pArg);
14958             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
14959           }
14960           eqp_render(pArg);
14961         }
14962         sqlite3_finalize(pExplain);
14963         sqlite3_free(zEQP);
14964         if( pArg->autoEQP>=AUTOEQP_full ){
14965           /* Also do an EXPLAIN for ".eqp full" mode */
14966           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
14967           shell_check_oom(zEQP);
14968           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
14969           if( rc==SQLITE_OK ){
14970             pArg->cMode = MODE_Explain;
14971             explain_data_prepare(pArg, pExplain);
14972             exec_prepared_stmt(pArg, pExplain);
14973             explain_data_delete(pArg);
14974           }
14975           sqlite3_finalize(pExplain);
14976           sqlite3_free(zEQP);
14977         }
14978         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
14979           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
14980           /* Reprepare pStmt before reactiving trace modes */
14981           sqlite3_finalize(pStmt);
14982           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
14983           if( pArg ) pArg->pStmt = pStmt;
14984         }
14985         restore_debug_trace_modes();
14986       }
14987 
14988       if( pArg ){
14989         pArg->cMode = pArg->mode;
14990         if( pArg->autoExplain ){
14991           if( sqlite3_stmt_isexplain(pStmt)==1 ){
14992             pArg->cMode = MODE_Explain;
14993           }
14994           if( sqlite3_stmt_isexplain(pStmt)==2 ){
14995             pArg->cMode = MODE_EQP;
14996           }
14997         }
14998 
14999         /* If the shell is currently in ".explain" mode, gather the extra
15000         ** data required to add indents to the output.*/
15001         if( pArg->cMode==MODE_Explain ){
15002           explain_data_prepare(pArg, pStmt);
15003         }
15004       }
15005 
15006       bind_prepared_stmt(pArg, pStmt);
15007       exec_prepared_stmt(pArg, pStmt);
15008       explain_data_delete(pArg);
15009       eqp_render(pArg);
15010 
15011       /* print usage stats if stats on */
15012       if( pArg && pArg->statsOn ){
15013         display_stats(db, pArg, 0);
15014       }
15015 
15016       /* print loop-counters if required */
15017       if( pArg && pArg->scanstatsOn ){
15018         display_scanstats(db, pArg);
15019       }
15020 
15021       /* Finalize the statement just executed. If this fails, save a
15022       ** copy of the error message. Otherwise, set zSql to point to the
15023       ** next statement to execute. */
15024       rc2 = sqlite3_finalize(pStmt);
15025       if( rc!=SQLITE_NOMEM ) rc = rc2;
15026       if( rc==SQLITE_OK ){
15027         zSql = zLeftover;
15028         while( IsSpace(zSql[0]) ) zSql++;
15029       }else if( pzErrMsg ){
15030         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
15031       }
15032 
15033       /* clear saved stmt handle */
15034       if( pArg ){
15035         pArg->pStmt = NULL;
15036       }
15037     }
15038   } /* end while */
15039 
15040   return rc;
15041 }
15042 
15043 /*
15044 ** Release memory previously allocated by tableColumnList().
15045 */
15046 static void freeColumnList(char **azCol){
15047   int i;
15048   for(i=1; azCol[i]; i++){
15049     sqlite3_free(azCol[i]);
15050   }
15051   /* azCol[0] is a static string */
15052   sqlite3_free(azCol);
15053 }
15054 
15055 /*
15056 ** Return a list of pointers to strings which are the names of all
15057 ** columns in table zTab.   The memory to hold the names is dynamically
15058 ** allocated and must be released by the caller using a subsequent call
15059 ** to freeColumnList().
15060 **
15061 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
15062 ** value that needs to be preserved, then azCol[0] is filled in with the
15063 ** name of the rowid column.
15064 **
15065 ** The first regular column in the table is azCol[1].  The list is terminated
15066 ** by an entry with azCol[i]==0.
15067 */
15068 static char **tableColumnList(ShellState *p, const char *zTab){
15069   char **azCol = 0;
15070   sqlite3_stmt *pStmt;
15071   char *zSql;
15072   int nCol = 0;
15073   int nAlloc = 0;
15074   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
15075   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
15076   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
15077   int rc;
15078 
15079   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
15080   shell_check_oom(zSql);
15081   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
15082   sqlite3_free(zSql);
15083   if( rc ) return 0;
15084   while( sqlite3_step(pStmt)==SQLITE_ROW ){
15085     if( nCol>=nAlloc-2 ){
15086       nAlloc = nAlloc*2 + nCol + 10;
15087       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
15088       shell_check_oom(azCol);
15089     }
15090     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
15091     shell_check_oom(azCol[nCol]);
15092     if( sqlite3_column_int(pStmt, 5) ){
15093       nPK++;
15094       if( nPK==1
15095        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
15096                           "INTEGER")==0
15097       ){
15098         isIPK = 1;
15099       }else{
15100         isIPK = 0;
15101       }
15102     }
15103   }
15104   sqlite3_finalize(pStmt);
15105   if( azCol==0 ) return 0;
15106   azCol[0] = 0;
15107   azCol[nCol+1] = 0;
15108 
15109   /* The decision of whether or not a rowid really needs to be preserved
15110   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
15111   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
15112   ** rowids on tables where the rowid is inaccessible because there are other
15113   ** columns in the table named "rowid", "_rowid_", and "oid".
15114   */
15115   if( preserveRowid && isIPK ){
15116     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
15117     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
15118     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
15119     ** ROWID aliases.  To distinguish these cases, check to see if
15120     ** there is a "pk" entry in "PRAGMA index_list".  There will be
15121     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
15122     */
15123     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
15124                            " WHERE origin='pk'", zTab);
15125     shell_check_oom(zSql);
15126     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
15127     sqlite3_free(zSql);
15128     if( rc ){
15129       freeColumnList(azCol);
15130       return 0;
15131     }
15132     rc = sqlite3_step(pStmt);
15133     sqlite3_finalize(pStmt);
15134     preserveRowid = rc==SQLITE_ROW;
15135   }
15136   if( preserveRowid ){
15137     /* Only preserve the rowid if we can find a name to use for the
15138     ** rowid */
15139     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
15140     int i, j;
15141     for(j=0; j<3; j++){
15142       for(i=1; i<=nCol; i++){
15143         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
15144       }
15145       if( i>nCol ){
15146         /* At this point, we know that azRowid[j] is not the name of any
15147         ** ordinary column in the table.  Verify that azRowid[j] is a valid
15148         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
15149         ** tables will fail this last check */
15150         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
15151         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
15152         break;
15153       }
15154     }
15155   }
15156   return azCol;
15157 }
15158 
15159 /*
15160 ** Toggle the reverse_unordered_selects setting.
15161 */
15162 static void toggleSelectOrder(sqlite3 *db){
15163   sqlite3_stmt *pStmt = 0;
15164   int iSetting = 0;
15165   char zStmt[100];
15166   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
15167   if( sqlite3_step(pStmt)==SQLITE_ROW ){
15168     iSetting = sqlite3_column_int(pStmt, 0);
15169   }
15170   sqlite3_finalize(pStmt);
15171   sqlite3_snprintf(sizeof(zStmt), zStmt,
15172        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
15173   sqlite3_exec(db, zStmt, 0, 0, 0);
15174 }
15175 
15176 /*
15177 ** This is a different callback routine used for dumping the database.
15178 ** Each row received by this callback consists of a table name,
15179 ** the table type ("index" or "table") and SQL to create the table.
15180 ** This routine should print text sufficient to recreate the table.
15181 */
15182 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
15183   int rc;
15184   const char *zTable;
15185   const char *zType;
15186   const char *zSql;
15187   ShellState *p = (ShellState *)pArg;
15188   int dataOnly;
15189   int noSys;
15190 
15191   UNUSED_PARAMETER(azNotUsed);
15192   if( nArg!=3 || azArg==0 ) return 0;
15193   zTable = azArg[0];
15194   zType = azArg[1];
15195   zSql = azArg[2];
15196   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
15197   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
15198 
15199   if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
15200     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
15201   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
15202     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
15203   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
15204     return 0;
15205   }else if( dataOnly ){
15206     /* no-op */
15207   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
15208     char *zIns;
15209     if( !p->writableSchema ){
15210       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
15211       p->writableSchema = 1;
15212     }
15213     zIns = sqlite3_mprintf(
15214        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
15215        "VALUES('table','%q','%q',0,'%q');",
15216        zTable, zTable, zSql);
15217     shell_check_oom(zIns);
15218     utf8_printf(p->out, "%s\n", zIns);
15219     sqlite3_free(zIns);
15220     return 0;
15221   }else{
15222     printSchemaLine(p->out, zSql, ";\n");
15223   }
15224 
15225   if( strcmp(zType, "table")==0 ){
15226     ShellText sSelect;
15227     ShellText sTable;
15228     char **azCol;
15229     int i;
15230     char *savedDestTable;
15231     int savedMode;
15232 
15233     azCol = tableColumnList(p, zTable);
15234     if( azCol==0 ){
15235       p->nErr++;
15236       return 0;
15237     }
15238 
15239     /* Always quote the table name, even if it appears to be pure ascii,
15240     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
15241     initText(&sTable);
15242     appendText(&sTable, zTable, quoteChar(zTable));
15243     /* If preserving the rowid, add a column list after the table name.
15244     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
15245     ** instead of the usual "INSERT INTO tab VALUES(...)".
15246     */
15247     if( azCol[0] ){
15248       appendText(&sTable, "(", 0);
15249       appendText(&sTable, azCol[0], 0);
15250       for(i=1; azCol[i]; i++){
15251         appendText(&sTable, ",", 0);
15252         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
15253       }
15254       appendText(&sTable, ")", 0);
15255     }
15256 
15257     /* Build an appropriate SELECT statement */
15258     initText(&sSelect);
15259     appendText(&sSelect, "SELECT ", 0);
15260     if( azCol[0] ){
15261       appendText(&sSelect, azCol[0], 0);
15262       appendText(&sSelect, ",", 0);
15263     }
15264     for(i=1; azCol[i]; i++){
15265       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
15266       if( azCol[i+1] ){
15267         appendText(&sSelect, ",", 0);
15268       }
15269     }
15270     freeColumnList(azCol);
15271     appendText(&sSelect, " FROM ", 0);
15272     appendText(&sSelect, zTable, quoteChar(zTable));
15273 
15274     savedDestTable = p->zDestTable;
15275     savedMode = p->mode;
15276     p->zDestTable = sTable.z;
15277     p->mode = p->cMode = MODE_Insert;
15278     rc = shell_exec(p, sSelect.z, 0);
15279     if( (rc&0xff)==SQLITE_CORRUPT ){
15280       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
15281       toggleSelectOrder(p->db);
15282       shell_exec(p, sSelect.z, 0);
15283       toggleSelectOrder(p->db);
15284     }
15285     p->zDestTable = savedDestTable;
15286     p->mode = savedMode;
15287     freeText(&sTable);
15288     freeText(&sSelect);
15289     if( rc ) p->nErr++;
15290   }
15291   return 0;
15292 }
15293 
15294 /*
15295 ** Run zQuery.  Use dump_callback() as the callback routine so that
15296 ** the contents of the query are output as SQL statements.
15297 **
15298 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
15299 ** "ORDER BY rowid DESC" to the end.
15300 */
15301 static int run_schema_dump_query(
15302   ShellState *p,
15303   const char *zQuery
15304 ){
15305   int rc;
15306   char *zErr = 0;
15307   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
15308   if( rc==SQLITE_CORRUPT ){
15309     char *zQ2;
15310     int len = strlen30(zQuery);
15311     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
15312     if( zErr ){
15313       utf8_printf(p->out, "/****** %s ******/\n", zErr);
15314       sqlite3_free(zErr);
15315       zErr = 0;
15316     }
15317     zQ2 = malloc( len+100 );
15318     if( zQ2==0 ) return rc;
15319     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
15320     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
15321     if( rc ){
15322       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
15323     }else{
15324       rc = SQLITE_CORRUPT;
15325     }
15326     sqlite3_free(zErr);
15327     free(zQ2);
15328   }
15329   return rc;
15330 }
15331 
15332 /*
15333 ** Text of help messages.
15334 **
15335 ** The help text for each individual command begins with a line that starts
15336 ** with ".".  Subsequent lines are supplemental information.
15337 **
15338 ** There must be two or more spaces between the end of the command and the
15339 ** start of the description of what that command does.
15340 */
15341 static const char *(azHelp[]) = {
15342 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
15343   && !defined(SQLITE_SHELL_WASM_MODE)
15344   ".archive ...             Manage SQL archives",
15345   "   Each command must have exactly one of the following options:",
15346   "     -c, --create               Create a new archive",
15347   "     -u, --update               Add or update files with changed mtime",
15348   "     -i, --insert               Like -u but always add even if unchanged",
15349   "     -r, --remove               Remove files from archive",
15350   "     -t, --list                 List contents of archive",
15351   "     -x, --extract              Extract files from archive",
15352   "   Optional arguments:",
15353   "     -v, --verbose              Print each filename as it is processed",
15354   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
15355   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
15356   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
15357   "     -g, --glob                 Use glob matching for names in archive",
15358   "     -n, --dryrun               Show the SQL that would have occurred",
15359   "   Examples:",
15360   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
15361   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
15362   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
15363   "   See also:",
15364   "      http://sqlite.org/cli.html#sqlite_archive_support",
15365 #endif
15366 #ifndef SQLITE_OMIT_AUTHORIZATION
15367   ".auth ON|OFF             Show authorizer callbacks",
15368 #endif
15369 #ifndef SQLITE_SHELL_WASM_MODE
15370   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
15371   "   Options:",
15372   "       --append            Use the appendvfs",
15373   "       --async             Write to FILE without journal and fsync()",
15374 #endif
15375   ".bail on|off             Stop after hitting an error.  Default OFF",
15376   ".binary on|off           Turn binary output on or off.  Default OFF",
15377 #ifndef SQLITE_SHELL_WASM_MODE
15378   ".cd DIRECTORY            Change the working directory to DIRECTORY",
15379 #endif
15380   ".changes on|off          Show number of rows changed by SQL",
15381 #ifndef SQLITE_SHELL_WASM_MODE
15382   ".check GLOB              Fail if output since .testcase does not match",
15383   ".clone NEWDB             Clone data into NEWDB from the existing database",
15384 #endif
15385   ".connection [close] [#]  Open or close an auxiliary database connection",
15386   ".databases               List names and files of attached databases",
15387   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
15388 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15389   ".dbinfo ?DB?             Show status information about the database",
15390 #endif
15391   ".dump ?OBJECTS?          Render database content as SQL",
15392   "   Options:",
15393   "     --data-only            Output only INSERT statements",
15394   "     --newlines             Allow unescaped newline characters in output",
15395   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
15396   "     --preserve-rowids      Include ROWID values in the output",
15397   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
15398   "   Additional LIKE patterns can be given in subsequent arguments",
15399   ".echo on|off             Turn command echo on or off",
15400   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
15401   "   Other Modes:",
15402 #ifdef SQLITE_DEBUG
15403   "      test                  Show raw EXPLAIN QUERY PLAN output",
15404   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
15405 #endif
15406   "      trigger               Like \"full\" but also show trigger bytecode",
15407 #ifndef SQLITE_SHELL_WASM_MODE
15408   ".excel                   Display the output of next command in spreadsheet",
15409   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
15410 #endif
15411 #ifndef SQLITE_SHELL_WASM_MODE
15412   ".exit ?CODE?             Exit this program with return-code CODE",
15413 #endif
15414   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
15415   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
15416   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
15417   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
15418   "   --help                  Show CMD details",
15419   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
15420   ".headers on|off          Turn display of headers on or off",
15421   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
15422 #ifndef SQLITE_SHELL_WASM_MODE
15423   ".import FILE TABLE       Import data from FILE into TABLE",
15424   "   Options:",
15425   "     --ascii               Use \\037 and \\036 as column and row separators",
15426   "     --csv                 Use , and \\n as column and row separators",
15427   "     --skip N              Skip the first N rows of input",
15428   "     --schema S            Target table to be S.TABLE",
15429   "     -v                    \"Verbose\" - increase auxiliary output",
15430   "   Notes:",
15431   "     *  If TABLE does not exist, it is created.  The first row of input",
15432   "        determines the column names.",
15433   "     *  If neither --csv or --ascii are used, the input mode is derived",
15434   "        from the \".mode\" output mode",
15435   "     *  If FILE begins with \"|\" then it is a command that generates the",
15436   "        input text.",
15437 #endif
15438 #ifndef SQLITE_OMIT_TEST_CONTROL
15439   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
15440 #endif
15441   ".indexes ?TABLE?         Show names of indexes",
15442   "                           If TABLE is specified, only show indexes for",
15443   "                           tables matching TABLE using the LIKE operator.",
15444 #ifdef SQLITE_ENABLE_IOTRACE
15445   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
15446 #endif
15447   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
15448   ".lint OPTIONS            Report potential schema issues.",
15449   "     Options:",
15450   "        fkey-indexes     Find missing foreign key indexes",
15451 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
15452   ".load FILE ?ENTRY?       Load an extension library",
15453 #endif
15454 #ifndef SQLITE_SHELL_WASM_MODE
15455   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
15456 #endif
15457   ".mode MODE ?OPTIONS?     Set output mode",
15458   "   MODE is one of:",
15459   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
15460   "     box         Tables using unicode box-drawing characters",
15461   "     csv         Comma-separated values",
15462   "     column      Output in columns.  (See .width)",
15463   "     html        HTML <table> code",
15464   "     insert      SQL insert statements for TABLE",
15465   "     json        Results in a JSON array",
15466   "     line        One value per line",
15467   "     list        Values delimited by \"|\"",
15468   "     markdown    Markdown table format",
15469   "     qbox        Shorthand for \"box --width 60 --quote\"",
15470   "     quote       Escape answers as for SQL",
15471   "     table       ASCII-art table",
15472   "     tabs        Tab-separated values",
15473   "     tcl         TCL list elements",
15474   "   OPTIONS: (for columnar modes or insert mode):",
15475   "     --wrap N       Wrap output lines to no longer than N characters",
15476   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
15477   "     --ww           Shorthand for \"--wordwrap 1\"",
15478   "     --quote        Quote output text as SQL literals",
15479   "     --noquote      Do not quote output text",
15480   "     TABLE          The name of SQL table used for \"insert\" mode",
15481 #ifndef SQLITE_SHELL_WASM_MODE
15482   ".nonce STRING            Suspend safe mode for one command if nonce matches",
15483 #endif
15484   ".nullvalue STRING        Use STRING in place of NULL values",
15485 #ifndef SQLITE_SHELL_WASM_MODE
15486   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
15487   "     If FILE begins with '|' then open as a pipe",
15488   "       --bom  Put a UTF8 byte-order mark at the beginning",
15489   "       -e     Send output to the system text editor",
15490   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
15491   /* Note that .open is (partially) available in WASM builds but is
15492   ** currently only intended to be used by the fiddle tool, not
15493   ** end users, so is "undocumented." */
15494   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
15495   "     Options:",
15496   "        --append        Use appendvfs to append database to the end of FILE",
15497 #endif
15498 #ifndef SQLITE_OMIT_DESERIALIZE
15499   "        --deserialize   Load into memory using sqlite3_deserialize()",
15500   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
15501   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
15502 #endif
15503   "        --new           Initialize FILE to an empty database",
15504   "        --nofollow      Do not follow symbolic links",
15505   "        --readonly      Open FILE readonly",
15506   "        --zip           FILE is a ZIP archive",
15507 #ifndef SQLITE_SHELL_WASM_MODE
15508   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
15509   "   If FILE begins with '|' then open it as a pipe.",
15510   "   Options:",
15511   "     --bom                 Prefix output with a UTF8 byte-order mark",
15512   "     -e                    Send output to the system text editor",
15513   "     -x                    Send output as CSV to a spreadsheet",
15514 #endif
15515   ".parameter CMD ...       Manage SQL parameter bindings",
15516   "   clear                   Erase all bindings",
15517   "   init                    Initialize the TEMP table that holds bindings",
15518   "   list                    List the current parameter bindings",
15519   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
15520   "                           PARAMETER should start with one of: $ : @ ?",
15521   "   unset PARAMETER         Remove PARAMETER from the binding table",
15522   ".print STRING...         Print literal STRING",
15523 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
15524   ".progress N              Invoke progress handler after every N opcodes",
15525   "   --limit N                 Interrupt after N progress callbacks",
15526   "   --once                    Do no more than one progress interrupt",
15527   "   --quiet|-q                No output except at interrupts",
15528   "   --reset                   Reset the count for each input and interrupt",
15529 #endif
15530   ".prompt MAIN CONTINUE    Replace the standard prompts",
15531 #ifndef SQLITE_SHELL_WASM_MODE
15532   ".quit                    Exit this program",
15533   ".read FILE               Read input from FILE or command output",
15534   "    If FILE begins with \"|\", it is a command that generates the input.",
15535 #endif
15536 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15537   ".recover                 Recover as much data as possible from corrupt db.",
15538   "   --freelist-corrupt       Assume the freelist is corrupt",
15539   "   --recovery-db NAME       Store recovery metadata in database file NAME",
15540   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
15541   "   --no-rowids              Do not attempt to recover rowid values",
15542   "                            that are not also INTEGER PRIMARY KEYs",
15543 #endif
15544 #ifndef SQLITE_SHELL_WASM_MODE
15545   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
15546   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
15547 #endif
15548   ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
15549   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
15550   "   Options:",
15551   "      --indent             Try to pretty-print the schema",
15552   "      --nosys              Omit objects whose names start with \"sqlite_\"",
15553   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
15554   "    Options:",
15555   "       --init               Create a new SELFTEST table",
15556   "       -v                   Verbose output",
15557   ".separator COL ?ROW?     Change the column and row separators",
15558 #if defined(SQLITE_ENABLE_SESSION)
15559   ".session ?NAME? CMD ...  Create or control sessions",
15560   "   Subcommands:",
15561   "     attach TABLE             Attach TABLE",
15562   "     changeset FILE           Write a changeset into FILE",
15563   "     close                    Close one session",
15564   "     enable ?BOOLEAN?         Set or query the enable bit",
15565   "     filter GLOB...           Reject tables matching GLOBs",
15566   "     indirect ?BOOLEAN?       Mark or query the indirect status",
15567   "     isempty                  Query whether the session is empty",
15568   "     list                     List currently open session names",
15569   "     open DB NAME             Open a new session on DB",
15570   "     patchset FILE            Write a patchset into FILE",
15571   "   If ?NAME? is omitted, the first defined session is used.",
15572 #endif
15573   ".sha3sum ...             Compute a SHA3 hash of database content",
15574   "    Options:",
15575   "      --schema              Also hash the sqlite_schema table",
15576   "      --sha3-224            Use the sha3-224 algorithm",
15577   "      --sha3-256            Use the sha3-256 algorithm (default)",
15578   "      --sha3-384            Use the sha3-384 algorithm",
15579   "      --sha3-512            Use the sha3-512 algorithm",
15580   "    Any other argument is a LIKE pattern for tables to hash",
15581 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
15582   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
15583 #endif
15584   ".show                    Show the current values for various settings",
15585   ".stats ?ARG?             Show stats or turn stats on or off",
15586   "   off                      Turn off automatic stat display",
15587   "   on                       Turn on automatic stat display",
15588   "   stmt                     Show statement stats",
15589   "   vmstep                   Show the virtual machine step count only",
15590 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
15591   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
15592 #endif
15593   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
15594 #ifndef SQLITE_SHELL_WASM_MODE
15595   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
15596 #endif
15597   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
15598   "                           Run \".testctrl\" with no arguments for details",
15599   ".timeout MS              Try opening locked tables for MS milliseconds",
15600   ".timer on|off            Turn SQL timer on or off",
15601 #ifndef SQLITE_OMIT_TRACE
15602   ".trace ?OPTIONS?         Output each SQL statement as it is run",
15603   "    FILE                    Send output to FILE",
15604   "    stdout                  Send output to stdout",
15605   "    stderr                  Send output to stderr",
15606   "    off                     Disable tracing",
15607   "    --expanded              Expand query parameters",
15608 #ifdef SQLITE_ENABLE_NORMALIZE
15609   "    --normalized            Normal the SQL statements",
15610 #endif
15611   "    --plain                 Show SQL as it is input",
15612   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
15613   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
15614   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
15615   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
15616 #endif /* SQLITE_OMIT_TRACE */
15617 #ifdef SQLITE_DEBUG
15618   ".unmodule NAME ...       Unregister virtual table modules",
15619   "    --allexcept             Unregister everything except those named",
15620 #endif
15621   ".vfsinfo ?AUX?           Information about the top-level VFS",
15622   ".vfslist                 List all available VFSes",
15623   ".vfsname ?AUX?           Print the name of the VFS stack",
15624   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
15625   "     Negative values right-justify",
15626 };
15627 
15628 /*
15629 ** Output help text.
15630 **
15631 ** zPattern describes the set of commands for which help text is provided.
15632 ** If zPattern is NULL, then show all commands, but only give a one-line
15633 ** description of each.
15634 **
15635 ** Return the number of matches.
15636 */
15637 static int showHelp(FILE *out, const char *zPattern){
15638   int i = 0;
15639   int j = 0;
15640   int n = 0;
15641   char *zPat;
15642   if( zPattern==0
15643    || zPattern[0]=='0'
15644    || strcmp(zPattern,"-a")==0
15645    || strcmp(zPattern,"-all")==0
15646    || strcmp(zPattern,"--all")==0
15647   ){
15648     /* Show all commands, but only one line per command */
15649     if( zPattern==0 ) zPattern = "";
15650     for(i=0; i<ArraySize(azHelp); i++){
15651       if( azHelp[i][0]=='.' || zPattern[0] ){
15652         utf8_printf(out, "%s\n", azHelp[i]);
15653         n++;
15654       }
15655     }
15656   }else{
15657     /* Look for commands that for which zPattern is an exact prefix */
15658     zPat = sqlite3_mprintf(".%s*", zPattern);
15659     shell_check_oom(zPat);
15660     for(i=0; i<ArraySize(azHelp); i++){
15661       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
15662         utf8_printf(out, "%s\n", azHelp[i]);
15663         j = i+1;
15664         n++;
15665       }
15666     }
15667     sqlite3_free(zPat);
15668     if( n ){
15669       if( n==1 ){
15670         /* when zPattern is a prefix of exactly one command, then include the
15671         ** details of that command, which should begin at offset j */
15672         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
15673           utf8_printf(out, "%s\n", azHelp[j]);
15674           j++;
15675         }
15676       }
15677       return n;
15678     }
15679     /* Look for commands that contain zPattern anywhere.  Show the complete
15680     ** text of all commands that match. */
15681     zPat = sqlite3_mprintf("%%%s%%", zPattern);
15682     shell_check_oom(zPat);
15683     for(i=0; i<ArraySize(azHelp); i++){
15684       if( azHelp[i][0]=='.' ) j = i;
15685       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
15686         utf8_printf(out, "%s\n", azHelp[j]);
15687         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
15688           j++;
15689           utf8_printf(out, "%s\n", azHelp[j]);
15690         }
15691         i = j;
15692         n++;
15693       }
15694     }
15695     sqlite3_free(zPat);
15696   }
15697   return n;
15698 }
15699 
15700 /* Forward reference */
15701 static int process_input(ShellState *p);
15702 
15703 /*
15704 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
15705 ** and return a pointer to the buffer. The caller is responsible for freeing
15706 ** the memory.
15707 **
15708 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
15709 ** read.
15710 **
15711 ** For convenience, a nul-terminator byte is always appended to the data read
15712 ** from the file before the buffer is returned. This byte is not included in
15713 ** the final value of (*pnByte), if applicable.
15714 **
15715 ** NULL is returned if any error is encountered. The final value of *pnByte
15716 ** is undefined in this case.
15717 */
15718 static char *readFile(const char *zName, int *pnByte){
15719   FILE *in = fopen(zName, "rb");
15720   long nIn;
15721   size_t nRead;
15722   char *pBuf;
15723   if( in==0 ) return 0;
15724   fseek(in, 0, SEEK_END);
15725   nIn = ftell(in);
15726   rewind(in);
15727   pBuf = sqlite3_malloc64( nIn+1 );
15728   if( pBuf==0 ){ fclose(in); return 0; }
15729   nRead = fread(pBuf, nIn, 1, in);
15730   fclose(in);
15731   if( nRead!=1 ){
15732     sqlite3_free(pBuf);
15733     return 0;
15734   }
15735   pBuf[nIn] = 0;
15736   if( pnByte ) *pnByte = nIn;
15737   return pBuf;
15738 }
15739 
15740 #if defined(SQLITE_ENABLE_SESSION)
15741 /*
15742 ** Close a single OpenSession object and release all of its associated
15743 ** resources.
15744 */
15745 static void session_close(OpenSession *pSession){
15746   int i;
15747   sqlite3session_delete(pSession->p);
15748   sqlite3_free(pSession->zName);
15749   for(i=0; i<pSession->nFilter; i++){
15750     sqlite3_free(pSession->azFilter[i]);
15751   }
15752   sqlite3_free(pSession->azFilter);
15753   memset(pSession, 0, sizeof(OpenSession));
15754 }
15755 #endif
15756 
15757 /*
15758 ** Close all OpenSession objects and release all associated resources.
15759 */
15760 #if defined(SQLITE_ENABLE_SESSION)
15761 static void session_close_all(ShellState *p, int i){
15762   int j;
15763   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
15764   for(j=0; j<pAuxDb->nSession; j++){
15765     session_close(&pAuxDb->aSession[j]);
15766   }
15767   pAuxDb->nSession = 0;
15768 }
15769 #else
15770 # define session_close_all(X,Y)
15771 #endif
15772 
15773 /*
15774 ** Implementation of the xFilter function for an open session.  Omit
15775 ** any tables named by ".session filter" but let all other table through.
15776 */
15777 #if defined(SQLITE_ENABLE_SESSION)
15778 static int session_filter(void *pCtx, const char *zTab){
15779   OpenSession *pSession = (OpenSession*)pCtx;
15780   int i;
15781   for(i=0; i<pSession->nFilter; i++){
15782     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
15783   }
15784   return 1;
15785 }
15786 #endif
15787 
15788 /*
15789 ** Try to deduce the type of file for zName based on its content.  Return
15790 ** one of the SHELL_OPEN_* constants.
15791 **
15792 ** If the file does not exist or is empty but its name looks like a ZIP
15793 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
15794 ** Otherwise, assume an ordinary database regardless of the filename if
15795 ** the type cannot be determined from content.
15796 */
15797 int deduceDatabaseType(const char *zName, int dfltZip){
15798   FILE *f = fopen(zName, "rb");
15799   size_t n;
15800   int rc = SHELL_OPEN_UNSPEC;
15801   char zBuf[100];
15802   if( f==0 ){
15803     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
15804        return SHELL_OPEN_ZIPFILE;
15805     }else{
15806        return SHELL_OPEN_NORMAL;
15807     }
15808   }
15809   n = fread(zBuf, 16, 1, f);
15810   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
15811     fclose(f);
15812     return SHELL_OPEN_NORMAL;
15813   }
15814   fseek(f, -25, SEEK_END);
15815   n = fread(zBuf, 25, 1, f);
15816   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
15817     rc = SHELL_OPEN_APPENDVFS;
15818   }else{
15819     fseek(f, -22, SEEK_END);
15820     n = fread(zBuf, 22, 1, f);
15821     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
15822        && zBuf[3]==0x06 ){
15823       rc = SHELL_OPEN_ZIPFILE;
15824     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
15825       rc = SHELL_OPEN_ZIPFILE;
15826     }
15827   }
15828   fclose(f);
15829   return rc;
15830 }
15831 
15832 #ifndef SQLITE_OMIT_DESERIALIZE
15833 /*
15834 ** Reconstruct an in-memory database using the output from the "dbtotxt"
15835 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
15836 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
15837 */
15838 static unsigned char *readHexDb(ShellState *p, int *pnData){
15839   unsigned char *a = 0;
15840   int nLine;
15841   int n = 0;
15842   int pgsz = 0;
15843   int iOffset = 0;
15844   int j, k;
15845   int rc;
15846   FILE *in;
15847   const char *zDbFilename = p->pAuxDb->zDbFilename;
15848   unsigned int x[16];
15849   char zLine[1000];
15850   if( zDbFilename ){
15851     in = fopen(zDbFilename, "r");
15852     if( in==0 ){
15853       utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
15854       return 0;
15855     }
15856     nLine = 0;
15857   }else{
15858     in = p->in;
15859     nLine = p->lineno;
15860     if( in==0 ) in = stdin;
15861   }
15862   *pnData = 0;
15863   nLine++;
15864   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
15865   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
15866   if( rc!=2 ) goto readHexDb_error;
15867   if( n<0 ) goto readHexDb_error;
15868   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
15869   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
15870   a = sqlite3_malloc( n ? n : 1 );
15871   shell_check_oom(a);
15872   memset(a, 0, n);
15873   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
15874     utf8_printf(stderr, "invalid pagesize\n");
15875     goto readHexDb_error;
15876   }
15877   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
15878     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
15879     if( rc==2 ){
15880       iOffset = k;
15881       continue;
15882     }
15883     if( strncmp(zLine, "| end ", 6)==0 ){
15884       break;
15885     }
15886     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
15887                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
15888                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
15889     if( rc==17 ){
15890       k = iOffset+j;
15891       if( k+16<=n && k>=0 ){
15892         int ii;
15893         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
15894       }
15895     }
15896   }
15897   *pnData = n;
15898   if( in!=p->in ){
15899     fclose(in);
15900   }else{
15901     p->lineno = nLine;
15902   }
15903   return a;
15904 
15905 readHexDb_error:
15906   if( in!=p->in ){
15907     fclose(in);
15908   }else{
15909     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
15910       nLine++;
15911       if(strncmp(zLine, "| end ", 6)==0 ) break;
15912     }
15913     p->lineno = nLine;
15914   }
15915   sqlite3_free(a);
15916   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
15917   return 0;
15918 }
15919 #endif /* SQLITE_OMIT_DESERIALIZE */
15920 
15921 /*
15922 ** Scalar function "shell_int32". The first argument to this function
15923 ** must be a blob. The second a non-negative integer. This function
15924 ** reads and returns a 32-bit big-endian integer from byte
15925 ** offset (4*<arg2>) of the blob.
15926 */
15927 static void shellInt32(
15928   sqlite3_context *context,
15929   int argc,
15930   sqlite3_value **argv
15931 ){
15932   const unsigned char *pBlob;
15933   int nBlob;
15934   int iInt;
15935 
15936   UNUSED_PARAMETER(argc);
15937   nBlob = sqlite3_value_bytes(argv[0]);
15938   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
15939   iInt = sqlite3_value_int(argv[1]);
15940 
15941   if( iInt>=0 && (iInt+1)*4<=nBlob ){
15942     const unsigned char *a = &pBlob[iInt*4];
15943     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
15944                        + ((sqlite3_int64)a[1]<<16)
15945                        + ((sqlite3_int64)a[2]<< 8)
15946                        + ((sqlite3_int64)a[3]<< 0);
15947     sqlite3_result_int64(context, iVal);
15948   }
15949 }
15950 
15951 /*
15952 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
15953 ** using "..." with internal double-quote characters doubled.
15954 */
15955 static void shellIdQuote(
15956   sqlite3_context *context,
15957   int argc,
15958   sqlite3_value **argv
15959 ){
15960   const char *zName = (const char*)sqlite3_value_text(argv[0]);
15961   UNUSED_PARAMETER(argc);
15962   if( zName ){
15963     char *z = sqlite3_mprintf("\"%w\"", zName);
15964     sqlite3_result_text(context, z, -1, sqlite3_free);
15965   }
15966 }
15967 
15968 /*
15969 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
15970 */
15971 static void shellUSleepFunc(
15972   sqlite3_context *context,
15973   int argcUnused,
15974   sqlite3_value **argv
15975 ){
15976   int sleep = sqlite3_value_int(argv[0]);
15977   (void)argcUnused;
15978   sqlite3_sleep(sleep/1000);
15979   sqlite3_result_int(context, sleep);
15980 }
15981 
15982 /*
15983 ** Scalar function "shell_escape_crnl" used by the .recover command.
15984 ** The argument passed to this function is the output of built-in
15985 ** function quote(). If the first character of the input is "'",
15986 ** indicating that the value passed to quote() was a text value,
15987 ** then this function searches the input for "\n" and "\r" characters
15988 ** and adds a wrapper similar to the following:
15989 **
15990 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
15991 **
15992 ** Or, if the first character of the input is not "'", then a copy
15993 ** of the input is returned.
15994 */
15995 static void shellEscapeCrnl(
15996   sqlite3_context *context,
15997   int argc,
15998   sqlite3_value **argv
15999 ){
16000   const char *zText = (const char*)sqlite3_value_text(argv[0]);
16001   UNUSED_PARAMETER(argc);
16002   if( zText && zText[0]=='\'' ){
16003     int nText = sqlite3_value_bytes(argv[0]);
16004     int i;
16005     char zBuf1[20];
16006     char zBuf2[20];
16007     const char *zNL = 0;
16008     const char *zCR = 0;
16009     int nCR = 0;
16010     int nNL = 0;
16011 
16012     for(i=0; zText[i]; i++){
16013       if( zNL==0 && zText[i]=='\n' ){
16014         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
16015         nNL = (int)strlen(zNL);
16016       }
16017       if( zCR==0 && zText[i]=='\r' ){
16018         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
16019         nCR = (int)strlen(zCR);
16020       }
16021     }
16022 
16023     if( zNL || zCR ){
16024       int iOut = 0;
16025       i64 nMax = (nNL > nCR) ? nNL : nCR;
16026       i64 nAlloc = nMax * nText + (nMax+64)*2;
16027       char *zOut = (char*)sqlite3_malloc64(nAlloc);
16028       if( zOut==0 ){
16029         sqlite3_result_error_nomem(context);
16030         return;
16031       }
16032 
16033       if( zNL && zCR ){
16034         memcpy(&zOut[iOut], "replace(replace(", 16);
16035         iOut += 16;
16036       }else{
16037         memcpy(&zOut[iOut], "replace(", 8);
16038         iOut += 8;
16039       }
16040       for(i=0; zText[i]; i++){
16041         if( zText[i]=='\n' ){
16042           memcpy(&zOut[iOut], zNL, nNL);
16043           iOut += nNL;
16044         }else if( zText[i]=='\r' ){
16045           memcpy(&zOut[iOut], zCR, nCR);
16046           iOut += nCR;
16047         }else{
16048           zOut[iOut] = zText[i];
16049           iOut++;
16050         }
16051       }
16052 
16053       if( zNL ){
16054         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16055         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
16056         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
16057       }
16058       if( zCR ){
16059         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
16060         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
16061         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
16062       }
16063 
16064       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
16065       sqlite3_free(zOut);
16066       return;
16067     }
16068   }
16069 
16070   sqlite3_result_value(context, argv[0]);
16071 }
16072 
16073 /* Flags for open_db().
16074 **
16075 ** The default behavior of open_db() is to exit(1) if the database fails to
16076 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
16077 ** but still returns without calling exit.
16078 **
16079 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
16080 ** ZIP archive if the file does not exist or is empty and its name matches
16081 ** the *.zip pattern.
16082 */
16083 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
16084 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
16085 
16086 /*
16087 ** Make sure the database is open.  If it is not, then open it.  If
16088 ** the database fails to open, print an error message and exit.
16089 */
16090 static void open_db(ShellState *p, int openFlags){
16091   if( p->db==0 ){
16092     const char *zDbFilename = p->pAuxDb->zDbFilename;
16093     if( p->openMode==SHELL_OPEN_UNSPEC ){
16094       if( zDbFilename==0 || zDbFilename[0]==0 ){
16095         p->openMode = SHELL_OPEN_NORMAL;
16096       }else{
16097         p->openMode = (u8)deduceDatabaseType(zDbFilename,
16098                              (openFlags & OPEN_DB_ZIPFILE)!=0);
16099       }
16100     }
16101     switch( p->openMode ){
16102       case SHELL_OPEN_APPENDVFS: {
16103         sqlite3_open_v2(zDbFilename, &p->db,
16104            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
16105         break;
16106       }
16107       case SHELL_OPEN_HEXDB:
16108       case SHELL_OPEN_DESERIALIZE: {
16109         sqlite3_open(0, &p->db);
16110         break;
16111       }
16112       case SHELL_OPEN_ZIPFILE: {
16113         sqlite3_open(":memory:", &p->db);
16114         break;
16115       }
16116       case SHELL_OPEN_READONLY: {
16117         sqlite3_open_v2(zDbFilename, &p->db,
16118             SQLITE_OPEN_READONLY|p->openFlags, 0);
16119         break;
16120       }
16121       case SHELL_OPEN_UNSPEC:
16122       case SHELL_OPEN_NORMAL: {
16123         sqlite3_open_v2(zDbFilename, &p->db,
16124            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
16125         break;
16126       }
16127     }
16128     globalDb = p->db;
16129     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
16130       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
16131           zDbFilename, sqlite3_errmsg(p->db));
16132       if( openFlags & OPEN_DB_KEEPALIVE ){
16133         sqlite3_open(":memory:", &p->db);
16134         return;
16135       }
16136       exit(1);
16137     }
16138 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16139     sqlite3_enable_load_extension(p->db, 1);
16140 #endif
16141     sqlite3_shathree_init(p->db, 0, 0);
16142     sqlite3_uint_init(p->db, 0, 0);
16143     sqlite3_decimal_init(p->db, 0, 0);
16144     sqlite3_regexp_init(p->db, 0, 0);
16145     sqlite3_ieee_init(p->db, 0, 0);
16146     sqlite3_series_init(p->db, 0, 0);
16147 #ifndef SQLITE_SHELL_WASM_MODE
16148     sqlite3_fileio_init(p->db, 0, 0);
16149     sqlite3_completion_init(p->db, 0, 0);
16150 #endif
16151 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
16152     sqlite3_dbdata_init(p->db, 0, 0);
16153 #endif
16154 #ifdef SQLITE_HAVE_ZLIB
16155     if( !p->bSafeModePersist ){
16156       sqlite3_zipfile_init(p->db, 0, 0);
16157       sqlite3_sqlar_init(p->db, 0, 0);
16158     }
16159 #endif
16160     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
16161                             shellAddSchemaName, 0, 0);
16162     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
16163                             shellModuleSchema, 0, 0);
16164     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
16165                             shellPutsFunc, 0, 0);
16166     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
16167                             shellEscapeCrnl, 0, 0);
16168     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
16169                             shellInt32, 0, 0);
16170     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
16171                             shellIdQuote, 0, 0);
16172     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
16173                             shellUSleepFunc, 0, 0);
16174 #ifndef SQLITE_NOHAVE_SYSTEM
16175     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
16176                             editFunc, 0, 0);
16177     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
16178                             editFunc, 0, 0);
16179 #endif
16180     if( p->openMode==SHELL_OPEN_ZIPFILE ){
16181       char *zSql = sqlite3_mprintf(
16182          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
16183       shell_check_oom(zSql);
16184       sqlite3_exec(p->db, zSql, 0, 0, 0);
16185       sqlite3_free(zSql);
16186     }
16187 #ifndef SQLITE_OMIT_DESERIALIZE
16188     else
16189     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
16190       int rc;
16191       int nData = 0;
16192       unsigned char *aData;
16193       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
16194         aData = (unsigned char*)readFile(zDbFilename, &nData);
16195       }else{
16196         aData = readHexDb(p, &nData);
16197         if( aData==0 ){
16198           return;
16199         }
16200       }
16201       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
16202                    SQLITE_DESERIALIZE_RESIZEABLE |
16203                    SQLITE_DESERIALIZE_FREEONCLOSE);
16204       if( rc ){
16205         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
16206       }
16207       if( p->szMax>0 ){
16208         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
16209       }
16210     }
16211 #endif
16212   }
16213   if( p->bSafeModePersist && p->db!=0 ){
16214     sqlite3_set_authorizer(p->db, safeModeAuth, p);
16215   }
16216 }
16217 
16218 /*
16219 ** Attempt to close the databaes connection.  Report errors.
16220 */
16221 void close_db(sqlite3 *db){
16222   int rc = sqlite3_close(db);
16223   if( rc ){
16224     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
16225         rc, sqlite3_errmsg(db));
16226   }
16227 }
16228 
16229 #if HAVE_READLINE || HAVE_EDITLINE
16230 /*
16231 ** Readline completion callbacks
16232 */
16233 static char *readline_completion_generator(const char *text, int state){
16234   static sqlite3_stmt *pStmt = 0;
16235   char *zRet;
16236   if( state==0 ){
16237     char *zSql;
16238     sqlite3_finalize(pStmt);
16239     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
16240                            "  FROM completion(%Q) ORDER BY 1", text);
16241     shell_check_oom(zSql);
16242     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
16243     sqlite3_free(zSql);
16244   }
16245   if( sqlite3_step(pStmt)==SQLITE_ROW ){
16246     const char *z = (const char*)sqlite3_column_text(pStmt,0);
16247     zRet = z ? strdup(z) : 0;
16248   }else{
16249     sqlite3_finalize(pStmt);
16250     pStmt = 0;
16251     zRet = 0;
16252   }
16253   return zRet;
16254 }
16255 static char **readline_completion(const char *zText, int iStart, int iEnd){
16256   rl_attempted_completion_over = 1;
16257   return rl_completion_matches(zText, readline_completion_generator);
16258 }
16259 
16260 #elif HAVE_LINENOISE
16261 /*
16262 ** Linenoise completion callback
16263 */
16264 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
16265   int nLine = strlen30(zLine);
16266   int i, iStart;
16267   sqlite3_stmt *pStmt = 0;
16268   char *zSql;
16269   char zBuf[1000];
16270 
16271   if( nLine>sizeof(zBuf)-30 ) return;
16272   if( zLine[0]=='.' || zLine[0]=='#') return;
16273   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
16274   if( i==nLine-1 ) return;
16275   iStart = i+1;
16276   memcpy(zBuf, zLine, iStart);
16277   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
16278                          "  FROM completion(%Q,%Q) ORDER BY 1",
16279                          &zLine[iStart], zLine);
16280   shell_check_oom(zSql);
16281   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
16282   sqlite3_free(zSql);
16283   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
16284   while( sqlite3_step(pStmt)==SQLITE_ROW ){
16285     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
16286     int nCompletion = sqlite3_column_bytes(pStmt, 0);
16287     if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
16288       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
16289       linenoiseAddCompletion(lc, zBuf);
16290     }
16291   }
16292   sqlite3_finalize(pStmt);
16293 }
16294 #endif
16295 
16296 /*
16297 ** Do C-language style dequoting.
16298 **
16299 **    \a    -> alarm
16300 **    \b    -> backspace
16301 **    \t    -> tab
16302 **    \n    -> newline
16303 **    \v    -> vertical tab
16304 **    \f    -> form feed
16305 **    \r    -> carriage return
16306 **    \s    -> space
16307 **    \"    -> "
16308 **    \'    -> '
16309 **    \\    -> backslash
16310 **    \NNN  -> ascii character NNN in octal
16311 */
16312 static void resolve_backslashes(char *z){
16313   int i, j;
16314   char c;
16315   while( *z && *z!='\\' ) z++;
16316   for(i=j=0; (c = z[i])!=0; i++, j++){
16317     if( c=='\\' && z[i+1]!=0 ){
16318       c = z[++i];
16319       if( c=='a' ){
16320         c = '\a';
16321       }else if( c=='b' ){
16322         c = '\b';
16323       }else if( c=='t' ){
16324         c = '\t';
16325       }else if( c=='n' ){
16326         c = '\n';
16327       }else if( c=='v' ){
16328         c = '\v';
16329       }else if( c=='f' ){
16330         c = '\f';
16331       }else if( c=='r' ){
16332         c = '\r';
16333       }else if( c=='"' ){
16334         c = '"';
16335       }else if( c=='\'' ){
16336         c = '\'';
16337       }else if( c=='\\' ){
16338         c = '\\';
16339       }else if( c>='0' && c<='7' ){
16340         c -= '0';
16341         if( z[i+1]>='0' && z[i+1]<='7' ){
16342           i++;
16343           c = (c<<3) + z[i] - '0';
16344           if( z[i+1]>='0' && z[i+1]<='7' ){
16345             i++;
16346             c = (c<<3) + z[i] - '0';
16347           }
16348         }
16349       }
16350     }
16351     z[j] = c;
16352   }
16353   if( j<i ) z[j] = 0;
16354 }
16355 
16356 /*
16357 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
16358 ** for TRUE and FALSE.  Return the integer value if appropriate.
16359 */
16360 static int booleanValue(const char *zArg){
16361   int i;
16362   if( zArg[0]=='0' && zArg[1]=='x' ){
16363     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
16364   }else{
16365     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
16366   }
16367   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
16368   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
16369     return 1;
16370   }
16371   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
16372     return 0;
16373   }
16374   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
16375           zArg);
16376   return 0;
16377 }
16378 
16379 /*
16380 ** Set or clear a shell flag according to a boolean value.
16381 */
16382 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
16383   if( booleanValue(zArg) ){
16384     ShellSetFlag(p, mFlag);
16385   }else{
16386     ShellClearFlag(p, mFlag);
16387   }
16388 }
16389 
16390 /*
16391 ** Close an output file, assuming it is not stderr or stdout
16392 */
16393 static void output_file_close(FILE *f){
16394   if( f && f!=stdout && f!=stderr ) fclose(f);
16395 }
16396 
16397 /*
16398 ** Try to open an output file.   The names "stdout" and "stderr" are
16399 ** recognized and do the right thing.  NULL is returned if the output
16400 ** filename is "off".
16401 */
16402 static FILE *output_file_open(const char *zFile, int bTextMode){
16403   FILE *f;
16404   if( strcmp(zFile,"stdout")==0 ){
16405     f = stdout;
16406   }else if( strcmp(zFile, "stderr")==0 ){
16407     f = stderr;
16408   }else if( strcmp(zFile, "off")==0 ){
16409     f = 0;
16410   }else{
16411     f = fopen(zFile, bTextMode ? "w" : "wb");
16412     if( f==0 ){
16413       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
16414     }
16415   }
16416   return f;
16417 }
16418 
16419 #ifndef SQLITE_OMIT_TRACE
16420 /*
16421 ** A routine for handling output from sqlite3_trace().
16422 */
16423 static int sql_trace_callback(
16424   unsigned mType,         /* The trace type */
16425   void *pArg,             /* The ShellState pointer */
16426   void *pP,               /* Usually a pointer to sqlite_stmt */
16427   void *pX                /* Auxiliary output */
16428 ){
16429   ShellState *p = (ShellState*)pArg;
16430   sqlite3_stmt *pStmt;
16431   const char *zSql;
16432   int nSql;
16433   if( p->traceOut==0 ) return 0;
16434   if( mType==SQLITE_TRACE_CLOSE ){
16435     utf8_printf(p->traceOut, "-- closing database connection\n");
16436     return 0;
16437   }
16438   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
16439     zSql = (const char*)pX;
16440   }else{
16441     pStmt = (sqlite3_stmt*)pP;
16442     switch( p->eTraceType ){
16443       case SHELL_TRACE_EXPANDED: {
16444         zSql = sqlite3_expanded_sql(pStmt);
16445         break;
16446       }
16447 #ifdef SQLITE_ENABLE_NORMALIZE
16448       case SHELL_TRACE_NORMALIZED: {
16449         zSql = sqlite3_normalized_sql(pStmt);
16450         break;
16451       }
16452 #endif
16453       default: {
16454         zSql = sqlite3_sql(pStmt);
16455         break;
16456       }
16457     }
16458   }
16459   if( zSql==0 ) return 0;
16460   nSql = strlen30(zSql);
16461   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
16462   switch( mType ){
16463     case SQLITE_TRACE_ROW:
16464     case SQLITE_TRACE_STMT: {
16465       utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
16466       break;
16467     }
16468     case SQLITE_TRACE_PROFILE: {
16469       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
16470       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
16471       break;
16472     }
16473   }
16474   return 0;
16475 }
16476 #endif
16477 
16478 /*
16479 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
16480 ** a useful spot to set a debugger breakpoint.
16481 */
16482 static void test_breakpoint(void){
16483   static int nCall = 0;
16484   nCall++;
16485 }
16486 
16487 /*
16488 ** An object used to read a CSV and other files for import.
16489 */
16490 typedef struct ImportCtx ImportCtx;
16491 struct ImportCtx {
16492   const char *zFile;  /* Name of the input file */
16493   FILE *in;           /* Read the CSV text from this input stream */
16494   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
16495   char *z;            /* Accumulated text for a field */
16496   int n;              /* Number of bytes in z */
16497   int nAlloc;         /* Space allocated for z[] */
16498   int nLine;          /* Current line number */
16499   int nRow;           /* Number of rows imported */
16500   int nErr;           /* Number of errors encountered */
16501   int bNotFirst;      /* True if one or more bytes already read */
16502   int cTerm;          /* Character that terminated the most recent field */
16503   int cColSep;        /* The column separator character.  (Usually ",") */
16504   int cRowSep;        /* The row separator character.  (Usually "\n") */
16505 };
16506 
16507 /* Clean up resourced used by an ImportCtx */
16508 static void import_cleanup(ImportCtx *p){
16509   if( p->in!=0 && p->xCloser!=0 ){
16510     p->xCloser(p->in);
16511     p->in = 0;
16512   }
16513   sqlite3_free(p->z);
16514   p->z = 0;
16515 }
16516 
16517 /* Append a single byte to z[] */
16518 static void import_append_char(ImportCtx *p, int c){
16519   if( p->n+1>=p->nAlloc ){
16520     p->nAlloc += p->nAlloc + 100;
16521     p->z = sqlite3_realloc64(p->z, p->nAlloc);
16522     shell_check_oom(p->z);
16523   }
16524   p->z[p->n++] = (char)c;
16525 }
16526 
16527 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
16528 ** with the option of having a separator other than ",".
16529 **
16530 **   +  Input comes from p->in.
16531 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
16532 **      from sqlite3_malloc64().
16533 **   +  Use p->cSep as the column separator.  The default is ",".
16534 **   +  Use p->rSep as the row separator.  The default is "\n".
16535 **   +  Keep track of the line number in p->nLine.
16536 **   +  Store the character that terminates the field in p->cTerm.  Store
16537 **      EOF on end-of-file.
16538 **   +  Report syntax errors on stderr
16539 */
16540 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
16541   int c;
16542   int cSep = p->cColSep;
16543   int rSep = p->cRowSep;
16544   p->n = 0;
16545   c = fgetc(p->in);
16546   if( c==EOF || seenInterrupt ){
16547     p->cTerm = EOF;
16548     return 0;
16549   }
16550   if( c=='"' ){
16551     int pc, ppc;
16552     int startLine = p->nLine;
16553     int cQuote = c;
16554     pc = ppc = 0;
16555     while( 1 ){
16556       c = fgetc(p->in);
16557       if( c==rSep ) p->nLine++;
16558       if( c==cQuote ){
16559         if( pc==cQuote ){
16560           pc = 0;
16561           continue;
16562         }
16563       }
16564       if( (c==cSep && pc==cQuote)
16565        || (c==rSep && pc==cQuote)
16566        || (c==rSep && pc=='\r' && ppc==cQuote)
16567        || (c==EOF && pc==cQuote)
16568       ){
16569         do{ p->n--; }while( p->z[p->n]!=cQuote );
16570         p->cTerm = c;
16571         break;
16572       }
16573       if( pc==cQuote && c!='\r' ){
16574         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
16575                 p->zFile, p->nLine, cQuote);
16576       }
16577       if( c==EOF ){
16578         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
16579                 p->zFile, startLine, cQuote);
16580         p->cTerm = c;
16581         break;
16582       }
16583       import_append_char(p, c);
16584       ppc = pc;
16585       pc = c;
16586     }
16587   }else{
16588     /* If this is the first field being parsed and it begins with the
16589     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
16590     if( (c&0xff)==0xef && p->bNotFirst==0 ){
16591       import_append_char(p, c);
16592       c = fgetc(p->in);
16593       if( (c&0xff)==0xbb ){
16594         import_append_char(p, c);
16595         c = fgetc(p->in);
16596         if( (c&0xff)==0xbf ){
16597           p->bNotFirst = 1;
16598           p->n = 0;
16599           return csv_read_one_field(p);
16600         }
16601       }
16602     }
16603     while( c!=EOF && c!=cSep && c!=rSep ){
16604       import_append_char(p, c);
16605       c = fgetc(p->in);
16606     }
16607     if( c==rSep ){
16608       p->nLine++;
16609       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
16610     }
16611     p->cTerm = c;
16612   }
16613   if( p->z ) p->z[p->n] = 0;
16614   p->bNotFirst = 1;
16615   return p->z;
16616 }
16617 
16618 /* Read a single field of ASCII delimited text.
16619 **
16620 **   +  Input comes from p->in.
16621 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
16622 **      from sqlite3_malloc64().
16623 **   +  Use p->cSep as the column separator.  The default is "\x1F".
16624 **   +  Use p->rSep as the row separator.  The default is "\x1E".
16625 **   +  Keep track of the row number in p->nLine.
16626 **   +  Store the character that terminates the field in p->cTerm.  Store
16627 **      EOF on end-of-file.
16628 **   +  Report syntax errors on stderr
16629 */
16630 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
16631   int c;
16632   int cSep = p->cColSep;
16633   int rSep = p->cRowSep;
16634   p->n = 0;
16635   c = fgetc(p->in);
16636   if( c==EOF || seenInterrupt ){
16637     p->cTerm = EOF;
16638     return 0;
16639   }
16640   while( c!=EOF && c!=cSep && c!=rSep ){
16641     import_append_char(p, c);
16642     c = fgetc(p->in);
16643   }
16644   if( c==rSep ){
16645     p->nLine++;
16646   }
16647   p->cTerm = c;
16648   if( p->z ) p->z[p->n] = 0;
16649   return p->z;
16650 }
16651 
16652 /*
16653 ** Try to transfer data for table zTable.  If an error is seen while
16654 ** moving forward, try to go backwards.  The backwards movement won't
16655 ** work for WITHOUT ROWID tables.
16656 */
16657 static void tryToCloneData(
16658   ShellState *p,
16659   sqlite3 *newDb,
16660   const char *zTable
16661 ){
16662   sqlite3_stmt *pQuery = 0;
16663   sqlite3_stmt *pInsert = 0;
16664   char *zQuery = 0;
16665   char *zInsert = 0;
16666   int rc;
16667   int i, j, n;
16668   int nTable = strlen30(zTable);
16669   int k = 0;
16670   int cnt = 0;
16671   const int spinRate = 10000;
16672 
16673   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
16674   shell_check_oom(zQuery);
16675   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16676   if( rc ){
16677     utf8_printf(stderr, "Error %d: %s on [%s]\n",
16678             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
16679             zQuery);
16680     goto end_data_xfer;
16681   }
16682   n = sqlite3_column_count(pQuery);
16683   zInsert = sqlite3_malloc64(200 + nTable + n*3);
16684   shell_check_oom(zInsert);
16685   sqlite3_snprintf(200+nTable,zInsert,
16686                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
16687   i = strlen30(zInsert);
16688   for(j=1; j<n; j++){
16689     memcpy(zInsert+i, ",?", 2);
16690     i += 2;
16691   }
16692   memcpy(zInsert+i, ");", 3);
16693   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
16694   if( rc ){
16695     utf8_printf(stderr, "Error %d: %s on [%s]\n",
16696             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
16697             zQuery);
16698     goto end_data_xfer;
16699   }
16700   for(k=0; k<2; k++){
16701     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
16702       for(i=0; i<n; i++){
16703         switch( sqlite3_column_type(pQuery, i) ){
16704           case SQLITE_NULL: {
16705             sqlite3_bind_null(pInsert, i+1);
16706             break;
16707           }
16708           case SQLITE_INTEGER: {
16709             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
16710             break;
16711           }
16712           case SQLITE_FLOAT: {
16713             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
16714             break;
16715           }
16716           case SQLITE_TEXT: {
16717             sqlite3_bind_text(pInsert, i+1,
16718                              (const char*)sqlite3_column_text(pQuery,i),
16719                              -1, SQLITE_STATIC);
16720             break;
16721           }
16722           case SQLITE_BLOB: {
16723             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
16724                                             sqlite3_column_bytes(pQuery,i),
16725                                             SQLITE_STATIC);
16726             break;
16727           }
16728         }
16729       } /* End for */
16730       rc = sqlite3_step(pInsert);
16731       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
16732         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
16733                         sqlite3_errmsg(newDb));
16734       }
16735       sqlite3_reset(pInsert);
16736       cnt++;
16737       if( (cnt%spinRate)==0 ){
16738         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
16739         fflush(stdout);
16740       }
16741     } /* End while */
16742     if( rc==SQLITE_DONE ) break;
16743     sqlite3_finalize(pQuery);
16744     sqlite3_free(zQuery);
16745     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
16746                              zTable);
16747     shell_check_oom(zQuery);
16748     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16749     if( rc ){
16750       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
16751       break;
16752     }
16753   } /* End for(k=0...) */
16754 
16755 end_data_xfer:
16756   sqlite3_finalize(pQuery);
16757   sqlite3_finalize(pInsert);
16758   sqlite3_free(zQuery);
16759   sqlite3_free(zInsert);
16760 }
16761 
16762 
16763 /*
16764 ** Try to transfer all rows of the schema that match zWhere.  For
16765 ** each row, invoke xForEach() on the object defined by that row.
16766 ** If an error is encountered while moving forward through the
16767 ** sqlite_schema table, try again moving backwards.
16768 */
16769 static void tryToCloneSchema(
16770   ShellState *p,
16771   sqlite3 *newDb,
16772   const char *zWhere,
16773   void (*xForEach)(ShellState*,sqlite3*,const char*)
16774 ){
16775   sqlite3_stmt *pQuery = 0;
16776   char *zQuery = 0;
16777   int rc;
16778   const unsigned char *zName;
16779   const unsigned char *zSql;
16780   char *zErrMsg = 0;
16781 
16782   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
16783                            " WHERE %s", zWhere);
16784   shell_check_oom(zQuery);
16785   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16786   if( rc ){
16787     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
16788                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
16789                     zQuery);
16790     goto end_schema_xfer;
16791   }
16792   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
16793     zName = sqlite3_column_text(pQuery, 0);
16794     zSql = sqlite3_column_text(pQuery, 1);
16795     if( zName==0 || zSql==0 ) continue;
16796     printf("%s... ", zName); fflush(stdout);
16797     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
16798     if( zErrMsg ){
16799       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
16800       sqlite3_free(zErrMsg);
16801       zErrMsg = 0;
16802     }
16803     if( xForEach ){
16804       xForEach(p, newDb, (const char*)zName);
16805     }
16806     printf("done\n");
16807   }
16808   if( rc!=SQLITE_DONE ){
16809     sqlite3_finalize(pQuery);
16810     sqlite3_free(zQuery);
16811     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
16812                              " WHERE %s ORDER BY rowid DESC", zWhere);
16813     shell_check_oom(zQuery);
16814     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
16815     if( rc ){
16816       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
16817                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
16818                       zQuery);
16819       goto end_schema_xfer;
16820     }
16821     while( sqlite3_step(pQuery)==SQLITE_ROW ){
16822       zName = sqlite3_column_text(pQuery, 0);
16823       zSql = sqlite3_column_text(pQuery, 1);
16824       if( zName==0 || zSql==0 ) continue;
16825       printf("%s... ", zName); fflush(stdout);
16826       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
16827       if( zErrMsg ){
16828         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
16829         sqlite3_free(zErrMsg);
16830         zErrMsg = 0;
16831       }
16832       if( xForEach ){
16833         xForEach(p, newDb, (const char*)zName);
16834       }
16835       printf("done\n");
16836     }
16837   }
16838 end_schema_xfer:
16839   sqlite3_finalize(pQuery);
16840   sqlite3_free(zQuery);
16841 }
16842 
16843 /*
16844 ** Open a new database file named "zNewDb".  Try to recover as much information
16845 ** as possible out of the main database (which might be corrupt) and write it
16846 ** into zNewDb.
16847 */
16848 static void tryToClone(ShellState *p, const char *zNewDb){
16849   int rc;
16850   sqlite3 *newDb = 0;
16851   if( access(zNewDb,0)==0 ){
16852     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
16853     return;
16854   }
16855   rc = sqlite3_open(zNewDb, &newDb);
16856   if( rc ){
16857     utf8_printf(stderr, "Cannot create output database: %s\n",
16858             sqlite3_errmsg(newDb));
16859   }else{
16860     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
16861     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
16862     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
16863     tryToCloneSchema(p, newDb, "type!='table'", 0);
16864     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
16865     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
16866   }
16867   close_db(newDb);
16868 }
16869 
16870 /*
16871 ** Change the output file back to stdout.
16872 **
16873 ** If the p->doXdgOpen flag is set, that means the output was being
16874 ** redirected to a temporary file named by p->zTempFile.  In that case,
16875 ** launch start/open/xdg-open on that temporary file.
16876 */
16877 static void output_reset(ShellState *p){
16878   if( p->outfile[0]=='|' ){
16879 #ifndef SQLITE_OMIT_POPEN
16880     pclose(p->out);
16881 #endif
16882   }else{
16883     output_file_close(p->out);
16884 #ifndef SQLITE_NOHAVE_SYSTEM
16885     if( p->doXdgOpen ){
16886       const char *zXdgOpenCmd =
16887 #if defined(_WIN32)
16888       "start";
16889 #elif defined(__APPLE__)
16890       "open";
16891 #else
16892       "xdg-open";
16893 #endif
16894       char *zCmd;
16895       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
16896       if( system(zCmd) ){
16897         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
16898       }else{
16899         /* Give the start/open/xdg-open command some time to get
16900         ** going before we continue, and potential delete the
16901         ** p->zTempFile data file out from under it */
16902         sqlite3_sleep(2000);
16903       }
16904       sqlite3_free(zCmd);
16905       outputModePop(p);
16906       p->doXdgOpen = 0;
16907     }
16908 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
16909   }
16910   p->outfile[0] = 0;
16911   p->out = stdout;
16912 }
16913 
16914 /*
16915 ** Run an SQL command and return the single integer result.
16916 */
16917 static int db_int(sqlite3 *db, const char *zSql){
16918   sqlite3_stmt *pStmt;
16919   int res = 0;
16920   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
16921   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
16922     res = sqlite3_column_int(pStmt,0);
16923   }
16924   sqlite3_finalize(pStmt);
16925   return res;
16926 }
16927 
16928 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
16929 /*
16930 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
16931 */
16932 static unsigned int get2byteInt(unsigned char *a){
16933   return (a[0]<<8) + a[1];
16934 }
16935 static unsigned int get4byteInt(unsigned char *a){
16936   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
16937 }
16938 
16939 /*
16940 ** Implementation of the ".dbinfo" command.
16941 **
16942 ** Return 1 on error, 2 to exit, and 0 otherwise.
16943 */
16944 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
16945   static const struct { const char *zName; int ofst; } aField[] = {
16946      { "file change counter:",  24  },
16947      { "database page count:",  28  },
16948      { "freelist page count:",  36  },
16949      { "schema cookie:",        40  },
16950      { "schema format:",        44  },
16951      { "default cache size:",   48  },
16952      { "autovacuum top root:",  52  },
16953      { "incremental vacuum:",   64  },
16954      { "text encoding:",        56  },
16955      { "user version:",         60  },
16956      { "application id:",       68  },
16957      { "software version:",     96  },
16958   };
16959   static const struct { const char *zName; const char *zSql; } aQuery[] = {
16960      { "number of tables:",
16961        "SELECT count(*) FROM %s WHERE type='table'" },
16962      { "number of indexes:",
16963        "SELECT count(*) FROM %s WHERE type='index'" },
16964      { "number of triggers:",
16965        "SELECT count(*) FROM %s WHERE type='trigger'" },
16966      { "number of views:",
16967        "SELECT count(*) FROM %s WHERE type='view'" },
16968      { "schema size:",
16969        "SELECT total(length(sql)) FROM %s" },
16970   };
16971   int i, rc;
16972   unsigned iDataVersion;
16973   char *zSchemaTab;
16974   char *zDb = nArg>=2 ? azArg[1] : "main";
16975   sqlite3_stmt *pStmt = 0;
16976   unsigned char aHdr[100];
16977   open_db(p, 0);
16978   if( p->db==0 ) return 1;
16979   rc = sqlite3_prepare_v2(p->db,
16980              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
16981              -1, &pStmt, 0);
16982   if( rc ){
16983     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
16984     sqlite3_finalize(pStmt);
16985     return 1;
16986   }
16987   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
16988   if( sqlite3_step(pStmt)==SQLITE_ROW
16989    && sqlite3_column_bytes(pStmt,0)>100
16990   ){
16991     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
16992     sqlite3_finalize(pStmt);
16993   }else{
16994     raw_printf(stderr, "unable to read database header\n");
16995     sqlite3_finalize(pStmt);
16996     return 1;
16997   }
16998   i = get2byteInt(aHdr+16);
16999   if( i==1 ) i = 65536;
17000   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
17001   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
17002   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
17003   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
17004   for(i=0; i<ArraySize(aField); i++){
17005     int ofst = aField[i].ofst;
17006     unsigned int val = get4byteInt(aHdr + ofst);
17007     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
17008     switch( ofst ){
17009       case 56: {
17010         if( val==1 ) raw_printf(p->out, " (utf8)");
17011         if( val==2 ) raw_printf(p->out, " (utf16le)");
17012         if( val==3 ) raw_printf(p->out, " (utf16be)");
17013       }
17014     }
17015     raw_printf(p->out, "\n");
17016   }
17017   if( zDb==0 ){
17018     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
17019   }else if( strcmp(zDb,"temp")==0 ){
17020     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
17021   }else{
17022     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
17023   }
17024   for(i=0; i<ArraySize(aQuery); i++){
17025     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
17026     int val = db_int(p->db, zSql);
17027     sqlite3_free(zSql);
17028     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
17029   }
17030   sqlite3_free(zSchemaTab);
17031   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
17032   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
17033   return 0;
17034 }
17035 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
17036           && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
17037 
17038 /*
17039 ** Print the current sqlite3_errmsg() value to stderr and return 1.
17040 */
17041 static int shellDatabaseError(sqlite3 *db){
17042   const char *zErr = sqlite3_errmsg(db);
17043   utf8_printf(stderr, "Error: %s\n", zErr);
17044   return 1;
17045 }
17046 
17047 /*
17048 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
17049 ** if they match and FALSE (0) if they do not match.
17050 **
17051 ** Globbing rules:
17052 **
17053 **      '*'       Matches any sequence of zero or more characters.
17054 **
17055 **      '?'       Matches exactly one character.
17056 **
17057 **     [...]      Matches one character from the enclosed list of
17058 **                characters.
17059 **
17060 **     [^...]     Matches one character not in the enclosed list.
17061 **
17062 **      '#'       Matches any sequence of one or more digits with an
17063 **                optional + or - sign in front
17064 **
17065 **      ' '       Any span of whitespace matches any other span of
17066 **                whitespace.
17067 **
17068 ** Extra whitespace at the end of z[] is ignored.
17069 */
17070 static int testcase_glob(const char *zGlob, const char *z){
17071   int c, c2;
17072   int invert;
17073   int seen;
17074 
17075   while( (c = (*(zGlob++)))!=0 ){
17076     if( IsSpace(c) ){
17077       if( !IsSpace(*z) ) return 0;
17078       while( IsSpace(*zGlob) ) zGlob++;
17079       while( IsSpace(*z) ) z++;
17080     }else if( c=='*' ){
17081       while( (c=(*(zGlob++))) == '*' || c=='?' ){
17082         if( c=='?' && (*(z++))==0 ) return 0;
17083       }
17084       if( c==0 ){
17085         return 1;
17086       }else if( c=='[' ){
17087         while( *z && testcase_glob(zGlob-1,z)==0 ){
17088           z++;
17089         }
17090         return (*z)!=0;
17091       }
17092       while( (c2 = (*(z++)))!=0 ){
17093         while( c2!=c ){
17094           c2 = *(z++);
17095           if( c2==0 ) return 0;
17096         }
17097         if( testcase_glob(zGlob,z) ) return 1;
17098       }
17099       return 0;
17100     }else if( c=='?' ){
17101       if( (*(z++))==0 ) return 0;
17102     }else if( c=='[' ){
17103       int prior_c = 0;
17104       seen = 0;
17105       invert = 0;
17106       c = *(z++);
17107       if( c==0 ) return 0;
17108       c2 = *(zGlob++);
17109       if( c2=='^' ){
17110         invert = 1;
17111         c2 = *(zGlob++);
17112       }
17113       if( c2==']' ){
17114         if( c==']' ) seen = 1;
17115         c2 = *(zGlob++);
17116       }
17117       while( c2 && c2!=']' ){
17118         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
17119           c2 = *(zGlob++);
17120           if( c>=prior_c && c<=c2 ) seen = 1;
17121           prior_c = 0;
17122         }else{
17123           if( c==c2 ){
17124             seen = 1;
17125           }
17126           prior_c = c2;
17127         }
17128         c2 = *(zGlob++);
17129       }
17130       if( c2==0 || (seen ^ invert)==0 ) return 0;
17131     }else if( c=='#' ){
17132       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
17133       if( !IsDigit(z[0]) ) return 0;
17134       z++;
17135       while( IsDigit(z[0]) ){ z++; }
17136     }else{
17137       if( c!=(*(z++)) ) return 0;
17138     }
17139   }
17140   while( IsSpace(*z) ){ z++; }
17141   return *z==0;
17142 }
17143 
17144 
17145 /*
17146 ** Compare the string as a command-line option with either one or two
17147 ** initial "-" characters.
17148 */
17149 static int optionMatch(const char *zStr, const char *zOpt){
17150   if( zStr[0]!='-' ) return 0;
17151   zStr++;
17152   if( zStr[0]=='-' ) zStr++;
17153   return strcmp(zStr, zOpt)==0;
17154 }
17155 
17156 /*
17157 ** Delete a file.
17158 */
17159 int shellDeleteFile(const char *zFilename){
17160   int rc;
17161 #ifdef _WIN32
17162   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
17163   rc = _wunlink(z);
17164   sqlite3_free(z);
17165 #else
17166   rc = unlink(zFilename);
17167 #endif
17168   return rc;
17169 }
17170 
17171 /*
17172 ** Try to delete the temporary file (if there is one) and free the
17173 ** memory used to hold the name of the temp file.
17174 */
17175 static void clearTempFile(ShellState *p){
17176   if( p->zTempFile==0 ) return;
17177   if( p->doXdgOpen ) return;
17178   if( shellDeleteFile(p->zTempFile) ) return;
17179   sqlite3_free(p->zTempFile);
17180   p->zTempFile = 0;
17181 }
17182 
17183 /*
17184 ** Create a new temp file name with the given suffix.
17185 */
17186 static void newTempFile(ShellState *p, const char *zSuffix){
17187   clearTempFile(p);
17188   sqlite3_free(p->zTempFile);
17189   p->zTempFile = 0;
17190   if( p->db ){
17191     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
17192   }
17193   if( p->zTempFile==0 ){
17194     /* If p->db is an in-memory database then the TEMPFILENAME file-control
17195     ** will not work and we will need to fallback to guessing */
17196     char *zTemp;
17197     sqlite3_uint64 r;
17198     sqlite3_randomness(sizeof(r), &r);
17199     zTemp = getenv("TEMP");
17200     if( zTemp==0 ) zTemp = getenv("TMP");
17201     if( zTemp==0 ){
17202 #ifdef _WIN32
17203       zTemp = "\\tmp";
17204 #else
17205       zTemp = "/tmp";
17206 #endif
17207     }
17208     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
17209   }else{
17210     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
17211   }
17212   shell_check_oom(p->zTempFile);
17213 }
17214 
17215 
17216 /*
17217 ** The implementation of SQL scalar function fkey_collate_clause(), used
17218 ** by the ".lint fkey-indexes" command. This scalar function is always
17219 ** called with four arguments - the parent table name, the parent column name,
17220 ** the child table name and the child column name.
17221 **
17222 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
17223 **
17224 ** If either of the named tables or columns do not exist, this function
17225 ** returns an empty string. An empty string is also returned if both tables
17226 ** and columns exist but have the same default collation sequence. Or,
17227 ** if both exist but the default collation sequences are different, this
17228 ** function returns the string " COLLATE <parent-collation>", where
17229 ** <parent-collation> is the default collation sequence of the parent column.
17230 */
17231 static void shellFkeyCollateClause(
17232   sqlite3_context *pCtx,
17233   int nVal,
17234   sqlite3_value **apVal
17235 ){
17236   sqlite3 *db = sqlite3_context_db_handle(pCtx);
17237   const char *zParent;
17238   const char *zParentCol;
17239   const char *zParentSeq;
17240   const char *zChild;
17241   const char *zChildCol;
17242   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
17243   int rc;
17244 
17245   assert( nVal==4 );
17246   zParent = (const char*)sqlite3_value_text(apVal[0]);
17247   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
17248   zChild = (const char*)sqlite3_value_text(apVal[2]);
17249   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
17250 
17251   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
17252   rc = sqlite3_table_column_metadata(
17253       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
17254   );
17255   if( rc==SQLITE_OK ){
17256     rc = sqlite3_table_column_metadata(
17257         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
17258     );
17259   }
17260 
17261   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
17262     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
17263     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
17264     sqlite3_free(z);
17265   }
17266 }
17267 
17268 
17269 /*
17270 ** The implementation of dot-command ".lint fkey-indexes".
17271 */
17272 static int lintFkeyIndexes(
17273   ShellState *pState,             /* Current shell tool state */
17274   char **azArg,                   /* Array of arguments passed to dot command */
17275   int nArg                        /* Number of entries in azArg[] */
17276 ){
17277   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
17278   FILE *out = pState->out;        /* Stream to write non-error output to */
17279   int bVerbose = 0;               /* If -verbose is present */
17280   int bGroupByParent = 0;         /* If -groupbyparent is present */
17281   int i;                          /* To iterate through azArg[] */
17282   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
17283   int rc;                         /* Return code */
17284   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
17285 
17286   /*
17287   ** This SELECT statement returns one row for each foreign key constraint
17288   ** in the schema of the main database. The column values are:
17289   **
17290   ** 0. The text of an SQL statement similar to:
17291   **
17292   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
17293   **
17294   **    This SELECT is similar to the one that the foreign keys implementation
17295   **    needs to run internally on child tables. If there is an index that can
17296   **    be used to optimize this query, then it can also be used by the FK
17297   **    implementation to optimize DELETE or UPDATE statements on the parent
17298   **    table.
17299   **
17300   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
17301   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
17302   **    contains an index that can be used to optimize the query.
17303   **
17304   ** 2. Human readable text that describes the child table and columns. e.g.
17305   **
17306   **       "child_table(child_key1, child_key2)"
17307   **
17308   ** 3. Human readable text that describes the parent table and columns. e.g.
17309   **
17310   **       "parent_table(parent_key1, parent_key2)"
17311   **
17312   ** 4. A full CREATE INDEX statement for an index that could be used to
17313   **    optimize DELETE or UPDATE statements on the parent table. e.g.
17314   **
17315   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
17316   **
17317   ** 5. The name of the parent table.
17318   **
17319   ** These six values are used by the C logic below to generate the report.
17320   */
17321   const char *zSql =
17322   "SELECT "
17323     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
17324     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
17325     "  || fkey_collate_clause("
17326     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
17327     ", "
17328     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
17329     "  || group_concat('*=?', ' AND ') || ')'"
17330     ", "
17331     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
17332     ", "
17333     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
17334     ", "
17335     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
17336     "  || ' ON ' || quote(s.name) || '('"
17337     "  || group_concat(quote(f.[from]) ||"
17338     "        fkey_collate_clause("
17339     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
17340     "  || ');'"
17341     ", "
17342     "     f.[table] "
17343     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
17344     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
17345     "GROUP BY s.name, f.id "
17346     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
17347   ;
17348   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
17349 
17350   for(i=2; i<nArg; i++){
17351     int n = strlen30(azArg[i]);
17352     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
17353       bVerbose = 1;
17354     }
17355     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
17356       bGroupByParent = 1;
17357       zIndent = "    ";
17358     }
17359     else{
17360       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
17361           azArg[0], azArg[1]
17362       );
17363       return SQLITE_ERROR;
17364     }
17365   }
17366 
17367   /* Register the fkey_collate_clause() SQL function */
17368   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
17369       0, shellFkeyCollateClause, 0, 0
17370   );
17371 
17372 
17373   if( rc==SQLITE_OK ){
17374     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
17375   }
17376   if( rc==SQLITE_OK ){
17377     sqlite3_bind_int(pSql, 1, bGroupByParent);
17378   }
17379 
17380   if( rc==SQLITE_OK ){
17381     int rc2;
17382     char *zPrev = 0;
17383     while( SQLITE_ROW==sqlite3_step(pSql) ){
17384       int res = -1;
17385       sqlite3_stmt *pExplain = 0;
17386       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
17387       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
17388       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
17389       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
17390       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
17391       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
17392 
17393       if( zEQP==0 ) continue;
17394       if( zGlob==0 ) continue;
17395       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
17396       if( rc!=SQLITE_OK ) break;
17397       if( SQLITE_ROW==sqlite3_step(pExplain) ){
17398         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
17399         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
17400                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
17401       }
17402       rc = sqlite3_finalize(pExplain);
17403       if( rc!=SQLITE_OK ) break;
17404 
17405       if( res<0 ){
17406         raw_printf(stderr, "Error: internal error");
17407         break;
17408       }else{
17409         if( bGroupByParent
17410         && (bVerbose || res==0)
17411         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
17412         ){
17413           raw_printf(out, "-- Parent table %s\n", zParent);
17414           sqlite3_free(zPrev);
17415           zPrev = sqlite3_mprintf("%s", zParent);
17416         }
17417 
17418         if( res==0 ){
17419           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
17420         }else if( bVerbose ){
17421           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
17422               zIndent, zFrom, zTarget
17423           );
17424         }
17425       }
17426     }
17427     sqlite3_free(zPrev);
17428 
17429     if( rc!=SQLITE_OK ){
17430       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
17431     }
17432 
17433     rc2 = sqlite3_finalize(pSql);
17434     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
17435       rc = rc2;
17436       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
17437     }
17438   }else{
17439     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
17440   }
17441 
17442   return rc;
17443 }
17444 
17445 /*
17446 ** Implementation of ".lint" dot command.
17447 */
17448 static int lintDotCommand(
17449   ShellState *pState,             /* Current shell tool state */
17450   char **azArg,                   /* Array of arguments passed to dot command */
17451   int nArg                        /* Number of entries in azArg[] */
17452 ){
17453   int n;
17454   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
17455   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
17456   return lintFkeyIndexes(pState, azArg, nArg);
17457 
17458  usage:
17459   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
17460   raw_printf(stderr, "Where sub-commands are:\n");
17461   raw_printf(stderr, "    fkey-indexes\n");
17462   return SQLITE_ERROR;
17463 }
17464 
17465 #if !defined SQLITE_OMIT_VIRTUALTABLE
17466 static void shellPrepare(
17467   sqlite3 *db,
17468   int *pRc,
17469   const char *zSql,
17470   sqlite3_stmt **ppStmt
17471 ){
17472   *ppStmt = 0;
17473   if( *pRc==SQLITE_OK ){
17474     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
17475     if( rc!=SQLITE_OK ){
17476       raw_printf(stderr, "sql error: %s (%d)\n",
17477           sqlite3_errmsg(db), sqlite3_errcode(db)
17478       );
17479       *pRc = rc;
17480     }
17481   }
17482 }
17483 
17484 /*
17485 ** Create a prepared statement using printf-style arguments for the SQL.
17486 **
17487 ** This routine is could be marked "static".  But it is not always used,
17488 ** depending on compile-time options.  By omitting the "static", we avoid
17489 ** nuisance compiler warnings about "defined but not used".
17490 */
17491 void shellPreparePrintf(
17492   sqlite3 *db,
17493   int *pRc,
17494   sqlite3_stmt **ppStmt,
17495   const char *zFmt,
17496   ...
17497 ){
17498   *ppStmt = 0;
17499   if( *pRc==SQLITE_OK ){
17500     va_list ap;
17501     char *z;
17502     va_start(ap, zFmt);
17503     z = sqlite3_vmprintf(zFmt, ap);
17504     va_end(ap);
17505     if( z==0 ){
17506       *pRc = SQLITE_NOMEM;
17507     }else{
17508       shellPrepare(db, pRc, z, ppStmt);
17509       sqlite3_free(z);
17510     }
17511   }
17512 }
17513 
17514 /* Finalize the prepared statement created using shellPreparePrintf().
17515 **
17516 ** This routine is could be marked "static".  But it is not always used,
17517 ** depending on compile-time options.  By omitting the "static", we avoid
17518 ** nuisance compiler warnings about "defined but not used".
17519 */
17520 void shellFinalize(
17521   int *pRc,
17522   sqlite3_stmt *pStmt
17523 ){
17524   if( pStmt ){
17525     sqlite3 *db = sqlite3_db_handle(pStmt);
17526     int rc = sqlite3_finalize(pStmt);
17527     if( *pRc==SQLITE_OK ){
17528       if( rc!=SQLITE_OK ){
17529         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
17530       }
17531       *pRc = rc;
17532     }
17533   }
17534 }
17535 
17536 /* Reset the prepared statement created using shellPreparePrintf().
17537 **
17538 ** This routine is could be marked "static".  But it is not always used,
17539 ** depending on compile-time options.  By omitting the "static", we avoid
17540 ** nuisance compiler warnings about "defined but not used".
17541 */
17542 void shellReset(
17543   int *pRc,
17544   sqlite3_stmt *pStmt
17545 ){
17546   int rc = sqlite3_reset(pStmt);
17547   if( *pRc==SQLITE_OK ){
17548     if( rc!=SQLITE_OK ){
17549       sqlite3 *db = sqlite3_db_handle(pStmt);
17550       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
17551     }
17552     *pRc = rc;
17553   }
17554 }
17555 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
17556 
17557 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
17558 /******************************************************************************
17559 ** The ".archive" or ".ar" command.
17560 */
17561 /*
17562 ** Structure representing a single ".ar" command.
17563 */
17564 typedef struct ArCommand ArCommand;
17565 struct ArCommand {
17566   u8 eCmd;                        /* An AR_CMD_* value */
17567   u8 bVerbose;                    /* True if --verbose */
17568   u8 bZip;                        /* True if the archive is a ZIP */
17569   u8 bDryRun;                     /* True if --dry-run */
17570   u8 bAppend;                     /* True if --append */
17571   u8 bGlob;                       /* True if --glob */
17572   u8 fromCmdLine;                 /* Run from -A instead of .archive */
17573   int nArg;                       /* Number of command arguments */
17574   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
17575   const char *zFile;              /* --file argument, or NULL */
17576   const char *zDir;               /* --directory argument, or NULL */
17577   char **azArg;                   /* Array of command arguments */
17578   ShellState *p;                  /* Shell state */
17579   sqlite3 *db;                    /* Database containing the archive */
17580 };
17581 
17582 /*
17583 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
17584 */
17585 static int arUsage(FILE *f){
17586   showHelp(f,"archive");
17587   return SQLITE_ERROR;
17588 }
17589 
17590 /*
17591 ** Print an error message for the .ar command to stderr and return
17592 ** SQLITE_ERROR.
17593 */
17594 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
17595   va_list ap;
17596   char *z;
17597   va_start(ap, zFmt);
17598   z = sqlite3_vmprintf(zFmt, ap);
17599   va_end(ap);
17600   utf8_printf(stderr, "Error: %s\n", z);
17601   if( pAr->fromCmdLine ){
17602     utf8_printf(stderr, "Use \"-A\" for more help\n");
17603   }else{
17604     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
17605   }
17606   sqlite3_free(z);
17607   return SQLITE_ERROR;
17608 }
17609 
17610 /*
17611 ** Values for ArCommand.eCmd.
17612 */
17613 #define AR_CMD_CREATE       1
17614 #define AR_CMD_UPDATE       2
17615 #define AR_CMD_INSERT       3
17616 #define AR_CMD_EXTRACT      4
17617 #define AR_CMD_LIST         5
17618 #define AR_CMD_HELP         6
17619 #define AR_CMD_REMOVE       7
17620 
17621 /*
17622 ** Other (non-command) switches.
17623 */
17624 #define AR_SWITCH_VERBOSE     8
17625 #define AR_SWITCH_FILE        9
17626 #define AR_SWITCH_DIRECTORY  10
17627 #define AR_SWITCH_APPEND     11
17628 #define AR_SWITCH_DRYRUN     12
17629 #define AR_SWITCH_GLOB       13
17630 
17631 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
17632   switch( eSwitch ){
17633     case AR_CMD_CREATE:
17634     case AR_CMD_EXTRACT:
17635     case AR_CMD_LIST:
17636     case AR_CMD_REMOVE:
17637     case AR_CMD_UPDATE:
17638     case AR_CMD_INSERT:
17639     case AR_CMD_HELP:
17640       if( pAr->eCmd ){
17641         return arErrorMsg(pAr, "multiple command options");
17642       }
17643       pAr->eCmd = eSwitch;
17644       break;
17645 
17646     case AR_SWITCH_DRYRUN:
17647       pAr->bDryRun = 1;
17648       break;
17649     case AR_SWITCH_GLOB:
17650       pAr->bGlob = 1;
17651       break;
17652     case AR_SWITCH_VERBOSE:
17653       pAr->bVerbose = 1;
17654       break;
17655     case AR_SWITCH_APPEND:
17656       pAr->bAppend = 1;
17657       /* Fall thru into --file */
17658     case AR_SWITCH_FILE:
17659       pAr->zFile = zArg;
17660       break;
17661     case AR_SWITCH_DIRECTORY:
17662       pAr->zDir = zArg;
17663       break;
17664   }
17665 
17666   return SQLITE_OK;
17667 }
17668 
17669 /*
17670 ** Parse the command line for an ".ar" command. The results are written into
17671 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
17672 ** successfully, otherwise an error message is written to stderr and
17673 ** SQLITE_ERROR returned.
17674 */
17675 static int arParseCommand(
17676   char **azArg,                   /* Array of arguments passed to dot command */
17677   int nArg,                       /* Number of entries in azArg[] */
17678   ArCommand *pAr                  /* Populate this object */
17679 ){
17680   struct ArSwitch {
17681     const char *zLong;
17682     char cShort;
17683     u8 eSwitch;
17684     u8 bArg;
17685   } aSwitch[] = {
17686     { "create",    'c', AR_CMD_CREATE,       0 },
17687     { "extract",   'x', AR_CMD_EXTRACT,      0 },
17688     { "insert",    'i', AR_CMD_INSERT,       0 },
17689     { "list",      't', AR_CMD_LIST,         0 },
17690     { "remove",    'r', AR_CMD_REMOVE,       0 },
17691     { "update",    'u', AR_CMD_UPDATE,       0 },
17692     { "help",      'h', AR_CMD_HELP,         0 },
17693     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
17694     { "file",      'f', AR_SWITCH_FILE,      1 },
17695     { "append",    'a', AR_SWITCH_APPEND,    1 },
17696     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
17697     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
17698     { "glob",      'g', AR_SWITCH_GLOB,      0 },
17699   };
17700   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
17701   struct ArSwitch *pEnd = &aSwitch[nSwitch];
17702 
17703   if( nArg<=1 ){
17704     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
17705     return arUsage(stderr);
17706   }else{
17707     char *z = azArg[1];
17708     if( z[0]!='-' ){
17709       /* Traditional style [tar] invocation */
17710       int i;
17711       int iArg = 2;
17712       for(i=0; z[i]; i++){
17713         const char *zArg = 0;
17714         struct ArSwitch *pOpt;
17715         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
17716           if( z[i]==pOpt->cShort ) break;
17717         }
17718         if( pOpt==pEnd ){
17719           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
17720         }
17721         if( pOpt->bArg ){
17722           if( iArg>=nArg ){
17723             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
17724           }
17725           zArg = azArg[iArg++];
17726         }
17727         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
17728       }
17729       pAr->nArg = nArg-iArg;
17730       if( pAr->nArg>0 ){
17731         pAr->azArg = &azArg[iArg];
17732       }
17733     }else{
17734       /* Non-traditional invocation */
17735       int iArg;
17736       for(iArg=1; iArg<nArg; iArg++){
17737         int n;
17738         z = azArg[iArg];
17739         if( z[0]!='-' ){
17740           /* All remaining command line words are command arguments. */
17741           pAr->azArg = &azArg[iArg];
17742           pAr->nArg = nArg-iArg;
17743           break;
17744         }
17745         n = strlen30(z);
17746 
17747         if( z[1]!='-' ){
17748           int i;
17749           /* One or more short options */
17750           for(i=1; i<n; i++){
17751             const char *zArg = 0;
17752             struct ArSwitch *pOpt;
17753             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
17754               if( z[i]==pOpt->cShort ) break;
17755             }
17756             if( pOpt==pEnd ){
17757               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
17758             }
17759             if( pOpt->bArg ){
17760               if( i<(n-1) ){
17761                 zArg = &z[i+1];
17762                 i = n;
17763               }else{
17764                 if( iArg>=(nArg-1) ){
17765                   return arErrorMsg(pAr, "option requires an argument: %c",
17766                                     z[i]);
17767                 }
17768                 zArg = azArg[++iArg];
17769               }
17770             }
17771             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
17772           }
17773         }else if( z[2]=='\0' ){
17774           /* A -- option, indicating that all remaining command line words
17775           ** are command arguments.  */
17776           pAr->azArg = &azArg[iArg+1];
17777           pAr->nArg = nArg-iArg-1;
17778           break;
17779         }else{
17780           /* A long option */
17781           const char *zArg = 0;             /* Argument for option, if any */
17782           struct ArSwitch *pMatch = 0;      /* Matching option */
17783           struct ArSwitch *pOpt;            /* Iterator */
17784           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
17785             const char *zLong = pOpt->zLong;
17786             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
17787               if( pMatch ){
17788                 return arErrorMsg(pAr, "ambiguous option: %s",z);
17789               }else{
17790                 pMatch = pOpt;
17791               }
17792             }
17793           }
17794 
17795           if( pMatch==0 ){
17796             return arErrorMsg(pAr, "unrecognized option: %s", z);
17797           }
17798           if( pMatch->bArg ){
17799             if( iArg>=(nArg-1) ){
17800               return arErrorMsg(pAr, "option requires an argument: %s", z);
17801             }
17802             zArg = azArg[++iArg];
17803           }
17804           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
17805         }
17806       }
17807     }
17808   }
17809 
17810   return SQLITE_OK;
17811 }
17812 
17813 /*
17814 ** This function assumes that all arguments within the ArCommand.azArg[]
17815 ** array refer to archive members, as for the --extract, --list or --remove
17816 ** commands. It checks that each of them are "present". If any specified
17817 ** file is not present in the archive, an error is printed to stderr and an
17818 ** error code returned. Otherwise, if all specified arguments are present
17819 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
17820 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
17821 ** when pAr->bGlob is true.
17822 **
17823 ** This function strips any trailing '/' characters from each argument.
17824 ** This is consistent with the way the [tar] command seems to work on
17825 ** Linux.
17826 */
17827 static int arCheckEntries(ArCommand *pAr){
17828   int rc = SQLITE_OK;
17829   if( pAr->nArg ){
17830     int i, j;
17831     sqlite3_stmt *pTest = 0;
17832     const char *zSel = (pAr->bGlob)
17833       ? "SELECT name FROM %s WHERE glob($name,name)"
17834       : "SELECT name FROM %s WHERE name=$name";
17835 
17836     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
17837     j = sqlite3_bind_parameter_index(pTest, "$name");
17838     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
17839       char *z = pAr->azArg[i];
17840       int n = strlen30(z);
17841       int bOk = 0;
17842       while( n>0 && z[n-1]=='/' ) n--;
17843       z[n] = '\0';
17844       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
17845       if( SQLITE_ROW==sqlite3_step(pTest) ){
17846         bOk = 1;
17847       }
17848       shellReset(&rc, pTest);
17849       if( rc==SQLITE_OK && bOk==0 ){
17850         utf8_printf(stderr, "not found in archive: %s\n", z);
17851         rc = SQLITE_ERROR;
17852       }
17853     }
17854     shellFinalize(&rc, pTest);
17855   }
17856   return rc;
17857 }
17858 
17859 /*
17860 ** Format a WHERE clause that can be used against the "sqlar" table to
17861 ** identify all archive members that match the command arguments held
17862 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
17863 ** The caller is responsible for eventually calling sqlite3_free() on
17864 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
17865 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
17866 */
17867 static void arWhereClause(
17868   int *pRc,
17869   ArCommand *pAr,
17870   char **pzWhere                  /* OUT: New WHERE clause */
17871 ){
17872   char *zWhere = 0;
17873   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
17874   if( *pRc==SQLITE_OK ){
17875     if( pAr->nArg==0 ){
17876       zWhere = sqlite3_mprintf("1");
17877     }else{
17878       int i;
17879       const char *zSep = "";
17880       for(i=0; i<pAr->nArg; i++){
17881         const char *z = pAr->azArg[i];
17882         zWhere = sqlite3_mprintf(
17883           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
17884           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
17885         );
17886         if( zWhere==0 ){
17887           *pRc = SQLITE_NOMEM;
17888           break;
17889         }
17890         zSep = " OR ";
17891       }
17892     }
17893   }
17894   *pzWhere = zWhere;
17895 }
17896 
17897 /*
17898 ** Implementation of .ar "lisT" command.
17899 */
17900 static int arListCommand(ArCommand *pAr){
17901   const char *zSql = "SELECT %s FROM %s WHERE %s";
17902   const char *azCols[] = {
17903     "name",
17904     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
17905   };
17906 
17907   char *zWhere = 0;
17908   sqlite3_stmt *pSql = 0;
17909   int rc;
17910 
17911   rc = arCheckEntries(pAr);
17912   arWhereClause(&rc, pAr, &zWhere);
17913 
17914   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
17915                      pAr->zSrcTable, zWhere);
17916   if( pAr->bDryRun ){
17917     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
17918   }else{
17919     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
17920       if( pAr->bVerbose ){
17921         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
17922             sqlite3_column_text(pSql, 0),
17923             sqlite3_column_int(pSql, 1),
17924             sqlite3_column_text(pSql, 2),
17925             sqlite3_column_text(pSql, 3)
17926         );
17927       }else{
17928         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
17929       }
17930     }
17931   }
17932   shellFinalize(&rc, pSql);
17933   sqlite3_free(zWhere);
17934   return rc;
17935 }
17936 
17937 
17938 /*
17939 ** Implementation of .ar "Remove" command.
17940 */
17941 static int arRemoveCommand(ArCommand *pAr){
17942   int rc = 0;
17943   char *zSql = 0;
17944   char *zWhere = 0;
17945 
17946   if( pAr->nArg ){
17947     /* Verify that args actually exist within the archive before proceeding.
17948     ** And formulate a WHERE clause to match them.  */
17949     rc = arCheckEntries(pAr);
17950     arWhereClause(&rc, pAr, &zWhere);
17951   }
17952   if( rc==SQLITE_OK ){
17953     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
17954                            pAr->zSrcTable, zWhere);
17955     if( pAr->bDryRun ){
17956       utf8_printf(pAr->p->out, "%s\n", zSql);
17957     }else{
17958       char *zErr = 0;
17959       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
17960       if( rc==SQLITE_OK ){
17961         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
17962         if( rc!=SQLITE_OK ){
17963           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
17964         }else{
17965           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
17966         }
17967       }
17968       if( zErr ){
17969         utf8_printf(stdout, "ERROR: %s\n", zErr);
17970         sqlite3_free(zErr);
17971       }
17972     }
17973   }
17974   sqlite3_free(zWhere);
17975   sqlite3_free(zSql);
17976   return rc;
17977 }
17978 
17979 /*
17980 ** Implementation of .ar "eXtract" command.
17981 */
17982 static int arExtractCommand(ArCommand *pAr){
17983   const char *zSql1 =
17984     "SELECT "
17985     " ($dir || name),"
17986     " writefile(($dir || name), %s, mode, mtime) "
17987     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
17988     " AND name NOT GLOB '*..[/\\]*'";
17989 
17990   const char *azExtraArg[] = {
17991     "sqlar_uncompress(data, sz)",
17992     "data"
17993   };
17994 
17995   sqlite3_stmt *pSql = 0;
17996   int rc = SQLITE_OK;
17997   char *zDir = 0;
17998   char *zWhere = 0;
17999   int i, j;
18000 
18001   /* If arguments are specified, check that they actually exist within
18002   ** the archive before proceeding. And formulate a WHERE clause to
18003   ** match them.  */
18004   rc = arCheckEntries(pAr);
18005   arWhereClause(&rc, pAr, &zWhere);
18006 
18007   if( rc==SQLITE_OK ){
18008     if( pAr->zDir ){
18009       zDir = sqlite3_mprintf("%s/", pAr->zDir);
18010     }else{
18011       zDir = sqlite3_mprintf("");
18012     }
18013     if( zDir==0 ) rc = SQLITE_NOMEM;
18014   }
18015 
18016   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
18017       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
18018   );
18019 
18020   if( rc==SQLITE_OK ){
18021     j = sqlite3_bind_parameter_index(pSql, "$dir");
18022     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
18023 
18024     /* Run the SELECT statement twice. The first time, writefile() is called
18025     ** for all archive members that should be extracted. The second time,
18026     ** only for the directories. This is because the timestamps for
18027     ** extracted directories must be reset after they are populated (as
18028     ** populating them changes the timestamp).  */
18029     for(i=0; i<2; i++){
18030       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
18031       sqlite3_bind_int(pSql, j, i);
18032       if( pAr->bDryRun ){
18033         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
18034       }else{
18035         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
18036           if( i==0 && pAr->bVerbose ){
18037             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
18038           }
18039         }
18040       }
18041       shellReset(&rc, pSql);
18042     }
18043     shellFinalize(&rc, pSql);
18044   }
18045 
18046   sqlite3_free(zDir);
18047   sqlite3_free(zWhere);
18048   return rc;
18049 }
18050 
18051 /*
18052 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
18053 */
18054 static int arExecSql(ArCommand *pAr, const char *zSql){
18055   int rc;
18056   if( pAr->bDryRun ){
18057     utf8_printf(pAr->p->out, "%s\n", zSql);
18058     rc = SQLITE_OK;
18059   }else{
18060     char *zErr = 0;
18061     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
18062     if( zErr ){
18063       utf8_printf(stdout, "ERROR: %s\n", zErr);
18064       sqlite3_free(zErr);
18065     }
18066   }
18067   return rc;
18068 }
18069 
18070 
18071 /*
18072 ** Implementation of .ar "create", "insert", and "update" commands.
18073 **
18074 **     create    ->     Create a new SQL archive
18075 **     insert    ->     Insert or reinsert all files listed
18076 **     update    ->     Insert files that have changed or that were not
18077 **                      previously in the archive
18078 **
18079 ** Create the "sqlar" table in the database if it does not already exist.
18080 ** Then add each file in the azFile[] array to the archive. Directories
18081 ** are added recursively. If argument bVerbose is non-zero, a message is
18082 ** printed on stdout for each file archived.
18083 **
18084 ** The create command is the same as update, except that it drops
18085 ** any existing "sqlar" table before beginning.  The "insert" command
18086 ** always overwrites every file named on the command-line, where as
18087 ** "update" only overwrites if the size or mtime or mode has changed.
18088 */
18089 static int arCreateOrUpdateCommand(
18090   ArCommand *pAr,                 /* Command arguments and options */
18091   int bUpdate,                    /* true for a --create. */
18092   int bOnlyIfChanged              /* Only update if file has changed */
18093 ){
18094   const char *zCreate =
18095       "CREATE TABLE IF NOT EXISTS sqlar(\n"
18096       "  name TEXT PRIMARY KEY,  -- name of the file\n"
18097       "  mode INT,               -- access permissions\n"
18098       "  mtime INT,              -- last modification time\n"
18099       "  sz INT,                 -- original file size\n"
18100       "  data BLOB               -- compressed content\n"
18101       ")";
18102   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
18103   const char *zInsertFmt[2] = {
18104      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
18105      "  SELECT\n"
18106      "    %s,\n"
18107      "    mode,\n"
18108      "    mtime,\n"
18109      "    CASE substr(lsmode(mode),1,1)\n"
18110      "      WHEN '-' THEN length(data)\n"
18111      "      WHEN 'd' THEN 0\n"
18112      "      ELSE -1 END,\n"
18113      "    sqlar_compress(data)\n"
18114      "  FROM fsdir(%Q,%Q) AS disk\n"
18115      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
18116      ,
18117      "REPLACE INTO %s(name,mode,mtime,data)\n"
18118      "  SELECT\n"
18119      "    %s,\n"
18120      "    mode,\n"
18121      "    mtime,\n"
18122      "    data\n"
18123      "  FROM fsdir(%Q,%Q) AS disk\n"
18124      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
18125   };
18126   int i;                          /* For iterating through azFile[] */
18127   int rc;                         /* Return code */
18128   const char *zTab = 0;           /* SQL table into which to insert */
18129   char *zSql;
18130   char zTemp[50];
18131   char *zExists = 0;
18132 
18133   arExecSql(pAr, "PRAGMA page_size=512");
18134   rc = arExecSql(pAr, "SAVEPOINT ar;");
18135   if( rc!=SQLITE_OK ) return rc;
18136   zTemp[0] = 0;
18137   if( pAr->bZip ){
18138     /* Initialize the zipfile virtual table, if necessary */
18139     if( pAr->zFile ){
18140       sqlite3_uint64 r;
18141       sqlite3_randomness(sizeof(r),&r);
18142       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
18143       zTab = zTemp;
18144       zSql = sqlite3_mprintf(
18145          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
18146          zTab, pAr->zFile
18147       );
18148       rc = arExecSql(pAr, zSql);
18149       sqlite3_free(zSql);
18150     }else{
18151       zTab = "zip";
18152     }
18153   }else{
18154     /* Initialize the table for an SQLAR */
18155     zTab = "sqlar";
18156     if( bUpdate==0 ){
18157       rc = arExecSql(pAr, zDrop);
18158       if( rc!=SQLITE_OK ) goto end_ar_transaction;
18159     }
18160     rc = arExecSql(pAr, zCreate);
18161   }
18162   if( bOnlyIfChanged ){
18163     zExists = sqlite3_mprintf(
18164       " AND NOT EXISTS("
18165           "SELECT 1 FROM %s AS mem"
18166           " WHERE mem.name=disk.name"
18167           " AND mem.mtime=disk.mtime"
18168           " AND mem.mode=disk.mode)", zTab);
18169   }else{
18170     zExists = sqlite3_mprintf("");
18171   }
18172   if( zExists==0 ) rc = SQLITE_NOMEM;
18173   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
18174     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
18175         pAr->bVerbose ? "shell_putsnl(name)" : "name",
18176         pAr->azArg[i], pAr->zDir, zExists);
18177     rc = arExecSql(pAr, zSql2);
18178     sqlite3_free(zSql2);
18179   }
18180 end_ar_transaction:
18181   if( rc!=SQLITE_OK ){
18182     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
18183   }else{
18184     rc = arExecSql(pAr, "RELEASE ar;");
18185     if( pAr->bZip && pAr->zFile ){
18186       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
18187       arExecSql(pAr, zSql);
18188       sqlite3_free(zSql);
18189     }
18190   }
18191   sqlite3_free(zExists);
18192   return rc;
18193 }
18194 
18195 /*
18196 ** Implementation of ".ar" dot command.
18197 */
18198 static int arDotCommand(
18199   ShellState *pState,          /* Current shell tool state */
18200   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
18201   char **azArg,                /* Array of arguments passed to dot command */
18202   int nArg                     /* Number of entries in azArg[] */
18203 ){
18204   ArCommand cmd;
18205   int rc;
18206   memset(&cmd, 0, sizeof(cmd));
18207   cmd.fromCmdLine = fromCmdLine;
18208   rc = arParseCommand(azArg, nArg, &cmd);
18209   if( rc==SQLITE_OK ){
18210     int eDbType = SHELL_OPEN_UNSPEC;
18211     cmd.p = pState;
18212     cmd.db = pState->db;
18213     if( cmd.zFile ){
18214       eDbType = deduceDatabaseType(cmd.zFile, 1);
18215     }else{
18216       eDbType = pState->openMode;
18217     }
18218     if( eDbType==SHELL_OPEN_ZIPFILE ){
18219       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
18220         if( cmd.zFile==0 ){
18221           cmd.zSrcTable = sqlite3_mprintf("zip");
18222         }else{
18223           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
18224         }
18225       }
18226       cmd.bZip = 1;
18227     }else if( cmd.zFile ){
18228       int flags;
18229       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
18230       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
18231            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
18232         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
18233       }else{
18234         flags = SQLITE_OPEN_READONLY;
18235       }
18236       cmd.db = 0;
18237       if( cmd.bDryRun ){
18238         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
18239              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
18240       }
18241       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
18242              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
18243       if( rc!=SQLITE_OK ){
18244         utf8_printf(stderr, "cannot open file: %s (%s)\n",
18245             cmd.zFile, sqlite3_errmsg(cmd.db)
18246         );
18247         goto end_ar_command;
18248       }
18249       sqlite3_fileio_init(cmd.db, 0, 0);
18250       sqlite3_sqlar_init(cmd.db, 0, 0);
18251       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
18252                               shellPutsFunc, 0, 0);
18253 
18254     }
18255     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
18256       if( cmd.eCmd!=AR_CMD_CREATE
18257        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
18258       ){
18259         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
18260         rc = SQLITE_ERROR;
18261         goto end_ar_command;
18262       }
18263       cmd.zSrcTable = sqlite3_mprintf("sqlar");
18264     }
18265 
18266     switch( cmd.eCmd ){
18267       case AR_CMD_CREATE:
18268         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
18269         break;
18270 
18271       case AR_CMD_EXTRACT:
18272         rc = arExtractCommand(&cmd);
18273         break;
18274 
18275       case AR_CMD_LIST:
18276         rc = arListCommand(&cmd);
18277         break;
18278 
18279       case AR_CMD_HELP:
18280         arUsage(pState->out);
18281         break;
18282 
18283       case AR_CMD_INSERT:
18284         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
18285         break;
18286 
18287       case AR_CMD_REMOVE:
18288         rc = arRemoveCommand(&cmd);
18289         break;
18290 
18291       default:
18292         assert( cmd.eCmd==AR_CMD_UPDATE );
18293         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
18294         break;
18295     }
18296   }
18297 end_ar_command:
18298   if( cmd.db!=pState->db ){
18299     close_db(cmd.db);
18300   }
18301   sqlite3_free(cmd.zSrcTable);
18302 
18303   return rc;
18304 }
18305 /* End of the ".archive" or ".ar" command logic
18306 *******************************************************************************/
18307 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
18308 
18309 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
18310 /*
18311 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
18312 ** Otherwise, the SQL statement or statements in zSql are executed using
18313 ** database connection db and the error code written to *pRc before
18314 ** this function returns.
18315 */
18316 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
18317   int rc = *pRc;
18318   if( rc==SQLITE_OK ){
18319     char *zErr = 0;
18320     rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
18321     if( rc!=SQLITE_OK ){
18322       raw_printf(stderr, "SQL error: %s\n", zErr);
18323     }
18324     sqlite3_free(zErr);
18325     *pRc = rc;
18326   }
18327 }
18328 
18329 /*
18330 ** Like shellExec(), except that zFmt is a printf() style format string.
18331 */
18332 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
18333   char *z = 0;
18334   if( *pRc==SQLITE_OK ){
18335     va_list ap;
18336     va_start(ap, zFmt);
18337     z = sqlite3_vmprintf(zFmt, ap);
18338     va_end(ap);
18339     if( z==0 ){
18340       *pRc = SQLITE_NOMEM;
18341     }else{
18342       shellExec(db, pRc, z);
18343     }
18344     sqlite3_free(z);
18345   }
18346 }
18347 
18348 /*
18349 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
18350 ** Otherwise, an attempt is made to allocate, zero and return a pointer
18351 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
18352 ** to SQLITE_NOMEM and NULL returned.
18353 */
18354 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
18355   void *pRet = 0;
18356   if( *pRc==SQLITE_OK ){
18357     pRet = sqlite3_malloc64(nByte);
18358     if( pRet==0 ){
18359       *pRc = SQLITE_NOMEM;
18360     }else{
18361       memset(pRet, 0, nByte);
18362     }
18363   }
18364   return pRet;
18365 }
18366 
18367 /*
18368 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
18369 ** Otherwise, zFmt is treated as a printf() style string. The result of
18370 ** formatting it along with any trailing arguments is written into a
18371 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
18372 ** It is the responsibility of the caller to eventually free this buffer
18373 ** using a call to sqlite3_free().
18374 **
18375 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
18376 ** pointer returned.
18377 */
18378 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
18379   char *z = 0;
18380   if( *pRc==SQLITE_OK ){
18381     va_list ap;
18382     va_start(ap, zFmt);
18383     z = sqlite3_vmprintf(zFmt, ap);
18384     va_end(ap);
18385     if( z==0 ){
18386       *pRc = SQLITE_NOMEM;
18387     }
18388   }
18389   return z;
18390 }
18391 
18392 
18393 /*
18394 ** When running the ".recover" command, each output table, and the special
18395 ** orphaned row table if it is required, is represented by an instance
18396 ** of the following struct.
18397 */
18398 typedef struct RecoverTable RecoverTable;
18399 struct RecoverTable {
18400   char *zQuoted;                  /* Quoted version of table name */
18401   int nCol;                       /* Number of columns in table */
18402   char **azlCol;                  /* Array of column lists */
18403   int iPk;                        /* Index of IPK column */
18404 };
18405 
18406 /*
18407 ** Free a RecoverTable object allocated by recoverFindTable() or
18408 ** recoverOrphanTable().
18409 */
18410 static void recoverFreeTable(RecoverTable *pTab){
18411   if( pTab ){
18412     sqlite3_free(pTab->zQuoted);
18413     if( pTab->azlCol ){
18414       int i;
18415       for(i=0; i<=pTab->nCol; i++){
18416         sqlite3_free(pTab->azlCol[i]);
18417       }
18418       sqlite3_free(pTab->azlCol);
18419     }
18420     sqlite3_free(pTab);
18421   }
18422 }
18423 
18424 /*
18425 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
18426 ** Otherwise, it allocates and returns a RecoverTable object based on the
18427 ** final four arguments passed to this function. It is the responsibility
18428 ** of the caller to eventually free the returned object using
18429 ** recoverFreeTable().
18430 */
18431 static RecoverTable *recoverNewTable(
18432   int *pRc,                       /* IN/OUT: Error code */
18433   const char *zName,              /* Name of table */
18434   const char *zSql,               /* CREATE TABLE statement */
18435   int bIntkey,
18436   int nCol
18437 ){
18438   sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
18439   int rc = *pRc;
18440   RecoverTable *pTab = 0;
18441 
18442   pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
18443   if( rc==SQLITE_OK ){
18444     int nSqlCol = 0;
18445     int bSqlIntkey = 0;
18446     sqlite3_stmt *pStmt = 0;
18447 
18448     rc = sqlite3_open("", &dbtmp);
18449     if( rc==SQLITE_OK ){
18450       sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
18451                               shellIdQuote, 0, 0);
18452     }
18453     if( rc==SQLITE_OK ){
18454       rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
18455     }
18456     if( rc==SQLITE_OK ){
18457       rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
18458       if( rc==SQLITE_ERROR ){
18459         rc = SQLITE_OK;
18460         goto finished;
18461       }
18462     }
18463     shellPreparePrintf(dbtmp, &rc, &pStmt,
18464         "SELECT count(*) FROM pragma_table_info(%Q)", zName
18465     );
18466     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18467       nSqlCol = sqlite3_column_int(pStmt, 0);
18468     }
18469     shellFinalize(&rc, pStmt);
18470 
18471     if( rc!=SQLITE_OK || nSqlCol<nCol ){
18472       goto finished;
18473     }
18474 
18475     shellPreparePrintf(dbtmp, &rc, &pStmt,
18476       "SELECT ("
18477       "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
18478       ") FROM sqlite_schema WHERE name = %Q", zName
18479     );
18480     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18481       bSqlIntkey = sqlite3_column_int(pStmt, 0);
18482     }
18483     shellFinalize(&rc, pStmt);
18484 
18485     if( bIntkey==bSqlIntkey ){
18486       int i;
18487       const char *zPk = "_rowid_";
18488       sqlite3_stmt *pPkFinder = 0;
18489 
18490       /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
18491       ** set zPk to the name of the PK column, and pTab->iPk to the index
18492       ** of the column, where columns are 0-numbered from left to right.
18493       ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
18494       ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
18495       pTab->iPk = -2;
18496       if( bIntkey ){
18497         shellPreparePrintf(dbtmp, &rc, &pPkFinder,
18498           "SELECT cid, name FROM pragma_table_info(%Q) "
18499           "  WHERE pk=1 AND type='integer' COLLATE nocase"
18500           "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
18501           , zName, zName
18502         );
18503         if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
18504           pTab->iPk = sqlite3_column_int(pPkFinder, 0);
18505           zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
18506           if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
18507         }
18508       }
18509 
18510       pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
18511       pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
18512       pTab->nCol = nSqlCol;
18513 
18514       if( bIntkey ){
18515         pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
18516       }else{
18517         pTab->azlCol[0] = shellMPrintf(&rc, "");
18518       }
18519       i = 1;
18520       shellPreparePrintf(dbtmp, &rc, &pStmt,
18521           "SELECT %Q || group_concat(shell_idquote(name), ', ') "
18522           "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
18523           "FROM pragma_table_info(%Q)",
18524           bIntkey ? ", " : "", pTab->iPk,
18525           bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
18526           zName
18527       );
18528       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18529         const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
18530         pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
18531         i++;
18532       }
18533       shellFinalize(&rc, pStmt);
18534 
18535       shellFinalize(&rc, pPkFinder);
18536     }
18537   }
18538 
18539  finished:
18540   sqlite3_close(dbtmp);
18541   *pRc = rc;
18542   if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
18543     recoverFreeTable(pTab);
18544     pTab = 0;
18545   }
18546   return pTab;
18547 }
18548 
18549 /*
18550 ** This function is called to search the schema recovered from the
18551 ** sqlite_schema table of the (possibly) corrupt database as part
18552 ** of a ".recover" command. Specifically, for a table with root page
18553 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
18554 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
18555 ** those.
18556 **
18557 ** If a table is found, a (RecoverTable*) object is returned. Or, if
18558 ** no such table is found, but bIntkey is false and iRoot is the
18559 ** root page of an index in the recovered schema, then (*pbNoop) is
18560 ** set to true and NULL returned. Or, if there is no such table or
18561 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
18562 ** the caller should write data to the orphans table.
18563 */
18564 static RecoverTable *recoverFindTable(
18565   ShellState *pState,             /* Shell state object */
18566   int *pRc,                       /* IN/OUT: Error code */
18567   int iRoot,                      /* Root page of table */
18568   int bIntkey,                    /* True for an intkey table */
18569   int nCol,                       /* Number of columns in table */
18570   int *pbNoop                     /* OUT: True if iRoot is root of index */
18571 ){
18572   sqlite3_stmt *pStmt = 0;
18573   RecoverTable *pRet = 0;
18574   int bNoop = 0;
18575   const char *zSql = 0;
18576   const char *zName = 0;
18577 
18578   /* Search the recovered schema for an object with root page iRoot. */
18579   shellPreparePrintf(pState->db, pRc, &pStmt,
18580       "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
18581   );
18582   while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18583     const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
18584     if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
18585       bNoop = 1;
18586       break;
18587     }
18588     if( sqlite3_stricmp(zType, "table")==0 ){
18589       zName = (const char*)sqlite3_column_text(pStmt, 1);
18590       zSql = (const char*)sqlite3_column_text(pStmt, 2);
18591       if( zName!=0 && zSql!=0 ){
18592         pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
18593         break;
18594       }
18595     }
18596   }
18597 
18598   shellFinalize(pRc, pStmt);
18599   *pbNoop = bNoop;
18600   return pRet;
18601 }
18602 
18603 /*
18604 ** Return a RecoverTable object representing the orphans table.
18605 */
18606 static RecoverTable *recoverOrphanTable(
18607   ShellState *pState,             /* Shell state object */
18608   int *pRc,                       /* IN/OUT: Error code */
18609   const char *zLostAndFound,      /* Base name for orphans table */
18610   int nCol                        /* Number of user data columns */
18611 ){
18612   RecoverTable *pTab = 0;
18613   if( nCol>=0 && *pRc==SQLITE_OK ){
18614     int i;
18615 
18616     /* This block determines the name of the orphan table. The prefered
18617     ** name is zLostAndFound. But if that clashes with another name
18618     ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
18619     ** and so on until a non-clashing name is found.  */
18620     int iTab = 0;
18621     char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
18622     sqlite3_stmt *pTest = 0;
18623     shellPrepare(pState->db, pRc,
18624         "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
18625     );
18626     if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
18627     while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
18628       shellReset(pRc, pTest);
18629       sqlite3_free(zTab);
18630       zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
18631       sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
18632     }
18633     shellFinalize(pRc, pTest);
18634 
18635     pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
18636     if( pTab ){
18637       pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
18638       pTab->nCol = nCol;
18639       pTab->iPk = -2;
18640       if( nCol>0 ){
18641         pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
18642         if( pTab->azlCol ){
18643           pTab->azlCol[nCol] = shellMPrintf(pRc, "");
18644           for(i=nCol-1; i>=0; i--){
18645             pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
18646           }
18647         }
18648       }
18649 
18650       if( *pRc!=SQLITE_OK ){
18651         recoverFreeTable(pTab);
18652         pTab = 0;
18653       }else{
18654         raw_printf(pState->out,
18655             "CREATE TABLE %s(rootpgno INTEGER, "
18656             "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
18657         );
18658         for(i=0; i<nCol; i++){
18659           raw_printf(pState->out, ", c%d", i);
18660         }
18661         raw_printf(pState->out, ");\n");
18662       }
18663     }
18664     sqlite3_free(zTab);
18665   }
18666   return pTab;
18667 }
18668 
18669 /*
18670 ** This function is called to recover data from the database. A script
18671 ** to construct a new database containing all recovered data is output
18672 ** on stream pState->out.
18673 */
18674 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
18675   int rc = SQLITE_OK;
18676   sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
18677   sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
18678   sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
18679   const char *zRecoveryDb = "";   /* Name of "recovery" database */
18680   const char *zLostAndFound = "lost_and_found";
18681   int i;
18682   int nOrphan = -1;
18683   RecoverTable *pOrphan = 0;
18684 
18685   int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
18686   int bRowids = 1;                /* 0 if --no-rowids */
18687   for(i=1; i<nArg; i++){
18688     char *z = azArg[i];
18689     int n;
18690     if( z[0]=='-' && z[1]=='-' ) z++;
18691     n = strlen30(z);
18692     if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
18693       bFreelist = 0;
18694     }else
18695     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
18696       i++;
18697       zRecoveryDb = azArg[i];
18698     }else
18699     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
18700       i++;
18701       zLostAndFound = azArg[i];
18702     }else
18703     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
18704       bRowids = 0;
18705     }
18706     else{
18707       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
18708       showHelp(pState->out, azArg[0]);
18709       return 1;
18710     }
18711   }
18712 
18713   shellExecPrintf(pState->db, &rc,
18714     /* Attach an in-memory database named 'recovery'. Create an indexed
18715     ** cache of the sqlite_dbptr virtual table. */
18716     "PRAGMA writable_schema = on;"
18717     "ATTACH %Q AS recovery;"
18718     "DROP TABLE IF EXISTS recovery.dbptr;"
18719     "DROP TABLE IF EXISTS recovery.freelist;"
18720     "DROP TABLE IF EXISTS recovery.map;"
18721     "DROP TABLE IF EXISTS recovery.schema;"
18722     "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
18723   );
18724 
18725   if( bFreelist ){
18726     shellExec(pState->db, &rc,
18727       "WITH trunk(pgno) AS ("
18728       "  SELECT shell_int32("
18729       "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
18730       "      WHERE x>0"
18731       "    UNION"
18732       "  SELECT shell_int32("
18733       "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
18734       "      FROM trunk WHERE x>0"
18735       "),"
18736       "freelist(data, n, freepgno) AS ("
18737       "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
18738       "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
18739       "    UNION ALL"
18740       "  SELECT data, n-1, shell_int32(data, 2+n) "
18741       "      FROM freelist WHERE n>=0"
18742       ")"
18743       "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
18744     );
18745   }
18746 
18747   /* If this is an auto-vacuum database, add all pointer-map pages to
18748   ** the freelist table. Do this regardless of whether or not
18749   ** --freelist-corrupt was specified.  */
18750   shellExec(pState->db, &rc,
18751     "WITH ptrmap(pgno) AS ("
18752     "  SELECT 2 WHERE shell_int32("
18753     "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
18754     "  )"
18755     "    UNION ALL "
18756     "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
18757     "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
18758     ")"
18759     "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
18760   );
18761 
18762   shellExec(pState->db, &rc,
18763     "CREATE TABLE recovery.dbptr("
18764     "      pgno, child, PRIMARY KEY(child, pgno)"
18765     ") WITHOUT ROWID;"
18766     "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
18767     "    SELECT * FROM sqlite_dbptr"
18768     "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
18769 
18770     /* Delete any pointer to page 1. This ensures that page 1 is considered
18771     ** a root page, regardless of how corrupt the db is. */
18772     "DELETE FROM recovery.dbptr WHERE child = 1;"
18773 
18774     /* Delete all pointers to any pages that have more than one pointer
18775     ** to them. Such pages will be treated as root pages when recovering
18776     ** data.  */
18777     "DELETE FROM recovery.dbptr WHERE child IN ("
18778     "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
18779     ");"
18780 
18781     /* Create the "map" table that will (eventually) contain instructions
18782     ** for dealing with each page in the db that contains one or more
18783     ** records. */
18784     "CREATE TABLE recovery.map("
18785       "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
18786     ");"
18787 
18788     /* Populate table [map]. If there are circular loops of pages in the
18789     ** database, the following adds all pages in such a loop to the map
18790     ** as individual root pages. This could be handled better.  */
18791     "WITH pages(i, maxlen) AS ("
18792     "  SELECT page_count, ("
18793     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
18794     "  ) FROM pragma_page_count WHERE page_count>0"
18795     "    UNION ALL"
18796     "  SELECT i-1, ("
18797     "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
18798     "  ) FROM pages WHERE i>=2"
18799     ")"
18800     "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
18801     "  SELECT i, maxlen, NULL, ("
18802     "    WITH p(orig, pgno, parent) AS ("
18803     "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
18804     "        UNION "
18805     "      SELECT i, p.parent, "
18806     "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
18807     "    )"
18808     "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
18809     ") "
18810     "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
18811     "UPDATE recovery.map AS o SET intkey = ("
18812     "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
18813     ");"
18814 
18815     /* Extract data from page 1 and any linked pages into table
18816     ** recovery.schema. With the same schema as an sqlite_schema table.  */
18817     "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
18818     "INSERT INTO recovery.schema SELECT "
18819     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
18820     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
18821     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
18822     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
18823     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
18824     "FROM sqlite_dbdata WHERE pgno IN ("
18825     "  SELECT pgno FROM recovery.map WHERE root=1"
18826     ")"
18827     "GROUP BY pgno, cell;"
18828     "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
18829   );
18830 
18831   /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
18832   ** CREATE TABLE statements that extracted from the existing schema.  */
18833   if( rc==SQLITE_OK ){
18834     sqlite3_stmt *pStmt = 0;
18835     /* ".recover" might output content in an order which causes immediate
18836     ** foreign key constraints to be violated. So disable foreign-key
18837     ** constraint enforcement to prevent problems when running the output
18838     ** script. */
18839     raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
18840     raw_printf(pState->out, "BEGIN;\n");
18841     raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
18842     shellPrepare(pState->db, &rc,
18843         "SELECT sql FROM recovery.schema "
18844         "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
18845     );
18846     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18847       const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
18848       raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
18849           &zCreateTable[12]
18850       );
18851     }
18852     shellFinalize(&rc, pStmt);
18853   }
18854 
18855   /* Figure out if an orphan table will be required. And if so, how many
18856   ** user columns it should contain */
18857   shellPrepare(pState->db, &rc,
18858       "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
18859       , &pLoop
18860   );
18861   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
18862     nOrphan = sqlite3_column_int(pLoop, 0);
18863   }
18864   shellFinalize(&rc, pLoop);
18865   pLoop = 0;
18866 
18867   shellPrepare(pState->db, &rc,
18868       "SELECT pgno FROM recovery.map WHERE root=?", &pPages
18869   );
18870 
18871   shellPrepare(pState->db, &rc,
18872       "SELECT max(field), group_concat(shell_escape_crnl(quote"
18873       "(case when (? AND field<0) then NULL else value end)"
18874       "), ', ')"
18875       ", min(field) "
18876       "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
18877       "GROUP BY cell", &pCells
18878   );
18879 
18880   /* Loop through each root page. */
18881   shellPrepare(pState->db, &rc,
18882       "SELECT root, intkey, max(maxlen) FROM recovery.map"
18883       " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
18884       "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
18885       ")", &pLoop
18886   );
18887   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
18888     int iRoot = sqlite3_column_int(pLoop, 0);
18889     int bIntkey = sqlite3_column_int(pLoop, 1);
18890     int nCol = sqlite3_column_int(pLoop, 2);
18891     int bNoop = 0;
18892     RecoverTable *pTab;
18893 
18894     assert( bIntkey==0 || bIntkey==1 );
18895     pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
18896     if( bNoop || rc ) continue;
18897     if( pTab==0 ){
18898       if( pOrphan==0 ){
18899         pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
18900       }
18901       pTab = pOrphan;
18902       if( pTab==0 ) break;
18903     }
18904 
18905     if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
18906       raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
18907     }
18908     sqlite3_bind_int(pPages, 1, iRoot);
18909     if( bRowids==0 && pTab->iPk<0 ){
18910       sqlite3_bind_int(pCells, 1, 1);
18911     }else{
18912       sqlite3_bind_int(pCells, 1, 0);
18913     }
18914     sqlite3_bind_int(pCells, 3, pTab->iPk);
18915 
18916     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
18917       int iPgno = sqlite3_column_int(pPages, 0);
18918       sqlite3_bind_int(pCells, 2, iPgno);
18919       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
18920         int nField = sqlite3_column_int(pCells, 0);
18921         int iMin = sqlite3_column_int(pCells, 2);
18922         const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
18923 
18924         RecoverTable *pTab2 = pTab;
18925         if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
18926           if( pOrphan==0 ){
18927             pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
18928           }
18929           pTab2 = pOrphan;
18930           if( pTab2==0 ) break;
18931         }
18932 
18933         nField = nField+1;
18934         if( pTab2==pOrphan ){
18935           raw_printf(pState->out,
18936               "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
18937               pTab2->zQuoted, iRoot, iPgno, nField,
18938               iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
18939           );
18940         }else{
18941           raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
18942               pTab2->zQuoted, pTab2->azlCol[nField], zVal
18943           );
18944         }
18945       }
18946       shellReset(&rc, pCells);
18947     }
18948     shellReset(&rc, pPages);
18949     if( pTab!=pOrphan ) recoverFreeTable(pTab);
18950   }
18951   shellFinalize(&rc, pLoop);
18952   shellFinalize(&rc, pPages);
18953   shellFinalize(&rc, pCells);
18954   recoverFreeTable(pOrphan);
18955 
18956   /* The rest of the schema */
18957   if( rc==SQLITE_OK ){
18958     sqlite3_stmt *pStmt = 0;
18959     shellPrepare(pState->db, &rc,
18960         "SELECT sql, name FROM recovery.schema "
18961         "WHERE sql NOT LIKE 'create table%'", &pStmt
18962     );
18963     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
18964       const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
18965       if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
18966         const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
18967         char *zPrint = shellMPrintf(&rc,
18968           "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
18969           zName, zName, zSql
18970         );
18971         raw_printf(pState->out, "%s;\n", zPrint);
18972         sqlite3_free(zPrint);
18973       }else{
18974         raw_printf(pState->out, "%s;\n", zSql);
18975       }
18976     }
18977     shellFinalize(&rc, pStmt);
18978   }
18979 
18980   if( rc==SQLITE_OK ){
18981     raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
18982     raw_printf(pState->out, "COMMIT;\n");
18983   }
18984   sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
18985   return rc;
18986 }
18987 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
18988 
18989 
18990 /*
18991  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
18992  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
18993  *   close db and set it to 0, and return the columns spec, to later
18994  *   be sqlite3_free()'ed by the caller.
18995  * The return is 0 when either:
18996  *   (a) The db was not initialized and zCol==0 (There are no columns.)
18997  *   (b) zCol!=0  (Column was added, db initialized as needed.)
18998  * The 3rd argument, pRenamed, references an out parameter. If the
18999  * pointer is non-zero, its referent will be set to a summary of renames
19000  * done if renaming was necessary, or set to 0 if none was done. The out
19001  * string (if any) must be sqlite3_free()'ed by the caller.
19002  */
19003 #ifdef SHELL_DEBUG
19004 #define rc_err_oom_die(rc) \
19005   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
19006   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
19007     fprintf(stderr,"E:%d\n",rc), assert(0)
19008 #else
19009 static void rc_err_oom_die(int rc){
19010   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
19011   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
19012 }
19013 #endif
19014 
19015 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
19016 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
19017 #else  /* Otherwise, memory is faster/better for the transient DB. */
19018 static const char *zCOL_DB = ":memory:";
19019 #endif
19020 
19021 /* Define character (as C string) to separate generated column ordinal
19022  * from protected part of incoming column names. This defaults to "_"
19023  * so that incoming column identifiers that did not need not be quoted
19024  * remain usable without being quoted. It must be one character.
19025  */
19026 #ifndef SHELL_AUTOCOLUMN_SEP
19027 # define AUTOCOLUMN_SEP "_"
19028 #else
19029 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
19030 #endif
19031 
19032 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
19033   /* Queries and D{D,M}L used here */
19034   static const char * const zTabMake = "\
19035 CREATE TABLE ColNames(\
19036  cpos INTEGER PRIMARY KEY,\
19037  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
19038 CREATE VIEW RepeatedNames AS \
19039 SELECT DISTINCT t.name FROM ColNames t \
19040 WHERE t.name COLLATE NOCASE IN (\
19041  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
19042 );\
19043 ";
19044   static const char * const zTabFill = "\
19045 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
19046  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
19047 ";
19048   static const char * const zHasDupes = "\
19049 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
19050  <count(name) FROM ColNames\
19051 ";
19052 #ifdef SHELL_COLUMN_RENAME_CLEAN
19053   static const char * const zDedoctor = "\
19054 UPDATE ColNames SET chop=iif(\
19055   (substring(name,nlen,1) BETWEEN '0' AND '9')\
19056   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
19057  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
19058  0\
19059 )\
19060 ";
19061 #endif
19062   static const char * const zSetReps = "\
19063 UPDATE ColNames AS t SET reps=\
19064 (SELECT count(*) FROM ColNames d \
19065  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
19066  COLLATE NOCASE\
19067 )\
19068 ";
19069 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
19070   static const char * const zColDigits = "\
19071 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
19072 ";
19073 #else
19074   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
19075   static const char * const zColDigits = "\
19076 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
19077  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
19078  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
19079 ";
19080 #endif
19081   static const char * const zRenameRank =
19082 #ifdef SHELL_COLUMN_RENAME_CLEAN
19083     "UPDATE ColNames AS t SET suff="
19084     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
19085 #else /* ...RENAME_MINIMAL_ONE_PASS */
19086 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
19087 "  SELECT 0 AS nlz"
19088 "  UNION"
19089 "  SELECT nlz+1 AS nlz FROM Lzn"
19090 "  WHERE EXISTS("
19091 "   SELECT 1"
19092 "   FROM ColNames t, ColNames o"
19093 "   WHERE"
19094 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
19095 "     printf('%s"AUTOCOLUMN_SEP"%s',"
19096 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
19097 "     t.name"
19098 "    )"
19099 "    ="
19100 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
19101 "     printf('%s"AUTOCOLUMN_SEP"%s',"
19102 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
19103 "     o.name"
19104 "    )"
19105 "    COLLATE NOCASE"
19106 "    AND o.cpos<>t.cpos"
19107 "   GROUP BY t.cpos"
19108 "  )"
19109 ") UPDATE Colnames AS t SET"
19110 " chop = 0," /* No chopping, never touch incoming names. */
19111 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
19112 "  printf('"AUTOCOLUMN_SEP"%s', substring("
19113 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
19114 "  ''"
19115 " )"
19116 #endif
19117     ;
19118   static const char * const zCollectVar = "\
19119 SELECT\
19120  '('||x'0a'\
19121  || group_concat(\
19122   cname||' TEXT',\
19123   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
19124  ||')' AS ColsSpec \
19125 FROM (\
19126  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
19127  FROM ColNames ORDER BY cpos\
19128 )";
19129   static const char * const zRenamesDone =
19130     "SELECT group_concat("
19131     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
19132     " ','||x'0a')"
19133     "FROM ColNames WHERE suff<>'' OR chop!=0"
19134     ;
19135   int rc;
19136   sqlite3_stmt *pStmt = 0;
19137   assert(pDb!=0);
19138   if( zColNew ){
19139     /* Add initial or additional column. Init db if necessary. */
19140     if( *pDb==0 ){
19141       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
19142 #ifdef SHELL_COLFIX_DB
19143       if(*zCOL_DB!=':')
19144         sqlite3_exec(*pDb,"drop table if exists ColNames;"
19145                      "drop view if exists RepeatedNames;",0,0,0);
19146 #endif
19147       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
19148       rc_err_oom_die(rc);
19149     }
19150     assert(*pDb!=0);
19151     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
19152     rc_err_oom_die(rc);
19153     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
19154     rc_err_oom_die(rc);
19155     rc = sqlite3_step(pStmt);
19156     rc_err_oom_die(rc);
19157     sqlite3_finalize(pStmt);
19158     return 0;
19159   }else if( *pDb==0 ){
19160     return 0;
19161   }else{
19162     /* Formulate the columns spec, close the DB, zero *pDb. */
19163     char *zColsSpec = 0;
19164     int hasDupes = db_int(*pDb, zHasDupes);
19165     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
19166     if( hasDupes ){
19167 #ifdef SHELL_COLUMN_RENAME_CLEAN
19168       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
19169       rc_err_oom_die(rc);
19170 #endif
19171       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
19172       rc_err_oom_die(rc);
19173       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
19174       rc_err_oom_die(rc);
19175       sqlite3_bind_int(pStmt, 1, nDigits);
19176       rc = sqlite3_step(pStmt);
19177       sqlite3_finalize(pStmt);
19178       assert(rc==SQLITE_DONE);
19179     }
19180     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
19181     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
19182     rc_err_oom_die(rc);
19183     rc = sqlite3_step(pStmt);
19184     if( rc==SQLITE_ROW ){
19185       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
19186     }else{
19187       zColsSpec = 0;
19188     }
19189     if( pzRenamed!=0 ){
19190       if( !hasDupes ) *pzRenamed = 0;
19191       else{
19192         sqlite3_finalize(pStmt);
19193         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
19194             && SQLITE_ROW==sqlite3_step(pStmt) ){
19195           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
19196         }else
19197           *pzRenamed = 0;
19198       }
19199     }
19200     sqlite3_finalize(pStmt);
19201     sqlite3_close(*pDb);
19202     *pDb = 0;
19203     return zColsSpec;
19204   }
19205 }
19206 
19207 /*
19208 ** If an input line begins with "." then invoke this routine to
19209 ** process that line.
19210 **
19211 ** Return 1 on error, 2 to exit, and 0 otherwise.
19212 */
19213 static int do_meta_command(char *zLine, ShellState *p){
19214   int h = 1;
19215   int nArg = 0;
19216   int n, c;
19217   int rc = 0;
19218   char *azArg[52];
19219 
19220 #ifndef SQLITE_OMIT_VIRTUALTABLE
19221   if( p->expert.pExpert ){
19222     expertFinish(p, 1, 0);
19223   }
19224 #endif
19225 
19226   /* Parse the input line into tokens.
19227   */
19228   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
19229     while( IsSpace(zLine[h]) ){ h++; }
19230     if( zLine[h]==0 ) break;
19231     if( zLine[h]=='\'' || zLine[h]=='"' ){
19232       int delim = zLine[h++];
19233       azArg[nArg++] = &zLine[h];
19234       while( zLine[h] && zLine[h]!=delim ){
19235         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
19236         h++;
19237       }
19238       if( zLine[h]==delim ){
19239         zLine[h++] = 0;
19240       }
19241       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
19242     }else{
19243       azArg[nArg++] = &zLine[h];
19244       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
19245       if( zLine[h] ) zLine[h++] = 0;
19246       resolve_backslashes(azArg[nArg-1]);
19247     }
19248   }
19249   azArg[nArg] = 0;
19250 
19251   /* Process the input line.
19252   */
19253   if( nArg==0 ) return 0; /* no tokens, no error */
19254   n = strlen30(azArg[0]);
19255   c = azArg[0][0];
19256   clearTempFile(p);
19257 
19258 #ifndef SQLITE_OMIT_AUTHORIZATION
19259   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
19260     if( nArg!=2 ){
19261       raw_printf(stderr, "Usage: .auth ON|OFF\n");
19262       rc = 1;
19263       goto meta_command_exit;
19264     }
19265     open_db(p, 0);
19266     if( booleanValue(azArg[1]) ){
19267       sqlite3_set_authorizer(p->db, shellAuth, p);
19268     }else if( p->bSafeModePersist ){
19269       sqlite3_set_authorizer(p->db, safeModeAuth, p);
19270     }else{
19271       sqlite3_set_authorizer(p->db, 0, 0);
19272     }
19273   }else
19274 #endif
19275 
19276 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
19277   && !defined(SQLITE_SHELL_WASM_MODE)
19278   if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
19279     open_db(p, 0);
19280     failIfSafeMode(p, "cannot run .archive in safe mode");
19281     rc = arDotCommand(p, 0, azArg, nArg);
19282   }else
19283 #endif
19284 
19285 #ifndef SQLITE_SHELL_WASM_MODE
19286   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
19287    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
19288   ){
19289     const char *zDestFile = 0;
19290     const char *zDb = 0;
19291     sqlite3 *pDest;
19292     sqlite3_backup *pBackup;
19293     int j;
19294     int bAsync = 0;
19295     const char *zVfs = 0;
19296     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
19297     for(j=1; j<nArg; j++){
19298       const char *z = azArg[j];
19299       if( z[0]=='-' ){
19300         if( z[1]=='-' ) z++;
19301         if( strcmp(z, "-append")==0 ){
19302           zVfs = "apndvfs";
19303         }else
19304         if( strcmp(z, "-async")==0 ){
19305           bAsync = 1;
19306         }else
19307         {
19308           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
19309           return 1;
19310         }
19311       }else if( zDestFile==0 ){
19312         zDestFile = azArg[j];
19313       }else if( zDb==0 ){
19314         zDb = zDestFile;
19315         zDestFile = azArg[j];
19316       }else{
19317         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
19318         return 1;
19319       }
19320     }
19321     if( zDestFile==0 ){
19322       raw_printf(stderr, "missing FILENAME argument on .backup\n");
19323       return 1;
19324     }
19325     if( zDb==0 ) zDb = "main";
19326     rc = sqlite3_open_v2(zDestFile, &pDest,
19327                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
19328     if( rc!=SQLITE_OK ){
19329       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
19330       close_db(pDest);
19331       return 1;
19332     }
19333     if( bAsync ){
19334       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
19335                    0, 0, 0);
19336     }
19337     open_db(p, 0);
19338     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
19339     if( pBackup==0 ){
19340       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
19341       close_db(pDest);
19342       return 1;
19343     }
19344     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
19345     sqlite3_backup_finish(pBackup);
19346     if( rc==SQLITE_DONE ){
19347       rc = 0;
19348     }else{
19349       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
19350       rc = 1;
19351     }
19352     close_db(pDest);
19353   }else
19354 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
19355 
19356   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
19357     if( nArg==2 ){
19358       bail_on_error = booleanValue(azArg[1]);
19359     }else{
19360       raw_printf(stderr, "Usage: .bail on|off\n");
19361       rc = 1;
19362     }
19363   }else
19364 
19365   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
19366     if( nArg==2 ){
19367       if( booleanValue(azArg[1]) ){
19368         setBinaryMode(p->out, 1);
19369       }else{
19370         setTextMode(p->out, 1);
19371       }
19372     }else{
19373       raw_printf(stderr, "Usage: .binary on|off\n");
19374       rc = 1;
19375     }
19376   }else
19377 
19378   /* The undocumented ".breakpoint" command causes a call to the no-op
19379   ** routine named test_breakpoint().
19380   */
19381   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
19382     test_breakpoint();
19383   }else
19384 
19385 #ifndef SQLITE_SHELL_WASM_MODE
19386   if( c=='c' && strcmp(azArg[0],"cd")==0 ){
19387     failIfSafeMode(p, "cannot run .cd in safe mode");
19388     if( nArg==2 ){
19389 #if defined(_WIN32) || defined(WIN32)
19390       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
19391       rc = !SetCurrentDirectoryW(z);
19392       sqlite3_free(z);
19393 #else
19394       rc = chdir(azArg[1]);
19395 #endif
19396       if( rc ){
19397         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
19398         rc = 1;
19399       }
19400     }else{
19401       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
19402       rc = 1;
19403     }
19404   }else
19405 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
19406 
19407   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
19408     if( nArg==2 ){
19409       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
19410     }else{
19411       raw_printf(stderr, "Usage: .changes on|off\n");
19412       rc = 1;
19413     }
19414   }else
19415 
19416 #ifndef SQLITE_SHELL_WASM_MODE
19417   /* Cancel output redirection, if it is currently set (by .testcase)
19418   ** Then read the content of the testcase-out.txt file and compare against
19419   ** azArg[1].  If there are differences, report an error and exit.
19420   */
19421   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
19422     char *zRes = 0;
19423     output_reset(p);
19424     if( nArg!=2 ){
19425       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
19426       rc = 2;
19427     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
19428       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
19429       rc = 2;
19430     }else if( testcase_glob(azArg[1],zRes)==0 ){
19431       utf8_printf(stderr,
19432                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
19433                  p->zTestcase, azArg[1], zRes);
19434       rc = 1;
19435     }else{
19436       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
19437       p->nCheck++;
19438     }
19439     sqlite3_free(zRes);
19440   }else
19441 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
19442 
19443 #ifndef SQLITE_SHELL_WASM_MODE
19444   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
19445     failIfSafeMode(p, "cannot run .clone in safe mode");
19446     if( nArg==2 ){
19447       tryToClone(p, azArg[1]);
19448     }else{
19449       raw_printf(stderr, "Usage: .clone FILENAME\n");
19450       rc = 1;
19451     }
19452   }else
19453 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
19454 
19455   if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
19456     if( nArg==1 ){
19457       /* List available connections */
19458       int i;
19459       for(i=0; i<ArraySize(p->aAuxDb); i++){
19460         const char *zFile = p->aAuxDb[i].zDbFilename;
19461         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
19462           zFile = "(not open)";
19463         }else if( zFile==0 ){
19464           zFile = "(memory)";
19465         }else if( zFile[0]==0 ){
19466           zFile = "(temporary-file)";
19467         }
19468         if( p->pAuxDb == &p->aAuxDb[i] ){
19469           utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
19470         }else if( p->aAuxDb[i].db!=0 ){
19471           utf8_printf(stdout, "       %d: %s\n", i, zFile);
19472         }
19473       }
19474     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
19475       int i = azArg[1][0] - '0';
19476       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
19477         p->pAuxDb->db = p->db;
19478         p->pAuxDb = &p->aAuxDb[i];
19479         globalDb = p->db = p->pAuxDb->db;
19480         p->pAuxDb->db = 0;
19481       }
19482     }else if( nArg==3 && strcmp(azArg[1], "close")==0
19483            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
19484       int i = azArg[2][0] - '0';
19485       if( i<0 || i>=ArraySize(p->aAuxDb) ){
19486         /* No-op */
19487       }else if( p->pAuxDb == &p->aAuxDb[i] ){
19488         raw_printf(stderr, "cannot close the active database connection\n");
19489         rc = 1;
19490       }else if( p->aAuxDb[i].db ){
19491         session_close_all(p, i);
19492         close_db(p->aAuxDb[i].db);
19493         p->aAuxDb[i].db = 0;
19494       }
19495     }else{
19496       raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
19497       rc = 1;
19498     }
19499   }else
19500 
19501   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
19502     char **azName = 0;
19503     int nName = 0;
19504     sqlite3_stmt *pStmt;
19505     int i;
19506     open_db(p, 0);
19507     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
19508     if( rc ){
19509       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
19510       rc = 1;
19511     }else{
19512       while( sqlite3_step(pStmt)==SQLITE_ROW ){
19513         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
19514         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
19515         if( zSchema==0 || zFile==0 ) continue;
19516         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
19517         shell_check_oom(azName);
19518         azName[nName*2] = strdup(zSchema);
19519         azName[nName*2+1] = strdup(zFile);
19520         nName++;
19521       }
19522     }
19523     sqlite3_finalize(pStmt);
19524     for(i=0; i<nName; i++){
19525       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
19526       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
19527       const char *z = azName[i*2+1];
19528       utf8_printf(p->out, "%s: %s %s%s\n",
19529          azName[i*2],
19530          z && z[0] ? z : "\"\"",
19531          bRdonly ? "r/o" : "r/w",
19532          eTxn==SQLITE_TXN_NONE ? "" :
19533             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
19534       free(azName[i*2]);
19535       free(azName[i*2+1]);
19536     }
19537     sqlite3_free(azName);
19538   }else
19539 
19540   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
19541     static const struct DbConfigChoices {
19542       const char *zName;
19543       int op;
19544     } aDbConfig[] = {
19545         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
19546         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
19547         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
19548         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
19549         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
19550         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
19551         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
19552         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
19553         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
19554         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
19555         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
19556         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
19557         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
19558         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
19559         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
19560         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
19561     };
19562     int ii, v;
19563     open_db(p, 0);
19564     for(ii=0; ii<ArraySize(aDbConfig); ii++){
19565       if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
19566       if( nArg>=3 ){
19567         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
19568       }
19569       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
19570       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
19571       if( nArg>1 ) break;
19572     }
19573     if( nArg>1 && ii==ArraySize(aDbConfig) ){
19574       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
19575       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
19576     }
19577   }else
19578 
19579 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
19580   if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
19581     rc = shell_dbinfo_command(p, nArg, azArg);
19582   }else
19583 
19584   if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
19585     open_db(p, 0);
19586     rc = recoverDatabaseCmd(p, nArg, azArg);
19587   }else
19588 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
19589 
19590   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
19591     char *zLike = 0;
19592     char *zSql;
19593     int i;
19594     int savedShowHeader = p->showHeader;
19595     int savedShellFlags = p->shellFlgs;
19596     ShellClearFlag(p,
19597        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
19598        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
19599     for(i=1; i<nArg; i++){
19600       if( azArg[i][0]=='-' ){
19601         const char *z = azArg[i]+1;
19602         if( z[0]=='-' ) z++;
19603         if( strcmp(z,"preserve-rowids")==0 ){
19604 #ifdef SQLITE_OMIT_VIRTUALTABLE
19605           raw_printf(stderr, "The --preserve-rowids option is not compatible"
19606                              " with SQLITE_OMIT_VIRTUALTABLE\n");
19607           rc = 1;
19608           sqlite3_free(zLike);
19609           goto meta_command_exit;
19610 #else
19611           ShellSetFlag(p, SHFLG_PreserveRowid);
19612 #endif
19613         }else
19614         if( strcmp(z,"newlines")==0 ){
19615           ShellSetFlag(p, SHFLG_Newlines);
19616         }else
19617         if( strcmp(z,"data-only")==0 ){
19618           ShellSetFlag(p, SHFLG_DumpDataOnly);
19619         }else
19620         if( strcmp(z,"nosys")==0 ){
19621           ShellSetFlag(p, SHFLG_DumpNoSys);
19622         }else
19623         {
19624           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
19625           rc = 1;
19626           sqlite3_free(zLike);
19627           goto meta_command_exit;
19628         }
19629       }else{
19630         /* azArg[i] contains a LIKE pattern. This ".dump" request should
19631         ** only dump data for tables for which either the table name matches
19632         ** the LIKE pattern, or the table appears to be a shadow table of
19633         ** a virtual table for which the name matches the LIKE pattern.
19634         */
19635         char *zExpr = sqlite3_mprintf(
19636             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
19637             "  SELECT 1 FROM sqlite_schema WHERE "
19638             "    name LIKE %Q ESCAPE '\\' AND"
19639             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
19640             "    substr(o.name, 1, length(name)+1) == (name||'_')"
19641             ")", azArg[i], azArg[i]
19642         );
19643 
19644         if( zLike ){
19645           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
19646         }else{
19647           zLike = zExpr;
19648         }
19649       }
19650     }
19651 
19652     open_db(p, 0);
19653 
19654     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
19655       /* When playing back a "dump", the content might appear in an order
19656       ** which causes immediate foreign key constraints to be violated.
19657       ** So disable foreign-key constraint enforcement to prevent problems. */
19658       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
19659       raw_printf(p->out, "BEGIN TRANSACTION;\n");
19660     }
19661     p->writableSchema = 0;
19662     p->showHeader = 0;
19663     /* Set writable_schema=ON since doing so forces SQLite to initialize
19664     ** as much of the schema as it can even if the sqlite_schema table is
19665     ** corrupt. */
19666     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
19667     p->nErr = 0;
19668     if( zLike==0 ) zLike = sqlite3_mprintf("true");
19669     zSql = sqlite3_mprintf(
19670       "SELECT name, type, sql FROM sqlite_schema AS o "
19671       "WHERE (%s) AND type=='table'"
19672       "  AND sql NOT NULL"
19673       " ORDER BY tbl_name='sqlite_sequence', rowid",
19674       zLike
19675     );
19676     run_schema_dump_query(p,zSql);
19677     sqlite3_free(zSql);
19678     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
19679       zSql = sqlite3_mprintf(
19680         "SELECT sql FROM sqlite_schema AS o "
19681         "WHERE (%s) AND sql NOT NULL"
19682         "  AND type IN ('index','trigger','view')",
19683         zLike
19684       );
19685       run_table_dump_query(p, zSql);
19686       sqlite3_free(zSql);
19687     }
19688     sqlite3_free(zLike);
19689     if( p->writableSchema ){
19690       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
19691       p->writableSchema = 0;
19692     }
19693     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
19694     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
19695     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
19696       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
19697     }
19698     p->showHeader = savedShowHeader;
19699     p->shellFlgs = savedShellFlags;
19700   }else
19701 
19702   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
19703     if( nArg==2 ){
19704       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
19705     }else{
19706       raw_printf(stderr, "Usage: .echo on|off\n");
19707       rc = 1;
19708     }
19709   }else
19710 
19711   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
19712     if( nArg==2 ){
19713       p->autoEQPtest = 0;
19714       if( p->autoEQPtrace ){
19715         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
19716         p->autoEQPtrace = 0;
19717       }
19718       if( strcmp(azArg[1],"full")==0 ){
19719         p->autoEQP = AUTOEQP_full;
19720       }else if( strcmp(azArg[1],"trigger")==0 ){
19721         p->autoEQP = AUTOEQP_trigger;
19722 #ifdef SQLITE_DEBUG
19723       }else if( strcmp(azArg[1],"test")==0 ){
19724         p->autoEQP = AUTOEQP_on;
19725         p->autoEQPtest = 1;
19726       }else if( strcmp(azArg[1],"trace")==0 ){
19727         p->autoEQP = AUTOEQP_full;
19728         p->autoEQPtrace = 1;
19729         open_db(p, 0);
19730         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
19731         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
19732 #endif
19733       }else{
19734         p->autoEQP = (u8)booleanValue(azArg[1]);
19735       }
19736     }else{
19737       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
19738       rc = 1;
19739     }
19740   }else
19741 
19742 #ifndef SQLITE_SHELL_WASM_MODE
19743   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
19744     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
19745     rc = 2;
19746   }else
19747 #endif
19748 
19749   /* The ".explain" command is automatic now.  It is largely pointless.  It
19750   ** retained purely for backwards compatibility */
19751   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
19752     int val = 1;
19753     if( nArg>=2 ){
19754       if( strcmp(azArg[1],"auto")==0 ){
19755         val = 99;
19756       }else{
19757         val =  booleanValue(azArg[1]);
19758       }
19759     }
19760     if( val==1 && p->mode!=MODE_Explain ){
19761       p->normalMode = p->mode;
19762       p->mode = MODE_Explain;
19763       p->autoExplain = 0;
19764     }else if( val==0 ){
19765       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
19766       p->autoExplain = 0;
19767     }else if( val==99 ){
19768       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
19769       p->autoExplain = 1;
19770     }
19771   }else
19772 
19773 #ifndef SQLITE_OMIT_VIRTUALTABLE
19774   if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
19775     if( p->bSafeMode ){
19776       raw_printf(stderr,
19777         "Cannot run experimental commands such as \"%s\" in safe mode\n",
19778         azArg[0]);
19779       rc = 1;
19780     }else{
19781       open_db(p, 0);
19782       expertDotCommand(p, azArg, nArg);
19783     }
19784   }else
19785 #endif
19786 
19787   if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
19788     static const struct {
19789        const char *zCtrlName;   /* Name of a test-control option */
19790        int ctrlCode;            /* Integer code for that option */
19791        const char *zUsage;      /* Usage notes */
19792     } aCtrl[] = {
19793       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
19794       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
19795       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
19796       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
19797       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
19798    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
19799       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
19800       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
19801       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
19802       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
19803    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
19804     };
19805     int filectrl = -1;
19806     int iCtrl = -1;
19807     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
19808     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
19809     int n2, i;
19810     const char *zCmd = 0;
19811     const char *zSchema = 0;
19812 
19813     open_db(p, 0);
19814     zCmd = nArg>=2 ? azArg[1] : "help";
19815 
19816     if( zCmd[0]=='-'
19817      && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
19818      && nArg>=4
19819     ){
19820       zSchema = azArg[2];
19821       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
19822       nArg -= 2;
19823       zCmd = azArg[1];
19824     }
19825 
19826     /* The argument can optionally begin with "-" or "--" */
19827     if( zCmd[0]=='-' && zCmd[1] ){
19828       zCmd++;
19829       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
19830     }
19831 
19832     /* --help lists all file-controls */
19833     if( strcmp(zCmd,"help")==0 ){
19834       utf8_printf(p->out, "Available file-controls:\n");
19835       for(i=0; i<ArraySize(aCtrl); i++){
19836         utf8_printf(p->out, "  .filectrl %s %s\n",
19837                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
19838       }
19839       rc = 1;
19840       goto meta_command_exit;
19841     }
19842 
19843     /* convert filectrl text option to value. allow any unique prefix
19844     ** of the option name, or a numerical value. */
19845     n2 = strlen30(zCmd);
19846     for(i=0; i<ArraySize(aCtrl); i++){
19847       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
19848         if( filectrl<0 ){
19849           filectrl = aCtrl[i].ctrlCode;
19850           iCtrl = i;
19851         }else{
19852           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
19853                               "Use \".filectrl --help\" for help\n", zCmd);
19854           rc = 1;
19855           goto meta_command_exit;
19856         }
19857       }
19858     }
19859     if( filectrl<0 ){
19860       utf8_printf(stderr,"Error: unknown file-control: %s\n"
19861                          "Use \".filectrl --help\" for help\n", zCmd);
19862     }else{
19863       switch(filectrl){
19864         case SQLITE_FCNTL_SIZE_LIMIT: {
19865           if( nArg!=2 && nArg!=3 ) break;
19866           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
19867           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
19868           isOk = 1;
19869           break;
19870         }
19871         case SQLITE_FCNTL_LOCK_TIMEOUT:
19872         case SQLITE_FCNTL_CHUNK_SIZE: {
19873           int x;
19874           if( nArg!=3 ) break;
19875           x = (int)integerValue(azArg[2]);
19876           sqlite3_file_control(p->db, zSchema, filectrl, &x);
19877           isOk = 2;
19878           break;
19879         }
19880         case SQLITE_FCNTL_PERSIST_WAL:
19881         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
19882           int x;
19883           if( nArg!=2 && nArg!=3 ) break;
19884           x = nArg==3 ? booleanValue(azArg[2]) : -1;
19885           sqlite3_file_control(p->db, zSchema, filectrl, &x);
19886           iRes = x;
19887           isOk = 1;
19888           break;
19889         }
19890         case SQLITE_FCNTL_DATA_VERSION:
19891         case SQLITE_FCNTL_HAS_MOVED: {
19892           int x;
19893           if( nArg!=2 ) break;
19894           sqlite3_file_control(p->db, zSchema, filectrl, &x);
19895           iRes = x;
19896           isOk = 1;
19897           break;
19898         }
19899         case SQLITE_FCNTL_TEMPFILENAME: {
19900           char *z = 0;
19901           if( nArg!=2 ) break;
19902           sqlite3_file_control(p->db, zSchema, filectrl, &z);
19903           if( z ){
19904             utf8_printf(p->out, "%s\n", z);
19905             sqlite3_free(z);
19906           }
19907           isOk = 2;
19908           break;
19909         }
19910         case SQLITE_FCNTL_RESERVE_BYTES: {
19911           int x;
19912           if( nArg>=3 ){
19913             x = atoi(azArg[2]);
19914             sqlite3_file_control(p->db, zSchema, filectrl, &x);
19915           }
19916           x = -1;
19917           sqlite3_file_control(p->db, zSchema, filectrl, &x);
19918           utf8_printf(p->out,"%d\n", x);
19919           isOk = 2;
19920           break;
19921         }
19922       }
19923     }
19924     if( isOk==0 && iCtrl>=0 ){
19925       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
19926       rc = 1;
19927     }else if( isOk==1 ){
19928       char zBuf[100];
19929       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
19930       raw_printf(p->out, "%s\n", zBuf);
19931     }
19932   }else
19933 
19934   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
19935     ShellState data;
19936     int doStats = 0;
19937     memcpy(&data, p, sizeof(data));
19938     data.showHeader = 0;
19939     data.cMode = data.mode = MODE_Semi;
19940     if( nArg==2 && optionMatch(azArg[1], "indent") ){
19941       data.cMode = data.mode = MODE_Pretty;
19942       nArg = 1;
19943     }
19944     if( nArg!=1 ){
19945       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
19946       rc = 1;
19947       goto meta_command_exit;
19948     }
19949     open_db(p, 0);
19950     rc = sqlite3_exec(p->db,
19951        "SELECT sql FROM"
19952        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
19953        "     FROM sqlite_schema UNION ALL"
19954        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
19955        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
19956        "ORDER BY x",
19957        callback, &data, 0
19958     );
19959     if( rc==SQLITE_OK ){
19960       sqlite3_stmt *pStmt;
19961       rc = sqlite3_prepare_v2(p->db,
19962                "SELECT rowid FROM sqlite_schema"
19963                " WHERE name GLOB 'sqlite_stat[134]'",
19964                -1, &pStmt, 0);
19965       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
19966       sqlite3_finalize(pStmt);
19967     }
19968     if( doStats==0 ){
19969       raw_printf(p->out, "/* No STAT tables available */\n");
19970     }else{
19971       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19972       data.cMode = data.mode = MODE_Insert;
19973       data.zDestTable = "sqlite_stat1";
19974       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
19975       data.zDestTable = "sqlite_stat4";
19976       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
19977       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19978     }
19979   }else
19980 
19981   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
19982     if( nArg==2 ){
19983       p->showHeader = booleanValue(azArg[1]);
19984       p->shellFlgs |= SHFLG_HeaderSet;
19985     }else{
19986       raw_printf(stderr, "Usage: .headers on|off\n");
19987       rc = 1;
19988     }
19989   }else
19990 
19991   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
19992     if( nArg>=2 ){
19993       n = showHelp(p->out, azArg[1]);
19994       if( n==0 ){
19995         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
19996       }
19997     }else{
19998       showHelp(p->out, 0);
19999     }
20000   }else
20001 
20002 #ifndef SQLITE_SHELL_WASM_MODE
20003   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
20004     char *zTable = 0;           /* Insert data into this table */
20005     char *zSchema = 0;          /* within this schema (may default to "main") */
20006     char *zFile = 0;            /* Name of file to extra content from */
20007     sqlite3_stmt *pStmt = NULL; /* A statement */
20008     int nCol;                   /* Number of columns in the table */
20009     int nByte;                  /* Number of bytes in an SQL string */
20010     int i, j;                   /* Loop counters */
20011     int needCommit;             /* True to COMMIT or ROLLBACK at end */
20012     int nSep;                   /* Number of bytes in p->colSeparator[] */
20013     char *zSql;                 /* An SQL statement */
20014     char *zFullTabName;         /* Table name with schema if applicable */
20015     ImportCtx sCtx;             /* Reader context */
20016     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
20017     int eVerbose = 0;           /* Larger for more console output */
20018     int nSkip = 0;              /* Initial lines to skip */
20019     int useOutputMode = 1;      /* Use output mode to determine separators */
20020     char *zCreate = 0;          /* CREATE TABLE statement text */
20021 
20022     failIfSafeMode(p, "cannot run .import in safe mode");
20023     memset(&sCtx, 0, sizeof(sCtx));
20024     if( p->mode==MODE_Ascii ){
20025       xRead = ascii_read_one_field;
20026     }else{
20027       xRead = csv_read_one_field;
20028     }
20029     rc = 1;
20030     for(i=1; i<nArg; i++){
20031       char *z = azArg[i];
20032       if( z[0]=='-' && z[1]=='-' ) z++;
20033       if( z[0]!='-' ){
20034         if( zFile==0 ){
20035           zFile = z;
20036         }else if( zTable==0 ){
20037           zTable = z;
20038         }else{
20039           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
20040           showHelp(p->out, "import");
20041           goto meta_command_exit;
20042         }
20043       }else if( strcmp(z,"-v")==0 ){
20044         eVerbose++;
20045       }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
20046         zSchema = azArg[++i];
20047       }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
20048         nSkip = integerValue(azArg[++i]);
20049       }else if( strcmp(z,"-ascii")==0 ){
20050         sCtx.cColSep = SEP_Unit[0];
20051         sCtx.cRowSep = SEP_Record[0];
20052         xRead = ascii_read_one_field;
20053         useOutputMode = 0;
20054       }else if( strcmp(z,"-csv")==0 ){
20055         sCtx.cColSep = ',';
20056         sCtx.cRowSep = '\n';
20057         xRead = csv_read_one_field;
20058         useOutputMode = 0;
20059       }else{
20060         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
20061         showHelp(p->out, "import");
20062         goto meta_command_exit;
20063       }
20064     }
20065     if( zTable==0 ){
20066       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
20067                   zFile==0 ? "FILE" : "TABLE");
20068       showHelp(p->out, "import");
20069       goto meta_command_exit;
20070     }
20071     seenInterrupt = 0;
20072     open_db(p, 0);
20073     if( useOutputMode ){
20074       /* If neither the --csv or --ascii options are specified, then set
20075       ** the column and row separator characters from the output mode. */
20076       nSep = strlen30(p->colSeparator);
20077       if( nSep==0 ){
20078         raw_printf(stderr,
20079                    "Error: non-null column separator required for import\n");
20080         goto meta_command_exit;
20081       }
20082       if( nSep>1 ){
20083         raw_printf(stderr,
20084               "Error: multi-character column separators not allowed"
20085               " for import\n");
20086         goto meta_command_exit;
20087       }
20088       nSep = strlen30(p->rowSeparator);
20089       if( nSep==0 ){
20090         raw_printf(stderr,
20091             "Error: non-null row separator required for import\n");
20092         goto meta_command_exit;
20093       }
20094       if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
20095         /* When importing CSV (only), if the row separator is set to the
20096         ** default output row separator, change it to the default input
20097         ** row separator.  This avoids having to maintain different input
20098         ** and output row separators. */
20099         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
20100         nSep = strlen30(p->rowSeparator);
20101       }
20102       if( nSep>1 ){
20103         raw_printf(stderr, "Error: multi-character row separators not allowed"
20104                            " for import\n");
20105         goto meta_command_exit;
20106       }
20107       sCtx.cColSep = p->colSeparator[0];
20108       sCtx.cRowSep = p->rowSeparator[0];
20109     }
20110     sCtx.zFile = zFile;
20111     sCtx.nLine = 1;
20112     if( sCtx.zFile[0]=='|' ){
20113 #ifdef SQLITE_OMIT_POPEN
20114       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
20115       goto meta_command_exit;
20116 #else
20117       sCtx.in = popen(sCtx.zFile+1, "r");
20118       sCtx.zFile = "<pipe>";
20119       sCtx.xCloser = pclose;
20120 #endif
20121     }else{
20122       sCtx.in = fopen(sCtx.zFile, "rb");
20123       sCtx.xCloser = fclose;
20124     }
20125     if( sCtx.in==0 ){
20126       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
20127       goto meta_command_exit;
20128     }
20129     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
20130       char zSep[2];
20131       zSep[1] = 0;
20132       zSep[0] = sCtx.cColSep;
20133       utf8_printf(p->out, "Column separator ");
20134       output_c_string(p->out, zSep);
20135       utf8_printf(p->out, ", row separator ");
20136       zSep[0] = sCtx.cRowSep;
20137       output_c_string(p->out, zSep);
20138       utf8_printf(p->out, "\n");
20139     }
20140     sCtx.z = sqlite3_malloc64(120);
20141     if( sCtx.z==0 ){
20142       import_cleanup(&sCtx);
20143       shell_out_of_memory();
20144     }
20145     /* Below, resources must be freed before exit. */
20146     while( (nSkip--)>0 ){
20147       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
20148     }
20149     if( zSchema!=0 ){
20150       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
20151     }else{
20152       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
20153     }
20154     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
20155     if( zSql==0 || zFullTabName==0 ){
20156       import_cleanup(&sCtx);
20157       shell_out_of_memory();
20158     }
20159     nByte = strlen30(zSql);
20160     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20161     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
20162     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
20163       sqlite3 *dbCols = 0;
20164       char *zRenames = 0;
20165       char *zColDefs;
20166       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
20167       while( xRead(&sCtx) ){
20168         zAutoColumn(sCtx.z, &dbCols, 0);
20169         if( sCtx.cTerm!=sCtx.cColSep ) break;
20170       }
20171       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
20172       if( zRenames!=0 ){
20173         utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
20174                     "Columns renamed during .import %s due to duplicates:\n"
20175                     "%s\n", sCtx.zFile, zRenames);
20176         sqlite3_free(zRenames);
20177       }
20178       assert(dbCols==0);
20179       if( zColDefs==0 ){
20180         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
20181       import_fail:
20182         sqlite3_free(zCreate);
20183         sqlite3_free(zSql);
20184         sqlite3_free(zFullTabName);
20185         import_cleanup(&sCtx);
20186         rc = 1;
20187         goto meta_command_exit;
20188       }
20189       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
20190       if( eVerbose>=1 ){
20191         utf8_printf(p->out, "%s\n", zCreate);
20192       }
20193       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
20194       if( rc ){
20195         utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
20196         goto import_fail;
20197       }
20198       sqlite3_free(zCreate);
20199       zCreate = 0;
20200       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20201     }
20202     if( rc ){
20203       if (pStmt) sqlite3_finalize(pStmt);
20204       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
20205       goto import_fail;
20206     }
20207     sqlite3_free(zSql);
20208     nCol = sqlite3_column_count(pStmt);
20209     sqlite3_finalize(pStmt);
20210     pStmt = 0;
20211     if( nCol==0 ) return 0; /* no columns, no error */
20212     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
20213     if( zSql==0 ){
20214       import_cleanup(&sCtx);
20215       shell_out_of_memory();
20216     }
20217     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
20218     j = strlen30(zSql);
20219     for(i=1; i<nCol; i++){
20220       zSql[j++] = ',';
20221       zSql[j++] = '?';
20222     }
20223     zSql[j++] = ')';
20224     zSql[j] = 0;
20225     if( eVerbose>=2 ){
20226       utf8_printf(p->out, "Insert using: %s\n", zSql);
20227     }
20228     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20229     if( rc ){
20230       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
20231       if (pStmt) sqlite3_finalize(pStmt);
20232       goto import_fail;
20233     }
20234     sqlite3_free(zSql);
20235     sqlite3_free(zFullTabName);
20236     needCommit = sqlite3_get_autocommit(p->db);
20237     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
20238     do{
20239       int startLine = sCtx.nLine;
20240       for(i=0; i<nCol; i++){
20241         char *z = xRead(&sCtx);
20242         /*
20243         ** Did we reach end-of-file before finding any columns?
20244         ** If so, stop instead of NULL filling the remaining columns.
20245         */
20246         if( z==0 && i==0 ) break;
20247         /*
20248         ** Did we reach end-of-file OR end-of-line before finding any
20249         ** columns in ASCII mode?  If so, stop instead of NULL filling
20250         ** the remaining columns.
20251         */
20252         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
20253         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
20254         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
20255           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
20256                           "filling the rest with NULL\n",
20257                           sCtx.zFile, startLine, nCol, i+1);
20258           i += 2;
20259           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
20260         }
20261       }
20262       if( sCtx.cTerm==sCtx.cColSep ){
20263         do{
20264           xRead(&sCtx);
20265           i++;
20266         }while( sCtx.cTerm==sCtx.cColSep );
20267         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
20268                         "extras ignored\n",
20269                         sCtx.zFile, startLine, nCol, i);
20270       }
20271       if( i>=nCol ){
20272         sqlite3_step(pStmt);
20273         rc = sqlite3_reset(pStmt);
20274         if( rc!=SQLITE_OK ){
20275           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
20276                       startLine, sqlite3_errmsg(p->db));
20277           sCtx.nErr++;
20278         }else{
20279           sCtx.nRow++;
20280         }
20281       }
20282     }while( sCtx.cTerm!=EOF );
20283 
20284     import_cleanup(&sCtx);
20285     sqlite3_finalize(pStmt);
20286     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
20287     if( eVerbose>0 ){
20288       utf8_printf(p->out,
20289           "Added %d rows with %d errors using %d lines of input\n",
20290           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
20291     }
20292   }else
20293 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
20294 
20295 #ifndef SQLITE_UNTESTABLE
20296   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
20297     char *zSql;
20298     char *zCollist = 0;
20299     sqlite3_stmt *pStmt;
20300     int tnum = 0;
20301     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
20302     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
20303     int i;
20304     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
20305       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
20306                           "       .imposter off\n");
20307       /* Also allowed, but not documented:
20308       **
20309       **    .imposter TABLE IMPOSTER
20310       **
20311       ** where TABLE is a WITHOUT ROWID table.  In that case, the
20312       ** imposter is another WITHOUT ROWID table with the columns in
20313       ** storage order. */
20314       rc = 1;
20315       goto meta_command_exit;
20316     }
20317     open_db(p, 0);
20318     if( nArg==2 ){
20319       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
20320       goto meta_command_exit;
20321     }
20322     zSql = sqlite3_mprintf(
20323       "SELECT rootpage, 0 FROM sqlite_schema"
20324       " WHERE name='%q' AND type='index'"
20325       "UNION ALL "
20326       "SELECT rootpage, 1 FROM sqlite_schema"
20327       " WHERE name='%q' AND type='table'"
20328       "   AND sql LIKE '%%without%%rowid%%'",
20329       azArg[1], azArg[1]
20330     );
20331     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20332     sqlite3_free(zSql);
20333     if( sqlite3_step(pStmt)==SQLITE_ROW ){
20334       tnum = sqlite3_column_int(pStmt, 0);
20335       isWO = sqlite3_column_int(pStmt, 1);
20336     }
20337     sqlite3_finalize(pStmt);
20338     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
20339     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20340     sqlite3_free(zSql);
20341     i = 0;
20342     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
20343       char zLabel[20];
20344       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
20345       i++;
20346       if( zCol==0 ){
20347         if( sqlite3_column_int(pStmt,1)==-1 ){
20348           zCol = "_ROWID_";
20349         }else{
20350           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
20351           zCol = zLabel;
20352         }
20353       }
20354       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
20355         lenPK = (int)strlen(zCollist);
20356       }
20357       if( zCollist==0 ){
20358         zCollist = sqlite3_mprintf("\"%w\"", zCol);
20359       }else{
20360         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
20361       }
20362     }
20363     sqlite3_finalize(pStmt);
20364     if( i==0 || tnum==0 ){
20365       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
20366       rc = 1;
20367       sqlite3_free(zCollist);
20368       goto meta_command_exit;
20369     }
20370     if( lenPK==0 ) lenPK = 100000;
20371     zSql = sqlite3_mprintf(
20372           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
20373           azArg[2], zCollist, lenPK, zCollist);
20374     sqlite3_free(zCollist);
20375     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
20376     if( rc==SQLITE_OK ){
20377       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
20378       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
20379       if( rc ){
20380         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
20381       }else{
20382         utf8_printf(stdout, "%s;\n", zSql);
20383         raw_printf(stdout,
20384           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
20385           azArg[1], isWO ? "table" : "index"
20386         );
20387       }
20388     }else{
20389       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
20390       rc = 1;
20391     }
20392     sqlite3_free(zSql);
20393   }else
20394 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
20395 
20396 #ifdef SQLITE_ENABLE_IOTRACE
20397   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
20398     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
20399     if( iotrace && iotrace!=stdout ) fclose(iotrace);
20400     iotrace = 0;
20401     if( nArg<2 ){
20402       sqlite3IoTrace = 0;
20403     }else if( strcmp(azArg[1], "-")==0 ){
20404       sqlite3IoTrace = iotracePrintf;
20405       iotrace = stdout;
20406     }else{
20407       iotrace = fopen(azArg[1], "w");
20408       if( iotrace==0 ){
20409         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
20410         sqlite3IoTrace = 0;
20411         rc = 1;
20412       }else{
20413         sqlite3IoTrace = iotracePrintf;
20414       }
20415     }
20416   }else
20417 #endif
20418 
20419   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
20420     static const struct {
20421        const char *zLimitName;   /* Name of a limit */
20422        int limitCode;            /* Integer code for that limit */
20423     } aLimit[] = {
20424       { "length",                SQLITE_LIMIT_LENGTH                    },
20425       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
20426       { "column",                SQLITE_LIMIT_COLUMN                    },
20427       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
20428       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
20429       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
20430       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
20431       { "attached",              SQLITE_LIMIT_ATTACHED                  },
20432       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
20433       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
20434       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
20435       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
20436     };
20437     int i, n2;
20438     open_db(p, 0);
20439     if( nArg==1 ){
20440       for(i=0; i<ArraySize(aLimit); i++){
20441         printf("%20s %d\n", aLimit[i].zLimitName,
20442                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
20443       }
20444     }else if( nArg>3 ){
20445       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
20446       rc = 1;
20447       goto meta_command_exit;
20448     }else{
20449       int iLimit = -1;
20450       n2 = strlen30(azArg[1]);
20451       for(i=0; i<ArraySize(aLimit); i++){
20452         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
20453           if( iLimit<0 ){
20454             iLimit = i;
20455           }else{
20456             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
20457             rc = 1;
20458             goto meta_command_exit;
20459           }
20460         }
20461       }
20462       if( iLimit<0 ){
20463         utf8_printf(stderr, "unknown limit: \"%s\"\n"
20464                         "enter \".limits\" with no arguments for a list.\n",
20465                          azArg[1]);
20466         rc = 1;
20467         goto meta_command_exit;
20468       }
20469       if( nArg==3 ){
20470         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
20471                       (int)integerValue(azArg[2]));
20472       }
20473       printf("%20s %d\n", aLimit[iLimit].zLimitName,
20474              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
20475     }
20476   }else
20477 
20478   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
20479     open_db(p, 0);
20480     lintDotCommand(p, azArg, nArg);
20481   }else
20482 
20483 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
20484   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
20485     const char *zFile, *zProc;
20486     char *zErrMsg = 0;
20487     failIfSafeMode(p, "cannot run .load in safe mode");
20488     if( nArg<2 ){
20489       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
20490       rc = 1;
20491       goto meta_command_exit;
20492     }
20493     zFile = azArg[1];
20494     zProc = nArg>=3 ? azArg[2] : 0;
20495     open_db(p, 0);
20496     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
20497     if( rc!=SQLITE_OK ){
20498       utf8_printf(stderr, "Error: %s\n", zErrMsg);
20499       sqlite3_free(zErrMsg);
20500       rc = 1;
20501     }
20502   }else
20503 #endif
20504 
20505 #ifndef SQLITE_SHELL_WASM_MODE
20506   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
20507     failIfSafeMode(p, "cannot run .log in safe mode");
20508     if( nArg!=2 ){
20509       raw_printf(stderr, "Usage: .log FILENAME\n");
20510       rc = 1;
20511     }else{
20512       const char *zFile = azArg[1];
20513       output_file_close(p->pLog);
20514       p->pLog = output_file_open(zFile, 0);
20515     }
20516   }else
20517 #endif
20518 
20519   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
20520     const char *zMode = 0;
20521     const char *zTabname = 0;
20522     int i, n2;
20523     ColModeOpts cmOpts = ColModeOpts_default;
20524     for(i=1; i<nArg; i++){
20525       const char *z = azArg[i];
20526       if( optionMatch(z,"wrap") && i+1<nArg ){
20527         cmOpts.iWrap = integerValue(azArg[++i]);
20528       }else if( optionMatch(z,"ww") ){
20529         cmOpts.bWordWrap = 1;
20530       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
20531         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
20532       }else if( optionMatch(z,"quote") ){
20533         cmOpts.bQuote = 1;
20534       }else if( optionMatch(z,"noquote") ){
20535         cmOpts.bQuote = 0;
20536       }else if( zMode==0 ){
20537         zMode = z;
20538         /* Apply defaults for qbox pseudo-mods. If that
20539          * overwrites already-set values, user was informed of this.
20540          */
20541         if( strcmp(z, "qbox")==0 ){
20542           ColModeOpts cmo = ColModeOpts_default_qbox;
20543           zMode = "box";
20544           cmOpts = cmo;
20545         }
20546       }else if( zTabname==0 ){
20547         zTabname = z;
20548       }else if( z[0]=='-' ){
20549         utf8_printf(stderr, "unknown option: %s\n", z);
20550         utf8_printf(stderr, "options:\n"
20551                             "  --noquote\n"
20552                             "  --quote\n"
20553                             "  --wordwrap on/off\n"
20554                             "  --wrap N\n"
20555                             "  --ww\n");
20556         rc = 1;
20557         goto meta_command_exit;
20558       }else{
20559         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
20560         rc = 1;
20561         goto meta_command_exit;
20562       }
20563     }
20564     if( zMode==0 ){
20565       if( p->mode==MODE_Column
20566        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
20567       ){
20568         raw_printf
20569           (p->out,
20570            "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
20571            modeDescr[p->mode], p->cmOpts.iWrap,
20572            p->cmOpts.bWordWrap ? "on" : "off",
20573            p->cmOpts.bQuote ? "" : "no");
20574       }else{
20575         raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
20576       }
20577       zMode = modeDescr[p->mode];
20578     }
20579     n2 = strlen30(zMode);
20580     if( strncmp(zMode,"lines",n2)==0 ){
20581       p->mode = MODE_Line;
20582       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
20583     }else if( strncmp(zMode,"columns",n2)==0 ){
20584       p->mode = MODE_Column;
20585       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
20586         p->showHeader = 1;
20587       }
20588       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
20589       p->cmOpts = cmOpts;
20590     }else if( strncmp(zMode,"list",n2)==0 ){
20591       p->mode = MODE_List;
20592       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
20593       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
20594     }else if( strncmp(zMode,"html",n2)==0 ){
20595       p->mode = MODE_Html;
20596     }else if( strncmp(zMode,"tcl",n2)==0 ){
20597       p->mode = MODE_Tcl;
20598       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
20599       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
20600     }else if( strncmp(zMode,"csv",n2)==0 ){
20601       p->mode = MODE_Csv;
20602       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
20603       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
20604     }else if( strncmp(zMode,"tabs",n2)==0 ){
20605       p->mode = MODE_List;
20606       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
20607     }else if( strncmp(zMode,"insert",n2)==0 ){
20608       p->mode = MODE_Insert;
20609       set_table_name(p, zTabname ? zTabname : "table");
20610     }else if( strncmp(zMode,"quote",n2)==0 ){
20611       p->mode = MODE_Quote;
20612       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
20613       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
20614     }else if( strncmp(zMode,"ascii",n2)==0 ){
20615       p->mode = MODE_Ascii;
20616       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
20617       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
20618     }else if( strncmp(zMode,"markdown",n2)==0 ){
20619       p->mode = MODE_Markdown;
20620       p->cmOpts = cmOpts;
20621     }else if( strncmp(zMode,"table",n2)==0 ){
20622       p->mode = MODE_Table;
20623       p->cmOpts = cmOpts;
20624     }else if( strncmp(zMode,"box",n2)==0 ){
20625       p->mode = MODE_Box;
20626       p->cmOpts = cmOpts;
20627     }else if( strncmp(zMode,"count",n2)==0 ){
20628       p->mode = MODE_Count;
20629     }else if( strncmp(zMode,"off",n2)==0 ){
20630       p->mode = MODE_Off;
20631     }else if( strncmp(zMode,"json",n2)==0 ){
20632       p->mode = MODE_Json;
20633     }else{
20634       raw_printf(stderr, "Error: mode should be one of: "
20635          "ascii box column csv html insert json line list markdown "
20636          "qbox quote table tabs tcl\n");
20637       rc = 1;
20638     }
20639     p->cMode = p->mode;
20640   }else
20641 
20642 #ifndef SQLITE_SHELL_WASM_MODE
20643   if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
20644     if( nArg!=2 ){
20645       raw_printf(stderr, "Usage: .nonce NONCE\n");
20646       rc = 1;
20647     }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
20648       raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
20649                  p->lineno, azArg[1]);
20650       exit(1);
20651     }else{
20652       p->bSafeMode = 0;
20653       return 0;  /* Return immediately to bypass the safe mode reset
20654                  ** at the end of this procedure */
20655     }
20656   }else
20657 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
20658 
20659   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
20660     if( nArg==2 ){
20661       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
20662                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
20663     }else{
20664       raw_printf(stderr, "Usage: .nullvalue STRING\n");
20665       rc = 1;
20666     }
20667   }else
20668 
20669   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
20670     const char *zFN = 0;     /* Pointer to constant filename */
20671     char *zNewFilename = 0;  /* Name of the database file to open */
20672     int iName = 1;           /* Index in azArg[] of the filename */
20673     int newFlag = 0;         /* True to delete file before opening */
20674     int openMode = SHELL_OPEN_UNSPEC;
20675 
20676     /* Check for command-line arguments */
20677     for(iName=1; iName<nArg; iName++){
20678       const char *z = azArg[iName];
20679 #ifndef SQLITE_SHELL_WASM_MODE
20680       if( optionMatch(z,"new") ){
20681         newFlag = 1;
20682 #ifdef SQLITE_HAVE_ZLIB
20683       }else if( optionMatch(z, "zip") ){
20684         openMode = SHELL_OPEN_ZIPFILE;
20685 #endif
20686       }else if( optionMatch(z, "append") ){
20687         openMode = SHELL_OPEN_APPENDVFS;
20688       }else if( optionMatch(z, "readonly") ){
20689         openMode = SHELL_OPEN_READONLY;
20690       }else if( optionMatch(z, "nofollow") ){
20691         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
20692 #ifndef SQLITE_OMIT_DESERIALIZE
20693       }else if( optionMatch(z, "deserialize") ){
20694         openMode = SHELL_OPEN_DESERIALIZE;
20695       }else if( optionMatch(z, "hexdb") ){
20696         openMode = SHELL_OPEN_HEXDB;
20697       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
20698         p->szMax = integerValue(azArg[++iName]);
20699 #endif /* SQLITE_OMIT_DESERIALIZE */
20700       }else
20701 #endif /* !SQLITE_SHELL_WASM_MODE */
20702       if( z[0]=='-' ){
20703         utf8_printf(stderr, "unknown option: %s\n", z);
20704         rc = 1;
20705         goto meta_command_exit;
20706       }else if( zFN ){
20707         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
20708         rc = 1;
20709         goto meta_command_exit;
20710       }else{
20711         zFN = z;
20712       }
20713     }
20714 
20715     /* Close the existing database */
20716     session_close_all(p, -1);
20717     close_db(p->db);
20718     p->db = 0;
20719     p->pAuxDb->zDbFilename = 0;
20720     sqlite3_free(p->pAuxDb->zFreeOnClose);
20721     p->pAuxDb->zFreeOnClose = 0;
20722     p->openMode = openMode;
20723     p->openFlags = 0;
20724     p->szMax = 0;
20725 
20726     /* If a filename is specified, try to open it first */
20727     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
20728       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
20729 #ifndef SQLITE_SHELL_WASM_MODE
20730       if( p->bSafeMode
20731        && p->openMode!=SHELL_OPEN_HEXDB
20732        && zFN
20733        && strcmp(zFN,":memory:")!=0
20734       ){
20735         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
20736       }
20737 #else
20738       /* WASM mode has its own sandboxed pseudo-filesystem. */
20739 #endif
20740       if( zFN ){
20741         zNewFilename = sqlite3_mprintf("%s", zFN);
20742         shell_check_oom(zNewFilename);
20743       }else{
20744         zNewFilename = 0;
20745       }
20746       p->pAuxDb->zDbFilename = zNewFilename;
20747       open_db(p, OPEN_DB_KEEPALIVE);
20748       if( p->db==0 ){
20749         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
20750         sqlite3_free(zNewFilename);
20751       }else{
20752         p->pAuxDb->zFreeOnClose = zNewFilename;
20753       }
20754     }
20755     if( p->db==0 ){
20756       /* As a fall-back open a TEMP database */
20757       p->pAuxDb->zDbFilename = 0;
20758       open_db(p, 0);
20759     }
20760   }else
20761 
20762 #ifndef SQLITE_SHELL_WASM_MODE
20763   if( (c=='o'
20764         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
20765    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
20766   ){
20767     char *zFile = 0;
20768     int bTxtMode = 0;
20769     int i;
20770     int eMode = 0;
20771     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
20772     unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
20773 
20774     zBOM[0] = 0;
20775     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
20776     if( c=='e' ){
20777       eMode = 'x';
20778       bOnce = 2;
20779     }else if( strncmp(azArg[0],"once",n)==0 ){
20780       bOnce = 1;
20781     }
20782     for(i=1; i<nArg; i++){
20783       char *z = azArg[i];
20784       if( z[0]=='-' ){
20785         if( z[1]=='-' ) z++;
20786         if( strcmp(z,"-bom")==0 ){
20787           zBOM[0] = 0xef;
20788           zBOM[1] = 0xbb;
20789           zBOM[2] = 0xbf;
20790           zBOM[3] = 0;
20791         }else if( c!='e' && strcmp(z,"-x")==0 ){
20792           eMode = 'x';  /* spreadsheet */
20793         }else if( c!='e' && strcmp(z,"-e")==0 ){
20794           eMode = 'e';  /* text editor */
20795         }else{
20796           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
20797                       azArg[i]);
20798           showHelp(p->out, azArg[0]);
20799           rc = 1;
20800           goto meta_command_exit;
20801         }
20802       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
20803         zFile = sqlite3_mprintf("%s", z);
20804         if( zFile && zFile[0]=='|' ){
20805           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
20806           break;
20807         }
20808       }else{
20809         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
20810                     azArg[i]);
20811         showHelp(p->out, azArg[0]);
20812         rc = 1;
20813         sqlite3_free(zFile);
20814         goto meta_command_exit;
20815       }
20816     }
20817     if( zFile==0 ){
20818       zFile = sqlite3_mprintf("stdout");
20819     }
20820     if( bOnce ){
20821       p->outCount = 2;
20822     }else{
20823       p->outCount = 0;
20824     }
20825     output_reset(p);
20826 #ifndef SQLITE_NOHAVE_SYSTEM
20827     if( eMode=='e' || eMode=='x' ){
20828       p->doXdgOpen = 1;
20829       outputModePush(p);
20830       if( eMode=='x' ){
20831         /* spreadsheet mode.  Output as CSV. */
20832         newTempFile(p, "csv");
20833         ShellClearFlag(p, SHFLG_Echo);
20834         p->mode = MODE_Csv;
20835         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
20836         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
20837       }else{
20838         /* text editor mode */
20839         newTempFile(p, "txt");
20840         bTxtMode = 1;
20841       }
20842       sqlite3_free(zFile);
20843       zFile = sqlite3_mprintf("%s", p->zTempFile);
20844     }
20845 #endif /* SQLITE_NOHAVE_SYSTEM */
20846     shell_check_oom(zFile);
20847     if( zFile[0]=='|' ){
20848 #ifdef SQLITE_OMIT_POPEN
20849       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
20850       rc = 1;
20851       p->out = stdout;
20852 #else
20853       p->out = popen(zFile + 1, "w");
20854       if( p->out==0 ){
20855         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
20856         p->out = stdout;
20857         rc = 1;
20858       }else{
20859         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
20860         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
20861       }
20862 #endif
20863     }else{
20864       p->out = output_file_open(zFile, bTxtMode);
20865       if( p->out==0 ){
20866         if( strcmp(zFile,"off")!=0 ){
20867           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
20868         }
20869         p->out = stdout;
20870         rc = 1;
20871       } else {
20872         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
20873         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
20874       }
20875     }
20876     sqlite3_free(zFile);
20877   }else
20878 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
20879 
20880   if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
20881     open_db(p,0);
20882     if( nArg<=1 ) goto parameter_syntax_error;
20883 
20884     /* .parameter clear
20885     ** Clear all bind parameters by dropping the TEMP table that holds them.
20886     */
20887     if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
20888       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
20889                    0, 0, 0);
20890     }else
20891 
20892     /* .parameter list
20893     ** List all bind parameters.
20894     */
20895     if( nArg==2 && strcmp(azArg[1],"list")==0 ){
20896       sqlite3_stmt *pStmt = 0;
20897       int rx;
20898       int len = 0;
20899       rx = sqlite3_prepare_v2(p->db,
20900              "SELECT max(length(key)) "
20901              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
20902       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
20903         len = sqlite3_column_int(pStmt, 0);
20904         if( len>40 ) len = 40;
20905       }
20906       sqlite3_finalize(pStmt);
20907       pStmt = 0;
20908       if( len ){
20909         rx = sqlite3_prepare_v2(p->db,
20910              "SELECT key, quote(value) "
20911              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
20912         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
20913           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
20914                       sqlite3_column_text(pStmt,1));
20915         }
20916         sqlite3_finalize(pStmt);
20917       }
20918     }else
20919 
20920     /* .parameter init
20921     ** Make sure the TEMP table used to hold bind parameters exists.
20922     ** Create it if necessary.
20923     */
20924     if( nArg==2 && strcmp(azArg[1],"init")==0 ){
20925       bind_table_init(p);
20926     }else
20927 
20928     /* .parameter set NAME VALUE
20929     ** Set or reset a bind parameter.  NAME should be the full parameter
20930     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
20931     ** VALUE can be in either SQL literal notation, or if not it will be
20932     ** understood to be a text string.
20933     */
20934     if( nArg==4 && strcmp(azArg[1],"set")==0 ){
20935       int rx;
20936       char *zSql;
20937       sqlite3_stmt *pStmt;
20938       const char *zKey = azArg[2];
20939       const char *zValue = azArg[3];
20940       bind_table_init(p);
20941       zSql = sqlite3_mprintf(
20942                   "REPLACE INTO temp.sqlite_parameters(key,value)"
20943                   "VALUES(%Q,%s);", zKey, zValue);
20944       shell_check_oom(zSql);
20945       pStmt = 0;
20946       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20947       sqlite3_free(zSql);
20948       if( rx!=SQLITE_OK ){
20949         sqlite3_finalize(pStmt);
20950         pStmt = 0;
20951         zSql = sqlite3_mprintf(
20952                    "REPLACE INTO temp.sqlite_parameters(key,value)"
20953                    "VALUES(%Q,%Q);", zKey, zValue);
20954         shell_check_oom(zSql);
20955         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20956         sqlite3_free(zSql);
20957         if( rx!=SQLITE_OK ){
20958           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
20959           sqlite3_finalize(pStmt);
20960           pStmt = 0;
20961           rc = 1;
20962         }
20963       }
20964       sqlite3_step(pStmt);
20965       sqlite3_finalize(pStmt);
20966     }else
20967 
20968     /* .parameter unset NAME
20969     ** Remove the NAME binding from the parameter binding table, if it
20970     ** exists.
20971     */
20972     if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
20973       char *zSql = sqlite3_mprintf(
20974           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
20975       shell_check_oom(zSql);
20976       sqlite3_exec(p->db, zSql, 0, 0, 0);
20977       sqlite3_free(zSql);
20978     }else
20979     /* If no command name matches, show a syntax error */
20980     parameter_syntax_error:
20981     showHelp(p->out, "parameter");
20982   }else
20983 
20984   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
20985     int i;
20986     for(i=1; i<nArg; i++){
20987       if( i>1 ) raw_printf(p->out, " ");
20988       utf8_printf(p->out, "%s", azArg[i]);
20989     }
20990     raw_printf(p->out, "\n");
20991   }else
20992 
20993 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
20994   if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
20995     int i;
20996     int nn = 0;
20997     p->flgProgress = 0;
20998     p->mxProgress = 0;
20999     p->nProgress = 0;
21000     for(i=1; i<nArg; i++){
21001       const char *z = azArg[i];
21002       if( z[0]=='-' ){
21003         z++;
21004         if( z[0]=='-' ) z++;
21005         if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
21006           p->flgProgress |= SHELL_PROGRESS_QUIET;
21007           continue;
21008         }
21009         if( strcmp(z,"reset")==0 ){
21010           p->flgProgress |= SHELL_PROGRESS_RESET;
21011           continue;
21012         }
21013         if( strcmp(z,"once")==0 ){
21014           p->flgProgress |= SHELL_PROGRESS_ONCE;
21015           continue;
21016         }
21017         if( strcmp(z,"limit")==0 ){
21018           if( i+1>=nArg ){
21019             utf8_printf(stderr, "Error: missing argument on --limit\n");
21020             rc = 1;
21021             goto meta_command_exit;
21022           }else{
21023             p->mxProgress = (int)integerValue(azArg[++i]);
21024           }
21025           continue;
21026         }
21027         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
21028         rc = 1;
21029         goto meta_command_exit;
21030       }else{
21031         nn = (int)integerValue(z);
21032       }
21033     }
21034     open_db(p, 0);
21035     sqlite3_progress_handler(p->db, nn, progress_handler, p);
21036   }else
21037 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
21038 
21039   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
21040     if( nArg >= 2) {
21041       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
21042     }
21043     if( nArg >= 3) {
21044       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
21045     }
21046   }else
21047 
21048 #ifndef SQLITE_SHELL_WASM_MODE
21049   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
21050     rc = 2;
21051   }else
21052 #endif
21053 
21054 #ifndef SQLITE_SHELL_WASM_MODE
21055   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
21056     FILE *inSaved = p->in;
21057     int savedLineno = p->lineno;
21058     failIfSafeMode(p, "cannot run .read in safe mode");
21059     if( nArg!=2 ){
21060       raw_printf(stderr, "Usage: .read FILE\n");
21061       rc = 1;
21062       goto meta_command_exit;
21063     }
21064     if( azArg[1][0]=='|' ){
21065 #ifdef SQLITE_OMIT_POPEN
21066       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
21067       rc = 1;
21068       p->out = stdout;
21069 #else
21070       p->in = popen(azArg[1]+1, "r");
21071       if( p->in==0 ){
21072         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
21073         rc = 1;
21074       }else{
21075         rc = process_input(p);
21076         pclose(p->in);
21077       }
21078 #endif
21079     }else if( (p->in = openChrSource(azArg[1]))==0 ){
21080       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
21081       rc = 1;
21082     }else{
21083       rc = process_input(p);
21084       fclose(p->in);
21085     }
21086     p->in = inSaved;
21087     p->lineno = savedLineno;
21088   }else
21089 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
21090 
21091 #ifndef SQLITE_SHELL_WASM_MODE
21092   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
21093     const char *zSrcFile;
21094     const char *zDb;
21095     sqlite3 *pSrc;
21096     sqlite3_backup *pBackup;
21097     int nTimeout = 0;
21098 
21099     failIfSafeMode(p, "cannot run .restore in safe mode");
21100     if( nArg==2 ){
21101       zSrcFile = azArg[1];
21102       zDb = "main";
21103     }else if( nArg==3 ){
21104       zSrcFile = azArg[2];
21105       zDb = azArg[1];
21106     }else{
21107       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
21108       rc = 1;
21109       goto meta_command_exit;
21110     }
21111     rc = sqlite3_open(zSrcFile, &pSrc);
21112     if( rc!=SQLITE_OK ){
21113       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
21114       close_db(pSrc);
21115       return 1;
21116     }
21117     open_db(p, 0);
21118     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
21119     if( pBackup==0 ){
21120       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
21121       close_db(pSrc);
21122       return 1;
21123     }
21124     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
21125           || rc==SQLITE_BUSY  ){
21126       if( rc==SQLITE_BUSY ){
21127         if( nTimeout++ >= 3 ) break;
21128         sqlite3_sleep(100);
21129       }
21130     }
21131     sqlite3_backup_finish(pBackup);
21132     if( rc==SQLITE_DONE ){
21133       rc = 0;
21134     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
21135       raw_printf(stderr, "Error: source database is busy\n");
21136       rc = 1;
21137     }else{
21138       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
21139       rc = 1;
21140     }
21141     close_db(pSrc);
21142   }else
21143 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
21144 
21145   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
21146     if( nArg==2 ){
21147       p->scanstatsOn = (u8)booleanValue(azArg[1]);
21148 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
21149       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
21150 #endif
21151     }else{
21152       raw_printf(stderr, "Usage: .scanstats on|off\n");
21153       rc = 1;
21154     }
21155   }else
21156 
21157   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
21158     ShellText sSelect;
21159     ShellState data;
21160     char *zErrMsg = 0;
21161     const char *zDiv = "(";
21162     const char *zName = 0;
21163     int iSchema = 0;
21164     int bDebug = 0;
21165     int bNoSystemTabs = 0;
21166     int ii;
21167 
21168     open_db(p, 0);
21169     memcpy(&data, p, sizeof(data));
21170     data.showHeader = 0;
21171     data.cMode = data.mode = MODE_Semi;
21172     initText(&sSelect);
21173     for(ii=1; ii<nArg; ii++){
21174       if( optionMatch(azArg[ii],"indent") ){
21175         data.cMode = data.mode = MODE_Pretty;
21176       }else if( optionMatch(azArg[ii],"debug") ){
21177         bDebug = 1;
21178       }else if( optionMatch(azArg[ii],"nosys") ){
21179         bNoSystemTabs = 1;
21180       }else if( azArg[ii][0]=='-' ){
21181         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
21182         rc = 1;
21183         goto meta_command_exit;
21184       }else if( zName==0 ){
21185         zName = azArg[ii];
21186       }else{
21187         raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
21188         rc = 1;
21189         goto meta_command_exit;
21190       }
21191     }
21192     if( zName!=0 ){
21193       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
21194                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
21195                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
21196                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
21197       if( isSchema ){
21198         char *new_argv[2], *new_colv[2];
21199         new_argv[0] = sqlite3_mprintf(
21200                       "CREATE TABLE %s (\n"
21201                       "  type text,\n"
21202                       "  name text,\n"
21203                       "  tbl_name text,\n"
21204                       "  rootpage integer,\n"
21205                       "  sql text\n"
21206                       ")", zName);
21207         shell_check_oom(new_argv[0]);
21208         new_argv[1] = 0;
21209         new_colv[0] = "sql";
21210         new_colv[1] = 0;
21211         callback(&data, 1, new_argv, new_colv);
21212         sqlite3_free(new_argv[0]);
21213       }
21214     }
21215     if( zDiv ){
21216       sqlite3_stmt *pStmt = 0;
21217       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
21218                               -1, &pStmt, 0);
21219       if( rc ){
21220         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
21221         sqlite3_finalize(pStmt);
21222         rc = 1;
21223         goto meta_command_exit;
21224       }
21225       appendText(&sSelect, "SELECT sql FROM", 0);
21226       iSchema = 0;
21227       while( sqlite3_step(pStmt)==SQLITE_ROW ){
21228         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
21229         char zScNum[30];
21230         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
21231         appendText(&sSelect, zDiv, 0);
21232         zDiv = " UNION ALL ";
21233         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
21234         if( sqlite3_stricmp(zDb, "main")!=0 ){
21235           appendText(&sSelect, zDb, '\'');
21236         }else{
21237           appendText(&sSelect, "NULL", 0);
21238         }
21239         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
21240         appendText(&sSelect, zScNum, 0);
21241         appendText(&sSelect, " AS snum, ", 0);
21242         appendText(&sSelect, zDb, '\'');
21243         appendText(&sSelect, " AS sname FROM ", 0);
21244         appendText(&sSelect, zDb, quoteChar(zDb));
21245         appendText(&sSelect, ".sqlite_schema", 0);
21246       }
21247       sqlite3_finalize(pStmt);
21248 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
21249       if( zName ){
21250         appendText(&sSelect,
21251            " UNION ALL SELECT shell_module_schema(name),"
21252            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
21253         0);
21254       }
21255 #endif
21256       appendText(&sSelect, ") WHERE ", 0);
21257       if( zName ){
21258         char *zQarg = sqlite3_mprintf("%Q", zName);
21259         int bGlob;
21260         shell_check_oom(zQarg);
21261         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
21262                 strchr(zName, '[') != 0;
21263         if( strchr(zName, '.') ){
21264           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
21265         }else{
21266           appendText(&sSelect, "lower(tbl_name)", 0);
21267         }
21268         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
21269         appendText(&sSelect, zQarg, 0);
21270         if( !bGlob ){
21271           appendText(&sSelect, " ESCAPE '\\' ", 0);
21272         }
21273         appendText(&sSelect, " AND ", 0);
21274         sqlite3_free(zQarg);
21275       }
21276       if( bNoSystemTabs ){
21277         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
21278       }
21279       appendText(&sSelect, "sql IS NOT NULL"
21280                            " ORDER BY snum, rowid", 0);
21281       if( bDebug ){
21282         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
21283       }else{
21284         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
21285       }
21286       freeText(&sSelect);
21287     }
21288     if( zErrMsg ){
21289       utf8_printf(stderr,"Error: %s\n", zErrMsg);
21290       sqlite3_free(zErrMsg);
21291       rc = 1;
21292     }else if( rc != SQLITE_OK ){
21293       raw_printf(stderr,"Error: querying schema information\n");
21294       rc = 1;
21295     }else{
21296       rc = 0;
21297     }
21298   }else
21299 
21300   if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
21301    || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
21302   ){
21303     unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
21304     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
21305   }else
21306 
21307 #if defined(SQLITE_ENABLE_SESSION)
21308   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
21309     struct AuxDb *pAuxDb = p->pAuxDb;
21310     OpenSession *pSession = &pAuxDb->aSession[0];
21311     char **azCmd = &azArg[1];
21312     int iSes = 0;
21313     int nCmd = nArg - 1;
21314     int i;
21315     if( nArg<=1 ) goto session_syntax_error;
21316     open_db(p, 0);
21317     if( nArg>=3 ){
21318       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
21319         if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
21320       }
21321       if( iSes<pAuxDb->nSession ){
21322         pSession = &pAuxDb->aSession[iSes];
21323         azCmd++;
21324         nCmd--;
21325       }else{
21326         pSession = &pAuxDb->aSession[0];
21327         iSes = 0;
21328       }
21329     }
21330 
21331     /* .session attach TABLE
21332     ** Invoke the sqlite3session_attach() interface to attach a particular
21333     ** table so that it is never filtered.
21334     */
21335     if( strcmp(azCmd[0],"attach")==0 ){
21336       if( nCmd!=2 ) goto session_syntax_error;
21337       if( pSession->p==0 ){
21338         session_not_open:
21339         raw_printf(stderr, "ERROR: No sessions are open\n");
21340       }else{
21341         rc = sqlite3session_attach(pSession->p, azCmd[1]);
21342         if( rc ){
21343           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
21344           rc = 0;
21345         }
21346       }
21347     }else
21348 
21349     /* .session changeset FILE
21350     ** .session patchset FILE
21351     ** Write a changeset or patchset into a file.  The file is overwritten.
21352     */
21353     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
21354       FILE *out = 0;
21355       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
21356       if( nCmd!=2 ) goto session_syntax_error;
21357       if( pSession->p==0 ) goto session_not_open;
21358       out = fopen(azCmd[1], "wb");
21359       if( out==0 ){
21360         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
21361                     azCmd[1]);
21362       }else{
21363         int szChng;
21364         void *pChng;
21365         if( azCmd[0][0]=='c' ){
21366           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
21367         }else{
21368           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
21369         }
21370         if( rc ){
21371           printf("Error: error code %d\n", rc);
21372           rc = 0;
21373         }
21374         if( pChng
21375           && fwrite(pChng, szChng, 1, out)!=1 ){
21376           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
21377                   szChng);
21378         }
21379         sqlite3_free(pChng);
21380         fclose(out);
21381       }
21382     }else
21383 
21384     /* .session close
21385     ** Close the identified session
21386     */
21387     if( strcmp(azCmd[0], "close")==0 ){
21388       if( nCmd!=1 ) goto session_syntax_error;
21389       if( pAuxDb->nSession ){
21390         session_close(pSession);
21391         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
21392       }
21393     }else
21394 
21395     /* .session enable ?BOOLEAN?
21396     ** Query or set the enable flag
21397     */
21398     if( strcmp(azCmd[0], "enable")==0 ){
21399       int ii;
21400       if( nCmd>2 ) goto session_syntax_error;
21401       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
21402       if( pAuxDb->nSession ){
21403         ii = sqlite3session_enable(pSession->p, ii);
21404         utf8_printf(p->out, "session %s enable flag = %d\n",
21405                     pSession->zName, ii);
21406       }
21407     }else
21408 
21409     /* .session filter GLOB ....
21410     ** Set a list of GLOB patterns of table names to be excluded.
21411     */
21412     if( strcmp(azCmd[0], "filter")==0 ){
21413       int ii, nByte;
21414       if( nCmd<2 ) goto session_syntax_error;
21415       if( pAuxDb->nSession ){
21416         for(ii=0; ii<pSession->nFilter; ii++){
21417           sqlite3_free(pSession->azFilter[ii]);
21418         }
21419         sqlite3_free(pSession->azFilter);
21420         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
21421         pSession->azFilter = sqlite3_malloc( nByte );
21422         if( pSession->azFilter==0 ){
21423           raw_printf(stderr, "Error: out or memory\n");
21424           exit(1);
21425         }
21426         for(ii=1; ii<nCmd; ii++){
21427           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
21428           shell_check_oom(x);
21429         }
21430         pSession->nFilter = ii-1;
21431       }
21432     }else
21433 
21434     /* .session indirect ?BOOLEAN?
21435     ** Query or set the indirect flag
21436     */
21437     if( strcmp(azCmd[0], "indirect")==0 ){
21438       int ii;
21439       if( nCmd>2 ) goto session_syntax_error;
21440       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
21441       if( pAuxDb->nSession ){
21442         ii = sqlite3session_indirect(pSession->p, ii);
21443         utf8_printf(p->out, "session %s indirect flag = %d\n",
21444                     pSession->zName, ii);
21445       }
21446     }else
21447 
21448     /* .session isempty
21449     ** Determine if the session is empty
21450     */
21451     if( strcmp(azCmd[0], "isempty")==0 ){
21452       int ii;
21453       if( nCmd!=1 ) goto session_syntax_error;
21454       if( pAuxDb->nSession ){
21455         ii = sqlite3session_isempty(pSession->p);
21456         utf8_printf(p->out, "session %s isempty flag = %d\n",
21457                     pSession->zName, ii);
21458       }
21459     }else
21460 
21461     /* .session list
21462     ** List all currently open sessions
21463     */
21464     if( strcmp(azCmd[0],"list")==0 ){
21465       for(i=0; i<pAuxDb->nSession; i++){
21466         utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
21467       }
21468     }else
21469 
21470     /* .session open DB NAME
21471     ** Open a new session called NAME on the attached database DB.
21472     ** DB is normally "main".
21473     */
21474     if( strcmp(azCmd[0],"open")==0 ){
21475       char *zName;
21476       if( nCmd!=3 ) goto session_syntax_error;
21477       zName = azCmd[2];
21478       if( zName[0]==0 ) goto session_syntax_error;
21479       for(i=0; i<pAuxDb->nSession; i++){
21480         if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
21481           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
21482           goto meta_command_exit;
21483         }
21484       }
21485       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
21486         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
21487         goto meta_command_exit;
21488       }
21489       pSession = &pAuxDb->aSession[pAuxDb->nSession];
21490       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
21491       if( rc ){
21492         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
21493         rc = 0;
21494         goto meta_command_exit;
21495       }
21496       pSession->nFilter = 0;
21497       sqlite3session_table_filter(pSession->p, session_filter, pSession);
21498       pAuxDb->nSession++;
21499       pSession->zName = sqlite3_mprintf("%s", zName);
21500       shell_check_oom(pSession->zName);
21501     }else
21502     /* If no command name matches, show a syntax error */
21503     session_syntax_error:
21504     showHelp(p->out, "session");
21505   }else
21506 #endif
21507 
21508 #ifdef SQLITE_DEBUG
21509   /* Undocumented commands for internal testing.  Subject to change
21510   ** without notice. */
21511   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
21512     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
21513       int i, v;
21514       for(i=1; i<nArg; i++){
21515         v = booleanValue(azArg[i]);
21516         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
21517       }
21518     }
21519     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
21520       int i; sqlite3_int64 v;
21521       for(i=1; i<nArg; i++){
21522         char zBuf[200];
21523         v = integerValue(azArg[i]);
21524         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
21525         utf8_printf(p->out, "%s", zBuf);
21526       }
21527     }
21528   }else
21529 #endif
21530 
21531   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
21532     int bIsInit = 0;         /* True to initialize the SELFTEST table */
21533     int bVerbose = 0;        /* Verbose output */
21534     int bSelftestExists;     /* True if SELFTEST already exists */
21535     int i, k;                /* Loop counters */
21536     int nTest = 0;           /* Number of tests runs */
21537     int nErr = 0;            /* Number of errors seen */
21538     ShellText str;           /* Answer for a query */
21539     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
21540 
21541     open_db(p,0);
21542     for(i=1; i<nArg; i++){
21543       const char *z = azArg[i];
21544       if( z[0]=='-' && z[1]=='-' ) z++;
21545       if( strcmp(z,"-init")==0 ){
21546         bIsInit = 1;
21547       }else
21548       if( strcmp(z,"-v")==0 ){
21549         bVerbose++;
21550       }else
21551       {
21552         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
21553                     azArg[i], azArg[0]);
21554         raw_printf(stderr, "Should be one of: --init -v\n");
21555         rc = 1;
21556         goto meta_command_exit;
21557       }
21558     }
21559     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
21560            != SQLITE_OK ){
21561       bSelftestExists = 0;
21562     }else{
21563       bSelftestExists = 1;
21564     }
21565     if( bIsInit ){
21566       createSelftestTable(p);
21567       bSelftestExists = 1;
21568     }
21569     initText(&str);
21570     appendText(&str, "x", 0);
21571     for(k=bSelftestExists; k>=0; k--){
21572       if( k==1 ){
21573         rc = sqlite3_prepare_v2(p->db,
21574             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
21575             -1, &pStmt, 0);
21576       }else{
21577         rc = sqlite3_prepare_v2(p->db,
21578           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
21579           "      (1,'run','PRAGMA integrity_check','ok')",
21580           -1, &pStmt, 0);
21581       }
21582       if( rc ){
21583         raw_printf(stderr, "Error querying the selftest table\n");
21584         rc = 1;
21585         sqlite3_finalize(pStmt);
21586         goto meta_command_exit;
21587       }
21588       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
21589         int tno = sqlite3_column_int(pStmt, 0);
21590         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
21591         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
21592         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
21593 
21594         if( zOp==0 ) continue;
21595         if( zSql==0 ) continue;
21596         if( zAns==0 ) continue;
21597         k = 0;
21598         if( bVerbose>0 ){
21599           printf("%d: %s %s\n", tno, zOp, zSql);
21600         }
21601         if( strcmp(zOp,"memo")==0 ){
21602           utf8_printf(p->out, "%s\n", zSql);
21603         }else
21604         if( strcmp(zOp,"run")==0 ){
21605           char *zErrMsg = 0;
21606           str.n = 0;
21607           str.z[0] = 0;
21608           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
21609           nTest++;
21610           if( bVerbose ){
21611             utf8_printf(p->out, "Result: %s\n", str.z);
21612           }
21613           if( rc || zErrMsg ){
21614             nErr++;
21615             rc = 1;
21616             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
21617             sqlite3_free(zErrMsg);
21618           }else if( strcmp(zAns,str.z)!=0 ){
21619             nErr++;
21620             rc = 1;
21621             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
21622             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
21623           }
21624         }else
21625         {
21626           utf8_printf(stderr,
21627             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
21628           rc = 1;
21629           break;
21630         }
21631       } /* End loop over rows of content from SELFTEST */
21632       sqlite3_finalize(pStmt);
21633     } /* End loop over k */
21634     freeText(&str);
21635     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
21636   }else
21637 
21638   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
21639     if( nArg<2 || nArg>3 ){
21640       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
21641       rc = 1;
21642     }
21643     if( nArg>=2 ){
21644       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
21645                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
21646     }
21647     if( nArg>=3 ){
21648       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
21649                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
21650     }
21651   }else
21652 
21653   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
21654     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
21655     int i;                   /* Loop counter */
21656     int bSchema = 0;         /* Also hash the schema */
21657     int bSeparate = 0;       /* Hash each table separately */
21658     int iSize = 224;         /* Hash algorithm to use */
21659     int bDebug = 0;          /* Only show the query that would have run */
21660     sqlite3_stmt *pStmt;     /* For querying tables names */
21661     char *zSql;              /* SQL to be run */
21662     char *zSep;              /* Separator */
21663     ShellText sSql;          /* Complete SQL for the query to run the hash */
21664     ShellText sQuery;        /* Set of queries used to read all content */
21665     open_db(p, 0);
21666     for(i=1; i<nArg; i++){
21667       const char *z = azArg[i];
21668       if( z[0]=='-' ){
21669         z++;
21670         if( z[0]=='-' ) z++;
21671         if( strcmp(z,"schema")==0 ){
21672           bSchema = 1;
21673         }else
21674         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
21675          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
21676         ){
21677           iSize = atoi(&z[5]);
21678         }else
21679         if( strcmp(z,"debug")==0 ){
21680           bDebug = 1;
21681         }else
21682         {
21683           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
21684                       azArg[i], azArg[0]);
21685           showHelp(p->out, azArg[0]);
21686           rc = 1;
21687           goto meta_command_exit;
21688         }
21689       }else if( zLike ){
21690         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
21691         rc = 1;
21692         goto meta_command_exit;
21693       }else{
21694         zLike = z;
21695         bSeparate = 1;
21696         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
21697       }
21698     }
21699     if( bSchema ){
21700       zSql = "SELECT lower(name) FROM sqlite_schema"
21701              " WHERE type='table' AND coalesce(rootpage,0)>1"
21702              " UNION ALL SELECT 'sqlite_schema'"
21703              " ORDER BY 1 collate nocase";
21704     }else{
21705       zSql = "SELECT lower(name) FROM sqlite_schema"
21706              " WHERE type='table' AND coalesce(rootpage,0)>1"
21707              " AND name NOT LIKE 'sqlite_%'"
21708              " ORDER BY 1 collate nocase";
21709     }
21710     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
21711     initText(&sQuery);
21712     initText(&sSql);
21713     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
21714     zSep = "VALUES(";
21715     while( SQLITE_ROW==sqlite3_step(pStmt) ){
21716       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
21717       if( zTab==0 ) continue;
21718       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
21719       if( strncmp(zTab, "sqlite_",7)!=0 ){
21720         appendText(&sQuery,"SELECT * FROM ", 0);
21721         appendText(&sQuery,zTab,'"');
21722         appendText(&sQuery," NOT INDEXED;", 0);
21723       }else if( strcmp(zTab, "sqlite_schema")==0 ){
21724         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
21725                            " ORDER BY name;", 0);
21726       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
21727         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
21728                            " ORDER BY name;", 0);
21729       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
21730         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
21731                            " ORDER BY tbl,idx;", 0);
21732       }else if( strcmp(zTab, "sqlite_stat4")==0 ){
21733         appendText(&sQuery, "SELECT * FROM ", 0);
21734         appendText(&sQuery, zTab, 0);
21735         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
21736       }
21737       appendText(&sSql, zSep, 0);
21738       appendText(&sSql, sQuery.z, '\'');
21739       sQuery.n = 0;
21740       appendText(&sSql, ",", 0);
21741       appendText(&sSql, zTab, '\'');
21742       zSep = "),(";
21743     }
21744     sqlite3_finalize(pStmt);
21745     if( bSeparate ){
21746       zSql = sqlite3_mprintf(
21747           "%s))"
21748           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
21749           "   FROM [sha3sum$query]",
21750           sSql.z, iSize);
21751     }else{
21752       zSql = sqlite3_mprintf(
21753           "%s))"
21754           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
21755           "   FROM [sha3sum$query]",
21756           sSql.z, iSize);
21757     }
21758     shell_check_oom(zSql);
21759     freeText(&sQuery);
21760     freeText(&sSql);
21761     if( bDebug ){
21762       utf8_printf(p->out, "%s\n", zSql);
21763     }else{
21764       shell_exec(p, zSql, 0);
21765     }
21766     sqlite3_free(zSql);
21767   }else
21768 
21769 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
21770   if( c=='s'
21771    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
21772   ){
21773     char *zCmd;
21774     int i, x;
21775     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
21776     if( nArg<2 ){
21777       raw_printf(stderr, "Usage: .system COMMAND\n");
21778       rc = 1;
21779       goto meta_command_exit;
21780     }
21781     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
21782     for(i=2; i<nArg && zCmd!=0; i++){
21783       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
21784                              zCmd, azArg[i]);
21785     }
21786     x = zCmd!=0 ? system(zCmd) : 1;
21787     sqlite3_free(zCmd);
21788     if( x ) raw_printf(stderr, "System command returns %d\n", x);
21789   }else
21790 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE) */
21791 
21792   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
21793     static const char *azBool[] = { "off", "on", "trigger", "full"};
21794     const char *zOut;
21795     int i;
21796     if( nArg!=1 ){
21797       raw_printf(stderr, "Usage: .show\n");
21798       rc = 1;
21799       goto meta_command_exit;
21800     }
21801     utf8_printf(p->out, "%12.12s: %s\n","echo",
21802                 azBool[ShellHasFlag(p, SHFLG_Echo)]);
21803     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
21804     utf8_printf(p->out, "%12.12s: %s\n","explain",
21805          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
21806     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
21807     if( p->mode==MODE_Column
21808      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
21809     ){
21810       utf8_printf
21811         (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
21812          modeDescr[p->mode], p->cmOpts.iWrap,
21813          p->cmOpts.bWordWrap ? "on" : "off",
21814          p->cmOpts.bQuote ? "" : "no");
21815     }else{
21816       utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
21817     }
21818     utf8_printf(p->out, "%12.12s: ", "nullvalue");
21819       output_c_string(p->out, p->nullValue);
21820       raw_printf(p->out, "\n");
21821     utf8_printf(p->out,"%12.12s: %s\n","output",
21822             strlen30(p->outfile) ? p->outfile : "stdout");
21823     utf8_printf(p->out,"%12.12s: ", "colseparator");
21824       output_c_string(p->out, p->colSeparator);
21825       raw_printf(p->out, "\n");
21826     utf8_printf(p->out,"%12.12s: ", "rowseparator");
21827       output_c_string(p->out, p->rowSeparator);
21828       raw_printf(p->out, "\n");
21829     switch( p->statsOn ){
21830       case 0:  zOut = "off";     break;
21831       default: zOut = "on";      break;
21832       case 2:  zOut = "stmt";    break;
21833       case 3:  zOut = "vmstep";  break;
21834     }
21835     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
21836     utf8_printf(p->out, "%12.12s: ", "width");
21837     for (i=0;i<p->nWidth;i++) {
21838       raw_printf(p->out, "%d ", p->colWidth[i]);
21839     }
21840     raw_printf(p->out, "\n");
21841     utf8_printf(p->out, "%12.12s: %s\n", "filename",
21842                 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
21843   }else
21844 
21845   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
21846     if( nArg==2 ){
21847       if( strcmp(azArg[1],"stmt")==0 ){
21848         p->statsOn = 2;
21849       }else if( strcmp(azArg[1],"vmstep")==0 ){
21850         p->statsOn = 3;
21851       }else{
21852         p->statsOn = (u8)booleanValue(azArg[1]);
21853       }
21854     }else if( nArg==1 ){
21855       display_stats(p->db, p, 0);
21856     }else{
21857       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
21858       rc = 1;
21859     }
21860   }else
21861 
21862   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
21863    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
21864                  || strncmp(azArg[0], "indexes", n)==0) )
21865   ){
21866     sqlite3_stmt *pStmt;
21867     char **azResult;
21868     int nRow, nAlloc;
21869     int ii;
21870     ShellText s;
21871     initText(&s);
21872     open_db(p, 0);
21873     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
21874     if( rc ){
21875       sqlite3_finalize(pStmt);
21876       return shellDatabaseError(p->db);
21877     }
21878 
21879     if( nArg>2 && c=='i' ){
21880       /* It is an historical accident that the .indexes command shows an error
21881       ** when called with the wrong number of arguments whereas the .tables
21882       ** command does not. */
21883       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
21884       rc = 1;
21885       sqlite3_finalize(pStmt);
21886       goto meta_command_exit;
21887     }
21888     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
21889       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
21890       if( zDbName==0 ) continue;
21891       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
21892       if( sqlite3_stricmp(zDbName, "main")==0 ){
21893         appendText(&s, "SELECT name FROM ", 0);
21894       }else{
21895         appendText(&s, "SELECT ", 0);
21896         appendText(&s, zDbName, '\'');
21897         appendText(&s, "||'.'||name FROM ", 0);
21898       }
21899       appendText(&s, zDbName, '"');
21900       appendText(&s, ".sqlite_schema ", 0);
21901       if( c=='t' ){
21902         appendText(&s," WHERE type IN ('table','view')"
21903                       "   AND name NOT LIKE 'sqlite_%'"
21904                       "   AND name LIKE ?1", 0);
21905       }else{
21906         appendText(&s," WHERE type='index'"
21907                       "   AND tbl_name LIKE ?1", 0);
21908       }
21909     }
21910     rc = sqlite3_finalize(pStmt);
21911     if( rc==SQLITE_OK ){
21912       appendText(&s, " ORDER BY 1", 0);
21913       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
21914     }
21915     freeText(&s);
21916     if( rc ) return shellDatabaseError(p->db);
21917 
21918     /* Run the SQL statement prepared by the above block. Store the results
21919     ** as an array of nul-terminated strings in azResult[].  */
21920     nRow = nAlloc = 0;
21921     azResult = 0;
21922     if( nArg>1 ){
21923       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
21924     }else{
21925       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
21926     }
21927     while( sqlite3_step(pStmt)==SQLITE_ROW ){
21928       if( nRow>=nAlloc ){
21929         char **azNew;
21930         int n2 = nAlloc*2 + 10;
21931         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
21932         shell_check_oom(azNew);
21933         nAlloc = n2;
21934         azResult = azNew;
21935       }
21936       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
21937       shell_check_oom(azResult[nRow]);
21938       nRow++;
21939     }
21940     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
21941       rc = shellDatabaseError(p->db);
21942     }
21943 
21944     /* Pretty-print the contents of array azResult[] to the output */
21945     if( rc==0 && nRow>0 ){
21946       int len, maxlen = 0;
21947       int i, j;
21948       int nPrintCol, nPrintRow;
21949       for(i=0; i<nRow; i++){
21950         len = strlen30(azResult[i]);
21951         if( len>maxlen ) maxlen = len;
21952       }
21953       nPrintCol = 80/(maxlen+2);
21954       if( nPrintCol<1 ) nPrintCol = 1;
21955       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
21956       for(i=0; i<nPrintRow; i++){
21957         for(j=i; j<nRow; j+=nPrintRow){
21958           char *zSp = j<nPrintRow ? "" : "  ";
21959           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
21960                       azResult[j] ? azResult[j]:"");
21961         }
21962         raw_printf(p->out, "\n");
21963       }
21964     }
21965 
21966     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
21967     sqlite3_free(azResult);
21968   }else
21969 
21970 #ifndef SQLITE_SHELL_WASM_MODE
21971   /* Begin redirecting output to the file "testcase-out.txt" */
21972   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
21973     output_reset(p);
21974     p->out = output_file_open("testcase-out.txt", 0);
21975     if( p->out==0 ){
21976       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
21977     }
21978     if( nArg>=2 ){
21979       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
21980     }else{
21981       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
21982     }
21983   }else
21984 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
21985 
21986 #ifndef SQLITE_UNTESTABLE
21987   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
21988     static const struct {
21989        const char *zCtrlName;   /* Name of a test-control option */
21990        int ctrlCode;            /* Integer code for that option */
21991        int unSafe;              /* Not valid for --safe mode */
21992        const char *zUsage;      /* Usage notes */
21993     } aCtrl[] = {
21994       { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
21995       { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
21996     /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
21997     /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
21998       { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
21999       { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
22000     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
22001       { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
22002       { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
22003       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
22004       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
22005       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
22006 #ifdef YYCOVERAGE
22007       { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
22008 #endif
22009       { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
22010       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
22011       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
22012       { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
22013       { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
22014       { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
22015       { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
22016     };
22017     int testctrl = -1;
22018     int iCtrl = -1;
22019     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
22020     int isOk = 0;
22021     int i, n2;
22022     const char *zCmd = 0;
22023 
22024     open_db(p, 0);
22025     zCmd = nArg>=2 ? azArg[1] : "help";
22026 
22027     /* The argument can optionally begin with "-" or "--" */
22028     if( zCmd[0]=='-' && zCmd[1] ){
22029       zCmd++;
22030       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
22031     }
22032 
22033     /* --help lists all test-controls */
22034     if( strcmp(zCmd,"help")==0 ){
22035       utf8_printf(p->out, "Available test-controls:\n");
22036       for(i=0; i<ArraySize(aCtrl); i++){
22037         utf8_printf(p->out, "  .testctrl %s %s\n",
22038                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
22039       }
22040       rc = 1;
22041       goto meta_command_exit;
22042     }
22043 
22044     /* convert testctrl text option to value. allow any unique prefix
22045     ** of the option name, or a numerical value. */
22046     n2 = strlen30(zCmd);
22047     for(i=0; i<ArraySize(aCtrl); i++){
22048       if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
22049         if( testctrl<0 ){
22050           testctrl = aCtrl[i].ctrlCode;
22051           iCtrl = i;
22052         }else{
22053           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
22054                               "Use \".testctrl --help\" for help\n", zCmd);
22055           rc = 1;
22056           goto meta_command_exit;
22057         }
22058       }
22059     }
22060     if( testctrl<0 ){
22061       utf8_printf(stderr,"Error: unknown test-control: %s\n"
22062                          "Use \".testctrl --help\" for help\n", zCmd);
22063     }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
22064       utf8_printf(stderr,
22065          "line %d: \".testctrl %s\" may not be used in safe mode\n",
22066          p->lineno, aCtrl[iCtrl].zCtrlName);
22067       exit(1);
22068     }else{
22069       switch(testctrl){
22070 
22071         /* sqlite3_test_control(int, db, int) */
22072         case SQLITE_TESTCTRL_OPTIMIZATIONS:
22073           if( nArg==3 ){
22074             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
22075             rc2 = sqlite3_test_control(testctrl, p->db, opt);
22076             isOk = 3;
22077           }
22078           break;
22079 
22080         /* sqlite3_test_control(int) */
22081         case SQLITE_TESTCTRL_PRNG_SAVE:
22082         case SQLITE_TESTCTRL_PRNG_RESTORE:
22083         case SQLITE_TESTCTRL_BYTEORDER:
22084           if( nArg==2 ){
22085             rc2 = sqlite3_test_control(testctrl);
22086             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
22087           }
22088           break;
22089 
22090         /* sqlite3_test_control(int, uint) */
22091         case SQLITE_TESTCTRL_PENDING_BYTE:
22092           if( nArg==3 ){
22093             unsigned int opt = (unsigned int)integerValue(azArg[2]);
22094             rc2 = sqlite3_test_control(testctrl, opt);
22095             isOk = 3;
22096           }
22097           break;
22098 
22099         /* sqlite3_test_control(int, int, sqlite3*) */
22100         case SQLITE_TESTCTRL_PRNG_SEED:
22101           if( nArg==3 || nArg==4 ){
22102             int ii = (int)integerValue(azArg[2]);
22103             sqlite3 *db;
22104             if( ii==0 && strcmp(azArg[2],"random")==0 ){
22105               sqlite3_randomness(sizeof(ii),&ii);
22106               printf("-- random seed: %d\n", ii);
22107             }
22108             if( nArg==3 ){
22109               db = 0;
22110             }else{
22111               db = p->db;
22112               /* Make sure the schema has been loaded */
22113               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
22114             }
22115             rc2 = sqlite3_test_control(testctrl, ii, db);
22116             isOk = 3;
22117           }
22118           break;
22119 
22120         /* sqlite3_test_control(int, int) */
22121         case SQLITE_TESTCTRL_ASSERT:
22122         case SQLITE_TESTCTRL_ALWAYS:
22123           if( nArg==3 ){
22124             int opt = booleanValue(azArg[2]);
22125             rc2 = sqlite3_test_control(testctrl, opt);
22126             isOk = 1;
22127           }
22128           break;
22129 
22130         /* sqlite3_test_control(int, int) */
22131         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
22132         case SQLITE_TESTCTRL_NEVER_CORRUPT:
22133           if( nArg==3 ){
22134             int opt = booleanValue(azArg[2]);
22135             rc2 = sqlite3_test_control(testctrl, opt);
22136             isOk = 3;
22137           }
22138           break;
22139 
22140         /* sqlite3_test_control(sqlite3*) */
22141         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
22142           rc2 = sqlite3_test_control(testctrl, p->db);
22143           isOk = 3;
22144           break;
22145 
22146         case SQLITE_TESTCTRL_IMPOSTER:
22147           if( nArg==5 ){
22148             rc2 = sqlite3_test_control(testctrl, p->db,
22149                           azArg[2],
22150                           integerValue(azArg[3]),
22151                           integerValue(azArg[4]));
22152             isOk = 3;
22153           }
22154           break;
22155 
22156         case SQLITE_TESTCTRL_SEEK_COUNT: {
22157           u64 x = 0;
22158           rc2 = sqlite3_test_control(testctrl, p->db, &x);
22159           utf8_printf(p->out, "%llu\n", x);
22160           isOk = 3;
22161           break;
22162         }
22163 
22164 #ifdef YYCOVERAGE
22165         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
22166           if( nArg==2 ){
22167             sqlite3_test_control(testctrl, p->out);
22168             isOk = 3;
22169           }
22170           break;
22171         }
22172 #endif
22173 #ifdef SQLITE_DEBUG
22174         case SQLITE_TESTCTRL_TUNE: {
22175           if( nArg==4 ){
22176             int id = (int)integerValue(azArg[2]);
22177             int val = (int)integerValue(azArg[3]);
22178             sqlite3_test_control(testctrl, id, &val);
22179             isOk = 3;
22180           }else if( nArg==3 ){
22181             int id = (int)integerValue(azArg[2]);
22182             sqlite3_test_control(testctrl, -id, &rc2);
22183             isOk = 1;
22184           }else if( nArg==2 ){
22185             int id = 1;
22186             while(1){
22187               int val = 0;
22188               rc2 = sqlite3_test_control(testctrl, -id, &val);
22189               if( rc2!=SQLITE_OK ) break;
22190               if( id>1 ) utf8_printf(p->out, "  ");
22191               utf8_printf(p->out, "%d: %d", id, val);
22192               id++;
22193             }
22194             if( id>1 ) utf8_printf(p->out, "\n");
22195             isOk = 3;
22196           }
22197           break;
22198         }
22199 #endif
22200         case SQLITE_TESTCTRL_SORTER_MMAP:
22201           if( nArg==3 ){
22202             int opt = (unsigned int)integerValue(azArg[2]);
22203             rc2 = sqlite3_test_control(testctrl, p->db, opt);
22204             isOk = 3;
22205           }
22206           break;
22207       }
22208     }
22209     if( isOk==0 && iCtrl>=0 ){
22210       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
22211       rc = 1;
22212     }else if( isOk==1 ){
22213       raw_printf(p->out, "%d\n", rc2);
22214     }else if( isOk==2 ){
22215       raw_printf(p->out, "0x%08x\n", rc2);
22216     }
22217   }else
22218 #endif /* !defined(SQLITE_UNTESTABLE) */
22219 
22220   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
22221     open_db(p, 0);
22222     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
22223   }else
22224 
22225   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
22226     if( nArg==2 ){
22227       enableTimer = booleanValue(azArg[1]);
22228       if( enableTimer && !HAS_TIMER ){
22229         raw_printf(stderr, "Error: timer not available on this system.\n");
22230         enableTimer = 0;
22231       }
22232     }else{
22233       raw_printf(stderr, "Usage: .timer on|off\n");
22234       rc = 1;
22235     }
22236   }else
22237 
22238 #ifndef SQLITE_OMIT_TRACE
22239   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
22240     int mType = 0;
22241     int jj;
22242     open_db(p, 0);
22243     for(jj=1; jj<nArg; jj++){
22244       const char *z = azArg[jj];
22245       if( z[0]=='-' ){
22246         if( optionMatch(z, "expanded") ){
22247           p->eTraceType = SHELL_TRACE_EXPANDED;
22248         }
22249 #ifdef SQLITE_ENABLE_NORMALIZE
22250         else if( optionMatch(z, "normalized") ){
22251           p->eTraceType = SHELL_TRACE_NORMALIZED;
22252         }
22253 #endif
22254         else if( optionMatch(z, "plain") ){
22255           p->eTraceType = SHELL_TRACE_PLAIN;
22256         }
22257         else if( optionMatch(z, "profile") ){
22258           mType |= SQLITE_TRACE_PROFILE;
22259         }
22260         else if( optionMatch(z, "row") ){
22261           mType |= SQLITE_TRACE_ROW;
22262         }
22263         else if( optionMatch(z, "stmt") ){
22264           mType |= SQLITE_TRACE_STMT;
22265         }
22266         else if( optionMatch(z, "close") ){
22267           mType |= SQLITE_TRACE_CLOSE;
22268         }
22269         else {
22270           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
22271           rc = 1;
22272           goto meta_command_exit;
22273         }
22274       }else{
22275         output_file_close(p->traceOut);
22276         p->traceOut = output_file_open(azArg[1], 0);
22277       }
22278     }
22279     if( p->traceOut==0 ){
22280       sqlite3_trace_v2(p->db, 0, 0, 0);
22281     }else{
22282       if( mType==0 ) mType = SQLITE_TRACE_STMT;
22283       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
22284     }
22285   }else
22286 #endif /* !defined(SQLITE_OMIT_TRACE) */
22287 
22288 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
22289   if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
22290     int ii;
22291     int lenOpt;
22292     char *zOpt;
22293     if( nArg<2 ){
22294       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
22295       rc = 1;
22296       goto meta_command_exit;
22297     }
22298     open_db(p, 0);
22299     zOpt = azArg[1];
22300     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
22301     lenOpt = (int)strlen(zOpt);
22302     if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
22303       assert( azArg[nArg]==0 );
22304       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
22305     }else{
22306       for(ii=1; ii<nArg; ii++){
22307         sqlite3_create_module(p->db, azArg[ii], 0, 0);
22308       }
22309     }
22310   }else
22311 #endif
22312 
22313 #if SQLITE_USER_AUTHENTICATION
22314   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
22315     if( nArg<2 ){
22316       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
22317       rc = 1;
22318       goto meta_command_exit;
22319     }
22320     open_db(p, 0);
22321     if( strcmp(azArg[1],"login")==0 ){
22322       if( nArg!=4 ){
22323         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
22324         rc = 1;
22325         goto meta_command_exit;
22326       }
22327       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
22328                                      strlen30(azArg[3]));
22329       if( rc ){
22330         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
22331         rc = 1;
22332       }
22333     }else if( strcmp(azArg[1],"add")==0 ){
22334       if( nArg!=5 ){
22335         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
22336         rc = 1;
22337         goto meta_command_exit;
22338       }
22339       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
22340                             booleanValue(azArg[4]));
22341       if( rc ){
22342         raw_printf(stderr, "User-Add failed: %d\n", rc);
22343         rc = 1;
22344       }
22345     }else if( strcmp(azArg[1],"edit")==0 ){
22346       if( nArg!=5 ){
22347         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
22348         rc = 1;
22349         goto meta_command_exit;
22350       }
22351       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
22352                               booleanValue(azArg[4]));
22353       if( rc ){
22354         raw_printf(stderr, "User-Edit failed: %d\n", rc);
22355         rc = 1;
22356       }
22357     }else if( strcmp(azArg[1],"delete")==0 ){
22358       if( nArg!=3 ){
22359         raw_printf(stderr, "Usage: .user delete USER\n");
22360         rc = 1;
22361         goto meta_command_exit;
22362       }
22363       rc = sqlite3_user_delete(p->db, azArg[2]);
22364       if( rc ){
22365         raw_printf(stderr, "User-Delete failed: %d\n", rc);
22366         rc = 1;
22367       }
22368     }else{
22369       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
22370       rc = 1;
22371       goto meta_command_exit;
22372     }
22373   }else
22374 #endif /* SQLITE_USER_AUTHENTICATION */
22375 
22376   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
22377     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
22378         sqlite3_libversion(), sqlite3_sourceid());
22379 #if SQLITE_HAVE_ZLIB
22380     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
22381 #endif
22382 #define CTIMEOPT_VAL_(opt) #opt
22383 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
22384 #if defined(__clang__) && defined(__clang_major__)
22385     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
22386                     CTIMEOPT_VAL(__clang_minor__) "."
22387                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
22388 #elif defined(_MSC_VER)
22389     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
22390 #elif defined(__GNUC__) && defined(__VERSION__)
22391     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
22392 #endif
22393   }else
22394 
22395   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
22396     const char *zDbName = nArg==2 ? azArg[1] : "main";
22397     sqlite3_vfs *pVfs = 0;
22398     if( p->db ){
22399       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
22400       if( pVfs ){
22401         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
22402         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
22403         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
22404         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
22405       }
22406     }
22407   }else
22408 
22409   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
22410     sqlite3_vfs *pVfs;
22411     sqlite3_vfs *pCurrent = 0;
22412     if( p->db ){
22413       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
22414     }
22415     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
22416       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
22417            pVfs==pCurrent ? "  <--- CURRENT" : "");
22418       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
22419       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
22420       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
22421       if( pVfs->pNext ){
22422         raw_printf(p->out, "-----------------------------------\n");
22423       }
22424     }
22425   }else
22426 
22427   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
22428     const char *zDbName = nArg==2 ? azArg[1] : "main";
22429     char *zVfsName = 0;
22430     if( p->db ){
22431       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
22432       if( zVfsName ){
22433         utf8_printf(p->out, "%s\n", zVfsName);
22434         sqlite3_free(zVfsName);
22435       }
22436     }
22437   }else
22438 
22439   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
22440     unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
22441     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
22442   }else
22443 
22444   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
22445     int j;
22446     assert( nArg<=ArraySize(azArg) );
22447     p->nWidth = nArg-1;
22448     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
22449     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
22450     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
22451     for(j=1; j<nArg; j++){
22452       p->colWidth[j-1] = (int)integerValue(azArg[j]);
22453     }
22454   }else
22455 
22456   {
22457     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
22458       " \"%s\". Enter \".help\" for help\n", azArg[0]);
22459     rc = 1;
22460   }
22461 
22462 meta_command_exit:
22463   if( p->outCount ){
22464     p->outCount--;
22465     if( p->outCount==0 ) output_reset(p);
22466   }
22467   p->bSafeMode = p->bSafeModePersist;
22468   return rc;
22469 }
22470 
22471 /* Line scan result and intermediate states (supporting scan resumption)
22472 */
22473 #ifndef CHAR_BIT
22474 # define CHAR_BIT 8
22475 #endif
22476 typedef enum {
22477   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
22478   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
22479   QSS_Start = 0
22480 } QuickScanState;
22481 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
22482 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
22483 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
22484 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
22485 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
22486 
22487 /*
22488 ** Scan line for classification to guide shell's handling.
22489 ** The scan is resumable for subsequent lines when prior
22490 ** return values are passed as the 2nd argument.
22491 */
22492 static QuickScanState quickscan(char *zLine, QuickScanState qss){
22493   char cin;
22494   char cWait = (char)qss; /* intentional narrowing loss */
22495   if( cWait==0 ){
22496   PlainScan:
22497     assert( cWait==0 );
22498     while( (cin = *zLine++)!=0 ){
22499       if( IsSpace(cin) )
22500         continue;
22501       switch (cin){
22502       case '-':
22503         if( *zLine!='-' )
22504           break;
22505         while((cin = *++zLine)!=0 )
22506           if( cin=='\n')
22507             goto PlainScan;
22508         return qss;
22509       case ';':
22510         qss |= QSS_EndingSemi;
22511         continue;
22512       case '/':
22513         if( *zLine=='*' ){
22514           ++zLine;
22515           cWait = '*';
22516           qss = QSS_SETV(qss, cWait);
22517           goto TermScan;
22518         }
22519         break;
22520       case '[':
22521         cin = ']';
22522         /* fall thru */
22523       case '`': case '\'': case '"':
22524         cWait = cin;
22525         qss = QSS_HasDark | cWait;
22526         goto TermScan;
22527       default:
22528         break;
22529       }
22530       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
22531     }
22532   }else{
22533   TermScan:
22534     while( (cin = *zLine++)!=0 ){
22535       if( cin==cWait ){
22536         switch( cWait ){
22537         case '*':
22538           if( *zLine != '/' )
22539             continue;
22540           ++zLine;
22541           cWait = 0;
22542           qss = QSS_SETV(qss, 0);
22543           goto PlainScan;
22544         case '`': case '\'': case '"':
22545           if(*zLine==cWait){
22546             ++zLine;
22547             continue;
22548           }
22549           /* fall thru */
22550         case ']':
22551           cWait = 0;
22552           qss = QSS_SETV(qss, 0);
22553           goto PlainScan;
22554         default: assert(0);
22555         }
22556       }
22557     }
22558   }
22559   return qss;
22560 }
22561 
22562 /*
22563 ** Return TRUE if the line typed in is an SQL command terminator other
22564 ** than a semi-colon.  The SQL Server style "go" command is understood
22565 ** as is the Oracle "/".
22566 */
22567 static int line_is_command_terminator(char *zLine){
22568   while( IsSpace(zLine[0]) ){ zLine++; };
22569   if( zLine[0]=='/' )
22570     zLine += 1; /* Oracle */
22571   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
22572     zLine += 2; /* SQL Server */
22573   else
22574     return 0;
22575   return quickscan(zLine, QSS_Start)==QSS_Start;
22576 }
22577 
22578 /*
22579 ** We need a default sqlite3_complete() implementation to use in case
22580 ** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
22581 ** any arbitrary text is a complete SQL statement.  This is not very
22582 ** user-friendly, but it does seem to work.
22583 */
22584 #ifdef SQLITE_OMIT_COMPLETE
22585 #define sqlite3_complete(x) 1
22586 #endif
22587 
22588 /*
22589 ** Return true if zSql is a complete SQL statement.  Return false if it
22590 ** ends in the middle of a string literal or C-style comment.
22591 */
22592 static int line_is_complete(char *zSql, int nSql){
22593   int rc;
22594   if( zSql==0 ) return 1;
22595   zSql[nSql] = ';';
22596   zSql[nSql+1] = 0;
22597   rc = sqlite3_complete(zSql);
22598   zSql[nSql] = 0;
22599   return rc;
22600 }
22601 
22602 /*
22603 ** Run a single line of SQL.  Return the number of errors.
22604 */
22605 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
22606   int rc;
22607   char *zErrMsg = 0;
22608 
22609   open_db(p, 0);
22610   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
22611   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
22612   BEGIN_TIMER;
22613   rc = shell_exec(p, zSql, &zErrMsg);
22614   END_TIMER;
22615   if( rc || zErrMsg ){
22616     char zPrefix[100];
22617     const char *zErrorTail;
22618     const char *zErrorType;
22619     if( zErrMsg==0 ){
22620       zErrorType = "Error";
22621       zErrorTail = sqlite3_errmsg(p->db);
22622     }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
22623       zErrorType = "Parse error";
22624       zErrorTail = &zErrMsg[12];
22625     }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
22626       zErrorType = "Runtime error";
22627       zErrorTail = &zErrMsg[10];
22628     }else{
22629       zErrorType = "Error";
22630       zErrorTail = zErrMsg;
22631     }
22632     if( in!=0 || !stdin_is_interactive ){
22633       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
22634                        "%s near line %d:", zErrorType, startline);
22635     }else{
22636       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
22637     }
22638     utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
22639     sqlite3_free(zErrMsg);
22640     zErrMsg = 0;
22641     return 1;
22642   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
22643     char zLineBuf[2000];
22644     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
22645             "changes: %lld   total_changes: %lld",
22646             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
22647     raw_printf(p->out, "%s\n", zLineBuf);
22648   }
22649   return 0;
22650 }
22651 
22652 static void echo_group_input(ShellState *p, const char *zDo){
22653   if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
22654 }
22655 
22656 #ifdef SQLITE_SHELL_WASM_MODE
22657 /*
22658 ** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
22659 ** because we need the global shellState and cannot access it from that function
22660 ** without moving lots of code around (creating a larger/messier diff).
22661 */
22662 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
22663   /* Parse the next line from shellState.wasm.zInput. */
22664   const char *zBegin = shellState.wasm.zPos;
22665   const char *z = zBegin;
22666   char *zLine = 0;
22667   int nZ = 0;
22668 
22669   UNUSED_PARAMETER(in);
22670   UNUSED_PARAMETER(isContinuation);
22671   if(!z || !*z){
22672     return 0;
22673   }
22674   while(*z && isspace(*z)) ++z;
22675   zBegin = z;
22676   for(; *z && '\n'!=*z; ++nZ, ++z){}
22677   if(nZ>0 && '\r'==zBegin[nZ-1]){
22678     --nZ;
22679   }
22680   shellState.wasm.zPos = z;
22681   zLine = realloc(zPrior, nZ+1);
22682   shell_check_oom(zLine);
22683   memcpy(zLine, zBegin, (size_t)nZ);
22684   zLine[nZ] = 0;
22685   return zLine;
22686 }
22687 #endif /* SQLITE_SHELL_WASM_MODE */
22688 
22689 /*
22690 ** Read input from *in and process it.  If *in==0 then input
22691 ** is interactive - the user is typing it it.  Otherwise, input
22692 ** is coming from a file or device.  A prompt is issued and history
22693 ** is saved only if input is interactive.  An interrupt signal will
22694 ** cause this routine to exit immediately, unless input is interactive.
22695 **
22696 ** Return the number of errors.
22697 */
22698 static int process_input(ShellState *p){
22699   char *zLine = 0;          /* A single input line */
22700   char *zSql = 0;           /* Accumulated SQL text */
22701   int nLine;                /* Length of current line */
22702   int nSql = 0;             /* Bytes of zSql[] used */
22703   int nAlloc = 0;           /* Allocated zSql[] space */
22704   int rc;                   /* Error code */
22705   int errCnt = 0;           /* Number of errors seen */
22706   int startline = 0;        /* Line number for start of current input */
22707   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
22708 
22709   if( p->inputNesting==MAX_INPUT_NESTING ){
22710     /* This will be more informative in a later version. */
22711     utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
22712                 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
22713     return 1;
22714   }
22715   ++p->inputNesting;
22716   p->lineno = 0;
22717   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
22718     fflush(p->out);
22719     zLine = one_input_line(p->in, zLine, nSql>0);
22720     if( zLine==0 ){
22721       /* End of input */
22722       if( p->in==0 && stdin_is_interactive ) printf("\n");
22723       break;
22724     }
22725     if( seenInterrupt ){
22726       if( p->in!=0 ) break;
22727       seenInterrupt = 0;
22728     }
22729     p->lineno++;
22730     if( QSS_INPLAIN(qss)
22731         && line_is_command_terminator(zLine)
22732         && line_is_complete(zSql, nSql) ){
22733       memcpy(zLine,";",2);
22734     }
22735     qss = quickscan(zLine, qss);
22736     if( QSS_PLAINWHITE(qss) && nSql==0 ){
22737       /* Just swallow single-line whitespace */
22738       echo_group_input(p, zLine);
22739       qss = QSS_Start;
22740       continue;
22741     }
22742     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
22743       echo_group_input(p, zLine);
22744       if( zLine[0]=='.' ){
22745         rc = do_meta_command(zLine, p);
22746         if( rc==2 ){ /* exit requested */
22747           break;
22748         }else if( rc ){
22749           errCnt++;
22750         }
22751       }
22752       qss = QSS_Start;
22753       continue;
22754     }
22755     /* No single-line dispositions remain; accumulate line(s). */
22756     nLine = strlen30(zLine);
22757     if( nSql+nLine+2>=nAlloc ){
22758       /* Grow buffer by half-again increments when big. */
22759       nAlloc = nSql+(nSql>>1)+nLine+100;
22760       zSql = realloc(zSql, nAlloc);
22761       shell_check_oom(zSql);
22762     }
22763     if( nSql==0 ){
22764       int i;
22765       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
22766       assert( nAlloc>0 && zSql!=0 );
22767       memcpy(zSql, zLine+i, nLine+1-i);
22768       startline = p->lineno;
22769       nSql = nLine-i;
22770     }else{
22771       zSql[nSql++] = '\n';
22772       memcpy(zSql+nSql, zLine, nLine+1);
22773       nSql += nLine;
22774     }
22775     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
22776       echo_group_input(p, zSql);
22777       errCnt += runOneSqlLine(p, zSql, p->in, startline);
22778       nSql = 0;
22779       if( p->outCount ){
22780         output_reset(p);
22781         p->outCount = 0;
22782       }else{
22783         clearTempFile(p);
22784       }
22785       p->bSafeMode = p->bSafeModePersist;
22786       qss = QSS_Start;
22787     }else if( nSql && QSS_PLAINWHITE(qss) ){
22788       echo_group_input(p, zSql);
22789       nSql = 0;
22790       qss = QSS_Start;
22791     }
22792   }
22793   if( nSql ){
22794     /* This may be incomplete. Let the SQL parser deal with that. */
22795     echo_group_input(p, zSql);
22796     errCnt += runOneSqlLine(p, zSql, p->in, startline);
22797   }
22798   free(zSql);
22799   free(zLine);
22800   --p->inputNesting;
22801   return errCnt>0;
22802 }
22803 
22804 /*
22805 ** Return a pathname which is the user's home directory.  A
22806 ** 0 return indicates an error of some kind.
22807 */
22808 static char *find_home_dir(int clearFlag){
22809   static char *home_dir = NULL;
22810   if( clearFlag ){
22811     free(home_dir);
22812     home_dir = 0;
22813     return 0;
22814   }
22815   if( home_dir ) return home_dir;
22816 
22817 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
22818      && !defined(__RTP__) && !defined(_WRS_KERNEL)
22819   {
22820     struct passwd *pwent;
22821     uid_t uid = getuid();
22822     if( (pwent=getpwuid(uid)) != NULL) {
22823       home_dir = pwent->pw_dir;
22824     }
22825   }
22826 #endif
22827 
22828 #if defined(_WIN32_WCE)
22829   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
22830    */
22831   home_dir = "/";
22832 #else
22833 
22834 #if defined(_WIN32) || defined(WIN32)
22835   if (!home_dir) {
22836     home_dir = getenv("USERPROFILE");
22837   }
22838 #endif
22839 
22840   if (!home_dir) {
22841     home_dir = getenv("HOME");
22842   }
22843 
22844 #if defined(_WIN32) || defined(WIN32)
22845   if (!home_dir) {
22846     char *zDrive, *zPath;
22847     int n;
22848     zDrive = getenv("HOMEDRIVE");
22849     zPath = getenv("HOMEPATH");
22850     if( zDrive && zPath ){
22851       n = strlen30(zDrive) + strlen30(zPath) + 1;
22852       home_dir = malloc( n );
22853       if( home_dir==0 ) return 0;
22854       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
22855       return home_dir;
22856     }
22857     home_dir = "c:\\";
22858   }
22859 #endif
22860 
22861 #endif /* !_WIN32_WCE */
22862 
22863   if( home_dir ){
22864     int n = strlen30(home_dir) + 1;
22865     char *z = malloc( n );
22866     if( z ) memcpy(z, home_dir, n);
22867     home_dir = z;
22868   }
22869 
22870   return home_dir;
22871 }
22872 
22873 /*
22874 ** Read input from the file given by sqliterc_override.  Or if that
22875 ** parameter is NULL, take input from ~/.sqliterc
22876 **
22877 ** Returns the number of errors.
22878 */
22879 static void process_sqliterc(
22880   ShellState *p,                  /* Configuration data */
22881   const char *sqliterc_override   /* Name of config file. NULL to use default */
22882 ){
22883   char *home_dir = NULL;
22884   const char *sqliterc = sqliterc_override;
22885   char *zBuf = 0;
22886   FILE *inSaved = p->in;
22887   int savedLineno = p->lineno;
22888 
22889   if (sqliterc == NULL) {
22890     home_dir = find_home_dir(0);
22891     if( home_dir==0 ){
22892       raw_printf(stderr, "-- warning: cannot find home directory;"
22893                       " cannot read ~/.sqliterc\n");
22894       return;
22895     }
22896     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
22897     shell_check_oom(zBuf);
22898     sqliterc = zBuf;
22899   }
22900   p->in = fopen(sqliterc,"rb");
22901   if( p->in ){
22902     if( stdin_is_interactive ){
22903       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
22904     }
22905     if( process_input(p) && bail_on_error ) exit(1);
22906     fclose(p->in);
22907   }else if( sqliterc_override!=0 ){
22908     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
22909     if( bail_on_error ) exit(1);
22910   }
22911   p->in = inSaved;
22912   p->lineno = savedLineno;
22913   sqlite3_free(zBuf);
22914 }
22915 
22916 /*
22917 ** Show available command line options
22918 */
22919 static const char zOptions[] =
22920 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
22921   "   -A ARGS...           run \".archive ARGS\" and exit\n"
22922 #endif
22923   "   -append              append the database to the end of the file\n"
22924   "   -ascii               set output mode to 'ascii'\n"
22925   "   -bail                stop after hitting an error\n"
22926   "   -batch               force batch I/O\n"
22927   "   -box                 set output mode to 'box'\n"
22928   "   -column              set output mode to 'column'\n"
22929   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
22930   "   -csv                 set output mode to 'csv'\n"
22931 #if !defined(SQLITE_OMIT_DESERIALIZE)
22932   "   -deserialize         open the database using sqlite3_deserialize()\n"
22933 #endif
22934   "   -echo                print inputs before execution\n"
22935   "   -init FILENAME       read/process named file\n"
22936   "   -[no]header          turn headers on or off\n"
22937 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
22938   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
22939 #endif
22940   "   -help                show this message\n"
22941   "   -html                set output mode to HTML\n"
22942   "   -interactive         force interactive I/O\n"
22943   "   -json                set output mode to 'json'\n"
22944   "   -line                set output mode to 'line'\n"
22945   "   -list                set output mode to 'list'\n"
22946   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
22947   "   -markdown            set output mode to 'markdown'\n"
22948 #if !defined(SQLITE_OMIT_DESERIALIZE)
22949   "   -maxsize N           maximum size for a --deserialize database\n"
22950 #endif
22951   "   -memtrace            trace all memory allocations and deallocations\n"
22952   "   -mmap N              default mmap size set to N\n"
22953 #ifdef SQLITE_ENABLE_MULTIPLEX
22954   "   -multiplex           enable the multiplexor VFS\n"
22955 #endif
22956   "   -newline SEP         set output row separator. Default: '\\n'\n"
22957   "   -nofollow            refuse to open symbolic links to database files\n"
22958   "   -nonce STRING        set the safe-mode escape nonce\n"
22959   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
22960   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
22961   "   -quote               set output mode to 'quote'\n"
22962   "   -readonly            open the database read-only\n"
22963   "   -safe                enable safe-mode\n"
22964   "   -separator SEP       set output column separator. Default: '|'\n"
22965 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
22966   "   -sorterref SIZE      sorter references threshold size\n"
22967 #endif
22968   "   -stats               print memory stats before each finalize\n"
22969   "   -table               set output mode to 'table'\n"
22970   "   -tabs                set output mode to 'tabs'\n"
22971   "   -version             show SQLite version\n"
22972   "   -vfs NAME            use NAME as the default VFS\n"
22973 #ifdef SQLITE_ENABLE_VFSTRACE
22974   "   -vfstrace            enable tracing of all VFS calls\n"
22975 #endif
22976 #ifdef SQLITE_HAVE_ZLIB
22977   "   -zip                 open the file as a ZIP Archive\n"
22978 #endif
22979 ;
22980 static void usage(int showDetail){
22981   utf8_printf(stderr,
22982       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
22983       "FILENAME is the name of an SQLite database. A new database is created\n"
22984       "if the file does not previously exist.\n", Argv0);
22985   if( showDetail ){
22986     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
22987   }else{
22988     raw_printf(stderr, "Use the -help option for additional information\n");
22989   }
22990   exit(1);
22991 }
22992 
22993 /*
22994 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
22995 ** error message if it is initialized.
22996 */
22997 static void verify_uninitialized(void){
22998   if( sqlite3_config(-1)==SQLITE_MISUSE ){
22999     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
23000                         " initialization.\n");
23001   }
23002 }
23003 
23004 /*
23005 ** Initialize the state information in data
23006 */
23007 static void main_init(ShellState *data) {
23008   memset(data, 0, sizeof(*data));
23009   data->normalMode = data->cMode = data->mode = MODE_List;
23010   data->autoExplain = 1;
23011   data->pAuxDb = &data->aAuxDb[0];
23012   memcpy(data->colSeparator,SEP_Column, 2);
23013   memcpy(data->rowSeparator,SEP_Row, 2);
23014   data->showHeader = 0;
23015   data->shellFlgs = SHFLG_Lookaside;
23016   verify_uninitialized();
23017   sqlite3_config(SQLITE_CONFIG_URI, 1);
23018   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
23019   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
23020   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
23021   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
23022 }
23023 
23024 /*
23025 ** Output text to the console in a font that attracts extra attention.
23026 */
23027 #ifdef _WIN32
23028 static void printBold(const char *zText){
23029 #if !SQLITE_OS_WINRT
23030   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
23031   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
23032   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
23033   SetConsoleTextAttribute(out,
23034          FOREGROUND_RED|FOREGROUND_INTENSITY
23035   );
23036 #endif
23037   printf("%s", zText);
23038 #if !SQLITE_OS_WINRT
23039   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
23040 #endif
23041 }
23042 #else
23043 static void printBold(const char *zText){
23044   printf("\033[1m%s\033[0m", zText);
23045 }
23046 #endif
23047 
23048 /*
23049 ** Get the argument to an --option.  Throw an error and die if no argument
23050 ** is available.
23051 */
23052 static char *cmdline_option_value(int argc, char **argv, int i){
23053   if( i==argc ){
23054     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
23055             argv[0], argv[argc-1]);
23056     exit(1);
23057   }
23058   return argv[i];
23059 }
23060 
23061 #ifndef SQLITE_SHELL_IS_UTF8
23062 #  if (defined(_WIN32) || defined(WIN32)) \
23063    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
23064 #    define SQLITE_SHELL_IS_UTF8          (0)
23065 #  else
23066 #    define SQLITE_SHELL_IS_UTF8          (1)
23067 #  endif
23068 #endif
23069 
23070 #ifdef SQLITE_SHELL_WASM_MODE
23071 #  define main fiddle_main
23072 #endif
23073 
23074 #if SQLITE_SHELL_IS_UTF8
23075 int SQLITE_CDECL main(int argc, char **argv){
23076 #else
23077 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
23078   char **argv;
23079 #endif
23080 #ifdef SQLITE_DEBUG
23081   sqlite3_uint64 mem_main_enter = sqlite3_memory_used();
23082 #endif
23083   char *zErrMsg = 0;
23084 #ifdef SQLITE_SHELL_WASM_MODE
23085 #  define data shellState
23086 #else
23087   ShellState data;
23088 #endif
23089   const char *zInitFile = 0;
23090   int i;
23091   int rc = 0;
23092   int warnInmemoryDb = 0;
23093   int readStdin = 1;
23094   int nCmd = 0;
23095   char **azCmd = 0;
23096   const char *zVfs = 0;           /* Value of -vfs command-line option */
23097 #if !SQLITE_SHELL_IS_UTF8
23098   char **argvToFree = 0;
23099   int argcToFree = 0;
23100 #endif
23101 
23102   setBinaryMode(stdin, 0);
23103   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
23104 #ifdef SQLITE_SHELL_WASM_MODE
23105   stdin_is_interactive = 0;
23106   stdout_is_console = 1;
23107 #else
23108   stdin_is_interactive = isatty(0);
23109   stdout_is_console = isatty(1);
23110 #endif
23111 
23112 #if !defined(_WIN32_WCE)
23113   if( getenv("SQLITE_DEBUG_BREAK") ){
23114     if( isatty(0) && isatty(2) ){
23115       fprintf(stderr,
23116           "attach debugger to process %d and press any key to continue.\n",
23117           GETPID());
23118       fgetc(stdin);
23119     }else{
23120 #if defined(_WIN32) || defined(WIN32)
23121 #if SQLITE_OS_WINRT
23122       __debugbreak();
23123 #else
23124       DebugBreak();
23125 #endif
23126 #elif defined(SIGTRAP)
23127       raise(SIGTRAP);
23128 #endif
23129     }
23130   }
23131 #endif
23132 
23133 #if USE_SYSTEM_SQLITE+0!=1
23134   if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
23135     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
23136             sqlite3_sourceid(), SQLITE_SOURCE_ID);
23137     exit(1);
23138   }
23139 #endif
23140   main_init(&data);
23141 
23142   /* On Windows, we must translate command-line arguments into UTF-8.
23143   ** The SQLite memory allocator subsystem has to be enabled in order to
23144   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
23145   ** subsequent sqlite3_config() calls will work.  So copy all results into
23146   ** memory that does not come from the SQLite memory allocator.
23147   */
23148 #if !SQLITE_SHELL_IS_UTF8
23149   sqlite3_initialize();
23150   argvToFree = malloc(sizeof(argv[0])*argc*2);
23151   shell_check_oom(argvToFree);
23152   argcToFree = argc;
23153   argv = argvToFree + argc;
23154   for(i=0; i<argc; i++){
23155     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
23156     int n;
23157     shell_check_oom(z);
23158     n = (int)strlen(z);
23159     argv[i] = malloc( n+1 );
23160     shell_check_oom(argv[i]);
23161     memcpy(argv[i], z, n+1);
23162     argvToFree[i] = argv[i];
23163     sqlite3_free(z);
23164   }
23165   sqlite3_shutdown();
23166 #endif
23167 
23168   assert( argc>=1 && argv && argv[0] );
23169   Argv0 = argv[0];
23170 
23171   /* Make sure we have a valid signal handler early, before anything
23172   ** else is done.
23173   */
23174 #ifdef SIGINT
23175   signal(SIGINT, interrupt_handler);
23176 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
23177   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
23178 #endif
23179 
23180 #ifdef SQLITE_SHELL_DBNAME_PROC
23181   {
23182     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
23183     ** of a C-function that will provide the name of the database file.  Use
23184     ** this compile-time option to embed this shell program in larger
23185     ** applications. */
23186     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
23187     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
23188     warnInmemoryDb = 0;
23189   }
23190 #endif
23191 
23192   /* Do an initial pass through the command-line argument to locate
23193   ** the name of the database file, the name of the initialization file,
23194   ** the size of the alternative malloc heap,
23195   ** and the first command to execute.
23196   */
23197   verify_uninitialized();
23198   for(i=1; i<argc; i++){
23199     char *z;
23200     z = argv[i];
23201     if( z[0]!='-' ){
23202       if( data.aAuxDb->zDbFilename==0 ){
23203         data.aAuxDb->zDbFilename = z;
23204       }else{
23205         /* Excesss arguments are interpreted as SQL (or dot-commands) and
23206         ** mean that nothing is read from stdin */
23207         readStdin = 0;
23208         nCmd++;
23209         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
23210         shell_check_oom(azCmd);
23211         azCmd[nCmd-1] = z;
23212       }
23213     }
23214     if( z[1]=='-' ) z++;
23215     if( strcmp(z,"-separator")==0
23216      || strcmp(z,"-nullvalue")==0
23217      || strcmp(z,"-newline")==0
23218      || strcmp(z,"-cmd")==0
23219     ){
23220       (void)cmdline_option_value(argc, argv, ++i);
23221     }else if( strcmp(z,"-init")==0 ){
23222       zInitFile = cmdline_option_value(argc, argv, ++i);
23223     }else if( strcmp(z,"-batch")==0 ){
23224       /* Need to check for batch mode here to so we can avoid printing
23225       ** informational messages (like from process_sqliterc) before
23226       ** we do the actual processing of arguments later in a second pass.
23227       */
23228       stdin_is_interactive = 0;
23229     }else if( strcmp(z,"-heap")==0 ){
23230 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
23231       const char *zSize;
23232       sqlite3_int64 szHeap;
23233 
23234       zSize = cmdline_option_value(argc, argv, ++i);
23235       szHeap = integerValue(zSize);
23236       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
23237       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
23238 #else
23239       (void)cmdline_option_value(argc, argv, ++i);
23240 #endif
23241     }else if( strcmp(z,"-pagecache")==0 ){
23242       sqlite3_int64 n, sz;
23243       sz = integerValue(cmdline_option_value(argc,argv,++i));
23244       if( sz>70000 ) sz = 70000;
23245       if( sz<0 ) sz = 0;
23246       n = integerValue(cmdline_option_value(argc,argv,++i));
23247       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
23248         n = 0xffffffffffffLL/sz;
23249       }
23250       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
23251                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
23252       data.shellFlgs |= SHFLG_Pagecache;
23253     }else if( strcmp(z,"-lookaside")==0 ){
23254       int n, sz;
23255       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
23256       if( sz<0 ) sz = 0;
23257       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
23258       if( n<0 ) n = 0;
23259       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
23260       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
23261     }else if( strcmp(z,"-threadsafe")==0 ){
23262       int n;
23263       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
23264       switch( n ){
23265          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
23266          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
23267          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
23268       }
23269 #ifdef SQLITE_ENABLE_VFSTRACE
23270     }else if( strcmp(z,"-vfstrace")==0 ){
23271       extern int vfstrace_register(
23272          const char *zTraceName,
23273          const char *zOldVfsName,
23274          int (*xOut)(const char*,void*),
23275          void *pOutArg,
23276          int makeDefault
23277       );
23278       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
23279 #endif
23280 #ifdef SQLITE_ENABLE_MULTIPLEX
23281     }else if( strcmp(z,"-multiplex")==0 ){
23282       extern int sqlite3_multiple_initialize(const char*,int);
23283       sqlite3_multiplex_initialize(0, 1);
23284 #endif
23285     }else if( strcmp(z,"-mmap")==0 ){
23286       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
23287       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
23288 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
23289     }else if( strcmp(z,"-sorterref")==0 ){
23290       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
23291       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
23292 #endif
23293     }else if( strcmp(z,"-vfs")==0 ){
23294       zVfs = cmdline_option_value(argc, argv, ++i);
23295 #ifdef SQLITE_HAVE_ZLIB
23296     }else if( strcmp(z,"-zip")==0 ){
23297       data.openMode = SHELL_OPEN_ZIPFILE;
23298 #endif
23299     }else if( strcmp(z,"-append")==0 ){
23300       data.openMode = SHELL_OPEN_APPENDVFS;
23301 #ifndef SQLITE_OMIT_DESERIALIZE
23302     }else if( strcmp(z,"-deserialize")==0 ){
23303       data.openMode = SHELL_OPEN_DESERIALIZE;
23304     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
23305       data.szMax = integerValue(argv[++i]);
23306 #endif
23307     }else if( strcmp(z,"-readonly")==0 ){
23308       data.openMode = SHELL_OPEN_READONLY;
23309     }else if( strcmp(z,"-nofollow")==0 ){
23310       data.openFlags = SQLITE_OPEN_NOFOLLOW;
23311 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
23312     }else if( strncmp(z, "-A",2)==0 ){
23313       /* All remaining command-line arguments are passed to the ".archive"
23314       ** command, so ignore them */
23315       break;
23316 #endif
23317     }else if( strcmp(z, "-memtrace")==0 ){
23318       sqlite3MemTraceActivate(stderr);
23319     }else if( strcmp(z,"-bail")==0 ){
23320       bail_on_error = 1;
23321     }else if( strcmp(z,"-nonce")==0 ){
23322       free(data.zNonce);
23323       data.zNonce = strdup(argv[++i]);
23324     }else if( strcmp(z,"-safe")==0 ){
23325       /* no-op - catch this on the second pass */
23326     }
23327   }
23328   verify_uninitialized();
23329 
23330 
23331 #ifdef SQLITE_SHELL_INIT_PROC
23332   {
23333     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
23334     ** of a C-function that will perform initialization actions on SQLite that
23335     ** occur just before or after sqlite3_initialize(). Use this compile-time
23336     ** option to embed this shell program in larger applications. */
23337     extern void SQLITE_SHELL_INIT_PROC(void);
23338     SQLITE_SHELL_INIT_PROC();
23339   }
23340 #else
23341   /* All the sqlite3_config() calls have now been made. So it is safe
23342   ** to call sqlite3_initialize() and process any command line -vfs option. */
23343   sqlite3_initialize();
23344 #endif
23345 
23346   if( zVfs ){
23347     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
23348     if( pVfs ){
23349       sqlite3_vfs_register(pVfs, 1);
23350     }else{
23351       utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
23352       exit(1);
23353     }
23354   }
23355 
23356   if( data.pAuxDb->zDbFilename==0 ){
23357 #ifndef SQLITE_OMIT_MEMORYDB
23358     data.pAuxDb->zDbFilename = ":memory:";
23359     warnInmemoryDb = argc==1;
23360 #else
23361     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
23362     return 1;
23363 #endif
23364   }
23365   data.out = stdout;
23366 #ifndef SQLITE_SHELL_WASM_MODE
23367   sqlite3_appendvfs_init(0,0,0);
23368 #endif
23369 
23370   /* Go ahead and open the database file if it already exists.  If the
23371   ** file does not exist, delay opening it.  This prevents empty database
23372   ** files from being created if a user mistypes the database name argument
23373   ** to the sqlite command-line tool.
23374   */
23375   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
23376     open_db(&data, 0);
23377   }
23378 
23379   /* Process the initialization file if there is one.  If no -init option
23380   ** is given on the command line, look for a file named ~/.sqliterc and
23381   ** try to process it.
23382   */
23383   process_sqliterc(&data,zInitFile);
23384 
23385   /* Make a second pass through the command-line argument and set
23386   ** options.  This second pass is delayed until after the initialization
23387   ** file is processed so that the command-line arguments will override
23388   ** settings in the initialization file.
23389   */
23390   for(i=1; i<argc; i++){
23391     char *z = argv[i];
23392     if( z[0]!='-' ) continue;
23393     if( z[1]=='-' ){ z++; }
23394     if( strcmp(z,"-init")==0 ){
23395       i++;
23396     }else if( strcmp(z,"-html")==0 ){
23397       data.mode = MODE_Html;
23398     }else if( strcmp(z,"-list")==0 ){
23399       data.mode = MODE_List;
23400     }else if( strcmp(z,"-quote")==0 ){
23401       data.mode = MODE_Quote;
23402       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
23403       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
23404     }else if( strcmp(z,"-line")==0 ){
23405       data.mode = MODE_Line;
23406     }else if( strcmp(z,"-column")==0 ){
23407       data.mode = MODE_Column;
23408     }else if( strcmp(z,"-json")==0 ){
23409       data.mode = MODE_Json;
23410     }else if( strcmp(z,"-markdown")==0 ){
23411       data.mode = MODE_Markdown;
23412     }else if( strcmp(z,"-table")==0 ){
23413       data.mode = MODE_Table;
23414     }else if( strcmp(z,"-box")==0 ){
23415       data.mode = MODE_Box;
23416     }else if( strcmp(z,"-csv")==0 ){
23417       data.mode = MODE_Csv;
23418       memcpy(data.colSeparator,",",2);
23419 #ifdef SQLITE_HAVE_ZLIB
23420     }else if( strcmp(z,"-zip")==0 ){
23421       data.openMode = SHELL_OPEN_ZIPFILE;
23422 #endif
23423     }else if( strcmp(z,"-append")==0 ){
23424       data.openMode = SHELL_OPEN_APPENDVFS;
23425 #ifndef SQLITE_OMIT_DESERIALIZE
23426     }else if( strcmp(z,"-deserialize")==0 ){
23427       data.openMode = SHELL_OPEN_DESERIALIZE;
23428     }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
23429       data.szMax = integerValue(argv[++i]);
23430 #endif
23431     }else if( strcmp(z,"-readonly")==0 ){
23432       data.openMode = SHELL_OPEN_READONLY;
23433     }else if( strcmp(z,"-nofollow")==0 ){
23434       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
23435     }else if( strcmp(z,"-ascii")==0 ){
23436       data.mode = MODE_Ascii;
23437       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
23438       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
23439     }else if( strcmp(z,"-tabs")==0 ){
23440       data.mode = MODE_List;
23441       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
23442       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
23443     }else if( strcmp(z,"-separator")==0 ){
23444       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
23445                        "%s",cmdline_option_value(argc,argv,++i));
23446     }else if( strcmp(z,"-newline")==0 ){
23447       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
23448                        "%s",cmdline_option_value(argc,argv,++i));
23449     }else if( strcmp(z,"-nullvalue")==0 ){
23450       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
23451                        "%s",cmdline_option_value(argc,argv,++i));
23452     }else if( strcmp(z,"-header")==0 ){
23453       data.showHeader = 1;
23454       ShellSetFlag(&data, SHFLG_HeaderSet);
23455      }else if( strcmp(z,"-noheader")==0 ){
23456       data.showHeader = 0;
23457       ShellSetFlag(&data, SHFLG_HeaderSet);
23458     }else if( strcmp(z,"-echo")==0 ){
23459       ShellSetFlag(&data, SHFLG_Echo);
23460     }else if( strcmp(z,"-eqp")==0 ){
23461       data.autoEQP = AUTOEQP_on;
23462     }else if( strcmp(z,"-eqpfull")==0 ){
23463       data.autoEQP = AUTOEQP_full;
23464     }else if( strcmp(z,"-stats")==0 ){
23465       data.statsOn = 1;
23466     }else if( strcmp(z,"-scanstats")==0 ){
23467       data.scanstatsOn = 1;
23468     }else if( strcmp(z,"-backslash")==0 ){
23469       /* Undocumented command-line option: -backslash
23470       ** Causes C-style backslash escapes to be evaluated in SQL statements
23471       ** prior to sending the SQL into SQLite.  Useful for injecting
23472       ** crazy bytes in the middle of SQL statements for testing and debugging.
23473       */
23474       ShellSetFlag(&data, SHFLG_Backslash);
23475     }else if( strcmp(z,"-bail")==0 ){
23476       /* No-op.  The bail_on_error flag should already be set. */
23477     }else if( strcmp(z,"-version")==0 ){
23478       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
23479       return 0;
23480     }else if( strcmp(z,"-interactive")==0 ){
23481       stdin_is_interactive = 1;
23482     }else if( strcmp(z,"-batch")==0 ){
23483       stdin_is_interactive = 0;
23484     }else if( strcmp(z,"-heap")==0 ){
23485       i++;
23486     }else if( strcmp(z,"-pagecache")==0 ){
23487       i+=2;
23488     }else if( strcmp(z,"-lookaside")==0 ){
23489       i+=2;
23490     }else if( strcmp(z,"-threadsafe")==0 ){
23491       i+=2;
23492     }else if( strcmp(z,"-nonce")==0 ){
23493       i += 2;
23494     }else if( strcmp(z,"-mmap")==0 ){
23495       i++;
23496     }else if( strcmp(z,"-memtrace")==0 ){
23497       i++;
23498 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
23499     }else if( strcmp(z,"-sorterref")==0 ){
23500       i++;
23501 #endif
23502     }else if( strcmp(z,"-vfs")==0 ){
23503       i++;
23504 #ifdef SQLITE_ENABLE_VFSTRACE
23505     }else if( strcmp(z,"-vfstrace")==0 ){
23506       i++;
23507 #endif
23508 #ifdef SQLITE_ENABLE_MULTIPLEX
23509     }else if( strcmp(z,"-multiplex")==0 ){
23510       i++;
23511 #endif
23512     }else if( strcmp(z,"-help")==0 ){
23513       usage(1);
23514     }else if( strcmp(z,"-cmd")==0 ){
23515       /* Run commands that follow -cmd first and separately from commands
23516       ** that simply appear on the command-line.  This seems goofy.  It would
23517       ** be better if all commands ran in the order that they appear.  But
23518       ** we retain the goofy behavior for historical compatibility. */
23519       if( i==argc-1 ) break;
23520       z = cmdline_option_value(argc,argv,++i);
23521       if( z[0]=='.' ){
23522         rc = do_meta_command(z, &data);
23523         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
23524       }else{
23525         open_db(&data, 0);
23526         rc = shell_exec(&data, z, &zErrMsg);
23527         if( zErrMsg!=0 ){
23528           utf8_printf(stderr,"Error: %s\n", zErrMsg);
23529           if( bail_on_error ) return rc!=0 ? rc : 1;
23530         }else if( rc!=0 ){
23531           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
23532           if( bail_on_error ) return rc;
23533         }
23534       }
23535 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
23536     }else if( strncmp(z, "-A", 2)==0 ){
23537       if( nCmd>0 ){
23538         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
23539                             " with \"%s\"\n", z);
23540         return 1;
23541       }
23542       open_db(&data, OPEN_DB_ZIPFILE);
23543       if( z[2] ){
23544         argv[i] = &z[2];
23545         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
23546       }else{
23547         arDotCommand(&data, 1, argv+i, argc-i);
23548       }
23549       readStdin = 0;
23550       break;
23551 #endif
23552     }else if( strcmp(z,"-safe")==0 ){
23553       data.bSafeMode = data.bSafeModePersist = 1;
23554     }else{
23555       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
23556       raw_printf(stderr,"Use -help for a list of options.\n");
23557       return 1;
23558     }
23559     data.cMode = data.mode;
23560   }
23561 
23562   if( !readStdin ){
23563     /* Run all arguments that do not begin with '-' as if they were separate
23564     ** command-line inputs, except for the argToSkip argument which contains
23565     ** the database filename.
23566     */
23567     for(i=0; i<nCmd; i++){
23568       if( azCmd[i][0]=='.' ){
23569         rc = do_meta_command(azCmd[i], &data);
23570         if( rc ){
23571           free(azCmd);
23572           return rc==2 ? 0 : rc;
23573         }
23574       }else{
23575         open_db(&data, 0);
23576         rc = shell_exec(&data, azCmd[i], &zErrMsg);
23577         if( zErrMsg || rc ){
23578           if( zErrMsg!=0 ){
23579             utf8_printf(stderr,"Error: %s\n", zErrMsg);
23580           }else{
23581             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
23582           }
23583           sqlite3_free(zErrMsg);
23584           free(azCmd);
23585           return rc!=0 ? rc : 1;
23586         }
23587       }
23588     }
23589   }else{
23590     /* Run commands received from standard input
23591     */
23592     if( stdin_is_interactive ){
23593       char *zHome;
23594       char *zHistory;
23595       int nHistory;
23596       printf(
23597         "SQLite version %s %.19s\n" /*extra-version-info*/
23598         "Enter \".help\" for usage hints.\n",
23599         sqlite3_libversion(), sqlite3_sourceid()
23600       );
23601       if( warnInmemoryDb ){
23602         printf("Connected to a ");
23603         printBold("transient in-memory database");
23604         printf(".\nUse \".open FILENAME\" to reopen on a "
23605                "persistent database.\n");
23606       }
23607       zHistory = getenv("SQLITE_HISTORY");
23608       if( zHistory ){
23609         zHistory = strdup(zHistory);
23610       }else if( (zHome = find_home_dir(0))!=0 ){
23611         nHistory = strlen30(zHome) + 20;
23612         if( (zHistory = malloc(nHistory))!=0 ){
23613           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
23614         }
23615       }
23616       if( zHistory ){ shell_read_history(zHistory); }
23617 #if HAVE_READLINE || HAVE_EDITLINE
23618       rl_attempted_completion_function = readline_completion;
23619 #elif HAVE_LINENOISE
23620       linenoiseSetCompletionCallback(linenoise_completion);
23621 #endif
23622       data.in = 0;
23623       rc = process_input(&data);
23624       if( zHistory ){
23625         shell_stifle_history(2000);
23626         shell_write_history(zHistory);
23627         free(zHistory);
23628       }
23629     }else{
23630       data.in = stdin;
23631       rc = process_input(&data);
23632     }
23633   }
23634 #ifndef SQLITE_SHELL_WASM_MODE
23635   /* In WASM mode we have to leave the db state in place so that
23636   ** client code can "push" SQL into it after this call returns. */
23637   free(azCmd);
23638   set_table_name(&data, 0);
23639   if( data.db ){
23640     session_close_all(&data, -1);
23641     close_db(data.db);
23642   }
23643   for(i=0; i<ArraySize(data.aAuxDb); i++){
23644     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
23645     if( data.aAuxDb[i].db ){
23646       session_close_all(&data, i);
23647       close_db(data.aAuxDb[i].db);
23648     }
23649   }
23650   find_home_dir(1);
23651   output_reset(&data);
23652   data.doXdgOpen = 0;
23653   clearTempFile(&data);
23654 #if !SQLITE_SHELL_IS_UTF8
23655   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
23656   free(argvToFree);
23657 #endif
23658   free(data.colWidth);
23659   free(data.zNonce);
23660   /* Clear the global data structure so that valgrind will detect memory
23661   ** leaks */
23662   memset(&data, 0, sizeof(data));
23663 #ifdef SQLITE_DEBUG
23664   if( sqlite3_memory_used()>mem_main_enter ){
23665     utf8_printf(stderr, "Memory leaked: %u bytes\n",
23666                 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
23667   }
23668 #endif
23669 #endif /* !SQLITE_SHELL_WASM_MODE */
23670   return rc;
23671 }
23672 
23673 
23674 #ifdef SQLITE_SHELL_WASM_MODE
23675 /* Only for emcc experimentation purposes. */
23676 int fiddle_experiment(int a,int b){
23677    return a + b;
23678 }
23679 
23680 /* Only for emcc experimentation purposes.
23681 
23682   Define this function in JS using:
23683 
23684   emcc ... --js-library somefile.js
23685 
23686   containing:
23687 
23688 mergeInto(LibraryManager.library, {
23689     my_foo: function(){
23690         console.debug("my_foo()",arguments);
23691     }
23692 });
23693 */
23694 /*extern void my_foo(sqlite3 *);*/
23695 /* Only for emcc experimentation purposes. */
23696 sqlite3 * fiddle_the_db(){
23697     printf("fiddle_the_db(%p)\n", (const void*)globalDb);
23698     /*my_foo(globalDb);*/
23699     return globalDb;
23700 }
23701 /* Only for emcc experimentation purposes. */
23702 sqlite3 * fiddle_db_arg(sqlite3 *arg){
23703     printf("fiddle_db_arg(%p)\n", (const void*)arg);
23704     return arg;
23705 }
23706 
23707 /*
23708 ** Intended to be called via a SharedWorker() while a separate
23709 ** SharedWorker() (which manages the wasm module) is performing work
23710 ** which should be interrupted. Unfortunately, SharedWorker is not
23711 ** portable enough to make real use of.
23712 */
23713 void fiddle_interrupt(void){
23714   if(globalDb) sqlite3_interrupt(globalDb);
23715 }
23716 
23717 /*
23718 ** Returns the filename of the given db name, assuming "main" if
23719 ** zDbName is NULL. Returns NULL if globalDb is not opened.
23720 */
23721 const char * fiddle_db_filename(const char * zDbName){
23722     return globalDb
23723       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
23724       : NULL;
23725 }
23726 
23727 /*
23728 ** Closes, unlinks, and reopens the db using its current filename (or
23729 ** the default if the db is currently closed). It is assumed, for
23730 ** purposes of the fiddle build, that the file is in a transient
23731 ** virtual filesystem within the browser.
23732 */
23733 void fiddle_reset_db(void){
23734   char *zFilename = 0;
23735   if(0==globalDb){
23736     shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
23737   }else{
23738     zFilename =
23739       sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
23740     shell_check_oom(zFilename);
23741     close_db(globalDb);
23742     shellDeleteFile(zFilename);
23743     shellState.db = 0;
23744     shellState.pAuxDb->zDbFilename = zFilename;
23745   }
23746   open_db(&shellState, 0);
23747   sqlite3_free(zFilename);
23748 }
23749 
23750 /*
23751 ** Trivial exportable function for emscripten. Needs to be exported using:
23752 **
23753 ** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
23754 **
23755 ** (Note the underscore before the function name.) It processes zSql
23756 ** as if it were input to the sqlite3 shell and redirects all output
23757 ** to the wasm binding.
23758 */
23759 void fiddle_exec(const char * zSql){
23760   static int once = 0;
23761   int rc = 0;
23762   if(!once){
23763     /* Simulate an argv array for main() */
23764     static char * argv[] = {"fiddle",
23765                             "-bail",
23766                             "-safe"};
23767     rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
23768     once = rc ? -1 : 1;
23769     memset(&shellState.wasm, 0, sizeof(shellState.wasm));
23770     printf(
23771         "SQLite version %s %.19s\n" /*extra-version-info*/,
23772         sqlite3_libversion(), sqlite3_sourceid()
23773     );
23774     puts("WASM shell");
23775     puts("Enter \".help\" for usage hints.");
23776     if(once>0){
23777       fiddle_reset_db();
23778     }
23779     if(shellState.db){
23780       printf("Connected to %s.\n", fiddle_db_filename(NULL));
23781     }else{
23782       fprintf(stderr,"ERROR initializing db!\n");
23783       return;
23784     }
23785   }
23786   if(once<0){
23787     puts("DB init failed. Not executing SQL.");
23788   }else if(zSql && *zSql){
23789     shellState.wasm.zInput = zSql;
23790     shellState.wasm.zPos = zSql;
23791     process_input(&shellState);
23792     memset(&shellState.wasm, 0, sizeof(shellState.wasm));
23793   }
23794 }
23795 #endif /* SQLITE_SHELL_WASM_MODE */
23796