xref: /freebsd/contrib/sqlite3/shell.c (revision 2b833162)
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 typedef unsigned int u32;
38 typedef unsigned short int u16;
39 
40 /*
41 ** Optionally #include a user-defined header, whereby compilation options
42 ** may be set prior to where they take effect, but after platform setup.
43 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
44 ** file. Note that this macro has a like effect on sqlite3.c compilation.
45 */
46 # define SHELL_STRINGIFY_(f) #f
47 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
48 #ifdef SQLITE_CUSTOM_INCLUDE
49 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
50 #endif
51 
52 /*
53 ** Determine if we are dealing with WinRT, which provides only a subset of
54 ** the full Win32 API.
55 */
56 #if !defined(SQLITE_OS_WINRT)
57 # define SQLITE_OS_WINRT 0
58 #endif
59 
60 /*
61 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
62 ** somewhat for use as a WASM module in a web browser. This flag
63 ** should only be used when building the "fiddle" web application, as
64 ** the browser-mode build has much different user input requirements
65 ** and this build mode rewires the user input subsystem to account for
66 ** that.
67 */
68 
69 /*
70 ** Warning pragmas copied from msvc.h in the core.
71 */
72 #if defined(_MSC_VER)
73 #pragma warning(disable : 4054)
74 #pragma warning(disable : 4055)
75 #pragma warning(disable : 4100)
76 #pragma warning(disable : 4127)
77 #pragma warning(disable : 4130)
78 #pragma warning(disable : 4152)
79 #pragma warning(disable : 4189)
80 #pragma warning(disable : 4206)
81 #pragma warning(disable : 4210)
82 #pragma warning(disable : 4232)
83 #pragma warning(disable : 4244)
84 #pragma warning(disable : 4305)
85 #pragma warning(disable : 4306)
86 #pragma warning(disable : 4702)
87 #pragma warning(disable : 4706)
88 #endif /* defined(_MSC_VER) */
89 
90 /*
91 ** No support for loadable extensions in VxWorks.
92 */
93 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
94 # define SQLITE_OMIT_LOAD_EXTENSION 1
95 #endif
96 
97 /*
98 ** Enable large-file support for fopen() and friends on unix.
99 */
100 #ifndef SQLITE_DISABLE_LFS
101 # define _LARGE_FILE       1
102 # ifndef _FILE_OFFSET_BITS
103 #   define _FILE_OFFSET_BITS 64
104 # endif
105 # define _LARGEFILE_SOURCE 1
106 #endif
107 
108 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
109 /*
110 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
111 ** to expose strdup().
112 */
113 # define _POSIX_SOURCE
114 #endif
115 
116 #include <stdlib.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include <assert.h>
120 #include "sqlite3.h"
121 typedef sqlite3_int64 i64;
122 typedef sqlite3_uint64 u64;
123 typedef unsigned char u8;
124 #if SQLITE_USER_AUTHENTICATION
125 # include "sqlite3userauth.h"
126 #endif
127 #include <ctype.h>
128 #include <stdarg.h>
129 
130 #if !defined(_WIN32) && !defined(WIN32)
131 # include <signal.h>
132 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
133 #  include <pwd.h>
134 # endif
135 #endif
136 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
137 # include <unistd.h>
138 # include <dirent.h>
139 # define GETPID getpid
140 # if defined(__MINGW32__)
141 #  define DIRENT dirent
142 #  ifndef S_ISLNK
143 #   define S_ISLNK(mode) (0)
144 #  endif
145 # endif
146 #else
147 # define GETPID (int)GetCurrentProcessId
148 #endif
149 #include <sys/types.h>
150 #include <sys/stat.h>
151 
152 #if HAVE_READLINE
153 # include <readline/readline.h>
154 # include <readline/history.h>
155 #endif
156 
157 #if HAVE_EDITLINE
158 # include <editline/readline.h>
159 #endif
160 
161 #if HAVE_EDITLINE || HAVE_READLINE
162 
163 # define shell_add_history(X) add_history(X)
164 # define shell_read_history(X) read_history(X)
165 # define shell_write_history(X) write_history(X)
166 # define shell_stifle_history(X) stifle_history(X)
167 # define shell_readline(X) readline(X)
168 
169 #elif HAVE_LINENOISE
170 
171 # include "linenoise.h"
172 # define shell_add_history(X) linenoiseHistoryAdd(X)
173 # define shell_read_history(X) linenoiseHistoryLoad(X)
174 # define shell_write_history(X) linenoiseHistorySave(X)
175 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
176 # define shell_readline(X) linenoise(X)
177 
178 #else
179 
180 # define shell_read_history(X)
181 # define shell_write_history(X)
182 # define shell_stifle_history(X)
183 
184 # define SHELL_USE_LOCAL_GETLINE 1
185 #endif
186 
187 #ifndef deliberate_fall_through
188 /* Quiet some compilers about some of our intentional code. */
189 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
190 #  define deliberate_fall_through __attribute__((fallthrough));
191 # else
192 #  define deliberate_fall_through
193 # endif
194 #endif
195 
196 #if defined(_WIN32) || defined(WIN32)
197 # if SQLITE_OS_WINRT
198 #  define SQLITE_OMIT_POPEN 1
199 # else
200 #  include <io.h>
201 #  include <fcntl.h>
202 #  define isatty(h) _isatty(h)
203 #  ifndef access
204 #   define access(f,m) _access((f),(m))
205 #  endif
206 #  ifndef unlink
207 #   define unlink _unlink
208 #  endif
209 #  ifndef strdup
210 #   define strdup _strdup
211 #  endif
212 #  undef popen
213 #  define popen _popen
214 #  undef pclose
215 #  define pclose _pclose
216 # endif
217 #else
218  /* Make sure isatty() has a prototype. */
219  extern int isatty(int);
220 
221 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
222   /* popen and pclose are not C89 functions and so are
223   ** sometimes omitted from the <stdio.h> header */
224    extern FILE *popen(const char*,const char*);
225    extern int pclose(FILE*);
226 # else
227 #  define SQLITE_OMIT_POPEN 1
228 # endif
229 #endif
230 
231 #if defined(_WIN32_WCE)
232 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
233  * thus we always assume that we have a console. That can be
234  * overridden with the -batch command line option.
235  */
236 #define isatty(x) 1
237 #endif
238 
239 /* ctype macros that work with signed characters */
240 #define IsSpace(X)  isspace((unsigned char)X)
241 #define IsDigit(X)  isdigit((unsigned char)X)
242 #define ToLower(X)  (char)tolower((unsigned char)X)
243 
244 #if defined(_WIN32) || defined(WIN32)
245 #if SQLITE_OS_WINRT
246 #include <intrin.h>
247 #endif
248 #include <windows.h>
249 
250 /* string conversion routines only needed on Win32 */
251 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
252 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
253 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
254 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
255 #endif
256 
257 /* On Windows, we normally run with output mode of TEXT so that \n characters
258 ** are automatically translated into \r\n.  However, this behavior needs
259 ** to be disabled in some cases (ex: when generating CSV output and when
260 ** rendering quoted strings that contain \n characters).  The following
261 ** routines take care of that.
262 */
263 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
264 static void setBinaryMode(FILE *file, int isOutput){
265   if( isOutput ) fflush(file);
266   _setmode(_fileno(file), _O_BINARY);
267 }
268 static void setTextMode(FILE *file, int isOutput){
269   if( isOutput ) fflush(file);
270   _setmode(_fileno(file), _O_TEXT);
271 }
272 #else
273 # define setBinaryMode(X,Y)
274 # define setTextMode(X,Y)
275 #endif
276 
277 /* True if the timer is enabled */
278 static int enableTimer = 0;
279 
280 /* A version of strcmp() that works with NULL values */
281 static int cli_strcmp(const char *a, const char *b){
282   if( a==0 ) a = "";
283   if( b==0 ) b = "";
284   return strcmp(a,b);
285 }
286 static int cli_strncmp(const char *a, const char *b, size_t n){
287   if( a==0 ) a = "";
288   if( b==0 ) b = "";
289   return strncmp(a,b,n);
290 }
291 
292 /* Return the current wall-clock time */
293 static sqlite3_int64 timeOfDay(void){
294   static sqlite3_vfs *clockVfs = 0;
295   sqlite3_int64 t;
296   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
297   if( clockVfs==0 ) return 0;  /* Never actually happens */
298   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
299     clockVfs->xCurrentTimeInt64(clockVfs, &t);
300   }else{
301     double r;
302     clockVfs->xCurrentTime(clockVfs, &r);
303     t = (sqlite3_int64)(r*86400000.0);
304   }
305   return t;
306 }
307 
308 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
309 #include <sys/time.h>
310 #include <sys/resource.h>
311 
312 /* VxWorks does not support getrusage() as far as we can determine */
313 #if defined(_WRS_KERNEL) || defined(__RTP__)
314 struct rusage {
315   struct timeval ru_utime; /* user CPU time used */
316   struct timeval ru_stime; /* system CPU time used */
317 };
318 #define getrusage(A,B) memset(B,0,sizeof(*B))
319 #endif
320 
321 /* Saved resource information for the beginning of an operation */
322 static struct rusage sBegin;  /* CPU time at start */
323 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
324 
325 /*
326 ** Begin timing an operation
327 */
328 static void beginTimer(void){
329   if( enableTimer ){
330     getrusage(RUSAGE_SELF, &sBegin);
331     iBegin = timeOfDay();
332   }
333 }
334 
335 /* Return the difference of two time_structs in seconds */
336 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
337   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
338          (double)(pEnd->tv_sec - pStart->tv_sec);
339 }
340 
341 /*
342 ** Print the timing results.
343 */
344 static void endTimer(void){
345   if( enableTimer ){
346     sqlite3_int64 iEnd = timeOfDay();
347     struct rusage sEnd;
348     getrusage(RUSAGE_SELF, &sEnd);
349     printf("Run Time: real %.3f user %f sys %f\n",
350        (iEnd - iBegin)*0.001,
351        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
352        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
353   }
354 }
355 
356 #define BEGIN_TIMER beginTimer()
357 #define END_TIMER endTimer()
358 #define HAS_TIMER 1
359 
360 #elif (defined(_WIN32) || defined(WIN32))
361 
362 /* Saved resource information for the beginning of an operation */
363 static HANDLE hProcess;
364 static FILETIME ftKernelBegin;
365 static FILETIME ftUserBegin;
366 static sqlite3_int64 ftWallBegin;
367 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
368                                     LPFILETIME, LPFILETIME);
369 static GETPROCTIMES getProcessTimesAddr = NULL;
370 
371 /*
372 ** Check to see if we have timer support.  Return 1 if necessary
373 ** support found (or found previously).
374 */
375 static int hasTimer(void){
376   if( getProcessTimesAddr ){
377     return 1;
378   } else {
379 #if !SQLITE_OS_WINRT
380     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
381     ** versions. See if the version we are running on has it, and if it
382     ** does, save off a pointer to it and the current process handle.
383     */
384     hProcess = GetCurrentProcess();
385     if( hProcess ){
386       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
387       if( NULL != hinstLib ){
388         getProcessTimesAddr =
389             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
390         if( NULL != getProcessTimesAddr ){
391           return 1;
392         }
393         FreeLibrary(hinstLib);
394       }
395     }
396 #endif
397   }
398   return 0;
399 }
400 
401 /*
402 ** Begin timing an operation
403 */
404 static void beginTimer(void){
405   if( enableTimer && getProcessTimesAddr ){
406     FILETIME ftCreation, ftExit;
407     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
408                         &ftKernelBegin,&ftUserBegin);
409     ftWallBegin = timeOfDay();
410   }
411 }
412 
413 /* Return the difference of two FILETIME structs in seconds */
414 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
415   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
416   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
417   return (double) ((i64End - i64Start) / 10000000.0);
418 }
419 
420 /*
421 ** Print the timing results.
422 */
423 static void endTimer(void){
424   if( enableTimer && getProcessTimesAddr){
425     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
426     sqlite3_int64 ftWallEnd = timeOfDay();
427     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
428     printf("Run Time: real %.3f user %f sys %f\n",
429        (ftWallEnd - ftWallBegin)*0.001,
430        timeDiff(&ftUserBegin, &ftUserEnd),
431        timeDiff(&ftKernelBegin, &ftKernelEnd));
432   }
433 }
434 
435 #define BEGIN_TIMER beginTimer()
436 #define END_TIMER endTimer()
437 #define HAS_TIMER hasTimer()
438 
439 #else
440 #define BEGIN_TIMER
441 #define END_TIMER
442 #define HAS_TIMER 0
443 #endif
444 
445 /*
446 ** Used to prevent warnings about unused parameters
447 */
448 #define UNUSED_PARAMETER(x) (void)(x)
449 
450 /*
451 ** Number of elements in an array
452 */
453 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
454 
455 /*
456 ** If the following flag is set, then command execution stops
457 ** at an error if we are not interactive.
458 */
459 static int bail_on_error = 0;
460 
461 /*
462 ** Threat stdin as an interactive input if the following variable
463 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
464 */
465 static int stdin_is_interactive = 1;
466 
467 /*
468 ** On Windows systems we have to know if standard output is a console
469 ** in order to translate UTF-8 into MBCS.  The following variable is
470 ** true if translation is required.
471 */
472 static int stdout_is_console = 1;
473 
474 /*
475 ** The following is the open SQLite database.  We make a pointer
476 ** to this database a static variable so that it can be accessed
477 ** by the SIGINT handler to interrupt database processing.
478 */
479 static sqlite3 *globalDb = 0;
480 
481 /*
482 ** True if an interrupt (Control-C) has been received.
483 */
484 static volatile int seenInterrupt = 0;
485 
486 /*
487 ** This is the name of our program. It is set in main(), used
488 ** in a number of other places, mostly for error messages.
489 */
490 static char *Argv0;
491 
492 /*
493 ** Prompt strings. Initialized in main. Settable with
494 **   .prompt main continue
495 */
496 #define PROMPT_LEN_MAX 20
497 /* First line prompt.   default: "sqlite> " */
498 static char mainPrompt[PROMPT_LEN_MAX];
499 /* Continuation prompt. default: "   ...> " */
500 static char continuePrompt[PROMPT_LEN_MAX];
501 
502 /* This is variant of the standard-library strncpy() routine with the
503 ** one change that the destination string is always zero-terminated, even
504 ** if there is no zero-terminator in the first n-1 characters of the source
505 ** string.
506 */
507 static char *shell_strncpy(char *dest, const char *src, size_t n){
508   size_t i;
509   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
510   dest[i] = 0;
511   return dest;
512 }
513 
514 /*
515 ** Optionally disable dynamic continuation prompt.
516 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
517 ** or open parentheses level if non-zero, or continuation prompt as set.
518 ** This facility interacts with the scanner and process_input() where the
519 ** below 5 macros are used.
520 */
521 #ifdef SQLITE_OMIT_DYNAPROMPT
522 # define CONTINUATION_PROMPT continuePrompt
523 # define CONTINUE_PROMPT_RESET
524 # define CONTINUE_PROMPT_AWAITS(p,s)
525 # define CONTINUE_PROMPT_AWAITC(p,c)
526 # define CONTINUE_PAREN_INCR(p,n)
527 # define CONTINUE_PROMPT_PSTATE 0
528 typedef void *t_NoDynaPrompt;
529 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
530 #else
531 # define CONTINUATION_PROMPT dynamicContinuePrompt()
532 # define CONTINUE_PROMPT_RESET \
533   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
534 # define CONTINUE_PROMPT_AWAITS(p,s) \
535   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
536 # define CONTINUE_PROMPT_AWAITC(p,c) \
537   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
538 # define CONTINUE_PAREN_INCR(p,n) \
539   if(p && stdin_is_interactive) (trackParenLevel(p,n))
540 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
541 typedef struct DynaPrompt *t_DynaPromptRef;
542 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
543 
544 static struct DynaPrompt {
545   char dynamicPrompt[PROMPT_LEN_MAX];
546   char acAwait[2];
547   int inParenLevel;
548   char *zScannerAwaits;
549 } dynPrompt = { {0}, {0}, 0, 0 };
550 
551 /* Record parenthesis nesting level change, or force level to 0. */
552 static void trackParenLevel(struct DynaPrompt *p, int ni){
553   p->inParenLevel += ni;
554   if( ni==0 ) p->inParenLevel = 0;
555   p->zScannerAwaits = 0;
556 }
557 
558 /* Record that a lexeme is opened, or closed with args==0. */
559 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
560   if( s!=0 || c==0 ){
561     p->zScannerAwaits = s;
562     p->acAwait[0] = 0;
563   }else{
564     p->acAwait[0] = c;
565     p->zScannerAwaits = p->acAwait;
566   }
567 }
568 
569 /* Upon demand, derive the continuation prompt to display. */
570 static char *dynamicContinuePrompt(void){
571   if( continuePrompt[0]==0
572       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
573     return continuePrompt;
574   }else{
575     if( dynPrompt.zScannerAwaits ){
576       size_t ncp = strlen(continuePrompt);
577       size_t ndp = strlen(dynPrompt.zScannerAwaits);
578       if( ndp > ncp-3 ) return continuePrompt;
579       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
580       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
581       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
582               PROMPT_LEN_MAX-4);
583     }else{
584       if( dynPrompt.inParenLevel>9 ){
585         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
586       }else if( dynPrompt.inParenLevel<0 ){
587         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
588       }else{
589         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
590         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
591       }
592       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, PROMPT_LEN_MAX-4);
593     }
594   }
595   return dynPrompt.dynamicPrompt;
596 }
597 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
598 
599 /*
600 ** Render output like fprintf().  Except, if the output is going to the
601 ** console and if this is running on a Windows machine, translate the
602 ** output from UTF-8 into MBCS.
603 */
604 #if defined(_WIN32) || defined(WIN32)
605 void utf8_printf(FILE *out, const char *zFormat, ...){
606   va_list ap;
607   va_start(ap, zFormat);
608   if( stdout_is_console && (out==stdout || out==stderr) ){
609     char *z1 = sqlite3_vmprintf(zFormat, ap);
610     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
611     sqlite3_free(z1);
612     fputs(z2, out);
613     sqlite3_free(z2);
614   }else{
615     vfprintf(out, zFormat, ap);
616   }
617   va_end(ap);
618 }
619 #elif !defined(utf8_printf)
620 # define utf8_printf fprintf
621 #endif
622 
623 /*
624 ** Render output like fprintf().  This should not be used on anything that
625 ** includes string formatting (e.g. "%s").
626 */
627 #if !defined(raw_printf)
628 # define raw_printf fprintf
629 #endif
630 
631 /* Indicate out-of-memory and exit. */
632 static void shell_out_of_memory(void){
633   raw_printf(stderr,"Error: out of memory\n");
634   exit(1);
635 }
636 
637 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
638 ** out-of-memory error.
639 */
640 static void shell_check_oom(void *p){
641   if( p==0 ) shell_out_of_memory();
642 }
643 
644 /*
645 ** Write I/O traces to the following stream.
646 */
647 #ifdef SQLITE_ENABLE_IOTRACE
648 static FILE *iotrace = 0;
649 #endif
650 
651 /*
652 ** This routine works like printf in that its first argument is a
653 ** format string and subsequent arguments are values to be substituted
654 ** in place of % fields.  The result of formatting this string
655 ** is written to iotrace.
656 */
657 #ifdef SQLITE_ENABLE_IOTRACE
658 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
659   va_list ap;
660   char *z;
661   if( iotrace==0 ) return;
662   va_start(ap, zFormat);
663   z = sqlite3_vmprintf(zFormat, ap);
664   va_end(ap);
665   utf8_printf(iotrace, "%s", z);
666   sqlite3_free(z);
667 }
668 #endif
669 
670 /*
671 ** Output string zUtf to stream pOut as w characters.  If w is negative,
672 ** then right-justify the text.  W is the width in UTF-8 characters, not
673 ** in bytes.  This is different from the %*.*s specification in printf
674 ** since with %*.*s the width is measured in bytes, not characters.
675 */
676 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
677   int i;
678   int n;
679   int aw = w<0 ? -w : w;
680   if( zUtf==0 ) zUtf = "";
681   for(i=n=0; zUtf[i]; i++){
682     if( (zUtf[i]&0xc0)!=0x80 ){
683       n++;
684       if( n==aw ){
685         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
686         break;
687       }
688     }
689   }
690   if( n>=aw ){
691     utf8_printf(pOut, "%.*s", i, zUtf);
692   }else if( w<0 ){
693     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
694   }else{
695     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
696   }
697 }
698 
699 
700 /*
701 ** Determines if a string is a number of not.
702 */
703 static int isNumber(const char *z, int *realnum){
704   if( *z=='-' || *z=='+' ) z++;
705   if( !IsDigit(*z) ){
706     return 0;
707   }
708   z++;
709   if( realnum ) *realnum = 0;
710   while( IsDigit(*z) ){ z++; }
711   if( *z=='.' ){
712     z++;
713     if( !IsDigit(*z) ) return 0;
714     while( IsDigit(*z) ){ z++; }
715     if( realnum ) *realnum = 1;
716   }
717   if( *z=='e' || *z=='E' ){
718     z++;
719     if( *z=='+' || *z=='-' ) z++;
720     if( !IsDigit(*z) ) return 0;
721     while( IsDigit(*z) ){ z++; }
722     if( realnum ) *realnum = 1;
723   }
724   return *z==0;
725 }
726 
727 /*
728 ** Compute a string length that is limited to what can be stored in
729 ** lower 30 bits of a 32-bit signed integer.
730 */
731 static int strlen30(const char *z){
732   const char *z2 = z;
733   while( *z2 ){ z2++; }
734   return 0x3fffffff & (int)(z2 - z);
735 }
736 
737 /*
738 ** Return the length of a string in characters.  Multibyte UTF8 characters
739 ** count as a single character.
740 */
741 static int strlenChar(const char *z){
742   int n = 0;
743   while( *z ){
744     if( (0xc0&*(z++))!=0x80 ) n++;
745   }
746   return n;
747 }
748 
749 /*
750 ** Return open FILE * if zFile exists, can be opened for read
751 ** and is an ordinary file or a character stream source.
752 ** Otherwise return 0.
753 */
754 static FILE * openChrSource(const char *zFile){
755 #ifdef _WIN32
756   struct _stat x = {0};
757 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
758   /* On Windows, open first, then check the stream nature. This order
759   ** is necessary because _stat() and sibs, when checking a named pipe,
760   ** effectively break the pipe as its supplier sees it. */
761   FILE *rv = fopen(zFile, "rb");
762   if( rv==0 ) return 0;
763   if( _fstat(_fileno(rv), &x) != 0
764       || !STAT_CHR_SRC(x.st_mode)){
765     fclose(rv);
766     rv = 0;
767   }
768   return rv;
769 #else
770   struct stat x = {0};
771   int rc = stat(zFile, &x);
772 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
773   if( rc!=0 ) return 0;
774   if( STAT_CHR_SRC(x.st_mode) ){
775     return fopen(zFile, "rb");
776   }else{
777     return 0;
778   }
779 #endif
780 #undef STAT_CHR_SRC
781 }
782 
783 /*
784 ** This routine reads a line of text from FILE in, stores
785 ** the text in memory obtained from malloc() and returns a pointer
786 ** to the text.  NULL is returned at end of file, or if malloc()
787 ** fails.
788 **
789 ** If zLine is not NULL then it is a malloced buffer returned from
790 ** a previous call to this routine that may be reused.
791 */
792 static char *local_getline(char *zLine, FILE *in){
793   int nLine = zLine==0 ? 0 : 100;
794   int n = 0;
795 
796   while( 1 ){
797     if( n+100>nLine ){
798       nLine = nLine*2 + 100;
799       zLine = realloc(zLine, nLine);
800       shell_check_oom(zLine);
801     }
802     if( fgets(&zLine[n], nLine - n, in)==0 ){
803       if( n==0 ){
804         free(zLine);
805         return 0;
806       }
807       zLine[n] = 0;
808       break;
809     }
810     while( zLine[n] ) n++;
811     if( n>0 && zLine[n-1]=='\n' ){
812       n--;
813       if( n>0 && zLine[n-1]=='\r' ) n--;
814       zLine[n] = 0;
815       break;
816     }
817   }
818 #if defined(_WIN32) || defined(WIN32)
819   /* For interactive input on Windows systems, translate the
820   ** multi-byte characterset characters into UTF-8. */
821   if( stdin_is_interactive && in==stdin ){
822     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
823     if( zTrans ){
824       i64 nTrans = strlen(zTrans)+1;
825       if( nTrans>nLine ){
826         zLine = realloc(zLine, nTrans);
827         shell_check_oom(zLine);
828       }
829       memcpy(zLine, zTrans, nTrans);
830       sqlite3_free(zTrans);
831     }
832   }
833 #endif /* defined(_WIN32) || defined(WIN32) */
834   return zLine;
835 }
836 
837 /*
838 ** Retrieve a single line of input text.
839 **
840 ** If in==0 then read from standard input and prompt before each line.
841 ** If isContinuation is true, then a continuation prompt is appropriate.
842 ** If isContinuation is zero, then the main prompt should be used.
843 **
844 ** If zPrior is not NULL then it is a buffer from a prior call to this
845 ** routine that can be reused.
846 **
847 ** The result is stored in space obtained from malloc() and must either
848 ** be freed by the caller or else passed back into this routine via the
849 ** zPrior argument for reuse.
850 */
851 #ifndef SQLITE_SHELL_FIDDLE
852 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
853   char *zPrompt;
854   char *zResult;
855   if( in!=0 ){
856     zResult = local_getline(zPrior, in);
857   }else{
858     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
859 #if SHELL_USE_LOCAL_GETLINE
860     printf("%s", zPrompt);
861     fflush(stdout);
862     zResult = local_getline(zPrior, stdin);
863 #else
864     free(zPrior);
865     zResult = shell_readline(zPrompt);
866     if( zResult && *zResult ) shell_add_history(zResult);
867 #endif
868   }
869   return zResult;
870 }
871 #endif /* !SQLITE_SHELL_FIDDLE */
872 
873 /*
874 ** Return the value of a hexadecimal digit.  Return -1 if the input
875 ** is not a hex digit.
876 */
877 static int hexDigitValue(char c){
878   if( c>='0' && c<='9' ) return c - '0';
879   if( c>='a' && c<='f' ) return c - 'a' + 10;
880   if( c>='A' && c<='F' ) return c - 'A' + 10;
881   return -1;
882 }
883 
884 /*
885 ** Interpret zArg as an integer value, possibly with suffixes.
886 */
887 static sqlite3_int64 integerValue(const char *zArg){
888   sqlite3_int64 v = 0;
889   static const struct { char *zSuffix; int iMult; } aMult[] = {
890     { "KiB", 1024 },
891     { "MiB", 1024*1024 },
892     { "GiB", 1024*1024*1024 },
893     { "KB",  1000 },
894     { "MB",  1000000 },
895     { "GB",  1000000000 },
896     { "K",   1000 },
897     { "M",   1000000 },
898     { "G",   1000000000 },
899   };
900   int i;
901   int isNeg = 0;
902   if( zArg[0]=='-' ){
903     isNeg = 1;
904     zArg++;
905   }else if( zArg[0]=='+' ){
906     zArg++;
907   }
908   if( zArg[0]=='0' && zArg[1]=='x' ){
909     int x;
910     zArg += 2;
911     while( (x = hexDigitValue(zArg[0]))>=0 ){
912       v = (v<<4) + x;
913       zArg++;
914     }
915   }else{
916     while( IsDigit(zArg[0]) ){
917       v = v*10 + zArg[0] - '0';
918       zArg++;
919     }
920   }
921   for(i=0; i<ArraySize(aMult); i++){
922     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
923       v *= aMult[i].iMult;
924       break;
925     }
926   }
927   return isNeg? -v : v;
928 }
929 
930 /*
931 ** A variable length string to which one can append text.
932 */
933 typedef struct ShellText ShellText;
934 struct ShellText {
935   char *z;
936   int n;
937   int nAlloc;
938 };
939 
940 /*
941 ** Initialize and destroy a ShellText object
942 */
943 static void initText(ShellText *p){
944   memset(p, 0, sizeof(*p));
945 }
946 static void freeText(ShellText *p){
947   free(p->z);
948   initText(p);
949 }
950 
951 /* zIn is either a pointer to a NULL-terminated string in memory obtained
952 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
953 ** added to zIn, and the result returned in memory obtained from malloc().
954 ** zIn, if it was not NULL, is freed.
955 **
956 ** If the third argument, quote, is not '\0', then it is used as a
957 ** quote character for zAppend.
958 */
959 static void appendText(ShellText *p, const char *zAppend, char quote){
960   i64 len;
961   i64 i;
962   i64 nAppend = strlen30(zAppend);
963 
964   len = nAppend+p->n+1;
965   if( quote ){
966     len += 2;
967     for(i=0; i<nAppend; i++){
968       if( zAppend[i]==quote ) len++;
969     }
970   }
971 
972   if( p->z==0 || p->n+len>=p->nAlloc ){
973     p->nAlloc = p->nAlloc*2 + len + 20;
974     p->z = realloc(p->z, p->nAlloc);
975     shell_check_oom(p->z);
976   }
977 
978   if( quote ){
979     char *zCsr = p->z+p->n;
980     *zCsr++ = quote;
981     for(i=0; i<nAppend; i++){
982       *zCsr++ = zAppend[i];
983       if( zAppend[i]==quote ) *zCsr++ = quote;
984     }
985     *zCsr++ = quote;
986     p->n = (int)(zCsr - p->z);
987     *zCsr = '\0';
988   }else{
989     memcpy(p->z+p->n, zAppend, nAppend);
990     p->n += nAppend;
991     p->z[p->n] = '\0';
992   }
993 }
994 
995 /*
996 ** Attempt to determine if identifier zName needs to be quoted, either
997 ** because it contains non-alphanumeric characters, or because it is an
998 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
999 ** that quoting is required.
1000 **
1001 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1002 */
1003 static char quoteChar(const char *zName){
1004   int i;
1005   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1006   for(i=0; zName[i]; i++){
1007     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1008   }
1009   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1010 }
1011 
1012 /*
1013 ** Construct a fake object name and column list to describe the structure
1014 ** of the view, virtual table, or table valued function zSchema.zName.
1015 */
1016 static char *shellFakeSchema(
1017   sqlite3 *db,            /* The database connection containing the vtab */
1018   const char *zSchema,    /* Schema of the database holding the vtab */
1019   const char *zName       /* The name of the virtual table */
1020 ){
1021   sqlite3_stmt *pStmt = 0;
1022   char *zSql;
1023   ShellText s;
1024   char cQuote;
1025   char *zDiv = "(";
1026   int nRow = 0;
1027 
1028   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1029                          zSchema ? zSchema : "main", zName);
1030   shell_check_oom(zSql);
1031   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1032   sqlite3_free(zSql);
1033   initText(&s);
1034   if( zSchema ){
1035     cQuote = quoteChar(zSchema);
1036     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1037     appendText(&s, zSchema, cQuote);
1038     appendText(&s, ".", 0);
1039   }
1040   cQuote = quoteChar(zName);
1041   appendText(&s, zName, cQuote);
1042   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1043     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1044     nRow++;
1045     appendText(&s, zDiv, 0);
1046     zDiv = ",";
1047     if( zCol==0 ) zCol = "";
1048     cQuote = quoteChar(zCol);
1049     appendText(&s, zCol, cQuote);
1050   }
1051   appendText(&s, ")", 0);
1052   sqlite3_finalize(pStmt);
1053   if( nRow==0 ){
1054     freeText(&s);
1055     s.z = 0;
1056   }
1057   return s.z;
1058 }
1059 
1060 /*
1061 ** SQL function:  shell_module_schema(X)
1062 **
1063 ** Return a fake schema for the table-valued function or eponymous virtual
1064 ** table X.
1065 */
1066 static void shellModuleSchema(
1067   sqlite3_context *pCtx,
1068   int nVal,
1069   sqlite3_value **apVal
1070 ){
1071   const char *zName;
1072   char *zFake;
1073   UNUSED_PARAMETER(nVal);
1074   zName = (const char*)sqlite3_value_text(apVal[0]);
1075   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1076   if( zFake ){
1077     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1078                         -1, sqlite3_free);
1079     free(zFake);
1080   }
1081 }
1082 
1083 /*
1084 ** SQL function:  shell_add_schema(S,X)
1085 **
1086 ** Add the schema name X to the CREATE statement in S and return the result.
1087 ** Examples:
1088 **
1089 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
1090 **
1091 ** Also works on
1092 **
1093 **    CREATE INDEX
1094 **    CREATE UNIQUE INDEX
1095 **    CREATE VIEW
1096 **    CREATE TRIGGER
1097 **    CREATE VIRTUAL TABLE
1098 **
1099 ** This UDF is used by the .schema command to insert the schema name of
1100 ** attached databases into the middle of the sqlite_schema.sql field.
1101 */
1102 static void shellAddSchemaName(
1103   sqlite3_context *pCtx,
1104   int nVal,
1105   sqlite3_value **apVal
1106 ){
1107   static const char *aPrefix[] = {
1108      "TABLE",
1109      "INDEX",
1110      "UNIQUE INDEX",
1111      "VIEW",
1112      "TRIGGER",
1113      "VIRTUAL TABLE"
1114   };
1115   int i = 0;
1116   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1117   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1118   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1119   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1120   UNUSED_PARAMETER(nVal);
1121   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1122     for(i=0; i<ArraySize(aPrefix); i++){
1123       int n = strlen30(aPrefix[i]);
1124       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1125         char *z = 0;
1126         char *zFake = 0;
1127         if( zSchema ){
1128           char cQuote = quoteChar(zSchema);
1129           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1130             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1131           }else{
1132             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1133           }
1134         }
1135         if( zName
1136          && aPrefix[i][0]=='V'
1137          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1138         ){
1139           if( z==0 ){
1140             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1141           }else{
1142             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1143           }
1144           free(zFake);
1145         }
1146         if( z ){
1147           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1148           return;
1149         }
1150       }
1151     }
1152   }
1153   sqlite3_result_value(pCtx, apVal[0]);
1154 }
1155 
1156 /*
1157 ** The source code for several run-time loadable extensions is inserted
1158 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1159 ** code, we need to override some macros to make the included program code
1160 ** work here in the middle of this regular program.
1161 */
1162 #define SQLITE_EXTENSION_INIT1
1163 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1164 
1165 #if defined(_WIN32) && defined(_MSC_VER)
1166 /************************* Begin test_windirent.h ******************/
1167 /*
1168 ** 2015 November 30
1169 **
1170 ** The author disclaims copyright to this source code.  In place of
1171 ** a legal notice, here is a blessing:
1172 **
1173 **    May you do good and not evil.
1174 **    May you find forgiveness for yourself and forgive others.
1175 **    May you share freely, never taking more than you give.
1176 **
1177 *************************************************************************
1178 ** This file contains declarations for most of the opendir() family of
1179 ** POSIX functions on Win32 using the MSVCRT.
1180 */
1181 
1182 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1183 #define SQLITE_WINDIRENT_H
1184 
1185 /*
1186 ** We need several data types from the Windows SDK header.
1187 */
1188 
1189 #ifndef WIN32_LEAN_AND_MEAN
1190 #define WIN32_LEAN_AND_MEAN
1191 #endif
1192 
1193 #include "windows.h"
1194 
1195 /*
1196 ** We need several support functions from the SQLite core.
1197 */
1198 
1199 /* #include "sqlite3.h" */
1200 
1201 /*
1202 ** We need several things from the ANSI and MSVCRT headers.
1203 */
1204 
1205 #include <stdio.h>
1206 #include <stdlib.h>
1207 #include <errno.h>
1208 #include <io.h>
1209 #include <limits.h>
1210 #include <sys/types.h>
1211 #include <sys/stat.h>
1212 
1213 /*
1214 ** We may need several defines that should have been in "sys/stat.h".
1215 */
1216 
1217 #ifndef S_ISREG
1218 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1219 #endif
1220 
1221 #ifndef S_ISDIR
1222 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1223 #endif
1224 
1225 #ifndef S_ISLNK
1226 #define S_ISLNK(mode) (0)
1227 #endif
1228 
1229 /*
1230 ** We may need to provide the "mode_t" type.
1231 */
1232 
1233 #ifndef MODE_T_DEFINED
1234   #define MODE_T_DEFINED
1235   typedef unsigned short mode_t;
1236 #endif
1237 
1238 /*
1239 ** We may need to provide the "ino_t" type.
1240 */
1241 
1242 #ifndef INO_T_DEFINED
1243   #define INO_T_DEFINED
1244   typedef unsigned short ino_t;
1245 #endif
1246 
1247 /*
1248 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1249 */
1250 
1251 #ifndef NAME_MAX
1252 #  ifdef FILENAME_MAX
1253 #    define NAME_MAX (FILENAME_MAX)
1254 #  else
1255 #    define NAME_MAX (260)
1256 #  endif
1257 #endif
1258 
1259 /*
1260 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1261 */
1262 
1263 #ifndef NULL_INTPTR_T
1264 #  define NULL_INTPTR_T ((intptr_t)(0))
1265 #endif
1266 
1267 #ifndef BAD_INTPTR_T
1268 #  define BAD_INTPTR_T ((intptr_t)(-1))
1269 #endif
1270 
1271 /*
1272 ** We need to provide the necessary structures and related types.
1273 */
1274 
1275 #ifndef DIRENT_DEFINED
1276 #define DIRENT_DEFINED
1277 typedef struct DIRENT DIRENT;
1278 typedef DIRENT *LPDIRENT;
1279 struct DIRENT {
1280   ino_t d_ino;               /* Sequence number, do not use. */
1281   unsigned d_attributes;     /* Win32 file attributes. */
1282   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1283 };
1284 #endif
1285 
1286 #ifndef DIR_DEFINED
1287 #define DIR_DEFINED
1288 typedef struct DIR DIR;
1289 typedef DIR *LPDIR;
1290 struct DIR {
1291   intptr_t d_handle; /* Value returned by "_findfirst". */
1292   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1293   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1294 };
1295 #endif
1296 
1297 /*
1298 ** Provide a macro, for use by the implementation, to determine if a
1299 ** particular directory entry should be skipped over when searching for
1300 ** the next directory entry that should be returned by the readdir() or
1301 ** readdir_r() functions.
1302 */
1303 
1304 #ifndef is_filtered
1305 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1306 #endif
1307 
1308 /*
1309 ** Provide the function prototype for the POSIX compatiable getenv()
1310 ** function.  This function is not thread-safe.
1311 */
1312 
1313 extern const char *windirent_getenv(const char *name);
1314 
1315 /*
1316 ** Finally, we can provide the function prototypes for the opendir(),
1317 ** readdir(), readdir_r(), and closedir() POSIX functions.
1318 */
1319 
1320 extern LPDIR opendir(const char *dirname);
1321 extern LPDIRENT readdir(LPDIR dirp);
1322 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1323 extern INT closedir(LPDIR dirp);
1324 
1325 #endif /* defined(WIN32) && defined(_MSC_VER) */
1326 
1327 /************************* End test_windirent.h ********************/
1328 /************************* Begin test_windirent.c ******************/
1329 /*
1330 ** 2015 November 30
1331 **
1332 ** The author disclaims copyright to this source code.  In place of
1333 ** a legal notice, here is a blessing:
1334 **
1335 **    May you do good and not evil.
1336 **    May you find forgiveness for yourself and forgive others.
1337 **    May you share freely, never taking more than you give.
1338 **
1339 *************************************************************************
1340 ** This file contains code to implement most of the opendir() family of
1341 ** POSIX functions on Win32 using the MSVCRT.
1342 */
1343 
1344 #if defined(_WIN32) && defined(_MSC_VER)
1345 /* #include "test_windirent.h" */
1346 
1347 /*
1348 ** Implementation of the POSIX getenv() function using the Win32 API.
1349 ** This function is not thread-safe.
1350 */
1351 const char *windirent_getenv(
1352   const char *name
1353 ){
1354   static char value[32768]; /* Maximum length, per MSDN */
1355   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1356   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1357 
1358   memset(value, 0, sizeof(value));
1359   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1360   if( dwRet==0 || dwRet>dwSize ){
1361     /*
1362     ** The function call to GetEnvironmentVariableA() failed -OR-
1363     ** the buffer is not large enough.  Either way, return NULL.
1364     */
1365     return 0;
1366   }else{
1367     /*
1368     ** The function call to GetEnvironmentVariableA() succeeded
1369     ** -AND- the buffer contains the entire value.
1370     */
1371     return value;
1372   }
1373 }
1374 
1375 /*
1376 ** Implementation of the POSIX opendir() function using the MSVCRT.
1377 */
1378 LPDIR opendir(
1379   const char *dirname
1380 ){
1381   struct _finddata_t data;
1382   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1383   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1384 
1385   if( dirp==NULL ) return NULL;
1386   memset(dirp, 0, sizeof(DIR));
1387 
1388   /* TODO: Remove this if Unix-style root paths are not used. */
1389   if( sqlite3_stricmp(dirname, "/")==0 ){
1390     dirname = windirent_getenv("SystemDrive");
1391   }
1392 
1393   memset(&data, 0, sizeof(struct _finddata_t));
1394   _snprintf(data.name, namesize, "%s\\*", dirname);
1395   dirp->d_handle = _findfirst(data.name, &data);
1396 
1397   if( dirp->d_handle==BAD_INTPTR_T ){
1398     closedir(dirp);
1399     return NULL;
1400   }
1401 
1402   /* TODO: Remove this block to allow hidden and/or system files. */
1403   if( is_filtered(data) ){
1404 next:
1405 
1406     memset(&data, 0, sizeof(struct _finddata_t));
1407     if( _findnext(dirp->d_handle, &data)==-1 ){
1408       closedir(dirp);
1409       return NULL;
1410     }
1411 
1412     /* TODO: Remove this block to allow hidden and/or system files. */
1413     if( is_filtered(data) ) goto next;
1414   }
1415 
1416   dirp->d_first.d_attributes = data.attrib;
1417   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1418   dirp->d_first.d_name[NAME_MAX] = '\0';
1419 
1420   return dirp;
1421 }
1422 
1423 /*
1424 ** Implementation of the POSIX readdir() function using the MSVCRT.
1425 */
1426 LPDIRENT readdir(
1427   LPDIR dirp
1428 ){
1429   struct _finddata_t data;
1430 
1431   if( dirp==NULL ) return NULL;
1432 
1433   if( dirp->d_first.d_ino==0 ){
1434     dirp->d_first.d_ino++;
1435     dirp->d_next.d_ino++;
1436 
1437     return &dirp->d_first;
1438   }
1439 
1440 next:
1441 
1442   memset(&data, 0, sizeof(struct _finddata_t));
1443   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1444 
1445   /* TODO: Remove this block to allow hidden and/or system files. */
1446   if( is_filtered(data) ) goto next;
1447 
1448   dirp->d_next.d_ino++;
1449   dirp->d_next.d_attributes = data.attrib;
1450   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1451   dirp->d_next.d_name[NAME_MAX] = '\0';
1452 
1453   return &dirp->d_next;
1454 }
1455 
1456 /*
1457 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1458 */
1459 INT readdir_r(
1460   LPDIR dirp,
1461   LPDIRENT entry,
1462   LPDIRENT *result
1463 ){
1464   struct _finddata_t data;
1465 
1466   if( dirp==NULL ) return EBADF;
1467 
1468   if( dirp->d_first.d_ino==0 ){
1469     dirp->d_first.d_ino++;
1470     dirp->d_next.d_ino++;
1471 
1472     entry->d_ino = dirp->d_first.d_ino;
1473     entry->d_attributes = dirp->d_first.d_attributes;
1474     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1475     entry->d_name[NAME_MAX] = '\0';
1476 
1477     *result = entry;
1478     return 0;
1479   }
1480 
1481 next:
1482 
1483   memset(&data, 0, sizeof(struct _finddata_t));
1484   if( _findnext(dirp->d_handle, &data)==-1 ){
1485     *result = NULL;
1486     return ENOENT;
1487   }
1488 
1489   /* TODO: Remove this block to allow hidden and/or system files. */
1490   if( is_filtered(data) ) goto next;
1491 
1492   entry->d_ino = (ino_t)-1; /* not available */
1493   entry->d_attributes = data.attrib;
1494   strncpy(entry->d_name, data.name, NAME_MAX);
1495   entry->d_name[NAME_MAX] = '\0';
1496 
1497   *result = entry;
1498   return 0;
1499 }
1500 
1501 /*
1502 ** Implementation of the POSIX closedir() function using the MSVCRT.
1503 */
1504 INT closedir(
1505   LPDIR dirp
1506 ){
1507   INT result = 0;
1508 
1509   if( dirp==NULL ) return EINVAL;
1510 
1511   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1512     result = _findclose(dirp->d_handle);
1513   }
1514 
1515   sqlite3_free(dirp);
1516   return result;
1517 }
1518 
1519 #endif /* defined(WIN32) && defined(_MSC_VER) */
1520 
1521 /************************* End test_windirent.c ********************/
1522 #define dirent DIRENT
1523 #endif
1524 /************************* Begin ../ext/misc/memtrace.c ******************/
1525 /*
1526 ** 2019-01-21
1527 **
1528 ** The author disclaims copyright to this source code.  In place of
1529 ** a legal notice, here is a blessing:
1530 **
1531 **    May you do good and not evil.
1532 **    May you find forgiveness for yourself and forgive others.
1533 **    May you share freely, never taking more than you give.
1534 **
1535 *************************************************************************
1536 **
1537 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
1538 ** mechanism to add a tracing layer on top of SQLite.  If this extension
1539 ** is registered prior to sqlite3_initialize(), it will cause all memory
1540 ** allocation activities to be logged on standard output, or to some other
1541 ** FILE specified by the initializer.
1542 **
1543 ** This file needs to be compiled into the application that uses it.
1544 **
1545 ** This extension is used to implement the --memtrace option of the
1546 ** command-line shell.
1547 */
1548 #include <assert.h>
1549 #include <string.h>
1550 #include <stdio.h>
1551 
1552 /* The original memory allocation routines */
1553 static sqlite3_mem_methods memtraceBase;
1554 static FILE *memtraceOut;
1555 
1556 /* Methods that trace memory allocations */
1557 static void *memtraceMalloc(int n){
1558   if( memtraceOut ){
1559     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
1560             memtraceBase.xRoundup(n));
1561   }
1562   return memtraceBase.xMalloc(n);
1563 }
1564 static void memtraceFree(void *p){
1565   if( p==0 ) return;
1566   if( memtraceOut ){
1567     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
1568   }
1569   memtraceBase.xFree(p);
1570 }
1571 static void *memtraceRealloc(void *p, int n){
1572   if( p==0 ) return memtraceMalloc(n);
1573   if( n==0 ){
1574     memtraceFree(p);
1575     return 0;
1576   }
1577   if( memtraceOut ){
1578     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
1579             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
1580   }
1581   return memtraceBase.xRealloc(p, n);
1582 }
1583 static int memtraceSize(void *p){
1584   return memtraceBase.xSize(p);
1585 }
1586 static int memtraceRoundup(int n){
1587   return memtraceBase.xRoundup(n);
1588 }
1589 static int memtraceInit(void *p){
1590   return memtraceBase.xInit(p);
1591 }
1592 static void memtraceShutdown(void *p){
1593   memtraceBase.xShutdown(p);
1594 }
1595 
1596 /* The substitute memory allocator */
1597 static sqlite3_mem_methods ersaztMethods = {
1598   memtraceMalloc,
1599   memtraceFree,
1600   memtraceRealloc,
1601   memtraceSize,
1602   memtraceRoundup,
1603   memtraceInit,
1604   memtraceShutdown,
1605   0
1606 };
1607 
1608 /* Begin tracing memory allocations to out. */
1609 int sqlite3MemTraceActivate(FILE *out){
1610   int rc = SQLITE_OK;
1611   if( memtraceBase.xMalloc==0 ){
1612     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
1613     if( rc==SQLITE_OK ){
1614       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
1615     }
1616   }
1617   memtraceOut = out;
1618   return rc;
1619 }
1620 
1621 /* Deactivate memory tracing */
1622 int sqlite3MemTraceDeactivate(void){
1623   int rc = SQLITE_OK;
1624   if( memtraceBase.xMalloc!=0 ){
1625     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
1626     if( rc==SQLITE_OK ){
1627       memset(&memtraceBase, 0, sizeof(memtraceBase));
1628     }
1629   }
1630   memtraceOut = 0;
1631   return rc;
1632 }
1633 
1634 /************************* End ../ext/misc/memtrace.c ********************/
1635 /************************* Begin ../ext/misc/shathree.c ******************/
1636 /*
1637 ** 2017-03-08
1638 **
1639 ** The author disclaims copyright to this source code.  In place of
1640 ** a legal notice, here is a blessing:
1641 **
1642 **    May you do good and not evil.
1643 **    May you find forgiveness for yourself and forgive others.
1644 **    May you share freely, never taking more than you give.
1645 **
1646 ******************************************************************************
1647 **
1648 ** This SQLite extension implements functions that compute SHA3 hashes.
1649 ** Two SQL functions are implemented:
1650 **
1651 **     sha3(X,SIZE)
1652 **     sha3_query(Y,SIZE)
1653 **
1654 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1655 ** X is NULL.
1656 **
1657 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
1658 ** and returns a hash of their results.
1659 **
1660 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1661 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1662 ** 384, or 512, to determine SHA3 hash variant that is computed.
1663 */
1664 /* #include "sqlite3ext.h" */
1665 SQLITE_EXTENSION_INIT1
1666 #include <assert.h>
1667 #include <string.h>
1668 #include <stdarg.h>
1669 
1670 #ifndef SQLITE_AMALGAMATION
1671 /* typedef sqlite3_uint64 u64; */
1672 #endif /* SQLITE_AMALGAMATION */
1673 
1674 /******************************************************************************
1675 ** The Hash Engine
1676 */
1677 /*
1678 ** Macros to determine whether the machine is big or little endian,
1679 ** and whether or not that determination is run-time or compile-time.
1680 **
1681 ** For best performance, an attempt is made to guess at the byte-order
1682 ** using C-preprocessor macros.  If that is unsuccessful, or if
1683 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1684 ** at run-time.
1685 */
1686 #ifndef SHA3_BYTEORDER
1687 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1688      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1689      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1690      defined(__arm__)
1691 #   define SHA3_BYTEORDER    1234
1692 # elif defined(sparc)    || defined(__ppc__)
1693 #   define SHA3_BYTEORDER    4321
1694 # else
1695 #   define SHA3_BYTEORDER 0
1696 # endif
1697 #endif
1698 
1699 
1700 /*
1701 ** State structure for a SHA3 hash in progress
1702 */
1703 typedef struct SHA3Context SHA3Context;
1704 struct SHA3Context {
1705   union {
1706     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1707     unsigned char x[1600];    /* ... or 1600 bytes */
1708   } u;
1709   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1710   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1711   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1712 };
1713 
1714 /*
1715 ** A single step of the Keccak mixing function for a 1600-bit state
1716 */
1717 static void KeccakF1600Step(SHA3Context *p){
1718   int i;
1719   u64 b0, b1, b2, b3, b4;
1720   u64 c0, c1, c2, c3, c4;
1721   u64 d0, d1, d2, d3, d4;
1722   static const u64 RC[] = {
1723     0x0000000000000001ULL,  0x0000000000008082ULL,
1724     0x800000000000808aULL,  0x8000000080008000ULL,
1725     0x000000000000808bULL,  0x0000000080000001ULL,
1726     0x8000000080008081ULL,  0x8000000000008009ULL,
1727     0x000000000000008aULL,  0x0000000000000088ULL,
1728     0x0000000080008009ULL,  0x000000008000000aULL,
1729     0x000000008000808bULL,  0x800000000000008bULL,
1730     0x8000000000008089ULL,  0x8000000000008003ULL,
1731     0x8000000000008002ULL,  0x8000000000000080ULL,
1732     0x000000000000800aULL,  0x800000008000000aULL,
1733     0x8000000080008081ULL,  0x8000000000008080ULL,
1734     0x0000000080000001ULL,  0x8000000080008008ULL
1735   };
1736 # define a00 (p->u.s[0])
1737 # define a01 (p->u.s[1])
1738 # define a02 (p->u.s[2])
1739 # define a03 (p->u.s[3])
1740 # define a04 (p->u.s[4])
1741 # define a10 (p->u.s[5])
1742 # define a11 (p->u.s[6])
1743 # define a12 (p->u.s[7])
1744 # define a13 (p->u.s[8])
1745 # define a14 (p->u.s[9])
1746 # define a20 (p->u.s[10])
1747 # define a21 (p->u.s[11])
1748 # define a22 (p->u.s[12])
1749 # define a23 (p->u.s[13])
1750 # define a24 (p->u.s[14])
1751 # define a30 (p->u.s[15])
1752 # define a31 (p->u.s[16])
1753 # define a32 (p->u.s[17])
1754 # define a33 (p->u.s[18])
1755 # define a34 (p->u.s[19])
1756 # define a40 (p->u.s[20])
1757 # define a41 (p->u.s[21])
1758 # define a42 (p->u.s[22])
1759 # define a43 (p->u.s[23])
1760 # define a44 (p->u.s[24])
1761 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1762 
1763   for(i=0; i<24; i+=4){
1764     c0 = a00^a10^a20^a30^a40;
1765     c1 = a01^a11^a21^a31^a41;
1766     c2 = a02^a12^a22^a32^a42;
1767     c3 = a03^a13^a23^a33^a43;
1768     c4 = a04^a14^a24^a34^a44;
1769     d0 = c4^ROL64(c1, 1);
1770     d1 = c0^ROL64(c2, 1);
1771     d2 = c1^ROL64(c3, 1);
1772     d3 = c2^ROL64(c4, 1);
1773     d4 = c3^ROL64(c0, 1);
1774 
1775     b0 = (a00^d0);
1776     b1 = ROL64((a11^d1), 44);
1777     b2 = ROL64((a22^d2), 43);
1778     b3 = ROL64((a33^d3), 21);
1779     b4 = ROL64((a44^d4), 14);
1780     a00 =   b0 ^((~b1)&  b2 );
1781     a00 ^= RC[i];
1782     a11 =   b1 ^((~b2)&  b3 );
1783     a22 =   b2 ^((~b3)&  b4 );
1784     a33 =   b3 ^((~b4)&  b0 );
1785     a44 =   b4 ^((~b0)&  b1 );
1786 
1787     b2 = ROL64((a20^d0), 3);
1788     b3 = ROL64((a31^d1), 45);
1789     b4 = ROL64((a42^d2), 61);
1790     b0 = ROL64((a03^d3), 28);
1791     b1 = ROL64((a14^d4), 20);
1792     a20 =   b0 ^((~b1)&  b2 );
1793     a31 =   b1 ^((~b2)&  b3 );
1794     a42 =   b2 ^((~b3)&  b4 );
1795     a03 =   b3 ^((~b4)&  b0 );
1796     a14 =   b4 ^((~b0)&  b1 );
1797 
1798     b4 = ROL64((a40^d0), 18);
1799     b0 = ROL64((a01^d1), 1);
1800     b1 = ROL64((a12^d2), 6);
1801     b2 = ROL64((a23^d3), 25);
1802     b3 = ROL64((a34^d4), 8);
1803     a40 =   b0 ^((~b1)&  b2 );
1804     a01 =   b1 ^((~b2)&  b3 );
1805     a12 =   b2 ^((~b3)&  b4 );
1806     a23 =   b3 ^((~b4)&  b0 );
1807     a34 =   b4 ^((~b0)&  b1 );
1808 
1809     b1 = ROL64((a10^d0), 36);
1810     b2 = ROL64((a21^d1), 10);
1811     b3 = ROL64((a32^d2), 15);
1812     b4 = ROL64((a43^d3), 56);
1813     b0 = ROL64((a04^d4), 27);
1814     a10 =   b0 ^((~b1)&  b2 );
1815     a21 =   b1 ^((~b2)&  b3 );
1816     a32 =   b2 ^((~b3)&  b4 );
1817     a43 =   b3 ^((~b4)&  b0 );
1818     a04 =   b4 ^((~b0)&  b1 );
1819 
1820     b3 = ROL64((a30^d0), 41);
1821     b4 = ROL64((a41^d1), 2);
1822     b0 = ROL64((a02^d2), 62);
1823     b1 = ROL64((a13^d3), 55);
1824     b2 = ROL64((a24^d4), 39);
1825     a30 =   b0 ^((~b1)&  b2 );
1826     a41 =   b1 ^((~b2)&  b3 );
1827     a02 =   b2 ^((~b3)&  b4 );
1828     a13 =   b3 ^((~b4)&  b0 );
1829     a24 =   b4 ^((~b0)&  b1 );
1830 
1831     c0 = a00^a20^a40^a10^a30;
1832     c1 = a11^a31^a01^a21^a41;
1833     c2 = a22^a42^a12^a32^a02;
1834     c3 = a33^a03^a23^a43^a13;
1835     c4 = a44^a14^a34^a04^a24;
1836     d0 = c4^ROL64(c1, 1);
1837     d1 = c0^ROL64(c2, 1);
1838     d2 = c1^ROL64(c3, 1);
1839     d3 = c2^ROL64(c4, 1);
1840     d4 = c3^ROL64(c0, 1);
1841 
1842     b0 = (a00^d0);
1843     b1 = ROL64((a31^d1), 44);
1844     b2 = ROL64((a12^d2), 43);
1845     b3 = ROL64((a43^d3), 21);
1846     b4 = ROL64((a24^d4), 14);
1847     a00 =   b0 ^((~b1)&  b2 );
1848     a00 ^= RC[i+1];
1849     a31 =   b1 ^((~b2)&  b3 );
1850     a12 =   b2 ^((~b3)&  b4 );
1851     a43 =   b3 ^((~b4)&  b0 );
1852     a24 =   b4 ^((~b0)&  b1 );
1853 
1854     b2 = ROL64((a40^d0), 3);
1855     b3 = ROL64((a21^d1), 45);
1856     b4 = ROL64((a02^d2), 61);
1857     b0 = ROL64((a33^d3), 28);
1858     b1 = ROL64((a14^d4), 20);
1859     a40 =   b0 ^((~b1)&  b2 );
1860     a21 =   b1 ^((~b2)&  b3 );
1861     a02 =   b2 ^((~b3)&  b4 );
1862     a33 =   b3 ^((~b4)&  b0 );
1863     a14 =   b4 ^((~b0)&  b1 );
1864 
1865     b4 = ROL64((a30^d0), 18);
1866     b0 = ROL64((a11^d1), 1);
1867     b1 = ROL64((a42^d2), 6);
1868     b2 = ROL64((a23^d3), 25);
1869     b3 = ROL64((a04^d4), 8);
1870     a30 =   b0 ^((~b1)&  b2 );
1871     a11 =   b1 ^((~b2)&  b3 );
1872     a42 =   b2 ^((~b3)&  b4 );
1873     a23 =   b3 ^((~b4)&  b0 );
1874     a04 =   b4 ^((~b0)&  b1 );
1875 
1876     b1 = ROL64((a20^d0), 36);
1877     b2 = ROL64((a01^d1), 10);
1878     b3 = ROL64((a32^d2), 15);
1879     b4 = ROL64((a13^d3), 56);
1880     b0 = ROL64((a44^d4), 27);
1881     a20 =   b0 ^((~b1)&  b2 );
1882     a01 =   b1 ^((~b2)&  b3 );
1883     a32 =   b2 ^((~b3)&  b4 );
1884     a13 =   b3 ^((~b4)&  b0 );
1885     a44 =   b4 ^((~b0)&  b1 );
1886 
1887     b3 = ROL64((a10^d0), 41);
1888     b4 = ROL64((a41^d1), 2);
1889     b0 = ROL64((a22^d2), 62);
1890     b1 = ROL64((a03^d3), 55);
1891     b2 = ROL64((a34^d4), 39);
1892     a10 =   b0 ^((~b1)&  b2 );
1893     a41 =   b1 ^((~b2)&  b3 );
1894     a22 =   b2 ^((~b3)&  b4 );
1895     a03 =   b3 ^((~b4)&  b0 );
1896     a34 =   b4 ^((~b0)&  b1 );
1897 
1898     c0 = a00^a40^a30^a20^a10;
1899     c1 = a31^a21^a11^a01^a41;
1900     c2 = a12^a02^a42^a32^a22;
1901     c3 = a43^a33^a23^a13^a03;
1902     c4 = a24^a14^a04^a44^a34;
1903     d0 = c4^ROL64(c1, 1);
1904     d1 = c0^ROL64(c2, 1);
1905     d2 = c1^ROL64(c3, 1);
1906     d3 = c2^ROL64(c4, 1);
1907     d4 = c3^ROL64(c0, 1);
1908 
1909     b0 = (a00^d0);
1910     b1 = ROL64((a21^d1), 44);
1911     b2 = ROL64((a42^d2), 43);
1912     b3 = ROL64((a13^d3), 21);
1913     b4 = ROL64((a34^d4), 14);
1914     a00 =   b0 ^((~b1)&  b2 );
1915     a00 ^= RC[i+2];
1916     a21 =   b1 ^((~b2)&  b3 );
1917     a42 =   b2 ^((~b3)&  b4 );
1918     a13 =   b3 ^((~b4)&  b0 );
1919     a34 =   b4 ^((~b0)&  b1 );
1920 
1921     b2 = ROL64((a30^d0), 3);
1922     b3 = ROL64((a01^d1), 45);
1923     b4 = ROL64((a22^d2), 61);
1924     b0 = ROL64((a43^d3), 28);
1925     b1 = ROL64((a14^d4), 20);
1926     a30 =   b0 ^((~b1)&  b2 );
1927     a01 =   b1 ^((~b2)&  b3 );
1928     a22 =   b2 ^((~b3)&  b4 );
1929     a43 =   b3 ^((~b4)&  b0 );
1930     a14 =   b4 ^((~b0)&  b1 );
1931 
1932     b4 = ROL64((a10^d0), 18);
1933     b0 = ROL64((a31^d1), 1);
1934     b1 = ROL64((a02^d2), 6);
1935     b2 = ROL64((a23^d3), 25);
1936     b3 = ROL64((a44^d4), 8);
1937     a10 =   b0 ^((~b1)&  b2 );
1938     a31 =   b1 ^((~b2)&  b3 );
1939     a02 =   b2 ^((~b3)&  b4 );
1940     a23 =   b3 ^((~b4)&  b0 );
1941     a44 =   b4 ^((~b0)&  b1 );
1942 
1943     b1 = ROL64((a40^d0), 36);
1944     b2 = ROL64((a11^d1), 10);
1945     b3 = ROL64((a32^d2), 15);
1946     b4 = ROL64((a03^d3), 56);
1947     b0 = ROL64((a24^d4), 27);
1948     a40 =   b0 ^((~b1)&  b2 );
1949     a11 =   b1 ^((~b2)&  b3 );
1950     a32 =   b2 ^((~b3)&  b4 );
1951     a03 =   b3 ^((~b4)&  b0 );
1952     a24 =   b4 ^((~b0)&  b1 );
1953 
1954     b3 = ROL64((a20^d0), 41);
1955     b4 = ROL64((a41^d1), 2);
1956     b0 = ROL64((a12^d2), 62);
1957     b1 = ROL64((a33^d3), 55);
1958     b2 = ROL64((a04^d4), 39);
1959     a20 =   b0 ^((~b1)&  b2 );
1960     a41 =   b1 ^((~b2)&  b3 );
1961     a12 =   b2 ^((~b3)&  b4 );
1962     a33 =   b3 ^((~b4)&  b0 );
1963     a04 =   b4 ^((~b0)&  b1 );
1964 
1965     c0 = a00^a30^a10^a40^a20;
1966     c1 = a21^a01^a31^a11^a41;
1967     c2 = a42^a22^a02^a32^a12;
1968     c3 = a13^a43^a23^a03^a33;
1969     c4 = a34^a14^a44^a24^a04;
1970     d0 = c4^ROL64(c1, 1);
1971     d1 = c0^ROL64(c2, 1);
1972     d2 = c1^ROL64(c3, 1);
1973     d3 = c2^ROL64(c4, 1);
1974     d4 = c3^ROL64(c0, 1);
1975 
1976     b0 = (a00^d0);
1977     b1 = ROL64((a01^d1), 44);
1978     b2 = ROL64((a02^d2), 43);
1979     b3 = ROL64((a03^d3), 21);
1980     b4 = ROL64((a04^d4), 14);
1981     a00 =   b0 ^((~b1)&  b2 );
1982     a00 ^= RC[i+3];
1983     a01 =   b1 ^((~b2)&  b3 );
1984     a02 =   b2 ^((~b3)&  b4 );
1985     a03 =   b3 ^((~b4)&  b0 );
1986     a04 =   b4 ^((~b0)&  b1 );
1987 
1988     b2 = ROL64((a10^d0), 3);
1989     b3 = ROL64((a11^d1), 45);
1990     b4 = ROL64((a12^d2), 61);
1991     b0 = ROL64((a13^d3), 28);
1992     b1 = ROL64((a14^d4), 20);
1993     a10 =   b0 ^((~b1)&  b2 );
1994     a11 =   b1 ^((~b2)&  b3 );
1995     a12 =   b2 ^((~b3)&  b4 );
1996     a13 =   b3 ^((~b4)&  b0 );
1997     a14 =   b4 ^((~b0)&  b1 );
1998 
1999     b4 = ROL64((a20^d0), 18);
2000     b0 = ROL64((a21^d1), 1);
2001     b1 = ROL64((a22^d2), 6);
2002     b2 = ROL64((a23^d3), 25);
2003     b3 = ROL64((a24^d4), 8);
2004     a20 =   b0 ^((~b1)&  b2 );
2005     a21 =   b1 ^((~b2)&  b3 );
2006     a22 =   b2 ^((~b3)&  b4 );
2007     a23 =   b3 ^((~b4)&  b0 );
2008     a24 =   b4 ^((~b0)&  b1 );
2009 
2010     b1 = ROL64((a30^d0), 36);
2011     b2 = ROL64((a31^d1), 10);
2012     b3 = ROL64((a32^d2), 15);
2013     b4 = ROL64((a33^d3), 56);
2014     b0 = ROL64((a34^d4), 27);
2015     a30 =   b0 ^((~b1)&  b2 );
2016     a31 =   b1 ^((~b2)&  b3 );
2017     a32 =   b2 ^((~b3)&  b4 );
2018     a33 =   b3 ^((~b4)&  b0 );
2019     a34 =   b4 ^((~b0)&  b1 );
2020 
2021     b3 = ROL64((a40^d0), 41);
2022     b4 = ROL64((a41^d1), 2);
2023     b0 = ROL64((a42^d2), 62);
2024     b1 = ROL64((a43^d3), 55);
2025     b2 = ROL64((a44^d4), 39);
2026     a40 =   b0 ^((~b1)&  b2 );
2027     a41 =   b1 ^((~b2)&  b3 );
2028     a42 =   b2 ^((~b3)&  b4 );
2029     a43 =   b3 ^((~b4)&  b0 );
2030     a44 =   b4 ^((~b0)&  b1 );
2031   }
2032 }
2033 
2034 /*
2035 ** Initialize a new hash.  iSize determines the size of the hash
2036 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
2037 ** can be zero to use the default hash size of 256 bits.
2038 */
2039 static void SHA3Init(SHA3Context *p, int iSize){
2040   memset(p, 0, sizeof(*p));
2041   if( iSize>=128 && iSize<=512 ){
2042     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
2043   }else{
2044     p->nRate = (1600 - 2*256)/8;
2045   }
2046 #if SHA3_BYTEORDER==1234
2047   /* Known to be little-endian at compile-time. No-op */
2048 #elif SHA3_BYTEORDER==4321
2049   p->ixMask = 7;  /* Big-endian */
2050 #else
2051   {
2052     static unsigned int one = 1;
2053     if( 1==*(unsigned char*)&one ){
2054       /* Little endian.  No byte swapping. */
2055       p->ixMask = 0;
2056     }else{
2057       /* Big endian.  Byte swap. */
2058       p->ixMask = 7;
2059     }
2060   }
2061 #endif
2062 }
2063 
2064 /*
2065 ** Make consecutive calls to the SHA3Update function to add new content
2066 ** to the hash
2067 */
2068 static void SHA3Update(
2069   SHA3Context *p,
2070   const unsigned char *aData,
2071   unsigned int nData
2072 ){
2073   unsigned int i = 0;
2074   if( aData==0 ) return;
2075 #if SHA3_BYTEORDER==1234
2076   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
2077     for(; i+7<nData; i+=8){
2078       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
2079       p->nLoaded += 8;
2080       if( p->nLoaded>=p->nRate ){
2081         KeccakF1600Step(p);
2082         p->nLoaded = 0;
2083       }
2084     }
2085   }
2086 #endif
2087   for(; i<nData; i++){
2088 #if SHA3_BYTEORDER==1234
2089     p->u.x[p->nLoaded] ^= aData[i];
2090 #elif SHA3_BYTEORDER==4321
2091     p->u.x[p->nLoaded^0x07] ^= aData[i];
2092 #else
2093     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
2094 #endif
2095     p->nLoaded++;
2096     if( p->nLoaded==p->nRate ){
2097       KeccakF1600Step(p);
2098       p->nLoaded = 0;
2099     }
2100   }
2101 }
2102 
2103 /*
2104 ** After all content has been added, invoke SHA3Final() to compute
2105 ** the final hash.  The function returns a pointer to the binary
2106 ** hash value.
2107 */
2108 static unsigned char *SHA3Final(SHA3Context *p){
2109   unsigned int i;
2110   if( p->nLoaded==p->nRate-1 ){
2111     const unsigned char c1 = 0x86;
2112     SHA3Update(p, &c1, 1);
2113   }else{
2114     const unsigned char c2 = 0x06;
2115     const unsigned char c3 = 0x80;
2116     SHA3Update(p, &c2, 1);
2117     p->nLoaded = p->nRate - 1;
2118     SHA3Update(p, &c3, 1);
2119   }
2120   for(i=0; i<p->nRate; i++){
2121     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
2122   }
2123   return &p->u.x[p->nRate];
2124 }
2125 /* End of the hashing logic
2126 *****************************************************************************/
2127 
2128 /*
2129 ** Implementation of the sha3(X,SIZE) function.
2130 **
2131 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
2132 ** size is 256.  If X is a BLOB, it is hashed as is.
2133 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2134 ** and the string is hashed without the trailing 0x00 terminator.  The hash
2135 ** of a NULL value is NULL.
2136 */
2137 static void sha3Func(
2138   sqlite3_context *context,
2139   int argc,
2140   sqlite3_value **argv
2141 ){
2142   SHA3Context cx;
2143   int eType = sqlite3_value_type(argv[0]);
2144   int nByte = sqlite3_value_bytes(argv[0]);
2145   int iSize;
2146   if( argc==1 ){
2147     iSize = 256;
2148   }else{
2149     iSize = sqlite3_value_int(argv[1]);
2150     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2151       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2152                                     "384 512", -1);
2153       return;
2154     }
2155   }
2156   if( eType==SQLITE_NULL ) return;
2157   SHA3Init(&cx, iSize);
2158   if( eType==SQLITE_BLOB ){
2159     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
2160   }else{
2161     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
2162   }
2163   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2164 }
2165 
2166 /* Compute a string using sqlite3_vsnprintf() with a maximum length
2167 ** of 50 bytes and add it to the hash.
2168 */
2169 static void sha3_step_vformat(
2170   SHA3Context *p,                 /* Add content to this context */
2171   const char *zFormat,
2172   ...
2173 ){
2174   va_list ap;
2175   int n;
2176   char zBuf[50];
2177   va_start(ap, zFormat);
2178   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
2179   va_end(ap);
2180   n = (int)strlen(zBuf);
2181   SHA3Update(p, (unsigned char*)zBuf, n);
2182 }
2183 
2184 /*
2185 ** Implementation of the sha3_query(SQL,SIZE) function.
2186 **
2187 ** This function compiles and runs the SQL statement(s) given in the
2188 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
2189 ** size is 256.
2190 **
2191 ** The format of the byte stream that is hashed is summarized as follows:
2192 **
2193 **       S<n>:<sql>
2194 **       R
2195 **       N
2196 **       I<int>
2197 **       F<ieee-float>
2198 **       B<size>:<bytes>
2199 **       T<size>:<text>
2200 **
2201 ** <sql> is the original SQL text for each statement run and <n> is
2202 ** the size of that text.  The SQL text is UTF-8.  A single R character
2203 ** occurs before the start of each row.  N means a NULL value.
2204 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
2205 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
2206 ** B means blobs of <size> bytes.  T means text rendered as <size>
2207 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
2208 ** text integers.
2209 **
2210 ** For each SQL statement in the X input, there is one S segment.  Each
2211 ** S segment is followed by zero or more R segments, one for each row in the
2212 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
2213 ** one for each column in the result set.  Segments are concatentated directly
2214 ** with no delimiters of any kind.
2215 */
2216 static void sha3QueryFunc(
2217   sqlite3_context *context,
2218   int argc,
2219   sqlite3_value **argv
2220 ){
2221   sqlite3 *db = sqlite3_context_db_handle(context);
2222   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
2223   sqlite3_stmt *pStmt = 0;
2224   int nCol;                   /* Number of columns in the result set */
2225   int i;                      /* Loop counter */
2226   int rc;
2227   int n;
2228   const char *z;
2229   SHA3Context cx;
2230   int iSize;
2231 
2232   if( argc==1 ){
2233     iSize = 256;
2234   }else{
2235     iSize = sqlite3_value_int(argv[1]);
2236     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2237       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2238                                     "384 512", -1);
2239       return;
2240     }
2241   }
2242   if( zSql==0 ) return;
2243   SHA3Init(&cx, iSize);
2244   while( zSql[0] ){
2245     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2246     if( rc ){
2247       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2248                                    zSql, sqlite3_errmsg(db));
2249       sqlite3_finalize(pStmt);
2250       sqlite3_result_error(context, zMsg, -1);
2251       sqlite3_free(zMsg);
2252       return;
2253     }
2254     if( !sqlite3_stmt_readonly(pStmt) ){
2255       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2256       sqlite3_finalize(pStmt);
2257       sqlite3_result_error(context, zMsg, -1);
2258       sqlite3_free(zMsg);
2259       return;
2260     }
2261     nCol = sqlite3_column_count(pStmt);
2262     z = sqlite3_sql(pStmt);
2263     if( z ){
2264       n = (int)strlen(z);
2265       sha3_step_vformat(&cx,"S%d:",n);
2266       SHA3Update(&cx,(unsigned char*)z,n);
2267     }
2268 
2269     /* Compute a hash over the result of the query */
2270     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2271       SHA3Update(&cx,(const unsigned char*)"R",1);
2272       for(i=0; i<nCol; i++){
2273         switch( sqlite3_column_type(pStmt,i) ){
2274           case SQLITE_NULL: {
2275             SHA3Update(&cx, (const unsigned char*)"N",1);
2276             break;
2277           }
2278           case SQLITE_INTEGER: {
2279             sqlite3_uint64 u;
2280             int j;
2281             unsigned char x[9];
2282             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2283             memcpy(&u, &v, 8);
2284             for(j=8; j>=1; j--){
2285               x[j] = u & 0xff;
2286               u >>= 8;
2287             }
2288             x[0] = 'I';
2289             SHA3Update(&cx, x, 9);
2290             break;
2291           }
2292           case SQLITE_FLOAT: {
2293             sqlite3_uint64 u;
2294             int j;
2295             unsigned char x[9];
2296             double r = sqlite3_column_double(pStmt,i);
2297             memcpy(&u, &r, 8);
2298             for(j=8; j>=1; j--){
2299               x[j] = u & 0xff;
2300               u >>= 8;
2301             }
2302             x[0] = 'F';
2303             SHA3Update(&cx,x,9);
2304             break;
2305           }
2306           case SQLITE_TEXT: {
2307             int n2 = sqlite3_column_bytes(pStmt, i);
2308             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2309             sha3_step_vformat(&cx,"T%d:",n2);
2310             SHA3Update(&cx, z2, n2);
2311             break;
2312           }
2313           case SQLITE_BLOB: {
2314             int n2 = sqlite3_column_bytes(pStmt, i);
2315             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2316             sha3_step_vformat(&cx,"B%d:",n2);
2317             SHA3Update(&cx, z2, n2);
2318             break;
2319           }
2320         }
2321       }
2322     }
2323     sqlite3_finalize(pStmt);
2324   }
2325   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2326 }
2327 
2328 
2329 #ifdef _WIN32
2330 
2331 #endif
2332 int sqlite3_shathree_init(
2333   sqlite3 *db,
2334   char **pzErrMsg,
2335   const sqlite3_api_routines *pApi
2336 ){
2337   int rc = SQLITE_OK;
2338   SQLITE_EXTENSION_INIT2(pApi);
2339   (void)pzErrMsg;  /* Unused parameter */
2340   rc = sqlite3_create_function(db, "sha3", 1,
2341                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2342                       0, sha3Func, 0, 0);
2343   if( rc==SQLITE_OK ){
2344     rc = sqlite3_create_function(db, "sha3", 2,
2345                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2346                       0, sha3Func, 0, 0);
2347   }
2348   if( rc==SQLITE_OK ){
2349     rc = sqlite3_create_function(db, "sha3_query", 1,
2350                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2351                       0, sha3QueryFunc, 0, 0);
2352   }
2353   if( rc==SQLITE_OK ){
2354     rc = sqlite3_create_function(db, "sha3_query", 2,
2355                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2356                       0, sha3QueryFunc, 0, 0);
2357   }
2358   return rc;
2359 }
2360 
2361 /************************* End ../ext/misc/shathree.c ********************/
2362 /************************* Begin ../ext/misc/uint.c ******************/
2363 /*
2364 ** 2020-04-14
2365 **
2366 ** The author disclaims copyright to this source code.  In place of
2367 ** a legal notice, here is a blessing:
2368 **
2369 **    May you do good and not evil.
2370 **    May you find forgiveness for yourself and forgive others.
2371 **    May you share freely, never taking more than you give.
2372 **
2373 ******************************************************************************
2374 **
2375 ** This SQLite extension implements the UINT collating sequence.
2376 **
2377 ** UINT works like BINARY for text, except that embedded strings
2378 ** of digits compare in numeric order.
2379 **
2380 **     *   Leading zeros are handled properly, in the sense that
2381 **         they do not mess of the maginitude comparison of embedded
2382 **         strings of digits.  "x00123y" is equal to "x123y".
2383 **
2384 **     *   Only unsigned integers are recognized.  Plus and minus
2385 **         signs are ignored.  Decimal points and exponential notation
2386 **         are ignored.
2387 **
2388 **     *   Embedded integers can be of arbitrary length.  Comparison
2389 **         is *not* limited integers that can be expressed as a
2390 **         64-bit machine integer.
2391 */
2392 /* #include "sqlite3ext.h" */
2393 SQLITE_EXTENSION_INIT1
2394 #include <assert.h>
2395 #include <string.h>
2396 #include <ctype.h>
2397 
2398 /*
2399 ** Compare text in lexicographic order, except strings of digits
2400 ** compare in numeric order.
2401 */
2402 static int uintCollFunc(
2403   void *notUsed,
2404   int nKey1, const void *pKey1,
2405   int nKey2, const void *pKey2
2406 ){
2407   const unsigned char *zA = (const unsigned char*)pKey1;
2408   const unsigned char *zB = (const unsigned char*)pKey2;
2409   int i=0, j=0, x;
2410   (void)notUsed;
2411   while( i<nKey1 && j<nKey2 ){
2412     x = zA[i] - zB[j];
2413     if( isdigit(zA[i]) ){
2414       int k;
2415       if( !isdigit(zB[j]) ) return x;
2416       while( i<nKey1 && zA[i]=='0' ){ i++; }
2417       while( j<nKey2 && zB[j]=='0' ){ j++; }
2418       k = 0;
2419       while( i+k<nKey1 && isdigit(zA[i+k])
2420              && j+k<nKey2 && isdigit(zB[j+k]) ){
2421         k++;
2422       }
2423       if( i+k<nKey1 && isdigit(zA[i+k]) ){
2424         return +1;
2425       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
2426         return -1;
2427       }else{
2428         x = memcmp(zA+i, zB+j, k);
2429         if( x ) return x;
2430         i += k;
2431         j += k;
2432       }
2433     }else if( x ){
2434       return x;
2435     }else{
2436       i++;
2437       j++;
2438     }
2439   }
2440   return (nKey1 - i) - (nKey2 - j);
2441 }
2442 
2443 #ifdef _WIN32
2444 
2445 #endif
2446 int sqlite3_uint_init(
2447   sqlite3 *db,
2448   char **pzErrMsg,
2449   const sqlite3_api_routines *pApi
2450 ){
2451   SQLITE_EXTENSION_INIT2(pApi);
2452   (void)pzErrMsg;  /* Unused parameter */
2453   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
2454 }
2455 
2456 /************************* End ../ext/misc/uint.c ********************/
2457 /************************* Begin ../ext/misc/decimal.c ******************/
2458 /*
2459 ** 2020-06-22
2460 **
2461 ** The author disclaims copyright to this source code.  In place of
2462 ** a legal notice, here is a blessing:
2463 **
2464 **    May you do good and not evil.
2465 **    May you find forgiveness for yourself and forgive others.
2466 **    May you share freely, never taking more than you give.
2467 **
2468 ******************************************************************************
2469 **
2470 ** Routines to implement arbitrary-precision decimal math.
2471 **
2472 ** The focus here is on simplicity and correctness, not performance.
2473 */
2474 /* #include "sqlite3ext.h" */
2475 SQLITE_EXTENSION_INIT1
2476 #include <assert.h>
2477 #include <string.h>
2478 #include <ctype.h>
2479 #include <stdlib.h>
2480 
2481 /* Mark a function parameter as unused, to suppress nuisance compiler
2482 ** warnings. */
2483 #ifndef UNUSED_PARAMETER
2484 # define UNUSED_PARAMETER(X)  (void)(X)
2485 #endif
2486 
2487 
2488 /* A decimal object */
2489 typedef struct Decimal Decimal;
2490 struct Decimal {
2491   char sign;        /* 0 for positive, 1 for negative */
2492   char oom;         /* True if an OOM is encountered */
2493   char isNull;      /* True if holds a NULL rather than a number */
2494   char isInit;      /* True upon initialization */
2495   int nDigit;       /* Total number of digits */
2496   int nFrac;        /* Number of digits to the right of the decimal point */
2497   signed char *a;   /* Array of digits.  Most significant first. */
2498 };
2499 
2500 /*
2501 ** Release memory held by a Decimal, but do not free the object itself.
2502 */
2503 static void decimal_clear(Decimal *p){
2504   sqlite3_free(p->a);
2505 }
2506 
2507 /*
2508 ** Destroy a Decimal object
2509 */
2510 static void decimal_free(Decimal *p){
2511   if( p ){
2512     decimal_clear(p);
2513     sqlite3_free(p);
2514   }
2515 }
2516 
2517 /*
2518 ** Allocate a new Decimal object.  Initialize it to the number given
2519 ** by the input string.
2520 */
2521 static Decimal *decimal_new(
2522   sqlite3_context *pCtx,
2523   sqlite3_value *pIn,
2524   int nAlt,
2525   const unsigned char *zAlt
2526 ){
2527   Decimal *p;
2528   int n, i;
2529   const unsigned char *zIn;
2530   int iExp = 0;
2531   p = sqlite3_malloc( sizeof(*p) );
2532   if( p==0 ) goto new_no_mem;
2533   p->sign = 0;
2534   p->oom = 0;
2535   p->isInit = 1;
2536   p->isNull = 0;
2537   p->nDigit = 0;
2538   p->nFrac = 0;
2539   if( zAlt ){
2540     n = nAlt,
2541     zIn = zAlt;
2542   }else{
2543     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
2544       p->a = 0;
2545       p->isNull = 1;
2546       return p;
2547     }
2548     n = sqlite3_value_bytes(pIn);
2549     zIn = sqlite3_value_text(pIn);
2550   }
2551   p->a = sqlite3_malloc64( n+1 );
2552   if( p->a==0 ) goto new_no_mem;
2553   for(i=0; isspace(zIn[i]); i++){}
2554   if( zIn[i]=='-' ){
2555     p->sign = 1;
2556     i++;
2557   }else if( zIn[i]=='+' ){
2558     i++;
2559   }
2560   while( i<n && zIn[i]=='0' ) i++;
2561   while( i<n ){
2562     char c = zIn[i];
2563     if( c>='0' && c<='9' ){
2564       p->a[p->nDigit++] = c - '0';
2565     }else if( c=='.' ){
2566       p->nFrac = p->nDigit + 1;
2567     }else if( c=='e' || c=='E' ){
2568       int j = i+1;
2569       int neg = 0;
2570       if( j>=n ) break;
2571       if( zIn[j]=='-' ){
2572         neg = 1;
2573         j++;
2574       }else if( zIn[j]=='+' ){
2575         j++;
2576       }
2577       while( j<n && iExp<1000000 ){
2578         if( zIn[j]>='0' && zIn[j]<='9' ){
2579           iExp = iExp*10 + zIn[j] - '0';
2580         }
2581         j++;
2582       }
2583       if( neg ) iExp = -iExp;
2584       break;
2585     }
2586     i++;
2587   }
2588   if( p->nFrac ){
2589     p->nFrac = p->nDigit - (p->nFrac - 1);
2590   }
2591   if( iExp>0 ){
2592     if( p->nFrac>0 ){
2593       if( iExp<=p->nFrac ){
2594         p->nFrac -= iExp;
2595         iExp = 0;
2596       }else{
2597         iExp -= p->nFrac;
2598         p->nFrac = 0;
2599       }
2600     }
2601     if( iExp>0 ){
2602       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2603       if( p->a==0 ) goto new_no_mem;
2604       memset(p->a+p->nDigit, 0, iExp);
2605       p->nDigit += iExp;
2606     }
2607   }else if( iExp<0 ){
2608     int nExtra;
2609     iExp = -iExp;
2610     nExtra = p->nDigit - p->nFrac - 1;
2611     if( nExtra ){
2612       if( nExtra>=iExp ){
2613         p->nFrac += iExp;
2614         iExp  = 0;
2615       }else{
2616         iExp -= nExtra;
2617         p->nFrac = p->nDigit - 1;
2618       }
2619     }
2620     if( iExp>0 ){
2621       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2622       if( p->a==0 ) goto new_no_mem;
2623       memmove(p->a+iExp, p->a, p->nDigit);
2624       memset(p->a, 0, iExp);
2625       p->nDigit += iExp;
2626       p->nFrac += iExp;
2627     }
2628   }
2629   return p;
2630 
2631 new_no_mem:
2632   if( pCtx ) sqlite3_result_error_nomem(pCtx);
2633   sqlite3_free(p);
2634   return 0;
2635 }
2636 
2637 /*
2638 ** Make the given Decimal the result.
2639 */
2640 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
2641   char *z;
2642   int i, j;
2643   int n;
2644   if( p==0 || p->oom ){
2645     sqlite3_result_error_nomem(pCtx);
2646     return;
2647   }
2648   if( p->isNull ){
2649     sqlite3_result_null(pCtx);
2650     return;
2651   }
2652   z = sqlite3_malloc( p->nDigit+4 );
2653   if( z==0 ){
2654     sqlite3_result_error_nomem(pCtx);
2655     return;
2656   }
2657   i = 0;
2658   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
2659     p->sign = 0;
2660   }
2661   if( p->sign ){
2662     z[0] = '-';
2663     i = 1;
2664   }
2665   n = p->nDigit - p->nFrac;
2666   if( n<=0 ){
2667     z[i++] = '0';
2668   }
2669   j = 0;
2670   while( n>1 && p->a[j]==0 ){
2671     j++;
2672     n--;
2673   }
2674   while( n>0  ){
2675     z[i++] = p->a[j] + '0';
2676     j++;
2677     n--;
2678   }
2679   if( p->nFrac ){
2680     z[i++] = '.';
2681     do{
2682       z[i++] = p->a[j] + '0';
2683       j++;
2684     }while( j<p->nDigit );
2685   }
2686   z[i] = 0;
2687   sqlite3_result_text(pCtx, z, i, sqlite3_free);
2688 }
2689 
2690 /*
2691 ** SQL Function:   decimal(X)
2692 **
2693 ** Convert input X into decimal and then back into text
2694 */
2695 static void decimalFunc(
2696   sqlite3_context *context,
2697   int argc,
2698   sqlite3_value **argv
2699 ){
2700   Decimal *p = decimal_new(context, argv[0], 0, 0);
2701   UNUSED_PARAMETER(argc);
2702   decimal_result(context, p);
2703   decimal_free(p);
2704 }
2705 
2706 /*
2707 ** Compare to Decimal objects.  Return negative, 0, or positive if the
2708 ** first object is less than, equal to, or greater than the second.
2709 **
2710 ** Preconditions for this routine:
2711 **
2712 **    pA!=0
2713 **    pA->isNull==0
2714 **    pB!=0
2715 **    pB->isNull==0
2716 */
2717 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
2718   int nASig, nBSig, rc, n;
2719   if( pA->sign!=pB->sign ){
2720     return pA->sign ? -1 : +1;
2721   }
2722   if( pA->sign ){
2723     const Decimal *pTemp = pA;
2724     pA = pB;
2725     pB = pTemp;
2726   }
2727   nASig = pA->nDigit - pA->nFrac;
2728   nBSig = pB->nDigit - pB->nFrac;
2729   if( nASig!=nBSig ){
2730     return nASig - nBSig;
2731   }
2732   n = pA->nDigit;
2733   if( n>pB->nDigit ) n = pB->nDigit;
2734   rc = memcmp(pA->a, pB->a, n);
2735   if( rc==0 ){
2736     rc = pA->nDigit - pB->nDigit;
2737   }
2738   return rc;
2739 }
2740 
2741 /*
2742 ** SQL Function:   decimal_cmp(X, Y)
2743 **
2744 ** Return negative, zero, or positive if X is less then, equal to, or
2745 ** greater than Y.
2746 */
2747 static void decimalCmpFunc(
2748   sqlite3_context *context,
2749   int argc,
2750   sqlite3_value **argv
2751 ){
2752   Decimal *pA = 0, *pB = 0;
2753   int rc;
2754 
2755   UNUSED_PARAMETER(argc);
2756   pA = decimal_new(context, argv[0], 0, 0);
2757   if( pA==0 || pA->isNull ) goto cmp_done;
2758   pB = decimal_new(context, argv[1], 0, 0);
2759   if( pB==0 || pB->isNull ) goto cmp_done;
2760   rc = decimal_cmp(pA, pB);
2761   if( rc<0 ) rc = -1;
2762   else if( rc>0 ) rc = +1;
2763   sqlite3_result_int(context, rc);
2764 cmp_done:
2765   decimal_free(pA);
2766   decimal_free(pB);
2767 }
2768 
2769 /*
2770 ** Expand the Decimal so that it has a least nDigit digits and nFrac
2771 ** digits to the right of the decimal point.
2772 */
2773 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
2774   int nAddSig;
2775   int nAddFrac;
2776   if( p==0 ) return;
2777   nAddFrac = nFrac - p->nFrac;
2778   nAddSig = (nDigit - p->nDigit) - nAddFrac;
2779   if( nAddFrac==0 && nAddSig==0 ) return;
2780   p->a = sqlite3_realloc64(p->a, nDigit+1);
2781   if( p->a==0 ){
2782     p->oom = 1;
2783     return;
2784   }
2785   if( nAddSig ){
2786     memmove(p->a+nAddSig, p->a, p->nDigit);
2787     memset(p->a, 0, nAddSig);
2788     p->nDigit += nAddSig;
2789   }
2790   if( nAddFrac ){
2791     memset(p->a+p->nDigit, 0, nAddFrac);
2792     p->nDigit += nAddFrac;
2793     p->nFrac += nAddFrac;
2794   }
2795 }
2796 
2797 /*
2798 ** Add the value pB into pA.
2799 **
2800 ** Both pA and pB might become denormalized by this routine.
2801 */
2802 static void decimal_add(Decimal *pA, Decimal *pB){
2803   int nSig, nFrac, nDigit;
2804   int i, rc;
2805   if( pA==0 ){
2806     return;
2807   }
2808   if( pA->oom || pB==0 || pB->oom ){
2809     pA->oom = 1;
2810     return;
2811   }
2812   if( pA->isNull || pB->isNull ){
2813     pA->isNull = 1;
2814     return;
2815   }
2816   nSig = pA->nDigit - pA->nFrac;
2817   if( nSig && pA->a[0]==0 ) nSig--;
2818   if( nSig<pB->nDigit-pB->nFrac ){
2819     nSig = pB->nDigit - pB->nFrac;
2820   }
2821   nFrac = pA->nFrac;
2822   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
2823   nDigit = nSig + nFrac + 1;
2824   decimal_expand(pA, nDigit, nFrac);
2825   decimal_expand(pB, nDigit, nFrac);
2826   if( pA->oom || pB->oom ){
2827     pA->oom = 1;
2828   }else{
2829     if( pA->sign==pB->sign ){
2830       int carry = 0;
2831       for(i=nDigit-1; i>=0; i--){
2832         int x = pA->a[i] + pB->a[i] + carry;
2833         if( x>=10 ){
2834           carry = 1;
2835           pA->a[i] = x - 10;
2836         }else{
2837           carry = 0;
2838           pA->a[i] = x;
2839         }
2840       }
2841     }else{
2842       signed char *aA, *aB;
2843       int borrow = 0;
2844       rc = memcmp(pA->a, pB->a, nDigit);
2845       if( rc<0 ){
2846         aA = pB->a;
2847         aB = pA->a;
2848         pA->sign = !pA->sign;
2849       }else{
2850         aA = pA->a;
2851         aB = pB->a;
2852       }
2853       for(i=nDigit-1; i>=0; i--){
2854         int x = aA[i] - aB[i] - borrow;
2855         if( x<0 ){
2856           pA->a[i] = x+10;
2857           borrow = 1;
2858         }else{
2859           pA->a[i] = x;
2860           borrow = 0;
2861         }
2862       }
2863     }
2864   }
2865 }
2866 
2867 /*
2868 ** Compare text in decimal order.
2869 */
2870 static int decimalCollFunc(
2871   void *notUsed,
2872   int nKey1, const void *pKey1,
2873   int nKey2, const void *pKey2
2874 ){
2875   const unsigned char *zA = (const unsigned char*)pKey1;
2876   const unsigned char *zB = (const unsigned char*)pKey2;
2877   Decimal *pA = decimal_new(0, 0, nKey1, zA);
2878   Decimal *pB = decimal_new(0, 0, nKey2, zB);
2879   int rc;
2880   UNUSED_PARAMETER(notUsed);
2881   if( pA==0 || pB==0 ){
2882     rc = 0;
2883   }else{
2884     rc = decimal_cmp(pA, pB);
2885   }
2886   decimal_free(pA);
2887   decimal_free(pB);
2888   return rc;
2889 }
2890 
2891 
2892 /*
2893 ** SQL Function:   decimal_add(X, Y)
2894 **                 decimal_sub(X, Y)
2895 **
2896 ** Return the sum or difference of X and Y.
2897 */
2898 static void decimalAddFunc(
2899   sqlite3_context *context,
2900   int argc,
2901   sqlite3_value **argv
2902 ){
2903   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2904   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2905   UNUSED_PARAMETER(argc);
2906   decimal_add(pA, pB);
2907   decimal_result(context, pA);
2908   decimal_free(pA);
2909   decimal_free(pB);
2910 }
2911 static void decimalSubFunc(
2912   sqlite3_context *context,
2913   int argc,
2914   sqlite3_value **argv
2915 ){
2916   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2917   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2918   UNUSED_PARAMETER(argc);
2919   if( pB ){
2920     pB->sign = !pB->sign;
2921     decimal_add(pA, pB);
2922     decimal_result(context, pA);
2923   }
2924   decimal_free(pA);
2925   decimal_free(pB);
2926 }
2927 
2928 /* Aggregate funcion:   decimal_sum(X)
2929 **
2930 ** Works like sum() except that it uses decimal arithmetic for unlimited
2931 ** precision.
2932 */
2933 static void decimalSumStep(
2934   sqlite3_context *context,
2935   int argc,
2936   sqlite3_value **argv
2937 ){
2938   Decimal *p;
2939   Decimal *pArg;
2940   UNUSED_PARAMETER(argc);
2941   p = sqlite3_aggregate_context(context, sizeof(*p));
2942   if( p==0 ) return;
2943   if( !p->isInit ){
2944     p->isInit = 1;
2945     p->a = sqlite3_malloc(2);
2946     if( p->a==0 ){
2947       p->oom = 1;
2948     }else{
2949       p->a[0] = 0;
2950     }
2951     p->nDigit = 1;
2952     p->nFrac = 0;
2953   }
2954   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2955   pArg = decimal_new(context, argv[0], 0, 0);
2956   decimal_add(p, pArg);
2957   decimal_free(pArg);
2958 }
2959 static void decimalSumInverse(
2960   sqlite3_context *context,
2961   int argc,
2962   sqlite3_value **argv
2963 ){
2964   Decimal *p;
2965   Decimal *pArg;
2966   UNUSED_PARAMETER(argc);
2967   p = sqlite3_aggregate_context(context, sizeof(*p));
2968   if( p==0 ) return;
2969   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2970   pArg = decimal_new(context, argv[0], 0, 0);
2971   if( pArg ) pArg->sign = !pArg->sign;
2972   decimal_add(p, pArg);
2973   decimal_free(pArg);
2974 }
2975 static void decimalSumValue(sqlite3_context *context){
2976   Decimal *p = sqlite3_aggregate_context(context, 0);
2977   if( p==0 ) return;
2978   decimal_result(context, p);
2979 }
2980 static void decimalSumFinalize(sqlite3_context *context){
2981   Decimal *p = sqlite3_aggregate_context(context, 0);
2982   if( p==0 ) return;
2983   decimal_result(context, p);
2984   decimal_clear(p);
2985 }
2986 
2987 /*
2988 ** SQL Function:   decimal_mul(X, Y)
2989 **
2990 ** Return the product of X and Y.
2991 **
2992 ** All significant digits after the decimal point are retained.
2993 ** Trailing zeros after the decimal point are omitted as long as
2994 ** the number of digits after the decimal point is no less than
2995 ** either the number of digits in either input.
2996 */
2997 static void decimalMulFunc(
2998   sqlite3_context *context,
2999   int argc,
3000   sqlite3_value **argv
3001 ){
3002   Decimal *pA = decimal_new(context, argv[0], 0, 0);
3003   Decimal *pB = decimal_new(context, argv[1], 0, 0);
3004   signed char *acc = 0;
3005   int i, j, k;
3006   int minFrac;
3007   UNUSED_PARAMETER(argc);
3008   if( pA==0 || pA->oom || pA->isNull
3009    || pB==0 || pB->oom || pB->isNull
3010   ){
3011     goto mul_end;
3012   }
3013   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
3014   if( acc==0 ){
3015     sqlite3_result_error_nomem(context);
3016     goto mul_end;
3017   }
3018   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
3019   minFrac = pA->nFrac;
3020   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
3021   for(i=pA->nDigit-1; i>=0; i--){
3022     signed char f = pA->a[i];
3023     int carry = 0, x;
3024     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
3025       x = acc[k] + f*pB->a[j] + carry;
3026       acc[k] = x%10;
3027       carry = x/10;
3028     }
3029     x = acc[k] + carry;
3030     acc[k] = x%10;
3031     acc[k-1] += x/10;
3032   }
3033   sqlite3_free(pA->a);
3034   pA->a = acc;
3035   acc = 0;
3036   pA->nDigit += pB->nDigit + 2;
3037   pA->nFrac += pB->nFrac;
3038   pA->sign ^= pB->sign;
3039   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
3040     pA->nFrac--;
3041     pA->nDigit--;
3042   }
3043   decimal_result(context, pA);
3044 
3045 mul_end:
3046   sqlite3_free(acc);
3047   decimal_free(pA);
3048   decimal_free(pB);
3049 }
3050 
3051 #ifdef _WIN32
3052 
3053 #endif
3054 int sqlite3_decimal_init(
3055   sqlite3 *db,
3056   char **pzErrMsg,
3057   const sqlite3_api_routines *pApi
3058 ){
3059   int rc = SQLITE_OK;
3060   static const struct {
3061     const char *zFuncName;
3062     int nArg;
3063     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3064   } aFunc[] = {
3065     { "decimal",       1,   decimalFunc        },
3066     { "decimal_cmp",   2,   decimalCmpFunc     },
3067     { "decimal_add",   2,   decimalAddFunc     },
3068     { "decimal_sub",   2,   decimalSubFunc     },
3069     { "decimal_mul",   2,   decimalMulFunc     },
3070   };
3071   unsigned int i;
3072   (void)pzErrMsg;  /* Unused parameter */
3073 
3074   SQLITE_EXTENSION_INIT2(pApi);
3075 
3076   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
3077     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
3078                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
3079                    0, aFunc[i].xFunc, 0, 0);
3080   }
3081   if( rc==SQLITE_OK ){
3082     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
3083                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
3084                    decimalSumStep, decimalSumFinalize,
3085                    decimalSumValue, decimalSumInverse, 0);
3086   }
3087   if( rc==SQLITE_OK ){
3088     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
3089                                   0, decimalCollFunc);
3090   }
3091   return rc;
3092 }
3093 
3094 /************************* End ../ext/misc/decimal.c ********************/
3095 #undef sqlite3_base_init
3096 #define sqlite3_base_init sqlite3_base64_init
3097 /************************* Begin ../ext/misc/base64.c ******************/
3098 /*
3099 ** 2022-11-18
3100 **
3101 ** The author disclaims copyright to this source code.  In place of
3102 ** a legal notice, here is a blessing:
3103 **
3104 **    May you do good and not evil.
3105 **    May you find forgiveness for yourself and forgive others.
3106 **    May you share freely, never taking more than you give.
3107 **
3108 *************************************************************************
3109 **
3110 ** This is a SQLite extension for converting in either direction
3111 ** between a (binary) blob and base64 text. Base64 can transit a
3112 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3113 ** written as TCL brace-enclosed literals or SQL string literals,
3114 ** and can be used unmodified in XML-like documents.
3115 **
3116 ** This is an independent implementation of conversions specified in
3117 ** RFC 4648, done on the above date by the author (Larry Brasfield)
3118 ** who thereby has the right to put this into the public domain.
3119 **
3120 ** The conversions meet RFC 4648 requirements, provided that this
3121 ** C source specifies that line-feeds are included in the encoded
3122 ** data to limit visible line lengths to 72 characters and to
3123 ** terminate any encoded blob having non-zero length.
3124 **
3125 ** Length limitations are not imposed except that the runtime
3126 ** SQLite string or blob length limits are respected. Otherwise,
3127 ** any length binary sequence can be represented and recovered.
3128 ** Generated base64 sequences, with their line-feeds included,
3129 ** can be concatenated; the result converted back to binary will
3130 ** be the concatenation of the represented binary sequences.
3131 **
3132 ** This SQLite3 extension creates a function, base64(x), which
3133 ** either: converts text x containing base64 to a returned blob;
3134 ** or converts a blob x to returned text containing base64. An
3135 ** error will be thrown for other input argument types.
3136 **
3137 ** This code relies on UTF-8 encoding only with respect to the
3138 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
3139 ** It will fail miserably if somehow made to try to convert EBCDIC.
3140 ** Because it is table-driven, it could be enhanced to handle that,
3141 ** but the world and SQLite have moved on from that anachronism.
3142 **
3143 ** To build the extension:
3144 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3145 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
3146 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
3147 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
3148 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
3149 */
3150 
3151 #include <assert.h>
3152 
3153 /* #include "sqlite3ext.h" */
3154 
3155 #ifndef deliberate_fall_through
3156 /* Quiet some compilers about some of our intentional code. */
3157 # if GCC_VERSION>=7000000
3158 #  define deliberate_fall_through __attribute__((fallthrough));
3159 # else
3160 #  define deliberate_fall_through
3161 # endif
3162 #endif
3163 
3164 SQLITE_EXTENSION_INIT1;
3165 
3166 #define PC 0x80 /* pad character */
3167 #define WS 0x81 /* whitespace */
3168 #define ND 0x82 /* Not above or digit-value */
3169 #define PAD_CHAR '='
3170 
3171 #ifndef U8_TYPEDEF
3172 /* typedef unsigned char u8; */
3173 #define U8_TYPEDEF
3174 #endif
3175 
3176 static const u8 b64DigitValues[128] = {
3177   /*                             HT LF VT  FF CR       */
3178     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
3179   /*                                                US */
3180     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
3181   /*sp                                  +            / */
3182     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
3183   /* 0  1            5            9            =       */
3184     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
3185   /*    A                                            O */
3186     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
3187   /* P                               Z                 */
3188     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
3189   /*    a                                            o */
3190     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
3191   /* p                               z                 */
3192     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
3193 };
3194 
3195 static const char b64Numerals[64+1]
3196 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3197 
3198 #define BX_DV_PROTO(c) \
3199   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
3200 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
3201 #define IS_BX_WS(bdp) ((bdp)==WS)
3202 #define IS_BX_PAD(bdp) ((bdp)==PC)
3203 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
3204 /* Width of base64 lines. Should be an integer multiple of 4. */
3205 #define B64_DARK_MAX 72
3206 
3207 /* Encode a byte buffer into base64 text with linefeeds appended to limit
3208 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
3209 */
3210 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
3211   int nCol = 0;
3212   while( nbIn >= 3 ){
3213     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
3214     pOut[0] = BX_NUMERAL(pIn[0]>>2);
3215     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
3216     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
3217     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
3218     pOut += 4;
3219     nbIn -= 3;
3220     pIn += 3;
3221     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
3222       *pOut++ = '\n';
3223       nCol = 0;
3224     }
3225   }
3226   if( nbIn > 0 ){
3227     signed char nco = nbIn+1;
3228     int nbe;
3229     unsigned long qv = *pIn++;
3230     for( nbe=1; nbe<3; ++nbe ){
3231       qv <<= 8;
3232       if( nbe<nbIn ) qv |= *pIn++;
3233     }
3234     for( nbe=3; nbe>=0; --nbe ){
3235       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
3236       qv >>= 6;
3237       pOut[nbe] = ce;
3238     }
3239     pOut += 4;
3240     *pOut++ = '\n';
3241   }
3242   *pOut = 0;
3243   return pOut;
3244 }
3245 
3246 /* Skip over text which is not base64 numeral(s). */
3247 static char * skipNonB64( char *s ){
3248   char c;
3249   while( (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
3250   return s;
3251 }
3252 
3253 /* Decode base64 text into a byte buffer. */
3254 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
3255   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3256   while( ncIn>0 && *pIn!=PAD_CHAR ){
3257     static signed char nboi[] = { 0, 0, 1, 2, 3 };
3258     char *pUse = skipNonB64(pIn);
3259     unsigned long qv = 0L;
3260     int nti, nbo, nac;
3261     ncIn -= (pUse - pIn);
3262     pIn = pUse;
3263     nti = (ncIn>4)? 4 : ncIn;
3264     ncIn -= nti;
3265     nbo = nboi[nti];
3266     if( nbo==0 ) break;
3267     for( nac=0; nac<4; ++nac ){
3268       char c = (nac<nti)? *pIn++ : b64Numerals[0];
3269       u8 bdp = BX_DV_PROTO(c);
3270       switch( bdp ){
3271       case ND:
3272         /*  Treat dark non-digits as pad, but they terminate decode too. */
3273         ncIn = 0;
3274         deliberate_fall_through;
3275       case WS:
3276         /* Treat whitespace as pad and terminate this group.*/
3277         nti = nac;
3278         deliberate_fall_through;
3279       case PC:
3280         bdp = 0;
3281         --nbo;
3282         deliberate_fall_through;
3283       default: /* bdp is the digit value. */
3284         qv = qv<<6 | bdp;
3285         break;
3286       }
3287     }
3288     switch( nbo ){
3289     case 3:
3290       pOut[2] = (qv) & 0xff;
3291     case 2:
3292       pOut[1] = (qv>>8) & 0xff;
3293     case 1:
3294       pOut[0] = (qv>>16) & 0xff;
3295     }
3296     pOut += nbo;
3297   }
3298   return pOut;
3299 }
3300 
3301 /* This function does the work for the SQLite base64(x) UDF. */
3302 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
3303   int nb, nc, nv = sqlite3_value_bytes(av[0]);
3304   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
3305                             SQLITE_LIMIT_LENGTH, -1);
3306   char *cBuf;
3307   u8 *bBuf;
3308   assert(na==1);
3309   switch( sqlite3_value_type(av[0]) ){
3310   case SQLITE_BLOB:
3311     nb = nv;
3312     nc = 4*(nv+2/3); /* quads needed */
3313     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
3314     if( nvMax < nc ){
3315       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
3316       return;
3317     }
3318     cBuf = sqlite3_malloc(nc);
3319     if( !cBuf ) goto memFail;
3320     bBuf = (u8*)sqlite3_value_blob(av[0]);
3321     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
3322     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
3323     break;
3324   case SQLITE_TEXT:
3325     nc = nv;
3326     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
3327     if( nvMax < nb ){
3328       sqlite3_result_error(context, "blob from base64 may be too big", -1);
3329       return;
3330     }else if( nb<1 ){
3331       nb = 1;
3332     }
3333     bBuf = sqlite3_malloc(nb);
3334     if( !bBuf ) goto memFail;
3335     cBuf = (char *)sqlite3_value_text(av[0]);
3336     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
3337     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
3338     break;
3339   default:
3340     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
3341     return;
3342   }
3343   return;
3344  memFail:
3345   sqlite3_result_error(context, "base64 OOM", -1);
3346 }
3347 
3348 /*
3349 ** Establish linkage to running SQLite library.
3350 */
3351 #ifndef SQLITE_SHELL_EXTFUNCS
3352 #ifdef _WIN32
3353 
3354 #endif
3355 int sqlite3_base_init
3356 #else
3357 static int sqlite3_base64_init
3358 #endif
3359 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
3360   SQLITE_EXTENSION_INIT2(pApi);
3361   (void)pzErr;
3362   return sqlite3_create_function
3363     (db, "base64", 1,
3364      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
3365      0, base64, 0, 0);
3366 }
3367 
3368 /*
3369 ** Define some macros to allow this extension to be built into the shell
3370 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
3371 ** allows shell.c, as distributed, to have this extension built in.
3372 */
3373 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
3374 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
3375 
3376 /************************* End ../ext/misc/base64.c ********************/
3377 #undef sqlite3_base_init
3378 #define sqlite3_base_init sqlite3_base85_init
3379 #define OMIT_BASE85_CHECKER
3380 /************************* Begin ../ext/misc/base85.c ******************/
3381 /*
3382 ** 2022-11-16
3383 **
3384 ** The author disclaims copyright to this source code.  In place of
3385 ** a legal notice, here is a blessing:
3386 **
3387 **    May you do good and not evil.
3388 **    May you find forgiveness for yourself and forgive others.
3389 **    May you share freely, never taking more than you give.
3390 **
3391 *************************************************************************
3392 **
3393 ** This is a utility for converting binary to base85 or vice-versa.
3394 ** It can be built as a standalone program or an SQLite3 extension.
3395 **
3396 ** Much like base64 representations, base85 can be sent through a
3397 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3398 ** written as TCL brace-enclosed literals or SQL string literals.
3399 ** It is not suited for unmodified use in XML-like documents.
3400 **
3401 ** The encoding used resembles Ascii85, but was devised by the author
3402 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
3403 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
3404 ** Further, this is an independent implementation of a base85 system.
3405 ** Hence, the author has rightfully put this into the public domain.
3406 **
3407 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
3408 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
3409 ** in code order representing digit values 0 to 84 (base 10.)
3410 **
3411 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
3412 ** are represented as 5-digit base85 numbers with MS to LS digit
3413 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
3414 ** still big-endian but 8-24 bit values. (Using big-endian yields
3415 ** the simplest transition to byte groups smaller than 4 bytes.
3416 ** These byte groups can also be considered base-256 numbers.)
3417 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
3418 ** No pad characters are used; Encoded base85 numeral sequence
3419 ** (aka "group") length maps 1-to-1 to the decoded binary length.
3420 **
3421 ** Any character not in the base85 numeral set delimits groups.
3422 ** When base85 is streamed or stored in containers of indefinite
3423 ** size, newline is used to separate it into sub-sequences of no
3424 ** more than 80 digits so that fgets() can be used to read it.
3425 **
3426 ** Length limitations are not imposed except that the runtime
3427 ** SQLite string or blob length limits are respected. Otherwise,
3428 ** any length binary sequence can be represented and recovered.
3429 ** Base85 sequences can be concatenated by separating them with
3430 ** a non-base85 character; the conversion to binary will then
3431 ** be the concatenation of the represented binary sequences.
3432 
3433 ** The standalone program either converts base85 on stdin to create
3434 ** a binary file or converts a binary file to base85 on stdout.
3435 ** Read or make it blurt its help for invocation details.
3436 **
3437 ** The SQLite3 extension creates a function, base85(x), which will
3438 ** either convert text base85 to a blob or a blob to text base85
3439 ** and return the result (or throw an error for other types.)
3440 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
3441 ** function, is_base85(t), which returns 1 iff the text t contains
3442 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
3443 **
3444 ** To build the extension:
3445 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3446 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
3447 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
3448 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
3449 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
3450 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
3451 **
3452 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
3453 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
3454 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
3455 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
3456 */
3457 
3458 #include <stdio.h>
3459 #include <memory.h>
3460 #include <string.h>
3461 #include <assert.h>
3462 #ifndef OMIT_BASE85_CHECKER
3463 # include <ctype.h>
3464 #endif
3465 
3466 #ifndef BASE85_STANDALONE
3467 
3468 /* # include "sqlite3ext.h" */
3469 
3470 SQLITE_EXTENSION_INIT1;
3471 
3472 #else
3473 
3474 # ifdef _WIN32
3475 #  include <io.h>
3476 #  include <fcntl.h>
3477 # else
3478 #  define setmode(fd,m)
3479 # endif
3480 
3481 static char *zHelp =
3482   "Usage: base85 <dirFlag> <binFile>\n"
3483   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
3484   "   content to be converted to/from base85 on stdout/stdin.\n"
3485   " <binFile> names a binary file to be rendered or created.\n"
3486   "   Or, the name '-' refers to the stdin or stdout stream.\n"
3487   ;
3488 
3489 static void sayHelp(){
3490   printf("%s", zHelp);
3491 }
3492 #endif
3493 
3494 #ifndef U8_TYPEDEF
3495 /* typedef unsigned char u8; */
3496 #define U8_TYPEDEF
3497 #endif
3498 
3499 /* Classify c according to interval within USASCII set w.r.t. base85
3500  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
3501  */
3502 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
3503 
3504 /* Provide digitValue to b85Numeral offset as a function of above class. */
3505 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
3506 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
3507 
3508 /* Say whether c is a base85 numeral. */
3509 #define IS_B85( c ) (B85_CLASS(c) & 1)
3510 
3511 #if 0 /* Not used, */
3512 static u8 base85DigitValue( char c ){
3513   u8 dv = (u8)(c - '#');
3514   if( dv>87 ) return 0xff;
3515   return (dv > 3)? dv-3 : dv;
3516 }
3517 #endif
3518 
3519 /* Width of base64 lines. Should be an integer multiple of 5. */
3520 #define B85_DARK_MAX 80
3521 
3522 
3523 static char * skipNonB85( char *s ){
3524   char c;
3525   while( (c = *s) && !IS_B85(c) ) ++s;
3526   return s;
3527 }
3528 
3529 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
3530  * Do not use the macro form with argument expression having a side-effect.*/
3531 #if 0
3532 static char base85Numeral( u8 b ){
3533   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
3534 }
3535 #else
3536 # define base85Numeral( dn )\
3537   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
3538 #endif
3539 
3540 static char *putcs(char *pc, char *s){
3541   char c;
3542   while( (c = *s++)!=0 ) *pc++ = c;
3543   return pc;
3544 }
3545 
3546 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
3547 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
3548 ** or to terminate the last group (to aid concatenation.)
3549 */
3550 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
3551   int nCol = 0;
3552   while( nbIn >= 4 ){
3553     int nco = 5;
3554     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
3555                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
3556     while( nco > 0 ){
3557       unsigned nqv = (unsigned)(qbv/85UL);
3558       unsigned char dv = qbv - 85UL*nqv;
3559       qbv = nqv;
3560       pOut[--nco] = base85Numeral(dv);
3561     }
3562     nbIn -= 4;
3563     pIn += 4;
3564     pOut += 5;
3565     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
3566       pOut = putcs(pOut, pSep);
3567       nCol = 0;
3568     }
3569   }
3570   if( nbIn > 0 ){
3571     int nco = nbIn + 1;
3572     unsigned long qv = *pIn++;
3573     int nbe = 1;
3574     while( nbe++ < nbIn ){
3575       qv = (qv<<8) | *pIn++;
3576     }
3577     nCol += nco;
3578     while( nco > 0 ){
3579       u8 dv = (u8)(qv % 85);
3580       qv /= 85;
3581       pOut[--nco] = base85Numeral(dv);
3582     }
3583     pOut += (nbIn+1);
3584   }
3585   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
3586   *pOut = 0;
3587   return pOut;
3588 }
3589 
3590 /* Decode base85 text into a byte buffer. */
3591 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
3592   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3593   while( ncIn>0 ){
3594     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
3595     char *pUse = skipNonB85(pIn);
3596     unsigned long qv = 0L;
3597     int nti, nbo;
3598     ncIn -= (pUse - pIn);
3599     pIn = pUse;
3600     nti = (ncIn>5)? 5 : ncIn;
3601     nbo = nboi[nti];
3602     if( nbo==0 ) break;
3603     while( nti>0 ){
3604       char c = *pIn++;
3605       u8 cdo = B85_DNOS(c);
3606       --ncIn;
3607       if( cdo==0 ) break;
3608       qv = 85 * qv + (c - cdo);
3609       --nti;
3610     }
3611     nbo -= nti; /* Adjust for early (non-digit) end of group. */
3612     switch( nbo ){
3613     case 4:
3614       *pOut++ = (qv >> 24)&0xff;
3615     case 3:
3616       *pOut++ = (qv >> 16)&0xff;
3617     case 2:
3618       *pOut++ = (qv >> 8)&0xff;
3619     case 1:
3620       *pOut++ = qv&0xff;
3621     case 0:
3622       break;
3623     }
3624   }
3625   return pOut;
3626 }
3627 
3628 #ifndef OMIT_BASE85_CHECKER
3629 /* Say whether input char sequence is all (base85 and/or whitespace).*/
3630 static int allBase85( char *p, int len ){
3631   char c;
3632   while( len-- > 0 && (c = *p++) != 0 ){
3633     if( !IS_B85(c) && !isspace(c) ) return 0;
3634   }
3635   return 1;
3636 }
3637 #endif
3638 
3639 #ifndef BASE85_STANDALONE
3640 
3641 # ifndef OMIT_BASE85_CHECKER
3642 /* This function does the work for the SQLite is_base85(t) UDF. */
3643 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
3644   assert(na==1);
3645   switch( sqlite3_value_type(av[0]) ){
3646   case SQLITE_TEXT:
3647     {
3648       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
3649                           sqlite3_value_bytes(av[0]) );
3650       sqlite3_result_int(context, rv);
3651     }
3652     break;
3653   case SQLITE_NULL:
3654     sqlite3_result_null(context);
3655     break;
3656   default:
3657     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
3658     return;
3659   }
3660 }
3661 # endif
3662 
3663 /* This function does the work for the SQLite base85(x) UDF. */
3664 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
3665   int nb, nc, nv = sqlite3_value_bytes(av[0]);
3666   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
3667                             SQLITE_LIMIT_LENGTH, -1);
3668   char *cBuf;
3669   u8 *bBuf;
3670   assert(na==1);
3671   switch( sqlite3_value_type(av[0]) ){
3672   case SQLITE_BLOB:
3673     nb = nv;
3674     /*    ulongs    tail   newlines  tailenc+nul*/
3675     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
3676     if( nvMax < nc ){
3677       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
3678       return;
3679     }
3680     cBuf = sqlite3_malloc(nc);
3681     if( !cBuf ) goto memFail;
3682     bBuf = (u8*)sqlite3_value_blob(av[0]);
3683     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
3684     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
3685     break;
3686   case SQLITE_TEXT:
3687     nc = nv;
3688     nb = 4*(nv/5) + nv%5; /* may overestimate */
3689     if( nvMax < nb ){
3690       sqlite3_result_error(context, "blob from base85 may be too big", -1);
3691       return;
3692     }else if( nb<1 ){
3693       nb = 1;
3694     }
3695     bBuf = sqlite3_malloc(nb);
3696     if( !bBuf ) goto memFail;
3697     cBuf = (char *)sqlite3_value_text(av[0]);
3698     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
3699     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
3700     break;
3701   default:
3702     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
3703     return;
3704   }
3705   return;
3706  memFail:
3707   sqlite3_result_error(context, "base85 OOM", -1);
3708 }
3709 
3710 /*
3711 ** Establish linkage to running SQLite library.
3712 */
3713 #ifndef SQLITE_SHELL_EXTFUNCS
3714 #ifdef _WIN32
3715 
3716 #endif
3717 int sqlite3_base_init
3718 #else
3719 static int sqlite3_base85_init
3720 #endif
3721 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
3722   SQLITE_EXTENSION_INIT2(pApi);
3723   (void)pzErr;
3724 # ifndef OMIT_BASE85_CHECKER
3725   {
3726     int rc = sqlite3_create_function
3727       (db, "is_base85", 1,
3728        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
3729        0, is_base85, 0, 0);
3730     if( rc!=SQLITE_OK ) return rc;
3731   }
3732 # endif
3733   return sqlite3_create_function
3734     (db, "base85", 1,
3735      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
3736      0, base85, 0, 0);
3737 }
3738 
3739 /*
3740 ** Define some macros to allow this extension to be built into the shell
3741 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
3742 ** allows shell.c, as distributed, to have this extension built in.
3743 */
3744 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
3745 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
3746 
3747 #else /* standalone program */
3748 
3749 int main(int na, char *av[]){
3750   int cin;
3751   int rc = 0;
3752   u8 bBuf[4*(B85_DARK_MAX/5)];
3753   char cBuf[5*(sizeof(bBuf)/4)+2];
3754   size_t nio;
3755 # ifndef OMIT_BASE85_CHECKER
3756   int b85Clean = 1;
3757 # endif
3758   char rw;
3759   FILE *fb = 0, *foc = 0;
3760   char fmode[3] = "xb";
3761   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
3762     sayHelp();
3763     return 0;
3764   }
3765   fmode[0] = rw;
3766   if( av[2][0]=='-' && av[2][1]==0 ){
3767     switch( rw ){
3768     case 'r':
3769       fb = stdin;
3770       setmode(fileno(stdin), O_BINARY);
3771       break;
3772     case 'w':
3773       fb = stdout;
3774       setmode(fileno(stdout), O_BINARY);
3775       break;
3776     }
3777   }else{
3778     fb = fopen(av[2], fmode);
3779     foc = fb;
3780   }
3781   if( !fb ){
3782     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
3783     rc = 1;
3784   }else{
3785     switch( rw ){
3786     case 'r':
3787       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
3788         toBase85( bBuf, (int)nio, cBuf, 0 );
3789         fprintf(stdout, "%s\n", cBuf);
3790       }
3791       break;
3792     case 'w':
3793       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
3794         int nc = strlen(cBuf);
3795         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
3796         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
3797 # ifndef OMIT_BASE85_CHECKER
3798         b85Clean &= allBase85( cBuf, nc );
3799 # endif
3800       }
3801       break;
3802     default:
3803       sayHelp();
3804       rc = 1;
3805     }
3806     if( foc ) fclose(foc);
3807   }
3808 # ifndef OMIT_BASE85_CHECKER
3809   if( !b85Clean ){
3810     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
3811   }
3812 # endif
3813   return rc;
3814 }
3815 
3816 #endif
3817 
3818 /************************* End ../ext/misc/base85.c ********************/
3819 /************************* Begin ../ext/misc/ieee754.c ******************/
3820 /*
3821 ** 2013-04-17
3822 **
3823 ** The author disclaims copyright to this source code.  In place of
3824 ** a legal notice, here is a blessing:
3825 **
3826 **    May you do good and not evil.
3827 **    May you find forgiveness for yourself and forgive others.
3828 **    May you share freely, never taking more than you give.
3829 **
3830 ******************************************************************************
3831 **
3832 ** This SQLite extension implements functions for the exact display
3833 ** and input of IEEE754 Binary64 floating-point numbers.
3834 **
3835 **   ieee754(X)
3836 **   ieee754(Y,Z)
3837 **
3838 ** In the first form, the value X should be a floating-point number.
3839 ** The function will return a string of the form 'ieee754(Y,Z)' where
3840 ** Y and Z are integers such that X==Y*pow(2,Z).
3841 **
3842 ** In the second form, Y and Z are integers which are the mantissa and
3843 ** base-2 exponent of a new floating point number.  The function returns
3844 ** a floating-point value equal to Y*pow(2,Z).
3845 **
3846 ** Examples:
3847 **
3848 **     ieee754(2.0)             ->     'ieee754(2,0)'
3849 **     ieee754(45.25)           ->     'ieee754(181,-2)'
3850 **     ieee754(2, 0)            ->     2.0
3851 **     ieee754(181, -2)         ->     45.25
3852 **
3853 ** Two additional functions break apart the one-argument ieee754()
3854 ** result into separate integer values:
3855 **
3856 **     ieee754_mantissa(45.25)  ->     181
3857 **     ieee754_exponent(45.25)  ->     -2
3858 **
3859 ** These functions convert binary64 numbers into blobs and back again.
3860 **
3861 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
3862 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
3863 **
3864 ** In all single-argument functions, if the argument is an 8-byte blob
3865 ** then that blob is interpreted as a big-endian binary64 value.
3866 **
3867 **
3868 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
3869 ** -----------------------------------------------
3870 **
3871 ** This extension in combination with the separate 'decimal' extension
3872 ** can be used to compute the exact decimal representation of binary64
3873 ** values.  To begin, first compute a table of exponent values:
3874 **
3875 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
3876 **    WITH RECURSIVE c(x,v) AS (
3877 **      VALUES(0,'1')
3878 **      UNION ALL
3879 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
3880 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
3881 **    WITH RECURSIVE c(x,v) AS (
3882 **      VALUES(-1,'0.5')
3883 **      UNION ALL
3884 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
3885 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
3886 **
3887 ** Then, to compute the exact decimal representation of a floating
3888 ** point value (the value 47.49 is used in the example) do:
3889 **
3890 **    WITH c(n) AS (VALUES(47.49))
3891 **          ---------------^^^^^---- Replace with whatever you want
3892 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
3893 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
3894 **
3895 ** Here is a query to show various boundry values for the binary64
3896 ** number format:
3897 **
3898 **    WITH c(name,bin) AS (VALUES
3899 **       ('minimum positive value',        x'0000000000000001'),
3900 **       ('maximum subnormal value',       x'000fffffffffffff'),
3901 **       ('mininum positive nornal value', x'0010000000000000'),
3902 **       ('maximum value',                 x'7fefffffffffffff'))
3903 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
3904 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
3905 **
3906 */
3907 /* #include "sqlite3ext.h" */
3908 SQLITE_EXTENSION_INIT1
3909 #include <assert.h>
3910 #include <string.h>
3911 
3912 /* Mark a function parameter as unused, to suppress nuisance compiler
3913 ** warnings. */
3914 #ifndef UNUSED_PARAMETER
3915 # define UNUSED_PARAMETER(X)  (void)(X)
3916 #endif
3917 
3918 /*
3919 ** Implementation of the ieee754() function
3920 */
3921 static void ieee754func(
3922   sqlite3_context *context,
3923   int argc,
3924   sqlite3_value **argv
3925 ){
3926   if( argc==1 ){
3927     sqlite3_int64 m, a;
3928     double r;
3929     int e;
3930     int isNeg;
3931     char zResult[100];
3932     assert( sizeof(m)==sizeof(r) );
3933     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
3934      && sqlite3_value_bytes(argv[0])==sizeof(r)
3935     ){
3936       const unsigned char *x = sqlite3_value_blob(argv[0]);
3937       unsigned int i;
3938       sqlite3_uint64 v = 0;
3939       for(i=0; i<sizeof(r); i++){
3940         v = (v<<8) | x[i];
3941       }
3942       memcpy(&r, &v, sizeof(r));
3943     }else{
3944       r = sqlite3_value_double(argv[0]);
3945     }
3946     if( r<0.0 ){
3947       isNeg = 1;
3948       r = -r;
3949     }else{
3950       isNeg = 0;
3951     }
3952     memcpy(&a,&r,sizeof(a));
3953     if( a==0 ){
3954       e = 0;
3955       m = 0;
3956     }else{
3957       e = a>>52;
3958       m = a & ((((sqlite3_int64)1)<<52)-1);
3959       if( e==0 ){
3960         m <<= 1;
3961       }else{
3962         m |= ((sqlite3_int64)1)<<52;
3963       }
3964       while( e<1075 && m>0 && (m&1)==0 ){
3965         m >>= 1;
3966         e++;
3967       }
3968       if( isNeg ) m = -m;
3969     }
3970     switch( *(int*)sqlite3_user_data(context) ){
3971       case 0:
3972         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
3973                          m, e-1075);
3974         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
3975         break;
3976       case 1:
3977         sqlite3_result_int64(context, m);
3978         break;
3979       case 2:
3980         sqlite3_result_int(context, e-1075);
3981         break;
3982     }
3983   }else{
3984     sqlite3_int64 m, e, a;
3985     double r;
3986     int isNeg = 0;
3987     m = sqlite3_value_int64(argv[0]);
3988     e = sqlite3_value_int64(argv[1]);
3989 
3990     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
3991     if( e>10000 ){
3992       e = 10000;
3993     }else if( e<-10000 ){
3994       e = -10000;
3995     }
3996 
3997     if( m<0 ){
3998       isNeg = 1;
3999       m = -m;
4000       if( m<0 ) return;
4001     }else if( m==0 && e>-1000 && e<1000 ){
4002       sqlite3_result_double(context, 0.0);
4003       return;
4004     }
4005     while( (m>>32)&0xffe00000 ){
4006       m >>= 1;
4007       e++;
4008     }
4009     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
4010       m <<= 1;
4011       e--;
4012     }
4013     e += 1075;
4014     if( e<=0 ){
4015       /* Subnormal */
4016       if( 1-e >= 64 ){
4017         m = 0;
4018       }else{
4019         m >>= 1-e;
4020       }
4021       e = 0;
4022     }else if( e>0x7ff ){
4023       e = 0x7ff;
4024     }
4025     a = m & ((((sqlite3_int64)1)<<52)-1);
4026     a |= e<<52;
4027     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
4028     memcpy(&r, &a, sizeof(r));
4029     sqlite3_result_double(context, r);
4030   }
4031 }
4032 
4033 /*
4034 ** Functions to convert between blobs and floats.
4035 */
4036 static void ieee754func_from_blob(
4037   sqlite3_context *context,
4038   int argc,
4039   sqlite3_value **argv
4040 ){
4041   UNUSED_PARAMETER(argc);
4042   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
4043    && sqlite3_value_bytes(argv[0])==sizeof(double)
4044   ){
4045     double r;
4046     const unsigned char *x = sqlite3_value_blob(argv[0]);
4047     unsigned int i;
4048     sqlite3_uint64 v = 0;
4049     for(i=0; i<sizeof(r); i++){
4050       v = (v<<8) | x[i];
4051     }
4052     memcpy(&r, &v, sizeof(r));
4053     sqlite3_result_double(context, r);
4054   }
4055 }
4056 static void ieee754func_to_blob(
4057   sqlite3_context *context,
4058   int argc,
4059   sqlite3_value **argv
4060 ){
4061   UNUSED_PARAMETER(argc);
4062   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
4063    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
4064   ){
4065     double r = sqlite3_value_double(argv[0]);
4066     sqlite3_uint64 v;
4067     unsigned char a[sizeof(r)];
4068     unsigned int i;
4069     memcpy(&v, &r, sizeof(r));
4070     for(i=1; i<=sizeof(r); i++){
4071       a[sizeof(r)-i] = v&0xff;
4072       v >>= 8;
4073     }
4074     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
4075   }
4076 }
4077 
4078 
4079 #ifdef _WIN32
4080 
4081 #endif
4082 int sqlite3_ieee_init(
4083   sqlite3 *db,
4084   char **pzErrMsg,
4085   const sqlite3_api_routines *pApi
4086 ){
4087   static const struct {
4088     char *zFName;
4089     int nArg;
4090     int iAux;
4091     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4092   } aFunc[] = {
4093     { "ieee754",           1,   0, ieee754func },
4094     { "ieee754",           2,   0, ieee754func },
4095     { "ieee754_mantissa",  1,   1, ieee754func },
4096     { "ieee754_exponent",  1,   2, ieee754func },
4097     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
4098     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
4099 
4100   };
4101   unsigned int i;
4102   int rc = SQLITE_OK;
4103   SQLITE_EXTENSION_INIT2(pApi);
4104   (void)pzErrMsg;  /* Unused parameter */
4105   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
4106     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
4107                                SQLITE_UTF8|SQLITE_INNOCUOUS,
4108                                (void*)&aFunc[i].iAux,
4109                                aFunc[i].xFunc, 0, 0);
4110   }
4111   return rc;
4112 }
4113 
4114 /************************* End ../ext/misc/ieee754.c ********************/
4115 /************************* Begin ../ext/misc/series.c ******************/
4116 /*
4117 ** 2015-08-18
4118 **
4119 ** The author disclaims copyright to this source code.  In place of
4120 ** a legal notice, here is a blessing:
4121 **
4122 **    May you do good and not evil.
4123 **    May you find forgiveness for yourself and forgive others.
4124 **    May you share freely, never taking more than you give.
4125 **
4126 *************************************************************************
4127 **
4128 ** This file demonstrates how to create a table-valued-function using
4129 ** a virtual table.  This demo implements the generate_series() function
4130 ** which gives similar results to the eponymous function in PostgreSQL.
4131 ** Examples:
4132 **
4133 **      SELECT * FROM generate_series(0,100,5);
4134 **
4135 ** The query above returns integers from 0 through 100 counting by steps
4136 ** of 5.
4137 **
4138 **      SELECT * FROM generate_series(0,100);
4139 **
4140 ** Integers from 0 through 100 with a step size of 1.
4141 **
4142 **      SELECT * FROM generate_series(20) LIMIT 10;
4143 **
4144 ** Integers 20 through 29.
4145 **
4146 ** HOW IT WORKS
4147 **
4148 ** The generate_series "function" is really a virtual table with the
4149 ** following schema:
4150 **
4151 **     CREATE TABLE generate_series(
4152 **       value,
4153 **       start HIDDEN,
4154 **       stop HIDDEN,
4155 **       step HIDDEN
4156 **     );
4157 **
4158 ** Function arguments in queries against this virtual table are translated
4159 ** into equality constraints against successive hidden columns.  In other
4160 ** words, the following pairs of queries are equivalent to each other:
4161 **
4162 **    SELECT * FROM generate_series(0,100,5);
4163 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
4164 **
4165 **    SELECT * FROM generate_series(0,100);
4166 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
4167 **
4168 **    SELECT * FROM generate_series(20) LIMIT 10;
4169 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
4170 **
4171 ** The generate_series virtual table implementation leaves the xCreate method
4172 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
4173 ** TABLE command with "generate_series" as the USING argument.  Instead, there
4174 ** is a single generate_series virtual table that is always available without
4175 ** having to be created first.
4176 **
4177 ** The xBestIndex method looks for equality constraints against the hidden
4178 ** start, stop, and step columns, and if present, it uses those constraints
4179 ** to bound the sequence of generated values.  If the equality constraints
4180 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
4181 ** xBestIndex returns a small cost when both start and stop are available,
4182 ** and a very large cost if either start or stop are unavailable.  This
4183 ** encourages the query planner to order joins such that the bounds of the
4184 ** series are well-defined.
4185 */
4186 /* #include "sqlite3ext.h" */
4187 SQLITE_EXTENSION_INIT1
4188 #include <assert.h>
4189 #include <string.h>
4190 
4191 #ifndef SQLITE_OMIT_VIRTUALTABLE
4192 
4193 
4194 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
4195 ** serve as the underlying representation of a cursor that scans
4196 ** over rows of the result
4197 */
4198 typedef struct series_cursor series_cursor;
4199 struct series_cursor {
4200   sqlite3_vtab_cursor base;  /* Base class - must be first */
4201   int isDesc;                /* True to count down rather than up */
4202   sqlite3_int64 iRowid;      /* The rowid */
4203   sqlite3_int64 iValue;      /* Current value ("value") */
4204   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
4205   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
4206   sqlite3_int64 iStep;       /* Increment ("step") */
4207 };
4208 
4209 /*
4210 ** The seriesConnect() method is invoked to create a new
4211 ** series_vtab that describes the generate_series virtual table.
4212 **
4213 ** Think of this routine as the constructor for series_vtab objects.
4214 **
4215 ** All this routine needs to do is:
4216 **
4217 **    (1) Allocate the series_vtab object and initialize all fields.
4218 **
4219 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
4220 **        result set of queries against generate_series will look like.
4221 */
4222 static int seriesConnect(
4223   sqlite3 *db,
4224   void *pUnused,
4225   int argcUnused, const char *const*argvUnused,
4226   sqlite3_vtab **ppVtab,
4227   char **pzErrUnused
4228 ){
4229   sqlite3_vtab *pNew;
4230   int rc;
4231 
4232 /* Column numbers */
4233 #define SERIES_COLUMN_VALUE 0
4234 #define SERIES_COLUMN_START 1
4235 #define SERIES_COLUMN_STOP  2
4236 #define SERIES_COLUMN_STEP  3
4237 
4238   (void)pUnused;
4239   (void)argcUnused;
4240   (void)argvUnused;
4241   (void)pzErrUnused;
4242   rc = sqlite3_declare_vtab(db,
4243      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
4244   if( rc==SQLITE_OK ){
4245     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
4246     if( pNew==0 ) return SQLITE_NOMEM;
4247     memset(pNew, 0, sizeof(*pNew));
4248     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
4249   }
4250   return rc;
4251 }
4252 
4253 /*
4254 ** This method is the destructor for series_cursor objects.
4255 */
4256 static int seriesDisconnect(sqlite3_vtab *pVtab){
4257   sqlite3_free(pVtab);
4258   return SQLITE_OK;
4259 }
4260 
4261 /*
4262 ** Constructor for a new series_cursor object.
4263 */
4264 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
4265   series_cursor *pCur;
4266   (void)pUnused;
4267   pCur = sqlite3_malloc( sizeof(*pCur) );
4268   if( pCur==0 ) return SQLITE_NOMEM;
4269   memset(pCur, 0, sizeof(*pCur));
4270   *ppCursor = &pCur->base;
4271   return SQLITE_OK;
4272 }
4273 
4274 /*
4275 ** Destructor for a series_cursor.
4276 */
4277 static int seriesClose(sqlite3_vtab_cursor *cur){
4278   sqlite3_free(cur);
4279   return SQLITE_OK;
4280 }
4281 
4282 
4283 /*
4284 ** Advance a series_cursor to its next row of output.
4285 */
4286 static int seriesNext(sqlite3_vtab_cursor *cur){
4287   series_cursor *pCur = (series_cursor*)cur;
4288   if( pCur->isDesc ){
4289     pCur->iValue -= pCur->iStep;
4290   }else{
4291     pCur->iValue += pCur->iStep;
4292   }
4293   pCur->iRowid++;
4294   return SQLITE_OK;
4295 }
4296 
4297 /*
4298 ** Return values of columns for the row at which the series_cursor
4299 ** is currently pointing.
4300 */
4301 static int seriesColumn(
4302   sqlite3_vtab_cursor *cur,   /* The cursor */
4303   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
4304   int i                       /* Which column to return */
4305 ){
4306   series_cursor *pCur = (series_cursor*)cur;
4307   sqlite3_int64 x = 0;
4308   switch( i ){
4309     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
4310     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
4311     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
4312     default:                   x = pCur->iValue;  break;
4313   }
4314   sqlite3_result_int64(ctx, x);
4315   return SQLITE_OK;
4316 }
4317 
4318 /*
4319 ** Return the rowid for the current row. In this implementation, the
4320 ** first row returned is assigned rowid value 1, and each subsequent
4321 ** row a value 1 more than that of the previous.
4322 */
4323 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
4324   series_cursor *pCur = (series_cursor*)cur;
4325   *pRowid = pCur->iRowid;
4326   return SQLITE_OK;
4327 }
4328 
4329 /*
4330 ** Return TRUE if the cursor has been moved off of the last
4331 ** row of output.
4332 */
4333 static int seriesEof(sqlite3_vtab_cursor *cur){
4334   series_cursor *pCur = (series_cursor*)cur;
4335   if( pCur->isDesc ){
4336     return pCur->iValue < pCur->mnValue;
4337   }else{
4338     return pCur->iValue > pCur->mxValue;
4339   }
4340 }
4341 
4342 /* True to cause run-time checking of the start=, stop=, and/or step=
4343 ** parameters.  The only reason to do this is for testing the
4344 ** constraint checking logic for virtual tables in the SQLite core.
4345 */
4346 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
4347 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
4348 #endif
4349 
4350 /*
4351 ** This method is called to "rewind" the series_cursor object back
4352 ** to the first row of output.  This method is always called at least
4353 ** once prior to any call to seriesColumn() or seriesRowid() or
4354 ** seriesEof().
4355 **
4356 ** The query plan selected by seriesBestIndex is passed in the idxNum
4357 ** parameter.  (idxStr is not used in this implementation.)  idxNum
4358 ** is a bitmask showing which constraints are available:
4359 **
4360 **    1:    start=VALUE
4361 **    2:    stop=VALUE
4362 **    4:    step=VALUE
4363 **
4364 ** Also, if bit 8 is set, that means that the series should be output
4365 ** in descending order rather than in ascending order.  If bit 16 is
4366 ** set, then output must appear in ascending order.
4367 **
4368 ** This routine should initialize the cursor and position it so that it
4369 ** is pointing at the first row, or pointing off the end of the table
4370 ** (so that seriesEof() will return true) if the table is empty.
4371 */
4372 static int seriesFilter(
4373   sqlite3_vtab_cursor *pVtabCursor,
4374   int idxNum, const char *idxStrUnused,
4375   int argc, sqlite3_value **argv
4376 ){
4377   series_cursor *pCur = (series_cursor *)pVtabCursor;
4378   int i = 0;
4379   (void)idxStrUnused;
4380   if( idxNum & 1 ){
4381     pCur->mnValue = sqlite3_value_int64(argv[i++]);
4382   }else{
4383     pCur->mnValue = 0;
4384   }
4385   if( idxNum & 2 ){
4386     pCur->mxValue = sqlite3_value_int64(argv[i++]);
4387   }else{
4388     pCur->mxValue = 0xffffffff;
4389   }
4390   if( idxNum & 4 ){
4391     pCur->iStep = sqlite3_value_int64(argv[i++]);
4392     if( pCur->iStep==0 ){
4393       pCur->iStep = 1;
4394     }else if( pCur->iStep<0 ){
4395       pCur->iStep = -pCur->iStep;
4396       if( (idxNum & 16)==0 ) idxNum |= 8;
4397     }
4398   }else{
4399     pCur->iStep = 1;
4400   }
4401   for(i=0; i<argc; i++){
4402     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
4403       /* If any of the constraints have a NULL value, then return no rows.
4404       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
4405       pCur->mnValue = 1;
4406       pCur->mxValue = 0;
4407       break;
4408     }
4409   }
4410   if( idxNum & 8 ){
4411     pCur->isDesc = 1;
4412     pCur->iValue = pCur->mxValue;
4413     if( pCur->iStep>0 ){
4414       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
4415     }
4416   }else{
4417     pCur->isDesc = 0;
4418     pCur->iValue = pCur->mnValue;
4419   }
4420   pCur->iRowid = 1;
4421   return SQLITE_OK;
4422 }
4423 
4424 /*
4425 ** SQLite will invoke this method one or more times while planning a query
4426 ** that uses the generate_series virtual table.  This routine needs to create
4427 ** a query plan for each invocation and compute an estimated cost for that
4428 ** plan.
4429 **
4430 ** In this implementation idxNum is used to represent the
4431 ** query plan.  idxStr is unused.
4432 **
4433 ** The query plan is represented by bits in idxNum:
4434 **
4435 **  (1)  start = $value  -- constraint exists
4436 **  (2)  stop = $value   -- constraint exists
4437 **  (4)  step = $value   -- constraint exists
4438 **  (8)  output in descending order
4439 */
4440 static int seriesBestIndex(
4441   sqlite3_vtab *pVTab,
4442   sqlite3_index_info *pIdxInfo
4443 ){
4444   int i, j;              /* Loop over constraints */
4445   int idxNum = 0;        /* The query plan bitmask */
4446   int bStartSeen = 0;    /* EQ constraint seen on the START column */
4447   int unusableMask = 0;  /* Mask of unusable constraints */
4448   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
4449   int aIdx[3];           /* Constraints on start, stop, and step */
4450   const struct sqlite3_index_constraint *pConstraint;
4451 
4452   /* This implementation assumes that the start, stop, and step columns
4453   ** are the last three columns in the virtual table. */
4454   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
4455   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
4456 
4457   aIdx[0] = aIdx[1] = aIdx[2] = -1;
4458   pConstraint = pIdxInfo->aConstraint;
4459   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
4460     int iCol;    /* 0 for start, 1 for stop, 2 for step */
4461     int iMask;   /* bitmask for those column */
4462     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
4463     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
4464     assert( iCol>=0 && iCol<=2 );
4465     iMask = 1 << iCol;
4466     if( iCol==0 ) bStartSeen = 1;
4467     if( pConstraint->usable==0 ){
4468       unusableMask |=  iMask;
4469       continue;
4470     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
4471       idxNum |= iMask;
4472       aIdx[iCol] = i;
4473     }
4474   }
4475   for(i=0; i<3; i++){
4476     if( (j = aIdx[i])>=0 ){
4477       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
4478       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
4479     }
4480   }
4481   /* The current generate_column() implementation requires at least one
4482   ** argument (the START value).  Legacy versions assumed START=0 if the
4483   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
4484   ** to obtain the legacy behavior */
4485 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
4486   if( !bStartSeen ){
4487     sqlite3_free(pVTab->zErrMsg);
4488     pVTab->zErrMsg = sqlite3_mprintf(
4489         "first argument to \"generate_series()\" missing or unusable");
4490     return SQLITE_ERROR;
4491   }
4492 #endif
4493   if( (unusableMask & ~idxNum)!=0 ){
4494     /* The start, stop, and step columns are inputs.  Therefore if there
4495     ** are unusable constraints on any of start, stop, or step then
4496     ** this plan is unusable */
4497     return SQLITE_CONSTRAINT;
4498   }
4499   if( (idxNum & 3)==3 ){
4500     /* Both start= and stop= boundaries are available.  This is the
4501     ** the preferred case */
4502     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
4503     pIdxInfo->estimatedRows = 1000;
4504     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
4505       if( pIdxInfo->aOrderBy[0].desc ){
4506         idxNum |= 8;
4507       }else{
4508         idxNum |= 16;
4509       }
4510       pIdxInfo->orderByConsumed = 1;
4511     }
4512   }else{
4513     /* If either boundary is missing, we have to generate a huge span
4514     ** of numbers.  Make this case very expensive so that the query
4515     ** planner will work hard to avoid it. */
4516     pIdxInfo->estimatedRows = 2147483647;
4517   }
4518   pIdxInfo->idxNum = idxNum;
4519   return SQLITE_OK;
4520 }
4521 
4522 /*
4523 ** This following structure defines all the methods for the
4524 ** generate_series virtual table.
4525 */
4526 static sqlite3_module seriesModule = {
4527   0,                         /* iVersion */
4528   0,                         /* xCreate */
4529   seriesConnect,             /* xConnect */
4530   seriesBestIndex,           /* xBestIndex */
4531   seriesDisconnect,          /* xDisconnect */
4532   0,                         /* xDestroy */
4533   seriesOpen,                /* xOpen - open a cursor */
4534   seriesClose,               /* xClose - close a cursor */
4535   seriesFilter,              /* xFilter - configure scan constraints */
4536   seriesNext,                /* xNext - advance a cursor */
4537   seriesEof,                 /* xEof - check for end of scan */
4538   seriesColumn,              /* xColumn - read data */
4539   seriesRowid,               /* xRowid - read data */
4540   0,                         /* xUpdate */
4541   0,                         /* xBegin */
4542   0,                         /* xSync */
4543   0,                         /* xCommit */
4544   0,                         /* xRollback */
4545   0,                         /* xFindMethod */
4546   0,                         /* xRename */
4547   0,                         /* xSavepoint */
4548   0,                         /* xRelease */
4549   0,                         /* xRollbackTo */
4550   0                          /* xShadowName */
4551 };
4552 
4553 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4554 
4555 #ifdef _WIN32
4556 
4557 #endif
4558 int sqlite3_series_init(
4559   sqlite3 *db,
4560   char **pzErrMsg,
4561   const sqlite3_api_routines *pApi
4562 ){
4563   int rc = SQLITE_OK;
4564   SQLITE_EXTENSION_INIT2(pApi);
4565 #ifndef SQLITE_OMIT_VIRTUALTABLE
4566   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
4567     *pzErrMsg = sqlite3_mprintf(
4568         "generate_series() requires SQLite 3.8.12 or later");
4569     return SQLITE_ERROR;
4570   }
4571   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
4572 #endif
4573   return rc;
4574 }
4575 
4576 /************************* End ../ext/misc/series.c ********************/
4577 /************************* Begin ../ext/misc/regexp.c ******************/
4578 /*
4579 ** 2012-11-13
4580 **
4581 ** The author disclaims copyright to this source code.  In place of
4582 ** a legal notice, here is a blessing:
4583 **
4584 **    May you do good and not evil.
4585 **    May you find forgiveness for yourself and forgive others.
4586 **    May you share freely, never taking more than you give.
4587 **
4588 ******************************************************************************
4589 **
4590 ** The code in this file implements a compact but reasonably
4591 ** efficient regular-expression matcher for posix extended regular
4592 ** expressions against UTF8 text.
4593 **
4594 ** This file is an SQLite extension.  It registers a single function
4595 ** named "regexp(A,B)" where A is the regular expression and B is the
4596 ** string to be matched.  By registering this function, SQLite will also
4597 ** then implement the "B regexp A" operator.  Note that with the function
4598 ** the regular expression comes first, but with the operator it comes
4599 ** second.
4600 **
4601 **  The following regular expression syntax is supported:
4602 **
4603 **     X*      zero or more occurrences of X
4604 **     X+      one or more occurrences of X
4605 **     X?      zero or one occurrences of X
4606 **     X{p,q}  between p and q occurrences of X
4607 **     (X)     match X
4608 **     X|Y     X or Y
4609 **     ^X      X occurring at the beginning of the string
4610 **     X$      X occurring at the end of the string
4611 **     .       Match any single character
4612 **     \c      Character c where c is one of \{}()[]|*+?.
4613 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
4614 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
4615 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
4616 **     [abc]   Any single character from the set abc
4617 **     [^abc]  Any single character not in the set abc
4618 **     [a-z]   Any single character in the range a-z
4619 **     [^a-z]  Any single character not in the range a-z
4620 **     \b      Word boundary
4621 **     \w      Word character.  [A-Za-z0-9_]
4622 **     \W      Non-word character
4623 **     \d      Digit
4624 **     \D      Non-digit
4625 **     \s      Whitespace character
4626 **     \S      Non-whitespace character
4627 **
4628 ** A nondeterministic finite automaton (NFA) is used for matching, so the
4629 ** performance is bounded by O(N*M) where N is the size of the regular
4630 ** expression and M is the size of the input string.  The matcher never
4631 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
4632 ** to p copies of X following by q-p copies of X? and that the size of the
4633 ** regular expression in the O(N*M) performance bound is computed after
4634 ** this expansion.
4635 */
4636 #include <string.h>
4637 #include <stdlib.h>
4638 /* #include "sqlite3ext.h" */
4639 SQLITE_EXTENSION_INIT1
4640 
4641 /*
4642 ** The following #defines change the names of some functions implemented in
4643 ** this file to prevent name collisions with C-library functions of the
4644 ** same name.
4645 */
4646 #define re_match   sqlite3re_match
4647 #define re_compile sqlite3re_compile
4648 #define re_free    sqlite3re_free
4649 
4650 /* The end-of-input character */
4651 #define RE_EOF            0    /* End of input */
4652 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
4653 
4654 /* The NFA is implemented as sequence of opcodes taken from the following
4655 ** set.  Each opcode has a single integer argument.
4656 */
4657 #define RE_OP_MATCH       1    /* Match the one character in the argument */
4658 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
4659 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
4660 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
4661 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
4662 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
4663 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
4664 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
4665 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
4666 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
4667 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
4668 #define RE_OP_NOTWORD    12    /* Not a perl word character */
4669 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
4670 #define RE_OP_NOTDIGIT   14    /* Not a digit */
4671 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
4672 #define RE_OP_NOTSPACE   16    /* Not a digit */
4673 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
4674 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
4675 
4676 #if defined(SQLITE_DEBUG)
4677 /* Opcode names used for symbolic debugging */
4678 static const char *ReOpName[] = {
4679   "EOF",
4680   "MATCH",
4681   "ANY",
4682   "ANYSTAR",
4683   "FORK",
4684   "GOTO",
4685   "ACCEPT",
4686   "CC_INC",
4687   "CC_EXC",
4688   "CC_VALUE",
4689   "CC_RANGE",
4690   "WORD",
4691   "NOTWORD",
4692   "DIGIT",
4693   "NOTDIGIT",
4694   "SPACE",
4695   "NOTSPACE",
4696   "BOUNDARY",
4697   "ATSTART",
4698 };
4699 #endif /* SQLITE_DEBUG */
4700 
4701 
4702 /* Each opcode is a "state" in the NFA */
4703 typedef unsigned short ReStateNumber;
4704 
4705 /* Because this is an NFA and not a DFA, multiple states can be active at
4706 ** once.  An instance of the following object records all active states in
4707 ** the NFA.  The implementation is optimized for the common case where the
4708 ** number of actives states is small.
4709 */
4710 typedef struct ReStateSet {
4711   unsigned nState;            /* Number of current states */
4712   ReStateNumber *aState;      /* Current states */
4713 } ReStateSet;
4714 
4715 /* An input string read one character at a time.
4716 */
4717 typedef struct ReInput ReInput;
4718 struct ReInput {
4719   const unsigned char *z;  /* All text */
4720   int i;                   /* Next byte to read */
4721   int mx;                  /* EOF when i>=mx */
4722 };
4723 
4724 /* A compiled NFA (or an NFA that is in the process of being compiled) is
4725 ** an instance of the following object.
4726 */
4727 typedef struct ReCompiled ReCompiled;
4728 struct ReCompiled {
4729   ReInput sIn;                /* Regular expression text */
4730   const char *zErr;           /* Error message to return */
4731   char *aOp;                  /* Operators for the virtual machine */
4732   int *aArg;                  /* Arguments to each operator */
4733   unsigned (*xNextChar)(ReInput*);  /* Next character function */
4734   unsigned char zInit[12];    /* Initial text to match */
4735   int nInit;                  /* Number of bytes in zInit */
4736   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
4737   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
4738 };
4739 
4740 /* Add a state to the given state set if it is not already there */
4741 static void re_add_state(ReStateSet *pSet, int newState){
4742   unsigned i;
4743   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
4744   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
4745 }
4746 
4747 /* Extract the next unicode character from *pzIn and return it.  Advance
4748 ** *pzIn to the first byte past the end of the character returned.  To
4749 ** be clear:  this routine converts utf8 to unicode.  This routine is
4750 ** optimized for the common case where the next character is a single byte.
4751 */
4752 static unsigned re_next_char(ReInput *p){
4753   unsigned c;
4754   if( p->i>=p->mx ) return 0;
4755   c = p->z[p->i++];
4756   if( c>=0x80 ){
4757     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
4758       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
4759       if( c<0x80 ) c = 0xfffd;
4760     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
4761            && (p->z[p->i+1]&0xc0)==0x80 ){
4762       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
4763       p->i += 2;
4764       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
4765     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
4766            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
4767       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
4768                        | (p->z[p->i+2]&0x3f);
4769       p->i += 3;
4770       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
4771     }else{
4772       c = 0xfffd;
4773     }
4774   }
4775   return c;
4776 }
4777 static unsigned re_next_char_nocase(ReInput *p){
4778   unsigned c = re_next_char(p);
4779   if( c>='A' && c<='Z' ) c += 'a' - 'A';
4780   return c;
4781 }
4782 
4783 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
4784 static int re_word_char(int c){
4785   return (c>='0' && c<='9') || (c>='a' && c<='z')
4786       || (c>='A' && c<='Z') || c=='_';
4787 }
4788 
4789 /* Return true if c is a "digit" character:  [0-9] */
4790 static int re_digit_char(int c){
4791   return (c>='0' && c<='9');
4792 }
4793 
4794 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
4795 static int re_space_char(int c){
4796   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
4797 }
4798 
4799 /* Run a compiled regular expression on the zero-terminated input
4800 ** string zIn[].  Return true on a match and false if there is no match.
4801 */
4802 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
4803   ReStateSet aStateSet[2], *pThis, *pNext;
4804   ReStateNumber aSpace[100];
4805   ReStateNumber *pToFree;
4806   unsigned int i = 0;
4807   unsigned int iSwap = 0;
4808   int c = RE_START;
4809   int cPrev = 0;
4810   int rc = 0;
4811   ReInput in;
4812 
4813   in.z = zIn;
4814   in.i = 0;
4815   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
4816 
4817   /* Look for the initial prefix match, if there is one. */
4818   if( pRe->nInit ){
4819     unsigned char x = pRe->zInit[0];
4820     while( in.i+pRe->nInit<=in.mx
4821      && (zIn[in.i]!=x ||
4822          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
4823     ){
4824       in.i++;
4825     }
4826     if( in.i+pRe->nInit>in.mx ) return 0;
4827     c = RE_START-1;
4828   }
4829 
4830   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
4831     pToFree = 0;
4832     aStateSet[0].aState = aSpace;
4833   }else{
4834     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
4835     if( pToFree==0 ) return -1;
4836     aStateSet[0].aState = pToFree;
4837   }
4838   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
4839   pNext = &aStateSet[1];
4840   pNext->nState = 0;
4841   re_add_state(pNext, 0);
4842   while( c!=RE_EOF && pNext->nState>0 ){
4843     cPrev = c;
4844     c = pRe->xNextChar(&in);
4845     pThis = pNext;
4846     pNext = &aStateSet[iSwap];
4847     iSwap = 1 - iSwap;
4848     pNext->nState = 0;
4849     for(i=0; i<pThis->nState; i++){
4850       int x = pThis->aState[i];
4851       switch( pRe->aOp[x] ){
4852         case RE_OP_MATCH: {
4853           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
4854           break;
4855         }
4856         case RE_OP_ATSTART: {
4857           if( cPrev==RE_START ) re_add_state(pThis, x+1);
4858           break;
4859         }
4860         case RE_OP_ANY: {
4861           if( c!=0 ) re_add_state(pNext, x+1);
4862           break;
4863         }
4864         case RE_OP_WORD: {
4865           if( re_word_char(c) ) re_add_state(pNext, x+1);
4866           break;
4867         }
4868         case RE_OP_NOTWORD: {
4869           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
4870           break;
4871         }
4872         case RE_OP_DIGIT: {
4873           if( re_digit_char(c) ) re_add_state(pNext, x+1);
4874           break;
4875         }
4876         case RE_OP_NOTDIGIT: {
4877           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
4878           break;
4879         }
4880         case RE_OP_SPACE: {
4881           if( re_space_char(c) ) re_add_state(pNext, x+1);
4882           break;
4883         }
4884         case RE_OP_NOTSPACE: {
4885           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
4886           break;
4887         }
4888         case RE_OP_BOUNDARY: {
4889           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
4890           break;
4891         }
4892         case RE_OP_ANYSTAR: {
4893           re_add_state(pNext, x);
4894           re_add_state(pThis, x+1);
4895           break;
4896         }
4897         case RE_OP_FORK: {
4898           re_add_state(pThis, x+pRe->aArg[x]);
4899           re_add_state(pThis, x+1);
4900           break;
4901         }
4902         case RE_OP_GOTO: {
4903           re_add_state(pThis, x+pRe->aArg[x]);
4904           break;
4905         }
4906         case RE_OP_ACCEPT: {
4907           rc = 1;
4908           goto re_match_end;
4909         }
4910         case RE_OP_CC_EXC: {
4911           if( c==0 ) break;
4912           /* fall-through */ goto re_op_cc_inc;
4913         }
4914         case RE_OP_CC_INC: re_op_cc_inc: {
4915           int j = 1;
4916           int n = pRe->aArg[x];
4917           int hit = 0;
4918           for(j=1; j>0 && j<n; j++){
4919             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
4920               if( pRe->aArg[x+j]==c ){
4921                 hit = 1;
4922                 j = -1;
4923               }
4924             }else{
4925               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
4926                 hit = 1;
4927                 j = -1;
4928               }else{
4929                 j++;
4930               }
4931             }
4932           }
4933           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
4934           if( hit ) re_add_state(pNext, x+n);
4935           break;
4936         }
4937       }
4938     }
4939   }
4940   for(i=0; i<pNext->nState; i++){
4941     int x = pNext->aState[i];
4942     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
4943     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
4944   }
4945 re_match_end:
4946   sqlite3_free(pToFree);
4947   return rc;
4948 }
4949 
4950 /* Resize the opcode and argument arrays for an RE under construction.
4951 */
4952 static int re_resize(ReCompiled *p, int N){
4953   char *aOp;
4954   int *aArg;
4955   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
4956   if( aOp==0 ) return 1;
4957   p->aOp = aOp;
4958   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
4959   if( aArg==0 ) return 1;
4960   p->aArg = aArg;
4961   p->nAlloc = N;
4962   return 0;
4963 }
4964 
4965 /* Insert a new opcode and argument into an RE under construction.  The
4966 ** insertion point is just prior to existing opcode iBefore.
4967 */
4968 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
4969   int i;
4970   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
4971   for(i=p->nState; i>iBefore; i--){
4972     p->aOp[i] = p->aOp[i-1];
4973     p->aArg[i] = p->aArg[i-1];
4974   }
4975   p->nState++;
4976   p->aOp[iBefore] = (char)op;
4977   p->aArg[iBefore] = arg;
4978   return iBefore;
4979 }
4980 
4981 /* Append a new opcode and argument to the end of the RE under construction.
4982 */
4983 static int re_append(ReCompiled *p, int op, int arg){
4984   return re_insert(p, p->nState, op, arg);
4985 }
4986 
4987 /* Make a copy of N opcodes starting at iStart onto the end of the RE
4988 ** under construction.
4989 */
4990 static void re_copy(ReCompiled *p, int iStart, int N){
4991   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
4992   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
4993   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
4994   p->nState += N;
4995 }
4996 
4997 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
4998 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
4999 ** c is not a hex digit *pV is unchanged.
5000 */
5001 static int re_hex(int c, int *pV){
5002   if( c>='0' && c<='9' ){
5003     c -= '0';
5004   }else if( c>='a' && c<='f' ){
5005     c -= 'a' - 10;
5006   }else if( c>='A' && c<='F' ){
5007     c -= 'A' - 10;
5008   }else{
5009     return 0;
5010   }
5011   *pV = (*pV)*16 + (c & 0xff);
5012   return 1;
5013 }
5014 
5015 /* A backslash character has been seen, read the next character and
5016 ** return its interpretation.
5017 */
5018 static unsigned re_esc_char(ReCompiled *p){
5019   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
5020   static const char zTrans[] = "\a\f\n\r\t\v";
5021   int i, v = 0;
5022   char c;
5023   if( p->sIn.i>=p->sIn.mx ) return 0;
5024   c = p->sIn.z[p->sIn.i];
5025   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
5026     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5027     if( re_hex(zIn[1],&v)
5028      && re_hex(zIn[2],&v)
5029      && re_hex(zIn[3],&v)
5030      && re_hex(zIn[4],&v)
5031     ){
5032       p->sIn.i += 5;
5033       return v;
5034     }
5035   }
5036   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
5037     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5038     if( re_hex(zIn[1],&v)
5039      && re_hex(zIn[2],&v)
5040     ){
5041       p->sIn.i += 3;
5042       return v;
5043     }
5044   }
5045   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
5046   if( zEsc[i] ){
5047     if( i<6 ) c = zTrans[i];
5048     p->sIn.i++;
5049   }else{
5050     p->zErr = "unknown \\ escape";
5051   }
5052   return c;
5053 }
5054 
5055 /* Forward declaration */
5056 static const char *re_subcompile_string(ReCompiled*);
5057 
5058 /* Peek at the next byte of input */
5059 static unsigned char rePeek(ReCompiled *p){
5060   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
5061 }
5062 
5063 /* Compile RE text into a sequence of opcodes.  Continue up to the
5064 ** first unmatched ")" character, then return.  If an error is found,
5065 ** return a pointer to the error message string.
5066 */
5067 static const char *re_subcompile_re(ReCompiled *p){
5068   const char *zErr;
5069   int iStart, iEnd, iGoto;
5070   iStart = p->nState;
5071   zErr = re_subcompile_string(p);
5072   if( zErr ) return zErr;
5073   while( rePeek(p)=='|' ){
5074     iEnd = p->nState;
5075     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
5076     iGoto = re_append(p, RE_OP_GOTO, 0);
5077     p->sIn.i++;
5078     zErr = re_subcompile_string(p);
5079     if( zErr ) return zErr;
5080     p->aArg[iGoto] = p->nState - iGoto;
5081   }
5082   return 0;
5083 }
5084 
5085 /* Compile an element of regular expression text (anything that can be
5086 ** an operand to the "|" operator).  Return NULL on success or a pointer
5087 ** to the error message if there is a problem.
5088 */
5089 static const char *re_subcompile_string(ReCompiled *p){
5090   int iPrev = -1;
5091   int iStart;
5092   unsigned c;
5093   const char *zErr;
5094   while( (c = p->xNextChar(&p->sIn))!=0 ){
5095     iStart = p->nState;
5096     switch( c ){
5097       case '|':
5098       case ')': {
5099         p->sIn.i--;
5100         return 0;
5101       }
5102       case '(': {
5103         zErr = re_subcompile_re(p);
5104         if( zErr ) return zErr;
5105         if( rePeek(p)!=')' ) return "unmatched '('";
5106         p->sIn.i++;
5107         break;
5108       }
5109       case '.': {
5110         if( rePeek(p)=='*' ){
5111           re_append(p, RE_OP_ANYSTAR, 0);
5112           p->sIn.i++;
5113         }else{
5114           re_append(p, RE_OP_ANY, 0);
5115         }
5116         break;
5117       }
5118       case '*': {
5119         if( iPrev<0 ) return "'*' without operand";
5120         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
5121         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
5122         break;
5123       }
5124       case '+': {
5125         if( iPrev<0 ) return "'+' without operand";
5126         re_append(p, RE_OP_FORK, iPrev - p->nState);
5127         break;
5128       }
5129       case '?': {
5130         if( iPrev<0 ) return "'?' without operand";
5131         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
5132         break;
5133       }
5134       case '$': {
5135         re_append(p, RE_OP_MATCH, RE_EOF);
5136         break;
5137       }
5138       case '^': {
5139         re_append(p, RE_OP_ATSTART, 0);
5140         break;
5141       }
5142       case '{': {
5143         int m = 0, n = 0;
5144         int sz, j;
5145         if( iPrev<0 ) return "'{m,n}' without operand";
5146         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
5147         n = m;
5148         if( c==',' ){
5149           p->sIn.i++;
5150           n = 0;
5151           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
5152         }
5153         if( c!='}' ) return "unmatched '{'";
5154         if( n>0 && n<m ) return "n less than m in '{m,n}'";
5155         p->sIn.i++;
5156         sz = p->nState - iPrev;
5157         if( m==0 ){
5158           if( n==0 ) return "both m and n are zero in '{m,n}'";
5159           re_insert(p, iPrev, RE_OP_FORK, sz+1);
5160           iPrev++;
5161           n--;
5162         }else{
5163           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
5164         }
5165         for(j=m; j<n; j++){
5166           re_append(p, RE_OP_FORK, sz+1);
5167           re_copy(p, iPrev, sz);
5168         }
5169         if( n==0 && m>0 ){
5170           re_append(p, RE_OP_FORK, -sz);
5171         }
5172         break;
5173       }
5174       case '[': {
5175         int iFirst = p->nState;
5176         if( rePeek(p)=='^' ){
5177           re_append(p, RE_OP_CC_EXC, 0);
5178           p->sIn.i++;
5179         }else{
5180           re_append(p, RE_OP_CC_INC, 0);
5181         }
5182         while( (c = p->xNextChar(&p->sIn))!=0 ){
5183           if( c=='[' && rePeek(p)==':' ){
5184             return "POSIX character classes not supported";
5185           }
5186           if( c=='\\' ) c = re_esc_char(p);
5187           if( rePeek(p)=='-' ){
5188             re_append(p, RE_OP_CC_RANGE, c);
5189             p->sIn.i++;
5190             c = p->xNextChar(&p->sIn);
5191             if( c=='\\' ) c = re_esc_char(p);
5192             re_append(p, RE_OP_CC_RANGE, c);
5193           }else{
5194             re_append(p, RE_OP_CC_VALUE, c);
5195           }
5196           if( rePeek(p)==']' ){ p->sIn.i++; break; }
5197         }
5198         if( c==0 ) return "unclosed '['";
5199         p->aArg[iFirst] = p->nState - iFirst;
5200         break;
5201       }
5202       case '\\': {
5203         int specialOp = 0;
5204         switch( rePeek(p) ){
5205           case 'b': specialOp = RE_OP_BOUNDARY;   break;
5206           case 'd': specialOp = RE_OP_DIGIT;      break;
5207           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
5208           case 's': specialOp = RE_OP_SPACE;      break;
5209           case 'S': specialOp = RE_OP_NOTSPACE;   break;
5210           case 'w': specialOp = RE_OP_WORD;       break;
5211           case 'W': specialOp = RE_OP_NOTWORD;    break;
5212         }
5213         if( specialOp ){
5214           p->sIn.i++;
5215           re_append(p, specialOp, 0);
5216         }else{
5217           c = re_esc_char(p);
5218           re_append(p, RE_OP_MATCH, c);
5219         }
5220         break;
5221       }
5222       default: {
5223         re_append(p, RE_OP_MATCH, c);
5224         break;
5225       }
5226     }
5227     iPrev = iStart;
5228   }
5229   return 0;
5230 }
5231 
5232 /* Free and reclaim all the memory used by a previously compiled
5233 ** regular expression.  Applications should invoke this routine once
5234 ** for every call to re_compile() to avoid memory leaks.
5235 */
5236 static void re_free(ReCompiled *pRe){
5237   if( pRe ){
5238     sqlite3_free(pRe->aOp);
5239     sqlite3_free(pRe->aArg);
5240     sqlite3_free(pRe);
5241   }
5242 }
5243 
5244 /*
5245 ** Compile a textual regular expression in zIn[] into a compiled regular
5246 ** expression suitable for us by re_match() and return a pointer to the
5247 ** compiled regular expression in *ppRe.  Return NULL on success or an
5248 ** error message if something goes wrong.
5249 */
5250 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
5251   ReCompiled *pRe;
5252   const char *zErr;
5253   int i, j;
5254 
5255   *ppRe = 0;
5256   pRe = sqlite3_malloc( sizeof(*pRe) );
5257   if( pRe==0 ){
5258     return "out of memory";
5259   }
5260   memset(pRe, 0, sizeof(*pRe));
5261   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
5262   if( re_resize(pRe, 30) ){
5263     re_free(pRe);
5264     return "out of memory";
5265   }
5266   if( zIn[0]=='^' ){
5267     zIn++;
5268   }else{
5269     re_append(pRe, RE_OP_ANYSTAR, 0);
5270   }
5271   pRe->sIn.z = (unsigned char*)zIn;
5272   pRe->sIn.i = 0;
5273   pRe->sIn.mx = (int)strlen(zIn);
5274   zErr = re_subcompile_re(pRe);
5275   if( zErr ){
5276     re_free(pRe);
5277     return zErr;
5278   }
5279   if( pRe->sIn.i>=pRe->sIn.mx ){
5280     re_append(pRe, RE_OP_ACCEPT, 0);
5281     *ppRe = pRe;
5282   }else{
5283     re_free(pRe);
5284     return "unrecognized character";
5285   }
5286 
5287   /* The following is a performance optimization.  If the regex begins with
5288   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
5289   ** one or more matching characters, enter those matching characters into
5290   ** zInit[].  The re_match() routine can then search ahead in the input
5291   ** string looking for the initial match without having to run the whole
5292   ** regex engine over the string.  Do not worry about trying to match
5293   ** unicode characters beyond plane 0 - those are very rare and this is
5294   ** just an optimization. */
5295   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
5296     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
5297       unsigned x = pRe->aArg[i];
5298       if( x<=0x7f ){
5299         pRe->zInit[j++] = (unsigned char)x;
5300       }else if( x<=0x7ff ){
5301         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
5302         pRe->zInit[j++] = 0x80 | (x&0x3f);
5303       }else if( x<=0xffff ){
5304         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
5305         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
5306         pRe->zInit[j++] = 0x80 | (x&0x3f);
5307       }else{
5308         break;
5309       }
5310     }
5311     if( j>0 && pRe->zInit[j-1]==0 ) j--;
5312     pRe->nInit = j;
5313   }
5314   return pRe->zErr;
5315 }
5316 
5317 /*
5318 ** Implementation of the regexp() SQL function.  This function implements
5319 ** the build-in REGEXP operator.  The first argument to the function is the
5320 ** pattern and the second argument is the string.  So, the SQL statements:
5321 **
5322 **       A REGEXP B
5323 **
5324 ** is implemented as regexp(B,A).
5325 */
5326 static void re_sql_func(
5327   sqlite3_context *context,
5328   int argc,
5329   sqlite3_value **argv
5330 ){
5331   ReCompiled *pRe;          /* Compiled regular expression */
5332   const char *zPattern;     /* The regular expression */
5333   const unsigned char *zStr;/* String being searched */
5334   const char *zErr;         /* Compile error message */
5335   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
5336 
5337   (void)argc;  /* Unused */
5338   pRe = sqlite3_get_auxdata(context, 0);
5339   if( pRe==0 ){
5340     zPattern = (const char*)sqlite3_value_text(argv[0]);
5341     if( zPattern==0 ) return;
5342     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
5343     if( zErr ){
5344       re_free(pRe);
5345       sqlite3_result_error(context, zErr, -1);
5346       return;
5347     }
5348     if( pRe==0 ){
5349       sqlite3_result_error_nomem(context);
5350       return;
5351     }
5352     setAux = 1;
5353   }
5354   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
5355   if( zStr!=0 ){
5356     sqlite3_result_int(context, re_match(pRe, zStr, -1));
5357   }
5358   if( setAux ){
5359     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
5360   }
5361 }
5362 
5363 #if defined(SQLITE_DEBUG)
5364 /*
5365 ** This function is used for testing and debugging only.  It is only available
5366 ** if the SQLITE_DEBUG compile-time option is used.
5367 **
5368 ** Compile a regular expression and then convert the compiled expression into
5369 ** text and return that text.
5370 */
5371 static void re_bytecode_func(
5372   sqlite3_context *context,
5373   int argc,
5374   sqlite3_value **argv
5375 ){
5376   const char *zPattern;
5377   const char *zErr;
5378   ReCompiled *pRe;
5379   sqlite3_str *pStr;
5380   int i;
5381   int n;
5382   char *z;
5383   (void)argc;
5384 
5385   zPattern = (const char*)sqlite3_value_text(argv[0]);
5386   if( zPattern==0 ) return;
5387   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
5388   if( zErr ){
5389     re_free(pRe);
5390     sqlite3_result_error(context, zErr, -1);
5391     return;
5392   }
5393   if( pRe==0 ){
5394     sqlite3_result_error_nomem(context);
5395     return;
5396   }
5397   pStr = sqlite3_str_new(0);
5398   if( pStr==0 ) goto re_bytecode_func_err;
5399   if( pRe->nInit>0 ){
5400     sqlite3_str_appendf(pStr, "INIT     ");
5401     for(i=0; i<pRe->nInit; i++){
5402       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
5403     }
5404     sqlite3_str_appendf(pStr, "\n");
5405   }
5406   for(i=0; (unsigned)i<pRe->nState; i++){
5407     sqlite3_str_appendf(pStr, "%-8s %4d\n",
5408          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
5409   }
5410   n = sqlite3_str_length(pStr);
5411   z = sqlite3_str_finish(pStr);
5412   if( n==0 ){
5413     sqlite3_free(z);
5414   }else{
5415     sqlite3_result_text(context, z, n-1, sqlite3_free);
5416   }
5417 
5418 re_bytecode_func_err:
5419   re_free(pRe);
5420 }
5421 
5422 #endif /* SQLITE_DEBUG */
5423 
5424 
5425 /*
5426 ** Invoke this routine to register the regexp() function with the
5427 ** SQLite database connection.
5428 */
5429 #ifdef _WIN32
5430 
5431 #endif
5432 int sqlite3_regexp_init(
5433   sqlite3 *db,
5434   char **pzErrMsg,
5435   const sqlite3_api_routines *pApi
5436 ){
5437   int rc = SQLITE_OK;
5438   SQLITE_EXTENSION_INIT2(pApi);
5439   (void)pzErrMsg;  /* Unused */
5440   rc = sqlite3_create_function(db, "regexp", 2,
5441                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5442                             0, re_sql_func, 0, 0);
5443   if( rc==SQLITE_OK ){
5444     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
5445     ** of regexp(PATTERN,STRING). */
5446     rc = sqlite3_create_function(db, "regexpi", 2,
5447                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5448                             (void*)db, re_sql_func, 0, 0);
5449 #if defined(SQLITE_DEBUG)
5450     if( rc==SQLITE_OK ){
5451       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
5452                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5453                             0, re_bytecode_func, 0, 0);
5454     }
5455 #endif /* SQLITE_DEBUG */
5456   }
5457   return rc;
5458 }
5459 
5460 /************************* End ../ext/misc/regexp.c ********************/
5461 #ifndef SQLITE_SHELL_FIDDLE
5462 /************************* Begin ../ext/misc/fileio.c ******************/
5463 /*
5464 ** 2014-06-13
5465 **
5466 ** The author disclaims copyright to this source code.  In place of
5467 ** a legal notice, here is a blessing:
5468 **
5469 **    May you do good and not evil.
5470 **    May you find forgiveness for yourself and forgive others.
5471 **    May you share freely, never taking more than you give.
5472 **
5473 ******************************************************************************
5474 **
5475 ** This SQLite extension implements SQL functions readfile() and
5476 ** writefile(), and eponymous virtual type "fsdir".
5477 **
5478 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
5479 **
5480 **   If neither of the optional arguments is present, then this UDF
5481 **   function writes blob DATA to file FILE. If successful, the number
5482 **   of bytes written is returned. If an error occurs, NULL is returned.
5483 **
5484 **   If the first option argument - MODE - is present, then it must
5485 **   be passed an integer value that corresponds to a POSIX mode
5486 **   value (file type + permissions, as returned in the stat.st_mode
5487 **   field by the stat() system call). Three types of files may
5488 **   be written/created:
5489 **
5490 **     regular files:  (mode & 0170000)==0100000
5491 **     symbolic links: (mode & 0170000)==0120000
5492 **     directories:    (mode & 0170000)==0040000
5493 **
5494 **   For a directory, the DATA is ignored. For a symbolic link, it is
5495 **   interpreted as text and used as the target of the link. For a
5496 **   regular file, it is interpreted as a blob and written into the
5497 **   named file. Regardless of the type of file, its permissions are
5498 **   set to (mode & 0777) before returning.
5499 **
5500 **   If the optional MTIME argument is present, then it is interpreted
5501 **   as an integer - the number of seconds since the unix epoch. The
5502 **   modification-time of the target file is set to this value before
5503 **   returning.
5504 **
5505 **   If three or more arguments are passed to this function and an
5506 **   error is encountered, an exception is raised.
5507 **
5508 ** READFILE(FILE):
5509 **
5510 **   Read and return the contents of file FILE (type blob) from disk.
5511 **
5512 ** FSDIR:
5513 **
5514 **   Used as follows:
5515 **
5516 **     SELECT * FROM fsdir($path [, $dir]);
5517 **
5518 **   Parameter $path is an absolute or relative pathname. If the file that it
5519 **   refers to does not exist, it is an error. If the path refers to a regular
5520 **   file or symbolic link, it returns a single row. Or, if the path refers
5521 **   to a directory, it returns one row for the directory, and one row for each
5522 **   file within the hierarchy rooted at $path.
5523 **
5524 **   Each row has the following columns:
5525 **
5526 **     name:  Path to file or directory (text value).
5527 **     mode:  Value of stat.st_mode for directory entry (an integer).
5528 **     mtime: Value of stat.st_mtime for directory entry (an integer).
5529 **     data:  For a regular file, a blob containing the file data. For a
5530 **            symlink, a text value containing the text of the link. For a
5531 **            directory, NULL.
5532 **
5533 **   If a non-NULL value is specified for the optional $dir parameter and
5534 **   $path is a relative path, then $path is interpreted relative to $dir.
5535 **   And the paths returned in the "name" column of the table are also
5536 **   relative to directory $dir.
5537 **
5538 ** Notes on building this extension for Windows:
5539 **   Unless linked statically with the SQLite library, a preprocessor
5540 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
5541 **   DLL form of this extension for WIN32. See its use below for details.
5542 */
5543 /* #include "sqlite3ext.h" */
5544 SQLITE_EXTENSION_INIT1
5545 #include <stdio.h>
5546 #include <string.h>
5547 #include <assert.h>
5548 
5549 #include <sys/types.h>
5550 #include <sys/stat.h>
5551 #include <fcntl.h>
5552 #if !defined(_WIN32) && !defined(WIN32)
5553 #  include <unistd.h>
5554 #  include <dirent.h>
5555 #  include <utime.h>
5556 #  include <sys/time.h>
5557 #else
5558 #  include "windows.h"
5559 #  include <io.h>
5560 #  include <direct.h>
5561 /* #  include "test_windirent.h" */
5562 #  define dirent DIRENT
5563 #  ifndef chmod
5564 #    define chmod _chmod
5565 #  endif
5566 #  ifndef stat
5567 #    define stat _stat
5568 #  endif
5569 #  define mkdir(path,mode) _mkdir(path)
5570 #  define lstat(path,buf) stat(path,buf)
5571 #endif
5572 #include <time.h>
5573 #include <errno.h>
5574 
5575 
5576 /*
5577 ** Structure of the fsdir() table-valued function
5578 */
5579                  /*    0    1    2     3    4           5             */
5580 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
5581 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
5582 #define FSDIR_COLUMN_MODE     1     /* Access mode */
5583 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
5584 #define FSDIR_COLUMN_DATA     3     /* File content */
5585 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
5586 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
5587 
5588 
5589 /*
5590 ** Set the result stored by context ctx to a blob containing the
5591 ** contents of file zName.  Or, leave the result unchanged (NULL)
5592 ** if the file does not exist or is unreadable.
5593 **
5594 ** If the file exceeds the SQLite blob size limit, through an
5595 ** SQLITE_TOOBIG error.
5596 **
5597 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
5598 ** off of disk.
5599 */
5600 static void readFileContents(sqlite3_context *ctx, const char *zName){
5601   FILE *in;
5602   sqlite3_int64 nIn;
5603   void *pBuf;
5604   sqlite3 *db;
5605   int mxBlob;
5606 
5607   in = fopen(zName, "rb");
5608   if( in==0 ){
5609     /* File does not exist or is unreadable. Leave the result set to NULL. */
5610     return;
5611   }
5612   fseek(in, 0, SEEK_END);
5613   nIn = ftell(in);
5614   rewind(in);
5615   db = sqlite3_context_db_handle(ctx);
5616   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
5617   if( nIn>mxBlob ){
5618     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
5619     fclose(in);
5620     return;
5621   }
5622   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
5623   if( pBuf==0 ){
5624     sqlite3_result_error_nomem(ctx);
5625     fclose(in);
5626     return;
5627   }
5628   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
5629     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
5630   }else{
5631     sqlite3_result_error_code(ctx, SQLITE_IOERR);
5632     sqlite3_free(pBuf);
5633   }
5634   fclose(in);
5635 }
5636 
5637 /*
5638 ** Implementation of the "readfile(X)" SQL function.  The entire content
5639 ** of the file named X is read and returned as a BLOB.  NULL is returned
5640 ** if the file does not exist or is unreadable.
5641 */
5642 static void readfileFunc(
5643   sqlite3_context *context,
5644   int argc,
5645   sqlite3_value **argv
5646 ){
5647   const char *zName;
5648   (void)(argc);  /* Unused parameter */
5649   zName = (const char*)sqlite3_value_text(argv[0]);
5650   if( zName==0 ) return;
5651   readFileContents(context, zName);
5652 }
5653 
5654 /*
5655 ** Set the error message contained in context ctx to the results of
5656 ** vprintf(zFmt, ...).
5657 */
5658 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
5659   char *zMsg = 0;
5660   va_list ap;
5661   va_start(ap, zFmt);
5662   zMsg = sqlite3_vmprintf(zFmt, ap);
5663   sqlite3_result_error(ctx, zMsg, -1);
5664   sqlite3_free(zMsg);
5665   va_end(ap);
5666 }
5667 
5668 #if defined(_WIN32)
5669 /*
5670 ** This function is designed to convert a Win32 FILETIME structure into the
5671 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
5672 */
5673 static sqlite3_uint64 fileTimeToUnixTime(
5674   LPFILETIME pFileTime
5675 ){
5676   SYSTEMTIME epochSystemTime;
5677   ULARGE_INTEGER epochIntervals;
5678   FILETIME epochFileTime;
5679   ULARGE_INTEGER fileIntervals;
5680 
5681   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
5682   epochSystemTime.wYear = 1970;
5683   epochSystemTime.wMonth = 1;
5684   epochSystemTime.wDay = 1;
5685   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
5686   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
5687   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
5688 
5689   fileIntervals.LowPart = pFileTime->dwLowDateTime;
5690   fileIntervals.HighPart = pFileTime->dwHighDateTime;
5691 
5692   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
5693 }
5694 
5695 
5696 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
5697 #  /* To allow a standalone DLL, use this next replacement function: */
5698 #  undef sqlite3_win32_utf8_to_unicode
5699 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
5700 #
5701 LPWSTR utf8_to_utf16(const char *z){
5702   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
5703   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
5704   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
5705     return rv;
5706   sqlite3_free(rv);
5707   return 0;
5708 }
5709 #endif
5710 
5711 /*
5712 ** This function attempts to normalize the time values found in the stat()
5713 ** buffer to UTC.  This is necessary on Win32, where the runtime library
5714 ** appears to return these values as local times.
5715 */
5716 static void statTimesToUtc(
5717   const char *zPath,
5718   struct stat *pStatBuf
5719 ){
5720   HANDLE hFindFile;
5721   WIN32_FIND_DATAW fd;
5722   LPWSTR zUnicodeName;
5723   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
5724   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
5725   if( zUnicodeName ){
5726     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
5727     hFindFile = FindFirstFileW(zUnicodeName, &fd);
5728     if( hFindFile!=NULL ){
5729       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
5730       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
5731       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
5732       FindClose(hFindFile);
5733     }
5734     sqlite3_free(zUnicodeName);
5735   }
5736 }
5737 #endif
5738 
5739 /*
5740 ** This function is used in place of stat().  On Windows, special handling
5741 ** is required in order for the included time to be returned as UTC.  On all
5742 ** other systems, this function simply calls stat().
5743 */
5744 static int fileStat(
5745   const char *zPath,
5746   struct stat *pStatBuf
5747 ){
5748 #if defined(_WIN32)
5749   int rc = stat(zPath, pStatBuf);
5750   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
5751   return rc;
5752 #else
5753   return stat(zPath, pStatBuf);
5754 #endif
5755 }
5756 
5757 /*
5758 ** This function is used in place of lstat().  On Windows, special handling
5759 ** is required in order for the included time to be returned as UTC.  On all
5760 ** other systems, this function simply calls lstat().
5761 */
5762 static int fileLinkStat(
5763   const char *zPath,
5764   struct stat *pStatBuf
5765 ){
5766 #if defined(_WIN32)
5767   int rc = lstat(zPath, pStatBuf);
5768   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
5769   return rc;
5770 #else
5771   return lstat(zPath, pStatBuf);
5772 #endif
5773 }
5774 
5775 /*
5776 ** Argument zFile is the name of a file that will be created and/or written
5777 ** by SQL function writefile(). This function ensures that the directory
5778 ** zFile will be written to exists, creating it if required. The permissions
5779 ** for any path components created by this function are set in accordance
5780 ** with the current umask.
5781 **
5782 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
5783 ** SQLITE_OK is returned if the directory is successfully created, or
5784 ** SQLITE_ERROR otherwise.
5785 */
5786 static int makeDirectory(
5787   const char *zFile
5788 ){
5789   char *zCopy = sqlite3_mprintf("%s", zFile);
5790   int rc = SQLITE_OK;
5791 
5792   if( zCopy==0 ){
5793     rc = SQLITE_NOMEM;
5794   }else{
5795     int nCopy = (int)strlen(zCopy);
5796     int i = 1;
5797 
5798     while( rc==SQLITE_OK ){
5799       struct stat sStat;
5800       int rc2;
5801 
5802       for(; zCopy[i]!='/' && i<nCopy; i++);
5803       if( i==nCopy ) break;
5804       zCopy[i] = '\0';
5805 
5806       rc2 = fileStat(zCopy, &sStat);
5807       if( rc2!=0 ){
5808         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
5809       }else{
5810         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
5811       }
5812       zCopy[i] = '/';
5813       i++;
5814     }
5815 
5816     sqlite3_free(zCopy);
5817   }
5818 
5819   return rc;
5820 }
5821 
5822 /*
5823 ** This function does the work for the writefile() UDF. Refer to
5824 ** header comments at the top of this file for details.
5825 */
5826 static int writeFile(
5827   sqlite3_context *pCtx,          /* Context to return bytes written in */
5828   const char *zFile,              /* File to write */
5829   sqlite3_value *pData,           /* Data to write */
5830   mode_t mode,                    /* MODE parameter passed to writefile() */
5831   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
5832 ){
5833   if( zFile==0 ) return 1;
5834 #if !defined(_WIN32) && !defined(WIN32)
5835   if( S_ISLNK(mode) ){
5836     const char *zTo = (const char*)sqlite3_value_text(pData);
5837     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
5838   }else
5839 #endif
5840   {
5841     if( S_ISDIR(mode) ){
5842       if( mkdir(zFile, mode) ){
5843         /* The mkdir() call to create the directory failed. This might not
5844         ** be an error though - if there is already a directory at the same
5845         ** path and either the permissions already match or can be changed
5846         ** to do so using chmod(), it is not an error.  */
5847         struct stat sStat;
5848         if( errno!=EEXIST
5849          || 0!=fileStat(zFile, &sStat)
5850          || !S_ISDIR(sStat.st_mode)
5851          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
5852         ){
5853           return 1;
5854         }
5855       }
5856     }else{
5857       sqlite3_int64 nWrite = 0;
5858       const char *z;
5859       int rc = 0;
5860       FILE *out = fopen(zFile, "wb");
5861       if( out==0 ) return 1;
5862       z = (const char*)sqlite3_value_blob(pData);
5863       if( z ){
5864         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
5865         nWrite = sqlite3_value_bytes(pData);
5866         if( nWrite!=n ){
5867           rc = 1;
5868         }
5869       }
5870       fclose(out);
5871       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
5872         rc = 1;
5873       }
5874       if( rc ) return 2;
5875       sqlite3_result_int64(pCtx, nWrite);
5876     }
5877   }
5878 
5879   if( mtime>=0 ){
5880 #if defined(_WIN32)
5881 #if !SQLITE_OS_WINRT
5882     /* Windows */
5883     FILETIME lastAccess;
5884     FILETIME lastWrite;
5885     SYSTEMTIME currentTime;
5886     LONGLONG intervals;
5887     HANDLE hFile;
5888     LPWSTR zUnicodeName;
5889     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
5890 
5891     GetSystemTime(&currentTime);
5892     SystemTimeToFileTime(&currentTime, &lastAccess);
5893     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
5894     lastWrite.dwLowDateTime = (DWORD)intervals;
5895     lastWrite.dwHighDateTime = intervals >> 32;
5896     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
5897     if( zUnicodeName==0 ){
5898       return 1;
5899     }
5900     hFile = CreateFileW(
5901       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
5902       FILE_FLAG_BACKUP_SEMANTICS, NULL
5903     );
5904     sqlite3_free(zUnicodeName);
5905     if( hFile!=INVALID_HANDLE_VALUE ){
5906       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
5907       CloseHandle(hFile);
5908       return !bResult;
5909     }else{
5910       return 1;
5911     }
5912 #endif
5913 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
5914     /* Recent unix */
5915     struct timespec times[2];
5916     times[0].tv_nsec = times[1].tv_nsec = 0;
5917     times[0].tv_sec = time(0);
5918     times[1].tv_sec = mtime;
5919     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
5920       return 1;
5921     }
5922 #else
5923     /* Legacy unix */
5924     struct timeval times[2];
5925     times[0].tv_usec = times[1].tv_usec = 0;
5926     times[0].tv_sec = time(0);
5927     times[1].tv_sec = mtime;
5928     if( utimes(zFile, times) ){
5929       return 1;
5930     }
5931 #endif
5932   }
5933 
5934   return 0;
5935 }
5936 
5937 /*
5938 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
5939 ** Refer to header comments at the top of this file for details.
5940 */
5941 static void writefileFunc(
5942   sqlite3_context *context,
5943   int argc,
5944   sqlite3_value **argv
5945 ){
5946   const char *zFile;
5947   mode_t mode = 0;
5948   int res;
5949   sqlite3_int64 mtime = -1;
5950 
5951   if( argc<2 || argc>4 ){
5952     sqlite3_result_error(context,
5953         "wrong number of arguments to function writefile()", -1
5954     );
5955     return;
5956   }
5957 
5958   zFile = (const char*)sqlite3_value_text(argv[0]);
5959   if( zFile==0 ) return;
5960   if( argc>=3 ){
5961     mode = (mode_t)sqlite3_value_int(argv[2]);
5962   }
5963   if( argc==4 ){
5964     mtime = sqlite3_value_int64(argv[3]);
5965   }
5966 
5967   res = writeFile(context, zFile, argv[1], mode, mtime);
5968   if( res==1 && errno==ENOENT ){
5969     if( makeDirectory(zFile)==SQLITE_OK ){
5970       res = writeFile(context, zFile, argv[1], mode, mtime);
5971     }
5972   }
5973 
5974   if( argc>2 && res!=0 ){
5975     if( S_ISLNK(mode) ){
5976       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
5977     }else if( S_ISDIR(mode) ){
5978       ctxErrorMsg(context, "failed to create directory: %s", zFile);
5979     }else{
5980       ctxErrorMsg(context, "failed to write file: %s", zFile);
5981     }
5982   }
5983 }
5984 
5985 /*
5986 ** SQL function:   lsmode(MODE)
5987 **
5988 ** Given a numberic st_mode from stat(), convert it into a human-readable
5989 ** text string in the style of "ls -l".
5990 */
5991 static void lsModeFunc(
5992   sqlite3_context *context,
5993   int argc,
5994   sqlite3_value **argv
5995 ){
5996   int i;
5997   int iMode = sqlite3_value_int(argv[0]);
5998   char z[16];
5999   (void)argc;
6000   if( S_ISLNK(iMode) ){
6001     z[0] = 'l';
6002   }else if( S_ISREG(iMode) ){
6003     z[0] = '-';
6004   }else if( S_ISDIR(iMode) ){
6005     z[0] = 'd';
6006   }else{
6007     z[0] = '?';
6008   }
6009   for(i=0; i<3; i++){
6010     int m = (iMode >> ((2-i)*3));
6011     char *a = &z[1 + i*3];
6012     a[0] = (m & 0x4) ? 'r' : '-';
6013     a[1] = (m & 0x2) ? 'w' : '-';
6014     a[2] = (m & 0x1) ? 'x' : '-';
6015   }
6016   z[10] = '\0';
6017   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
6018 }
6019 
6020 #ifndef SQLITE_OMIT_VIRTUALTABLE
6021 
6022 /*
6023 ** Cursor type for recursively iterating through a directory structure.
6024 */
6025 typedef struct fsdir_cursor fsdir_cursor;
6026 typedef struct FsdirLevel FsdirLevel;
6027 
6028 struct FsdirLevel {
6029   DIR *pDir;                 /* From opendir() */
6030   char *zDir;                /* Name of directory (nul-terminated) */
6031 };
6032 
6033 struct fsdir_cursor {
6034   sqlite3_vtab_cursor base;  /* Base class - must be first */
6035 
6036   int nLvl;                  /* Number of entries in aLvl[] array */
6037   int iLvl;                  /* Index of current entry */
6038   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
6039 
6040   const char *zBase;
6041   int nBase;
6042 
6043   struct stat sStat;         /* Current lstat() results */
6044   char *zPath;               /* Path to current entry */
6045   sqlite3_int64 iRowid;      /* Current rowid */
6046 };
6047 
6048 typedef struct fsdir_tab fsdir_tab;
6049 struct fsdir_tab {
6050   sqlite3_vtab base;         /* Base class - must be first */
6051 };
6052 
6053 /*
6054 ** Construct a new fsdir virtual table object.
6055 */
6056 static int fsdirConnect(
6057   sqlite3 *db,
6058   void *pAux,
6059   int argc, const char *const*argv,
6060   sqlite3_vtab **ppVtab,
6061   char **pzErr
6062 ){
6063   fsdir_tab *pNew = 0;
6064   int rc;
6065   (void)pAux;
6066   (void)argc;
6067   (void)argv;
6068   (void)pzErr;
6069   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
6070   if( rc==SQLITE_OK ){
6071     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
6072     if( pNew==0 ) return SQLITE_NOMEM;
6073     memset(pNew, 0, sizeof(*pNew));
6074     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
6075   }
6076   *ppVtab = (sqlite3_vtab*)pNew;
6077   return rc;
6078 }
6079 
6080 /*
6081 ** This method is the destructor for fsdir vtab objects.
6082 */
6083 static int fsdirDisconnect(sqlite3_vtab *pVtab){
6084   sqlite3_free(pVtab);
6085   return SQLITE_OK;
6086 }
6087 
6088 /*
6089 ** Constructor for a new fsdir_cursor object.
6090 */
6091 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6092   fsdir_cursor *pCur;
6093   (void)p;
6094   pCur = sqlite3_malloc( sizeof(*pCur) );
6095   if( pCur==0 ) return SQLITE_NOMEM;
6096   memset(pCur, 0, sizeof(*pCur));
6097   pCur->iLvl = -1;
6098   *ppCursor = &pCur->base;
6099   return SQLITE_OK;
6100 }
6101 
6102 /*
6103 ** Reset a cursor back to the state it was in when first returned
6104 ** by fsdirOpen().
6105 */
6106 static void fsdirResetCursor(fsdir_cursor *pCur){
6107   int i;
6108   for(i=0; i<=pCur->iLvl; i++){
6109     FsdirLevel *pLvl = &pCur->aLvl[i];
6110     if( pLvl->pDir ) closedir(pLvl->pDir);
6111     sqlite3_free(pLvl->zDir);
6112   }
6113   sqlite3_free(pCur->zPath);
6114   sqlite3_free(pCur->aLvl);
6115   pCur->aLvl = 0;
6116   pCur->zPath = 0;
6117   pCur->zBase = 0;
6118   pCur->nBase = 0;
6119   pCur->nLvl = 0;
6120   pCur->iLvl = -1;
6121   pCur->iRowid = 1;
6122 }
6123 
6124 /*
6125 ** Destructor for an fsdir_cursor.
6126 */
6127 static int fsdirClose(sqlite3_vtab_cursor *cur){
6128   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6129 
6130   fsdirResetCursor(pCur);
6131   sqlite3_free(pCur);
6132   return SQLITE_OK;
6133 }
6134 
6135 /*
6136 ** Set the error message for the virtual table associated with cursor
6137 ** pCur to the results of vprintf(zFmt, ...).
6138 */
6139 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
6140   va_list ap;
6141   va_start(ap, zFmt);
6142   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
6143   va_end(ap);
6144 }
6145 
6146 
6147 /*
6148 ** Advance an fsdir_cursor to its next row of output.
6149 */
6150 static int fsdirNext(sqlite3_vtab_cursor *cur){
6151   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6152   mode_t m = pCur->sStat.st_mode;
6153 
6154   pCur->iRowid++;
6155   if( S_ISDIR(m) ){
6156     /* Descend into this directory */
6157     int iNew = pCur->iLvl + 1;
6158     FsdirLevel *pLvl;
6159     if( iNew>=pCur->nLvl ){
6160       int nNew = iNew+1;
6161       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
6162       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
6163       if( aNew==0 ) return SQLITE_NOMEM;
6164       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
6165       pCur->aLvl = aNew;
6166       pCur->nLvl = nNew;
6167     }
6168     pCur->iLvl = iNew;
6169     pLvl = &pCur->aLvl[iNew];
6170 
6171     pLvl->zDir = pCur->zPath;
6172     pCur->zPath = 0;
6173     pLvl->pDir = opendir(pLvl->zDir);
6174     if( pLvl->pDir==0 ){
6175       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
6176       return SQLITE_ERROR;
6177     }
6178   }
6179 
6180   while( pCur->iLvl>=0 ){
6181     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
6182     struct dirent *pEntry = readdir(pLvl->pDir);
6183     if( pEntry ){
6184       if( pEntry->d_name[0]=='.' ){
6185        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
6186        if( pEntry->d_name[1]=='\0' ) continue;
6187       }
6188       sqlite3_free(pCur->zPath);
6189       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
6190       if( pCur->zPath==0 ) return SQLITE_NOMEM;
6191       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
6192         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
6193         return SQLITE_ERROR;
6194       }
6195       return SQLITE_OK;
6196     }
6197     closedir(pLvl->pDir);
6198     sqlite3_free(pLvl->zDir);
6199     pLvl->pDir = 0;
6200     pLvl->zDir = 0;
6201     pCur->iLvl--;
6202   }
6203 
6204   /* EOF */
6205   sqlite3_free(pCur->zPath);
6206   pCur->zPath = 0;
6207   return SQLITE_OK;
6208 }
6209 
6210 /*
6211 ** Return values of columns for the row at which the series_cursor
6212 ** is currently pointing.
6213 */
6214 static int fsdirColumn(
6215   sqlite3_vtab_cursor *cur,   /* The cursor */
6216   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6217   int i                       /* Which column to return */
6218 ){
6219   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6220   switch( i ){
6221     case FSDIR_COLUMN_NAME: {
6222       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
6223       break;
6224     }
6225 
6226     case FSDIR_COLUMN_MODE:
6227       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
6228       break;
6229 
6230     case FSDIR_COLUMN_MTIME:
6231       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
6232       break;
6233 
6234     case FSDIR_COLUMN_DATA: {
6235       mode_t m = pCur->sStat.st_mode;
6236       if( S_ISDIR(m) ){
6237         sqlite3_result_null(ctx);
6238 #if !defined(_WIN32) && !defined(WIN32)
6239       }else if( S_ISLNK(m) ){
6240         char aStatic[64];
6241         char *aBuf = aStatic;
6242         sqlite3_int64 nBuf = 64;
6243         int n;
6244 
6245         while( 1 ){
6246           n = readlink(pCur->zPath, aBuf, nBuf);
6247           if( n<nBuf ) break;
6248           if( aBuf!=aStatic ) sqlite3_free(aBuf);
6249           nBuf = nBuf*2;
6250           aBuf = sqlite3_malloc64(nBuf);
6251           if( aBuf==0 ){
6252             sqlite3_result_error_nomem(ctx);
6253             return SQLITE_NOMEM;
6254           }
6255         }
6256 
6257         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
6258         if( aBuf!=aStatic ) sqlite3_free(aBuf);
6259 #endif
6260       }else{
6261         readFileContents(ctx, pCur->zPath);
6262       }
6263     }
6264     case FSDIR_COLUMN_PATH:
6265     default: {
6266       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
6267       ** always return their values as NULL */
6268       break;
6269     }
6270   }
6271   return SQLITE_OK;
6272 }
6273 
6274 /*
6275 ** Return the rowid for the current row. In this implementation, the
6276 ** first row returned is assigned rowid value 1, and each subsequent
6277 ** row a value 1 more than that of the previous.
6278 */
6279 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
6280   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6281   *pRowid = pCur->iRowid;
6282   return SQLITE_OK;
6283 }
6284 
6285 /*
6286 ** Return TRUE if the cursor has been moved off of the last
6287 ** row of output.
6288 */
6289 static int fsdirEof(sqlite3_vtab_cursor *cur){
6290   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6291   return (pCur->zPath==0);
6292 }
6293 
6294 /*
6295 ** xFilter callback.
6296 **
6297 ** idxNum==1   PATH parameter only
6298 ** idxNum==2   Both PATH and DIR supplied
6299 */
6300 static int fsdirFilter(
6301   sqlite3_vtab_cursor *cur,
6302   int idxNum, const char *idxStr,
6303   int argc, sqlite3_value **argv
6304 ){
6305   const char *zDir = 0;
6306   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6307   (void)idxStr;
6308   fsdirResetCursor(pCur);
6309 
6310   if( idxNum==0 ){
6311     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
6312     return SQLITE_ERROR;
6313   }
6314 
6315   assert( argc==idxNum && (argc==1 || argc==2) );
6316   zDir = (const char*)sqlite3_value_text(argv[0]);
6317   if( zDir==0 ){
6318     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
6319     return SQLITE_ERROR;
6320   }
6321   if( argc==2 ){
6322     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
6323   }
6324   if( pCur->zBase ){
6325     pCur->nBase = (int)strlen(pCur->zBase)+1;
6326     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
6327   }else{
6328     pCur->zPath = sqlite3_mprintf("%s", zDir);
6329   }
6330 
6331   if( pCur->zPath==0 ){
6332     return SQLITE_NOMEM;
6333   }
6334   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
6335     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
6336     return SQLITE_ERROR;
6337   }
6338 
6339   return SQLITE_OK;
6340 }
6341 
6342 /*
6343 ** SQLite will invoke this method one or more times while planning a query
6344 ** that uses the generate_series virtual table.  This routine needs to create
6345 ** a query plan for each invocation and compute an estimated cost for that
6346 ** plan.
6347 **
6348 ** In this implementation idxNum is used to represent the
6349 ** query plan.  idxStr is unused.
6350 **
6351 ** The query plan is represented by values of idxNum:
6352 **
6353 **  (1)  The path value is supplied by argv[0]
6354 **  (2)  Path is in argv[0] and dir is in argv[1]
6355 */
6356 static int fsdirBestIndex(
6357   sqlite3_vtab *tab,
6358   sqlite3_index_info *pIdxInfo
6359 ){
6360   int i;                 /* Loop over constraints */
6361   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
6362   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
6363   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
6364   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
6365   const struct sqlite3_index_constraint *pConstraint;
6366 
6367   (void)tab;
6368   pConstraint = pIdxInfo->aConstraint;
6369   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6370     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
6371     switch( pConstraint->iColumn ){
6372       case FSDIR_COLUMN_PATH: {
6373         if( pConstraint->usable ){
6374           idxPath = i;
6375           seenPath = 0;
6376         }else if( idxPath<0 ){
6377           seenPath = 1;
6378         }
6379         break;
6380       }
6381       case FSDIR_COLUMN_DIR: {
6382         if( pConstraint->usable ){
6383           idxDir = i;
6384           seenDir = 0;
6385         }else if( idxDir<0 ){
6386           seenDir = 1;
6387         }
6388         break;
6389       }
6390     }
6391   }
6392   if( seenPath || seenDir ){
6393     /* If input parameters are unusable, disallow this plan */
6394     return SQLITE_CONSTRAINT;
6395   }
6396 
6397   if( idxPath<0 ){
6398     pIdxInfo->idxNum = 0;
6399     /* The pIdxInfo->estimatedCost should have been initialized to a huge
6400     ** number.  Leave it unchanged. */
6401     pIdxInfo->estimatedRows = 0x7fffffff;
6402   }else{
6403     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
6404     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
6405     if( idxDir>=0 ){
6406       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
6407       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
6408       pIdxInfo->idxNum = 2;
6409       pIdxInfo->estimatedCost = 10.0;
6410     }else{
6411       pIdxInfo->idxNum = 1;
6412       pIdxInfo->estimatedCost = 100.0;
6413     }
6414   }
6415 
6416   return SQLITE_OK;
6417 }
6418 
6419 /*
6420 ** Register the "fsdir" virtual table.
6421 */
6422 static int fsdirRegister(sqlite3 *db){
6423   static sqlite3_module fsdirModule = {
6424     0,                         /* iVersion */
6425     0,                         /* xCreate */
6426     fsdirConnect,              /* xConnect */
6427     fsdirBestIndex,            /* xBestIndex */
6428     fsdirDisconnect,           /* xDisconnect */
6429     0,                         /* xDestroy */
6430     fsdirOpen,                 /* xOpen - open a cursor */
6431     fsdirClose,                /* xClose - close a cursor */
6432     fsdirFilter,               /* xFilter - configure scan constraints */
6433     fsdirNext,                 /* xNext - advance a cursor */
6434     fsdirEof,                  /* xEof - check for end of scan */
6435     fsdirColumn,               /* xColumn - read data */
6436     fsdirRowid,                /* xRowid - read data */
6437     0,                         /* xUpdate */
6438     0,                         /* xBegin */
6439     0,                         /* xSync */
6440     0,                         /* xCommit */
6441     0,                         /* xRollback */
6442     0,                         /* xFindMethod */
6443     0,                         /* xRename */
6444     0,                         /* xSavepoint */
6445     0,                         /* xRelease */
6446     0,                         /* xRollbackTo */
6447     0,                         /* xShadowName */
6448   };
6449 
6450   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
6451   return rc;
6452 }
6453 #else         /* SQLITE_OMIT_VIRTUALTABLE */
6454 # define fsdirRegister(x) SQLITE_OK
6455 #endif
6456 
6457 #ifdef _WIN32
6458 
6459 #endif
6460 int sqlite3_fileio_init(
6461   sqlite3 *db,
6462   char **pzErrMsg,
6463   const sqlite3_api_routines *pApi
6464 ){
6465   int rc = SQLITE_OK;
6466   SQLITE_EXTENSION_INIT2(pApi);
6467   (void)pzErrMsg;  /* Unused parameter */
6468   rc = sqlite3_create_function(db, "readfile", 1,
6469                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
6470                                readfileFunc, 0, 0);
6471   if( rc==SQLITE_OK ){
6472     rc = sqlite3_create_function(db, "writefile", -1,
6473                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
6474                                  writefileFunc, 0, 0);
6475   }
6476   if( rc==SQLITE_OK ){
6477     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
6478                                  lsModeFunc, 0, 0);
6479   }
6480   if( rc==SQLITE_OK ){
6481     rc = fsdirRegister(db);
6482   }
6483   return rc;
6484 }
6485 
6486 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
6487 /* To allow a standalone DLL, make test_windirent.c use the same
6488  * redefined SQLite API calls as the above extension code does.
6489  * Just pull in this .c to accomplish this. As a beneficial side
6490  * effect, this extension becomes a single translation unit. */
6491 #  include "test_windirent.c"
6492 #endif
6493 
6494 /************************* End ../ext/misc/fileio.c ********************/
6495 /************************* Begin ../ext/misc/completion.c ******************/
6496 /*
6497 ** 2017-07-10
6498 **
6499 ** The author disclaims copyright to this source code.  In place of
6500 ** a legal notice, here is a blessing:
6501 **
6502 **    May you do good and not evil.
6503 **    May you find forgiveness for yourself and forgive others.
6504 **    May you share freely, never taking more than you give.
6505 **
6506 *************************************************************************
6507 **
6508 ** This file implements an eponymous virtual table that returns suggested
6509 ** completions for a partial SQL input.
6510 **
6511 ** Suggested usage:
6512 **
6513 **     SELECT DISTINCT candidate COLLATE nocase
6514 **       FROM completion($prefix,$wholeline)
6515 **      ORDER BY 1;
6516 **
6517 ** The two query parameters are optional.  $prefix is the text of the
6518 ** current word being typed and that is to be completed.  $wholeline is
6519 ** the complete input line, used for context.
6520 **
6521 ** The raw completion() table might return the same candidate multiple
6522 ** times, for example if the same column name is used to two or more
6523 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
6524 ** the DISTINCT and ORDER BY are recommended.
6525 **
6526 ** This virtual table operates at the speed of human typing, and so there
6527 ** is no attempt to make it fast.  Even a slow implementation will be much
6528 ** faster than any human can type.
6529 **
6530 */
6531 /* #include "sqlite3ext.h" */
6532 SQLITE_EXTENSION_INIT1
6533 #include <assert.h>
6534 #include <string.h>
6535 #include <ctype.h>
6536 
6537 #ifndef SQLITE_OMIT_VIRTUALTABLE
6538 
6539 /* completion_vtab is a subclass of sqlite3_vtab which will
6540 ** serve as the underlying representation of a completion virtual table
6541 */
6542 typedef struct completion_vtab completion_vtab;
6543 struct completion_vtab {
6544   sqlite3_vtab base;  /* Base class - must be first */
6545   sqlite3 *db;        /* Database connection for this completion vtab */
6546 };
6547 
6548 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
6549 ** serve as the underlying representation of a cursor that scans
6550 ** over rows of the result
6551 */
6552 typedef struct completion_cursor completion_cursor;
6553 struct completion_cursor {
6554   sqlite3_vtab_cursor base;  /* Base class - must be first */
6555   sqlite3 *db;               /* Database connection for this cursor */
6556   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
6557   char *zPrefix;             /* The prefix for the word we want to complete */
6558   char *zLine;               /* The whole that we want to complete */
6559   const char *zCurrentRow;   /* Current output row */
6560   int szRow;                 /* Length of the zCurrentRow string */
6561   sqlite3_stmt *pStmt;       /* Current statement */
6562   sqlite3_int64 iRowid;      /* The rowid */
6563   int ePhase;                /* Current phase */
6564   int j;                     /* inter-phase counter */
6565 };
6566 
6567 /* Values for ePhase:
6568 */
6569 #define COMPLETION_FIRST_PHASE   1
6570 #define COMPLETION_KEYWORDS      1
6571 #define COMPLETION_PRAGMAS       2
6572 #define COMPLETION_FUNCTIONS     3
6573 #define COMPLETION_COLLATIONS    4
6574 #define COMPLETION_INDEXES       5
6575 #define COMPLETION_TRIGGERS      6
6576 #define COMPLETION_DATABASES     7
6577 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
6578 #define COMPLETION_COLUMNS       9
6579 #define COMPLETION_MODULES       10
6580 #define COMPLETION_EOF           11
6581 
6582 /*
6583 ** The completionConnect() method is invoked to create a new
6584 ** completion_vtab that describes the completion virtual table.
6585 **
6586 ** Think of this routine as the constructor for completion_vtab objects.
6587 **
6588 ** All this routine needs to do is:
6589 **
6590 **    (1) Allocate the completion_vtab object and initialize all fields.
6591 **
6592 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
6593 **        result set of queries against completion will look like.
6594 */
6595 static int completionConnect(
6596   sqlite3 *db,
6597   void *pAux,
6598   int argc, const char *const*argv,
6599   sqlite3_vtab **ppVtab,
6600   char **pzErr
6601 ){
6602   completion_vtab *pNew;
6603   int rc;
6604 
6605   (void)(pAux);    /* Unused parameter */
6606   (void)(argc);    /* Unused parameter */
6607   (void)(argv);    /* Unused parameter */
6608   (void)(pzErr);   /* Unused parameter */
6609 
6610 /* Column numbers */
6611 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
6612 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
6613 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
6614 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
6615 
6616   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
6617   rc = sqlite3_declare_vtab(db,
6618       "CREATE TABLE x("
6619       "  candidate TEXT,"
6620       "  prefix TEXT HIDDEN,"
6621       "  wholeline TEXT HIDDEN,"
6622       "  phase INT HIDDEN"        /* Used for debugging only */
6623       ")");
6624   if( rc==SQLITE_OK ){
6625     pNew = sqlite3_malloc( sizeof(*pNew) );
6626     *ppVtab = (sqlite3_vtab*)pNew;
6627     if( pNew==0 ) return SQLITE_NOMEM;
6628     memset(pNew, 0, sizeof(*pNew));
6629     pNew->db = db;
6630   }
6631   return rc;
6632 }
6633 
6634 /*
6635 ** This method is the destructor for completion_cursor objects.
6636 */
6637 static int completionDisconnect(sqlite3_vtab *pVtab){
6638   sqlite3_free(pVtab);
6639   return SQLITE_OK;
6640 }
6641 
6642 /*
6643 ** Constructor for a new completion_cursor object.
6644 */
6645 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6646   completion_cursor *pCur;
6647   pCur = sqlite3_malloc( sizeof(*pCur) );
6648   if( pCur==0 ) return SQLITE_NOMEM;
6649   memset(pCur, 0, sizeof(*pCur));
6650   pCur->db = ((completion_vtab*)p)->db;
6651   *ppCursor = &pCur->base;
6652   return SQLITE_OK;
6653 }
6654 
6655 /*
6656 ** Reset the completion_cursor.
6657 */
6658 static void completionCursorReset(completion_cursor *pCur){
6659   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
6660   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
6661   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
6662   pCur->j = 0;
6663 }
6664 
6665 /*
6666 ** Destructor for a completion_cursor.
6667 */
6668 static int completionClose(sqlite3_vtab_cursor *cur){
6669   completionCursorReset((completion_cursor*)cur);
6670   sqlite3_free(cur);
6671   return SQLITE_OK;
6672 }
6673 
6674 /*
6675 ** Advance a completion_cursor to its next row of output.
6676 **
6677 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
6678 ** record the current state of the scan.  This routine sets ->zCurrentRow
6679 ** to the current row of output and then returns.  If no more rows remain,
6680 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
6681 ** table that has reached the end of its scan.
6682 **
6683 ** The current implementation just lists potential identifiers and
6684 ** keywords and filters them by zPrefix.  Future enhancements should
6685 ** take zLine into account to try to restrict the set of identifiers and
6686 ** keywords based on what would be legal at the current point of input.
6687 */
6688 static int completionNext(sqlite3_vtab_cursor *cur){
6689   completion_cursor *pCur = (completion_cursor*)cur;
6690   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
6691   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
6692   pCur->iRowid++;
6693   while( pCur->ePhase!=COMPLETION_EOF ){
6694     switch( pCur->ePhase ){
6695       case COMPLETION_KEYWORDS: {
6696         if( pCur->j >= sqlite3_keyword_count() ){
6697           pCur->zCurrentRow = 0;
6698           pCur->ePhase = COMPLETION_DATABASES;
6699         }else{
6700           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
6701         }
6702         iCol = -1;
6703         break;
6704       }
6705       case COMPLETION_DATABASES: {
6706         if( pCur->pStmt==0 ){
6707           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
6708                              &pCur->pStmt, 0);
6709         }
6710         iCol = 1;
6711         eNextPhase = COMPLETION_TABLES;
6712         break;
6713       }
6714       case COMPLETION_TABLES: {
6715         if( pCur->pStmt==0 ){
6716           sqlite3_stmt *pS2;
6717           char *zSql = 0;
6718           const char *zSep = "";
6719           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
6720           while( sqlite3_step(pS2)==SQLITE_ROW ){
6721             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
6722             zSql = sqlite3_mprintf(
6723                "%z%s"
6724                "SELECT name FROM \"%w\".sqlite_schema",
6725                zSql, zSep, zDb
6726             );
6727             if( zSql==0 ) return SQLITE_NOMEM;
6728             zSep = " UNION ";
6729           }
6730           sqlite3_finalize(pS2);
6731           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
6732           sqlite3_free(zSql);
6733         }
6734         iCol = 0;
6735         eNextPhase = COMPLETION_COLUMNS;
6736         break;
6737       }
6738       case COMPLETION_COLUMNS: {
6739         if( pCur->pStmt==0 ){
6740           sqlite3_stmt *pS2;
6741           char *zSql = 0;
6742           const char *zSep = "";
6743           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
6744           while( sqlite3_step(pS2)==SQLITE_ROW ){
6745             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
6746             zSql = sqlite3_mprintf(
6747                "%z%s"
6748                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
6749                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
6750                " WHERE sm.type='table'",
6751                zSql, zSep, zDb, zDb
6752             );
6753             if( zSql==0 ) return SQLITE_NOMEM;
6754             zSep = " UNION ";
6755           }
6756           sqlite3_finalize(pS2);
6757           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
6758           sqlite3_free(zSql);
6759         }
6760         iCol = 0;
6761         eNextPhase = COMPLETION_EOF;
6762         break;
6763       }
6764     }
6765     if( iCol<0 ){
6766       /* This case is when the phase presets zCurrentRow */
6767       if( pCur->zCurrentRow==0 ) continue;
6768     }else{
6769       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
6770         /* Extract the next row of content */
6771         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
6772         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
6773       }else{
6774         /* When all rows are finished, advance to the next phase */
6775         sqlite3_finalize(pCur->pStmt);
6776         pCur->pStmt = 0;
6777         pCur->ePhase = eNextPhase;
6778         continue;
6779       }
6780     }
6781     if( pCur->nPrefix==0 ) break;
6782     if( pCur->nPrefix<=pCur->szRow
6783      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
6784     ){
6785       break;
6786     }
6787   }
6788 
6789   return SQLITE_OK;
6790 }
6791 
6792 /*
6793 ** Return values of columns for the row at which the completion_cursor
6794 ** is currently pointing.
6795 */
6796 static int completionColumn(
6797   sqlite3_vtab_cursor *cur,   /* The cursor */
6798   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6799   int i                       /* Which column to return */
6800 ){
6801   completion_cursor *pCur = (completion_cursor*)cur;
6802   switch( i ){
6803     case COMPLETION_COLUMN_CANDIDATE: {
6804       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
6805       break;
6806     }
6807     case COMPLETION_COLUMN_PREFIX: {
6808       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
6809       break;
6810     }
6811     case COMPLETION_COLUMN_WHOLELINE: {
6812       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
6813       break;
6814     }
6815     case COMPLETION_COLUMN_PHASE: {
6816       sqlite3_result_int(ctx, pCur->ePhase);
6817       break;
6818     }
6819   }
6820   return SQLITE_OK;
6821 }
6822 
6823 /*
6824 ** Return the rowid for the current row.  In this implementation, the
6825 ** rowid is the same as the output value.
6826 */
6827 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
6828   completion_cursor *pCur = (completion_cursor*)cur;
6829   *pRowid = pCur->iRowid;
6830   return SQLITE_OK;
6831 }
6832 
6833 /*
6834 ** Return TRUE if the cursor has been moved off of the last
6835 ** row of output.
6836 */
6837 static int completionEof(sqlite3_vtab_cursor *cur){
6838   completion_cursor *pCur = (completion_cursor*)cur;
6839   return pCur->ePhase >= COMPLETION_EOF;
6840 }
6841 
6842 /*
6843 ** This method is called to "rewind" the completion_cursor object back
6844 ** to the first row of output.  This method is always called at least
6845 ** once prior to any call to completionColumn() or completionRowid() or
6846 ** completionEof().
6847 */
6848 static int completionFilter(
6849   sqlite3_vtab_cursor *pVtabCursor,
6850   int idxNum, const char *idxStr,
6851   int argc, sqlite3_value **argv
6852 ){
6853   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
6854   int iArg = 0;
6855   (void)(idxStr);   /* Unused parameter */
6856   (void)(argc);     /* Unused parameter */
6857   completionCursorReset(pCur);
6858   if( idxNum & 1 ){
6859     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
6860     if( pCur->nPrefix>0 ){
6861       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
6862       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
6863     }
6864     iArg = 1;
6865   }
6866   if( idxNum & 2 ){
6867     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
6868     if( pCur->nLine>0 ){
6869       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
6870       if( pCur->zLine==0 ) return SQLITE_NOMEM;
6871     }
6872   }
6873   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
6874     int i = pCur->nLine;
6875     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
6876       i--;
6877     }
6878     pCur->nPrefix = pCur->nLine - i;
6879     if( pCur->nPrefix>0 ){
6880       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
6881       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
6882     }
6883   }
6884   pCur->iRowid = 0;
6885   pCur->ePhase = COMPLETION_FIRST_PHASE;
6886   return completionNext(pVtabCursor);
6887 }
6888 
6889 /*
6890 ** SQLite will invoke this method one or more times while planning a query
6891 ** that uses the completion virtual table.  This routine needs to create
6892 ** a query plan for each invocation and compute an estimated cost for that
6893 ** plan.
6894 **
6895 ** There are two hidden parameters that act as arguments to the table-valued
6896 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
6897 ** is available and bit 1 is set if "wholeline" is available.
6898 */
6899 static int completionBestIndex(
6900   sqlite3_vtab *tab,
6901   sqlite3_index_info *pIdxInfo
6902 ){
6903   int i;                 /* Loop over constraints */
6904   int idxNum = 0;        /* The query plan bitmask */
6905   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
6906   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
6907   int nArg = 0;          /* Number of arguments that completeFilter() expects */
6908   const struct sqlite3_index_constraint *pConstraint;
6909 
6910   (void)(tab);    /* Unused parameter */
6911   pConstraint = pIdxInfo->aConstraint;
6912   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6913     if( pConstraint->usable==0 ) continue;
6914     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
6915     switch( pConstraint->iColumn ){
6916       case COMPLETION_COLUMN_PREFIX:
6917         prefixIdx = i;
6918         idxNum |= 1;
6919         break;
6920       case COMPLETION_COLUMN_WHOLELINE:
6921         wholelineIdx = i;
6922         idxNum |= 2;
6923         break;
6924     }
6925   }
6926   if( prefixIdx>=0 ){
6927     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
6928     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
6929   }
6930   if( wholelineIdx>=0 ){
6931     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
6932     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
6933   }
6934   pIdxInfo->idxNum = idxNum;
6935   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
6936   pIdxInfo->estimatedRows = 500 - 100*nArg;
6937   return SQLITE_OK;
6938 }
6939 
6940 /*
6941 ** This following structure defines all the methods for the
6942 ** completion virtual table.
6943 */
6944 static sqlite3_module completionModule = {
6945   0,                         /* iVersion */
6946   0,                         /* xCreate */
6947   completionConnect,         /* xConnect */
6948   completionBestIndex,       /* xBestIndex */
6949   completionDisconnect,      /* xDisconnect */
6950   0,                         /* xDestroy */
6951   completionOpen,            /* xOpen - open a cursor */
6952   completionClose,           /* xClose - close a cursor */
6953   completionFilter,          /* xFilter - configure scan constraints */
6954   completionNext,            /* xNext - advance a cursor */
6955   completionEof,             /* xEof - check for end of scan */
6956   completionColumn,          /* xColumn - read data */
6957   completionRowid,           /* xRowid - read data */
6958   0,                         /* xUpdate */
6959   0,                         /* xBegin */
6960   0,                         /* xSync */
6961   0,                         /* xCommit */
6962   0,                         /* xRollback */
6963   0,                         /* xFindMethod */
6964   0,                         /* xRename */
6965   0,                         /* xSavepoint */
6966   0,                         /* xRelease */
6967   0,                         /* xRollbackTo */
6968   0                          /* xShadowName */
6969 };
6970 
6971 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6972 
6973 int sqlite3CompletionVtabInit(sqlite3 *db){
6974   int rc = SQLITE_OK;
6975 #ifndef SQLITE_OMIT_VIRTUALTABLE
6976   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
6977 #endif
6978   return rc;
6979 }
6980 
6981 #ifdef _WIN32
6982 
6983 #endif
6984 int sqlite3_completion_init(
6985   sqlite3 *db,
6986   char **pzErrMsg,
6987   const sqlite3_api_routines *pApi
6988 ){
6989   int rc = SQLITE_OK;
6990   SQLITE_EXTENSION_INIT2(pApi);
6991   (void)(pzErrMsg);  /* Unused parameter */
6992 #ifndef SQLITE_OMIT_VIRTUALTABLE
6993   rc = sqlite3CompletionVtabInit(db);
6994 #endif
6995   return rc;
6996 }
6997 
6998 /************************* End ../ext/misc/completion.c ********************/
6999 /************************* Begin ../ext/misc/appendvfs.c ******************/
7000 /*
7001 ** 2017-10-20
7002 **
7003 ** The author disclaims copyright to this source code.  In place of
7004 ** a legal notice, here is a blessing:
7005 **
7006 **    May you do good and not evil.
7007 **    May you find forgiveness for yourself and forgive others.
7008 **    May you share freely, never taking more than you give.
7009 **
7010 ******************************************************************************
7011 **
7012 ** This file implements a VFS shim that allows an SQLite database to be
7013 ** appended onto the end of some other file, such as an executable.
7014 **
7015 ** A special record must appear at the end of the file that identifies the
7016 ** file as an appended database and provides the offset to the first page
7017 ** of the exposed content. (Or, it is the length of the content prefix.)
7018 ** For best performance page 1 should be located at a disk page boundary,
7019 ** though that is not required.
7020 **
7021 ** When opening a database using this VFS, the connection might treat
7022 ** the file as an ordinary SQLite database, or it might treat it as a
7023 ** database appended onto some other file.  The decision is made by
7024 ** applying the following rules in order:
7025 **
7026 **  (1)  An empty file is an ordinary database.
7027 **
7028 **  (2)  If the file ends with the appendvfs trailer string
7029 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
7030 **
7031 **  (3)  If the file begins with the standard SQLite prefix string
7032 **       "SQLite format 3", that file is an ordinary database.
7033 **
7034 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
7035 **       set, then a new database is appended to the already existing file.
7036 **
7037 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
7038 **
7039 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
7040 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
7041 ** This VFS will not read or write past the 1GiB mark.  This restriction
7042 ** might be lifted in future versions.  For now, if you need a larger
7043 ** database, then keep it in a separate file.
7044 **
7045 ** If the file being opened is a plain database (not an appended one), then
7046 ** this shim is a pass-through into the default underlying VFS. (rule 3)
7047 **/
7048 /* #include "sqlite3ext.h" */
7049 SQLITE_EXTENSION_INIT1
7050 #include <string.h>
7051 #include <assert.h>
7052 
7053 /* The append mark at the end of the database is:
7054 **
7055 **     Start-Of-SQLite3-NNNNNNNN
7056 **     123456789 123456789 12345
7057 **
7058 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
7059 ** the offset to page 1, and also the length of the prefix content.
7060 */
7061 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
7062 #define APND_MARK_PREFIX_SZ  17
7063 #define APND_MARK_FOS_SZ      8
7064 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
7065 
7066 /*
7067 ** Maximum size of the combined prefix + database + append-mark.  This
7068 ** must be less than 0x40000000 to avoid locking issues on Windows.
7069 */
7070 #define APND_MAX_SIZE  (0x40000000)
7071 
7072 /*
7073 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
7074 */
7075 #ifndef APND_ROUNDUP
7076 #define APND_ROUNDUP 4096
7077 #endif
7078 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
7079 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
7080 
7081 /*
7082 ** Forward declaration of objects used by this utility
7083 */
7084 typedef struct sqlite3_vfs ApndVfs;
7085 typedef struct ApndFile ApndFile;
7086 
7087 /* Access to a lower-level VFS that (might) implement dynamic loading,
7088 ** access to randomness, etc.
7089 */
7090 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
7091 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
7092 
7093 /* An open appendvfs file
7094 **
7095 ** An instance of this structure describes the appended database file.
7096 ** A separate sqlite3_file object is always appended. The appended
7097 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
7098 ** the entire file, including the prefix, the database, and the
7099 ** append-mark.
7100 **
7101 ** The structure of an AppendVFS database is like this:
7102 **
7103 **   +-------------+---------+----------+-------------+
7104 **   | prefix-file | padding | database | append-mark |
7105 **   +-------------+---------+----------+-------------+
7106 **                           ^          ^
7107 **                           |          |
7108 **                         iPgOne      iMark
7109 **
7110 **
7111 ** "prefix file" -  file onto which the database has been appended.
7112 ** "padding"     -  zero or more bytes inserted so that "database"
7113 **                  starts on an APND_ROUNDUP boundary
7114 ** "database"    -  The SQLite database file
7115 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
7116 **                  the offset from the start of prefix-file to the start
7117 **                  of "database".
7118 **
7119 ** The size of the database is iMark - iPgOne.
7120 **
7121 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
7122 ** of iPgOne stored as a big-ending 64-bit integer.
7123 **
7124 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
7125 ** Or, iMark is -1 to indicate that it has not yet been written.
7126 */
7127 struct ApndFile {
7128   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
7129   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
7130   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
7131   /* Always followed by another sqlite3_file that describes the whole file */
7132 };
7133 
7134 /*
7135 ** Methods for ApndFile
7136 */
7137 static int apndClose(sqlite3_file*);
7138 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
7139 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
7140 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
7141 static int apndSync(sqlite3_file*, int flags);
7142 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
7143 static int apndLock(sqlite3_file*, int);
7144 static int apndUnlock(sqlite3_file*, int);
7145 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
7146 static int apndFileControl(sqlite3_file*, int op, void *pArg);
7147 static int apndSectorSize(sqlite3_file*);
7148 static int apndDeviceCharacteristics(sqlite3_file*);
7149 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
7150 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
7151 static void apndShmBarrier(sqlite3_file*);
7152 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
7153 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
7154 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
7155 
7156 /*
7157 ** Methods for ApndVfs
7158 */
7159 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
7160 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
7161 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
7162 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
7163 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
7164 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
7165 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
7166 static void apndDlClose(sqlite3_vfs*, void*);
7167 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
7168 static int apndSleep(sqlite3_vfs*, int microseconds);
7169 static int apndCurrentTime(sqlite3_vfs*, double*);
7170 static int apndGetLastError(sqlite3_vfs*, int, char *);
7171 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
7172 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
7173 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
7174 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
7175 
7176 static sqlite3_vfs apnd_vfs = {
7177   3,                            /* iVersion (set when registered) */
7178   0,                            /* szOsFile (set when registered) */
7179   1024,                         /* mxPathname */
7180   0,                            /* pNext */
7181   "apndvfs",                    /* zName */
7182   0,                            /* pAppData (set when registered) */
7183   apndOpen,                     /* xOpen */
7184   apndDelete,                   /* xDelete */
7185   apndAccess,                   /* xAccess */
7186   apndFullPathname,             /* xFullPathname */
7187   apndDlOpen,                   /* xDlOpen */
7188   apndDlError,                  /* xDlError */
7189   apndDlSym,                    /* xDlSym */
7190   apndDlClose,                  /* xDlClose */
7191   apndRandomness,               /* xRandomness */
7192   apndSleep,                    /* xSleep */
7193   apndCurrentTime,              /* xCurrentTime */
7194   apndGetLastError,             /* xGetLastError */
7195   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
7196   apndSetSystemCall,            /* xSetSystemCall */
7197   apndGetSystemCall,            /* xGetSystemCall */
7198   apndNextSystemCall            /* xNextSystemCall */
7199 };
7200 
7201 static const sqlite3_io_methods apnd_io_methods = {
7202   3,                              /* iVersion */
7203   apndClose,                      /* xClose */
7204   apndRead,                       /* xRead */
7205   apndWrite,                      /* xWrite */
7206   apndTruncate,                   /* xTruncate */
7207   apndSync,                       /* xSync */
7208   apndFileSize,                   /* xFileSize */
7209   apndLock,                       /* xLock */
7210   apndUnlock,                     /* xUnlock */
7211   apndCheckReservedLock,          /* xCheckReservedLock */
7212   apndFileControl,                /* xFileControl */
7213   apndSectorSize,                 /* xSectorSize */
7214   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
7215   apndShmMap,                     /* xShmMap */
7216   apndShmLock,                    /* xShmLock */
7217   apndShmBarrier,                 /* xShmBarrier */
7218   apndShmUnmap,                   /* xShmUnmap */
7219   apndFetch,                      /* xFetch */
7220   apndUnfetch                     /* xUnfetch */
7221 };
7222 
7223 /*
7224 ** Close an apnd-file.
7225 */
7226 static int apndClose(sqlite3_file *pFile){
7227   pFile = ORIGFILE(pFile);
7228   return pFile->pMethods->xClose(pFile);
7229 }
7230 
7231 /*
7232 ** Read data from an apnd-file.
7233 */
7234 static int apndRead(
7235   sqlite3_file *pFile,
7236   void *zBuf,
7237   int iAmt,
7238   sqlite_int64 iOfst
7239 ){
7240   ApndFile *paf = (ApndFile *)pFile;
7241   pFile = ORIGFILE(pFile);
7242   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
7243 }
7244 
7245 /*
7246 ** Add the append-mark onto what should become the end of the file.
7247 *  If and only if this succeeds, internal ApndFile.iMark is updated.
7248 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
7249 */
7250 static int apndWriteMark(
7251   ApndFile *paf,
7252   sqlite3_file *pFile,
7253   sqlite_int64 iWriteEnd
7254 ){
7255   sqlite_int64 iPgOne = paf->iPgOne;
7256   unsigned char a[APND_MARK_SIZE];
7257   int i = APND_MARK_FOS_SZ;
7258   int rc;
7259   assert(pFile == ORIGFILE(paf));
7260   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
7261   while( --i >= 0 ){
7262     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
7263     iPgOne >>= 8;
7264   }
7265   iWriteEnd += paf->iPgOne;
7266   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
7267                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
7268     paf->iMark = iWriteEnd;
7269   }
7270   return rc;
7271 }
7272 
7273 /*
7274 ** Write data to an apnd-file.
7275 */
7276 static int apndWrite(
7277   sqlite3_file *pFile,
7278   const void *zBuf,
7279   int iAmt,
7280   sqlite_int64 iOfst
7281 ){
7282   ApndFile *paf = (ApndFile *)pFile;
7283   sqlite_int64 iWriteEnd = iOfst + iAmt;
7284   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
7285   pFile = ORIGFILE(pFile);
7286   /* If append-mark is absent or will be overwritten, write it. */
7287   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
7288     int rc = apndWriteMark(paf, pFile, iWriteEnd);
7289     if( SQLITE_OK!=rc ) return rc;
7290   }
7291   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
7292 }
7293 
7294 /*
7295 ** Truncate an apnd-file.
7296 */
7297 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
7298   ApndFile *paf = (ApndFile *)pFile;
7299   pFile = ORIGFILE(pFile);
7300   /* The append mark goes out first so truncate failure does not lose it. */
7301   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
7302   /* Truncate underlying file just past append mark */
7303   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
7304 }
7305 
7306 /*
7307 ** Sync an apnd-file.
7308 */
7309 static int apndSync(sqlite3_file *pFile, int flags){
7310   pFile = ORIGFILE(pFile);
7311   return pFile->pMethods->xSync(pFile, flags);
7312 }
7313 
7314 /*
7315 ** Return the current file-size of an apnd-file.
7316 ** If the append mark is not yet there, the file-size is 0.
7317 */
7318 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
7319   ApndFile *paf = (ApndFile *)pFile;
7320   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
7321   return SQLITE_OK;
7322 }
7323 
7324 /*
7325 ** Lock an apnd-file.
7326 */
7327 static int apndLock(sqlite3_file *pFile, int eLock){
7328   pFile = ORIGFILE(pFile);
7329   return pFile->pMethods->xLock(pFile, eLock);
7330 }
7331 
7332 /*
7333 ** Unlock an apnd-file.
7334 */
7335 static int apndUnlock(sqlite3_file *pFile, int eLock){
7336   pFile = ORIGFILE(pFile);
7337   return pFile->pMethods->xUnlock(pFile, eLock);
7338 }
7339 
7340 /*
7341 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
7342 */
7343 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
7344   pFile = ORIGFILE(pFile);
7345   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
7346 }
7347 
7348 /*
7349 ** File control method. For custom operations on an apnd-file.
7350 */
7351 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
7352   ApndFile *paf = (ApndFile *)pFile;
7353   int rc;
7354   pFile = ORIGFILE(pFile);
7355   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
7356   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
7357   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
7358     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
7359   }
7360   return rc;
7361 }
7362 
7363 /*
7364 ** Return the sector-size in bytes for an apnd-file.
7365 */
7366 static int apndSectorSize(sqlite3_file *pFile){
7367   pFile = ORIGFILE(pFile);
7368   return pFile->pMethods->xSectorSize(pFile);
7369 }
7370 
7371 /*
7372 ** Return the device characteristic flags supported by an apnd-file.
7373 */
7374 static int apndDeviceCharacteristics(sqlite3_file *pFile){
7375   pFile = ORIGFILE(pFile);
7376   return pFile->pMethods->xDeviceCharacteristics(pFile);
7377 }
7378 
7379 /* Create a shared memory file mapping */
7380 static int apndShmMap(
7381   sqlite3_file *pFile,
7382   int iPg,
7383   int pgsz,
7384   int bExtend,
7385   void volatile **pp
7386 ){
7387   pFile = ORIGFILE(pFile);
7388   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
7389 }
7390 
7391 /* Perform locking on a shared-memory segment */
7392 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
7393   pFile = ORIGFILE(pFile);
7394   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
7395 }
7396 
7397 /* Memory barrier operation on shared memory */
7398 static void apndShmBarrier(sqlite3_file *pFile){
7399   pFile = ORIGFILE(pFile);
7400   pFile->pMethods->xShmBarrier(pFile);
7401 }
7402 
7403 /* Unmap a shared memory segment */
7404 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
7405   pFile = ORIGFILE(pFile);
7406   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
7407 }
7408 
7409 /* Fetch a page of a memory-mapped file */
7410 static int apndFetch(
7411   sqlite3_file *pFile,
7412   sqlite3_int64 iOfst,
7413   int iAmt,
7414   void **pp
7415 ){
7416   ApndFile *p = (ApndFile *)pFile;
7417   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
7418     return SQLITE_IOERR; /* Cannot read what is not yet there. */
7419   }
7420   pFile = ORIGFILE(pFile);
7421   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
7422 }
7423 
7424 /* Release a memory-mapped page */
7425 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
7426   ApndFile *p = (ApndFile *)pFile;
7427   pFile = ORIGFILE(pFile);
7428   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
7429 }
7430 
7431 /*
7432 ** Try to read the append-mark off the end of a file.  Return the
7433 ** start of the appended database if the append-mark is present.
7434 ** If there is no valid append-mark, return -1;
7435 **
7436 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
7437 ** indicates that the appended database contains at least one page.  The
7438 ** start-of-database value must be a multiple of 512.
7439 */
7440 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
7441   int rc, i;
7442   sqlite3_int64 iMark;
7443   int msbs = 8 * (APND_MARK_FOS_SZ-1);
7444   unsigned char a[APND_MARK_SIZE];
7445 
7446   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
7447   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
7448   if( rc ) return -1;
7449   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
7450   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
7451   for(i=1; i<8; i++){
7452     msbs -= 8;
7453     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
7454   }
7455   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
7456   if( iMark & 0x1ff ) return -1;
7457   return iMark;
7458 }
7459 
7460 static const char apvfsSqliteHdr[] = "SQLite format 3";
7461 /*
7462 ** Check to see if the file is an appendvfs SQLite database file.
7463 ** Return true iff it is such. Parameter sz is the file's size.
7464 */
7465 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
7466   int rc;
7467   char zHdr[16];
7468   sqlite3_int64 iMark = apndReadMark(sz, pFile);
7469   if( iMark>=0 ){
7470     /* If file has the correct end-marker, the expected odd size, and the
7471     ** SQLite DB type marker where the end-marker puts it, then it
7472     ** is an appendvfs database.
7473     */
7474     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
7475     if( SQLITE_OK==rc
7476      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
7477      && (sz & 0x1ff) == APND_MARK_SIZE
7478      && sz>=512+APND_MARK_SIZE
7479     ){
7480       return 1; /* It's an appendvfs database */
7481     }
7482   }
7483   return 0;
7484 }
7485 
7486 /*
7487 ** Check to see if the file is an ordinary SQLite database file.
7488 ** Return true iff so. Parameter sz is the file's size.
7489 */
7490 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
7491   char zHdr[16];
7492   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
7493    || (sz & 0x1ff) != 0
7494    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
7495    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
7496   ){
7497     return 0;
7498   }else{
7499     return 1;
7500   }
7501 }
7502 
7503 /*
7504 ** Open an apnd file handle.
7505 */
7506 static int apndOpen(
7507   sqlite3_vfs *pApndVfs,
7508   const char *zName,
7509   sqlite3_file *pFile,
7510   int flags,
7511   int *pOutFlags
7512 ){
7513   ApndFile *pApndFile = (ApndFile*)pFile;
7514   sqlite3_file *pBaseFile = ORIGFILE(pFile);
7515   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
7516   int rc;
7517   sqlite3_int64 sz = 0;
7518   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
7519     /* The appendvfs is not to be used for transient or temporary databases.
7520     ** Just use the base VFS open to initialize the given file object and
7521     ** open the underlying file. (Appendvfs is then unused for this file.)
7522     */
7523     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
7524   }
7525   memset(pApndFile, 0, sizeof(ApndFile));
7526   pFile->pMethods = &apnd_io_methods;
7527   pApndFile->iMark = -1;    /* Append mark not yet written */
7528 
7529   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
7530   if( rc==SQLITE_OK ){
7531     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
7532     if( rc ){
7533       pBaseFile->pMethods->xClose(pBaseFile);
7534     }
7535   }
7536   if( rc ){
7537     pFile->pMethods = 0;
7538     return rc;
7539   }
7540   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
7541     /* The file being opened appears to be just an ordinary DB. Copy
7542     ** the base dispatch-table so this instance mimics the base VFS.
7543     */
7544     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
7545     return SQLITE_OK;
7546   }
7547   pApndFile->iPgOne = apndReadMark(sz, pFile);
7548   if( pApndFile->iPgOne>=0 ){
7549     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
7550     return SQLITE_OK;
7551   }
7552   if( (flags & SQLITE_OPEN_CREATE)==0 ){
7553     pBaseFile->pMethods->xClose(pBaseFile);
7554     rc = SQLITE_CANTOPEN;
7555     pFile->pMethods = 0;
7556   }else{
7557     /* Round newly added appendvfs location to #define'd page boundary.
7558     ** Note that nothing has yet been written to the underlying file.
7559     ** The append mark will be written along with first content write.
7560     ** Until then, paf->iMark value indicates it is not yet written.
7561     */
7562     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
7563   }
7564   return rc;
7565 }
7566 
7567 /*
7568 ** Delete an apnd file.
7569 ** For an appendvfs, this could mean delete the appendvfs portion,
7570 ** leaving the appendee as it was before it gained an appendvfs.
7571 ** For now, this code deletes the underlying file too.
7572 */
7573 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
7574   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
7575 }
7576 
7577 /*
7578 ** All other VFS methods are pass-thrus.
7579 */
7580 static int apndAccess(
7581   sqlite3_vfs *pVfs,
7582   const char *zPath,
7583   int flags,
7584   int *pResOut
7585 ){
7586   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
7587 }
7588 static int apndFullPathname(
7589   sqlite3_vfs *pVfs,
7590   const char *zPath,
7591   int nOut,
7592   char *zOut
7593 ){
7594   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
7595 }
7596 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
7597   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
7598 }
7599 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
7600   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
7601 }
7602 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
7603   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
7604 }
7605 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
7606   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
7607 }
7608 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
7609   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
7610 }
7611 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
7612   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
7613 }
7614 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
7615   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
7616 }
7617 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
7618   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
7619 }
7620 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
7621   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
7622 }
7623 static int apndSetSystemCall(
7624   sqlite3_vfs *pVfs,
7625   const char *zName,
7626   sqlite3_syscall_ptr pCall
7627 ){
7628   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
7629 }
7630 static sqlite3_syscall_ptr apndGetSystemCall(
7631   sqlite3_vfs *pVfs,
7632   const char *zName
7633 ){
7634   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
7635 }
7636 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
7637   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
7638 }
7639 
7640 
7641 #ifdef _WIN32
7642 
7643 #endif
7644 /*
7645 ** This routine is called when the extension is loaded.
7646 ** Register the new VFS.
7647 */
7648 int sqlite3_appendvfs_init(
7649   sqlite3 *db,
7650   char **pzErrMsg,
7651   const sqlite3_api_routines *pApi
7652 ){
7653   int rc = SQLITE_OK;
7654   sqlite3_vfs *pOrig;
7655   SQLITE_EXTENSION_INIT2(pApi);
7656   (void)pzErrMsg;
7657   (void)db;
7658   pOrig = sqlite3_vfs_find(0);
7659   if( pOrig==0 ) return SQLITE_ERROR;
7660   apnd_vfs.iVersion = pOrig->iVersion;
7661   apnd_vfs.pAppData = pOrig;
7662   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
7663   rc = sqlite3_vfs_register(&apnd_vfs, 0);
7664 #ifdef APPENDVFS_TEST
7665   if( rc==SQLITE_OK ){
7666     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
7667   }
7668 #endif
7669   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
7670   return rc;
7671 }
7672 
7673 /************************* End ../ext/misc/appendvfs.c ********************/
7674 #endif
7675 #ifdef SQLITE_HAVE_ZLIB
7676 /************************* Begin ../ext/misc/zipfile.c ******************/
7677 /*
7678 ** 2017-12-26
7679 **
7680 ** The author disclaims copyright to this source code.  In place of
7681 ** a legal notice, here is a blessing:
7682 **
7683 **    May you do good and not evil.
7684 **    May you find forgiveness for yourself and forgive others.
7685 **    May you share freely, never taking more than you give.
7686 **
7687 ******************************************************************************
7688 **
7689 ** This file implements a virtual table for reading and writing ZIP archive
7690 ** files.
7691 **
7692 ** Usage example:
7693 **
7694 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
7695 **
7696 ** Current limitations:
7697 **
7698 **    *  No support for encryption
7699 **    *  No support for ZIP archives spanning multiple files
7700 **    *  No support for zip64 extensions
7701 **    *  Only the "inflate/deflate" (zlib) compression method is supported
7702 */
7703 /* #include "sqlite3ext.h" */
7704 SQLITE_EXTENSION_INIT1
7705 #include <stdio.h>
7706 #include <string.h>
7707 #include <assert.h>
7708 
7709 #include <zlib.h>
7710 
7711 #ifndef SQLITE_OMIT_VIRTUALTABLE
7712 
7713 #ifndef SQLITE_AMALGAMATION
7714 
7715 #ifndef UINT32_TYPE
7716 # ifdef HAVE_UINT32_T
7717 #  define UINT32_TYPE uint32_t
7718 # else
7719 #  define UINT32_TYPE unsigned int
7720 # endif
7721 #endif
7722 #ifndef UINT16_TYPE
7723 # ifdef HAVE_UINT16_T
7724 #  define UINT16_TYPE uint16_t
7725 # else
7726 #  define UINT16_TYPE unsigned short int
7727 # endif
7728 #endif
7729 /* typedef sqlite3_int64 i64; */
7730 /* typedef unsigned char u8; */
7731 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
7732 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
7733 #define MIN(a,b) ((a)<(b) ? (a) : (b))
7734 
7735 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
7736 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
7737 #endif
7738 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
7739 # define ALWAYS(X)      (1)
7740 # define NEVER(X)       (0)
7741 #elif !defined(NDEBUG)
7742 # define ALWAYS(X)      ((X)?1:(assert(0),0))
7743 # define NEVER(X)       ((X)?(assert(0),1):0)
7744 #else
7745 # define ALWAYS(X)      (X)
7746 # define NEVER(X)       (X)
7747 #endif
7748 
7749 #endif   /* SQLITE_AMALGAMATION */
7750 
7751 /*
7752 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
7753 **
7754 ** In some ways it would be better to obtain these values from system
7755 ** header files. But, the dependency is undesirable and (a) these
7756 ** have been stable for decades, (b) the values are part of POSIX and
7757 ** are also made explicit in [man stat], and (c) are part of the
7758 ** file format for zip archives.
7759 */
7760 #ifndef S_IFDIR
7761 # define S_IFDIR 0040000
7762 #endif
7763 #ifndef S_IFREG
7764 # define S_IFREG 0100000
7765 #endif
7766 #ifndef S_IFLNK
7767 # define S_IFLNK 0120000
7768 #endif
7769 
7770 static const char ZIPFILE_SCHEMA[] =
7771   "CREATE TABLE y("
7772     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
7773     "mode,"              /* 1: POSIX mode for file */
7774     "mtime,"             /* 2: Last modification time (secs since 1970)*/
7775     "sz,"                /* 3: Size of object */
7776     "rawdata,"           /* 4: Raw data */
7777     "data,"              /* 5: Uncompressed data */
7778     "method,"            /* 6: Compression method (integer) */
7779     "z HIDDEN"           /* 7: Name of zip file */
7780   ") WITHOUT ROWID;";
7781 
7782 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
7783 #define ZIPFILE_BUFFER_SIZE (64*1024)
7784 
7785 
7786 /*
7787 ** Magic numbers used to read and write zip files.
7788 **
7789 ** ZIPFILE_NEWENTRY_MADEBY:
7790 **   Use this value for the "version-made-by" field in new zip file
7791 **   entries. The upper byte indicates "unix", and the lower byte
7792 **   indicates that the zip file matches pkzip specification 3.0.
7793 **   This is what info-zip seems to do.
7794 **
7795 ** ZIPFILE_NEWENTRY_REQUIRED:
7796 **   Value for "version-required-to-extract" field of new entries.
7797 **   Version 2.0 is required to support folders and deflate compression.
7798 **
7799 ** ZIPFILE_NEWENTRY_FLAGS:
7800 **   Value for "general-purpose-bit-flags" field of new entries. Bit
7801 **   11 means "utf-8 filename and comment".
7802 **
7803 ** ZIPFILE_SIGNATURE_CDS:
7804 **   First 4 bytes of a valid CDS record.
7805 **
7806 ** ZIPFILE_SIGNATURE_LFH:
7807 **   First 4 bytes of a valid LFH record.
7808 **
7809 ** ZIPFILE_SIGNATURE_EOCD
7810 **   First 4 bytes of a valid EOCD record.
7811 */
7812 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
7813 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
7814 #define ZIPFILE_NEWENTRY_REQUIRED 20
7815 #define ZIPFILE_NEWENTRY_FLAGS    0x800
7816 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
7817 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
7818 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
7819 
7820 /*
7821 ** The sizes of the fixed-size part of each of the three main data
7822 ** structures in a zip archive.
7823 */
7824 #define ZIPFILE_LFH_FIXED_SZ      30
7825 #define ZIPFILE_EOCD_FIXED_SZ     22
7826 #define ZIPFILE_CDS_FIXED_SZ      46
7827 
7828 /*
7829 *** 4.3.16  End of central directory record:
7830 ***
7831 ***   end of central dir signature    4 bytes  (0x06054b50)
7832 ***   number of this disk             2 bytes
7833 ***   number of the disk with the
7834 ***   start of the central directory  2 bytes
7835 ***   total number of entries in the
7836 ***   central directory on this disk  2 bytes
7837 ***   total number of entries in
7838 ***   the central directory           2 bytes
7839 ***   size of the central directory   4 bytes
7840 ***   offset of start of central
7841 ***   directory with respect to
7842 ***   the starting disk number        4 bytes
7843 ***   .ZIP file comment length        2 bytes
7844 ***   .ZIP file comment       (variable size)
7845 */
7846 typedef struct ZipfileEOCD ZipfileEOCD;
7847 struct ZipfileEOCD {
7848   u16 iDisk;
7849   u16 iFirstDisk;
7850   u16 nEntry;
7851   u16 nEntryTotal;
7852   u32 nSize;
7853   u32 iOffset;
7854 };
7855 
7856 /*
7857 *** 4.3.12  Central directory structure:
7858 ***
7859 *** ...
7860 ***
7861 ***   central file header signature   4 bytes  (0x02014b50)
7862 ***   version made by                 2 bytes
7863 ***   version needed to extract       2 bytes
7864 ***   general purpose bit flag        2 bytes
7865 ***   compression method              2 bytes
7866 ***   last mod file time              2 bytes
7867 ***   last mod file date              2 bytes
7868 ***   crc-32                          4 bytes
7869 ***   compressed size                 4 bytes
7870 ***   uncompressed size               4 bytes
7871 ***   file name length                2 bytes
7872 ***   extra field length              2 bytes
7873 ***   file comment length             2 bytes
7874 ***   disk number start               2 bytes
7875 ***   internal file attributes        2 bytes
7876 ***   external file attributes        4 bytes
7877 ***   relative offset of local header 4 bytes
7878 */
7879 typedef struct ZipfileCDS ZipfileCDS;
7880 struct ZipfileCDS {
7881   u16 iVersionMadeBy;
7882   u16 iVersionExtract;
7883   u16 flags;
7884   u16 iCompression;
7885   u16 mTime;
7886   u16 mDate;
7887   u32 crc32;
7888   u32 szCompressed;
7889   u32 szUncompressed;
7890   u16 nFile;
7891   u16 nExtra;
7892   u16 nComment;
7893   u16 iDiskStart;
7894   u16 iInternalAttr;
7895   u32 iExternalAttr;
7896   u32 iOffset;
7897   char *zFile;                    /* Filename (sqlite3_malloc()) */
7898 };
7899 
7900 /*
7901 *** 4.3.7  Local file header:
7902 ***
7903 ***   local file header signature     4 bytes  (0x04034b50)
7904 ***   version needed to extract       2 bytes
7905 ***   general purpose bit flag        2 bytes
7906 ***   compression method              2 bytes
7907 ***   last mod file time              2 bytes
7908 ***   last mod file date              2 bytes
7909 ***   crc-32                          4 bytes
7910 ***   compressed size                 4 bytes
7911 ***   uncompressed size               4 bytes
7912 ***   file name length                2 bytes
7913 ***   extra field length              2 bytes
7914 ***
7915 */
7916 typedef struct ZipfileLFH ZipfileLFH;
7917 struct ZipfileLFH {
7918   u16 iVersionExtract;
7919   u16 flags;
7920   u16 iCompression;
7921   u16 mTime;
7922   u16 mDate;
7923   u32 crc32;
7924   u32 szCompressed;
7925   u32 szUncompressed;
7926   u16 nFile;
7927   u16 nExtra;
7928 };
7929 
7930 typedef struct ZipfileEntry ZipfileEntry;
7931 struct ZipfileEntry {
7932   ZipfileCDS cds;            /* Parsed CDS record */
7933   u32 mUnixTime;             /* Modification time, in UNIX format */
7934   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
7935   i64 iDataOff;              /* Offset to data in file (if aData==0) */
7936   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
7937   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
7938 };
7939 
7940 /*
7941 ** Cursor type for zipfile tables.
7942 */
7943 typedef struct ZipfileCsr ZipfileCsr;
7944 struct ZipfileCsr {
7945   sqlite3_vtab_cursor base;  /* Base class - must be first */
7946   i64 iId;                   /* Cursor ID */
7947   u8 bEof;                   /* True when at EOF */
7948   u8 bNoop;                  /* If next xNext() call is no-op */
7949 
7950   /* Used outside of write transactions */
7951   FILE *pFile;               /* Zip file */
7952   i64 iNextOff;              /* Offset of next record in central directory */
7953   ZipfileEOCD eocd;          /* Parse of central directory record */
7954 
7955   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
7956   ZipfileEntry *pCurrent;    /* Current entry */
7957   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
7958 };
7959 
7960 typedef struct ZipfileTab ZipfileTab;
7961 struct ZipfileTab {
7962   sqlite3_vtab base;         /* Base class - must be first */
7963   char *zFile;               /* Zip file this table accesses (may be NULL) */
7964   sqlite3 *db;               /* Host database connection */
7965   u8 *aBuffer;               /* Temporary buffer used for various tasks */
7966 
7967   ZipfileCsr *pCsrList;      /* List of cursors */
7968   i64 iNextCsrid;
7969 
7970   /* The following are used by write transactions only */
7971   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
7972   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
7973   FILE *pWriteFd;            /* File handle open on zip archive */
7974   i64 szCurrent;             /* Current size of zip archive */
7975   i64 szOrig;                /* Size of archive at start of transaction */
7976 };
7977 
7978 /*
7979 ** Set the error message contained in context ctx to the results of
7980 ** vprintf(zFmt, ...).
7981 */
7982 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7983   char *zMsg = 0;
7984   va_list ap;
7985   va_start(ap, zFmt);
7986   zMsg = sqlite3_vmprintf(zFmt, ap);
7987   sqlite3_result_error(ctx, zMsg, -1);
7988   sqlite3_free(zMsg);
7989   va_end(ap);
7990 }
7991 
7992 /*
7993 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
7994 ** is not quoted, do nothing.
7995 */
7996 static void zipfileDequote(char *zIn){
7997   char q = zIn[0];
7998   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
7999     int iIn = 1;
8000     int iOut = 0;
8001     if( q=='[' ) q = ']';
8002     while( ALWAYS(zIn[iIn]) ){
8003       char c = zIn[iIn++];
8004       if( c==q && zIn[iIn++]!=q ) break;
8005       zIn[iOut++] = c;
8006     }
8007     zIn[iOut] = '\0';
8008   }
8009 }
8010 
8011 /*
8012 ** Construct a new ZipfileTab virtual table object.
8013 **
8014 **   argv[0]   -> module name  ("zipfile")
8015 **   argv[1]   -> database name
8016 **   argv[2]   -> table name
8017 **   argv[...] -> "column name" and other module argument fields.
8018 */
8019 static int zipfileConnect(
8020   sqlite3 *db,
8021   void *pAux,
8022   int argc, const char *const*argv,
8023   sqlite3_vtab **ppVtab,
8024   char **pzErr
8025 ){
8026   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
8027   int nFile = 0;
8028   const char *zFile = 0;
8029   ZipfileTab *pNew = 0;
8030   int rc;
8031   (void)pAux;
8032 
8033   /* If the table name is not "zipfile", require that the argument be
8034   ** specified. This stops zipfile tables from being created as:
8035   **
8036   **   CREATE VIRTUAL TABLE zzz USING zipfile();
8037   **
8038   ** It does not prevent:
8039   **
8040   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
8041   */
8042   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
8043   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
8044     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
8045     return SQLITE_ERROR;
8046   }
8047 
8048   if( argc>3 ){
8049     zFile = argv[3];
8050     nFile = (int)strlen(zFile)+1;
8051   }
8052 
8053   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
8054   if( rc==SQLITE_OK ){
8055     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
8056     if( pNew==0 ) return SQLITE_NOMEM;
8057     memset(pNew, 0, nByte+nFile);
8058     pNew->db = db;
8059     pNew->aBuffer = (u8*)&pNew[1];
8060     if( zFile ){
8061       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
8062       memcpy(pNew->zFile, zFile, nFile);
8063       zipfileDequote(pNew->zFile);
8064     }
8065   }
8066   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
8067   *ppVtab = (sqlite3_vtab*)pNew;
8068   return rc;
8069 }
8070 
8071 /*
8072 ** Free the ZipfileEntry structure indicated by the only argument.
8073 */
8074 static void zipfileEntryFree(ZipfileEntry *p){
8075   if( p ){
8076     sqlite3_free(p->cds.zFile);
8077     sqlite3_free(p);
8078   }
8079 }
8080 
8081 /*
8082 ** Release resources that should be freed at the end of a write
8083 ** transaction.
8084 */
8085 static void zipfileCleanupTransaction(ZipfileTab *pTab){
8086   ZipfileEntry *pEntry;
8087   ZipfileEntry *pNext;
8088 
8089   if( pTab->pWriteFd ){
8090     fclose(pTab->pWriteFd);
8091     pTab->pWriteFd = 0;
8092   }
8093   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
8094     pNext = pEntry->pNext;
8095     zipfileEntryFree(pEntry);
8096   }
8097   pTab->pFirstEntry = 0;
8098   pTab->pLastEntry = 0;
8099   pTab->szCurrent = 0;
8100   pTab->szOrig = 0;
8101 }
8102 
8103 /*
8104 ** This method is the destructor for zipfile vtab objects.
8105 */
8106 static int zipfileDisconnect(sqlite3_vtab *pVtab){
8107   zipfileCleanupTransaction((ZipfileTab*)pVtab);
8108   sqlite3_free(pVtab);
8109   return SQLITE_OK;
8110 }
8111 
8112 /*
8113 ** Constructor for a new ZipfileCsr object.
8114 */
8115 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
8116   ZipfileTab *pTab = (ZipfileTab*)p;
8117   ZipfileCsr *pCsr;
8118   pCsr = sqlite3_malloc(sizeof(*pCsr));
8119   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
8120   if( pCsr==0 ){
8121     return SQLITE_NOMEM;
8122   }
8123   memset(pCsr, 0, sizeof(*pCsr));
8124   pCsr->iId = ++pTab->iNextCsrid;
8125   pCsr->pCsrNext = pTab->pCsrList;
8126   pTab->pCsrList = pCsr;
8127   return SQLITE_OK;
8128 }
8129 
8130 /*
8131 ** Reset a cursor back to the state it was in when first returned
8132 ** by zipfileOpen().
8133 */
8134 static void zipfileResetCursor(ZipfileCsr *pCsr){
8135   ZipfileEntry *p;
8136   ZipfileEntry *pNext;
8137 
8138   pCsr->bEof = 0;
8139   if( pCsr->pFile ){
8140     fclose(pCsr->pFile);
8141     pCsr->pFile = 0;
8142     zipfileEntryFree(pCsr->pCurrent);
8143     pCsr->pCurrent = 0;
8144   }
8145 
8146   for(p=pCsr->pFreeEntry; p; p=pNext){
8147     pNext = p->pNext;
8148     zipfileEntryFree(p);
8149   }
8150 }
8151 
8152 /*
8153 ** Destructor for an ZipfileCsr.
8154 */
8155 static int zipfileClose(sqlite3_vtab_cursor *cur){
8156   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8157   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
8158   ZipfileCsr **pp;
8159   zipfileResetCursor(pCsr);
8160 
8161   /* Remove this cursor from the ZipfileTab.pCsrList list. */
8162   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
8163   *pp = pCsr->pCsrNext;
8164 
8165   sqlite3_free(pCsr);
8166   return SQLITE_OK;
8167 }
8168 
8169 /*
8170 ** Set the error message for the virtual table associated with cursor
8171 ** pCsr to the results of vprintf(zFmt, ...).
8172 */
8173 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
8174   va_list ap;
8175   va_start(ap, zFmt);
8176   sqlite3_free(pTab->base.zErrMsg);
8177   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
8178   va_end(ap);
8179 }
8180 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
8181   va_list ap;
8182   va_start(ap, zFmt);
8183   sqlite3_free(pCsr->base.pVtab->zErrMsg);
8184   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
8185   va_end(ap);
8186 }
8187 
8188 /*
8189 ** Read nRead bytes of data from offset iOff of file pFile into buffer
8190 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
8191 ** otherwise.
8192 **
8193 ** If an error does occur, output variable (*pzErrmsg) may be set to point
8194 ** to an English language error message. It is the responsibility of the
8195 ** caller to eventually free this buffer using
8196 ** sqlite3_free().
8197 */
8198 static int zipfileReadData(
8199   FILE *pFile,                    /* Read from this file */
8200   u8 *aRead,                      /* Read into this buffer */
8201   int nRead,                      /* Number of bytes to read */
8202   i64 iOff,                       /* Offset to read from */
8203   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
8204 ){
8205   size_t n;
8206   fseek(pFile, (long)iOff, SEEK_SET);
8207   n = fread(aRead, 1, nRead, pFile);
8208   if( (int)n!=nRead ){
8209     *pzErrmsg = sqlite3_mprintf("error in fread()");
8210     return SQLITE_ERROR;
8211   }
8212   return SQLITE_OK;
8213 }
8214 
8215 static int zipfileAppendData(
8216   ZipfileTab *pTab,
8217   const u8 *aWrite,
8218   int nWrite
8219 ){
8220   if( nWrite>0 ){
8221     size_t n = nWrite;
8222     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
8223     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
8224     if( (int)n!=nWrite ){
8225       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
8226       return SQLITE_ERROR;
8227     }
8228     pTab->szCurrent += nWrite;
8229   }
8230   return SQLITE_OK;
8231 }
8232 
8233 /*
8234 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
8235 */
8236 static u16 zipfileGetU16(const u8 *aBuf){
8237   return (aBuf[1] << 8) + aBuf[0];
8238 }
8239 
8240 /*
8241 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
8242 */
8243 static u32 zipfileGetU32(const u8 *aBuf){
8244   if( aBuf==0 ) return 0;
8245   return ((u32)(aBuf[3]) << 24)
8246        + ((u32)(aBuf[2]) << 16)
8247        + ((u32)(aBuf[1]) <<  8)
8248        + ((u32)(aBuf[0]) <<  0);
8249 }
8250 
8251 /*
8252 ** Write a 16-bit little endiate integer into buffer aBuf.
8253 */
8254 static void zipfilePutU16(u8 *aBuf, u16 val){
8255   aBuf[0] = val & 0xFF;
8256   aBuf[1] = (val>>8) & 0xFF;
8257 }
8258 
8259 /*
8260 ** Write a 32-bit little endiate integer into buffer aBuf.
8261 */
8262 static void zipfilePutU32(u8 *aBuf, u32 val){
8263   aBuf[0] = val & 0xFF;
8264   aBuf[1] = (val>>8) & 0xFF;
8265   aBuf[2] = (val>>16) & 0xFF;
8266   aBuf[3] = (val>>24) & 0xFF;
8267 }
8268 
8269 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
8270 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
8271 
8272 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
8273 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
8274 
8275 /*
8276 ** Magic numbers used to read CDS records.
8277 */
8278 #define ZIPFILE_CDS_NFILE_OFF        28
8279 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
8280 
8281 /*
8282 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
8283 ** if the record is not well-formed, or SQLITE_OK otherwise.
8284 */
8285 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
8286   u8 *aRead = aBuf;
8287   u32 sig = zipfileRead32(aRead);
8288   int rc = SQLITE_OK;
8289   if( sig!=ZIPFILE_SIGNATURE_CDS ){
8290     rc = SQLITE_ERROR;
8291   }else{
8292     pCDS->iVersionMadeBy = zipfileRead16(aRead);
8293     pCDS->iVersionExtract = zipfileRead16(aRead);
8294     pCDS->flags = zipfileRead16(aRead);
8295     pCDS->iCompression = zipfileRead16(aRead);
8296     pCDS->mTime = zipfileRead16(aRead);
8297     pCDS->mDate = zipfileRead16(aRead);
8298     pCDS->crc32 = zipfileRead32(aRead);
8299     pCDS->szCompressed = zipfileRead32(aRead);
8300     pCDS->szUncompressed = zipfileRead32(aRead);
8301     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
8302     pCDS->nFile = zipfileRead16(aRead);
8303     pCDS->nExtra = zipfileRead16(aRead);
8304     pCDS->nComment = zipfileRead16(aRead);
8305     pCDS->iDiskStart = zipfileRead16(aRead);
8306     pCDS->iInternalAttr = zipfileRead16(aRead);
8307     pCDS->iExternalAttr = zipfileRead32(aRead);
8308     pCDS->iOffset = zipfileRead32(aRead);
8309     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
8310   }
8311 
8312   return rc;
8313 }
8314 
8315 /*
8316 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
8317 ** if the record is not well-formed, or SQLITE_OK otherwise.
8318 */
8319 static int zipfileReadLFH(
8320   u8 *aBuffer,
8321   ZipfileLFH *pLFH
8322 ){
8323   u8 *aRead = aBuffer;
8324   int rc = SQLITE_OK;
8325 
8326   u32 sig = zipfileRead32(aRead);
8327   if( sig!=ZIPFILE_SIGNATURE_LFH ){
8328     rc = SQLITE_ERROR;
8329   }else{
8330     pLFH->iVersionExtract = zipfileRead16(aRead);
8331     pLFH->flags = zipfileRead16(aRead);
8332     pLFH->iCompression = zipfileRead16(aRead);
8333     pLFH->mTime = zipfileRead16(aRead);
8334     pLFH->mDate = zipfileRead16(aRead);
8335     pLFH->crc32 = zipfileRead32(aRead);
8336     pLFH->szCompressed = zipfileRead32(aRead);
8337     pLFH->szUncompressed = zipfileRead32(aRead);
8338     pLFH->nFile = zipfileRead16(aRead);
8339     pLFH->nExtra = zipfileRead16(aRead);
8340   }
8341   return rc;
8342 }
8343 
8344 
8345 /*
8346 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
8347 ** Scan through this buffer to find an "extra-timestamp" field. If one
8348 ** exists, extract the 32-bit modification-timestamp from it and store
8349 ** the value in output parameter *pmTime.
8350 **
8351 ** Zero is returned if no extra-timestamp record could be found (and so
8352 ** *pmTime is left unchanged), or non-zero otherwise.
8353 **
8354 ** The general format of an extra field is:
8355 **
8356 **   Header ID    2 bytes
8357 **   Data Size    2 bytes
8358 **   Data         N bytes
8359 */
8360 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
8361   int ret = 0;
8362   u8 *p = aExtra;
8363   u8 *pEnd = &aExtra[nExtra];
8364 
8365   while( p<pEnd ){
8366     u16 id = zipfileRead16(p);
8367     u16 nByte = zipfileRead16(p);
8368 
8369     switch( id ){
8370       case ZIPFILE_EXTRA_TIMESTAMP: {
8371         u8 b = p[0];
8372         if( b & 0x01 ){     /* 0x01 -> modtime is present */
8373           *pmTime = zipfileGetU32(&p[1]);
8374           ret = 1;
8375         }
8376         break;
8377       }
8378     }
8379 
8380     p += nByte;
8381   }
8382   return ret;
8383 }
8384 
8385 /*
8386 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
8387 ** fields of the CDS structure passed as the only argument to a 32-bit
8388 ** UNIX seconds-since-the-epoch timestamp. Return the result.
8389 **
8390 ** "Standard" MS-DOS time format:
8391 **
8392 **   File modification time:
8393 **     Bits 00-04: seconds divided by 2
8394 **     Bits 05-10: minute
8395 **     Bits 11-15: hour
8396 **   File modification date:
8397 **     Bits 00-04: day
8398 **     Bits 05-08: month (1-12)
8399 **     Bits 09-15: years from 1980
8400 **
8401 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
8402 */
8403 static u32 zipfileMtime(ZipfileCDS *pCDS){
8404   int Y,M,D,X1,X2,A,B,sec,min,hr;
8405   i64 JDsec;
8406   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
8407   M = ((pCDS->mDate >> 5) & 0x0F);
8408   D = (pCDS->mDate & 0x1F);
8409   sec = (pCDS->mTime & 0x1F)*2;
8410   min = (pCDS->mTime >> 5) & 0x3F;
8411   hr = (pCDS->mTime >> 11) & 0x1F;
8412   if( M<=2 ){
8413     Y--;
8414     M += 12;
8415   }
8416   X1 = 36525*(Y+4716)/100;
8417   X2 = 306001*(M+1)/10000;
8418   A = Y/100;
8419   B = 2 - A + (A/4);
8420   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
8421   return (u32)(JDsec - (i64)24405875*(i64)8640);
8422 }
8423 
8424 /*
8425 ** The opposite of zipfileMtime(). This function populates the mTime and
8426 ** mDate fields of the CDS structure passed as the first argument according
8427 ** to the UNIX timestamp value passed as the second.
8428 */
8429 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
8430   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
8431   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
8432 
8433   int A, B, C, D, E;
8434   int yr, mon, day;
8435   int hr, min, sec;
8436 
8437   A = (int)((JD - 1867216.25)/36524.25);
8438   A = (int)(JD + 1 + A - (A/4));
8439   B = A + 1524;
8440   C = (int)((B - 122.1)/365.25);
8441   D = (36525*(C&32767))/100;
8442   E = (int)((B-D)/30.6001);
8443 
8444   day = B - D - (int)(30.6001*E);
8445   mon = (E<14 ? E-1 : E-13);
8446   yr = mon>2 ? C-4716 : C-4715;
8447 
8448   hr = (mUnixTime % (24*60*60)) / (60*60);
8449   min = (mUnixTime % (60*60)) / 60;
8450   sec = (mUnixTime % 60);
8451 
8452   if( yr>=1980 ){
8453     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
8454     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
8455   }else{
8456     pCds->mDate = pCds->mTime = 0;
8457   }
8458 
8459   assert( mUnixTime<315507600
8460        || mUnixTime==zipfileMtime(pCds)
8461        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
8462        /* || (mUnixTime % 2) */
8463   );
8464 }
8465 
8466 /*
8467 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
8468 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
8469 ** then pFile is a file-handle open on a zip file. In either case, this
8470 ** function creates a ZipfileEntry object based on the zip archive entry
8471 ** for which the CDS record is at offset iOff.
8472 **
8473 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
8474 ** the new object. Otherwise, an SQLite error code is returned and the
8475 ** final value of (*ppEntry) undefined.
8476 */
8477 static int zipfileGetEntry(
8478   ZipfileTab *pTab,               /* Store any error message here */
8479   const u8 *aBlob,                /* Pointer to in-memory file image */
8480   int nBlob,                      /* Size of aBlob[] in bytes */
8481   FILE *pFile,                    /* If aBlob==0, read from this file */
8482   i64 iOff,                       /* Offset of CDS record */
8483   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
8484 ){
8485   u8 *aRead;
8486   char **pzErr = &pTab->base.zErrMsg;
8487   int rc = SQLITE_OK;
8488   (void)nBlob;
8489 
8490   if( aBlob==0 ){
8491     aRead = pTab->aBuffer;
8492     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
8493   }else{
8494     aRead = (u8*)&aBlob[iOff];
8495   }
8496 
8497   if( rc==SQLITE_OK ){
8498     sqlite3_int64 nAlloc;
8499     ZipfileEntry *pNew;
8500 
8501     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
8502     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
8503     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
8504 
8505     nAlloc = sizeof(ZipfileEntry) + nExtra;
8506     if( aBlob ){
8507       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
8508     }
8509 
8510     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
8511     if( pNew==0 ){
8512       rc = SQLITE_NOMEM;
8513     }else{
8514       memset(pNew, 0, sizeof(ZipfileEntry));
8515       rc = zipfileReadCDS(aRead, &pNew->cds);
8516       if( rc!=SQLITE_OK ){
8517         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
8518       }else if( aBlob==0 ){
8519         rc = zipfileReadData(
8520             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
8521         );
8522       }else{
8523         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
8524       }
8525     }
8526 
8527     if( rc==SQLITE_OK ){
8528       u32 *pt = &pNew->mUnixTime;
8529       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
8530       pNew->aExtra = (u8*)&pNew[1];
8531       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
8532       if( pNew->cds.zFile==0 ){
8533         rc = SQLITE_NOMEM;
8534       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
8535         pNew->mUnixTime = zipfileMtime(&pNew->cds);
8536       }
8537     }
8538 
8539     if( rc==SQLITE_OK ){
8540       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
8541       ZipfileLFH lfh;
8542       if( pFile ){
8543         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
8544       }else{
8545         aRead = (u8*)&aBlob[pNew->cds.iOffset];
8546       }
8547 
8548       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
8549       if( rc==SQLITE_OK ){
8550         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
8551         pNew->iDataOff += lfh.nFile + lfh.nExtra;
8552         if( aBlob && pNew->cds.szCompressed ){
8553           pNew->aData = &pNew->aExtra[nExtra];
8554           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
8555         }
8556       }else{
8557         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
8558             (int)pNew->cds.iOffset
8559         );
8560       }
8561     }
8562 
8563     if( rc!=SQLITE_OK ){
8564       zipfileEntryFree(pNew);
8565     }else{
8566       *ppEntry = pNew;
8567     }
8568   }
8569 
8570   return rc;
8571 }
8572 
8573 /*
8574 ** Advance an ZipfileCsr to its next row of output.
8575 */
8576 static int zipfileNext(sqlite3_vtab_cursor *cur){
8577   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8578   int rc = SQLITE_OK;
8579 
8580   if( pCsr->pFile ){
8581     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
8582     zipfileEntryFree(pCsr->pCurrent);
8583     pCsr->pCurrent = 0;
8584     if( pCsr->iNextOff>=iEof ){
8585       pCsr->bEof = 1;
8586     }else{
8587       ZipfileEntry *p = 0;
8588       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
8589       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
8590       if( rc==SQLITE_OK ){
8591         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
8592         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
8593       }
8594       pCsr->pCurrent = p;
8595     }
8596   }else{
8597     if( !pCsr->bNoop ){
8598       pCsr->pCurrent = pCsr->pCurrent->pNext;
8599     }
8600     if( pCsr->pCurrent==0 ){
8601       pCsr->bEof = 1;
8602     }
8603   }
8604 
8605   pCsr->bNoop = 0;
8606   return rc;
8607 }
8608 
8609 static void zipfileFree(void *p) {
8610   sqlite3_free(p);
8611 }
8612 
8613 /*
8614 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
8615 ** size is nOut bytes. This function uncompresses the data and sets the
8616 ** return value in context pCtx to the result (a blob).
8617 **
8618 ** If an error occurs, an error code is left in pCtx instead.
8619 */
8620 static void zipfileInflate(
8621   sqlite3_context *pCtx,          /* Store result here */
8622   const u8 *aIn,                  /* Compressed data */
8623   int nIn,                        /* Size of buffer aIn[] in bytes */
8624   int nOut                        /* Expected output size */
8625 ){
8626   u8 *aRes = sqlite3_malloc(nOut);
8627   if( aRes==0 ){
8628     sqlite3_result_error_nomem(pCtx);
8629   }else{
8630     int err;
8631     z_stream str;
8632     memset(&str, 0, sizeof(str));
8633 
8634     str.next_in = (Byte*)aIn;
8635     str.avail_in = nIn;
8636     str.next_out = (Byte*)aRes;
8637     str.avail_out = nOut;
8638 
8639     err = inflateInit2(&str, -15);
8640     if( err!=Z_OK ){
8641       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
8642     }else{
8643       err = inflate(&str, Z_NO_FLUSH);
8644       if( err!=Z_STREAM_END ){
8645         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
8646       }else{
8647         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
8648         aRes = 0;
8649       }
8650     }
8651     sqlite3_free(aRes);
8652     inflateEnd(&str);
8653   }
8654 }
8655 
8656 /*
8657 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
8658 ** compresses it and sets (*ppOut) to point to a buffer containing the
8659 ** compressed data. The caller is responsible for eventually calling
8660 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
8661 ** is set to the size of buffer (*ppOut) in bytes.
8662 **
8663 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
8664 ** code is returned and an error message left in virtual-table handle
8665 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
8666 ** case.
8667 */
8668 static int zipfileDeflate(
8669   const u8 *aIn, int nIn,         /* Input */
8670   u8 **ppOut, int *pnOut,         /* Output */
8671   char **pzErr                    /* OUT: Error message */
8672 ){
8673   int rc = SQLITE_OK;
8674   sqlite3_int64 nAlloc;
8675   z_stream str;
8676   u8 *aOut;
8677 
8678   memset(&str, 0, sizeof(str));
8679   str.next_in = (Bytef*)aIn;
8680   str.avail_in = nIn;
8681   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
8682 
8683   nAlloc = deflateBound(&str, nIn);
8684   aOut = (u8*)sqlite3_malloc64(nAlloc);
8685   if( aOut==0 ){
8686     rc = SQLITE_NOMEM;
8687   }else{
8688     int res;
8689     str.next_out = aOut;
8690     str.avail_out = nAlloc;
8691     res = deflate(&str, Z_FINISH);
8692     if( res==Z_STREAM_END ){
8693       *ppOut = aOut;
8694       *pnOut = (int)str.total_out;
8695     }else{
8696       sqlite3_free(aOut);
8697       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
8698       rc = SQLITE_ERROR;
8699     }
8700     deflateEnd(&str);
8701   }
8702 
8703   return rc;
8704 }
8705 
8706 
8707 /*
8708 ** Return values of columns for the row at which the series_cursor
8709 ** is currently pointing.
8710 */
8711 static int zipfileColumn(
8712   sqlite3_vtab_cursor *cur,   /* The cursor */
8713   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8714   int i                       /* Which column to return */
8715 ){
8716   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8717   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
8718   int rc = SQLITE_OK;
8719   switch( i ){
8720     case 0:   /* name */
8721       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
8722       break;
8723     case 1:   /* mode */
8724       /* TODO: Whether or not the following is correct surely depends on
8725       ** the platform on which the archive was created.  */
8726       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
8727       break;
8728     case 2: { /* mtime */
8729       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
8730       break;
8731     }
8732     case 3: { /* sz */
8733       if( sqlite3_vtab_nochange(ctx)==0 ){
8734         sqlite3_result_int64(ctx, pCDS->szUncompressed);
8735       }
8736       break;
8737     }
8738     case 4:   /* rawdata */
8739       if( sqlite3_vtab_nochange(ctx) ) break;
8740     case 5: { /* data */
8741       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
8742         int sz = pCDS->szCompressed;
8743         int szFinal = pCDS->szUncompressed;
8744         if( szFinal>0 ){
8745           u8 *aBuf;
8746           u8 *aFree = 0;
8747           if( pCsr->pCurrent->aData ){
8748             aBuf = pCsr->pCurrent->aData;
8749           }else{
8750             aBuf = aFree = sqlite3_malloc64(sz);
8751             if( aBuf==0 ){
8752               rc = SQLITE_NOMEM;
8753             }else{
8754               FILE *pFile = pCsr->pFile;
8755               if( pFile==0 ){
8756                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
8757               }
8758               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
8759                   &pCsr->base.pVtab->zErrMsg
8760               );
8761             }
8762           }
8763           if( rc==SQLITE_OK ){
8764             if( i==5 && pCDS->iCompression ){
8765               zipfileInflate(ctx, aBuf, sz, szFinal);
8766             }else{
8767               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
8768             }
8769           }
8770           sqlite3_free(aFree);
8771         }else{
8772           /* Figure out if this is a directory or a zero-sized file. Consider
8773           ** it to be a directory either if the mode suggests so, or if
8774           ** the final character in the name is '/'.  */
8775           u32 mode = pCDS->iExternalAttr >> 16;
8776           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
8777             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
8778           }
8779         }
8780       }
8781       break;
8782     }
8783     case 6:   /* method */
8784       sqlite3_result_int(ctx, pCDS->iCompression);
8785       break;
8786     default:  /* z */
8787       assert( i==7 );
8788       sqlite3_result_int64(ctx, pCsr->iId);
8789       break;
8790   }
8791 
8792   return rc;
8793 }
8794 
8795 /*
8796 ** Return TRUE if the cursor is at EOF.
8797 */
8798 static int zipfileEof(sqlite3_vtab_cursor *cur){
8799   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8800   return pCsr->bEof;
8801 }
8802 
8803 /*
8804 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
8805 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
8806 ** is guaranteed to be a file-handle open on a zip file.
8807 **
8808 ** This function attempts to locate the EOCD record within the zip archive
8809 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
8810 ** returned if successful. Otherwise, an SQLite error code is returned and
8811 ** an English language error message may be left in virtual-table pTab.
8812 */
8813 static int zipfileReadEOCD(
8814   ZipfileTab *pTab,               /* Return errors here */
8815   const u8 *aBlob,                /* Pointer to in-memory file image */
8816   int nBlob,                      /* Size of aBlob[] in bytes */
8817   FILE *pFile,                    /* Read from this file if aBlob==0 */
8818   ZipfileEOCD *pEOCD              /* Object to populate */
8819 ){
8820   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
8821   int nRead;                      /* Bytes to read from file */
8822   int rc = SQLITE_OK;
8823 
8824   memset(pEOCD, 0, sizeof(ZipfileEOCD));
8825   if( aBlob==0 ){
8826     i64 iOff;                     /* Offset to read from */
8827     i64 szFile;                   /* Total size of file in bytes */
8828     fseek(pFile, 0, SEEK_END);
8829     szFile = (i64)ftell(pFile);
8830     if( szFile==0 ){
8831       return SQLITE_OK;
8832     }
8833     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
8834     iOff = szFile - nRead;
8835     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
8836   }else{
8837     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
8838     aRead = (u8*)&aBlob[nBlob-nRead];
8839   }
8840 
8841   if( rc==SQLITE_OK ){
8842     int i;
8843 
8844     /* Scan backwards looking for the signature bytes */
8845     for(i=nRead-20; i>=0; i--){
8846       if( aRead[i]==0x50 && aRead[i+1]==0x4b
8847        && aRead[i+2]==0x05 && aRead[i+3]==0x06
8848       ){
8849         break;
8850       }
8851     }
8852     if( i<0 ){
8853       pTab->base.zErrMsg = sqlite3_mprintf(
8854           "cannot find end of central directory record"
8855       );
8856       return SQLITE_ERROR;
8857     }
8858 
8859     aRead += i+4;
8860     pEOCD->iDisk = zipfileRead16(aRead);
8861     pEOCD->iFirstDisk = zipfileRead16(aRead);
8862     pEOCD->nEntry = zipfileRead16(aRead);
8863     pEOCD->nEntryTotal = zipfileRead16(aRead);
8864     pEOCD->nSize = zipfileRead32(aRead);
8865     pEOCD->iOffset = zipfileRead32(aRead);
8866   }
8867 
8868   return rc;
8869 }
8870 
8871 /*
8872 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
8873 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
8874 ** to the end of the list. Otherwise, it is added to the list immediately
8875 ** before pBefore (which is guaranteed to be a part of said list).
8876 */
8877 static void zipfileAddEntry(
8878   ZipfileTab *pTab,
8879   ZipfileEntry *pBefore,
8880   ZipfileEntry *pNew
8881 ){
8882   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
8883   assert( pNew->pNext==0 );
8884   if( pBefore==0 ){
8885     if( pTab->pFirstEntry==0 ){
8886       pTab->pFirstEntry = pTab->pLastEntry = pNew;
8887     }else{
8888       assert( pTab->pLastEntry->pNext==0 );
8889       pTab->pLastEntry->pNext = pNew;
8890       pTab->pLastEntry = pNew;
8891     }
8892   }else{
8893     ZipfileEntry **pp;
8894     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
8895     pNew->pNext = pBefore;
8896     *pp = pNew;
8897   }
8898 }
8899 
8900 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
8901   ZipfileEOCD eocd;
8902   int rc;
8903   int i;
8904   i64 iOff;
8905 
8906   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
8907   iOff = eocd.iOffset;
8908   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
8909     ZipfileEntry *pNew = 0;
8910     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
8911 
8912     if( rc==SQLITE_OK ){
8913       zipfileAddEntry(pTab, 0, pNew);
8914       iOff += ZIPFILE_CDS_FIXED_SZ;
8915       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
8916     }
8917   }
8918   return rc;
8919 }
8920 
8921 /*
8922 ** xFilter callback.
8923 */
8924 static int zipfileFilter(
8925   sqlite3_vtab_cursor *cur,
8926   int idxNum, const char *idxStr,
8927   int argc, sqlite3_value **argv
8928 ){
8929   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
8930   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8931   const char *zFile = 0;          /* Zip file to scan */
8932   int rc = SQLITE_OK;             /* Return Code */
8933   int bInMemory = 0;              /* True for an in-memory zipfile */
8934 
8935   (void)idxStr;
8936   (void)argc;
8937 
8938   zipfileResetCursor(pCsr);
8939 
8940   if( pTab->zFile ){
8941     zFile = pTab->zFile;
8942   }else if( idxNum==0 ){
8943     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
8944     return SQLITE_ERROR;
8945   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
8946     static const u8 aEmptyBlob = 0;
8947     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
8948     int nBlob = sqlite3_value_bytes(argv[0]);
8949     assert( pTab->pFirstEntry==0 );
8950     if( aBlob==0 ){
8951       aBlob = &aEmptyBlob;
8952       nBlob = 0;
8953     }
8954     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
8955     pCsr->pFreeEntry = pTab->pFirstEntry;
8956     pTab->pFirstEntry = pTab->pLastEntry = 0;
8957     if( rc!=SQLITE_OK ) return rc;
8958     bInMemory = 1;
8959   }else{
8960     zFile = (const char*)sqlite3_value_text(argv[0]);
8961   }
8962 
8963   if( 0==pTab->pWriteFd && 0==bInMemory ){
8964     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
8965     if( pCsr->pFile==0 ){
8966       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
8967       rc = SQLITE_ERROR;
8968     }else{
8969       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
8970       if( rc==SQLITE_OK ){
8971         if( pCsr->eocd.nEntry==0 ){
8972           pCsr->bEof = 1;
8973         }else{
8974           pCsr->iNextOff = pCsr->eocd.iOffset;
8975           rc = zipfileNext(cur);
8976         }
8977       }
8978     }
8979   }else{
8980     pCsr->bNoop = 1;
8981     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
8982     rc = zipfileNext(cur);
8983   }
8984 
8985   return rc;
8986 }
8987 
8988 /*
8989 ** xBestIndex callback.
8990 */
8991 static int zipfileBestIndex(
8992   sqlite3_vtab *tab,
8993   sqlite3_index_info *pIdxInfo
8994 ){
8995   int i;
8996   int idx = -1;
8997   int unusable = 0;
8998   (void)tab;
8999 
9000   for(i=0; i<pIdxInfo->nConstraint; i++){
9001     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
9002     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
9003     if( pCons->usable==0 ){
9004       unusable = 1;
9005     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9006       idx = i;
9007     }
9008   }
9009   pIdxInfo->estimatedCost = 1000.0;
9010   if( idx>=0 ){
9011     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
9012     pIdxInfo->aConstraintUsage[idx].omit = 1;
9013     pIdxInfo->idxNum = 1;
9014   }else if( unusable ){
9015     return SQLITE_CONSTRAINT;
9016   }
9017   return SQLITE_OK;
9018 }
9019 
9020 static ZipfileEntry *zipfileNewEntry(const char *zPath){
9021   ZipfileEntry *pNew;
9022   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
9023   if( pNew ){
9024     memset(pNew, 0, sizeof(ZipfileEntry));
9025     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
9026     if( pNew->cds.zFile==0 ){
9027       sqlite3_free(pNew);
9028       pNew = 0;
9029     }
9030   }
9031   return pNew;
9032 }
9033 
9034 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
9035   ZipfileCDS *pCds = &pEntry->cds;
9036   u8 *a = aBuf;
9037 
9038   pCds->nExtra = 9;
9039 
9040   /* Write the LFH itself */
9041   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
9042   zipfileWrite16(a, pCds->iVersionExtract);
9043   zipfileWrite16(a, pCds->flags);
9044   zipfileWrite16(a, pCds->iCompression);
9045   zipfileWrite16(a, pCds->mTime);
9046   zipfileWrite16(a, pCds->mDate);
9047   zipfileWrite32(a, pCds->crc32);
9048   zipfileWrite32(a, pCds->szCompressed);
9049   zipfileWrite32(a, pCds->szUncompressed);
9050   zipfileWrite16(a, (u16)pCds->nFile);
9051   zipfileWrite16(a, pCds->nExtra);
9052   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
9053 
9054   /* Add the file name */
9055   memcpy(a, pCds->zFile, (int)pCds->nFile);
9056   a += (int)pCds->nFile;
9057 
9058   /* The "extra" data */
9059   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9060   zipfileWrite16(a, 5);
9061   *a++ = 0x01;
9062   zipfileWrite32(a, pEntry->mUnixTime);
9063 
9064   return a-aBuf;
9065 }
9066 
9067 static int zipfileAppendEntry(
9068   ZipfileTab *pTab,
9069   ZipfileEntry *pEntry,
9070   const u8 *pData,
9071   int nData
9072 ){
9073   u8 *aBuf = pTab->aBuffer;
9074   int nBuf;
9075   int rc;
9076 
9077   nBuf = zipfileSerializeLFH(pEntry, aBuf);
9078   rc = zipfileAppendData(pTab, aBuf, nBuf);
9079   if( rc==SQLITE_OK ){
9080     pEntry->iDataOff = pTab->szCurrent;
9081     rc = zipfileAppendData(pTab, pData, nData);
9082   }
9083 
9084   return rc;
9085 }
9086 
9087 static int zipfileGetMode(
9088   sqlite3_value *pVal,
9089   int bIsDir,                     /* If true, default to directory */
9090   u32 *pMode,                     /* OUT: Mode value */
9091   char **pzErr                    /* OUT: Error message */
9092 ){
9093   const char *z = (const char*)sqlite3_value_text(pVal);
9094   u32 mode = 0;
9095   if( z==0 ){
9096     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
9097   }else if( z[0]>='0' && z[0]<='9' ){
9098     mode = (unsigned int)sqlite3_value_int(pVal);
9099   }else{
9100     const char zTemplate[11] = "-rwxrwxrwx";
9101     int i;
9102     if( strlen(z)!=10 ) goto parse_error;
9103     switch( z[0] ){
9104       case '-': mode |= S_IFREG; break;
9105       case 'd': mode |= S_IFDIR; break;
9106       case 'l': mode |= S_IFLNK; break;
9107       default: goto parse_error;
9108     }
9109     for(i=1; i<10; i++){
9110       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
9111       else if( z[i]!='-' ) goto parse_error;
9112     }
9113   }
9114   if( ((mode & S_IFDIR)==0)==bIsDir ){
9115     /* The "mode" attribute is a directory, but data has been specified.
9116     ** Or vice-versa - no data but "mode" is a file or symlink.  */
9117     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
9118     return SQLITE_CONSTRAINT;
9119   }
9120   *pMode = mode;
9121   return SQLITE_OK;
9122 
9123  parse_error:
9124   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
9125   return SQLITE_ERROR;
9126 }
9127 
9128 /*
9129 ** Both (const char*) arguments point to nul-terminated strings. Argument
9130 ** nB is the value of strlen(zB). This function returns 0 if the strings are
9131 ** identical, ignoring any trailing '/' character in either path.  */
9132 static int zipfileComparePath(const char *zA, const char *zB, int nB){
9133   int nA = (int)strlen(zA);
9134   if( nA>0 && zA[nA-1]=='/' ) nA--;
9135   if( nB>0 && zB[nB-1]=='/' ) nB--;
9136   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
9137   return 1;
9138 }
9139 
9140 static int zipfileBegin(sqlite3_vtab *pVtab){
9141   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9142   int rc = SQLITE_OK;
9143 
9144   assert( pTab->pWriteFd==0 );
9145   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
9146     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
9147     return SQLITE_ERROR;
9148   }
9149 
9150   /* Open a write fd on the file. Also load the entire central directory
9151   ** structure into memory. During the transaction any new file data is
9152   ** appended to the archive file, but the central directory is accumulated
9153   ** in main-memory until the transaction is committed.  */
9154   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
9155   if( pTab->pWriteFd==0 ){
9156     pTab->base.zErrMsg = sqlite3_mprintf(
9157         "zipfile: failed to open file %s for writing", pTab->zFile
9158         );
9159     rc = SQLITE_ERROR;
9160   }else{
9161     fseek(pTab->pWriteFd, 0, SEEK_END);
9162     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
9163     rc = zipfileLoadDirectory(pTab, 0, 0);
9164   }
9165 
9166   if( rc!=SQLITE_OK ){
9167     zipfileCleanupTransaction(pTab);
9168   }
9169 
9170   return rc;
9171 }
9172 
9173 /*
9174 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
9175 ** time(2)).
9176 */
9177 static u32 zipfileTime(void){
9178   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
9179   u32 ret;
9180   if( pVfs==0 ) return 0;
9181   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
9182     i64 ms;
9183     pVfs->xCurrentTimeInt64(pVfs, &ms);
9184     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
9185   }else{
9186     double day;
9187     pVfs->xCurrentTime(pVfs, &day);
9188     ret = (u32)((day - 2440587.5) * 86400);
9189   }
9190   return ret;
9191 }
9192 
9193 /*
9194 ** Return a 32-bit timestamp in UNIX epoch format.
9195 **
9196 ** If the value passed as the only argument is either NULL or an SQL NULL,
9197 ** return the current time. Otherwise, return the value stored in (*pVal)
9198 ** cast to a 32-bit unsigned integer.
9199 */
9200 static u32 zipfileGetTime(sqlite3_value *pVal){
9201   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
9202     return zipfileTime();
9203   }
9204   return (u32)sqlite3_value_int64(pVal);
9205 }
9206 
9207 /*
9208 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
9209 ** linked list.  Remove it from the list and free the object.
9210 */
9211 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
9212   if( pOld ){
9213     ZipfileEntry **pp;
9214     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
9215     *pp = (*pp)->pNext;
9216     zipfileEntryFree(pOld);
9217   }
9218 }
9219 
9220 /*
9221 ** xUpdate method.
9222 */
9223 static int zipfileUpdate(
9224   sqlite3_vtab *pVtab,
9225   int nVal,
9226   sqlite3_value **apVal,
9227   sqlite_int64 *pRowid
9228 ){
9229   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9230   int rc = SQLITE_OK;             /* Return Code */
9231   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
9232 
9233   u32 mode = 0;                   /* Mode for new entry */
9234   u32 mTime = 0;                  /* Modification time for new entry */
9235   i64 sz = 0;                     /* Uncompressed size */
9236   const char *zPath = 0;          /* Path for new entry */
9237   int nPath = 0;                  /* strlen(zPath) */
9238   const u8 *pData = 0;            /* Pointer to buffer containing content */
9239   int nData = 0;                  /* Size of pData buffer in bytes */
9240   int iMethod = 0;                /* Compression method for new entry */
9241   u8 *pFree = 0;                  /* Free this */
9242   char *zFree = 0;                /* Also free this */
9243   ZipfileEntry *pOld = 0;
9244   ZipfileEntry *pOld2 = 0;
9245   int bUpdate = 0;                /* True for an update that modifies "name" */
9246   int bIsDir = 0;
9247   u32 iCrc32 = 0;
9248 
9249   (void)pRowid;
9250 
9251   if( pTab->pWriteFd==0 ){
9252     rc = zipfileBegin(pVtab);
9253     if( rc!=SQLITE_OK ) return rc;
9254   }
9255 
9256   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
9257   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
9258     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
9259     int nDelete = (int)strlen(zDelete);
9260     if( nVal>1 ){
9261       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
9262       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
9263         bUpdate = 1;
9264       }
9265     }
9266     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
9267       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
9268         break;
9269       }
9270       assert( pOld->pNext );
9271     }
9272   }
9273 
9274   if( nVal>1 ){
9275     /* Check that "sz" and "rawdata" are both NULL: */
9276     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
9277       zipfileTableErr(pTab, "sz must be NULL");
9278       rc = SQLITE_CONSTRAINT;
9279     }
9280     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
9281       zipfileTableErr(pTab, "rawdata must be NULL");
9282       rc = SQLITE_CONSTRAINT;
9283     }
9284 
9285     if( rc==SQLITE_OK ){
9286       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
9287         /* data=NULL. A directory */
9288         bIsDir = 1;
9289       }else{
9290         /* Value specified for "data", and possibly "method". This must be
9291         ** a regular file or a symlink. */
9292         const u8 *aIn = sqlite3_value_blob(apVal[7]);
9293         int nIn = sqlite3_value_bytes(apVal[7]);
9294         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
9295 
9296         iMethod = sqlite3_value_int(apVal[8]);
9297         sz = nIn;
9298         pData = aIn;
9299         nData = nIn;
9300         if( iMethod!=0 && iMethod!=8 ){
9301           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
9302           rc = SQLITE_CONSTRAINT;
9303         }else{
9304           if( bAuto || iMethod ){
9305             int nCmp;
9306             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
9307             if( rc==SQLITE_OK ){
9308               if( iMethod || nCmp<nIn ){
9309                 iMethod = 8;
9310                 pData = pFree;
9311                 nData = nCmp;
9312               }
9313             }
9314           }
9315           iCrc32 = crc32(0, aIn, nIn);
9316         }
9317       }
9318     }
9319 
9320     if( rc==SQLITE_OK ){
9321       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
9322     }
9323 
9324     if( rc==SQLITE_OK ){
9325       zPath = (const char*)sqlite3_value_text(apVal[2]);
9326       if( zPath==0 ) zPath = "";
9327       nPath = (int)strlen(zPath);
9328       mTime = zipfileGetTime(apVal[4]);
9329     }
9330 
9331     if( rc==SQLITE_OK && bIsDir ){
9332       /* For a directory, check that the last character in the path is a
9333       ** '/'. This appears to be required for compatibility with info-zip
9334       ** (the unzip command on unix). It does not create directories
9335       ** otherwise.  */
9336       if( nPath<=0 || zPath[nPath-1]!='/' ){
9337         zFree = sqlite3_mprintf("%s/", zPath);
9338         zPath = (const char*)zFree;
9339         if( zFree==0 ){
9340           rc = SQLITE_NOMEM;
9341           nPath = 0;
9342         }else{
9343           nPath = (int)strlen(zPath);
9344         }
9345       }
9346     }
9347 
9348     /* Check that we're not inserting a duplicate entry -OR- updating an
9349     ** entry with a path, thereby making it into a duplicate. */
9350     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
9351       ZipfileEntry *p;
9352       for(p=pTab->pFirstEntry; p; p=p->pNext){
9353         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
9354           switch( sqlite3_vtab_on_conflict(pTab->db) ){
9355             case SQLITE_IGNORE: {
9356               goto zipfile_update_done;
9357             }
9358             case SQLITE_REPLACE: {
9359               pOld2 = p;
9360               break;
9361             }
9362             default: {
9363               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
9364               rc = SQLITE_CONSTRAINT;
9365               break;
9366             }
9367           }
9368           break;
9369         }
9370       }
9371     }
9372 
9373     if( rc==SQLITE_OK ){
9374       /* Create the new CDS record. */
9375       pNew = zipfileNewEntry(zPath);
9376       if( pNew==0 ){
9377         rc = SQLITE_NOMEM;
9378       }else{
9379         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
9380         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
9381         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
9382         pNew->cds.iCompression = (u16)iMethod;
9383         zipfileMtimeToDos(&pNew->cds, mTime);
9384         pNew->cds.crc32 = iCrc32;
9385         pNew->cds.szCompressed = nData;
9386         pNew->cds.szUncompressed = (u32)sz;
9387         pNew->cds.iExternalAttr = (mode<<16);
9388         pNew->cds.iOffset = (u32)pTab->szCurrent;
9389         pNew->cds.nFile = (u16)nPath;
9390         pNew->mUnixTime = (u32)mTime;
9391         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
9392         zipfileAddEntry(pTab, pOld, pNew);
9393       }
9394     }
9395   }
9396 
9397   if( rc==SQLITE_OK && (pOld || pOld2) ){
9398     ZipfileCsr *pCsr;
9399     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
9400       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
9401         pCsr->pCurrent = pCsr->pCurrent->pNext;
9402         pCsr->bNoop = 1;
9403       }
9404     }
9405 
9406     zipfileRemoveEntryFromList(pTab, pOld);
9407     zipfileRemoveEntryFromList(pTab, pOld2);
9408   }
9409 
9410 zipfile_update_done:
9411   sqlite3_free(pFree);
9412   sqlite3_free(zFree);
9413   return rc;
9414 }
9415 
9416 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
9417   u8 *a = aBuf;
9418   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
9419   zipfileWrite16(a, p->iDisk);
9420   zipfileWrite16(a, p->iFirstDisk);
9421   zipfileWrite16(a, p->nEntry);
9422   zipfileWrite16(a, p->nEntryTotal);
9423   zipfileWrite32(a, p->nSize);
9424   zipfileWrite32(a, p->iOffset);
9425   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
9426 
9427   return a-aBuf;
9428 }
9429 
9430 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
9431   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
9432   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
9433   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
9434 }
9435 
9436 /*
9437 ** Serialize the CDS structure into buffer aBuf[]. Return the number
9438 ** of bytes written.
9439 */
9440 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
9441   u8 *a = aBuf;
9442   ZipfileCDS *pCDS = &pEntry->cds;
9443 
9444   if( pEntry->aExtra==0 ){
9445     pCDS->nExtra = 9;
9446   }
9447 
9448   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
9449   zipfileWrite16(a, pCDS->iVersionMadeBy);
9450   zipfileWrite16(a, pCDS->iVersionExtract);
9451   zipfileWrite16(a, pCDS->flags);
9452   zipfileWrite16(a, pCDS->iCompression);
9453   zipfileWrite16(a, pCDS->mTime);
9454   zipfileWrite16(a, pCDS->mDate);
9455   zipfileWrite32(a, pCDS->crc32);
9456   zipfileWrite32(a, pCDS->szCompressed);
9457   zipfileWrite32(a, pCDS->szUncompressed);
9458   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9459   zipfileWrite16(a, pCDS->nFile);
9460   zipfileWrite16(a, pCDS->nExtra);
9461   zipfileWrite16(a, pCDS->nComment);
9462   zipfileWrite16(a, pCDS->iDiskStart);
9463   zipfileWrite16(a, pCDS->iInternalAttr);
9464   zipfileWrite32(a, pCDS->iExternalAttr);
9465   zipfileWrite32(a, pCDS->iOffset);
9466 
9467   memcpy(a, pCDS->zFile, pCDS->nFile);
9468   a += pCDS->nFile;
9469 
9470   if( pEntry->aExtra ){
9471     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
9472     memcpy(a, pEntry->aExtra, n);
9473     a += n;
9474   }else{
9475     assert( pCDS->nExtra==9 );
9476     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9477     zipfileWrite16(a, 5);
9478     *a++ = 0x01;
9479     zipfileWrite32(a, pEntry->mUnixTime);
9480   }
9481 
9482   return a-aBuf;
9483 }
9484 
9485 static int zipfileCommit(sqlite3_vtab *pVtab){
9486   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9487   int rc = SQLITE_OK;
9488   if( pTab->pWriteFd ){
9489     i64 iOffset = pTab->szCurrent;
9490     ZipfileEntry *p;
9491     ZipfileEOCD eocd;
9492     int nEntry = 0;
9493 
9494     /* Write out all entries */
9495     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
9496       int n = zipfileSerializeCDS(p, pTab->aBuffer);
9497       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
9498       nEntry++;
9499     }
9500 
9501     /* Write out the EOCD record */
9502     eocd.iDisk = 0;
9503     eocd.iFirstDisk = 0;
9504     eocd.nEntry = (u16)nEntry;
9505     eocd.nEntryTotal = (u16)nEntry;
9506     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
9507     eocd.iOffset = (u32)iOffset;
9508     rc = zipfileAppendEOCD(pTab, &eocd);
9509 
9510     zipfileCleanupTransaction(pTab);
9511   }
9512   return rc;
9513 }
9514 
9515 static int zipfileRollback(sqlite3_vtab *pVtab){
9516   return zipfileCommit(pVtab);
9517 }
9518 
9519 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
9520   ZipfileCsr *pCsr;
9521   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
9522     if( iId==pCsr->iId ) break;
9523   }
9524   return pCsr;
9525 }
9526 
9527 static void zipfileFunctionCds(
9528   sqlite3_context *context,
9529   int argc,
9530   sqlite3_value **argv
9531 ){
9532   ZipfileCsr *pCsr;
9533   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
9534   assert( argc>0 );
9535 
9536   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
9537   if( pCsr ){
9538     ZipfileCDS *p = &pCsr->pCurrent->cds;
9539     char *zRes = sqlite3_mprintf("{"
9540         "\"version-made-by\" : %u, "
9541         "\"version-to-extract\" : %u, "
9542         "\"flags\" : %u, "
9543         "\"compression\" : %u, "
9544         "\"time\" : %u, "
9545         "\"date\" : %u, "
9546         "\"crc32\" : %u, "
9547         "\"compressed-size\" : %u, "
9548         "\"uncompressed-size\" : %u, "
9549         "\"file-name-length\" : %u, "
9550         "\"extra-field-length\" : %u, "
9551         "\"file-comment-length\" : %u, "
9552         "\"disk-number-start\" : %u, "
9553         "\"internal-attr\" : %u, "
9554         "\"external-attr\" : %u, "
9555         "\"offset\" : %u }",
9556         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
9557         (u32)p->flags, (u32)p->iCompression,
9558         (u32)p->mTime, (u32)p->mDate,
9559         (u32)p->crc32, (u32)p->szCompressed,
9560         (u32)p->szUncompressed, (u32)p->nFile,
9561         (u32)p->nExtra, (u32)p->nComment,
9562         (u32)p->iDiskStart, (u32)p->iInternalAttr,
9563         (u32)p->iExternalAttr, (u32)p->iOffset
9564     );
9565 
9566     if( zRes==0 ){
9567       sqlite3_result_error_nomem(context);
9568     }else{
9569       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
9570       sqlite3_free(zRes);
9571     }
9572   }
9573 }
9574 
9575 /*
9576 ** xFindFunction method.
9577 */
9578 static int zipfileFindFunction(
9579   sqlite3_vtab *pVtab,            /* Virtual table handle */
9580   int nArg,                       /* Number of SQL function arguments */
9581   const char *zName,              /* Name of SQL function */
9582   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
9583   void **ppArg                    /* OUT: User data for *pxFunc */
9584 ){
9585   (void)nArg;
9586   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
9587     *pxFunc = zipfileFunctionCds;
9588     *ppArg = (void*)pVtab;
9589     return 1;
9590   }
9591   return 0;
9592 }
9593 
9594 typedef struct ZipfileBuffer ZipfileBuffer;
9595 struct ZipfileBuffer {
9596   u8 *a;                          /* Pointer to buffer */
9597   int n;                          /* Size of buffer in bytes */
9598   int nAlloc;                     /* Byte allocated at a[] */
9599 };
9600 
9601 typedef struct ZipfileCtx ZipfileCtx;
9602 struct ZipfileCtx {
9603   int nEntry;
9604   ZipfileBuffer body;
9605   ZipfileBuffer cds;
9606 };
9607 
9608 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
9609   if( pBuf->n+nByte>pBuf->nAlloc ){
9610     u8 *aNew;
9611     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
9612     int nReq = pBuf->n + nByte;
9613 
9614     while( nNew<nReq ) nNew = nNew*2;
9615     aNew = sqlite3_realloc64(pBuf->a, nNew);
9616     if( aNew==0 ) return SQLITE_NOMEM;
9617     pBuf->a = aNew;
9618     pBuf->nAlloc = (int)nNew;
9619   }
9620   return SQLITE_OK;
9621 }
9622 
9623 /*
9624 ** xStep() callback for the zipfile() aggregate. This can be called in
9625 ** any of the following ways:
9626 **
9627 **   SELECT zipfile(name,data) ...
9628 **   SELECT zipfile(name,mode,mtime,data) ...
9629 **   SELECT zipfile(name,mode,mtime,data,method) ...
9630 */
9631 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
9632   ZipfileCtx *p;                  /* Aggregate function context */
9633   ZipfileEntry e;                 /* New entry to add to zip archive */
9634 
9635   sqlite3_value *pName = 0;
9636   sqlite3_value *pMode = 0;
9637   sqlite3_value *pMtime = 0;
9638   sqlite3_value *pData = 0;
9639   sqlite3_value *pMethod = 0;
9640 
9641   int bIsDir = 0;
9642   u32 mode;
9643   int rc = SQLITE_OK;
9644   char *zErr = 0;
9645 
9646   int iMethod = -1;               /* Compression method to use (0 or 8) */
9647 
9648   const u8 *aData = 0;            /* Possibly compressed data for new entry */
9649   int nData = 0;                  /* Size of aData[] in bytes */
9650   int szUncompressed = 0;         /* Size of data before compression */
9651   u8 *aFree = 0;                  /* Free this before returning */
9652   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
9653 
9654   char *zName = 0;                /* Path (name) of new entry */
9655   int nName = 0;                  /* Size of zName in bytes */
9656   char *zFree = 0;                /* Free this before returning */
9657   int nByte;
9658 
9659   memset(&e, 0, sizeof(e));
9660   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
9661   if( p==0 ) return;
9662 
9663   /* Martial the arguments into stack variables */
9664   if( nVal!=2 && nVal!=4 && nVal!=5 ){
9665     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
9666     rc = SQLITE_ERROR;
9667     goto zipfile_step_out;
9668   }
9669   pName = apVal[0];
9670   if( nVal==2 ){
9671     pData = apVal[1];
9672   }else{
9673     pMode = apVal[1];
9674     pMtime = apVal[2];
9675     pData = apVal[3];
9676     if( nVal==5 ){
9677       pMethod = apVal[4];
9678     }
9679   }
9680 
9681   /* Check that the 'name' parameter looks ok. */
9682   zName = (char*)sqlite3_value_text(pName);
9683   nName = sqlite3_value_bytes(pName);
9684   if( zName==0 ){
9685     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
9686     rc = SQLITE_ERROR;
9687     goto zipfile_step_out;
9688   }
9689 
9690   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
9691   ** deflate compression) or NULL (choose automatically).  */
9692   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
9693     iMethod = (int)sqlite3_value_int64(pMethod);
9694     if( iMethod!=0 && iMethod!=8 ){
9695       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
9696       rc = SQLITE_ERROR;
9697       goto zipfile_step_out;
9698     }
9699   }
9700 
9701   /* Now inspect the data. If this is NULL, then the new entry must be a
9702   ** directory.  Otherwise, figure out whether or not the data should
9703   ** be deflated or simply stored in the zip archive. */
9704   if( sqlite3_value_type(pData)==SQLITE_NULL ){
9705     bIsDir = 1;
9706     iMethod = 0;
9707   }else{
9708     aData = sqlite3_value_blob(pData);
9709     szUncompressed = nData = sqlite3_value_bytes(pData);
9710     iCrc32 = crc32(0, aData, nData);
9711     if( iMethod<0 || iMethod==8 ){
9712       int nOut = 0;
9713       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
9714       if( rc!=SQLITE_OK ){
9715         goto zipfile_step_out;
9716       }
9717       if( iMethod==8 || nOut<nData ){
9718         aData = aFree;
9719         nData = nOut;
9720         iMethod = 8;
9721       }else{
9722         iMethod = 0;
9723       }
9724     }
9725   }
9726 
9727   /* Decode the "mode" argument. */
9728   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
9729   if( rc ) goto zipfile_step_out;
9730 
9731   /* Decode the "mtime" argument. */
9732   e.mUnixTime = zipfileGetTime(pMtime);
9733 
9734   /* If this is a directory entry, ensure that there is exactly one '/'
9735   ** at the end of the path. Or, if this is not a directory and the path
9736   ** ends in '/' it is an error. */
9737   if( bIsDir==0 ){
9738     if( nName>0 && zName[nName-1]=='/' ){
9739       zErr = sqlite3_mprintf("non-directory name must not end with /");
9740       rc = SQLITE_ERROR;
9741       goto zipfile_step_out;
9742     }
9743   }else{
9744     if( nName==0 || zName[nName-1]!='/' ){
9745       zName = zFree = sqlite3_mprintf("%s/", zName);
9746       if( zName==0 ){
9747         rc = SQLITE_NOMEM;
9748         goto zipfile_step_out;
9749       }
9750       nName = (int)strlen(zName);
9751     }else{
9752       while( nName>1 && zName[nName-2]=='/' ) nName--;
9753     }
9754   }
9755 
9756   /* Assemble the ZipfileEntry object for the new zip archive entry */
9757   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
9758   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
9759   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
9760   e.cds.iCompression = (u16)iMethod;
9761   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
9762   e.cds.crc32 = iCrc32;
9763   e.cds.szCompressed = nData;
9764   e.cds.szUncompressed = szUncompressed;
9765   e.cds.iExternalAttr = (mode<<16);
9766   e.cds.iOffset = p->body.n;
9767   e.cds.nFile = (u16)nName;
9768   e.cds.zFile = zName;
9769 
9770   /* Append the LFH to the body of the new archive */
9771   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
9772   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
9773   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
9774 
9775   /* Append the data to the body of the new archive */
9776   if( nData>0 ){
9777     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
9778     memcpy(&p->body.a[p->body.n], aData, nData);
9779     p->body.n += nData;
9780   }
9781 
9782   /* Append the CDS record to the directory of the new archive */
9783   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
9784   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
9785   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
9786 
9787   /* Increment the count of entries in the archive */
9788   p->nEntry++;
9789 
9790  zipfile_step_out:
9791   sqlite3_free(aFree);
9792   sqlite3_free(zFree);
9793   if( rc ){
9794     if( zErr ){
9795       sqlite3_result_error(pCtx, zErr, -1);
9796     }else{
9797       sqlite3_result_error_code(pCtx, rc);
9798     }
9799   }
9800   sqlite3_free(zErr);
9801 }
9802 
9803 /*
9804 ** xFinalize() callback for zipfile aggregate function.
9805 */
9806 static void zipfileFinal(sqlite3_context *pCtx){
9807   ZipfileCtx *p;
9808   ZipfileEOCD eocd;
9809   sqlite3_int64 nZip;
9810   u8 *aZip;
9811 
9812   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
9813   if( p==0 ) return;
9814   if( p->nEntry>0 ){
9815     memset(&eocd, 0, sizeof(eocd));
9816     eocd.nEntry = (u16)p->nEntry;
9817     eocd.nEntryTotal = (u16)p->nEntry;
9818     eocd.nSize = p->cds.n;
9819     eocd.iOffset = p->body.n;
9820 
9821     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
9822     aZip = (u8*)sqlite3_malloc64(nZip);
9823     if( aZip==0 ){
9824       sqlite3_result_error_nomem(pCtx);
9825     }else{
9826       memcpy(aZip, p->body.a, p->body.n);
9827       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
9828       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
9829       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
9830     }
9831   }
9832 
9833   sqlite3_free(p->body.a);
9834   sqlite3_free(p->cds.a);
9835 }
9836 
9837 
9838 /*
9839 ** Register the "zipfile" virtual table.
9840 */
9841 static int zipfileRegister(sqlite3 *db){
9842   static sqlite3_module zipfileModule = {
9843     1,                         /* iVersion */
9844     zipfileConnect,            /* xCreate */
9845     zipfileConnect,            /* xConnect */
9846     zipfileBestIndex,          /* xBestIndex */
9847     zipfileDisconnect,         /* xDisconnect */
9848     zipfileDisconnect,         /* xDestroy */
9849     zipfileOpen,               /* xOpen - open a cursor */
9850     zipfileClose,              /* xClose - close a cursor */
9851     zipfileFilter,             /* xFilter - configure scan constraints */
9852     zipfileNext,               /* xNext - advance a cursor */
9853     zipfileEof,                /* xEof - check for end of scan */
9854     zipfileColumn,             /* xColumn - read data */
9855     0,                         /* xRowid - read data */
9856     zipfileUpdate,             /* xUpdate */
9857     zipfileBegin,              /* xBegin */
9858     0,                         /* xSync */
9859     zipfileCommit,             /* xCommit */
9860     zipfileRollback,           /* xRollback */
9861     zipfileFindFunction,       /* xFindMethod */
9862     0,                         /* xRename */
9863     0,                         /* xSavepoint */
9864     0,                         /* xRelease */
9865     0,                         /* xRollback */
9866     0                          /* xShadowName */
9867   };
9868 
9869   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
9870   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
9871   if( rc==SQLITE_OK ){
9872     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
9873         zipfileStep, zipfileFinal
9874     );
9875   }
9876   assert( sizeof(i64)==8 );
9877   assert( sizeof(u32)==4 );
9878   assert( sizeof(u16)==2 );
9879   assert( sizeof(u8)==1 );
9880   return rc;
9881 }
9882 #else         /* SQLITE_OMIT_VIRTUALTABLE */
9883 # define zipfileRegister(x) SQLITE_OK
9884 #endif
9885 
9886 #ifdef _WIN32
9887 
9888 #endif
9889 int sqlite3_zipfile_init(
9890   sqlite3 *db,
9891   char **pzErrMsg,
9892   const sqlite3_api_routines *pApi
9893 ){
9894   SQLITE_EXTENSION_INIT2(pApi);
9895   (void)pzErrMsg;  /* Unused parameter */
9896   return zipfileRegister(db);
9897 }
9898 
9899 /************************* End ../ext/misc/zipfile.c ********************/
9900 /************************* Begin ../ext/misc/sqlar.c ******************/
9901 /*
9902 ** 2017-12-17
9903 **
9904 ** The author disclaims copyright to this source code.  In place of
9905 ** a legal notice, here is a blessing:
9906 **
9907 **    May you do good and not evil.
9908 **    May you find forgiveness for yourself and forgive others.
9909 **    May you share freely, never taking more than you give.
9910 **
9911 ******************************************************************************
9912 **
9913 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
9914 ** for working with sqlar archives and used by the shell tool's built-in
9915 ** sqlar support.
9916 */
9917 /* #include "sqlite3ext.h" */
9918 SQLITE_EXTENSION_INIT1
9919 #include <zlib.h>
9920 #include <assert.h>
9921 
9922 /*
9923 ** Implementation of the "sqlar_compress(X)" SQL function.
9924 **
9925 ** If the type of X is SQLITE_BLOB, and compressing that blob using
9926 ** zlib utility function compress() yields a smaller blob, return the
9927 ** compressed blob. Otherwise, return a copy of X.
9928 **
9929 ** SQLar uses the "zlib format" for compressed content.  The zlib format
9930 ** contains a two-byte identification header and a four-byte checksum at
9931 ** the end.  This is different from ZIP which uses the raw deflate format.
9932 **
9933 ** Future enhancements to SQLar might add support for new compression formats.
9934 ** If so, those new formats will be identified by alternative headers in the
9935 ** compressed data.
9936 */
9937 static void sqlarCompressFunc(
9938   sqlite3_context *context,
9939   int argc,
9940   sqlite3_value **argv
9941 ){
9942   assert( argc==1 );
9943   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
9944     const Bytef *pData = sqlite3_value_blob(argv[0]);
9945     uLong nData = sqlite3_value_bytes(argv[0]);
9946     uLongf nOut = compressBound(nData);
9947     Bytef *pOut;
9948 
9949     pOut = (Bytef*)sqlite3_malloc(nOut);
9950     if( pOut==0 ){
9951       sqlite3_result_error_nomem(context);
9952       return;
9953     }else{
9954       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
9955         sqlite3_result_error(context, "error in compress()", -1);
9956       }else if( nOut<nData ){
9957         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
9958       }else{
9959         sqlite3_result_value(context, argv[0]);
9960       }
9961       sqlite3_free(pOut);
9962     }
9963   }else{
9964     sqlite3_result_value(context, argv[0]);
9965   }
9966 }
9967 
9968 /*
9969 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
9970 **
9971 ** Parameter SZ is interpreted as an integer. If it is less than or
9972 ** equal to zero, then this function returns a copy of X. Or, if
9973 ** SZ is equal to the size of X when interpreted as a blob, also
9974 ** return a copy of X. Otherwise, decompress blob X using zlib
9975 ** utility function uncompress() and return the results (another
9976 ** blob).
9977 */
9978 static void sqlarUncompressFunc(
9979   sqlite3_context *context,
9980   int argc,
9981   sqlite3_value **argv
9982 ){
9983   uLong nData;
9984   uLongf sz;
9985 
9986   assert( argc==2 );
9987   sz = sqlite3_value_int(argv[1]);
9988 
9989   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
9990     sqlite3_result_value(context, argv[0]);
9991   }else{
9992     const Bytef *pData= sqlite3_value_blob(argv[0]);
9993     Bytef *pOut = sqlite3_malloc(sz);
9994     if( pOut==0 ){
9995       sqlite3_result_error_nomem(context);
9996     }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
9997       sqlite3_result_error(context, "error in uncompress()", -1);
9998     }else{
9999       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
10000     }
10001     sqlite3_free(pOut);
10002   }
10003 }
10004 
10005 #ifdef _WIN32
10006 
10007 #endif
10008 int sqlite3_sqlar_init(
10009   sqlite3 *db,
10010   char **pzErrMsg,
10011   const sqlite3_api_routines *pApi
10012 ){
10013   int rc = SQLITE_OK;
10014   SQLITE_EXTENSION_INIT2(pApi);
10015   (void)pzErrMsg;  /* Unused parameter */
10016   rc = sqlite3_create_function(db, "sqlar_compress", 1,
10017                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10018                                sqlarCompressFunc, 0, 0);
10019   if( rc==SQLITE_OK ){
10020     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
10021                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10022                                  sqlarUncompressFunc, 0, 0);
10023   }
10024   return rc;
10025 }
10026 
10027 /************************* End ../ext/misc/sqlar.c ********************/
10028 #endif
10029 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
10030 /*
10031 ** 2017 April 07
10032 **
10033 ** The author disclaims copyright to this source code.  In place of
10034 ** a legal notice, here is a blessing:
10035 **
10036 **    May you do good and not evil.
10037 **    May you find forgiveness for yourself and forgive others.
10038 **    May you share freely, never taking more than you give.
10039 **
10040 *************************************************************************
10041 */
10042 #if !defined(SQLITEEXPERT_H)
10043 #define SQLITEEXPERT_H 1
10044 /* #include "sqlite3.h" */
10045 
10046 typedef struct sqlite3expert sqlite3expert;
10047 
10048 /*
10049 ** Create a new sqlite3expert object.
10050 **
10051 ** If successful, a pointer to the new object is returned and (*pzErr) set
10052 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
10053 ** an English-language error message. In this case it is the responsibility
10054 ** of the caller to eventually free the error message buffer using
10055 ** sqlite3_free().
10056 */
10057 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
10058 
10059 /*
10060 ** Configure an sqlite3expert object.
10061 **
10062 ** EXPERT_CONFIG_SAMPLE:
10063 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
10064 **   each candidate index. This involves scanning and sorting the entire
10065 **   contents of each user database table once for each candidate index
10066 **   associated with the table. For large databases, this can be
10067 **   prohibitively slow. This option allows the sqlite3expert object to
10068 **   be configured so that sqlite_stat1 data is instead generated based on a
10069 **   subset of each table, or so that no sqlite_stat1 data is used at all.
10070 **
10071 **   A single integer argument is passed to this option. If the value is less
10072 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
10073 **   the analysis - indexes are recommended based on the database schema only.
10074 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
10075 **   generated for each candidate index (this is the default). Finally, if the
10076 **   value falls between 0 and 100, then it represents the percentage of user
10077 **   table rows that should be considered when generating sqlite_stat1 data.
10078 **
10079 **   Examples:
10080 **
10081 **     // Do not generate any sqlite_stat1 data
10082 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
10083 **
10084 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
10085 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
10086 */
10087 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
10088 
10089 #define EXPERT_CONFIG_SAMPLE 1    /* int */
10090 
10091 /*
10092 ** Specify zero or more SQL statements to be included in the analysis.
10093 **
10094 ** Buffer zSql must contain zero or more complete SQL statements. This
10095 ** function parses all statements contained in the buffer and adds them
10096 ** to the internal list of statements to analyze. If successful, SQLITE_OK
10097 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
10098 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
10099 ** may be set to point to an English language error message. In this case
10100 ** the caller is responsible for eventually freeing the error message buffer
10101 ** using sqlite3_free().
10102 **
10103 ** If an error does occur while processing one of the statements in the
10104 ** buffer passed as the second argument, none of the statements in the
10105 ** buffer are added to the analysis.
10106 **
10107 ** This function must be called before sqlite3_expert_analyze(). If a call
10108 ** to this function is made on an sqlite3expert object that has already
10109 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
10110 ** immediately and no statements are added to the analysis.
10111 */
10112 int sqlite3_expert_sql(
10113   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
10114   const char *zSql,               /* SQL statement(s) to add */
10115   char **pzErr                    /* OUT: Error message (if any) */
10116 );
10117 
10118 
10119 /*
10120 ** This function is called after the sqlite3expert object has been configured
10121 ** with all SQL statements using sqlite3_expert_sql() to actually perform
10122 ** the analysis. Once this function has been called, it is not possible to
10123 ** add further SQL statements to the analysis.
10124 **
10125 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
10126 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
10127 ** point to a buffer containing an English language error message. In this
10128 ** case it is the responsibility of the caller to eventually free the buffer
10129 ** using sqlite3_free().
10130 **
10131 ** If an error does occur within this function, the sqlite3expert object
10132 ** is no longer useful for any purpose. At that point it is no longer
10133 ** possible to add further SQL statements to the object or to re-attempt
10134 ** the analysis. The sqlite3expert object must still be freed using a call
10135 ** sqlite3_expert_destroy().
10136 */
10137 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
10138 
10139 /*
10140 ** Return the total number of statements loaded using sqlite3_expert_sql().
10141 ** The total number of SQL statements may be different from the total number
10142 ** to calls to sqlite3_expert_sql().
10143 */
10144 int sqlite3_expert_count(sqlite3expert*);
10145 
10146 /*
10147 ** Return a component of the report.
10148 **
10149 ** This function is called after sqlite3_expert_analyze() to extract the
10150 ** results of the analysis. Each call to this function returns either a
10151 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
10152 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
10153 ** #define constants defined below.
10154 **
10155 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
10156 ** information relating to a specific SQL statement. In these cases that
10157 ** SQL statement is identified by the value passed as the second argument.
10158 ** SQL statements are numbered from 0 in the order in which they are parsed.
10159 ** If an out-of-range value (less than zero or equal to or greater than the
10160 ** value returned by sqlite3_expert_count()) is passed as the second argument
10161 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
10162 **
10163 ** EXPERT_REPORT_SQL:
10164 **   Return the text of SQL statement iStmt.
10165 **
10166 ** EXPERT_REPORT_INDEXES:
10167 **   Return a buffer containing the CREATE INDEX statements for all recommended
10168 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
10169 **   is returned.
10170 **
10171 ** EXPERT_REPORT_PLAN:
10172 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
10173 **   iStmt after the proposed indexes have been added to the database schema.
10174 **
10175 ** EXPERT_REPORT_CANDIDATES:
10176 **   Return a pointer to a buffer containing the CREATE INDEX statements
10177 **   for all indexes that were tested (for all SQL statements). The iStmt
10178 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
10179 */
10180 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
10181 
10182 /*
10183 ** Values for the third argument passed to sqlite3_expert_report().
10184 */
10185 #define EXPERT_REPORT_SQL        1
10186 #define EXPERT_REPORT_INDEXES    2
10187 #define EXPERT_REPORT_PLAN       3
10188 #define EXPERT_REPORT_CANDIDATES 4
10189 
10190 /*
10191 ** Free an (sqlite3expert*) handle and all associated resources. There
10192 ** should be one call to this function for each successful call to
10193 ** sqlite3-expert_new().
10194 */
10195 void sqlite3_expert_destroy(sqlite3expert*);
10196 
10197 #endif  /* !defined(SQLITEEXPERT_H) */
10198 
10199 /************************* End ../ext/expert/sqlite3expert.h ********************/
10200 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
10201 /*
10202 ** 2017 April 09
10203 **
10204 ** The author disclaims copyright to this source code.  In place of
10205 ** a legal notice, here is a blessing:
10206 **
10207 **    May you do good and not evil.
10208 **    May you find forgiveness for yourself and forgive others.
10209 **    May you share freely, never taking more than you give.
10210 **
10211 *************************************************************************
10212 */
10213 /* #include "sqlite3expert.h" */
10214 #include <assert.h>
10215 #include <string.h>
10216 #include <stdio.h>
10217 
10218 #if !defined(SQLITE_AMALGAMATION)
10219 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
10220 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
10221 #endif
10222 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
10223 # define ALWAYS(X)      (1)
10224 # define NEVER(X)       (0)
10225 #elif !defined(NDEBUG)
10226 # define ALWAYS(X)      ((X)?1:(assert(0),0))
10227 # define NEVER(X)       ((X)?(assert(0),1):0)
10228 #else
10229 # define ALWAYS(X)      (X)
10230 # define NEVER(X)       (X)
10231 #endif
10232 #endif /* !defined(SQLITE_AMALGAMATION) */
10233 
10234 
10235 #ifndef SQLITE_OMIT_VIRTUALTABLE
10236 
10237 /* typedef sqlite3_int64 i64; */
10238 /* typedef sqlite3_uint64 u64; */
10239 
10240 typedef struct IdxColumn IdxColumn;
10241 typedef struct IdxConstraint IdxConstraint;
10242 typedef struct IdxScan IdxScan;
10243 typedef struct IdxStatement IdxStatement;
10244 typedef struct IdxTable IdxTable;
10245 typedef struct IdxWrite IdxWrite;
10246 
10247 #define STRLEN  (int)strlen
10248 
10249 /*
10250 ** A temp table name that we assume no user database will actually use.
10251 ** If this assumption proves incorrect triggers on the table with the
10252 ** conflicting name will be ignored.
10253 */
10254 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
10255 
10256 /*
10257 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
10258 ** any other type of single-ended range constraint on a column).
10259 **
10260 ** pLink:
10261 **   Used to temporarily link IdxConstraint objects into lists while
10262 **   creating candidate indexes.
10263 */
10264 struct IdxConstraint {
10265   char *zColl;                    /* Collation sequence */
10266   int bRange;                     /* True for range, false for eq */
10267   int iCol;                       /* Constrained table column */
10268   int bFlag;                      /* Used by idxFindCompatible() */
10269   int bDesc;                      /* True if ORDER BY <expr> DESC */
10270   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
10271   IdxConstraint *pLink;           /* See above */
10272 };
10273 
10274 /*
10275 ** A single scan of a single table.
10276 */
10277 struct IdxScan {
10278   IdxTable *pTab;                 /* Associated table object */
10279   int iDb;                        /* Database containing table zTable */
10280   i64 covering;                   /* Mask of columns required for cov. index */
10281   IdxConstraint *pOrder;          /* ORDER BY columns */
10282   IdxConstraint *pEq;             /* List of == constraints */
10283   IdxConstraint *pRange;          /* List of < constraints */
10284   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
10285 };
10286 
10287 /*
10288 ** Information regarding a single database table. Extracted from
10289 ** "PRAGMA table_info" by function idxGetTableInfo().
10290 */
10291 struct IdxColumn {
10292   char *zName;
10293   char *zColl;
10294   int iPk;
10295 };
10296 struct IdxTable {
10297   int nCol;
10298   char *zName;                    /* Table name */
10299   IdxColumn *aCol;
10300   IdxTable *pNext;                /* Next table in linked list of all tables */
10301 };
10302 
10303 /*
10304 ** An object of the following type is created for each unique table/write-op
10305 ** seen. The objects are stored in a singly-linked list beginning at
10306 ** sqlite3expert.pWrite.
10307 */
10308 struct IdxWrite {
10309   IdxTable *pTab;
10310   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
10311   IdxWrite *pNext;
10312 };
10313 
10314 /*
10315 ** Each statement being analyzed is represented by an instance of this
10316 ** structure.
10317 */
10318 struct IdxStatement {
10319   int iId;                        /* Statement number */
10320   char *zSql;                     /* SQL statement */
10321   char *zIdx;                     /* Indexes */
10322   char *zEQP;                     /* Plan */
10323   IdxStatement *pNext;
10324 };
10325 
10326 
10327 /*
10328 ** A hash table for storing strings. With space for a payload string
10329 ** with each entry. Methods are:
10330 **
10331 **   idxHashInit()
10332 **   idxHashClear()
10333 **   idxHashAdd()
10334 **   idxHashSearch()
10335 */
10336 #define IDX_HASH_SIZE 1023
10337 typedef struct IdxHashEntry IdxHashEntry;
10338 typedef struct IdxHash IdxHash;
10339 struct IdxHashEntry {
10340   char *zKey;                     /* nul-terminated key */
10341   char *zVal;                     /* nul-terminated value string */
10342   char *zVal2;                    /* nul-terminated value string 2 */
10343   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
10344   IdxHashEntry *pNext;            /* Next entry in hash */
10345 };
10346 struct IdxHash {
10347   IdxHashEntry *pFirst;
10348   IdxHashEntry *aHash[IDX_HASH_SIZE];
10349 };
10350 
10351 /*
10352 ** sqlite3expert object.
10353 */
10354 struct sqlite3expert {
10355   int iSample;                    /* Percentage of tables to sample for stat1 */
10356   sqlite3 *db;                    /* User database */
10357   sqlite3 *dbm;                   /* In-memory db for this analysis */
10358   sqlite3 *dbv;                   /* Vtab schema for this analysis */
10359   IdxTable *pTable;               /* List of all IdxTable objects */
10360   IdxScan *pScan;                 /* List of scan objects */
10361   IdxWrite *pWrite;               /* List of write objects */
10362   IdxStatement *pStatement;       /* List of IdxStatement objects */
10363   int bRun;                       /* True once analysis has run */
10364   char **pzErrmsg;
10365   int rc;                         /* Error code from whereinfo hook */
10366   IdxHash hIdx;                   /* Hash containing all candidate indexes */
10367   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
10368 };
10369 
10370 
10371 /*
10372 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
10373 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
10374 */
10375 static void *idxMalloc(int *pRc, int nByte){
10376   void *pRet;
10377   assert( *pRc==SQLITE_OK );
10378   assert( nByte>0 );
10379   pRet = sqlite3_malloc(nByte);
10380   if( pRet ){
10381     memset(pRet, 0, nByte);
10382   }else{
10383     *pRc = SQLITE_NOMEM;
10384   }
10385   return pRet;
10386 }
10387 
10388 /*
10389 ** Initialize an IdxHash hash table.
10390 */
10391 static void idxHashInit(IdxHash *pHash){
10392   memset(pHash, 0, sizeof(IdxHash));
10393 }
10394 
10395 /*
10396 ** Reset an IdxHash hash table.
10397 */
10398 static void idxHashClear(IdxHash *pHash){
10399   int i;
10400   for(i=0; i<IDX_HASH_SIZE; i++){
10401     IdxHashEntry *pEntry;
10402     IdxHashEntry *pNext;
10403     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
10404       pNext = pEntry->pHashNext;
10405       sqlite3_free(pEntry->zVal2);
10406       sqlite3_free(pEntry);
10407     }
10408   }
10409   memset(pHash, 0, sizeof(IdxHash));
10410 }
10411 
10412 /*
10413 ** Return the index of the hash bucket that the string specified by the
10414 ** arguments to this function belongs.
10415 */
10416 static int idxHashString(const char *z, int n){
10417   unsigned int ret = 0;
10418   int i;
10419   for(i=0; i<n; i++){
10420     ret += (ret<<3) + (unsigned char)(z[i]);
10421   }
10422   return (int)(ret % IDX_HASH_SIZE);
10423 }
10424 
10425 /*
10426 ** If zKey is already present in the hash table, return non-zero and do
10427 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
10428 ** the hash table passed as the second argument.
10429 */
10430 static int idxHashAdd(
10431   int *pRc,
10432   IdxHash *pHash,
10433   const char *zKey,
10434   const char *zVal
10435 ){
10436   int nKey = STRLEN(zKey);
10437   int iHash = idxHashString(zKey, nKey);
10438   int nVal = (zVal ? STRLEN(zVal) : 0);
10439   IdxHashEntry *pEntry;
10440   assert( iHash>=0 );
10441   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
10442     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
10443       return 1;
10444     }
10445   }
10446   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
10447   if( pEntry ){
10448     pEntry->zKey = (char*)&pEntry[1];
10449     memcpy(pEntry->zKey, zKey, nKey);
10450     if( zVal ){
10451       pEntry->zVal = &pEntry->zKey[nKey+1];
10452       memcpy(pEntry->zVal, zVal, nVal);
10453     }
10454     pEntry->pHashNext = pHash->aHash[iHash];
10455     pHash->aHash[iHash] = pEntry;
10456 
10457     pEntry->pNext = pHash->pFirst;
10458     pHash->pFirst = pEntry;
10459   }
10460   return 0;
10461 }
10462 
10463 /*
10464 ** If zKey/nKey is present in the hash table, return a pointer to the
10465 ** hash-entry object.
10466 */
10467 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
10468   int iHash;
10469   IdxHashEntry *pEntry;
10470   if( nKey<0 ) nKey = STRLEN(zKey);
10471   iHash = idxHashString(zKey, nKey);
10472   assert( iHash>=0 );
10473   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
10474     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
10475       return pEntry;
10476     }
10477   }
10478   return 0;
10479 }
10480 
10481 /*
10482 ** If the hash table contains an entry with a key equal to the string
10483 ** passed as the final two arguments to this function, return a pointer
10484 ** to the payload string. Otherwise, if zKey/nKey is not present in the
10485 ** hash table, return NULL.
10486 */
10487 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
10488   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
10489   if( pEntry ) return pEntry->zVal;
10490   return 0;
10491 }
10492 
10493 /*
10494 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
10495 ** variable to point to a copy of nul-terminated string zColl.
10496 */
10497 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
10498   IdxConstraint *pNew;
10499   int nColl = STRLEN(zColl);
10500 
10501   assert( *pRc==SQLITE_OK );
10502   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
10503   if( pNew ){
10504     pNew->zColl = (char*)&pNew[1];
10505     memcpy(pNew->zColl, zColl, nColl+1);
10506   }
10507   return pNew;
10508 }
10509 
10510 /*
10511 ** An error associated with database handle db has just occurred. Pass
10512 ** the error message to callback function xOut.
10513 */
10514 static void idxDatabaseError(
10515   sqlite3 *db,                    /* Database handle */
10516   char **pzErrmsg                 /* Write error here */
10517 ){
10518   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
10519 }
10520 
10521 /*
10522 ** Prepare an SQL statement.
10523 */
10524 static int idxPrepareStmt(
10525   sqlite3 *db,                    /* Database handle to compile against */
10526   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
10527   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
10528   const char *zSql                /* SQL statement to compile */
10529 ){
10530   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
10531   if( rc!=SQLITE_OK ){
10532     *ppStmt = 0;
10533     idxDatabaseError(db, pzErrmsg);
10534   }
10535   return rc;
10536 }
10537 
10538 /*
10539 ** Prepare an SQL statement using the results of a printf() formatting.
10540 */
10541 static int idxPrintfPrepareStmt(
10542   sqlite3 *db,                    /* Database handle to compile against */
10543   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
10544   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
10545   const char *zFmt,               /* printf() format of SQL statement */
10546   ...                             /* Trailing printf() arguments */
10547 ){
10548   va_list ap;
10549   int rc;
10550   char *zSql;
10551   va_start(ap, zFmt);
10552   zSql = sqlite3_vmprintf(zFmt, ap);
10553   if( zSql==0 ){
10554     rc = SQLITE_NOMEM;
10555   }else{
10556     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
10557     sqlite3_free(zSql);
10558   }
10559   va_end(ap);
10560   return rc;
10561 }
10562 
10563 
10564 /*************************************************************************
10565 ** Beginning of virtual table implementation.
10566 */
10567 typedef struct ExpertVtab ExpertVtab;
10568 struct ExpertVtab {
10569   sqlite3_vtab base;
10570   IdxTable *pTab;
10571   sqlite3expert *pExpert;
10572 };
10573 
10574 typedef struct ExpertCsr ExpertCsr;
10575 struct ExpertCsr {
10576   sqlite3_vtab_cursor base;
10577   sqlite3_stmt *pData;
10578 };
10579 
10580 static char *expertDequote(const char *zIn){
10581   int n = STRLEN(zIn);
10582   char *zRet = sqlite3_malloc(n);
10583 
10584   assert( zIn[0]=='\'' );
10585   assert( zIn[n-1]=='\'' );
10586 
10587   if( zRet ){
10588     int iOut = 0;
10589     int iIn = 0;
10590     for(iIn=1; iIn<(n-1); iIn++){
10591       if( zIn[iIn]=='\'' ){
10592         assert( zIn[iIn+1]=='\'' );
10593         iIn++;
10594       }
10595       zRet[iOut++] = zIn[iIn];
10596     }
10597     zRet[iOut] = '\0';
10598   }
10599 
10600   return zRet;
10601 }
10602 
10603 /*
10604 ** This function is the implementation of both the xConnect and xCreate
10605 ** methods of the r-tree virtual table.
10606 **
10607 **   argv[0]   -> module name
10608 **   argv[1]   -> database name
10609 **   argv[2]   -> table name
10610 **   argv[...] -> column names...
10611 */
10612 static int expertConnect(
10613   sqlite3 *db,
10614   void *pAux,
10615   int argc, const char *const*argv,
10616   sqlite3_vtab **ppVtab,
10617   char **pzErr
10618 ){
10619   sqlite3expert *pExpert = (sqlite3expert*)pAux;
10620   ExpertVtab *p = 0;
10621   int rc;
10622 
10623   if( argc!=4 ){
10624     *pzErr = sqlite3_mprintf("internal error!");
10625     rc = SQLITE_ERROR;
10626   }else{
10627     char *zCreateTable = expertDequote(argv[3]);
10628     if( zCreateTable ){
10629       rc = sqlite3_declare_vtab(db, zCreateTable);
10630       if( rc==SQLITE_OK ){
10631         p = idxMalloc(&rc, sizeof(ExpertVtab));
10632       }
10633       if( rc==SQLITE_OK ){
10634         p->pExpert = pExpert;
10635         p->pTab = pExpert->pTable;
10636         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
10637       }
10638       sqlite3_free(zCreateTable);
10639     }else{
10640       rc = SQLITE_NOMEM;
10641     }
10642   }
10643 
10644   *ppVtab = (sqlite3_vtab*)p;
10645   return rc;
10646 }
10647 
10648 static int expertDisconnect(sqlite3_vtab *pVtab){
10649   ExpertVtab *p = (ExpertVtab*)pVtab;
10650   sqlite3_free(p);
10651   return SQLITE_OK;
10652 }
10653 
10654 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
10655   ExpertVtab *p = (ExpertVtab*)pVtab;
10656   int rc = SQLITE_OK;
10657   int n = 0;
10658   IdxScan *pScan;
10659   const int opmask =
10660     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
10661     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
10662     SQLITE_INDEX_CONSTRAINT_LE;
10663 
10664   pScan = idxMalloc(&rc, sizeof(IdxScan));
10665   if( pScan ){
10666     int i;
10667 
10668     /* Link the new scan object into the list */
10669     pScan->pTab = p->pTab;
10670     pScan->pNextScan = p->pExpert->pScan;
10671     p->pExpert->pScan = pScan;
10672 
10673     /* Add the constraints to the IdxScan object */
10674     for(i=0; i<pIdxInfo->nConstraint; i++){
10675       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10676       if( pCons->usable
10677        && pCons->iColumn>=0
10678        && p->pTab->aCol[pCons->iColumn].iPk==0
10679        && (pCons->op & opmask)
10680       ){
10681         IdxConstraint *pNew;
10682         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
10683         pNew = idxNewConstraint(&rc, zColl);
10684         if( pNew ){
10685           pNew->iCol = pCons->iColumn;
10686           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10687             pNew->pNext = pScan->pEq;
10688             pScan->pEq = pNew;
10689           }else{
10690             pNew->bRange = 1;
10691             pNew->pNext = pScan->pRange;
10692             pScan->pRange = pNew;
10693           }
10694         }
10695         n++;
10696         pIdxInfo->aConstraintUsage[i].argvIndex = n;
10697       }
10698     }
10699 
10700     /* Add the ORDER BY to the IdxScan object */
10701     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
10702       int iCol = pIdxInfo->aOrderBy[i].iColumn;
10703       if( iCol>=0 ){
10704         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
10705         if( pNew ){
10706           pNew->iCol = iCol;
10707           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
10708           pNew->pNext = pScan->pOrder;
10709           pNew->pLink = pScan->pOrder;
10710           pScan->pOrder = pNew;
10711           n++;
10712         }
10713       }
10714     }
10715   }
10716 
10717   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
10718   return rc;
10719 }
10720 
10721 static int expertUpdate(
10722   sqlite3_vtab *pVtab,
10723   int nData,
10724   sqlite3_value **azData,
10725   sqlite_int64 *pRowid
10726 ){
10727   (void)pVtab;
10728   (void)nData;
10729   (void)azData;
10730   (void)pRowid;
10731   return SQLITE_OK;
10732 }
10733 
10734 /*
10735 ** Virtual table module xOpen method.
10736 */
10737 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
10738   int rc = SQLITE_OK;
10739   ExpertCsr *pCsr;
10740   (void)pVTab;
10741   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
10742   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
10743   return rc;
10744 }
10745 
10746 /*
10747 ** Virtual table module xClose method.
10748 */
10749 static int expertClose(sqlite3_vtab_cursor *cur){
10750   ExpertCsr *pCsr = (ExpertCsr*)cur;
10751   sqlite3_finalize(pCsr->pData);
10752   sqlite3_free(pCsr);
10753   return SQLITE_OK;
10754 }
10755 
10756 /*
10757 ** Virtual table module xEof method.
10758 **
10759 ** Return non-zero if the cursor does not currently point to a valid
10760 ** record (i.e if the scan has finished), or zero otherwise.
10761 */
10762 static int expertEof(sqlite3_vtab_cursor *cur){
10763   ExpertCsr *pCsr = (ExpertCsr*)cur;
10764   return pCsr->pData==0;
10765 }
10766 
10767 /*
10768 ** Virtual table module xNext method.
10769 */
10770 static int expertNext(sqlite3_vtab_cursor *cur){
10771   ExpertCsr *pCsr = (ExpertCsr*)cur;
10772   int rc = SQLITE_OK;
10773 
10774   assert( pCsr->pData );
10775   rc = sqlite3_step(pCsr->pData);
10776   if( rc!=SQLITE_ROW ){
10777     rc = sqlite3_finalize(pCsr->pData);
10778     pCsr->pData = 0;
10779   }else{
10780     rc = SQLITE_OK;
10781   }
10782 
10783   return rc;
10784 }
10785 
10786 /*
10787 ** Virtual table module xRowid method.
10788 */
10789 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
10790   (void)cur;
10791   *pRowid = 0;
10792   return SQLITE_OK;
10793 }
10794 
10795 /*
10796 ** Virtual table module xColumn method.
10797 */
10798 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
10799   ExpertCsr *pCsr = (ExpertCsr*)cur;
10800   sqlite3_value *pVal;
10801   pVal = sqlite3_column_value(pCsr->pData, i);
10802   if( pVal ){
10803     sqlite3_result_value(ctx, pVal);
10804   }
10805   return SQLITE_OK;
10806 }
10807 
10808 /*
10809 ** Virtual table module xFilter method.
10810 */
10811 static int expertFilter(
10812   sqlite3_vtab_cursor *cur,
10813   int idxNum, const char *idxStr,
10814   int argc, sqlite3_value **argv
10815 ){
10816   ExpertCsr *pCsr = (ExpertCsr*)cur;
10817   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
10818   sqlite3expert *pExpert = pVtab->pExpert;
10819   int rc;
10820 
10821   (void)idxNum;
10822   (void)idxStr;
10823   (void)argc;
10824   (void)argv;
10825   rc = sqlite3_finalize(pCsr->pData);
10826   pCsr->pData = 0;
10827   if( rc==SQLITE_OK ){
10828     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
10829         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
10830     );
10831   }
10832 
10833   if( rc==SQLITE_OK ){
10834     rc = expertNext(cur);
10835   }
10836   return rc;
10837 }
10838 
10839 static int idxRegisterVtab(sqlite3expert *p){
10840   static sqlite3_module expertModule = {
10841     2,                            /* iVersion */
10842     expertConnect,                /* xCreate - create a table */
10843     expertConnect,                /* xConnect - connect to an existing table */
10844     expertBestIndex,              /* xBestIndex - Determine search strategy */
10845     expertDisconnect,             /* xDisconnect - Disconnect from a table */
10846     expertDisconnect,             /* xDestroy - Drop a table */
10847     expertOpen,                   /* xOpen - open a cursor */
10848     expertClose,                  /* xClose - close a cursor */
10849     expertFilter,                 /* xFilter - configure scan constraints */
10850     expertNext,                   /* xNext - advance a cursor */
10851     expertEof,                    /* xEof */
10852     expertColumn,                 /* xColumn - read data */
10853     expertRowid,                  /* xRowid - read data */
10854     expertUpdate,                 /* xUpdate - write data */
10855     0,                            /* xBegin - begin transaction */
10856     0,                            /* xSync - sync transaction */
10857     0,                            /* xCommit - commit transaction */
10858     0,                            /* xRollback - rollback transaction */
10859     0,                            /* xFindFunction - function overloading */
10860     0,                            /* xRename - rename the table */
10861     0,                            /* xSavepoint */
10862     0,                            /* xRelease */
10863     0,                            /* xRollbackTo */
10864     0,                            /* xShadowName */
10865   };
10866 
10867   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
10868 }
10869 /*
10870 ** End of virtual table implementation.
10871 *************************************************************************/
10872 /*
10873 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
10874 ** is called, set it to the return value of sqlite3_finalize() before
10875 ** returning. Otherwise, discard the sqlite3_finalize() return value.
10876 */
10877 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
10878   int rc = sqlite3_finalize(pStmt);
10879   if( *pRc==SQLITE_OK ) *pRc = rc;
10880 }
10881 
10882 /*
10883 ** Attempt to allocate an IdxTable structure corresponding to table zTab
10884 ** in the main database of connection db. If successful, set (*ppOut) to
10885 ** point to the new object and return SQLITE_OK. Otherwise, return an
10886 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
10887 ** set to point to an error string.
10888 **
10889 ** It is the responsibility of the caller to eventually free either the
10890 ** IdxTable object or error message using sqlite3_free().
10891 */
10892 static int idxGetTableInfo(
10893   sqlite3 *db,                    /* Database connection to read details from */
10894   const char *zTab,               /* Table name */
10895   IdxTable **ppOut,               /* OUT: New object (if successful) */
10896   char **pzErrmsg                 /* OUT: Error message (if not) */
10897 ){
10898   sqlite3_stmt *p1 = 0;
10899   int nCol = 0;
10900   int nTab;
10901   int nByte;
10902   IdxTable *pNew = 0;
10903   int rc, rc2;
10904   char *pCsr = 0;
10905   int nPk = 0;
10906 
10907   *ppOut = 0;
10908   if( zTab==0 ) return SQLITE_ERROR;
10909   nTab = STRLEN(zTab);
10910   nByte = sizeof(IdxTable) + nTab + 1;
10911   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
10912   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
10913     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
10914     const char *zColSeq = 0;
10915     if( zCol==0 ){
10916       rc = SQLITE_ERROR;
10917       break;
10918     }
10919     nByte += 1 + STRLEN(zCol);
10920     rc = sqlite3_table_column_metadata(
10921         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
10922     );
10923     if( zColSeq==0 ) zColSeq = "binary";
10924     nByte += 1 + STRLEN(zColSeq);
10925     nCol++;
10926     nPk += (sqlite3_column_int(p1, 5)>0);
10927   }
10928   rc2 = sqlite3_reset(p1);
10929   if( rc==SQLITE_OK ) rc = rc2;
10930 
10931   nByte += sizeof(IdxColumn) * nCol;
10932   if( rc==SQLITE_OK ){
10933     pNew = idxMalloc(&rc, nByte);
10934   }
10935   if( rc==SQLITE_OK ){
10936     pNew->aCol = (IdxColumn*)&pNew[1];
10937     pNew->nCol = nCol;
10938     pCsr = (char*)&pNew->aCol[nCol];
10939   }
10940 
10941   nCol = 0;
10942   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
10943     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
10944     const char *zColSeq = 0;
10945     int nCopy;
10946     if( zCol==0 ) continue;
10947     nCopy = STRLEN(zCol) + 1;
10948     pNew->aCol[nCol].zName = pCsr;
10949     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
10950     memcpy(pCsr, zCol, nCopy);
10951     pCsr += nCopy;
10952 
10953     rc = sqlite3_table_column_metadata(
10954         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
10955     );
10956     if( rc==SQLITE_OK ){
10957       if( zColSeq==0 ) zColSeq = "binary";
10958       nCopy = STRLEN(zColSeq) + 1;
10959       pNew->aCol[nCol].zColl = pCsr;
10960       memcpy(pCsr, zColSeq, nCopy);
10961       pCsr += nCopy;
10962     }
10963 
10964     nCol++;
10965   }
10966   idxFinalize(&rc, p1);
10967 
10968   if( rc!=SQLITE_OK ){
10969     sqlite3_free(pNew);
10970     pNew = 0;
10971   }else if( ALWAYS(pNew!=0) ){
10972     pNew->zName = pCsr;
10973     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
10974   }
10975 
10976   *ppOut = pNew;
10977   return rc;
10978 }
10979 
10980 /*
10981 ** This function is a no-op if *pRc is set to anything other than
10982 ** SQLITE_OK when it is called.
10983 **
10984 ** If *pRc is initially set to SQLITE_OK, then the text specified by
10985 ** the printf() style arguments is appended to zIn and the result returned
10986 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
10987 ** zIn before returning.
10988 */
10989 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
10990   va_list ap;
10991   char *zAppend = 0;
10992   char *zRet = 0;
10993   int nIn = zIn ? STRLEN(zIn) : 0;
10994   int nAppend = 0;
10995   va_start(ap, zFmt);
10996   if( *pRc==SQLITE_OK ){
10997     zAppend = sqlite3_vmprintf(zFmt, ap);
10998     if( zAppend ){
10999       nAppend = STRLEN(zAppend);
11000       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
11001     }
11002     if( zAppend && zRet ){
11003       if( nIn ) memcpy(zRet, zIn, nIn);
11004       memcpy(&zRet[nIn], zAppend, nAppend+1);
11005     }else{
11006       sqlite3_free(zRet);
11007       zRet = 0;
11008       *pRc = SQLITE_NOMEM;
11009     }
11010     sqlite3_free(zAppend);
11011     sqlite3_free(zIn);
11012   }
11013   va_end(ap);
11014   return zRet;
11015 }
11016 
11017 /*
11018 ** Return true if zId must be quoted in order to use it as an SQL
11019 ** identifier, or false otherwise.
11020 */
11021 static int idxIdentifierRequiresQuotes(const char *zId){
11022   int i;
11023   int nId = STRLEN(zId);
11024 
11025   if( sqlite3_keyword_check(zId, nId) ) return 1;
11026 
11027   for(i=0; zId[i]; i++){
11028     if( !(zId[i]=='_')
11029      && !(zId[i]>='0' && zId[i]<='9')
11030      && !(zId[i]>='a' && zId[i]<='z')
11031      && !(zId[i]>='A' && zId[i]<='Z')
11032     ){
11033       return 1;
11034     }
11035   }
11036   return 0;
11037 }
11038 
11039 /*
11040 ** This function appends an index column definition suitable for constraint
11041 ** pCons to the string passed as zIn and returns the result.
11042 */
11043 static char *idxAppendColDefn(
11044   int *pRc,                       /* IN/OUT: Error code */
11045   char *zIn,                      /* Column defn accumulated so far */
11046   IdxTable *pTab,                 /* Table index will be created on */
11047   IdxConstraint *pCons
11048 ){
11049   char *zRet = zIn;
11050   IdxColumn *p = &pTab->aCol[pCons->iCol];
11051   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
11052 
11053   if( idxIdentifierRequiresQuotes(p->zName) ){
11054     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
11055   }else{
11056     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
11057   }
11058 
11059   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
11060     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
11061       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
11062     }else{
11063       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
11064     }
11065   }
11066 
11067   if( pCons->bDesc ){
11068     zRet = idxAppendText(pRc, zRet, " DESC");
11069   }
11070   return zRet;
11071 }
11072 
11073 /*
11074 ** Search database dbm for an index compatible with the one idxCreateFromCons()
11075 ** would create from arguments pScan, pEq and pTail. If no error occurs and
11076 ** such an index is found, return non-zero. Or, if no such index is found,
11077 ** return zero.
11078 **
11079 ** If an error occurs, set *pRc to an SQLite error code and return zero.
11080 */
11081 static int idxFindCompatible(
11082   int *pRc,                       /* OUT: Error code */
11083   sqlite3* dbm,                   /* Database to search */
11084   IdxScan *pScan,                 /* Scan for table to search for index on */
11085   IdxConstraint *pEq,             /* List of == constraints */
11086   IdxConstraint *pTail            /* List of range constraints */
11087 ){
11088   const char *zTbl = pScan->pTab->zName;
11089   sqlite3_stmt *pIdxList = 0;
11090   IdxConstraint *pIter;
11091   int nEq = 0;                    /* Number of elements in pEq */
11092   int rc;
11093 
11094   /* Count the elements in list pEq */
11095   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
11096 
11097   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
11098   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
11099     int bMatch = 1;
11100     IdxConstraint *pT = pTail;
11101     sqlite3_stmt *pInfo = 0;
11102     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
11103     if( zIdx==0 ) continue;
11104 
11105     /* Zero the IdxConstraint.bFlag values in the pEq list */
11106     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
11107 
11108     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
11109     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
11110       int iIdx = sqlite3_column_int(pInfo, 0);
11111       int iCol = sqlite3_column_int(pInfo, 1);
11112       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
11113 
11114       if( iIdx<nEq ){
11115         for(pIter=pEq; pIter; pIter=pIter->pLink){
11116           if( pIter->bFlag ) continue;
11117           if( pIter->iCol!=iCol ) continue;
11118           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
11119           pIter->bFlag = 1;
11120           break;
11121         }
11122         if( pIter==0 ){
11123           bMatch = 0;
11124           break;
11125         }
11126       }else{
11127         if( pT ){
11128           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
11129             bMatch = 0;
11130             break;
11131           }
11132           pT = pT->pLink;
11133         }
11134       }
11135     }
11136     idxFinalize(&rc, pInfo);
11137 
11138     if( rc==SQLITE_OK && bMatch ){
11139       sqlite3_finalize(pIdxList);
11140       return 1;
11141     }
11142   }
11143   idxFinalize(&rc, pIdxList);
11144 
11145   *pRc = rc;
11146   return 0;
11147 }
11148 
11149 /* Callback for sqlite3_exec() with query with leading count(*) column.
11150  * The first argument is expected to be an int*, referent to be incremented
11151  * if that leading column is not exactly '0'.
11152  */
11153 static int countNonzeros(void* pCount, int nc,
11154                          char* azResults[], char* azColumns[]){
11155   (void)azColumns;  /* Suppress unused parameter warning */
11156   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
11157     *((int *)pCount) += 1;
11158   }
11159   return 0;
11160 }
11161 
11162 static int idxCreateFromCons(
11163   sqlite3expert *p,
11164   IdxScan *pScan,
11165   IdxConstraint *pEq,
11166   IdxConstraint *pTail
11167 ){
11168   sqlite3 *dbm = p->dbm;
11169   int rc = SQLITE_OK;
11170   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
11171     IdxTable *pTab = pScan->pTab;
11172     char *zCols = 0;
11173     char *zIdx = 0;
11174     IdxConstraint *pCons;
11175     unsigned int h = 0;
11176     const char *zFmt;
11177 
11178     for(pCons=pEq; pCons; pCons=pCons->pLink){
11179       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
11180     }
11181     for(pCons=pTail; pCons; pCons=pCons->pLink){
11182       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
11183     }
11184 
11185     if( rc==SQLITE_OK ){
11186       /* Hash the list of columns to come up with a name for the index */
11187       const char *zTable = pScan->pTab->zName;
11188       int quoteTable = idxIdentifierRequiresQuotes(zTable);
11189       char *zName = 0;          /* Index name */
11190       int collisions = 0;
11191       do{
11192         int i;
11193         char *zFind;
11194         for(i=0; zCols[i]; i++){
11195           h += ((h<<3) + zCols[i]);
11196         }
11197         sqlite3_free(zName);
11198         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
11199         if( zName==0 ) break;
11200         /* Is is unique among table, view and index names? */
11201         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
11202           " AND type in ('index','table','view')";
11203         zFind = sqlite3_mprintf(zFmt, zName);
11204         i = 0;
11205         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
11206         assert(rc==SQLITE_OK);
11207         sqlite3_free(zFind);
11208         if( i==0 ){
11209           collisions = 0;
11210           break;
11211         }
11212         ++collisions;
11213       }while( collisions<50 && zName!=0 );
11214       if( collisions ){
11215         /* This return means "Gave up trying to find a unique index name." */
11216         rc = SQLITE_BUSY_TIMEOUT;
11217       }else if( zName==0 ){
11218         rc = SQLITE_NOMEM;
11219       }else{
11220         if( quoteTable ){
11221           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
11222         }else{
11223           zFmt = "CREATE INDEX %s ON %s(%s)";
11224         }
11225         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
11226         if( !zIdx ){
11227           rc = SQLITE_NOMEM;
11228         }else{
11229           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
11230           if( rc!=SQLITE_OK ){
11231             rc = SQLITE_BUSY_TIMEOUT;
11232           }else{
11233             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
11234           }
11235         }
11236         sqlite3_free(zName);
11237         sqlite3_free(zIdx);
11238       }
11239     }
11240 
11241     sqlite3_free(zCols);
11242   }
11243   return rc;
11244 }
11245 
11246 /*
11247 ** Return true if list pList (linked by IdxConstraint.pLink) contains
11248 ** a constraint compatible with *p. Otherwise return false.
11249 */
11250 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
11251   IdxConstraint *pCmp;
11252   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
11253     if( p->iCol==pCmp->iCol ) return 1;
11254   }
11255   return 0;
11256 }
11257 
11258 static int idxCreateFromWhere(
11259   sqlite3expert *p,
11260   IdxScan *pScan,                 /* Create indexes for this scan */
11261   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
11262 ){
11263   IdxConstraint *p1 = 0;
11264   IdxConstraint *pCon;
11265   int rc;
11266 
11267   /* Gather up all the == constraints. */
11268   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
11269     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
11270       pCon->pLink = p1;
11271       p1 = pCon;
11272     }
11273   }
11274 
11275   /* Create an index using the == constraints collected above. And the
11276   ** range constraint/ORDER BY terms passed in by the caller, if any. */
11277   rc = idxCreateFromCons(p, pScan, p1, pTail);
11278 
11279   /* If no range/ORDER BY passed by the caller, create a version of the
11280   ** index for each range constraint.  */
11281   if( pTail==0 ){
11282     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
11283       assert( pCon->pLink==0 );
11284       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
11285         rc = idxCreateFromCons(p, pScan, p1, pCon);
11286       }
11287     }
11288   }
11289 
11290   return rc;
11291 }
11292 
11293 /*
11294 ** Create candidate indexes in database [dbm] based on the data in
11295 ** linked-list pScan.
11296 */
11297 static int idxCreateCandidates(sqlite3expert *p){
11298   int rc = SQLITE_OK;
11299   IdxScan *pIter;
11300 
11301   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
11302     rc = idxCreateFromWhere(p, pIter, 0);
11303     if( rc==SQLITE_OK && pIter->pOrder ){
11304       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
11305     }
11306   }
11307 
11308   return rc;
11309 }
11310 
11311 /*
11312 ** Free all elements of the linked list starting at pConstraint.
11313 */
11314 static void idxConstraintFree(IdxConstraint *pConstraint){
11315   IdxConstraint *pNext;
11316   IdxConstraint *p;
11317 
11318   for(p=pConstraint; p; p=pNext){
11319     pNext = p->pNext;
11320     sqlite3_free(p);
11321   }
11322 }
11323 
11324 /*
11325 ** Free all elements of the linked list starting from pScan up until pLast
11326 ** (pLast is not freed).
11327 */
11328 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
11329   IdxScan *p;
11330   IdxScan *pNext;
11331   for(p=pScan; p!=pLast; p=pNext){
11332     pNext = p->pNextScan;
11333     idxConstraintFree(p->pOrder);
11334     idxConstraintFree(p->pEq);
11335     idxConstraintFree(p->pRange);
11336     sqlite3_free(p);
11337   }
11338 }
11339 
11340 /*
11341 ** Free all elements of the linked list starting from pStatement up
11342 ** until pLast (pLast is not freed).
11343 */
11344 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
11345   IdxStatement *p;
11346   IdxStatement *pNext;
11347   for(p=pStatement; p!=pLast; p=pNext){
11348     pNext = p->pNext;
11349     sqlite3_free(p->zEQP);
11350     sqlite3_free(p->zIdx);
11351     sqlite3_free(p);
11352   }
11353 }
11354 
11355 /*
11356 ** Free the linked list of IdxTable objects starting at pTab.
11357 */
11358 static void idxTableFree(IdxTable *pTab){
11359   IdxTable *pIter;
11360   IdxTable *pNext;
11361   for(pIter=pTab; pIter; pIter=pNext){
11362     pNext = pIter->pNext;
11363     sqlite3_free(pIter);
11364   }
11365 }
11366 
11367 /*
11368 ** Free the linked list of IdxWrite objects starting at pTab.
11369 */
11370 static void idxWriteFree(IdxWrite *pTab){
11371   IdxWrite *pIter;
11372   IdxWrite *pNext;
11373   for(pIter=pTab; pIter; pIter=pNext){
11374     pNext = pIter->pNext;
11375     sqlite3_free(pIter);
11376   }
11377 }
11378 
11379 
11380 
11381 /*
11382 ** This function is called after candidate indexes have been created. It
11383 ** runs all the queries to see which indexes they prefer, and populates
11384 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
11385 */
11386 static int idxFindIndexes(
11387   sqlite3expert *p,
11388   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
11389 ){
11390   IdxStatement *pStmt;
11391   sqlite3 *dbm = p->dbm;
11392   int rc = SQLITE_OK;
11393 
11394   IdxHash hIdx;
11395   idxHashInit(&hIdx);
11396 
11397   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
11398     IdxHashEntry *pEntry;
11399     sqlite3_stmt *pExplain = 0;
11400     idxHashClear(&hIdx);
11401     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
11402         "EXPLAIN QUERY PLAN %s", pStmt->zSql
11403     );
11404     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
11405       /* int iId = sqlite3_column_int(pExplain, 0); */
11406       /* int iParent = sqlite3_column_int(pExplain, 1); */
11407       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
11408       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
11409       int nDetail;
11410       int i;
11411 
11412       if( !zDetail ) continue;
11413       nDetail = STRLEN(zDetail);
11414 
11415       for(i=0; i<nDetail; i++){
11416         const char *zIdx = 0;
11417         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
11418           zIdx = &zDetail[i+13];
11419         }else if( i+22<nDetail
11420             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
11421         ){
11422           zIdx = &zDetail[i+22];
11423         }
11424         if( zIdx ){
11425           const char *zSql;
11426           int nIdx = 0;
11427           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
11428             nIdx++;
11429           }
11430           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
11431           if( zSql ){
11432             idxHashAdd(&rc, &hIdx, zSql, 0);
11433             if( rc ) goto find_indexes_out;
11434           }
11435           break;
11436         }
11437       }
11438 
11439       if( zDetail[0]!='-' ){
11440         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
11441       }
11442     }
11443 
11444     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
11445       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
11446     }
11447 
11448     idxFinalize(&rc, pExplain);
11449   }
11450 
11451  find_indexes_out:
11452   idxHashClear(&hIdx);
11453   return rc;
11454 }
11455 
11456 static int idxAuthCallback(
11457   void *pCtx,
11458   int eOp,
11459   const char *z3,
11460   const char *z4,
11461   const char *zDb,
11462   const char *zTrigger
11463 ){
11464   int rc = SQLITE_OK;
11465   (void)z4;
11466   (void)zTrigger;
11467   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
11468     if( sqlite3_stricmp(zDb, "main")==0 ){
11469       sqlite3expert *p = (sqlite3expert*)pCtx;
11470       IdxTable *pTab;
11471       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
11472         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
11473       }
11474       if( pTab ){
11475         IdxWrite *pWrite;
11476         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
11477           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
11478         }
11479         if( pWrite==0 ){
11480           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
11481           if( rc==SQLITE_OK ){
11482             pWrite->pTab = pTab;
11483             pWrite->eOp = eOp;
11484             pWrite->pNext = p->pWrite;
11485             p->pWrite = pWrite;
11486           }
11487         }
11488       }
11489     }
11490   }
11491   return rc;
11492 }
11493 
11494 static int idxProcessOneTrigger(
11495   sqlite3expert *p,
11496   IdxWrite *pWrite,
11497   char **pzErr
11498 ){
11499   static const char *zInt = UNIQUE_TABLE_NAME;
11500   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
11501   IdxTable *pTab = pWrite->pTab;
11502   const char *zTab = pTab->zName;
11503   const char *zSql =
11504     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
11505     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
11506     "ORDER BY type;";
11507   sqlite3_stmt *pSelect = 0;
11508   int rc = SQLITE_OK;
11509   char *zWrite = 0;
11510 
11511   /* Create the table and its triggers in the temp schema */
11512   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
11513   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
11514     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
11515     if( zCreate==0 ) continue;
11516     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
11517   }
11518   idxFinalize(&rc, pSelect);
11519 
11520   /* Rename the table in the temp schema to zInt */
11521   if( rc==SQLITE_OK ){
11522     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
11523     if( z==0 ){
11524       rc = SQLITE_NOMEM;
11525     }else{
11526       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
11527       sqlite3_free(z);
11528     }
11529   }
11530 
11531   switch( pWrite->eOp ){
11532     case SQLITE_INSERT: {
11533       int i;
11534       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
11535       for(i=0; i<pTab->nCol; i++){
11536         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
11537       }
11538       zWrite = idxAppendText(&rc, zWrite, ")");
11539       break;
11540     }
11541     case SQLITE_UPDATE: {
11542       int i;
11543       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
11544       for(i=0; i<pTab->nCol; i++){
11545         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
11546             pTab->aCol[i].zName
11547         );
11548       }
11549       break;
11550     }
11551     default: {
11552       assert( pWrite->eOp==SQLITE_DELETE );
11553       if( rc==SQLITE_OK ){
11554         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
11555         if( zWrite==0 ) rc = SQLITE_NOMEM;
11556       }
11557     }
11558   }
11559 
11560   if( rc==SQLITE_OK ){
11561     sqlite3_stmt *pX = 0;
11562     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
11563     idxFinalize(&rc, pX);
11564     if( rc!=SQLITE_OK ){
11565       idxDatabaseError(p->dbv, pzErr);
11566     }
11567   }
11568   sqlite3_free(zWrite);
11569 
11570   if( rc==SQLITE_OK ){
11571     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
11572   }
11573 
11574   return rc;
11575 }
11576 
11577 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
11578   int rc = SQLITE_OK;
11579   IdxWrite *pEnd = 0;
11580   IdxWrite *pFirst = p->pWrite;
11581 
11582   while( rc==SQLITE_OK && pFirst!=pEnd ){
11583     IdxWrite *pIter;
11584     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
11585       rc = idxProcessOneTrigger(p, pIter, pzErr);
11586     }
11587     pEnd = pFirst;
11588     pFirst = p->pWrite;
11589   }
11590 
11591   return rc;
11592 }
11593 
11594 
11595 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
11596   int rc = idxRegisterVtab(p);
11597   sqlite3_stmt *pSchema = 0;
11598 
11599   /* For each table in the main db schema:
11600   **
11601   **   1) Add an entry to the p->pTable list, and
11602   **   2) Create the equivalent virtual table in dbv.
11603   */
11604   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
11605       "SELECT type, name, sql, 1 FROM sqlite_schema "
11606       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
11607       " UNION ALL "
11608       "SELECT type, name, sql, 2 FROM sqlite_schema "
11609       "WHERE type = 'trigger'"
11610       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
11611       "ORDER BY 4, 1"
11612   );
11613   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
11614     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
11615     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
11616     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
11617 
11618     if( zType==0 || zName==0 ) continue;
11619     if( zType[0]=='v' || zType[1]=='r' ){
11620       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
11621     }else{
11622       IdxTable *pTab;
11623       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
11624       if( rc==SQLITE_OK ){
11625         int i;
11626         char *zInner = 0;
11627         char *zOuter = 0;
11628         pTab->pNext = p->pTable;
11629         p->pTable = pTab;
11630 
11631         /* The statement the vtab will pass to sqlite3_declare_vtab() */
11632         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
11633         for(i=0; i<pTab->nCol; i++){
11634           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
11635               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
11636           );
11637         }
11638         zInner = idxAppendText(&rc, zInner, ")");
11639 
11640         /* The CVT statement to create the vtab */
11641         zOuter = idxAppendText(&rc, 0,
11642             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
11643         );
11644         if( rc==SQLITE_OK ){
11645           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
11646         }
11647         sqlite3_free(zInner);
11648         sqlite3_free(zOuter);
11649       }
11650     }
11651   }
11652   idxFinalize(&rc, pSchema);
11653   return rc;
11654 }
11655 
11656 struct IdxSampleCtx {
11657   int iTarget;
11658   double target;                  /* Target nRet/nRow value */
11659   double nRow;                    /* Number of rows seen */
11660   double nRet;                    /* Number of rows returned */
11661 };
11662 
11663 static void idxSampleFunc(
11664   sqlite3_context *pCtx,
11665   int argc,
11666   sqlite3_value **argv
11667 ){
11668   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
11669   int bRet;
11670 
11671   (void)argv;
11672   assert( argc==0 );
11673   if( p->nRow==0.0 ){
11674     bRet = 1;
11675   }else{
11676     bRet = (p->nRet / p->nRow) <= p->target;
11677     if( bRet==0 ){
11678       unsigned short rnd;
11679       sqlite3_randomness(2, (void*)&rnd);
11680       bRet = ((int)rnd % 100) <= p->iTarget;
11681     }
11682   }
11683 
11684   sqlite3_result_int(pCtx, bRet);
11685   p->nRow += 1.0;
11686   p->nRet += (double)bRet;
11687 }
11688 
11689 struct IdxRemCtx {
11690   int nSlot;
11691   struct IdxRemSlot {
11692     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
11693     i64 iVal;                     /* SQLITE_INTEGER value */
11694     double rVal;                  /* SQLITE_FLOAT value */
11695     int nByte;                    /* Bytes of space allocated at z */
11696     int n;                        /* Size of buffer z */
11697     char *z;                      /* SQLITE_TEXT/BLOB value */
11698   } aSlot[1];
11699 };
11700 
11701 /*
11702 ** Implementation of scalar function rem().
11703 */
11704 static void idxRemFunc(
11705   sqlite3_context *pCtx,
11706   int argc,
11707   sqlite3_value **argv
11708 ){
11709   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
11710   struct IdxRemSlot *pSlot;
11711   int iSlot;
11712   assert( argc==2 );
11713 
11714   iSlot = sqlite3_value_int(argv[0]);
11715   assert( iSlot<=p->nSlot );
11716   pSlot = &p->aSlot[iSlot];
11717 
11718   switch( pSlot->eType ){
11719     case SQLITE_NULL:
11720       /* no-op */
11721       break;
11722 
11723     case SQLITE_INTEGER:
11724       sqlite3_result_int64(pCtx, pSlot->iVal);
11725       break;
11726 
11727     case SQLITE_FLOAT:
11728       sqlite3_result_double(pCtx, pSlot->rVal);
11729       break;
11730 
11731     case SQLITE_BLOB:
11732       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
11733       break;
11734 
11735     case SQLITE_TEXT:
11736       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
11737       break;
11738   }
11739 
11740   pSlot->eType = sqlite3_value_type(argv[1]);
11741   switch( pSlot->eType ){
11742     case SQLITE_NULL:
11743       /* no-op */
11744       break;
11745 
11746     case SQLITE_INTEGER:
11747       pSlot->iVal = sqlite3_value_int64(argv[1]);
11748       break;
11749 
11750     case SQLITE_FLOAT:
11751       pSlot->rVal = sqlite3_value_double(argv[1]);
11752       break;
11753 
11754     case SQLITE_BLOB:
11755     case SQLITE_TEXT: {
11756       int nByte = sqlite3_value_bytes(argv[1]);
11757       const void *pData = 0;
11758       if( nByte>pSlot->nByte ){
11759         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
11760         if( zNew==0 ){
11761           sqlite3_result_error_nomem(pCtx);
11762           return;
11763         }
11764         pSlot->nByte = nByte*2;
11765         pSlot->z = zNew;
11766       }
11767       pSlot->n = nByte;
11768       if( pSlot->eType==SQLITE_BLOB ){
11769         pData = sqlite3_value_blob(argv[1]);
11770         if( pData ) memcpy(pSlot->z, pData, nByte);
11771       }else{
11772         pData = sqlite3_value_text(argv[1]);
11773         memcpy(pSlot->z, pData, nByte);
11774       }
11775       break;
11776     }
11777   }
11778 }
11779 
11780 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
11781   int rc = SQLITE_OK;
11782   const char *zMax =
11783     "SELECT max(i.seqno) FROM "
11784     "  sqlite_schema AS s, "
11785     "  pragma_index_list(s.name) AS l, "
11786     "  pragma_index_info(l.name) AS i "
11787     "WHERE s.type = 'table'";
11788   sqlite3_stmt *pMax = 0;
11789 
11790   *pnMax = 0;
11791   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
11792   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
11793     *pnMax = sqlite3_column_int(pMax, 0) + 1;
11794   }
11795   idxFinalize(&rc, pMax);
11796 
11797   return rc;
11798 }
11799 
11800 static int idxPopulateOneStat1(
11801   sqlite3expert *p,
11802   sqlite3_stmt *pIndexXInfo,
11803   sqlite3_stmt *pWriteStat,
11804   const char *zTab,
11805   const char *zIdx,
11806   char **pzErr
11807 ){
11808   char *zCols = 0;
11809   char *zOrder = 0;
11810   char *zQuery = 0;
11811   int nCol = 0;
11812   int i;
11813   sqlite3_stmt *pQuery = 0;
11814   int *aStat = 0;
11815   int rc = SQLITE_OK;
11816 
11817   assert( p->iSample>0 );
11818 
11819   /* Formulate the query text */
11820   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
11821   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
11822     const char *zComma = zCols==0 ? "" : ", ";
11823     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
11824     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
11825     zCols = idxAppendText(&rc, zCols,
11826         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
11827     );
11828     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
11829   }
11830   sqlite3_reset(pIndexXInfo);
11831   if( rc==SQLITE_OK ){
11832     if( p->iSample==100 ){
11833       zQuery = sqlite3_mprintf(
11834           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
11835       );
11836     }else{
11837       zQuery = sqlite3_mprintf(
11838           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
11839       );
11840     }
11841   }
11842   sqlite3_free(zCols);
11843   sqlite3_free(zOrder);
11844 
11845   /* Formulate the query text */
11846   if( rc==SQLITE_OK ){
11847     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
11848     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
11849   }
11850   sqlite3_free(zQuery);
11851 
11852   if( rc==SQLITE_OK ){
11853     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
11854   }
11855   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
11856     IdxHashEntry *pEntry;
11857     char *zStat = 0;
11858     for(i=0; i<=nCol; i++) aStat[i] = 1;
11859     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
11860       aStat[0]++;
11861       for(i=0; i<nCol; i++){
11862         if( sqlite3_column_int(pQuery, i)==0 ) break;
11863       }
11864       for(/*no-op*/; i<nCol; i++){
11865         aStat[i+1]++;
11866       }
11867     }
11868 
11869     if( rc==SQLITE_OK ){
11870       int s0 = aStat[0];
11871       zStat = sqlite3_mprintf("%d", s0);
11872       if( zStat==0 ) rc = SQLITE_NOMEM;
11873       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
11874         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
11875       }
11876     }
11877 
11878     if( rc==SQLITE_OK ){
11879       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
11880       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
11881       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
11882       sqlite3_step(pWriteStat);
11883       rc = sqlite3_reset(pWriteStat);
11884     }
11885 
11886     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
11887     if( pEntry ){
11888       assert( pEntry->zVal2==0 );
11889       pEntry->zVal2 = zStat;
11890     }else{
11891       sqlite3_free(zStat);
11892     }
11893   }
11894   sqlite3_free(aStat);
11895   idxFinalize(&rc, pQuery);
11896 
11897   return rc;
11898 }
11899 
11900 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
11901   int rc;
11902   char *zSql;
11903 
11904   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
11905   if( rc!=SQLITE_OK ) return rc;
11906 
11907   zSql = sqlite3_mprintf(
11908       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
11909   );
11910   if( zSql==0 ) return SQLITE_NOMEM;
11911   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
11912   sqlite3_free(zSql);
11913 
11914   return rc;
11915 }
11916 
11917 /*
11918 ** This function is called as part of sqlite3_expert_analyze(). Candidate
11919 ** indexes have already been created in database sqlite3expert.dbm, this
11920 ** function populates sqlite_stat1 table in the same database.
11921 **
11922 ** The stat1 data is generated by querying the
11923 */
11924 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
11925   int rc = SQLITE_OK;
11926   int nMax =0;
11927   struct IdxRemCtx *pCtx = 0;
11928   struct IdxSampleCtx samplectx;
11929   int i;
11930   i64 iPrev = -100000;
11931   sqlite3_stmt *pAllIndex = 0;
11932   sqlite3_stmt *pIndexXInfo = 0;
11933   sqlite3_stmt *pWrite = 0;
11934 
11935   const char *zAllIndex =
11936     "SELECT s.rowid, s.name, l.name FROM "
11937     "  sqlite_schema AS s, "
11938     "  pragma_index_list(s.name) AS l "
11939     "WHERE s.type = 'table'";
11940   const char *zIndexXInfo =
11941     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
11942   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
11943 
11944   /* If iSample==0, no sqlite_stat1 data is required. */
11945   if( p->iSample==0 ) return SQLITE_OK;
11946 
11947   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
11948   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
11949 
11950   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
11951 
11952   if( rc==SQLITE_OK ){
11953     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
11954     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
11955   }
11956 
11957   if( rc==SQLITE_OK ){
11958     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
11959     rc = sqlite3_create_function(
11960         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
11961     );
11962   }
11963   if( rc==SQLITE_OK ){
11964     rc = sqlite3_create_function(
11965         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
11966     );
11967   }
11968 
11969   if( rc==SQLITE_OK ){
11970     pCtx->nSlot = nMax+1;
11971     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
11972   }
11973   if( rc==SQLITE_OK ){
11974     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
11975   }
11976   if( rc==SQLITE_OK ){
11977     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
11978   }
11979 
11980   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
11981     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
11982     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
11983     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
11984     if( zTab==0 || zIdx==0 ) continue;
11985     if( p->iSample<100 && iPrev!=iRowid ){
11986       samplectx.target = (double)p->iSample / 100.0;
11987       samplectx.iTarget = p->iSample;
11988       samplectx.nRow = 0.0;
11989       samplectx.nRet = 0.0;
11990       rc = idxBuildSampleTable(p, zTab);
11991       if( rc!=SQLITE_OK ) break;
11992     }
11993     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
11994     iPrev = iRowid;
11995   }
11996   if( rc==SQLITE_OK && p->iSample<100 ){
11997     rc = sqlite3_exec(p->dbv,
11998         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
11999     );
12000   }
12001 
12002   idxFinalize(&rc, pAllIndex);
12003   idxFinalize(&rc, pIndexXInfo);
12004   idxFinalize(&rc, pWrite);
12005 
12006   if( pCtx ){
12007     for(i=0; i<pCtx->nSlot; i++){
12008       sqlite3_free(pCtx->aSlot[i].z);
12009     }
12010     sqlite3_free(pCtx);
12011   }
12012 
12013   if( rc==SQLITE_OK ){
12014     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
12015   }
12016 
12017   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
12018   return rc;
12019 }
12020 
12021 /*
12022 ** Allocate a new sqlite3expert object.
12023 */
12024 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
12025   int rc = SQLITE_OK;
12026   sqlite3expert *pNew;
12027 
12028   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
12029 
12030   /* Open two in-memory databases to work with. The "vtab database" (dbv)
12031   ** will contain a virtual table corresponding to each real table in
12032   ** the user database schema, and a copy of each view. It is used to
12033   ** collect information regarding the WHERE, ORDER BY and other clauses
12034   ** of the user's query.
12035   */
12036   if( rc==SQLITE_OK ){
12037     pNew->db = db;
12038     pNew->iSample = 100;
12039     rc = sqlite3_open(":memory:", &pNew->dbv);
12040   }
12041   if( rc==SQLITE_OK ){
12042     rc = sqlite3_open(":memory:", &pNew->dbm);
12043     if( rc==SQLITE_OK ){
12044       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
12045     }
12046   }
12047 
12048 
12049   /* Copy the entire schema of database [db] into [dbm]. */
12050   if( rc==SQLITE_OK ){
12051     sqlite3_stmt *pSql = 0;
12052     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
12053         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
12054         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
12055     );
12056     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12057       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
12058       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
12059     }
12060     idxFinalize(&rc, pSql);
12061   }
12062 
12063   /* Create the vtab schema */
12064   if( rc==SQLITE_OK ){
12065     rc = idxCreateVtabSchema(pNew, pzErrmsg);
12066   }
12067 
12068   /* Register the auth callback with dbv */
12069   if( rc==SQLITE_OK ){
12070     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
12071   }
12072 
12073   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
12074   ** return the new sqlite3expert handle.  */
12075   if( rc!=SQLITE_OK ){
12076     sqlite3_expert_destroy(pNew);
12077     pNew = 0;
12078   }
12079   return pNew;
12080 }
12081 
12082 /*
12083 ** Configure an sqlite3expert object.
12084 */
12085 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
12086   int rc = SQLITE_OK;
12087   va_list ap;
12088   va_start(ap, op);
12089   switch( op ){
12090     case EXPERT_CONFIG_SAMPLE: {
12091       int iVal = va_arg(ap, int);
12092       if( iVal<0 ) iVal = 0;
12093       if( iVal>100 ) iVal = 100;
12094       p->iSample = iVal;
12095       break;
12096     }
12097     default:
12098       rc = SQLITE_NOTFOUND;
12099       break;
12100   }
12101 
12102   va_end(ap);
12103   return rc;
12104 }
12105 
12106 /*
12107 ** Add an SQL statement to the analysis.
12108 */
12109 int sqlite3_expert_sql(
12110   sqlite3expert *p,               /* From sqlite3_expert_new() */
12111   const char *zSql,               /* SQL statement to add */
12112   char **pzErr                    /* OUT: Error message (if any) */
12113 ){
12114   IdxScan *pScanOrig = p->pScan;
12115   IdxStatement *pStmtOrig = p->pStatement;
12116   int rc = SQLITE_OK;
12117   const char *zStmt = zSql;
12118 
12119   if( p->bRun ) return SQLITE_MISUSE;
12120 
12121   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
12122     sqlite3_stmt *pStmt = 0;
12123     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
12124     if( rc==SQLITE_OK ){
12125       if( pStmt ){
12126         IdxStatement *pNew;
12127         const char *z = sqlite3_sql(pStmt);
12128         int n = STRLEN(z);
12129         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
12130         if( rc==SQLITE_OK ){
12131           pNew->zSql = (char*)&pNew[1];
12132           memcpy(pNew->zSql, z, n+1);
12133           pNew->pNext = p->pStatement;
12134           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
12135           p->pStatement = pNew;
12136         }
12137         sqlite3_finalize(pStmt);
12138       }
12139     }else{
12140       idxDatabaseError(p->dbv, pzErr);
12141     }
12142   }
12143 
12144   if( rc!=SQLITE_OK ){
12145     idxScanFree(p->pScan, pScanOrig);
12146     idxStatementFree(p->pStatement, pStmtOrig);
12147     p->pScan = pScanOrig;
12148     p->pStatement = pStmtOrig;
12149   }
12150 
12151   return rc;
12152 }
12153 
12154 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
12155   int rc;
12156   IdxHashEntry *pEntry;
12157 
12158   /* Do trigger processing to collect any extra IdxScan structures */
12159   rc = idxProcessTriggers(p, pzErr);
12160 
12161   /* Create candidate indexes within the in-memory database file */
12162   if( rc==SQLITE_OK ){
12163     rc = idxCreateCandidates(p);
12164   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
12165     if( pzErr )
12166       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
12167     return rc;
12168   }
12169 
12170   /* Generate the stat1 data */
12171   if( rc==SQLITE_OK ){
12172     rc = idxPopulateStat1(p, pzErr);
12173   }
12174 
12175   /* Formulate the EXPERT_REPORT_CANDIDATES text */
12176   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
12177     p->zCandidates = idxAppendText(&rc, p->zCandidates,
12178         "%s;%s%s\n", pEntry->zVal,
12179         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
12180     );
12181   }
12182 
12183   /* Figure out which of the candidate indexes are preferred by the query
12184   ** planner and report the results to the user.  */
12185   if( rc==SQLITE_OK ){
12186     rc = idxFindIndexes(p, pzErr);
12187   }
12188 
12189   if( rc==SQLITE_OK ){
12190     p->bRun = 1;
12191   }
12192   return rc;
12193 }
12194 
12195 /*
12196 ** Return the total number of statements that have been added to this
12197 ** sqlite3expert using sqlite3_expert_sql().
12198 */
12199 int sqlite3_expert_count(sqlite3expert *p){
12200   int nRet = 0;
12201   if( p->pStatement ) nRet = p->pStatement->iId+1;
12202   return nRet;
12203 }
12204 
12205 /*
12206 ** Return a component of the report.
12207 */
12208 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
12209   const char *zRet = 0;
12210   IdxStatement *pStmt;
12211 
12212   if( p->bRun==0 ) return 0;
12213   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
12214   switch( eReport ){
12215     case EXPERT_REPORT_SQL:
12216       if( pStmt ) zRet = pStmt->zSql;
12217       break;
12218     case EXPERT_REPORT_INDEXES:
12219       if( pStmt ) zRet = pStmt->zIdx;
12220       break;
12221     case EXPERT_REPORT_PLAN:
12222       if( pStmt ) zRet = pStmt->zEQP;
12223       break;
12224     case EXPERT_REPORT_CANDIDATES:
12225       zRet = p->zCandidates;
12226       break;
12227   }
12228   return zRet;
12229 }
12230 
12231 /*
12232 ** Free an sqlite3expert object.
12233 */
12234 void sqlite3_expert_destroy(sqlite3expert *p){
12235   if( p ){
12236     sqlite3_close(p->dbm);
12237     sqlite3_close(p->dbv);
12238     idxScanFree(p->pScan, 0);
12239     idxStatementFree(p->pStatement, 0);
12240     idxTableFree(p->pTable);
12241     idxWriteFree(p->pWrite);
12242     idxHashClear(&p->hIdx);
12243     sqlite3_free(p->zCandidates);
12244     sqlite3_free(p);
12245   }
12246 }
12247 
12248 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
12249 
12250 /************************* End ../ext/expert/sqlite3expert.c ********************/
12251 
12252 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12253 #define SQLITE_SHELL_HAVE_RECOVER 1
12254 #else
12255 #define SQLITE_SHELL_HAVE_RECOVER 0
12256 #endif
12257 #if SQLITE_SHELL_HAVE_RECOVER
12258 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
12259 /*
12260 ** 2022-08-27
12261 **
12262 ** The author disclaims copyright to this source code.  In place of
12263 ** a legal notice, here is a blessing:
12264 **
12265 **    May you do good and not evil.
12266 **    May you find forgiveness for yourself and forgive others.
12267 **    May you share freely, never taking more than you give.
12268 **
12269 *************************************************************************
12270 **
12271 ** This file contains the public interface to the "recover" extension -
12272 ** an SQLite extension designed to recover data from corrupted database
12273 ** files.
12274 */
12275 
12276 /*
12277 ** OVERVIEW:
12278 **
12279 ** To use the API to recover data from a corrupted database, an
12280 ** application:
12281 **
12282 **   1) Creates an sqlite3_recover handle by calling either
12283 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
12284 **
12285 **   2) Configures the new handle using one or more calls to
12286 **      sqlite3_recover_config().
12287 **
12288 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
12289 **      the handle until it returns something other than SQLITE_OK. If it
12290 **      returns SQLITE_DONE, then the recovery operation completed without
12291 **      error. If it returns some other non-SQLITE_OK value, then an error
12292 **      has occurred.
12293 **
12294 **   4) Retrieves any error code and English language error message using the
12295 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
12296 **      respectively.
12297 **
12298 **   5) Destroys the sqlite3_recover handle and frees all resources
12299 **      using sqlite3_recover_finish().
12300 **
12301 ** The application may abandon the recovery operation at any point
12302 ** before it is finished by passing the sqlite3_recover handle to
12303 ** sqlite3_recover_finish(). This is not an error, but the final state
12304 ** of the output database, or the results of running the partial script
12305 ** delivered to the SQL callback, are undefined.
12306 */
12307 
12308 #ifndef _SQLITE_RECOVER_H
12309 #define _SQLITE_RECOVER_H
12310 
12311 /* #include "sqlite3.h" */
12312 
12313 #ifdef __cplusplus
12314 extern "C" {
12315 #endif
12316 
12317 /*
12318 ** An instance of the sqlite3_recover object represents a recovery
12319 ** operation in progress.
12320 **
12321 ** Constructors:
12322 **
12323 **    sqlite3_recover_init()
12324 **    sqlite3_recover_init_sql()
12325 **
12326 ** Destructor:
12327 **
12328 **    sqlite3_recover_finish()
12329 **
12330 ** Methods:
12331 **
12332 **    sqlite3_recover_config()
12333 **    sqlite3_recover_errcode()
12334 **    sqlite3_recover_errmsg()
12335 **    sqlite3_recover_run()
12336 **    sqlite3_recover_step()
12337 */
12338 typedef struct sqlite3_recover sqlite3_recover;
12339 
12340 /*
12341 ** These two APIs attempt to create and return a new sqlite3_recover object.
12342 ** In both cases the first two arguments identify the (possibly
12343 ** corrupt) database to recover data from. The first argument is an open
12344 ** database handle and the second the name of a database attached to that
12345 ** handle (i.e. "main", "temp" or the name of an attached database).
12346 **
12347 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
12348 ** handle, then data is recovered into a new database, identified by
12349 ** string parameter zUri. zUri may be an absolute or relative file path,
12350 ** or may be an SQLite URI. If the identified database file already exists,
12351 ** it is overwritten.
12352 **
12353 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
12354 ** be returned to the user as a series of SQL statements. Executing these
12355 ** SQL statements results in the same database as would have been created
12356 ** had sqlite3_recover_init() been used. For each SQL statement in the
12357 ** output, the callback function passed as the third argument (xSql) is
12358 ** invoked once. The first parameter is a passed a copy of the fourth argument
12359 ** to this function (pCtx) as its first parameter, and a pointer to a
12360 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
12361 ** the second. If the xSql callback returns any value other than SQLITE_OK,
12362 ** then processing is immediately abandoned and the value returned used as
12363 ** the recover handle error code (see below).
12364 **
12365 ** If an out-of-memory error occurs, NULL may be returned instead of
12366 ** a valid handle. In all other cases, it is the responsibility of the
12367 ** application to avoid resource leaks by ensuring that
12368 ** sqlite3_recover_finish() is called on all allocated handles.
12369 */
12370 sqlite3_recover *sqlite3_recover_init(
12371   sqlite3* db,
12372   const char *zDb,
12373   const char *zUri
12374 );
12375 sqlite3_recover *sqlite3_recover_init_sql(
12376   sqlite3* db,
12377   const char *zDb,
12378   int (*xSql)(void*, const char*),
12379   void *pCtx
12380 );
12381 
12382 /*
12383 ** Configure an sqlite3_recover object that has just been created using
12384 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
12385 ** may only be called before the first call to sqlite3_recover_step()
12386 ** or sqlite3_recover_run() on the object.
12387 **
12388 ** The second argument passed to this function must be one of the
12389 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
12390 ** depend on the specific SQLITE_RECOVER_* symbol in use.
12391 **
12392 ** SQLITE_OK is returned if the configuration operation was successful,
12393 ** or an SQLite error code otherwise.
12394 */
12395 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
12396 
12397 /*
12398 ** SQLITE_RECOVER_LOST_AND_FOUND:
12399 **   The pArg argument points to a string buffer containing the name
12400 **   of a "lost-and-found" table in the output database, or NULL. If
12401 **   the argument is non-NULL and the database contains seemingly
12402 **   valid pages that cannot be associated with any table in the
12403 **   recovered part of the schema, data is extracted from these
12404 **   pages to add to the lost-and-found table.
12405 **
12406 ** SQLITE_RECOVER_FREELIST_CORRUPT:
12407 **   The pArg value must actually be a pointer to a value of type
12408 **   int containing value 0 or 1 cast as a (void*). If this option is set
12409 **   (argument is 1) and a lost-and-found table has been configured using
12410 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
12411 **   corrupt and an attempt is made to recover records from pages that
12412 **   appear to be linked into the freelist. Otherwise, pages on the freelist
12413 **   are ignored. Setting this option can recover more data from the
12414 **   database, but often ends up "recovering" deleted records. The default
12415 **   value is 0 (clear).
12416 **
12417 ** SQLITE_RECOVER_ROWIDS:
12418 **   The pArg value must actually be a pointer to a value of type
12419 **   int containing value 0 or 1 cast as a (void*). If this option is set
12420 **   (argument is 1), then an attempt is made to recover rowid values
12421 **   that are not also INTEGER PRIMARY KEY values. If this option is
12422 **   clear, then new rowids are assigned to all recovered rows. The
12423 **   default value is 1 (set).
12424 **
12425 ** SQLITE_RECOVER_SLOWINDEXES:
12426 **   The pArg value must actually be a pointer to a value of type
12427 **   int containing value 0 or 1 cast as a (void*). If this option is clear
12428 **   (argument is 0), then when creating an output database, the recover
12429 **   module creates and populates non-UNIQUE indexes right at the end of the
12430 **   recovery operation - after all recoverable data has been inserted
12431 **   into the new database. This is faster overall, but means that the
12432 **   final call to sqlite3_recover_step() for a recovery operation may
12433 **   be need to create a large number of indexes, which may be very slow.
12434 **
12435 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
12436 **   are created in the output database before it is populated with
12437 **   recovered data. This is slower overall, but avoids the slow call
12438 **   to sqlite3_recover_step() at the end of the recovery operation.
12439 **
12440 **   The default option value is 0.
12441 */
12442 #define SQLITE_RECOVER_LOST_AND_FOUND   1
12443 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
12444 #define SQLITE_RECOVER_ROWIDS           3
12445 #define SQLITE_RECOVER_SLOWINDEXES      4
12446 
12447 /*
12448 ** Perform a unit of work towards the recovery operation. This function
12449 ** must normally be called multiple times to complete database recovery.
12450 **
12451 ** If no error occurs but the recovery operation is not completed, this
12452 ** function returns SQLITE_OK. If recovery has been completed successfully
12453 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
12454 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
12455 ** considered an error if some or all of the data cannot be recovered
12456 ** due to database corruption.
12457 **
12458 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
12459 ** all further such calls on the same recover handle are no-ops that return
12460 ** the same non-SQLITE_OK value.
12461 */
12462 int sqlite3_recover_step(sqlite3_recover*);
12463 
12464 /*
12465 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
12466 ** or an SQLite error code otherwise. Calling this function is the same
12467 ** as executing:
12468 **
12469 **     while( SQLITE_OK==sqlite3_recover_step(p) );
12470 **     return sqlite3_recover_errcode(p);
12471 */
12472 int sqlite3_recover_run(sqlite3_recover*);
12473 
12474 /*
12475 ** If an error has been encountered during a prior call to
12476 ** sqlite3_recover_step(), then this function attempts to return a
12477 ** pointer to a buffer containing an English language explanation of
12478 ** the error. If no error message is available, or if an out-of memory
12479 ** error occurs while attempting to allocate a buffer in which to format
12480 ** the error message, NULL is returned.
12481 **
12482 ** The returned buffer remains valid until the sqlite3_recover handle is
12483 ** destroyed using sqlite3_recover_finish().
12484 */
12485 const char *sqlite3_recover_errmsg(sqlite3_recover*);
12486 
12487 /*
12488 ** If this function is called on an sqlite3_recover handle after
12489 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
12490 */
12491 int sqlite3_recover_errcode(sqlite3_recover*);
12492 
12493 /*
12494 ** Clean up a recovery object created by a call to sqlite3_recover_init().
12495 ** The results of using a recovery object with any API after it has been
12496 ** passed to this function are undefined.
12497 **
12498 ** This function returns the same value as sqlite3_recover_errcode().
12499 */
12500 int sqlite3_recover_finish(sqlite3_recover*);
12501 
12502 
12503 #ifdef __cplusplus
12504 }  /* end of the 'extern "C"' block */
12505 #endif
12506 
12507 #endif /* ifndef _SQLITE_RECOVER_H */
12508 
12509 /************************* End ../ext/recover/sqlite3recover.h ********************/
12510 # ifndef SQLITE_HAVE_SQLITE3R
12511 /************************* Begin ../ext/recover/dbdata.c ******************/
12512 /*
12513 ** 2019-04-17
12514 **
12515 ** The author disclaims copyright to this source code.  In place of
12516 ** a legal notice, here is a blessing:
12517 **
12518 **    May you do good and not evil.
12519 **    May you find forgiveness for yourself and forgive others.
12520 **    May you share freely, never taking more than you give.
12521 **
12522 ******************************************************************************
12523 **
12524 ** This file contains an implementation of two eponymous virtual tables,
12525 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
12526 ** "sqlite_dbpage" eponymous virtual table be available.
12527 **
12528 ** SQLITE_DBDATA:
12529 **   sqlite_dbdata is used to extract data directly from a database b-tree
12530 **   page and its associated overflow pages, bypassing the b-tree layer.
12531 **   The table schema is equivalent to:
12532 **
12533 **     CREATE TABLE sqlite_dbdata(
12534 **       pgno INTEGER,
12535 **       cell INTEGER,
12536 **       field INTEGER,
12537 **       value ANY,
12538 **       schema TEXT HIDDEN
12539 **     );
12540 **
12541 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
12542 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
12543 **   "schema".
12544 **
12545 **   Each page of the database is inspected. If it cannot be interpreted as
12546 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
12547 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
12548 **   table contains one row for each field in the record associated with
12549 **   each cell on the page. For intkey b-trees, the key value is stored in
12550 **   field -1.
12551 **
12552 **   For example, for the database:
12553 **
12554 **     CREATE TABLE t1(a, b);     -- root page is page 2
12555 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
12556 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
12557 **
12558 **   the sqlite_dbdata table contains, as well as from entries related to
12559 **   page 1, content equivalent to:
12560 **
12561 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
12562 **         (2, 0, -1, 5     ),
12563 **         (2, 0,  0, 'v'   ),
12564 **         (2, 0,  1, 'five'),
12565 **         (2, 1, -1, 10    ),
12566 **         (2, 1,  0, 'x'   ),
12567 **         (2, 1,  1, 'ten' );
12568 **
12569 **   If database corruption is encountered, this module does not report an
12570 **   error. Instead, it attempts to extract as much data as possible and
12571 **   ignores the corruption.
12572 **
12573 ** SQLITE_DBPTR:
12574 **   The sqlite_dbptr table has the following schema:
12575 **
12576 **     CREATE TABLE sqlite_dbptr(
12577 **       pgno INTEGER,
12578 **       child INTEGER,
12579 **       schema TEXT HIDDEN
12580 **     );
12581 **
12582 **   It contains one entry for each b-tree pointer between a parent and
12583 **   child page in the database.
12584 */
12585 
12586 #if !defined(SQLITEINT_H)
12587 /* #include "sqlite3ext.h" */
12588 
12589 /* typedef unsigned char u8; */
12590 /* typedef unsigned int u32; */
12591 
12592 #endif
12593 SQLITE_EXTENSION_INIT1
12594 #include <string.h>
12595 #include <assert.h>
12596 
12597 #ifndef SQLITE_OMIT_VIRTUALTABLE
12598 
12599 #define DBDATA_PADDING_BYTES 100
12600 
12601 typedef struct DbdataTable DbdataTable;
12602 typedef struct DbdataCursor DbdataCursor;
12603 
12604 /* Cursor object */
12605 struct DbdataCursor {
12606   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
12607   sqlite3_stmt *pStmt;            /* For fetching database pages */
12608 
12609   int iPgno;                      /* Current page number */
12610   u8 *aPage;                      /* Buffer containing page */
12611   int nPage;                      /* Size of aPage[] in bytes */
12612   int nCell;                      /* Number of cells on aPage[] */
12613   int iCell;                      /* Current cell number */
12614   int bOnePage;                   /* True to stop after one page */
12615   int szDb;
12616   sqlite3_int64 iRowid;
12617 
12618   /* Only for the sqlite_dbdata table */
12619   u8 *pRec;                       /* Buffer containing current record */
12620   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
12621   sqlite3_int64 nHdr;             /* Size of header in bytes */
12622   int iField;                     /* Current field number */
12623   u8 *pHdrPtr;
12624   u8 *pPtr;
12625   u32 enc;                        /* Text encoding */
12626 
12627   sqlite3_int64 iIntkey;          /* Integer key value */
12628 };
12629 
12630 /* Table object */
12631 struct DbdataTable {
12632   sqlite3_vtab base;              /* Base class.  Must be first */
12633   sqlite3 *db;                    /* The database connection */
12634   sqlite3_stmt *pStmt;            /* For fetching database pages */
12635   int bPtr;                       /* True for sqlite3_dbptr table */
12636 };
12637 
12638 /* Column and schema definitions for sqlite_dbdata */
12639 #define DBDATA_COLUMN_PGNO        0
12640 #define DBDATA_COLUMN_CELL        1
12641 #define DBDATA_COLUMN_FIELD       2
12642 #define DBDATA_COLUMN_VALUE       3
12643 #define DBDATA_COLUMN_SCHEMA      4
12644 #define DBDATA_SCHEMA             \
12645       "CREATE TABLE x("           \
12646       "  pgno INTEGER,"           \
12647       "  cell INTEGER,"           \
12648       "  field INTEGER,"          \
12649       "  value ANY,"              \
12650       "  schema TEXT HIDDEN"      \
12651       ")"
12652 
12653 /* Column and schema definitions for sqlite_dbptr */
12654 #define DBPTR_COLUMN_PGNO         0
12655 #define DBPTR_COLUMN_CHILD        1
12656 #define DBPTR_COLUMN_SCHEMA       2
12657 #define DBPTR_SCHEMA              \
12658       "CREATE TABLE x("           \
12659       "  pgno INTEGER,"           \
12660       "  child INTEGER,"          \
12661       "  schema TEXT HIDDEN"      \
12662       ")"
12663 
12664 /*
12665 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
12666 ** table.
12667 */
12668 static int dbdataConnect(
12669   sqlite3 *db,
12670   void *pAux,
12671   int argc, const char *const*argv,
12672   sqlite3_vtab **ppVtab,
12673   char **pzErr
12674 ){
12675   DbdataTable *pTab = 0;
12676   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
12677 
12678   (void)argc;
12679   (void)argv;
12680   (void)pzErr;
12681   if( rc==SQLITE_OK ){
12682     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
12683     if( pTab==0 ){
12684       rc = SQLITE_NOMEM;
12685     }else{
12686       memset(pTab, 0, sizeof(DbdataTable));
12687       pTab->db = db;
12688       pTab->bPtr = (pAux!=0);
12689     }
12690   }
12691 
12692   *ppVtab = (sqlite3_vtab*)pTab;
12693   return rc;
12694 }
12695 
12696 /*
12697 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
12698 */
12699 static int dbdataDisconnect(sqlite3_vtab *pVtab){
12700   DbdataTable *pTab = (DbdataTable*)pVtab;
12701   if( pTab ){
12702     sqlite3_finalize(pTab->pStmt);
12703     sqlite3_free(pVtab);
12704   }
12705   return SQLITE_OK;
12706 }
12707 
12708 /*
12709 ** This function interprets two types of constraints:
12710 **
12711 **       schema=?
12712 **       pgno=?
12713 **
12714 ** If neither are present, idxNum is set to 0. If schema=? is present,
12715 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
12716 ** in idxNum is set.
12717 **
12718 ** If both parameters are present, schema is in position 0 and pgno in
12719 ** position 1.
12720 */
12721 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
12722   DbdataTable *pTab = (DbdataTable*)tab;
12723   int i;
12724   int iSchema = -1;
12725   int iPgno = -1;
12726   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
12727 
12728   for(i=0; i<pIdx->nConstraint; i++){
12729     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
12730     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12731       if( p->iColumn==colSchema ){
12732         if( p->usable==0 ) return SQLITE_CONSTRAINT;
12733         iSchema = i;
12734       }
12735       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
12736         iPgno = i;
12737       }
12738     }
12739   }
12740 
12741   if( iSchema>=0 ){
12742     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
12743     pIdx->aConstraintUsage[iSchema].omit = 1;
12744   }
12745   if( iPgno>=0 ){
12746     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
12747     pIdx->aConstraintUsage[iPgno].omit = 1;
12748     pIdx->estimatedCost = 100;
12749     pIdx->estimatedRows =  50;
12750 
12751     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
12752       int iCol = pIdx->aOrderBy[0].iColumn;
12753       if( pIdx->nOrderBy==1 ){
12754         pIdx->orderByConsumed = (iCol==0 || iCol==1);
12755       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
12756         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
12757       }
12758     }
12759 
12760   }else{
12761     pIdx->estimatedCost = 100000000;
12762     pIdx->estimatedRows = 1000000000;
12763   }
12764   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
12765   return SQLITE_OK;
12766 }
12767 
12768 /*
12769 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
12770 */
12771 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12772   DbdataCursor *pCsr;
12773 
12774   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
12775   if( pCsr==0 ){
12776     return SQLITE_NOMEM;
12777   }else{
12778     memset(pCsr, 0, sizeof(DbdataCursor));
12779     pCsr->base.pVtab = pVTab;
12780   }
12781 
12782   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
12783   return SQLITE_OK;
12784 }
12785 
12786 /*
12787 ** Restore a cursor object to the state it was in when first allocated
12788 ** by dbdataOpen().
12789 */
12790 static void dbdataResetCursor(DbdataCursor *pCsr){
12791   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
12792   if( pTab->pStmt==0 ){
12793     pTab->pStmt = pCsr->pStmt;
12794   }else{
12795     sqlite3_finalize(pCsr->pStmt);
12796   }
12797   pCsr->pStmt = 0;
12798   pCsr->iPgno = 1;
12799   pCsr->iCell = 0;
12800   pCsr->iField = 0;
12801   pCsr->bOnePage = 0;
12802   sqlite3_free(pCsr->aPage);
12803   sqlite3_free(pCsr->pRec);
12804   pCsr->pRec = 0;
12805   pCsr->aPage = 0;
12806 }
12807 
12808 /*
12809 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
12810 */
12811 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
12812   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
12813   dbdataResetCursor(pCsr);
12814   sqlite3_free(pCsr);
12815   return SQLITE_OK;
12816 }
12817 
12818 /*
12819 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
12820 */
12821 static u32 get_uint16(unsigned char *a){
12822   return (a[0]<<8)|a[1];
12823 }
12824 static u32 get_uint32(unsigned char *a){
12825   return ((u32)a[0]<<24)
12826        | ((u32)a[1]<<16)
12827        | ((u32)a[2]<<8)
12828        | ((u32)a[3]);
12829 }
12830 
12831 /*
12832 ** Load page pgno from the database via the sqlite_dbpage virtual table.
12833 ** If successful, set (*ppPage) to point to a buffer containing the page
12834 ** data, (*pnPage) to the size of that buffer in bytes and return
12835 ** SQLITE_OK. In this case it is the responsibility of the caller to
12836 ** eventually free the buffer using sqlite3_free().
12837 **
12838 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
12839 ** return an SQLite error code.
12840 */
12841 static int dbdataLoadPage(
12842   DbdataCursor *pCsr,             /* Cursor object */
12843   u32 pgno,                       /* Page number of page to load */
12844   u8 **ppPage,                    /* OUT: pointer to page buffer */
12845   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
12846 ){
12847   int rc2;
12848   int rc = SQLITE_OK;
12849   sqlite3_stmt *pStmt = pCsr->pStmt;
12850 
12851   *ppPage = 0;
12852   *pnPage = 0;
12853   if( pgno>0 ){
12854     sqlite3_bind_int64(pStmt, 2, pgno);
12855     if( SQLITE_ROW==sqlite3_step(pStmt) ){
12856       int nCopy = sqlite3_column_bytes(pStmt, 0);
12857       if( nCopy>0 ){
12858         u8 *pPage;
12859         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
12860         if( pPage==0 ){
12861           rc = SQLITE_NOMEM;
12862         }else{
12863           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
12864           memcpy(pPage, pCopy, nCopy);
12865           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
12866         }
12867         *ppPage = pPage;
12868         *pnPage = nCopy;
12869       }
12870     }
12871     rc2 = sqlite3_reset(pStmt);
12872     if( rc==SQLITE_OK ) rc = rc2;
12873   }
12874 
12875   return rc;
12876 }
12877 
12878 /*
12879 ** Read a varint.  Put the value in *pVal and return the number of bytes.
12880 */
12881 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
12882   sqlite3_uint64 u = 0;
12883   int i;
12884   for(i=0; i<8; i++){
12885     u = (u<<7) + (z[i]&0x7f);
12886     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
12887   }
12888   u = (u<<8) + (z[i]&0xff);
12889   *pVal = (sqlite3_int64)u;
12890   return 9;
12891 }
12892 
12893 /*
12894 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
12895 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
12896 ** SQLite database except for key values in intkey tables.
12897 */
12898 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
12899   sqlite3_int64 val;
12900   int nRet = dbdataGetVarint(z, &val);
12901   if( val<0 || val>0xFFFFFFFF ) val = 0;
12902   *pVal = val;
12903   return nRet;
12904 }
12905 
12906 /*
12907 ** Return the number of bytes of space used by an SQLite value of type
12908 ** eType.
12909 */
12910 static int dbdataValueBytes(int eType){
12911   switch( eType ){
12912     case 0: case 8: case 9:
12913     case 10: case 11:
12914       return 0;
12915     case 1:
12916       return 1;
12917     case 2:
12918       return 2;
12919     case 3:
12920       return 3;
12921     case 4:
12922       return 4;
12923     case 5:
12924       return 6;
12925     case 6:
12926     case 7:
12927       return 8;
12928     default:
12929       if( eType>0 ){
12930         return ((eType-12) / 2);
12931       }
12932       return 0;
12933   }
12934 }
12935 
12936 /*
12937 ** Load a value of type eType from buffer pData and use it to set the
12938 ** result of context object pCtx.
12939 */
12940 static void dbdataValue(
12941   sqlite3_context *pCtx,
12942   u32 enc,
12943   int eType,
12944   u8 *pData,
12945   sqlite3_int64 nData
12946 ){
12947   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
12948     switch( eType ){
12949       case 0:
12950       case 10:
12951       case 11:
12952         sqlite3_result_null(pCtx);
12953         break;
12954 
12955       case 8:
12956         sqlite3_result_int(pCtx, 0);
12957         break;
12958       case 9:
12959         sqlite3_result_int(pCtx, 1);
12960         break;
12961 
12962       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
12963         sqlite3_uint64 v = (signed char)pData[0];
12964         pData++;
12965         switch( eType ){
12966           case 7:
12967           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
12968           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
12969           case 4:  v = (v<<8) + pData[0];  pData++;
12970           case 3:  v = (v<<8) + pData[0];  pData++;
12971           case 2:  v = (v<<8) + pData[0];  pData++;
12972         }
12973 
12974         if( eType==7 ){
12975           double r;
12976           memcpy(&r, &v, sizeof(r));
12977           sqlite3_result_double(pCtx, r);
12978         }else{
12979           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
12980         }
12981         break;
12982       }
12983 
12984       default: {
12985         int n = ((eType-12) / 2);
12986         if( eType % 2 ){
12987           switch( enc ){
12988 #ifndef SQLITE_OMIT_UTF16
12989             case SQLITE_UTF16BE:
12990               sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
12991               break;
12992             case SQLITE_UTF16LE:
12993               sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
12994               break;
12995 #endif
12996             default:
12997               sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
12998               break;
12999           }
13000         }else{
13001           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
13002         }
13003       }
13004     }
13005   }
13006 }
13007 
13008 /*
13009 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
13010 */
13011 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
13012   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13013   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13014 
13015   pCsr->iRowid++;
13016   while( 1 ){
13017     int rc;
13018     int iOff = (pCsr->iPgno==1 ? 100 : 0);
13019     int bNextPage = 0;
13020 
13021     if( pCsr->aPage==0 ){
13022       while( 1 ){
13023         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
13024         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
13025         if( rc!=SQLITE_OK ) return rc;
13026         if( pCsr->aPage ) break;
13027         if( pCsr->bOnePage ) return SQLITE_OK;
13028         pCsr->iPgno++;
13029       }
13030       pCsr->iCell = pTab->bPtr ? -2 : 0;
13031       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
13032     }
13033 
13034     if( pTab->bPtr ){
13035       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
13036         pCsr->iCell = pCsr->nCell;
13037       }
13038       pCsr->iCell++;
13039       if( pCsr->iCell>=pCsr->nCell ){
13040         sqlite3_free(pCsr->aPage);
13041         pCsr->aPage = 0;
13042         if( pCsr->bOnePage ) return SQLITE_OK;
13043         pCsr->iPgno++;
13044       }else{
13045         return SQLITE_OK;
13046       }
13047     }else{
13048       /* If there is no record loaded, load it now. */
13049       if( pCsr->pRec==0 ){
13050         int bHasRowid = 0;
13051         int nPointer = 0;
13052         sqlite3_int64 nPayload = 0;
13053         sqlite3_int64 nHdr = 0;
13054         int iHdr;
13055         int U, X;
13056         int nLocal;
13057 
13058         switch( pCsr->aPage[iOff] ){
13059           case 0x02:
13060             nPointer = 4;
13061             break;
13062           case 0x0a:
13063             break;
13064           case 0x0d:
13065             bHasRowid = 1;
13066             break;
13067           default:
13068             /* This is not a b-tree page with records on it. Continue. */
13069             pCsr->iCell = pCsr->nCell;
13070             break;
13071         }
13072 
13073         if( pCsr->iCell>=pCsr->nCell ){
13074           bNextPage = 1;
13075         }else{
13076 
13077           iOff += 8 + nPointer + pCsr->iCell*2;
13078           if( iOff>pCsr->nPage ){
13079             bNextPage = 1;
13080           }else{
13081             iOff = get_uint16(&pCsr->aPage[iOff]);
13082           }
13083 
13084           /* For an interior node cell, skip past the child-page number */
13085           iOff += nPointer;
13086 
13087           /* Load the "byte of payload including overflow" field */
13088           if( bNextPage || iOff>pCsr->nPage ){
13089             bNextPage = 1;
13090           }else{
13091             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
13092           }
13093 
13094           /* If this is a leaf intkey cell, load the rowid */
13095           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
13096             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
13097           }
13098 
13099           /* Figure out how much data to read from the local page */
13100           U = pCsr->nPage;
13101           if( bHasRowid ){
13102             X = U-35;
13103           }else{
13104             X = ((U-12)*64/255)-23;
13105           }
13106           if( nPayload<=X ){
13107             nLocal = nPayload;
13108           }else{
13109             int M, K;
13110             M = ((U-12)*32/255)-23;
13111             K = M+((nPayload-M)%(U-4));
13112             if( K<=X ){
13113               nLocal = K;
13114             }else{
13115               nLocal = M;
13116             }
13117           }
13118 
13119           if( bNextPage || nLocal+iOff>pCsr->nPage ){
13120             bNextPage = 1;
13121           }else{
13122 
13123             /* Allocate space for payload. And a bit more to catch small buffer
13124             ** overruns caused by attempting to read a varint or similar from
13125             ** near the end of a corrupt record.  */
13126             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
13127             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
13128             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
13129             pCsr->nRec = nPayload;
13130 
13131             /* Load the nLocal bytes of payload */
13132             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
13133             iOff += nLocal;
13134 
13135             /* Load content from overflow pages */
13136             if( nPayload>nLocal ){
13137               sqlite3_int64 nRem = nPayload - nLocal;
13138               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
13139               while( nRem>0 ){
13140                 u8 *aOvfl = 0;
13141                 int nOvfl = 0;
13142                 int nCopy;
13143                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
13144                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
13145                 if( rc!=SQLITE_OK ) return rc;
13146                 if( aOvfl==0 ) break;
13147 
13148                 nCopy = U-4;
13149                 if( nCopy>nRem ) nCopy = nRem;
13150                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
13151                 nRem -= nCopy;
13152 
13153                 pgnoOvfl = get_uint32(aOvfl);
13154                 sqlite3_free(aOvfl);
13155               }
13156             }
13157 
13158             iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
13159             if( nHdr>nPayload ) nHdr = 0;
13160             pCsr->nHdr = nHdr;
13161             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
13162             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
13163             pCsr->iField = (bHasRowid ? -1 : 0);
13164           }
13165         }
13166       }else{
13167         pCsr->iField++;
13168         if( pCsr->iField>0 ){
13169           sqlite3_int64 iType;
13170           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
13171             bNextPage = 1;
13172           }else{
13173             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
13174             pCsr->pPtr += dbdataValueBytes(iType);
13175           }
13176         }
13177       }
13178 
13179       if( bNextPage ){
13180         sqlite3_free(pCsr->aPage);
13181         sqlite3_free(pCsr->pRec);
13182         pCsr->aPage = 0;
13183         pCsr->pRec = 0;
13184         if( pCsr->bOnePage ) return SQLITE_OK;
13185         pCsr->iPgno++;
13186       }else{
13187         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
13188           return SQLITE_OK;
13189         }
13190 
13191         /* Advance to the next cell. The next iteration of the loop will load
13192         ** the record and so on. */
13193         sqlite3_free(pCsr->pRec);
13194         pCsr->pRec = 0;
13195         pCsr->iCell++;
13196       }
13197     }
13198   }
13199 
13200   assert( !"can't get here" );
13201   return SQLITE_OK;
13202 }
13203 
13204 /*
13205 ** Return true if the cursor is at EOF.
13206 */
13207 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
13208   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13209   return pCsr->aPage==0;
13210 }
13211 
13212 /*
13213 ** Return true if nul-terminated string zSchema ends in "()". Or false
13214 ** otherwise.
13215 */
13216 static int dbdataIsFunction(const char *zSchema){
13217   size_t n = strlen(zSchema);
13218   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
13219     return (int)n-2;
13220   }
13221   return 0;
13222 }
13223 
13224 /*
13225 ** Determine the size in pages of database zSchema (where zSchema is
13226 ** "main", "temp" or the name of an attached database) and set
13227 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
13228 ** an SQLite error code.
13229 */
13230 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
13231   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
13232   char *zSql = 0;
13233   int rc, rc2;
13234   int nFunc = 0;
13235   sqlite3_stmt *pStmt = 0;
13236 
13237   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
13238     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
13239   }else{
13240     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
13241   }
13242   if( zSql==0 ) return SQLITE_NOMEM;
13243 
13244   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
13245   sqlite3_free(zSql);
13246   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
13247     pCsr->szDb = sqlite3_column_int(pStmt, 0);
13248   }
13249   rc2 = sqlite3_finalize(pStmt);
13250   if( rc==SQLITE_OK ) rc = rc2;
13251   return rc;
13252 }
13253 
13254 /*
13255 ** Attempt to figure out the encoding of the database by retrieving page 1
13256 ** and inspecting the header field. If successful, set the pCsr->enc variable
13257 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
13258 */
13259 static int dbdataGetEncoding(DbdataCursor *pCsr){
13260   int rc = SQLITE_OK;
13261   int nPg1 = 0;
13262   u8 *aPg1 = 0;
13263   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
13264   assert( rc!=SQLITE_OK || nPg1==0 || nPg1>=512 );
13265   if( rc==SQLITE_OK && nPg1>0 ){
13266     pCsr->enc = get_uint32(&aPg1[56]);
13267   }
13268   sqlite3_free(aPg1);
13269   return rc;
13270 }
13271 
13272 
13273 /*
13274 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
13275 */
13276 static int dbdataFilter(
13277   sqlite3_vtab_cursor *pCursor,
13278   int idxNum, const char *idxStr,
13279   int argc, sqlite3_value **argv
13280 ){
13281   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13282   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13283   int rc = SQLITE_OK;
13284   const char *zSchema = "main";
13285   (void)idxStr;
13286   (void)argc;
13287 
13288   dbdataResetCursor(pCsr);
13289   assert( pCsr->iPgno==1 );
13290   if( idxNum & 0x01 ){
13291     zSchema = (const char*)sqlite3_value_text(argv[0]);
13292     if( zSchema==0 ) zSchema = "";
13293   }
13294   if( idxNum & 0x02 ){
13295     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
13296     pCsr->bOnePage = 1;
13297   }else{
13298     rc = dbdataDbsize(pCsr, zSchema);
13299   }
13300 
13301   if( rc==SQLITE_OK ){
13302     int nFunc = 0;
13303     if( pTab->pStmt ){
13304       pCsr->pStmt = pTab->pStmt;
13305       pTab->pStmt = 0;
13306     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
13307       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
13308       if( zSql==0 ){
13309         rc = SQLITE_NOMEM;
13310       }else{
13311         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
13312         sqlite3_free(zSql);
13313       }
13314     }else{
13315       rc = sqlite3_prepare_v2(pTab->db,
13316           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
13317           &pCsr->pStmt, 0
13318       );
13319     }
13320   }
13321   if( rc==SQLITE_OK ){
13322     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
13323   }else{
13324     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
13325   }
13326 
13327   /* Try to determine the encoding of the db by inspecting the header
13328   ** field on page 1. */
13329   if( rc==SQLITE_OK ){
13330     rc = dbdataGetEncoding(pCsr);
13331   }
13332 
13333   if( rc==SQLITE_OK ){
13334     rc = dbdataNext(pCursor);
13335   }
13336   return rc;
13337 }
13338 
13339 /*
13340 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
13341 */
13342 static int dbdataColumn(
13343   sqlite3_vtab_cursor *pCursor,
13344   sqlite3_context *ctx,
13345   int i
13346 ){
13347   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13348   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13349   if( pTab->bPtr ){
13350     switch( i ){
13351       case DBPTR_COLUMN_PGNO:
13352         sqlite3_result_int64(ctx, pCsr->iPgno);
13353         break;
13354       case DBPTR_COLUMN_CHILD: {
13355         int iOff = pCsr->iPgno==1 ? 100 : 0;
13356         if( pCsr->iCell<0 ){
13357           iOff += 8;
13358         }else{
13359           iOff += 12 + pCsr->iCell*2;
13360           if( iOff>pCsr->nPage ) return SQLITE_OK;
13361           iOff = get_uint16(&pCsr->aPage[iOff]);
13362         }
13363         if( iOff<=pCsr->nPage ){
13364           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
13365         }
13366         break;
13367       }
13368     }
13369   }else{
13370     switch( i ){
13371       case DBDATA_COLUMN_PGNO:
13372         sqlite3_result_int64(ctx, pCsr->iPgno);
13373         break;
13374       case DBDATA_COLUMN_CELL:
13375         sqlite3_result_int(ctx, pCsr->iCell);
13376         break;
13377       case DBDATA_COLUMN_FIELD:
13378         sqlite3_result_int(ctx, pCsr->iField);
13379         break;
13380       case DBDATA_COLUMN_VALUE: {
13381         if( pCsr->iField<0 ){
13382           sqlite3_result_int64(ctx, pCsr->iIntkey);
13383         }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
13384           sqlite3_int64 iType;
13385           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
13386           dbdataValue(
13387               ctx, pCsr->enc, iType, pCsr->pPtr,
13388               &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
13389           );
13390         }
13391         break;
13392       }
13393     }
13394   }
13395   return SQLITE_OK;
13396 }
13397 
13398 /*
13399 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
13400 */
13401 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
13402   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13403   *pRowid = pCsr->iRowid;
13404   return SQLITE_OK;
13405 }
13406 
13407 
13408 /*
13409 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
13410 */
13411 static int sqlite3DbdataRegister(sqlite3 *db){
13412   static sqlite3_module dbdata_module = {
13413     0,                            /* iVersion */
13414     0,                            /* xCreate */
13415     dbdataConnect,                /* xConnect */
13416     dbdataBestIndex,              /* xBestIndex */
13417     dbdataDisconnect,             /* xDisconnect */
13418     0,                            /* xDestroy */
13419     dbdataOpen,                   /* xOpen - open a cursor */
13420     dbdataClose,                  /* xClose - close a cursor */
13421     dbdataFilter,                 /* xFilter - configure scan constraints */
13422     dbdataNext,                   /* xNext - advance a cursor */
13423     dbdataEof,                    /* xEof - check for end of scan */
13424     dbdataColumn,                 /* xColumn - read data */
13425     dbdataRowid,                  /* xRowid - read data */
13426     0,                            /* xUpdate */
13427     0,                            /* xBegin */
13428     0,                            /* xSync */
13429     0,                            /* xCommit */
13430     0,                            /* xRollback */
13431     0,                            /* xFindMethod */
13432     0,                            /* xRename */
13433     0,                            /* xSavepoint */
13434     0,                            /* xRelease */
13435     0,                            /* xRollbackTo */
13436     0                             /* xShadowName */
13437   };
13438 
13439   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
13440   if( rc==SQLITE_OK ){
13441     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
13442   }
13443   return rc;
13444 }
13445 
13446 #ifdef _WIN32
13447 
13448 #endif
13449 int sqlite3_dbdata_init(
13450   sqlite3 *db,
13451   char **pzErrMsg,
13452   const sqlite3_api_routines *pApi
13453 ){
13454   SQLITE_EXTENSION_INIT2(pApi);
13455   (void)pzErrMsg;
13456   return sqlite3DbdataRegister(db);
13457 }
13458 
13459 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13460 
13461 /************************* End ../ext/recover/dbdata.c ********************/
13462 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
13463 /*
13464 ** 2022-08-27
13465 **
13466 ** The author disclaims copyright to this source code.  In place of
13467 ** a legal notice, here is a blessing:
13468 **
13469 **    May you do good and not evil.
13470 **    May you find forgiveness for yourself and forgive others.
13471 **    May you share freely, never taking more than you give.
13472 **
13473 *************************************************************************
13474 **
13475 */
13476 
13477 
13478 /* #include "sqlite3recover.h" */
13479 #include <assert.h>
13480 #include <string.h>
13481 
13482 #ifndef SQLITE_OMIT_VIRTUALTABLE
13483 
13484 /*
13485 ** Declaration for public API function in file dbdata.c. This may be called
13486 ** with NULL as the final two arguments to register the sqlite_dbptr and
13487 ** sqlite_dbdata virtual tables with a database handle.
13488 */
13489 #ifdef _WIN32
13490 
13491 #endif
13492 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
13493 
13494 /* typedef unsigned int u32; */
13495 /* typedef unsigned char u8; */
13496 /* typedef sqlite3_int64 i64; */
13497 
13498 typedef struct RecoverTable RecoverTable;
13499 typedef struct RecoverColumn RecoverColumn;
13500 
13501 /*
13502 ** When recovering rows of data that can be associated with table
13503 ** definitions recovered from the sqlite_schema table, each table is
13504 ** represented by an instance of the following object.
13505 **
13506 ** iRoot:
13507 **   The root page in the original database. Not necessarily (and usually
13508 **   not) the same in the recovered database.
13509 **
13510 ** zTab:
13511 **   Name of the table.
13512 **
13513 ** nCol/aCol[]:
13514 **   aCol[] is an array of nCol columns. In the order in which they appear
13515 **   in the table.
13516 **
13517 ** bIntkey:
13518 **   Set to true for intkey tables, false for WITHOUT ROWID.
13519 **
13520 ** iRowidBind:
13521 **   Each column in the aCol[] array has associated with it the index of
13522 **   the bind parameter its values will be bound to in the INSERT statement
13523 **   used to construct the output database. If the table does has a rowid
13524 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
13525 **   index of the bind paramater to which the rowid value should be bound.
13526 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
13527 **   KEY column, then the rowid value should be bound to the index associated
13528 **   with the column.
13529 **
13530 ** pNext:
13531 **   All RecoverTable objects used by the recovery operation are allocated
13532 **   and populated as part of creating the recovered database schema in
13533 **   the output database, before any non-schema data are recovered. They
13534 **   are then stored in a singly-linked list linked by this variable beginning
13535 **   at sqlite3_recover.pTblList.
13536 */
13537 struct RecoverTable {
13538   u32 iRoot;                      /* Root page in original database */
13539   char *zTab;                     /* Name of table */
13540   int nCol;                       /* Number of columns in table */
13541   RecoverColumn *aCol;            /* Array of columns */
13542   int bIntkey;                    /* True for intkey, false for without rowid */
13543   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
13544   RecoverTable *pNext;
13545 };
13546 
13547 /*
13548 ** Each database column is represented by an instance of the following object
13549 ** stored in the RecoverTable.aCol[] array of the associated table.
13550 **
13551 ** iField:
13552 **   The index of the associated field within database records. Or -1 if
13553 **   there is no associated field (e.g. for virtual generated columns).
13554 **
13555 ** iBind:
13556 **   The bind index of the INSERT statement to bind this columns values
13557 **   to. Or 0 if there is no such index (iff (iField<0)).
13558 **
13559 ** bIPK:
13560 **   True if this is the INTEGER PRIMARY KEY column.
13561 **
13562 ** zCol:
13563 **   Name of column.
13564 **
13565 ** eHidden:
13566 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
13567 */
13568 struct RecoverColumn {
13569   int iField;                     /* Field in record on disk */
13570   int iBind;                      /* Binding to use in INSERT */
13571   int bIPK;                       /* True for IPK column */
13572   char *zCol;
13573   int eHidden;
13574 };
13575 
13576 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
13577 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
13578 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
13579 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
13580 
13581 /*
13582 ** Bitmap object used to track pages in the input database. Allocated
13583 ** and manipulated only by the following functions:
13584 **
13585 **     recoverBitmapAlloc()
13586 **     recoverBitmapFree()
13587 **     recoverBitmapSet()
13588 **     recoverBitmapQuery()
13589 **
13590 ** nPg:
13591 **   Largest page number that may be stored in the bitmap. The range
13592 **   of valid keys is 1 to nPg, inclusive.
13593 **
13594 ** aElem[]:
13595 **   Array large enough to contain a bit for each key. For key value
13596 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
13597 **   In other words, the following is true if bit iKey is set, or
13598 **   false if it is clear:
13599 **
13600 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
13601 */
13602 typedef struct RecoverBitmap RecoverBitmap;
13603 struct RecoverBitmap {
13604   i64 nPg;                        /* Size of bitmap */
13605   u32 aElem[1];                   /* Array of 32-bit bitmasks */
13606 };
13607 
13608 /*
13609 ** State variables (part of the sqlite3_recover structure) used while
13610 ** recovering data for tables identified in the recovered schema (state
13611 ** RECOVER_STATE_WRITING).
13612 */
13613 typedef struct RecoverStateW1 RecoverStateW1;
13614 struct RecoverStateW1 {
13615   sqlite3_stmt *pTbls;
13616   sqlite3_stmt *pSel;
13617   sqlite3_stmt *pInsert;
13618   int nInsert;
13619 
13620   RecoverTable *pTab;             /* Table currently being written */
13621   int nMax;                       /* Max column count in any schema table */
13622   sqlite3_value **apVal;          /* Array of nMax values */
13623   int nVal;                       /* Number of valid entries in apVal[] */
13624   int bHaveRowid;
13625   i64 iRowid;
13626   i64 iPrevPage;
13627   int iPrevCell;
13628 };
13629 
13630 /*
13631 ** State variables (part of the sqlite3_recover structure) used while
13632 ** recovering data destined for the lost and found table (states
13633 ** RECOVER_STATE_LOSTANDFOUND[123]).
13634 */
13635 typedef struct RecoverStateLAF RecoverStateLAF;
13636 struct RecoverStateLAF {
13637   RecoverBitmap *pUsed;
13638   i64 nPg;                        /* Size of db in pages */
13639   sqlite3_stmt *pAllAndParent;
13640   sqlite3_stmt *pMapInsert;
13641   sqlite3_stmt *pMaxField;
13642   sqlite3_stmt *pUsedPages;
13643   sqlite3_stmt *pFindRoot;
13644   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
13645   sqlite3_stmt *pAllPage;
13646   sqlite3_stmt *pPageData;
13647   sqlite3_value **apVal;
13648   int nMaxField;
13649 };
13650 
13651 /*
13652 ** Main recover handle structure.
13653 */
13654 struct sqlite3_recover {
13655   /* Copies of sqlite3_recover_init[_sql]() parameters */
13656   sqlite3 *dbIn;                  /* Input database */
13657   char *zDb;                      /* Name of input db ("main" etc.) */
13658   char *zUri;                     /* URI for output database */
13659   void *pSqlCtx;                  /* SQL callback context */
13660   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
13661 
13662   /* Values configured by sqlite3_recover_config() */
13663   char *zStateDb;                 /* State database to use (or NULL) */
13664   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
13665   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
13666   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
13667   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
13668 
13669   int pgsz;
13670   int detected_pgsz;
13671   int nReserve;
13672   u8 *pPage1Disk;
13673   u8 *pPage1Cache;
13674 
13675   /* Error code and error message */
13676   int errCode;                    /* For sqlite3_recover_errcode() */
13677   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
13678 
13679   int eState;
13680   int bCloseTransaction;
13681 
13682   /* Variables used with eState==RECOVER_STATE_WRITING */
13683   RecoverStateW1 w1;
13684 
13685   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
13686   RecoverStateLAF laf;
13687 
13688   /* Fields used within sqlite3_recover_run() */
13689   sqlite3 *dbOut;                 /* Output database */
13690   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
13691   RecoverTable *pTblList;         /* List of tables recovered from schema */
13692 };
13693 
13694 /*
13695 ** The various states in which an sqlite3_recover object may exist:
13696 **
13697 **   RECOVER_STATE_INIT:
13698 **    The object is initially created in this state. sqlite3_recover_step()
13699 **    has yet to be called. This is the only state in which it is permitted
13700 **    to call sqlite3_recover_config().
13701 **
13702 **   RECOVER_STATE_WRITING:
13703 **
13704 **   RECOVER_STATE_LOSTANDFOUND1:
13705 **    State to populate the bitmap of pages used by other tables or the
13706 **    database freelist.
13707 **
13708 **   RECOVER_STATE_LOSTANDFOUND2:
13709 **    Populate the recovery.map table - used to figure out a "root" page
13710 **    for each lost page from in the database from which records are
13711 **    extracted.
13712 **
13713 **   RECOVER_STATE_LOSTANDFOUND3:
13714 **    Populate the lost-and-found table itself.
13715 */
13716 #define RECOVER_STATE_INIT           0
13717 #define RECOVER_STATE_WRITING        1
13718 #define RECOVER_STATE_LOSTANDFOUND1  2
13719 #define RECOVER_STATE_LOSTANDFOUND2  3
13720 #define RECOVER_STATE_LOSTANDFOUND3  4
13721 #define RECOVER_STATE_SCHEMA2        5
13722 #define RECOVER_STATE_DONE           6
13723 
13724 
13725 /*
13726 ** Global variables used by this extension.
13727 */
13728 typedef struct RecoverGlobal RecoverGlobal;
13729 struct RecoverGlobal {
13730   const sqlite3_io_methods *pMethods;
13731   sqlite3_recover *p;
13732 };
13733 static RecoverGlobal recover_g;
13734 
13735 /*
13736 ** Use this static SQLite mutex to protect the globals during the
13737 ** first call to sqlite3_recover_step().
13738 */
13739 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
13740 
13741 
13742 /*
13743 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
13744 */
13745 #define RECOVER_ROWID_DEFAULT 1
13746 
13747 /*
13748 ** Mutex handling:
13749 **
13750 **    recoverEnterMutex()       -   Enter the recovery mutex
13751 **    recoverLeaveMutex()       -   Leave the recovery mutex
13752 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
13753 */
13754 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
13755 # define recoverEnterMutex()
13756 # define recoverLeaveMutex()
13757 #else
13758 static void recoverEnterMutex(void){
13759   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
13760 }
13761 static void recoverLeaveMutex(void){
13762   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
13763 }
13764 #endif
13765 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
13766 static void recoverAssertMutexHeld(void){
13767   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
13768 }
13769 #else
13770 # define recoverAssertMutexHeld()
13771 #endif
13772 
13773 
13774 /*
13775 ** Like strlen(). But handles NULL pointer arguments.
13776 */
13777 static int recoverStrlen(const char *zStr){
13778   if( zStr==0 ) return 0;
13779   return (int)(strlen(zStr)&0x7fffffff);
13780 }
13781 
13782 /*
13783 ** This function is a no-op if the recover handle passed as the first
13784 ** argument already contains an error (if p->errCode!=SQLITE_OK).
13785 **
13786 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
13787 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
13788 ** if an OOM error occurs, NULL is returned and the handle error code
13789 ** (p->errCode) set to SQLITE_NOMEM.
13790 */
13791 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
13792   void *pRet = 0;
13793   assert( nByte>0 );
13794   if( p->errCode==SQLITE_OK ){
13795     pRet = sqlite3_malloc64(nByte);
13796     if( pRet ){
13797       memset(pRet, 0, nByte);
13798     }else{
13799       p->errCode = SQLITE_NOMEM;
13800     }
13801   }
13802   return pRet;
13803 }
13804 
13805 /*
13806 ** Set the error code and error message for the recover handle passed as
13807 ** the first argument. The error code is set to the value of parameter
13808 ** errCode.
13809 **
13810 ** Parameter zFmt must be a printf() style formatting string. The handle
13811 ** error message is set to the result of using any trailing arguments for
13812 ** parameter substitutions in the formatting string.
13813 **
13814 ** For example:
13815 **
13816 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
13817 */
13818 static int recoverError(
13819   sqlite3_recover *p,
13820   int errCode,
13821   const char *zFmt, ...
13822 ){
13823   char *z = 0;
13824   va_list ap;
13825   va_start(ap, zFmt);
13826   if( zFmt ){
13827     z = sqlite3_vmprintf(zFmt, ap);
13828     va_end(ap);
13829   }
13830   sqlite3_free(p->zErrMsg);
13831   p->zErrMsg = z;
13832   p->errCode = errCode;
13833   return errCode;
13834 }
13835 
13836 
13837 /*
13838 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
13839 ** In this case it returns NULL.
13840 **
13841 ** Otherwise, an attempt is made to allocate and return a bitmap object
13842 ** large enough to store a bit for all page numbers between 1 and nPg,
13843 ** inclusive. The bitmap is initially zeroed.
13844 */
13845 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
13846   int nElem = (nPg+1+31) / 32;
13847   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
13848   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
13849 
13850   if( pRet ){
13851     pRet->nPg = nPg;
13852   }
13853   return pRet;
13854 }
13855 
13856 /*
13857 ** Free a bitmap object allocated by recoverBitmapAlloc().
13858 */
13859 static void recoverBitmapFree(RecoverBitmap *pMap){
13860   sqlite3_free(pMap);
13861 }
13862 
13863 /*
13864 ** Set the bit associated with page iPg in bitvec pMap.
13865 */
13866 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
13867   if( iPg<=pMap->nPg ){
13868     int iElem = (iPg / 32);
13869     int iBit = (iPg % 32);
13870     pMap->aElem[iElem] |= (((u32)1) << iBit);
13871   }
13872 }
13873 
13874 /*
13875 ** Query bitmap object pMap for the state of the bit associated with page
13876 ** iPg. Return 1 if it is set, or 0 otherwise.
13877 */
13878 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
13879   int ret = 1;
13880   if( iPg<=pMap->nPg && iPg>0 ){
13881     int iElem = (iPg / 32);
13882     int iBit = (iPg % 32);
13883     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
13884   }
13885   return ret;
13886 }
13887 
13888 /*
13889 ** Set the recover handle error to the error code and message returned by
13890 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
13891 ** handle db.
13892 */
13893 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
13894   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
13895 }
13896 
13897 /*
13898 ** This function is a no-op if recover handle p already contains an error
13899 ** (if p->errCode!=SQLITE_OK).
13900 **
13901 ** Otherwise, it attempts to prepare the SQL statement in zSql against
13902 ** database handle db. If successful, the statement handle is returned.
13903 ** Or, if an error occurs, NULL is returned and an error left in the
13904 ** recover handle.
13905 */
13906 static sqlite3_stmt *recoverPrepare(
13907   sqlite3_recover *p,
13908   sqlite3 *db,
13909   const char *zSql
13910 ){
13911   sqlite3_stmt *pStmt = 0;
13912   if( p->errCode==SQLITE_OK ){
13913     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
13914       recoverDbError(p, db);
13915     }
13916   }
13917   return pStmt;
13918 }
13919 
13920 /*
13921 ** This function is a no-op if recover handle p already contains an error
13922 ** (if p->errCode!=SQLITE_OK).
13923 **
13924 ** Otherwise, argument zFmt is used as a printf() style format string,
13925 ** along with any trailing arguments, to create an SQL statement. This
13926 ** SQL statement is prepared against database handle db and, if successful,
13927 ** the statment handle returned. Or, if an error occurs - either during
13928 ** the printf() formatting or when preparing the resulting SQL - an
13929 ** error code and message are left in the recover handle.
13930 */
13931 static sqlite3_stmt *recoverPreparePrintf(
13932   sqlite3_recover *p,
13933   sqlite3 *db,
13934   const char *zFmt, ...
13935 ){
13936   sqlite3_stmt *pStmt = 0;
13937   if( p->errCode==SQLITE_OK ){
13938     va_list ap;
13939     char *z;
13940     va_start(ap, zFmt);
13941     z = sqlite3_vmprintf(zFmt, ap);
13942     va_end(ap);
13943     if( z==0 ){
13944       p->errCode = SQLITE_NOMEM;
13945     }else{
13946       pStmt = recoverPrepare(p, db, z);
13947       sqlite3_free(z);
13948     }
13949   }
13950   return pStmt;
13951 }
13952 
13953 /*
13954 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
13955 ** indicates that an error occurred, and there is not already an error
13956 ** in the recover handle passed as the first argument, set the error
13957 ** code and error message appropriately.
13958 **
13959 ** This function returns a copy of the statement handle pointer passed
13960 ** as the second argument.
13961 */
13962 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
13963   int rc = sqlite3_reset(pStmt);
13964   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
13965     recoverDbError(p, sqlite3_db_handle(pStmt));
13966   }
13967   return pStmt;
13968 }
13969 
13970 /*
13971 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
13972 ** indicates that an error occurred, and there is not already an error
13973 ** in the recover handle passed as the first argument, set the error
13974 ** code and error message appropriately.
13975 */
13976 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
13977   sqlite3 *db = sqlite3_db_handle(pStmt);
13978   int rc = sqlite3_finalize(pStmt);
13979   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
13980     recoverDbError(p, db);
13981   }
13982 }
13983 
13984 /*
13985 ** This function is a no-op if recover handle p already contains an error
13986 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
13987 ** case.
13988 **
13989 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
13990 ** Or, if an error occurs, leave an error code and message in the recover
13991 ** handle and return a copy of the error code.
13992 */
13993 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
13994   if( p->errCode==SQLITE_OK ){
13995     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
13996     if( rc ){
13997       recoverDbError(p, db);
13998     }
13999   }
14000   return p->errCode;
14001 }
14002 
14003 /*
14004 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
14005 ** error in the recover handle passed as the first argument if an error
14006 ** (e.g. an OOM) occurs.
14007 */
14008 static void recoverBindValue(
14009   sqlite3_recover *p,
14010   sqlite3_stmt *pStmt,
14011   int iBind,
14012   sqlite3_value *pVal
14013 ){
14014   if( p->errCode==SQLITE_OK ){
14015     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
14016     if( rc ) recoverError(p, rc, 0);
14017   }
14018 }
14019 
14020 /*
14021 ** This function is a no-op if recover handle p already contains an error
14022 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
14023 **
14024 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
14025 ** formatting string and the result of using the trailing arguments for
14026 ** parameter substitution with it written into a buffer obtained from
14027 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
14028 ** It is the responsibility of the caller to eventually free the buffer
14029 ** using sqlite3_free().
14030 **
14031 ** Or, if an error occurs, an error code and message is left in the recover
14032 ** handle and NULL returned.
14033 */
14034 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
14035   va_list ap;
14036   char *z;
14037   va_start(ap, zFmt);
14038   z = sqlite3_vmprintf(zFmt, ap);
14039   va_end(ap);
14040   if( p->errCode==SQLITE_OK ){
14041     if( z==0 ) p->errCode = SQLITE_NOMEM;
14042   }else{
14043     sqlite3_free(z);
14044     z = 0;
14045   }
14046   return z;
14047 }
14048 
14049 /*
14050 ** This function is a no-op if recover handle p already contains an error
14051 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
14052 **
14053 ** Otherwise, execute "PRAGMA page_count" against the input database. If
14054 ** successful, return the integer result. Or, if an error occurs, leave an
14055 ** error code and error message in the sqlite3_recover handle and return
14056 ** zero.
14057 */
14058 static i64 recoverPageCount(sqlite3_recover *p){
14059   i64 nPg = 0;
14060   if( p->errCode==SQLITE_OK ){
14061     sqlite3_stmt *pStmt = 0;
14062     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
14063     if( pStmt ){
14064       sqlite3_step(pStmt);
14065       nPg = sqlite3_column_int64(pStmt, 0);
14066     }
14067     recoverFinalize(p, pStmt);
14068   }
14069   return nPg;
14070 }
14071 
14072 /*
14073 ** Implementation of SQL scalar function "read_i32". The first argument to
14074 ** this function must be a blob. The second a non-negative integer. This
14075 ** function reads and returns a 32-bit big-endian integer from byte
14076 ** offset (4*<arg2>) of the blob.
14077 **
14078 **     SELECT read_i32(<blob>, <idx>)
14079 */
14080 static void recoverReadI32(
14081   sqlite3_context *context,
14082   int argc,
14083   sqlite3_value **argv
14084 ){
14085   const unsigned char *pBlob;
14086   int nBlob;
14087   int iInt;
14088 
14089   assert( argc==2 );
14090   nBlob = sqlite3_value_bytes(argv[0]);
14091   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
14092   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
14093 
14094   if( (iInt+1)*4<=nBlob ){
14095     const unsigned char *a = &pBlob[iInt*4];
14096     i64 iVal = ((i64)a[0]<<24)
14097              + ((i64)a[1]<<16)
14098              + ((i64)a[2]<< 8)
14099              + ((i64)a[3]<< 0);
14100     sqlite3_result_int64(context, iVal);
14101   }
14102 }
14103 
14104 /*
14105 ** Implementation of SQL scalar function "page_is_used". This function
14106 ** is used as part of the procedure for locating orphan rows for the
14107 ** lost-and-found table, and it depends on those routines having populated
14108 ** the sqlite3_recover.laf.pUsed variable.
14109 **
14110 ** The only argument to this function is a page-number. It returns true
14111 ** if the page has already been used somehow during data recovery, or false
14112 ** otherwise.
14113 **
14114 **     SELECT page_is_used(<pgno>);
14115 */
14116 static void recoverPageIsUsed(
14117   sqlite3_context *pCtx,
14118   int nArg,
14119   sqlite3_value **apArg
14120 ){
14121   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
14122   i64 pgno = sqlite3_value_int64(apArg[0]);
14123   assert( nArg==1 );
14124   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
14125 }
14126 
14127 /*
14128 ** The implementation of a user-defined SQL function invoked by the
14129 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
14130 ** of the database being recovered.
14131 **
14132 ** This function always takes a single integer argument. If the argument
14133 ** is zero, then the value returned is the number of pages in the db being
14134 ** recovered. If the argument is greater than zero, it is a page number.
14135 ** The value returned in this case is an SQL blob containing the data for
14136 ** the identified page of the db being recovered. e.g.
14137 **
14138 **     SELECT getpage(0);       -- return number of pages in db
14139 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
14140 */
14141 static void recoverGetPage(
14142   sqlite3_context *pCtx,
14143   int nArg,
14144   sqlite3_value **apArg
14145 ){
14146   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
14147   i64 pgno = sqlite3_value_int64(apArg[0]);
14148   sqlite3_stmt *pStmt = 0;
14149 
14150   assert( nArg==1 );
14151   if( pgno==0 ){
14152     i64 nPg = recoverPageCount(p);
14153     sqlite3_result_int64(pCtx, nPg);
14154     return;
14155   }else{
14156     if( p->pGetPage==0 ){
14157       pStmt = p->pGetPage = recoverPreparePrintf(
14158           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
14159       );
14160     }else if( p->errCode==SQLITE_OK ){
14161       pStmt = p->pGetPage;
14162     }
14163 
14164     if( pStmt ){
14165       sqlite3_bind_int64(pStmt, 1, pgno);
14166       if( SQLITE_ROW==sqlite3_step(pStmt) ){
14167         const u8 *aPg;
14168         int nPg;
14169         assert( p->errCode==SQLITE_OK );
14170         aPg = sqlite3_column_blob(pStmt, 0);
14171         nPg = sqlite3_column_bytes(pStmt, 0);
14172         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
14173           aPg = p->pPage1Disk;
14174         }
14175         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
14176       }
14177       recoverReset(p, pStmt);
14178     }
14179   }
14180 
14181   if( p->errCode ){
14182     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
14183     sqlite3_result_error_code(pCtx, p->errCode);
14184   }
14185 }
14186 
14187 /*
14188 ** Find a string that is not found anywhere in z[].  Return a pointer
14189 ** to that string.
14190 **
14191 ** Try to use zA and zB first.  If both of those are already found in z[]
14192 ** then make up some string and store it in the buffer zBuf.
14193 */
14194 static const char *recoverUnusedString(
14195   const char *z,                    /* Result must not appear anywhere in z */
14196   const char *zA, const char *zB,   /* Try these first */
14197   char *zBuf                        /* Space to store a generated string */
14198 ){
14199   unsigned i = 0;
14200   if( strstr(z, zA)==0 ) return zA;
14201   if( strstr(z, zB)==0 ) return zB;
14202   do{
14203     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
14204   }while( strstr(z,zBuf)!=0 );
14205   return zBuf;
14206 }
14207 
14208 /*
14209 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
14210 ** this function is the output of built-in function quote(). If the first
14211 ** character of the input is "'", indicating that the value passed to quote()
14212 ** was a text value, then this function searches the input for "\n" and "\r"
14213 ** characters and adds a wrapper similar to the following:
14214 **
14215 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
14216 **
14217 ** Or, if the first character of the input is not "'", then a copy of the input
14218 ** is returned.
14219 */
14220 static void recoverEscapeCrnl(
14221   sqlite3_context *context,
14222   int argc,
14223   sqlite3_value **argv
14224 ){
14225   const char *zText = (const char*)sqlite3_value_text(argv[0]);
14226   (void)argc;
14227   if( zText && zText[0]=='\'' ){
14228     int nText = sqlite3_value_bytes(argv[0]);
14229     int i;
14230     char zBuf1[20];
14231     char zBuf2[20];
14232     const char *zNL = 0;
14233     const char *zCR = 0;
14234     int nCR = 0;
14235     int nNL = 0;
14236 
14237     for(i=0; zText[i]; i++){
14238       if( zNL==0 && zText[i]=='\n' ){
14239         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
14240         nNL = (int)strlen(zNL);
14241       }
14242       if( zCR==0 && zText[i]=='\r' ){
14243         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
14244         nCR = (int)strlen(zCR);
14245       }
14246     }
14247 
14248     if( zNL || zCR ){
14249       int iOut = 0;
14250       i64 nMax = (nNL > nCR) ? nNL : nCR;
14251       i64 nAlloc = nMax * nText + (nMax+64)*2;
14252       char *zOut = (char*)sqlite3_malloc64(nAlloc);
14253       if( zOut==0 ){
14254         sqlite3_result_error_nomem(context);
14255         return;
14256       }
14257 
14258       if( zNL && zCR ){
14259         memcpy(&zOut[iOut], "replace(replace(", 16);
14260         iOut += 16;
14261       }else{
14262         memcpy(&zOut[iOut], "replace(", 8);
14263         iOut += 8;
14264       }
14265       for(i=0; zText[i]; i++){
14266         if( zText[i]=='\n' ){
14267           memcpy(&zOut[iOut], zNL, nNL);
14268           iOut += nNL;
14269         }else if( zText[i]=='\r' ){
14270           memcpy(&zOut[iOut], zCR, nCR);
14271           iOut += nCR;
14272         }else{
14273           zOut[iOut] = zText[i];
14274           iOut++;
14275         }
14276       }
14277 
14278       if( zNL ){
14279         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14280         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
14281         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
14282       }
14283       if( zCR ){
14284         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14285         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
14286         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
14287       }
14288 
14289       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
14290       sqlite3_free(zOut);
14291       return;
14292     }
14293   }
14294 
14295   sqlite3_result_value(context, argv[0]);
14296 }
14297 
14298 /*
14299 ** This function is a no-op if recover handle p already contains an error
14300 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
14301 ** this case.
14302 **
14303 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
14304 ** parts of the database schema that can be extracted from the input database.
14305 **
14306 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
14307 ** and error message are left in the recover handle and a copy of the
14308 ** error code returned. It is not considered an error if part of all of
14309 ** the database schema cannot be recovered due to corruption.
14310 */
14311 static int recoverCacheSchema(sqlite3_recover *p){
14312   return recoverExec(p, p->dbOut,
14313     "WITH RECURSIVE pages(p) AS ("
14314     "  SELECT 1"
14315     "    UNION"
14316     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
14317     ")"
14318     "INSERT INTO recovery.schema SELECT"
14319     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
14320     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
14321     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
14322     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
14323     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
14324     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
14325     "  SELECT p FROM pages"
14326     ") GROUP BY pgno, cell"
14327   );
14328 }
14329 
14330 /*
14331 ** If this recover handle is not in SQL callback mode (i.e. was not created
14332 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
14333 ** this function is a no-op. Otherwise, issue a callback with SQL statement
14334 ** zSql as the parameter.
14335 **
14336 ** If the callback returns non-zero, set the recover handle error code to
14337 ** the value returned (so that the caller will abandon processing).
14338 */
14339 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
14340   if( p->errCode==SQLITE_OK && p->xSql ){
14341     int res = p->xSql(p->pSqlCtx, zSql);
14342     if( res ){
14343       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
14344     }
14345   }
14346 }
14347 
14348 /*
14349 ** Transfer the following settings from the input database to the output
14350 ** database:
14351 **
14352 **   + page-size,
14353 **   + auto-vacuum settings,
14354 **   + database encoding,
14355 **   + user-version (PRAGMA user_version), and
14356 **   + application-id (PRAGMA application_id), and
14357 */
14358 static void recoverTransferSettings(sqlite3_recover *p){
14359   const char *aPragma[] = {
14360     "encoding",
14361     "page_size",
14362     "auto_vacuum",
14363     "user_version",
14364     "application_id"
14365   };
14366   int ii;
14367 
14368   /* Truncate the output database to 0 pages in size. This is done by
14369   ** opening a new, empty, temp db, then using the backup API to clobber
14370   ** any existing output db with a copy of it. */
14371   if( p->errCode==SQLITE_OK ){
14372     sqlite3 *db2 = 0;
14373     int rc = sqlite3_open("", &db2);
14374     if( rc!=SQLITE_OK ){
14375       recoverDbError(p, db2);
14376       return;
14377     }
14378 
14379     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
14380       const char *zPrag = aPragma[ii];
14381       sqlite3_stmt *p1 = 0;
14382       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
14383       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
14384         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
14385         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
14386         recoverSqlCallback(p, z2);
14387         recoverExec(p, db2, z2);
14388         sqlite3_free(z2);
14389         if( zArg==0 ){
14390           recoverError(p, SQLITE_NOMEM, 0);
14391         }
14392       }
14393       recoverFinalize(p, p1);
14394     }
14395     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
14396 
14397     if( p->errCode==SQLITE_OK ){
14398       sqlite3 *db = p->dbOut;
14399       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
14400       if( pBackup ){
14401         sqlite3_backup_step(pBackup, -1);
14402         p->errCode = sqlite3_backup_finish(pBackup);
14403       }else{
14404         recoverDbError(p, db);
14405       }
14406     }
14407 
14408     sqlite3_close(db2);
14409   }
14410 }
14411 
14412 /*
14413 ** This function is a no-op if recover handle p already contains an error
14414 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
14415 ** this case.
14416 **
14417 ** Otherwise, an attempt is made to open the output database, attach
14418 ** and create the schema of the temporary database used to store
14419 ** intermediate data, and to register all required user functions and
14420 ** virtual table modules with the output handle.
14421 **
14422 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
14423 ** and error message are left in the recover handle and a copy of the
14424 ** error code returned.
14425 */
14426 static int recoverOpenOutput(sqlite3_recover *p){
14427   struct Func {
14428     const char *zName;
14429     int nArg;
14430     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
14431   } aFunc[] = {
14432     { "getpage", 1, recoverGetPage },
14433     { "page_is_used", 1, recoverPageIsUsed },
14434     { "read_i32", 2, recoverReadI32 },
14435     { "escape_crnl", 1, recoverEscapeCrnl },
14436   };
14437 
14438   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
14439   sqlite3 *db = 0;                /* New database handle */
14440   int ii;                         /* For iterating through aFunc[] */
14441 
14442   assert( p->dbOut==0 );
14443 
14444   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
14445     recoverDbError(p, db);
14446   }
14447 
14448   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
14449   ** These two are registered with the output database handle - this
14450   ** module depends on the input handle supporting the sqlite_dbpage
14451   ** virtual table only.  */
14452   if( p->errCode==SQLITE_OK ){
14453     p->errCode = sqlite3_dbdata_init(db, 0, 0);
14454   }
14455 
14456   /* Register the custom user-functions with the output handle. */
14457   for(ii=0;
14458       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
14459       ii++){
14460     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
14461         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
14462     );
14463   }
14464 
14465   p->dbOut = db;
14466   return p->errCode;
14467 }
14468 
14469 /*
14470 ** Attach the auxiliary database 'recovery' to the output database handle.
14471 ** This temporary database is used during the recovery process and then
14472 ** discarded.
14473 */
14474 static void recoverOpenRecovery(sqlite3_recover *p){
14475   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
14476   recoverExec(p, p->dbOut, zSql);
14477   recoverExec(p, p->dbOut,
14478       "PRAGMA writable_schema = 1;"
14479       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
14480       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
14481   );
14482   sqlite3_free(zSql);
14483 }
14484 
14485 
14486 /*
14487 ** This function is a no-op if recover handle p already contains an error
14488 ** (if p->errCode!=SQLITE_OK).
14489 **
14490 ** Otherwise, argument zName must be the name of a table that has just been
14491 ** created in the output database. This function queries the output db
14492 ** for the schema of said table, and creates a RecoverTable object to
14493 ** store the schema in memory. The new RecoverTable object is linked into
14494 ** the list at sqlite3_recover.pTblList.
14495 **
14496 ** Parameter iRoot must be the root page of table zName in the INPUT
14497 ** database.
14498 */
14499 static void recoverAddTable(
14500   sqlite3_recover *p,
14501   const char *zName,              /* Name of table created in output db */
14502   i64 iRoot                       /* Root page of same table in INPUT db */
14503 ){
14504   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
14505       "PRAGMA table_xinfo(%Q)", zName
14506   );
14507 
14508   if( pStmt ){
14509     int iPk = -1;
14510     int iBind = 1;
14511     RecoverTable *pNew = 0;
14512     int nCol = 0;
14513     int nName = recoverStrlen(zName);
14514     int nByte = 0;
14515     while( sqlite3_step(pStmt)==SQLITE_ROW ){
14516       nCol++;
14517       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
14518     }
14519     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
14520     recoverReset(p, pStmt);
14521 
14522     pNew = recoverMalloc(p, nByte);
14523     if( pNew ){
14524       int i = 0;
14525       int iField = 0;
14526       char *csr = 0;
14527       pNew->aCol = (RecoverColumn*)&pNew[1];
14528       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
14529       pNew->nCol = nCol;
14530       pNew->iRoot = iRoot;
14531       memcpy(csr, zName, nName);
14532       csr += nName+1;
14533 
14534       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
14535         int iPKF = sqlite3_column_int(pStmt, 5);
14536         int n = sqlite3_column_bytes(pStmt, 1);
14537         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
14538         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
14539         int eHidden = sqlite3_column_int(pStmt, 6);
14540 
14541         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
14542         if( iPKF>1 ) iPk = -2;
14543         pNew->aCol[i].zCol = csr;
14544         pNew->aCol[i].eHidden = eHidden;
14545         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
14546           pNew->aCol[i].iField = -1;
14547         }else{
14548           pNew->aCol[i].iField = iField++;
14549         }
14550         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
14551          && eHidden!=RECOVER_EHIDDEN_STORED
14552         ){
14553           pNew->aCol[i].iBind = iBind++;
14554         }
14555         memcpy(csr, z, n);
14556         csr += (n+1);
14557       }
14558 
14559       pNew->pNext = p->pTblList;
14560       p->pTblList = pNew;
14561       pNew->bIntkey = 1;
14562     }
14563 
14564     recoverFinalize(p, pStmt);
14565 
14566     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
14567     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
14568       int iField = sqlite3_column_int(pStmt, 0);
14569       int iCol = sqlite3_column_int(pStmt, 1);
14570 
14571       assert( iField<pNew->nCol && iCol<pNew->nCol );
14572       pNew->aCol[iCol].iField = iField;
14573 
14574       pNew->bIntkey = 0;
14575       iPk = -2;
14576     }
14577     recoverFinalize(p, pStmt);
14578 
14579     if( p->errCode==SQLITE_OK ){
14580       if( iPk>=0 ){
14581         pNew->aCol[iPk].bIPK = 1;
14582       }else if( pNew->bIntkey ){
14583         pNew->iRowidBind = iBind++;
14584       }
14585     }
14586   }
14587 }
14588 
14589 /*
14590 ** This function is called after recoverCacheSchema() has cached those parts
14591 ** of the input database schema that could be recovered in temporary table
14592 ** "recovery.schema". This function creates in the output database copies
14593 ** of all parts of that schema that must be created before the tables can
14594 ** be populated. Specifically, this means:
14595 **
14596 **     * all tables that are not VIRTUAL, and
14597 **     * UNIQUE indexes.
14598 **
14599 ** If the recovery handle uses SQL callbacks, then callbacks containing
14600 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
14601 **
14602 ** Additionally, records are added to the sqlite_schema table of the
14603 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
14604 ** records are written directly to sqlite_schema, not actually executed.
14605 ** If the handle is in SQL callback mode, then callbacks are invoked
14606 ** with equivalent SQL statements.
14607 */
14608 static int recoverWriteSchema1(sqlite3_recover *p){
14609   sqlite3_stmt *pSelect = 0;
14610   sqlite3_stmt *pTblname = 0;
14611 
14612   pSelect = recoverPrepare(p, p->dbOut,
14613       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
14614       "  SELECT rootpage, name, sql, "
14615       "    type='table', "
14616       "    sql LIKE 'create virtual%',"
14617       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
14618       "  FROM recovery.schema"
14619       ")"
14620       "SELECT rootpage, tbl, isVirtual, name, sql"
14621       " FROM dbschema "
14622       "  WHERE tbl OR isIndex"
14623       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
14624   );
14625 
14626   pTblname = recoverPrepare(p, p->dbOut,
14627       "SELECT name FROM sqlite_schema "
14628       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
14629   );
14630 
14631   if( pSelect ){
14632     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
14633     while( sqlite3_step(pSelect)==SQLITE_ROW ){
14634       i64 iRoot = sqlite3_column_int64(pSelect, 0);
14635       int bTable = sqlite3_column_int(pSelect, 1);
14636       int bVirtual = sqlite3_column_int(pSelect, 2);
14637       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
14638       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
14639       char *zFree = 0;
14640       int rc = SQLITE_OK;
14641 
14642       if( bVirtual ){
14643         zSql = (const char*)(zFree = recoverMPrintf(p,
14644             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
14645             zName, zName, zSql
14646         ));
14647       }
14648       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
14649       if( rc==SQLITE_OK ){
14650         recoverSqlCallback(p, zSql);
14651         if( bTable && !bVirtual ){
14652           if( SQLITE_ROW==sqlite3_step(pTblname) ){
14653             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
14654             recoverAddTable(p, zTbl, iRoot);
14655           }
14656           recoverReset(p, pTblname);
14657         }
14658       }else if( rc!=SQLITE_ERROR ){
14659         recoverDbError(p, p->dbOut);
14660       }
14661       sqlite3_free(zFree);
14662     }
14663   }
14664   recoverFinalize(p, pSelect);
14665   recoverFinalize(p, pTblname);
14666 
14667   return p->errCode;
14668 }
14669 
14670 /*
14671 ** This function is called after the output database has been populated. It
14672 ** adds all recovered schema elements that were not created in the output
14673 ** database by recoverWriteSchema1() - everything except for tables and
14674 ** UNIQUE indexes. Specifically:
14675 **
14676 **     * views,
14677 **     * triggers,
14678 **     * non-UNIQUE indexes.
14679 **
14680 ** If the recover handle is in SQL callback mode, then equivalent callbacks
14681 ** are issued to create the schema elements.
14682 */
14683 static int recoverWriteSchema2(sqlite3_recover *p){
14684   sqlite3_stmt *pSelect = 0;
14685 
14686   pSelect = recoverPrepare(p, p->dbOut,
14687       p->bSlowIndexes ?
14688       "SELECT rootpage, sql FROM recovery.schema "
14689       "  WHERE type!='table' AND type!='index'"
14690       :
14691       "SELECT rootpage, sql FROM recovery.schema "
14692       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
14693   );
14694 
14695   if( pSelect ){
14696     while( sqlite3_step(pSelect)==SQLITE_ROW ){
14697       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
14698       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
14699       if( rc==SQLITE_OK ){
14700         recoverSqlCallback(p, zSql);
14701       }else if( rc!=SQLITE_ERROR ){
14702         recoverDbError(p, p->dbOut);
14703       }
14704     }
14705   }
14706   recoverFinalize(p, pSelect);
14707 
14708   return p->errCode;
14709 }
14710 
14711 /*
14712 ** This function is a no-op if recover handle p already contains an error
14713 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
14714 **
14715 ** Otherwise, if the recover handle is configured to create an output
14716 ** database (was created by sqlite3_recover_init()), then this function
14717 ** prepares and returns an SQL statement to INSERT a new record into table
14718 ** pTab, assuming the first nField fields of a record extracted from disk
14719 ** are valid.
14720 **
14721 ** For example, if table pTab is:
14722 **
14723 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
14724 **
14725 ** And nField is 4, then the SQL statement prepared and returned is:
14726 **
14727 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
14728 **
14729 ** In this case even though 4 values were extracted from the input db,
14730 ** only 3 are written to the output, as the generated STORED column
14731 ** cannot be written.
14732 **
14733 ** If the recover handle is in SQL callback mode, then the SQL statement
14734 ** prepared is such that evaluating it returns a single row containing
14735 ** a single text value - itself an SQL statement similar to the above,
14736 ** except with SQL literals in place of the variables. For example:
14737 **
14738 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
14739 **          || quote(?1) || ', '
14740 **          || quote(?2) || ', '
14741 **          || quote(?3) || ')';
14742 **
14743 ** In either case, it is the responsibility of the caller to eventually
14744 ** free the statement handle using sqlite3_finalize().
14745 */
14746 static sqlite3_stmt *recoverInsertStmt(
14747   sqlite3_recover *p,
14748   RecoverTable *pTab,
14749   int nField
14750 ){
14751   sqlite3_stmt *pRet = 0;
14752   const char *zSep = "";
14753   const char *zSqlSep = "";
14754   char *zSql = 0;
14755   char *zFinal = 0;
14756   char *zBind = 0;
14757   int ii;
14758   int bSql = p->xSql ? 1 : 0;
14759 
14760   if( nField<=0 ) return 0;
14761 
14762   assert( nField<=pTab->nCol );
14763 
14764   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
14765 
14766   if( pTab->iRowidBind ){
14767     assert( pTab->bIntkey );
14768     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
14769     if( bSql ){
14770       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
14771     }else{
14772       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
14773     }
14774     zSqlSep = "||', '||";
14775     zSep = ", ";
14776   }
14777 
14778   for(ii=0; ii<nField; ii++){
14779     int eHidden = pTab->aCol[ii].eHidden;
14780     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
14781      && eHidden!=RECOVER_EHIDDEN_STORED
14782     ){
14783       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
14784       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
14785 
14786       if( bSql ){
14787         zBind = recoverMPrintf(p,
14788             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
14789         );
14790         zSqlSep = "||', '||";
14791       }else{
14792         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
14793       }
14794       zSep = ", ";
14795     }
14796   }
14797 
14798   if( bSql ){
14799     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
14800         zSql, zBind
14801     );
14802   }else{
14803     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
14804   }
14805 
14806   pRet = recoverPrepare(p, p->dbOut, zFinal);
14807   sqlite3_free(zSql);
14808   sqlite3_free(zBind);
14809   sqlite3_free(zFinal);
14810 
14811   return pRet;
14812 }
14813 
14814 
14815 /*
14816 ** Search the list of RecoverTable objects at p->pTblList for one that
14817 ** has root page iRoot in the input database. If such an object is found,
14818 ** return a pointer to it. Otherwise, return NULL.
14819 */
14820 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
14821   RecoverTable *pRet = 0;
14822   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
14823   return pRet;
14824 }
14825 
14826 /*
14827 ** This function attempts to create a lost and found table within the
14828 ** output db. If successful, it returns a pointer to a buffer containing
14829 ** the name of the new table. It is the responsibility of the caller to
14830 ** eventually free this buffer using sqlite3_free().
14831 **
14832 ** If an error occurs, NULL is returned and an error code and error
14833 ** message left in the recover handle.
14834 */
14835 static char *recoverLostAndFoundCreate(
14836   sqlite3_recover *p,             /* Recover object */
14837   int nField                      /* Number of column fields in new table */
14838 ){
14839   char *zTbl = 0;
14840   sqlite3_stmt *pProbe = 0;
14841   int ii = 0;
14842 
14843   pProbe = recoverPrepare(p, p->dbOut,
14844     "SELECT 1 FROM sqlite_schema WHERE name=?"
14845   );
14846   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
14847     int bFail = 0;
14848     if( ii<0 ){
14849       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
14850     }else{
14851       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
14852     }
14853 
14854     if( p->errCode==SQLITE_OK ){
14855       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
14856       if( SQLITE_ROW==sqlite3_step(pProbe) ){
14857         bFail = 1;
14858       }
14859       recoverReset(p, pProbe);
14860     }
14861 
14862     if( bFail ){
14863       sqlite3_clear_bindings(pProbe);
14864       sqlite3_free(zTbl);
14865       zTbl = 0;
14866     }
14867   }
14868   recoverFinalize(p, pProbe);
14869 
14870   if( zTbl ){
14871     const char *zSep = 0;
14872     char *zField = 0;
14873     char *zSql = 0;
14874 
14875     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
14876     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
14877       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
14878       zSep = ", ";
14879     }
14880 
14881     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
14882     sqlite3_free(zField);
14883 
14884     recoverExec(p, p->dbOut, zSql);
14885     recoverSqlCallback(p, zSql);
14886     sqlite3_free(zSql);
14887   }else if( p->errCode==SQLITE_OK ){
14888     recoverError(
14889         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
14890     );
14891   }
14892 
14893   return zTbl;
14894 }
14895 
14896 /*
14897 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
14898 ** table in the output database. The name of the table is zTab, and it has
14899 ** nField c* fields.
14900 */
14901 static sqlite3_stmt *recoverLostAndFoundInsert(
14902   sqlite3_recover *p,
14903   const char *zTab,
14904   int nField
14905 ){
14906   int nTotal = nField + 4;
14907   int ii;
14908   char *zBind = 0;
14909   sqlite3_stmt *pRet = 0;
14910 
14911   if( p->xSql==0 ){
14912     for(ii=0; ii<nTotal; ii++){
14913       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
14914     }
14915     pRet = recoverPreparePrintf(
14916         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
14917     );
14918   }else{
14919     const char *zSep = "";
14920     for(ii=0; ii<nTotal; ii++){
14921       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
14922       zSep = "|| ', ' ||";
14923     }
14924     pRet = recoverPreparePrintf(
14925         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
14926     );
14927   }
14928 
14929   sqlite3_free(zBind);
14930   return pRet;
14931 }
14932 
14933 /*
14934 ** Input database page iPg contains data that will be written to the
14935 ** lost-and-found table of the output database. This function attempts
14936 ** to identify the root page of the tree that page iPg belonged to.
14937 ** If successful, it sets output variable (*piRoot) to the page number
14938 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
14939 ** an SQLite error code is returned and the final value of *piRoot
14940 ** undefined.
14941 */
14942 static int recoverLostAndFoundFindRoot(
14943   sqlite3_recover *p,
14944   i64 iPg,
14945   i64 *piRoot
14946 ){
14947   RecoverStateLAF *pLaf = &p->laf;
14948 
14949   if( pLaf->pFindRoot==0 ){
14950     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
14951         "WITH RECURSIVE p(pgno) AS ("
14952         "  SELECT ?"
14953         "    UNION"
14954         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
14955         ") "
14956         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
14957         "    AND m.parent IS NULL"
14958     );
14959   }
14960   if( p->errCode==SQLITE_OK ){
14961     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
14962     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
14963       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
14964     }else{
14965       *piRoot = iPg;
14966     }
14967     recoverReset(p, pLaf->pFindRoot);
14968   }
14969   return p->errCode;
14970 }
14971 
14972 /*
14973 ** Recover data from page iPage of the input database and write it to
14974 ** the lost-and-found table in the output database.
14975 */
14976 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
14977   RecoverStateLAF *pLaf = &p->laf;
14978   sqlite3_value **apVal = pLaf->apVal;
14979   sqlite3_stmt *pPageData = pLaf->pPageData;
14980   sqlite3_stmt *pInsert = pLaf->pInsert;
14981 
14982   int nVal = -1;
14983   int iPrevCell = 0;
14984   i64 iRoot = 0;
14985   int bHaveRowid = 0;
14986   i64 iRowid = 0;
14987   int ii = 0;
14988 
14989   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
14990   sqlite3_bind_int64(pPageData, 1, iPage);
14991   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
14992     int iCell = sqlite3_column_int64(pPageData, 0);
14993     int iField = sqlite3_column_int64(pPageData, 1);
14994 
14995     if( iPrevCell!=iCell && nVal>=0 ){
14996       /* Insert the new row */
14997       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
14998       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
14999       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
15000       if( bHaveRowid ){
15001         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
15002       }
15003       for(ii=0; ii<nVal; ii++){
15004         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
15005       }
15006       if( sqlite3_step(pInsert)==SQLITE_ROW ){
15007         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
15008       }
15009       recoverReset(p, pInsert);
15010 
15011       /* Discard the accumulated row data */
15012       for(ii=0; ii<nVal; ii++){
15013         sqlite3_value_free(apVal[ii]);
15014         apVal[ii] = 0;
15015       }
15016       sqlite3_clear_bindings(pInsert);
15017       bHaveRowid = 0;
15018       nVal = -1;
15019     }
15020 
15021     if( iCell<0 ) break;
15022 
15023     if( iField<0 ){
15024       assert( nVal==-1 );
15025       iRowid = sqlite3_column_int64(pPageData, 2);
15026       bHaveRowid = 1;
15027       nVal = 0;
15028     }else if( iField<pLaf->nMaxField ){
15029       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
15030       apVal[iField] = sqlite3_value_dup(pVal);
15031       assert( iField==nVal || (nVal==-1 && iField==0) );
15032       nVal = iField+1;
15033       if( apVal[iField]==0 ){
15034         recoverError(p, SQLITE_NOMEM, 0);
15035       }
15036     }
15037 
15038     iPrevCell = iCell;
15039   }
15040   recoverReset(p, pPageData);
15041 
15042   for(ii=0; ii<nVal; ii++){
15043     sqlite3_value_free(apVal[ii]);
15044     apVal[ii] = 0;
15045   }
15046 }
15047 
15048 /*
15049 ** Perform one step (sqlite3_recover_step()) of work for the connection
15050 ** passed as the only argument, which is guaranteed to be in
15051 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
15052 ** table of the output database is populated with recovered data that can
15053 ** not be assigned to any recovered schema object.
15054 */
15055 static int recoverLostAndFound3Step(sqlite3_recover *p){
15056   RecoverStateLAF *pLaf = &p->laf;
15057   if( p->errCode==SQLITE_OK ){
15058     if( pLaf->pInsert==0 ){
15059       return SQLITE_DONE;
15060     }else{
15061       if( p->errCode==SQLITE_OK ){
15062         int res = sqlite3_step(pLaf->pAllPage);
15063         if( res==SQLITE_ROW ){
15064           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
15065           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
15066             recoverLostAndFoundOnePage(p, iPage);
15067           }
15068         }else{
15069           recoverReset(p, pLaf->pAllPage);
15070           return SQLITE_DONE;
15071         }
15072       }
15073     }
15074   }
15075   return SQLITE_OK;
15076 }
15077 
15078 /*
15079 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
15080 ** state - during which the lost-and-found table of the output database
15081 ** is populated with recovered data that can not be assigned to any
15082 ** recovered schema object.
15083 */
15084 static void recoverLostAndFound3Init(sqlite3_recover *p){
15085   RecoverStateLAF *pLaf = &p->laf;
15086 
15087   if( pLaf->nMaxField>0 ){
15088     char *zTab = 0;               /* Name of lost_and_found table */
15089 
15090     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
15091     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
15092     sqlite3_free(zTab);
15093 
15094     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
15095         "WITH RECURSIVE seq(ii) AS ("
15096         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
15097         ")"
15098         "SELECT ii FROM seq" , p->laf.nPg
15099     );
15100     pLaf->pPageData = recoverPrepare(p, p->dbOut,
15101         "SELECT cell, field, value "
15102         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
15103         "UNION ALL "
15104         "SELECT -1, -1, -1"
15105     );
15106 
15107     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
15108         pLaf->nMaxField*sizeof(sqlite3_value*)
15109     );
15110   }
15111 }
15112 
15113 /*
15114 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
15115 ** tables recovered from the schema of the input database are populated with
15116 ** recovered data.
15117 */
15118 static int recoverWriteDataInit(sqlite3_recover *p){
15119   RecoverStateW1 *p1 = &p->w1;
15120   RecoverTable *pTbl = 0;
15121   int nByte = 0;
15122 
15123   /* Figure out the maximum number of columns for any table in the schema */
15124   assert( p1->nMax==0 );
15125   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
15126     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
15127   }
15128 
15129   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
15130   ** that will be written to the output database in a single row. */
15131   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
15132   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
15133   if( p1->apVal==0 ) return p->errCode;
15134 
15135   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
15136   ** to loop through cells that appear to belong to a single table (pSel). */
15137   p1->pTbls = recoverPrepare(p, p->dbOut,
15138       "SELECT rootpage FROM recovery.schema "
15139       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
15140       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
15141   );
15142   p1->pSel = recoverPrepare(p, p->dbOut,
15143       "WITH RECURSIVE pages(page) AS ("
15144       "  SELECT ?1"
15145       "    UNION"
15146       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
15147       "    WHERE pgno=page"
15148       ") "
15149       "SELECT page, cell, field, value "
15150       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
15151       "UNION ALL "
15152       "SELECT 0, 0, 0, 0"
15153   );
15154 
15155   return p->errCode;
15156 }
15157 
15158 /*
15159 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
15160 ** sqlite3_recover.w1).
15161 */
15162 static void recoverWriteDataCleanup(sqlite3_recover *p){
15163   RecoverStateW1 *p1 = &p->w1;
15164   int ii;
15165   for(ii=0; ii<p1->nVal; ii++){
15166     sqlite3_value_free(p1->apVal[ii]);
15167   }
15168   sqlite3_free(p1->apVal);
15169   recoverFinalize(p, p1->pInsert);
15170   recoverFinalize(p, p1->pTbls);
15171   recoverFinalize(p, p1->pSel);
15172   memset(p1, 0, sizeof(*p1));
15173 }
15174 
15175 /*
15176 ** Perform one step (sqlite3_recover_step()) of work for the connection
15177 ** passed as the only argument, which is guaranteed to be in
15178 ** RECOVER_STATE_WRITING state - during which tables recovered from the
15179 ** schema of the input database are populated with recovered data.
15180 */
15181 static int recoverWriteDataStep(sqlite3_recover *p){
15182   RecoverStateW1 *p1 = &p->w1;
15183   sqlite3_stmt *pSel = p1->pSel;
15184   sqlite3_value **apVal = p1->apVal;
15185 
15186   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
15187     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
15188       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
15189       p1->pTab = recoverFindTable(p, iRoot);
15190 
15191       recoverFinalize(p, p1->pInsert);
15192       p1->pInsert = 0;
15193 
15194       /* If this table is unknown, return early. The caller will invoke this
15195       ** function again and it will move on to the next table.  */
15196       if( p1->pTab==0 ) return p->errCode;
15197 
15198       /* If this is the sqlite_sequence table, delete any rows added by
15199       ** earlier INSERT statements on tables with AUTOINCREMENT primary
15200       ** keys before recovering its contents. The p1->pTbls SELECT statement
15201       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
15202       ** worry about it being modified after it is recovered. */
15203       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
15204         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
15205         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
15206       }
15207 
15208       /* Bind the root page of this table within the original database to
15209       ** SELECT statement p1->pSel. The SELECT statement will then iterate
15210       ** through cells that look like they belong to table pTab.  */
15211       sqlite3_bind_int64(pSel, 1, iRoot);
15212 
15213       p1->nVal = 0;
15214       p1->bHaveRowid = 0;
15215       p1->iPrevPage = -1;
15216       p1->iPrevCell = -1;
15217     }else{
15218       return SQLITE_DONE;
15219     }
15220   }
15221   assert( p->errCode!=SQLITE_OK || p1->pTab );
15222 
15223   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
15224     RecoverTable *pTab = p1->pTab;
15225 
15226     i64 iPage = sqlite3_column_int64(pSel, 0);
15227     int iCell = sqlite3_column_int(pSel, 1);
15228     int iField = sqlite3_column_int(pSel, 2);
15229     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
15230     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
15231 
15232     assert( bNewCell==0 || (iField==-1 || iField==0) );
15233     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
15234 
15235     if( bNewCell ){
15236       int ii = 0;
15237       if( p1->nVal>=0 ){
15238         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
15239           recoverFinalize(p, p1->pInsert);
15240           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
15241           p1->nInsert = p1->nVal;
15242         }
15243         if( p1->nVal>0 ){
15244           sqlite3_stmt *pInsert = p1->pInsert;
15245           for(ii=0; ii<pTab->nCol; ii++){
15246             RecoverColumn *pCol = &pTab->aCol[ii];
15247             int iBind = pCol->iBind;
15248             if( iBind>0 ){
15249               if( pCol->bIPK ){
15250                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
15251               }else if( pCol->iField<p1->nVal ){
15252                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
15253               }
15254             }
15255           }
15256           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
15257             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
15258           }
15259           if( SQLITE_ROW==sqlite3_step(pInsert) ){
15260             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
15261             recoverSqlCallback(p, z);
15262           }
15263           recoverReset(p, pInsert);
15264           assert( p->errCode || pInsert );
15265           if( pInsert ) sqlite3_clear_bindings(pInsert);
15266         }
15267       }
15268 
15269       for(ii=0; ii<p1->nVal; ii++){
15270         sqlite3_value_free(apVal[ii]);
15271         apVal[ii] = 0;
15272       }
15273       p1->nVal = -1;
15274       p1->bHaveRowid = 0;
15275     }
15276 
15277     if( iPage!=0 ){
15278       if( iField<0 ){
15279         p1->iRowid = sqlite3_column_int64(pSel, 3);
15280         assert( p1->nVal==-1 );
15281         p1->nVal = 0;
15282         p1->bHaveRowid = 1;
15283       }else if( iField<pTab->nCol ){
15284         assert( apVal[iField]==0 );
15285         apVal[iField] = sqlite3_value_dup( pVal );
15286         if( apVal[iField]==0 ){
15287           recoverError(p, SQLITE_NOMEM, 0);
15288         }
15289         p1->nVal = iField+1;
15290       }
15291       p1->iPrevCell = iCell;
15292       p1->iPrevPage = iPage;
15293     }
15294   }else{
15295     recoverReset(p, pSel);
15296     p1->pTab = 0;
15297   }
15298 
15299   return p->errCode;
15300 }
15301 
15302 /*
15303 ** Initialize resources required by sqlite3_recover_step() in
15304 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
15305 ** already allocated to a recovered schema element is determined.
15306 */
15307 static void recoverLostAndFound1Init(sqlite3_recover *p){
15308   RecoverStateLAF *pLaf = &p->laf;
15309   sqlite3_stmt *pStmt = 0;
15310 
15311   assert( p->laf.pUsed==0 );
15312   pLaf->nPg = recoverPageCount(p);
15313   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
15314 
15315   /* Prepare a statement to iterate through all pages that are part of any tree
15316   ** in the recoverable part of the input database schema to the bitmap. And,
15317   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
15318   ** freelist.  */
15319   pStmt = recoverPrepare(
15320       p, p->dbOut,
15321       "WITH trunk(pgno) AS ("
15322       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
15323       "    UNION"
15324       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
15325       "),"
15326       "trunkdata(pgno, data) AS ("
15327       "  SELECT pgno, getpage(pgno) FROM trunk"
15328       "),"
15329       "freelist(data, n, freepgno) AS ("
15330       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
15331       "    UNION ALL"
15332       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
15333       "),"
15334       ""
15335       "roots(r) AS ("
15336       "  SELECT 1 UNION ALL"
15337       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
15338       "),"
15339       "used(page) AS ("
15340       "  SELECT r FROM roots"
15341       "    UNION"
15342       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
15343       "    WHERE pgno=page"
15344       ") "
15345       "SELECT page FROM used"
15346       " UNION ALL "
15347       "SELECT freepgno FROM freelist WHERE NOT ?"
15348   );
15349   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
15350   pLaf->pUsedPages = pStmt;
15351 }
15352 
15353 /*
15354 ** Perform one step (sqlite3_recover_step()) of work for the connection
15355 ** passed as the only argument, which is guaranteed to be in
15356 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
15357 ** already allocated to a recovered schema element is determined.
15358 */
15359 static int recoverLostAndFound1Step(sqlite3_recover *p){
15360   RecoverStateLAF *pLaf = &p->laf;
15361   int rc = p->errCode;
15362   if( rc==SQLITE_OK ){
15363     rc = sqlite3_step(pLaf->pUsedPages);
15364     if( rc==SQLITE_ROW ){
15365       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
15366       recoverBitmapSet(pLaf->pUsed, iPg);
15367       rc = SQLITE_OK;
15368     }else{
15369       recoverFinalize(p, pLaf->pUsedPages);
15370       pLaf->pUsedPages = 0;
15371     }
15372   }
15373   return rc;
15374 }
15375 
15376 /*
15377 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
15378 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
15379 ** are sorted into sets that likely belonged to the same database tree.
15380 */
15381 static void recoverLostAndFound2Init(sqlite3_recover *p){
15382   RecoverStateLAF *pLaf = &p->laf;
15383 
15384   assert( p->laf.pAllAndParent==0 );
15385   assert( p->laf.pMapInsert==0 );
15386   assert( p->laf.pMaxField==0 );
15387   assert( p->laf.nMaxField==0 );
15388 
15389   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
15390       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
15391   );
15392   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
15393       "WITH RECURSIVE seq(ii) AS ("
15394       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
15395       ")"
15396       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
15397       " UNION ALL "
15398       "SELECT NULL, ii FROM seq", p->laf.nPg
15399   );
15400   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
15401       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
15402   );
15403 }
15404 
15405 /*
15406 ** Perform one step (sqlite3_recover_step()) of work for the connection
15407 ** passed as the only argument, which is guaranteed to be in
15408 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
15409 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
15410 ** to the same database tree.
15411 */
15412 static int recoverLostAndFound2Step(sqlite3_recover *p){
15413   RecoverStateLAF *pLaf = &p->laf;
15414   if( p->errCode==SQLITE_OK ){
15415     int res = sqlite3_step(pLaf->pAllAndParent);
15416     if( res==SQLITE_ROW ){
15417       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
15418       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
15419         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
15420         sqlite3_bind_value(pLaf->pMapInsert, 2,
15421             sqlite3_column_value(pLaf->pAllAndParent, 0)
15422         );
15423         sqlite3_step(pLaf->pMapInsert);
15424         recoverReset(p, pLaf->pMapInsert);
15425         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
15426         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
15427           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
15428           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
15429         }
15430         recoverReset(p, pLaf->pMaxField);
15431       }
15432     }else{
15433       recoverFinalize(p, pLaf->pAllAndParent);
15434       pLaf->pAllAndParent =0;
15435       return SQLITE_DONE;
15436     }
15437   }
15438   return p->errCode;
15439 }
15440 
15441 /*
15442 ** Free all resources allocated as part of sqlite3_recover_step() calls
15443 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
15444 */
15445 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
15446   recoverBitmapFree(p->laf.pUsed);
15447   p->laf.pUsed = 0;
15448   sqlite3_finalize(p->laf.pUsedPages);
15449   sqlite3_finalize(p->laf.pAllAndParent);
15450   sqlite3_finalize(p->laf.pMapInsert);
15451   sqlite3_finalize(p->laf.pMaxField);
15452   sqlite3_finalize(p->laf.pFindRoot);
15453   sqlite3_finalize(p->laf.pInsert);
15454   sqlite3_finalize(p->laf.pAllPage);
15455   sqlite3_finalize(p->laf.pPageData);
15456   p->laf.pUsedPages = 0;
15457   p->laf.pAllAndParent = 0;
15458   p->laf.pMapInsert = 0;
15459   p->laf.pMaxField = 0;
15460   p->laf.pFindRoot = 0;
15461   p->laf.pInsert = 0;
15462   p->laf.pAllPage = 0;
15463   p->laf.pPageData = 0;
15464   sqlite3_free(p->laf.apVal);
15465   p->laf.apVal = 0;
15466 }
15467 
15468 /*
15469 ** Free all resources allocated as part of sqlite3_recover_step() calls.
15470 */
15471 static void recoverFinalCleanup(sqlite3_recover *p){
15472   RecoverTable *pTab = 0;
15473   RecoverTable *pNext = 0;
15474 
15475   recoverWriteDataCleanup(p);
15476   recoverLostAndFoundCleanup(p);
15477 
15478   for(pTab=p->pTblList; pTab; pTab=pNext){
15479     pNext = pTab->pNext;
15480     sqlite3_free(pTab);
15481   }
15482   p->pTblList = 0;
15483   sqlite3_finalize(p->pGetPage);
15484   p->pGetPage = 0;
15485   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
15486 
15487   {
15488 #ifndef NDEBUG
15489     int res =
15490 #endif
15491        sqlite3_close(p->dbOut);
15492     assert( res==SQLITE_OK );
15493   }
15494   p->dbOut = 0;
15495 }
15496 
15497 /*
15498 ** Decode and return an unsigned 16-bit big-endian integer value from
15499 ** buffer a[].
15500 */
15501 static u32 recoverGetU16(const u8 *a){
15502   return (((u32)a[0])<<8) + ((u32)a[1]);
15503 }
15504 
15505 /*
15506 ** Decode and return an unsigned 32-bit big-endian integer value from
15507 ** buffer a[].
15508 */
15509 static u32 recoverGetU32(const u8 *a){
15510   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
15511 }
15512 
15513 /*
15514 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
15515 ** and return the number of bytes consumed.
15516 */
15517 static int recoverGetVarint(const u8 *a, i64 *pVal){
15518   sqlite3_uint64 u = 0;
15519   int i;
15520   for(i=0; i<8; i++){
15521     u = (u<<7) + (a[i]&0x7f);
15522     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
15523   }
15524   u = (u<<8) + (a[i]&0xff);
15525   *pVal = (sqlite3_int64)u;
15526   return 9;
15527 }
15528 
15529 /*
15530 ** The second argument points to a buffer n bytes in size. If this buffer
15531 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
15532 ** return the page-size in bytes. Otherwise, if the buffer does not
15533 ** appear to contain a well-formed b-tree page, return 0.
15534 */
15535 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
15536   u8 *aUsed = aTmp;
15537   int nFrag = 0;
15538   int nActual = 0;
15539   int iFree = 0;
15540   int nCell = 0;                  /* Number of cells on page */
15541   int iCellOff = 0;               /* Offset of cell array in page */
15542   int iContent = 0;
15543   int eType = 0;
15544   int ii = 0;
15545 
15546   eType = (int)a[0];
15547   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
15548 
15549   iFree = (int)recoverGetU16(&a[1]);
15550   nCell = (int)recoverGetU16(&a[3]);
15551   iContent = (int)recoverGetU16(&a[5]);
15552   if( iContent==0 ) iContent = 65536;
15553   nFrag = (int)a[7];
15554 
15555   if( iContent>n ) return 0;
15556 
15557   memset(aUsed, 0, n);
15558   memset(aUsed, 0xFF, iContent);
15559 
15560   /* Follow the free-list. This is the same format for all b-tree pages. */
15561   if( iFree && iFree<=iContent ) return 0;
15562   while( iFree ){
15563     int iNext = 0;
15564     int nByte = 0;
15565     if( iFree>(n-4) ) return 0;
15566     iNext = recoverGetU16(&a[iFree]);
15567     nByte = recoverGetU16(&a[iFree+2]);
15568     if( iFree+nByte>n ) return 0;
15569     if( iNext && iNext<iFree+nByte ) return 0;
15570     memset(&aUsed[iFree], 0xFF, nByte);
15571     iFree = iNext;
15572   }
15573 
15574   /* Run through the cells */
15575   if( eType==0x02 || eType==0x05 ){
15576     iCellOff = 12;
15577   }else{
15578     iCellOff = 8;
15579   }
15580   if( (iCellOff + 2*nCell)>iContent ) return 0;
15581   for(ii=0; ii<nCell; ii++){
15582     int iByte;
15583     i64 nPayload = 0;
15584     int nByte = 0;
15585     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
15586     if( iOff<iContent || iOff>n ){
15587       return 0;
15588     }
15589     if( eType==0x05 || eType==0x02 ) nByte += 4;
15590     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
15591     if( eType==0x0D ){
15592       i64 dummy = 0;
15593       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
15594     }
15595     if( eType!=0x05 ){
15596       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
15597       int M = ((n-12)*32/255)-23;
15598       int K = M+((nPayload-M)%(n-4));
15599 
15600       if( nPayload<X ){
15601         nByte += nPayload;
15602       }else if( K<=X ){
15603         nByte += K+4;
15604       }else{
15605         nByte += M+4;
15606       }
15607     }
15608 
15609     if( iOff+nByte>n ){
15610       return 0;
15611     }
15612     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
15613       if( aUsed[iByte]!=0 ){
15614         return 0;
15615       }
15616       aUsed[iByte] = 0xFF;
15617     }
15618   }
15619 
15620   nActual = 0;
15621   for(ii=0; ii<n; ii++){
15622     if( aUsed[ii]==0 ) nActual++;
15623   }
15624   return (nActual==nFrag);
15625 }
15626 
15627 
15628 static int recoverVfsClose(sqlite3_file*);
15629 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
15630 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
15631 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
15632 static int recoverVfsSync(sqlite3_file*, int flags);
15633 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
15634 static int recoverVfsLock(sqlite3_file*, int);
15635 static int recoverVfsUnlock(sqlite3_file*, int);
15636 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
15637 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
15638 static int recoverVfsSectorSize(sqlite3_file*);
15639 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
15640 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
15641 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
15642 static void recoverVfsShmBarrier(sqlite3_file*);
15643 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
15644 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
15645 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
15646 
15647 static sqlite3_io_methods recover_methods = {
15648   2, /* iVersion */
15649   recoverVfsClose,
15650   recoverVfsRead,
15651   recoverVfsWrite,
15652   recoverVfsTruncate,
15653   recoverVfsSync,
15654   recoverVfsFileSize,
15655   recoverVfsLock,
15656   recoverVfsUnlock,
15657   recoverVfsCheckReservedLock,
15658   recoverVfsFileControl,
15659   recoverVfsSectorSize,
15660   recoverVfsDeviceCharacteristics,
15661   recoverVfsShmMap,
15662   recoverVfsShmLock,
15663   recoverVfsShmBarrier,
15664   recoverVfsShmUnmap,
15665   recoverVfsFetch,
15666   recoverVfsUnfetch
15667 };
15668 
15669 static int recoverVfsClose(sqlite3_file *pFd){
15670   assert( pFd->pMethods!=&recover_methods );
15671   return pFd->pMethods->xClose(pFd);
15672 }
15673 
15674 /*
15675 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
15676 */
15677 static void recoverPutU16(u8 *a, u32 v){
15678   a[0] = (v>>8) & 0x00FF;
15679   a[1] = (v>>0) & 0x00FF;
15680 }
15681 
15682 /*
15683 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
15684 */
15685 static void recoverPutU32(u8 *a, u32 v){
15686   a[0] = (v>>24) & 0x00FF;
15687   a[1] = (v>>16) & 0x00FF;
15688   a[2] = (v>>8) & 0x00FF;
15689   a[3] = (v>>0) & 0x00FF;
15690 }
15691 
15692 /*
15693 ** Detect the page-size of the database opened by file-handle pFd by
15694 ** searching the first part of the file for a well-formed SQLite b-tree
15695 ** page. If parameter nReserve is non-zero, then as well as searching for
15696 ** a b-tree page with zero reserved bytes, this function searches for one
15697 ** with nReserve reserved bytes at the end of it.
15698 **
15699 ** If successful, set variable p->detected_pgsz to the detected page-size
15700 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
15701 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
15702 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
15703 ** is returned. The final value of p->detected_pgsz is undefined in this
15704 ** case.
15705 */
15706 static int recoverVfsDetectPagesize(
15707   sqlite3_recover *p,             /* Recover handle */
15708   sqlite3_file *pFd,              /* File-handle open on input database */
15709   u32 nReserve,                   /* Possible nReserve value */
15710   i64 nSz                         /* Size of database file in bytes */
15711 ){
15712   int rc = SQLITE_OK;
15713   const int nMin = 512;
15714   const int nMax = 65536;
15715   const int nMaxBlk = 4;
15716   u32 pgsz = 0;
15717   int iBlk = 0;
15718   u8 *aPg = 0;
15719   u8 *aTmp = 0;
15720   int nBlk = 0;
15721 
15722   aPg = (u8*)sqlite3_malloc(2*nMax);
15723   if( aPg==0 ) return SQLITE_NOMEM;
15724   aTmp = &aPg[nMax];
15725 
15726   nBlk = (nSz+nMax-1)/nMax;
15727   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
15728 
15729   do {
15730     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
15731       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
15732       memset(aPg, 0, nMax);
15733       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
15734       if( rc==SQLITE_OK ){
15735         int pgsz2;
15736         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
15737           int iOff;
15738           for(iOff=0; iOff<nMax; iOff+=pgsz2){
15739             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
15740               pgsz = pgsz2;
15741               break;
15742             }
15743           }
15744         }
15745       }
15746     }
15747     if( pgsz>(u32)p->detected_pgsz ){
15748       p->detected_pgsz = pgsz;
15749       p->nReserve = nReserve;
15750     }
15751     if( nReserve==0 ) break;
15752     nReserve = 0;
15753   }while( 1 );
15754 
15755   p->detected_pgsz = pgsz;
15756   sqlite3_free(aPg);
15757   return rc;
15758 }
15759 
15760 /*
15761 ** The xRead() method of the wrapper VFS. This is used to intercept calls
15762 ** to read page 1 of the input database.
15763 */
15764 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
15765   int rc = SQLITE_OK;
15766   if( pFd->pMethods==&recover_methods ){
15767     pFd->pMethods = recover_g.pMethods;
15768     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
15769     if( nByte==16 ){
15770       sqlite3_randomness(16, aBuf);
15771     }else
15772     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
15773       /* Ensure that the database has a valid header file. The only fields
15774       ** that really matter to recovery are:
15775       **
15776       **   + Database page size (16-bits at offset 16)
15777       **   + Size of db in pages (32-bits at offset 28)
15778       **   + Database encoding (32-bits at offset 56)
15779       **
15780       ** Also preserved are:
15781       **
15782       **   + first freelist page (32-bits at offset 32)
15783       **   + size of freelist (32-bits at offset 36)
15784       **   + the wal-mode flags (16-bits at offset 18)
15785       **
15786       ** We also try to preserve the auto-vacuum, incr-value, user-version
15787       ** and application-id fields - all 32 bit quantities at offsets
15788       ** 52, 60, 64 and 68. All other fields are set to known good values.
15789       **
15790       ** Byte offset 105 should also contain the page-size as a 16-bit
15791       ** integer.
15792       */
15793       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
15794       u8 aHdr[108] = {
15795         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
15796         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
15797         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
15798         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
15799         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
15800         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
15801         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
15802         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
15803         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
15804         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
15805         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
15806         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
15807         0x00, 0x2e, 0x5b, 0x30,
15808 
15809         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
15810       };
15811       u8 *a = (u8*)aBuf;
15812 
15813       u32 pgsz = recoverGetU16(&a[16]);
15814       u32 nReserve = a[20];
15815       u32 enc = recoverGetU32(&a[56]);
15816       u32 dbsz = 0;
15817       i64 dbFileSize = 0;
15818       int ii;
15819       sqlite3_recover *p = recover_g.p;
15820 
15821       if( pgsz==0x01 ) pgsz = 65536;
15822       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
15823 
15824       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
15825         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
15826       }
15827       if( p->detected_pgsz ){
15828         pgsz = p->detected_pgsz;
15829         nReserve = p->nReserve;
15830       }
15831 
15832       if( pgsz ){
15833         dbsz = dbFileSize / pgsz;
15834       }
15835       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
15836         enc = SQLITE_UTF8;
15837       }
15838 
15839       sqlite3_free(p->pPage1Cache);
15840       p->pPage1Cache = 0;
15841       p->pPage1Disk = 0;
15842 
15843       p->pgsz = nByte;
15844       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
15845       if( p->pPage1Cache ){
15846         p->pPage1Disk = &p->pPage1Cache[nByte];
15847         memcpy(p->pPage1Disk, aBuf, nByte);
15848         aHdr[18] = a[18];
15849         aHdr[19] = a[19];
15850         recoverPutU32(&aHdr[28], dbsz);
15851         recoverPutU32(&aHdr[56], enc);
15852         recoverPutU16(&aHdr[105], pgsz-nReserve);
15853         if( pgsz==65536 ) pgsz = 1;
15854         recoverPutU16(&aHdr[16], pgsz);
15855         aHdr[20] = nReserve;
15856         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
15857           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
15858         }
15859         memcpy(aBuf, aHdr, sizeof(aHdr));
15860         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
15861 
15862         memcpy(p->pPage1Cache, aBuf, nByte);
15863       }else{
15864         rc = p->errCode;
15865       }
15866 
15867     }
15868     pFd->pMethods = &recover_methods;
15869   }else{
15870     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
15871   }
15872   return rc;
15873 }
15874 
15875 /*
15876 ** Used to make sqlite3_io_methods wrapper methods less verbose.
15877 */
15878 #define RECOVER_VFS_WRAPPER(code)                         \
15879   int rc = SQLITE_OK;                                     \
15880   if( pFd->pMethods==&recover_methods ){                  \
15881     pFd->pMethods = recover_g.pMethods;                   \
15882     rc = code;                                            \
15883     pFd->pMethods = &recover_methods;                     \
15884   }else{                                                  \
15885     rc = code;                                            \
15886   }                                                       \
15887   return rc;
15888 
15889 /*
15890 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
15891 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
15892 ** method on the lower level VFS, then reinstall the wrapper before returning.
15893 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
15894 */
15895 static int recoverVfsWrite(
15896   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
15897 ){
15898   RECOVER_VFS_WRAPPER (
15899       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
15900   );
15901 }
15902 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
15903   RECOVER_VFS_WRAPPER (
15904       pFd->pMethods->xTruncate(pFd, size)
15905   );
15906 }
15907 static int recoverVfsSync(sqlite3_file *pFd, int flags){
15908   RECOVER_VFS_WRAPPER (
15909       pFd->pMethods->xSync(pFd, flags)
15910   );
15911 }
15912 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
15913   RECOVER_VFS_WRAPPER (
15914       pFd->pMethods->xFileSize(pFd, pSize)
15915   );
15916 }
15917 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
15918   RECOVER_VFS_WRAPPER (
15919       pFd->pMethods->xLock(pFd, eLock)
15920   );
15921 }
15922 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
15923   RECOVER_VFS_WRAPPER (
15924       pFd->pMethods->xUnlock(pFd, eLock)
15925   );
15926 }
15927 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
15928   RECOVER_VFS_WRAPPER (
15929       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
15930   );
15931 }
15932 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
15933   RECOVER_VFS_WRAPPER (
15934     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
15935   );
15936 }
15937 static int recoverVfsSectorSize(sqlite3_file *pFd){
15938   RECOVER_VFS_WRAPPER (
15939       pFd->pMethods->xSectorSize(pFd)
15940   );
15941 }
15942 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
15943   RECOVER_VFS_WRAPPER (
15944       pFd->pMethods->xDeviceCharacteristics(pFd)
15945   );
15946 }
15947 static int recoverVfsShmMap(
15948   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
15949 ){
15950   RECOVER_VFS_WRAPPER (
15951       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
15952   );
15953 }
15954 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
15955   RECOVER_VFS_WRAPPER (
15956       pFd->pMethods->xShmLock(pFd, offset, n, flags)
15957   );
15958 }
15959 static void recoverVfsShmBarrier(sqlite3_file *pFd){
15960   if( pFd->pMethods==&recover_methods ){
15961     pFd->pMethods = recover_g.pMethods;
15962     pFd->pMethods->xShmBarrier(pFd);
15963     pFd->pMethods = &recover_methods;
15964   }else{
15965     pFd->pMethods->xShmBarrier(pFd);
15966   }
15967 }
15968 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
15969   RECOVER_VFS_WRAPPER (
15970       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
15971   );
15972 }
15973 
15974 static int recoverVfsFetch(
15975   sqlite3_file *pFd,
15976   sqlite3_int64 iOff,
15977   int iAmt,
15978   void **pp
15979 ){
15980   (void)pFd;
15981   (void)iOff;
15982   (void)iAmt;
15983   *pp = 0;
15984   return SQLITE_OK;
15985 }
15986 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
15987   (void)pFd;
15988   (void)iOff;
15989   (void)p;
15990   return SQLITE_OK;
15991 }
15992 
15993 /*
15994 ** Install the VFS wrapper around the file-descriptor open on the input
15995 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
15996 ** when this function is called.
15997 */
15998 static void recoverInstallWrapper(sqlite3_recover *p){
15999   sqlite3_file *pFd = 0;
16000   assert( recover_g.pMethods==0 );
16001   recoverAssertMutexHeld();
16002   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
16003   assert( pFd==0 || pFd->pMethods!=&recover_methods );
16004   if( pFd && pFd->pMethods ){
16005     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
16006     recover_g.pMethods = pFd->pMethods;
16007     recover_g.p = p;
16008     recover_methods.iVersion = iVersion;
16009     pFd->pMethods = &recover_methods;
16010   }
16011 }
16012 
16013 /*
16014 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
16015 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
16016 ** held when this function is called.
16017 */
16018 static void recoverUninstallWrapper(sqlite3_recover *p){
16019   sqlite3_file *pFd = 0;
16020   recoverAssertMutexHeld();
16021   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
16022   if( pFd && pFd->pMethods ){
16023     pFd->pMethods = recover_g.pMethods;
16024     recover_g.pMethods = 0;
16025     recover_g.p = 0;
16026   }
16027 }
16028 
16029 /*
16030 ** This function does the work of a single sqlite3_recover_step() call. It
16031 ** is guaranteed that the handle is not in an error state when this
16032 ** function is called.
16033 */
16034 static void recoverStep(sqlite3_recover *p){
16035   assert( p && p->errCode==SQLITE_OK );
16036   switch( p->eState ){
16037     case RECOVER_STATE_INIT:
16038       /* This is the very first call to sqlite3_recover_step() on this object.
16039       */
16040       recoverSqlCallback(p, "BEGIN");
16041       recoverSqlCallback(p, "PRAGMA writable_schema = on");
16042 
16043       recoverEnterMutex();
16044       recoverInstallWrapper(p);
16045 
16046       /* Open the output database. And register required virtual tables and
16047       ** user functions with the new handle. */
16048       recoverOpenOutput(p);
16049 
16050       /* Open transactions on both the input and output databases. */
16051       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
16052       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
16053       recoverExec(p, p->dbIn, "BEGIN");
16054       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
16055       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
16056       recoverTransferSettings(p);
16057       recoverOpenRecovery(p);
16058       recoverCacheSchema(p);
16059 
16060       recoverUninstallWrapper(p);
16061       recoverLeaveMutex();
16062 
16063       recoverExec(p, p->dbOut, "BEGIN");
16064 
16065       recoverWriteSchema1(p);
16066       p->eState = RECOVER_STATE_WRITING;
16067       break;
16068 
16069     case RECOVER_STATE_WRITING: {
16070       if( p->w1.pTbls==0 ){
16071         recoverWriteDataInit(p);
16072       }
16073       if( SQLITE_DONE==recoverWriteDataStep(p) ){
16074         recoverWriteDataCleanup(p);
16075         if( p->zLostAndFound ){
16076           p->eState = RECOVER_STATE_LOSTANDFOUND1;
16077         }else{
16078           p->eState = RECOVER_STATE_SCHEMA2;
16079         }
16080       }
16081       break;
16082     }
16083 
16084     case RECOVER_STATE_LOSTANDFOUND1: {
16085       if( p->laf.pUsed==0 ){
16086         recoverLostAndFound1Init(p);
16087       }
16088       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
16089         p->eState = RECOVER_STATE_LOSTANDFOUND2;
16090       }
16091       break;
16092     }
16093     case RECOVER_STATE_LOSTANDFOUND2: {
16094       if( p->laf.pAllAndParent==0 ){
16095         recoverLostAndFound2Init(p);
16096       }
16097       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
16098         p->eState = RECOVER_STATE_LOSTANDFOUND3;
16099       }
16100       break;
16101     }
16102 
16103     case RECOVER_STATE_LOSTANDFOUND3: {
16104       if( p->laf.pInsert==0 ){
16105         recoverLostAndFound3Init(p);
16106       }
16107       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
16108         p->eState = RECOVER_STATE_SCHEMA2;
16109       }
16110       break;
16111     }
16112 
16113     case RECOVER_STATE_SCHEMA2: {
16114       int rc = SQLITE_OK;
16115 
16116       recoverWriteSchema2(p);
16117       p->eState = RECOVER_STATE_DONE;
16118 
16119       /* If no error has occurred, commit the write transaction on the output
16120       ** database. Regardless of whether or not an error has occurred, make
16121       ** an attempt to end the read transaction on the input database.  */
16122       recoverExec(p, p->dbOut, "COMMIT");
16123       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
16124       if( p->errCode==SQLITE_OK ) p->errCode = rc;
16125 
16126       recoverSqlCallback(p, "PRAGMA writable_schema = off");
16127       recoverSqlCallback(p, "COMMIT");
16128       p->eState = RECOVER_STATE_DONE;
16129       recoverFinalCleanup(p);
16130       break;
16131     };
16132 
16133     case RECOVER_STATE_DONE: {
16134       /* no-op */
16135       break;
16136     };
16137   }
16138 }
16139 
16140 
16141 /*
16142 ** This is a worker function that does the heavy lifting for both init
16143 ** functions:
16144 **
16145 **     sqlite3_recover_init()
16146 **     sqlite3_recover_init_sql()
16147 **
16148 ** All this function does is allocate space for the recover handle and
16149 ** take copies of the input parameters. All the real work is done within
16150 ** sqlite3_recover_run().
16151 */
16152 sqlite3_recover *recoverInit(
16153   sqlite3* db,
16154   const char *zDb,
16155   const char *zUri,               /* Output URI for _recover_init() */
16156   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
16157   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
16158 ){
16159   sqlite3_recover *pRet = 0;
16160   int nDb = 0;
16161   int nUri = 0;
16162   int nByte = 0;
16163 
16164   if( zDb==0 ){ zDb = "main"; }
16165 
16166   nDb = recoverStrlen(zDb);
16167   nUri = recoverStrlen(zUri);
16168 
16169   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
16170   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
16171   if( pRet ){
16172     memset(pRet, 0, nByte);
16173     pRet->dbIn = db;
16174     pRet->zDb = (char*)&pRet[1];
16175     pRet->zUri = &pRet->zDb[nDb+1];
16176     memcpy(pRet->zDb, zDb, nDb);
16177     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
16178     pRet->xSql = xSql;
16179     pRet->pSqlCtx = pSqlCtx;
16180     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
16181   }
16182 
16183   return pRet;
16184 }
16185 
16186 /*
16187 ** Initialize a recovery handle that creates a new database containing
16188 ** the recovered data.
16189 */
16190 sqlite3_recover *sqlite3_recover_init(
16191   sqlite3* db,
16192   const char *zDb,
16193   const char *zUri
16194 ){
16195   return recoverInit(db, zDb, zUri, 0, 0);
16196 }
16197 
16198 /*
16199 ** Initialize a recovery handle that returns recovered data in the
16200 ** form of SQL statements via a callback.
16201 */
16202 sqlite3_recover *sqlite3_recover_init_sql(
16203   sqlite3* db,
16204   const char *zDb,
16205   int (*xSql)(void*, const char*),
16206   void *pSqlCtx
16207 ){
16208   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
16209 }
16210 
16211 /*
16212 ** Return the handle error message, if any.
16213 */
16214 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
16215   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
16216 }
16217 
16218 /*
16219 ** Return the handle error code.
16220 */
16221 int sqlite3_recover_errcode(sqlite3_recover *p){
16222   return p ? p->errCode : SQLITE_NOMEM;
16223 }
16224 
16225 /*
16226 ** Configure the handle.
16227 */
16228 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
16229   int rc = SQLITE_OK;
16230   if( p==0 ){
16231     rc = SQLITE_NOMEM;
16232   }else if( p->eState!=RECOVER_STATE_INIT ){
16233     rc = SQLITE_MISUSE;
16234   }else{
16235     switch( op ){
16236       case 789:
16237         /* This undocumented magic configuration option is used to set the
16238         ** name of the auxiliary database that is ATTACH-ed to the database
16239         ** connection and used to hold state information during the
16240         ** recovery process.  This option is for debugging use only and
16241         ** is subject to change or removal at any time. */
16242         sqlite3_free(p->zStateDb);
16243         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
16244         break;
16245 
16246       case SQLITE_RECOVER_LOST_AND_FOUND: {
16247         const char *zArg = (const char*)pArg;
16248         sqlite3_free(p->zLostAndFound);
16249         if( zArg ){
16250           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
16251         }else{
16252           p->zLostAndFound = 0;
16253         }
16254         break;
16255       }
16256 
16257       case SQLITE_RECOVER_FREELIST_CORRUPT:
16258         p->bFreelistCorrupt = *(int*)pArg;
16259         break;
16260 
16261       case SQLITE_RECOVER_ROWIDS:
16262         p->bRecoverRowid = *(int*)pArg;
16263         break;
16264 
16265       case SQLITE_RECOVER_SLOWINDEXES:
16266         p->bSlowIndexes = *(int*)pArg;
16267         break;
16268 
16269       default:
16270         rc = SQLITE_NOTFOUND;
16271         break;
16272     }
16273   }
16274 
16275   return rc;
16276 }
16277 
16278 /*
16279 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
16280 ** no error has occurred but database recovery is not finished, SQLITE_DONE
16281 ** if database recovery has been successfully completed, or an SQLite
16282 ** error code if an error has occurred.
16283 */
16284 int sqlite3_recover_step(sqlite3_recover *p){
16285   if( p==0 ) return SQLITE_NOMEM;
16286   if( p->errCode==SQLITE_OK ) recoverStep(p);
16287   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
16288     return SQLITE_DONE;
16289   }
16290   return p->errCode;
16291 }
16292 
16293 /*
16294 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
16295 ** else an SQLite error code.
16296 */
16297 int sqlite3_recover_run(sqlite3_recover *p){
16298   while( SQLITE_OK==sqlite3_recover_step(p) );
16299   return sqlite3_recover_errcode(p);
16300 }
16301 
16302 
16303 /*
16304 ** Free all resources associated with the recover handle passed as the only
16305 ** argument. The results of using a handle with any sqlite3_recover_**
16306 ** API function after it has been passed to this function are undefined.
16307 **
16308 ** A copy of the value returned by the first call made to sqlite3_recover_run()
16309 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
16310 ** not been called on this handle.
16311 */
16312 int sqlite3_recover_finish(sqlite3_recover *p){
16313   int rc;
16314   if( p==0 ){
16315     rc = SQLITE_NOMEM;
16316   }else{
16317     recoverFinalCleanup(p);
16318     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
16319       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
16320       if( p->errCode==SQLITE_OK ) p->errCode = rc;
16321     }
16322     rc = p->errCode;
16323     sqlite3_free(p->zErrMsg);
16324     sqlite3_free(p->zStateDb);
16325     sqlite3_free(p->zLostAndFound);
16326     sqlite3_free(p->pPage1Cache);
16327     sqlite3_free(p);
16328   }
16329   return rc;
16330 }
16331 
16332 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
16333 
16334 /************************* End ../ext/recover/sqlite3recover.c ********************/
16335 # endif
16336 #endif
16337 #ifdef SQLITE_SHELL_EXTSRC
16338 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
16339 #endif
16340 
16341 #if defined(SQLITE_ENABLE_SESSION)
16342 /*
16343 ** State information for a single open session
16344 */
16345 typedef struct OpenSession OpenSession;
16346 struct OpenSession {
16347   char *zName;             /* Symbolic name for this session */
16348   int nFilter;             /* Number of xFilter rejection GLOB patterns */
16349   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
16350   sqlite3_session *p;      /* The open session */
16351 };
16352 #endif
16353 
16354 typedef struct ExpertInfo ExpertInfo;
16355 struct ExpertInfo {
16356   sqlite3expert *pExpert;
16357   int bVerbose;
16358 };
16359 
16360 /* A single line in the EQP output */
16361 typedef struct EQPGraphRow EQPGraphRow;
16362 struct EQPGraphRow {
16363   int iEqpId;           /* ID for this row */
16364   int iParentId;        /* ID of the parent row */
16365   EQPGraphRow *pNext;   /* Next row in sequence */
16366   char zText[1];        /* Text to display for this row */
16367 };
16368 
16369 /* All EQP output is collected into an instance of the following */
16370 typedef struct EQPGraph EQPGraph;
16371 struct EQPGraph {
16372   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
16373   EQPGraphRow *pLast;   /* Last element of the pRow list */
16374   char zPrefix[100];    /* Graph prefix */
16375 };
16376 
16377 /* Parameters affecting columnar mode result display (defaulting together) */
16378 typedef struct ColModeOpts {
16379   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
16380   u8 bQuote;            /* Quote results for .mode box and table */
16381   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
16382 } ColModeOpts;
16383 #define ColModeOpts_default { 60, 0, 0 }
16384 #define ColModeOpts_default_qbox { 60, 1, 0 }
16385 
16386 /*
16387 ** State information about the database connection is contained in an
16388 ** instance of the following structure.
16389 */
16390 typedef struct ShellState ShellState;
16391 struct ShellState {
16392   sqlite3 *db;           /* The database */
16393   u8 autoExplain;        /* Automatically turn on .explain mode */
16394   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
16395   u8 autoEQPtest;        /* autoEQP is in test mode */
16396   u8 autoEQPtrace;       /* autoEQP is in trace mode */
16397   u8 scanstatsOn;        /* True to display scan stats before each finalize */
16398   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
16399   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
16400   u8 nEqpLevel;          /* Depth of the EQP output graph */
16401   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
16402   u8 bSafeMode;          /* True to prohibit unsafe operations */
16403   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
16404   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
16405   unsigned statsOn;      /* True to display memory stats before each finalize */
16406   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
16407   int inputNesting;      /* Track nesting level of .read and other redirects */
16408   int outCount;          /* Revert to stdout when reaching zero */
16409   int cnt;               /* Number of records displayed so far */
16410   int lineno;            /* Line number of last line read from in */
16411   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
16412   FILE *in;              /* Read commands from this stream */
16413   FILE *out;             /* Write results here */
16414   FILE *traceOut;        /* Output for sqlite3_trace() */
16415   int nErr;              /* Number of errors seen */
16416   int mode;              /* An output mode setting */
16417   int modePrior;         /* Saved mode */
16418   int cMode;             /* temporary output mode for the current query */
16419   int normalMode;        /* Output mode before ".explain on" */
16420   int writableSchema;    /* True if PRAGMA writable_schema=ON */
16421   int showHeader;        /* True to show column names in List or Column mode */
16422   int nCheck;            /* Number of ".check" commands run */
16423   unsigned nProgress;    /* Number of progress callbacks encountered */
16424   unsigned mxProgress;   /* Maximum progress callbacks before failing */
16425   unsigned flgProgress;  /* Flags for the progress callback */
16426   unsigned shellFlgs;    /* Various flags */
16427   unsigned priorShFlgs;  /* Saved copy of flags */
16428   sqlite3_int64 szMax;   /* --maxsize argument to .open */
16429   char *zDestTable;      /* Name of destination table when MODE_Insert */
16430   char *zTempFile;       /* Temporary file that might need deleting */
16431   char zTestcase[30];    /* Name of current test case */
16432   char colSeparator[20]; /* Column separator character for several modes */
16433   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
16434   char colSepPrior[20];  /* Saved column separator */
16435   char rowSepPrior[20];  /* Saved row separator */
16436   int *colWidth;         /* Requested width of each column in columnar modes */
16437   int *actualWidth;      /* Actual width of each column */
16438   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
16439   char nullValue[20];    /* The text to print when a NULL comes back from
16440                          ** the database */
16441   char outfile[FILENAME_MAX]; /* Filename for *out */
16442   sqlite3_stmt *pStmt;   /* Current statement if any. */
16443   FILE *pLog;            /* Write log output here */
16444   struct AuxDb {         /* Storage space for auxiliary database connections */
16445     sqlite3 *db;               /* Connection pointer */
16446     const char *zDbFilename;   /* Filename used to open the connection */
16447     char *zFreeOnClose;        /* Free this memory allocation on close */
16448 #if defined(SQLITE_ENABLE_SESSION)
16449     int nSession;              /* Number of active sessions */
16450     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
16451 #endif
16452   } aAuxDb[5],           /* Array of all database connections */
16453     *pAuxDb;             /* Currently active database connection */
16454   int *aiIndent;         /* Array of indents used in MODE_Explain */
16455   int nIndent;           /* Size of array aiIndent[] */
16456   int iIndent;           /* Index of current op in aiIndent[] */
16457   char *zNonce;          /* Nonce for temporary safe-mode excapes */
16458   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
16459   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
16460 #ifdef SQLITE_SHELL_FIDDLE
16461   struct {
16462     const char * zInput; /* Input string from wasm/JS proxy */
16463     const char * zPos;   /* Cursor pos into zInput */
16464     const char * zDefaultDbName; /* Default name for db file */
16465   } wasm;
16466 #endif
16467 };
16468 
16469 #ifdef SQLITE_SHELL_FIDDLE
16470 static ShellState shellState;
16471 #endif
16472 
16473 
16474 /* Allowed values for ShellState.autoEQP
16475 */
16476 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
16477 #define AUTOEQP_on       1           /* Automatic EQP is on */
16478 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
16479 #define AUTOEQP_full     3           /* Show full EXPLAIN */
16480 
16481 /* Allowed values for ShellState.openMode
16482 */
16483 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
16484 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
16485 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
16486 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
16487 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
16488 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
16489 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
16490 
16491 /* Allowed values for ShellState.eTraceType
16492 */
16493 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
16494 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
16495 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
16496 
16497 /* Bits in the ShellState.flgProgress variable */
16498 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
16499 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
16500                                    ** callback limit is reached, and for each
16501                                    ** top-level SQL statement */
16502 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
16503 
16504 /*
16505 ** These are the allowed shellFlgs values
16506 */
16507 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
16508 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
16509 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
16510 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
16511 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
16512 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
16513 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
16514 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
16515 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
16516 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
16517 
16518 /*
16519 ** Macros for testing and setting shellFlgs
16520 */
16521 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
16522 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
16523 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
16524 
16525 /*
16526 ** These are the allowed modes.
16527 */
16528 #define MODE_Line     0  /* One column per line.  Blank line between records */
16529 #define MODE_Column   1  /* One record per line in neat columns */
16530 #define MODE_List     2  /* One record per line with a separator */
16531 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
16532 #define MODE_Html     4  /* Generate an XHTML table */
16533 #define MODE_Insert   5  /* Generate SQL "insert" statements */
16534 #define MODE_Quote    6  /* Quote values as for SQL */
16535 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
16536 #define MODE_Csv      8  /* Quote strings, numbers are plain */
16537 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
16538 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
16539 #define MODE_Pretty  11  /* Pretty-print schemas */
16540 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
16541 #define MODE_Json    13  /* Output JSON */
16542 #define MODE_Markdown 14 /* Markdown formatting */
16543 #define MODE_Table   15  /* MySQL-style table formatting */
16544 #define MODE_Box     16  /* Unicode box-drawing characters */
16545 #define MODE_Count   17  /* Output only a count of the rows of output */
16546 #define MODE_Off     18  /* No query output shown */
16547 
16548 static const char *modeDescr[] = {
16549   "line",
16550   "column",
16551   "list",
16552   "semi",
16553   "html",
16554   "insert",
16555   "quote",
16556   "tcl",
16557   "csv",
16558   "explain",
16559   "ascii",
16560   "prettyprint",
16561   "eqp",
16562   "json",
16563   "markdown",
16564   "table",
16565   "box",
16566   "count",
16567   "off"
16568 };
16569 
16570 /*
16571 ** These are the column/row/line separators used by the various
16572 ** import/export modes.
16573 */
16574 #define SEP_Column    "|"
16575 #define SEP_Row       "\n"
16576 #define SEP_Tab       "\t"
16577 #define SEP_Space     " "
16578 #define SEP_Comma     ","
16579 #define SEP_CrLf      "\r\n"
16580 #define SEP_Unit      "\x1F"
16581 #define SEP_Record    "\x1E"
16582 
16583 /*
16584 ** Limit input nesting via .read or any other input redirect.
16585 ** It's not too expensive, so a generous allowance can be made.
16586 */
16587 #define MAX_INPUT_NESTING 25
16588 
16589 /*
16590 ** A callback for the sqlite3_log() interface.
16591 */
16592 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
16593   ShellState *p = (ShellState*)pArg;
16594   if( p->pLog==0 ) return;
16595   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
16596   fflush(p->pLog);
16597 }
16598 
16599 /*
16600 ** SQL function:  shell_putsnl(X)
16601 **
16602 ** Write the text X to the screen (or whatever output is being directed)
16603 ** adding a newline at the end, and then return X.
16604 */
16605 static void shellPutsFunc(
16606   sqlite3_context *pCtx,
16607   int nVal,
16608   sqlite3_value **apVal
16609 ){
16610   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
16611   (void)nVal;
16612   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
16613   sqlite3_result_value(pCtx, apVal[0]);
16614 }
16615 
16616 /*
16617 ** If in safe mode, print an error message described by the arguments
16618 ** and exit immediately.
16619 */
16620 static void failIfSafeMode(
16621   ShellState *p,
16622   const char *zErrMsg,
16623   ...
16624 ){
16625   if( p->bSafeMode ){
16626     va_list ap;
16627     char *zMsg;
16628     va_start(ap, zErrMsg);
16629     zMsg = sqlite3_vmprintf(zErrMsg, ap);
16630     va_end(ap);
16631     raw_printf(stderr, "line %d: ", p->lineno);
16632     utf8_printf(stderr, "%s\n", zMsg);
16633     exit(1);
16634   }
16635 }
16636 
16637 /*
16638 ** SQL function:   edit(VALUE)
16639 **                 edit(VALUE,EDITOR)
16640 **
16641 ** These steps:
16642 **
16643 **     (1) Write VALUE into a temporary file.
16644 **     (2) Run program EDITOR on that temporary file.
16645 **     (3) Read the temporary file back and return its content as the result.
16646 **     (4) Delete the temporary file
16647 **
16648 ** If the EDITOR argument is omitted, use the value in the VISUAL
16649 ** environment variable.  If still there is no EDITOR, through an error.
16650 **
16651 ** Also throw an error if the EDITOR program returns a non-zero exit code.
16652 */
16653 #ifndef SQLITE_NOHAVE_SYSTEM
16654 static void editFunc(
16655   sqlite3_context *context,
16656   int argc,
16657   sqlite3_value **argv
16658 ){
16659   const char *zEditor;
16660   char *zTempFile = 0;
16661   sqlite3 *db;
16662   char *zCmd = 0;
16663   int bBin;
16664   int rc;
16665   int hasCRNL = 0;
16666   FILE *f = 0;
16667   sqlite3_int64 sz;
16668   sqlite3_int64 x;
16669   unsigned char *p = 0;
16670 
16671   if( argc==2 ){
16672     zEditor = (const char*)sqlite3_value_text(argv[1]);
16673   }else{
16674     zEditor = getenv("VISUAL");
16675   }
16676   if( zEditor==0 ){
16677     sqlite3_result_error(context, "no editor for edit()", -1);
16678     return;
16679   }
16680   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
16681     sqlite3_result_error(context, "NULL input to edit()", -1);
16682     return;
16683   }
16684   db = sqlite3_context_db_handle(context);
16685   zTempFile = 0;
16686   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
16687   if( zTempFile==0 ){
16688     sqlite3_uint64 r = 0;
16689     sqlite3_randomness(sizeof(r), &r);
16690     zTempFile = sqlite3_mprintf("temp%llx", r);
16691     if( zTempFile==0 ){
16692       sqlite3_result_error_nomem(context);
16693       return;
16694     }
16695   }
16696   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
16697   /* When writing the file to be edited, do \n to \r\n conversions on systems
16698   ** that want \r\n line endings */
16699   f = fopen(zTempFile, bBin ? "wb" : "w");
16700   if( f==0 ){
16701     sqlite3_result_error(context, "edit() cannot open temp file", -1);
16702     goto edit_func_end;
16703   }
16704   sz = sqlite3_value_bytes(argv[0]);
16705   if( bBin ){
16706     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
16707   }else{
16708     const char *z = (const char*)sqlite3_value_text(argv[0]);
16709     /* Remember whether or not the value originally contained \r\n */
16710     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
16711     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
16712   }
16713   fclose(f);
16714   f = 0;
16715   if( x!=sz ){
16716     sqlite3_result_error(context, "edit() could not write the whole file", -1);
16717     goto edit_func_end;
16718   }
16719   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
16720   if( zCmd==0 ){
16721     sqlite3_result_error_nomem(context);
16722     goto edit_func_end;
16723   }
16724   rc = system(zCmd);
16725   sqlite3_free(zCmd);
16726   if( rc ){
16727     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
16728     goto edit_func_end;
16729   }
16730   f = fopen(zTempFile, "rb");
16731   if( f==0 ){
16732     sqlite3_result_error(context,
16733       "edit() cannot reopen temp file after edit", -1);
16734     goto edit_func_end;
16735   }
16736   fseek(f, 0, SEEK_END);
16737   sz = ftell(f);
16738   rewind(f);
16739   p = sqlite3_malloc64( sz+1 );
16740   if( p==0 ){
16741     sqlite3_result_error_nomem(context);
16742     goto edit_func_end;
16743   }
16744   x = fread(p, 1, (size_t)sz, f);
16745   fclose(f);
16746   f = 0;
16747   if( x!=sz ){
16748     sqlite3_result_error(context, "could not read back the whole file", -1);
16749     goto edit_func_end;
16750   }
16751   if( bBin ){
16752     sqlite3_result_blob64(context, p, sz, sqlite3_free);
16753   }else{
16754     sqlite3_int64 i, j;
16755     if( hasCRNL ){
16756       /* If the original contains \r\n then do no conversions back to \n */
16757     }else{
16758       /* If the file did not originally contain \r\n then convert any new
16759       ** \r\n back into \n */
16760       for(i=j=0; i<sz; i++){
16761         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
16762         p[j++] = p[i];
16763       }
16764       sz = j;
16765       p[sz] = 0;
16766     }
16767     sqlite3_result_text64(context, (const char*)p, sz,
16768                           sqlite3_free, SQLITE_UTF8);
16769   }
16770   p = 0;
16771 
16772 edit_func_end:
16773   if( f ) fclose(f);
16774   unlink(zTempFile);
16775   sqlite3_free(zTempFile);
16776   sqlite3_free(p);
16777 }
16778 #endif /* SQLITE_NOHAVE_SYSTEM */
16779 
16780 /*
16781 ** Save or restore the current output mode
16782 */
16783 static void outputModePush(ShellState *p){
16784   p->modePrior = p->mode;
16785   p->priorShFlgs = p->shellFlgs;
16786   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
16787   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
16788 }
16789 static void outputModePop(ShellState *p){
16790   p->mode = p->modePrior;
16791   p->shellFlgs = p->priorShFlgs;
16792   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
16793   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
16794 }
16795 
16796 /*
16797 ** Output the given string as a hex-encoded blob (eg. X'1234' )
16798 */
16799 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
16800   int i;
16801   unsigned char *aBlob = (unsigned char*)pBlob;
16802 
16803   char *zStr = sqlite3_malloc(nBlob*2 + 1);
16804   shell_check_oom(zStr);
16805 
16806   for(i=0; i<nBlob; i++){
16807     static const char aHex[] = {
16808         '0', '1', '2', '3', '4', '5', '6', '7',
16809         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
16810     };
16811     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
16812     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
16813   }
16814   zStr[i*2] = '\0';
16815 
16816   raw_printf(out,"X'%s'", zStr);
16817   sqlite3_free(zStr);
16818 }
16819 
16820 /*
16821 ** Find a string that is not found anywhere in z[].  Return a pointer
16822 ** to that string.
16823 **
16824 ** Try to use zA and zB first.  If both of those are already found in z[]
16825 ** then make up some string and store it in the buffer zBuf.
16826 */
16827 static const char *unused_string(
16828   const char *z,                    /* Result must not appear anywhere in z */
16829   const char *zA, const char *zB,   /* Try these first */
16830   char *zBuf                        /* Space to store a generated string */
16831 ){
16832   unsigned i = 0;
16833   if( strstr(z, zA)==0 ) return zA;
16834   if( strstr(z, zB)==0 ) return zB;
16835   do{
16836     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
16837   }while( strstr(z,zBuf)!=0 );
16838   return zBuf;
16839 }
16840 
16841 /*
16842 ** Output the given string as a quoted string using SQL quoting conventions.
16843 **
16844 ** See also: output_quoted_escaped_string()
16845 */
16846 static void output_quoted_string(FILE *out, const char *z){
16847   int i;
16848   char c;
16849   setBinaryMode(out, 1);
16850   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
16851   if( c==0 ){
16852     utf8_printf(out,"'%s'",z);
16853   }else{
16854     raw_printf(out, "'");
16855     while( *z ){
16856       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
16857       if( c=='\'' ) i++;
16858       if( i ){
16859         utf8_printf(out, "%.*s", i, z);
16860         z += i;
16861       }
16862       if( c=='\'' ){
16863         raw_printf(out, "'");
16864         continue;
16865       }
16866       if( c==0 ){
16867         break;
16868       }
16869       z++;
16870     }
16871     raw_printf(out, "'");
16872   }
16873   setTextMode(out, 1);
16874 }
16875 
16876 /*
16877 ** Output the given string as a quoted string using SQL quoting conventions.
16878 ** Additionallly , escape the "\n" and "\r" characters so that they do not
16879 ** get corrupted by end-of-line translation facilities in some operating
16880 ** systems.
16881 **
16882 ** This is like output_quoted_string() but with the addition of the \r\n
16883 ** escape mechanism.
16884 */
16885 static void output_quoted_escaped_string(FILE *out, const char *z){
16886   int i;
16887   char c;
16888   setBinaryMode(out, 1);
16889   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
16890   if( c==0 ){
16891     utf8_printf(out,"'%s'",z);
16892   }else{
16893     const char *zNL = 0;
16894     const char *zCR = 0;
16895     int nNL = 0;
16896     int nCR = 0;
16897     char zBuf1[20], zBuf2[20];
16898     for(i=0; z[i]; i++){
16899       if( z[i]=='\n' ) nNL++;
16900       if( z[i]=='\r' ) nCR++;
16901     }
16902     if( nNL ){
16903       raw_printf(out, "replace(");
16904       zNL = unused_string(z, "\\n", "\\012", zBuf1);
16905     }
16906     if( nCR ){
16907       raw_printf(out, "replace(");
16908       zCR = unused_string(z, "\\r", "\\015", zBuf2);
16909     }
16910     raw_printf(out, "'");
16911     while( *z ){
16912       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
16913       if( c=='\'' ) i++;
16914       if( i ){
16915         utf8_printf(out, "%.*s", i, z);
16916         z += i;
16917       }
16918       if( c=='\'' ){
16919         raw_printf(out, "'");
16920         continue;
16921       }
16922       if( c==0 ){
16923         break;
16924       }
16925       z++;
16926       if( c=='\n' ){
16927         raw_printf(out, "%s", zNL);
16928         continue;
16929       }
16930       raw_printf(out, "%s", zCR);
16931     }
16932     raw_printf(out, "'");
16933     if( nCR ){
16934       raw_printf(out, ",'%s',char(13))", zCR);
16935     }
16936     if( nNL ){
16937       raw_printf(out, ",'%s',char(10))", zNL);
16938     }
16939   }
16940   setTextMode(out, 1);
16941 }
16942 
16943 /*
16944 ** Output the given string as a quoted according to C or TCL quoting rules.
16945 */
16946 static void output_c_string(FILE *out, const char *z){
16947   unsigned int c;
16948   fputc('"', out);
16949   while( (c = *(z++))!=0 ){
16950     if( c=='\\' ){
16951       fputc(c, out);
16952       fputc(c, out);
16953     }else if( c=='"' ){
16954       fputc('\\', out);
16955       fputc('"', out);
16956     }else if( c=='\t' ){
16957       fputc('\\', out);
16958       fputc('t', out);
16959     }else if( c=='\n' ){
16960       fputc('\\', out);
16961       fputc('n', out);
16962     }else if( c=='\r' ){
16963       fputc('\\', out);
16964       fputc('r', out);
16965     }else if( !isprint(c&0xff) ){
16966       raw_printf(out, "\\%03o", c&0xff);
16967     }else{
16968       fputc(c, out);
16969     }
16970   }
16971   fputc('"', out);
16972 }
16973 
16974 /*
16975 ** Output the given string as a quoted according to JSON quoting rules.
16976 */
16977 static void output_json_string(FILE *out, const char *z, i64 n){
16978   unsigned int c;
16979   if( n<0 ) n = strlen(z);
16980   fputc('"', out);
16981   while( n-- ){
16982     c = *(z++);
16983     if( c=='\\' || c=='"' ){
16984       fputc('\\', out);
16985       fputc(c, out);
16986     }else if( c<=0x1f ){
16987       fputc('\\', out);
16988       if( c=='\b' ){
16989         fputc('b', out);
16990       }else if( c=='\f' ){
16991         fputc('f', out);
16992       }else if( c=='\n' ){
16993         fputc('n', out);
16994       }else if( c=='\r' ){
16995         fputc('r', out);
16996       }else if( c=='\t' ){
16997         fputc('t', out);
16998       }else{
16999          raw_printf(out, "u%04x",c);
17000       }
17001     }else{
17002       fputc(c, out);
17003     }
17004   }
17005   fputc('"', out);
17006 }
17007 
17008 /*
17009 ** Output the given string with characters that are special to
17010 ** HTML escaped.
17011 */
17012 static void output_html_string(FILE *out, const char *z){
17013   int i;
17014   if( z==0 ) z = "";
17015   while( *z ){
17016     for(i=0;   z[i]
17017             && z[i]!='<'
17018             && z[i]!='&'
17019             && z[i]!='>'
17020             && z[i]!='\"'
17021             && z[i]!='\'';
17022         i++){}
17023     if( i>0 ){
17024       utf8_printf(out,"%.*s",i,z);
17025     }
17026     if( z[i]=='<' ){
17027       raw_printf(out,"&lt;");
17028     }else if( z[i]=='&' ){
17029       raw_printf(out,"&amp;");
17030     }else if( z[i]=='>' ){
17031       raw_printf(out,"&gt;");
17032     }else if( z[i]=='\"' ){
17033       raw_printf(out,"&quot;");
17034     }else if( z[i]=='\'' ){
17035       raw_printf(out,"&#39;");
17036     }else{
17037       break;
17038     }
17039     z += i + 1;
17040   }
17041 }
17042 
17043 /*
17044 ** If a field contains any character identified by a 1 in the following
17045 ** array, then the string must be quoted for CSV.
17046 */
17047 static const char needCsvQuote[] = {
17048   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17049   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17050   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
17051   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17052   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17053   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17054   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17055   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
17056   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17057   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17058   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17059   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17060   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17061   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17062   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17063   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17064 };
17065 
17066 /*
17067 ** Output a single term of CSV.  Actually, p->colSeparator is used for
17068 ** the separator, which may or may not be a comma.  p->nullValue is
17069 ** the null value.  Strings are quoted if necessary.  The separator
17070 ** is only issued if bSep is true.
17071 */
17072 static void output_csv(ShellState *p, const char *z, int bSep){
17073   FILE *out = p->out;
17074   if( z==0 ){
17075     utf8_printf(out,"%s",p->nullValue);
17076   }else{
17077     unsigned i;
17078     for(i=0; z[i]; i++){
17079       if( needCsvQuote[((unsigned char*)z)[i]] ){
17080         i = 0;
17081         break;
17082       }
17083     }
17084     if( i==0 || strstr(z, p->colSeparator)!=0 ){
17085       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
17086       shell_check_oom(zQuoted);
17087       utf8_printf(out, "%s", zQuoted);
17088       sqlite3_free(zQuoted);
17089     }else{
17090       utf8_printf(out, "%s", z);
17091     }
17092   }
17093   if( bSep ){
17094     utf8_printf(p->out, "%s", p->colSeparator);
17095   }
17096 }
17097 
17098 /*
17099 ** This routine runs when the user presses Ctrl-C
17100 */
17101 static void interrupt_handler(int NotUsed){
17102   UNUSED_PARAMETER(NotUsed);
17103   seenInterrupt++;
17104   if( seenInterrupt>2 ) exit(1);
17105   if( globalDb ) sqlite3_interrupt(globalDb);
17106 }
17107 
17108 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
17109 /*
17110 ** This routine runs for console events (e.g. Ctrl-C) on Win32
17111 */
17112 static BOOL WINAPI ConsoleCtrlHandler(
17113   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
17114 ){
17115   if( dwCtrlType==CTRL_C_EVENT ){
17116     interrupt_handler(0);
17117     return TRUE;
17118   }
17119   return FALSE;
17120 }
17121 #endif
17122 
17123 #ifndef SQLITE_OMIT_AUTHORIZATION
17124 /*
17125 ** This authorizer runs in safe mode.
17126 */
17127 static int safeModeAuth(
17128   void *pClientData,
17129   int op,
17130   const char *zA1,
17131   const char *zA2,
17132   const char *zA3,
17133   const char *zA4
17134 ){
17135   ShellState *p = (ShellState*)pClientData;
17136   static const char *azProhibitedFunctions[] = {
17137     "edit",
17138     "fts3_tokenizer",
17139     "load_extension",
17140     "readfile",
17141     "writefile",
17142     "zipfile",
17143     "zipfile_cds",
17144   };
17145   UNUSED_PARAMETER(zA1);
17146   UNUSED_PARAMETER(zA3);
17147   UNUSED_PARAMETER(zA4);
17148   switch( op ){
17149     case SQLITE_ATTACH: {
17150 #ifndef SQLITE_SHELL_FIDDLE
17151       /* In WASM builds the filesystem is a virtual sandbox, so
17152       ** there's no harm in using ATTACH. */
17153       failIfSafeMode(p, "cannot run ATTACH in safe mode");
17154 #endif
17155       break;
17156     }
17157     case SQLITE_FUNCTION: {
17158       int i;
17159       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
17160         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
17161           failIfSafeMode(p, "cannot use the %s() function in safe mode",
17162                          azProhibitedFunctions[i]);
17163         }
17164       }
17165       break;
17166     }
17167   }
17168   return SQLITE_OK;
17169 }
17170 
17171 /*
17172 ** When the ".auth ON" is set, the following authorizer callback is
17173 ** invoked.  It always returns SQLITE_OK.
17174 */
17175 static int shellAuth(
17176   void *pClientData,
17177   int op,
17178   const char *zA1,
17179   const char *zA2,
17180   const char *zA3,
17181   const char *zA4
17182 ){
17183   ShellState *p = (ShellState*)pClientData;
17184   static const char *azAction[] = { 0,
17185      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
17186      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
17187      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
17188      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
17189      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
17190      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
17191      "PRAGMA",               "READ",                 "SELECT",
17192      "TRANSACTION",          "UPDATE",               "ATTACH",
17193      "DETACH",               "ALTER_TABLE",          "REINDEX",
17194      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
17195      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
17196   };
17197   int i;
17198   const char *az[4];
17199   az[0] = zA1;
17200   az[1] = zA2;
17201   az[2] = zA3;
17202   az[3] = zA4;
17203   utf8_printf(p->out, "authorizer: %s", azAction[op]);
17204   for(i=0; i<4; i++){
17205     raw_printf(p->out, " ");
17206     if( az[i] ){
17207       output_c_string(p->out, az[i]);
17208     }else{
17209       raw_printf(p->out, "NULL");
17210     }
17211   }
17212   raw_printf(p->out, "\n");
17213   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
17214   return SQLITE_OK;
17215 }
17216 #endif
17217 
17218 /*
17219 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
17220 **
17221 ** This routine converts some CREATE TABLE statements for shadow tables
17222 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
17223 **
17224 ** If the schema statement in z[] contains a start-of-comment and if
17225 ** sqlite3_complete() returns false, try to terminate the comment before
17226 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
17227 */
17228 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
17229   char *zToFree = 0;
17230   if( z==0 ) return;
17231   if( zTail==0 ) return;
17232   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
17233     const char *zOrig = z;
17234     static const char *azTerm[] = { "", "*/", "\n" };
17235     int i;
17236     for(i=0; i<ArraySize(azTerm); i++){
17237       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
17238       if( sqlite3_complete(zNew) ){
17239         size_t n = strlen(zNew);
17240         zNew[n-1] = 0;
17241         zToFree = zNew;
17242         z = zNew;
17243         break;
17244       }
17245       sqlite3_free(zNew);
17246     }
17247   }
17248   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
17249     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
17250   }else{
17251     utf8_printf(out, "%s%s", z, zTail);
17252   }
17253   sqlite3_free(zToFree);
17254 }
17255 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
17256   char c = z[n];
17257   z[n] = 0;
17258   printSchemaLine(out, z, zTail);
17259   z[n] = c;
17260 }
17261 
17262 /*
17263 ** Return true if string z[] has nothing but whitespace and comments to the
17264 ** end of the first line.
17265 */
17266 static int wsToEol(const char *z){
17267   int i;
17268   for(i=0; z[i]; i++){
17269     if( z[i]=='\n' ) return 1;
17270     if( IsSpace(z[i]) ) continue;
17271     if( z[i]=='-' && z[i+1]=='-' ) return 1;
17272     return 0;
17273   }
17274   return 1;
17275 }
17276 
17277 /*
17278 ** Add a new entry to the EXPLAIN QUERY PLAN data
17279 */
17280 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
17281   EQPGraphRow *pNew;
17282   i64 nText;
17283   if( zText==0 ) return;
17284   nText = strlen(zText);
17285   if( p->autoEQPtest ){
17286     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
17287   }
17288   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
17289   shell_check_oom(pNew);
17290   pNew->iEqpId = iEqpId;
17291   pNew->iParentId = p2;
17292   memcpy(pNew->zText, zText, nText+1);
17293   pNew->pNext = 0;
17294   if( p->sGraph.pLast ){
17295     p->sGraph.pLast->pNext = pNew;
17296   }else{
17297     p->sGraph.pRow = pNew;
17298   }
17299   p->sGraph.pLast = pNew;
17300 }
17301 
17302 /*
17303 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
17304 ** in p->sGraph.
17305 */
17306 static void eqp_reset(ShellState *p){
17307   EQPGraphRow *pRow, *pNext;
17308   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
17309     pNext = pRow->pNext;
17310     sqlite3_free(pRow);
17311   }
17312   memset(&p->sGraph, 0, sizeof(p->sGraph));
17313 }
17314 
17315 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
17316 ** pOld, or return the first such line if pOld is NULL
17317 */
17318 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
17319   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
17320   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
17321   return pRow;
17322 }
17323 
17324 /* Render a single level of the graph that has iEqpId as its parent.  Called
17325 ** recursively to render sublevels.
17326 */
17327 static void eqp_render_level(ShellState *p, int iEqpId){
17328   EQPGraphRow *pRow, *pNext;
17329   i64 n = strlen(p->sGraph.zPrefix);
17330   char *z;
17331   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
17332     pNext = eqp_next_row(p, iEqpId, pRow);
17333     z = pRow->zText;
17334     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
17335                 pNext ? "|--" : "`--", z);
17336     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
17337       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
17338       eqp_render_level(p, pRow->iEqpId);
17339       p->sGraph.zPrefix[n] = 0;
17340     }
17341   }
17342 }
17343 
17344 /*
17345 ** Display and reset the EXPLAIN QUERY PLAN data
17346 */
17347 static void eqp_render(ShellState *p, i64 nCycle){
17348   EQPGraphRow *pRow = p->sGraph.pRow;
17349   if( pRow ){
17350     if( pRow->zText[0]=='-' ){
17351       if( pRow->pNext==0 ){
17352         eqp_reset(p);
17353         return;
17354       }
17355       utf8_printf(p->out, "%s\n", pRow->zText+3);
17356       p->sGraph.pRow = pRow->pNext;
17357       sqlite3_free(pRow);
17358     }else if( nCycle>0 ){
17359       utf8_printf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
17360     }else{
17361       utf8_printf(p->out, "QUERY PLAN\n");
17362     }
17363     p->sGraph.zPrefix[0] = 0;
17364     eqp_render_level(p, 0);
17365     eqp_reset(p);
17366   }
17367 }
17368 
17369 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
17370 /*
17371 ** Progress handler callback.
17372 */
17373 static int progress_handler(void *pClientData) {
17374   ShellState *p = (ShellState*)pClientData;
17375   p->nProgress++;
17376   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
17377     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
17378     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
17379     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
17380     return 1;
17381   }
17382   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
17383     raw_printf(p->out, "Progress %u\n", p->nProgress);
17384   }
17385   return 0;
17386 }
17387 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
17388 
17389 /*
17390 ** Print N dashes
17391 */
17392 static void print_dashes(FILE *out, int N){
17393   const char zDash[] = "--------------------------------------------------";
17394   const int nDash = sizeof(zDash) - 1;
17395   while( N>nDash ){
17396     fputs(zDash, out);
17397     N -= nDash;
17398   }
17399   raw_printf(out, "%.*s", N, zDash);
17400 }
17401 
17402 /*
17403 ** Print a markdown or table-style row separator using ascii-art
17404 */
17405 static void print_row_separator(
17406   ShellState *p,
17407   int nArg,
17408   const char *zSep
17409 ){
17410   int i;
17411   if( nArg>0 ){
17412     fputs(zSep, p->out);
17413     print_dashes(p->out, p->actualWidth[0]+2);
17414     for(i=1; i<nArg; i++){
17415       fputs(zSep, p->out);
17416       print_dashes(p->out, p->actualWidth[i]+2);
17417     }
17418     fputs(zSep, p->out);
17419   }
17420   fputs("\n", p->out);
17421 }
17422 
17423 /*
17424 ** This is the callback routine that the shell
17425 ** invokes for each row of a query result.
17426 */
17427 static int shell_callback(
17428   void *pArg,
17429   int nArg,        /* Number of result columns */
17430   char **azArg,    /* Text of each result column */
17431   char **azCol,    /* Column names */
17432   int *aiType      /* Column types.  Might be NULL */
17433 ){
17434   int i;
17435   ShellState *p = (ShellState*)pArg;
17436 
17437   if( azArg==0 ) return 0;
17438   switch( p->cMode ){
17439     case MODE_Count:
17440     case MODE_Off: {
17441       break;
17442     }
17443     case MODE_Line: {
17444       int w = 5;
17445       if( azArg==0 ) break;
17446       for(i=0; i<nArg; i++){
17447         int len = strlen30(azCol[i] ? azCol[i] : "");
17448         if( len>w ) w = len;
17449       }
17450       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
17451       for(i=0; i<nArg; i++){
17452         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
17453                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
17454       }
17455       break;
17456     }
17457     case MODE_Explain: {
17458       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
17459       if( nArg>ArraySize(aExplainWidth) ){
17460         nArg = ArraySize(aExplainWidth);
17461       }
17462       if( p->cnt++==0 ){
17463         for(i=0; i<nArg; i++){
17464           int w = aExplainWidth[i];
17465           utf8_width_print(p->out, w, azCol[i]);
17466           fputs(i==nArg-1 ? "\n" : "  ", p->out);
17467         }
17468         for(i=0; i<nArg; i++){
17469           int w = aExplainWidth[i];
17470           print_dashes(p->out, w);
17471           fputs(i==nArg-1 ? "\n" : "  ", p->out);
17472         }
17473       }
17474       if( azArg==0 ) break;
17475       for(i=0; i<nArg; i++){
17476         int w = aExplainWidth[i];
17477         if( i==nArg-1 ) w = 0;
17478         if( azArg[i] && strlenChar(azArg[i])>w ){
17479           w = strlenChar(azArg[i]);
17480         }
17481         if( i==1 && p->aiIndent && p->pStmt ){
17482           if( p->iIndent<p->nIndent ){
17483             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
17484           }
17485           p->iIndent++;
17486         }
17487         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
17488         fputs(i==nArg-1 ? "\n" : "  ", p->out);
17489       }
17490       break;
17491     }
17492     case MODE_Semi: {   /* .schema and .fullschema output */
17493       printSchemaLine(p->out, azArg[0], ";\n");
17494       break;
17495     }
17496     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
17497       char *z;
17498       int j;
17499       int nParen = 0;
17500       char cEnd = 0;
17501       char c;
17502       int nLine = 0;
17503       assert( nArg==1 );
17504       if( azArg[0]==0 ) break;
17505       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
17506        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
17507       ){
17508         utf8_printf(p->out, "%s;\n", azArg[0]);
17509         break;
17510       }
17511       z = sqlite3_mprintf("%s", azArg[0]);
17512       shell_check_oom(z);
17513       j = 0;
17514       for(i=0; IsSpace(z[i]); i++){}
17515       for(; (c = z[i])!=0; i++){
17516         if( IsSpace(c) ){
17517           if( z[j-1]=='\r' ) z[j-1] = '\n';
17518           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
17519         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
17520           j--;
17521         }
17522         z[j++] = c;
17523       }
17524       while( j>0 && IsSpace(z[j-1]) ){ j--; }
17525       z[j] = 0;
17526       if( strlen30(z)>=79 ){
17527         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
17528           if( c==cEnd ){
17529             cEnd = 0;
17530           }else if( c=='"' || c=='\'' || c=='`' ){
17531             cEnd = c;
17532           }else if( c=='[' ){
17533             cEnd = ']';
17534           }else if( c=='-' && z[i+1]=='-' ){
17535             cEnd = '\n';
17536           }else if( c=='(' ){
17537             nParen++;
17538           }else if( c==')' ){
17539             nParen--;
17540             if( nLine>0 && nParen==0 && j>0 ){
17541               printSchemaLineN(p->out, z, j, "\n");
17542               j = 0;
17543             }
17544           }
17545           z[j++] = c;
17546           if( nParen==1 && cEnd==0
17547            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
17548           ){
17549             if( c=='\n' ) j--;
17550             printSchemaLineN(p->out, z, j, "\n  ");
17551             j = 0;
17552             nLine++;
17553             while( IsSpace(z[i+1]) ){ i++; }
17554           }
17555         }
17556         z[j] = 0;
17557       }
17558       printSchemaLine(p->out, z, ";\n");
17559       sqlite3_free(z);
17560       break;
17561     }
17562     case MODE_List: {
17563       if( p->cnt++==0 && p->showHeader ){
17564         for(i=0; i<nArg; i++){
17565           utf8_printf(p->out,"%s%s",azCol[i],
17566                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
17567         }
17568       }
17569       if( azArg==0 ) break;
17570       for(i=0; i<nArg; i++){
17571         char *z = azArg[i];
17572         if( z==0 ) z = p->nullValue;
17573         utf8_printf(p->out, "%s", z);
17574         if( i<nArg-1 ){
17575           utf8_printf(p->out, "%s", p->colSeparator);
17576         }else{
17577           utf8_printf(p->out, "%s", p->rowSeparator);
17578         }
17579       }
17580       break;
17581     }
17582     case MODE_Html: {
17583       if( p->cnt++==0 && p->showHeader ){
17584         raw_printf(p->out,"<TR>");
17585         for(i=0; i<nArg; i++){
17586           raw_printf(p->out,"<TH>");
17587           output_html_string(p->out, azCol[i]);
17588           raw_printf(p->out,"</TH>\n");
17589         }
17590         raw_printf(p->out,"</TR>\n");
17591       }
17592       if( azArg==0 ) break;
17593       raw_printf(p->out,"<TR>");
17594       for(i=0; i<nArg; i++){
17595         raw_printf(p->out,"<TD>");
17596         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
17597         raw_printf(p->out,"</TD>\n");
17598       }
17599       raw_printf(p->out,"</TR>\n");
17600       break;
17601     }
17602     case MODE_Tcl: {
17603       if( p->cnt++==0 && p->showHeader ){
17604         for(i=0; i<nArg; i++){
17605           output_c_string(p->out,azCol[i] ? azCol[i] : "");
17606           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
17607         }
17608         utf8_printf(p->out, "%s", p->rowSeparator);
17609       }
17610       if( azArg==0 ) break;
17611       for(i=0; i<nArg; i++){
17612         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
17613         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
17614       }
17615       utf8_printf(p->out, "%s", p->rowSeparator);
17616       break;
17617     }
17618     case MODE_Csv: {
17619       setBinaryMode(p->out, 1);
17620       if( p->cnt++==0 && p->showHeader ){
17621         for(i=0; i<nArg; i++){
17622           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
17623         }
17624         utf8_printf(p->out, "%s", p->rowSeparator);
17625       }
17626       if( nArg>0 ){
17627         for(i=0; i<nArg; i++){
17628           output_csv(p, azArg[i], i<nArg-1);
17629         }
17630         utf8_printf(p->out, "%s", p->rowSeparator);
17631       }
17632       setTextMode(p->out, 1);
17633       break;
17634     }
17635     case MODE_Insert: {
17636       if( azArg==0 ) break;
17637       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
17638       if( p->showHeader ){
17639         raw_printf(p->out,"(");
17640         for(i=0; i<nArg; i++){
17641           if( i>0 ) raw_printf(p->out, ",");
17642           if( quoteChar(azCol[i]) ){
17643             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
17644             shell_check_oom(z);
17645             utf8_printf(p->out, "%s", z);
17646             sqlite3_free(z);
17647           }else{
17648             raw_printf(p->out, "%s", azCol[i]);
17649           }
17650         }
17651         raw_printf(p->out,")");
17652       }
17653       p->cnt++;
17654       for(i=0; i<nArg; i++){
17655         raw_printf(p->out, i>0 ? "," : " VALUES(");
17656         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17657           utf8_printf(p->out,"NULL");
17658         }else if( aiType && aiType[i]==SQLITE_TEXT ){
17659           if( ShellHasFlag(p, SHFLG_Newlines) ){
17660             output_quoted_string(p->out, azArg[i]);
17661           }else{
17662             output_quoted_escaped_string(p->out, azArg[i]);
17663           }
17664         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
17665           utf8_printf(p->out,"%s", azArg[i]);
17666         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
17667           char z[50];
17668           double r = sqlite3_column_double(p->pStmt, i);
17669           sqlite3_uint64 ur;
17670           memcpy(&ur,&r,sizeof(r));
17671           if( ur==0x7ff0000000000000LL ){
17672             raw_printf(p->out, "1e999");
17673           }else if( ur==0xfff0000000000000LL ){
17674             raw_printf(p->out, "-1e999");
17675           }else{
17676             sqlite3_int64 ir = (sqlite3_int64)r;
17677             if( r==(double)ir ){
17678               sqlite3_snprintf(50,z,"%lld.0", ir);
17679             }else{
17680               sqlite3_snprintf(50,z,"%!.20g", r);
17681             }
17682             raw_printf(p->out, "%s", z);
17683           }
17684         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
17685           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
17686           int nBlob = sqlite3_column_bytes(p->pStmt, i);
17687           output_hex_blob(p->out, pBlob, nBlob);
17688         }else if( isNumber(azArg[i], 0) ){
17689           utf8_printf(p->out,"%s", azArg[i]);
17690         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
17691           output_quoted_string(p->out, azArg[i]);
17692         }else{
17693           output_quoted_escaped_string(p->out, azArg[i]);
17694         }
17695       }
17696       raw_printf(p->out,");\n");
17697       break;
17698     }
17699     case MODE_Json: {
17700       if( azArg==0 ) break;
17701       if( p->cnt==0 ){
17702         fputs("[{", p->out);
17703       }else{
17704         fputs(",\n{", p->out);
17705       }
17706       p->cnt++;
17707       for(i=0; i<nArg; i++){
17708         output_json_string(p->out, azCol[i], -1);
17709         putc(':', p->out);
17710         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17711           fputs("null",p->out);
17712         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
17713           char z[50];
17714           double r = sqlite3_column_double(p->pStmt, i);
17715           sqlite3_uint64 ur;
17716           memcpy(&ur,&r,sizeof(r));
17717           if( ur==0x7ff0000000000000LL ){
17718             raw_printf(p->out, "1e999");
17719           }else if( ur==0xfff0000000000000LL ){
17720             raw_printf(p->out, "-1e999");
17721           }else{
17722             sqlite3_snprintf(50,z,"%!.20g", r);
17723             raw_printf(p->out, "%s", z);
17724           }
17725         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
17726           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
17727           int nBlob = sqlite3_column_bytes(p->pStmt, i);
17728           output_json_string(p->out, pBlob, nBlob);
17729         }else if( aiType && aiType[i]==SQLITE_TEXT ){
17730           output_json_string(p->out, azArg[i], -1);
17731         }else{
17732           utf8_printf(p->out,"%s", azArg[i]);
17733         }
17734         if( i<nArg-1 ){
17735           putc(',', p->out);
17736         }
17737       }
17738       putc('}', p->out);
17739       break;
17740     }
17741     case MODE_Quote: {
17742       if( azArg==0 ) break;
17743       if( p->cnt==0 && p->showHeader ){
17744         for(i=0; i<nArg; i++){
17745           if( i>0 ) fputs(p->colSeparator, p->out);
17746           output_quoted_string(p->out, azCol[i]);
17747         }
17748         fputs(p->rowSeparator, p->out);
17749       }
17750       p->cnt++;
17751       for(i=0; i<nArg; i++){
17752         if( i>0 ) fputs(p->colSeparator, p->out);
17753         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17754           utf8_printf(p->out,"NULL");
17755         }else if( aiType && aiType[i]==SQLITE_TEXT ){
17756           output_quoted_string(p->out, azArg[i]);
17757         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
17758           utf8_printf(p->out,"%s", azArg[i]);
17759         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
17760           char z[50];
17761           double r = sqlite3_column_double(p->pStmt, i);
17762           sqlite3_snprintf(50,z,"%!.20g", r);
17763           raw_printf(p->out, "%s", z);
17764         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
17765           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
17766           int nBlob = sqlite3_column_bytes(p->pStmt, i);
17767           output_hex_blob(p->out, pBlob, nBlob);
17768         }else if( isNumber(azArg[i], 0) ){
17769           utf8_printf(p->out,"%s", azArg[i]);
17770         }else{
17771           output_quoted_string(p->out, azArg[i]);
17772         }
17773       }
17774       fputs(p->rowSeparator, p->out);
17775       break;
17776     }
17777     case MODE_Ascii: {
17778       if( p->cnt++==0 && p->showHeader ){
17779         for(i=0; i<nArg; i++){
17780           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
17781           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
17782         }
17783         utf8_printf(p->out, "%s", p->rowSeparator);
17784       }
17785       if( azArg==0 ) break;
17786       for(i=0; i<nArg; i++){
17787         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
17788         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
17789       }
17790       utf8_printf(p->out, "%s", p->rowSeparator);
17791       break;
17792     }
17793     case MODE_EQP: {
17794       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
17795       break;
17796     }
17797   }
17798   return 0;
17799 }
17800 
17801 /*
17802 ** This is the callback routine that the SQLite library
17803 ** invokes for each row of a query result.
17804 */
17805 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
17806   /* since we don't have type info, call the shell_callback with a NULL value */
17807   return shell_callback(pArg, nArg, azArg, azCol, NULL);
17808 }
17809 
17810 /*
17811 ** This is the callback routine from sqlite3_exec() that appends all
17812 ** output onto the end of a ShellText object.
17813 */
17814 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
17815   ShellText *p = (ShellText*)pArg;
17816   int i;
17817   UNUSED_PARAMETER(az);
17818   if( azArg==0 ) return 0;
17819   if( p->n ) appendText(p, "|", 0);
17820   for(i=0; i<nArg; i++){
17821     if( i ) appendText(p, ",", 0);
17822     if( azArg[i] ) appendText(p, azArg[i], 0);
17823   }
17824   return 0;
17825 }
17826 
17827 /*
17828 ** Generate an appropriate SELFTEST table in the main database.
17829 */
17830 static void createSelftestTable(ShellState *p){
17831   char *zErrMsg = 0;
17832   sqlite3_exec(p->db,
17833     "SAVEPOINT selftest_init;\n"
17834     "CREATE TABLE IF NOT EXISTS selftest(\n"
17835     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
17836     "  op TEXT,\n"                   /* Operator:  memo run */
17837     "  cmd TEXT,\n"                  /* Command text */
17838     "  ans TEXT\n"                   /* Desired answer */
17839     ");"
17840     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
17841     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
17842     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
17843     "         'memo','Tests generated by --init');\n"
17844     "INSERT INTO [_shell$self]\n"
17845     "  SELECT 'run',\n"
17846     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
17847                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
17848     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
17849                           "FROM sqlite_schema ORDER BY 2',224));\n"
17850     "INSERT INTO [_shell$self]\n"
17851     "  SELECT 'run',"
17852     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
17853     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
17854     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
17855     "  FROM (\n"
17856     "    SELECT name FROM sqlite_schema\n"
17857     "     WHERE type='table'\n"
17858     "       AND name<>'selftest'\n"
17859     "       AND coalesce(rootpage,0)>0\n"
17860     "  )\n"
17861     " ORDER BY name;\n"
17862     "INSERT INTO [_shell$self]\n"
17863     "  VALUES('run','PRAGMA integrity_check','ok');\n"
17864     "INSERT INTO selftest(tno,op,cmd,ans)"
17865     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
17866     "DROP TABLE [_shell$self];"
17867     ,0,0,&zErrMsg);
17868   if( zErrMsg ){
17869     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
17870     sqlite3_free(zErrMsg);
17871   }
17872   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
17873 }
17874 
17875 
17876 /*
17877 ** Set the destination table field of the ShellState structure to
17878 ** the name of the table given.  Escape any quote characters in the
17879 ** table name.
17880 */
17881 static void set_table_name(ShellState *p, const char *zName){
17882   int i, n;
17883   char cQuote;
17884   char *z;
17885 
17886   if( p->zDestTable ){
17887     free(p->zDestTable);
17888     p->zDestTable = 0;
17889   }
17890   if( zName==0 ) return;
17891   cQuote = quoteChar(zName);
17892   n = strlen30(zName);
17893   if( cQuote ) n += n+2;
17894   z = p->zDestTable = malloc( n+1 );
17895   shell_check_oom(z);
17896   n = 0;
17897   if( cQuote ) z[n++] = cQuote;
17898   for(i=0; zName[i]; i++){
17899     z[n++] = zName[i];
17900     if( zName[i]==cQuote ) z[n++] = cQuote;
17901   }
17902   if( cQuote ) z[n++] = cQuote;
17903   z[n] = 0;
17904 }
17905 
17906 /*
17907 ** Maybe construct two lines of text that point out the position of a
17908 ** syntax error.  Return a pointer to the text, in memory obtained from
17909 ** sqlite3_malloc().  Or, if the most recent error does not involve a
17910 ** specific token that we can point to, return an empty string.
17911 **
17912 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
17913 ** and should be released by the caller invoking sqlite3_free().
17914 */
17915 static char *shell_error_context(const char *zSql, sqlite3 *db){
17916   int iOffset;
17917   size_t len;
17918   char *zCode;
17919   char *zMsg;
17920   int i;
17921   if( db==0
17922    || zSql==0
17923    || (iOffset = sqlite3_error_offset(db))<0
17924   ){
17925     return sqlite3_mprintf("");
17926   }
17927   while( iOffset>50 ){
17928     iOffset--;
17929     zSql++;
17930     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
17931   }
17932   len = strlen(zSql);
17933   if( len>78 ){
17934     len = 78;
17935     while( (zSql[len]&0xc0)==0x80 ) len--;
17936   }
17937   zCode = sqlite3_mprintf("%.*s", len, zSql);
17938   shell_check_oom(zCode);
17939   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
17940   if( iOffset<25 ){
17941     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
17942   }else{
17943     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
17944   }
17945   return zMsg;
17946 }
17947 
17948 
17949 /*
17950 ** Execute a query statement that will generate SQL output.  Print
17951 ** the result columns, comma-separated, on a line and then add a
17952 ** semicolon terminator to the end of that line.
17953 **
17954 ** If the number of columns is 1 and that column contains text "--"
17955 ** then write the semicolon on a separate line.  That way, if a
17956 ** "--" comment occurs at the end of the statement, the comment
17957 ** won't consume the semicolon terminator.
17958 */
17959 static int run_table_dump_query(
17960   ShellState *p,           /* Query context */
17961   const char *zSelect      /* SELECT statement to extract content */
17962 ){
17963   sqlite3_stmt *pSelect;
17964   int rc;
17965   int nResult;
17966   int i;
17967   const char *z;
17968   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
17969   if( rc!=SQLITE_OK || !pSelect ){
17970     char *zContext = shell_error_context(zSelect, p->db);
17971     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
17972                 sqlite3_errmsg(p->db), zContext);
17973     sqlite3_free(zContext);
17974     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
17975     return rc;
17976   }
17977   rc = sqlite3_step(pSelect);
17978   nResult = sqlite3_column_count(pSelect);
17979   while( rc==SQLITE_ROW ){
17980     z = (const char*)sqlite3_column_text(pSelect, 0);
17981     utf8_printf(p->out, "%s", z);
17982     for(i=1; i<nResult; i++){
17983       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
17984     }
17985     if( z==0 ) z = "";
17986     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
17987     if( z[0] ){
17988       raw_printf(p->out, "\n;\n");
17989     }else{
17990       raw_printf(p->out, ";\n");
17991     }
17992     rc = sqlite3_step(pSelect);
17993   }
17994   rc = sqlite3_finalize(pSelect);
17995   if( rc!=SQLITE_OK ){
17996     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
17997                 sqlite3_errmsg(p->db));
17998     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
17999   }
18000   return rc;
18001 }
18002 
18003 /*
18004 ** Allocate space and save off string indicating current error.
18005 */
18006 static char *save_err_msg(
18007   sqlite3 *db,           /* Database to query */
18008   const char *zPhase,    /* When the error occcurs */
18009   int rc,                /* Error code returned from API */
18010   const char *zSql       /* SQL string, or NULL */
18011 ){
18012   char *zErr;
18013   char *zContext;
18014   sqlite3_str *pStr = sqlite3_str_new(0);
18015   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
18016   if( rc>1 ){
18017     sqlite3_str_appendf(pStr, " (%d)", rc);
18018   }
18019   zContext = shell_error_context(zSql, db);
18020   if( zContext ){
18021     sqlite3_str_appendall(pStr, zContext);
18022     sqlite3_free(zContext);
18023   }
18024   zErr = sqlite3_str_finish(pStr);
18025   shell_check_oom(zErr);
18026   return zErr;
18027 }
18028 
18029 #ifdef __linux__
18030 /*
18031 ** Attempt to display I/O stats on Linux using /proc/PID/io
18032 */
18033 static void displayLinuxIoStats(FILE *out){
18034   FILE *in;
18035   char z[200];
18036   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
18037   in = fopen(z, "rb");
18038   if( in==0 ) return;
18039   while( fgets(z, sizeof(z), in)!=0 ){
18040     static const struct {
18041       const char *zPattern;
18042       const char *zDesc;
18043     } aTrans[] = {
18044       { "rchar: ",                  "Bytes received by read():" },
18045       { "wchar: ",                  "Bytes sent to write():"    },
18046       { "syscr: ",                  "Read() system calls:"      },
18047       { "syscw: ",                  "Write() system calls:"     },
18048       { "read_bytes: ",             "Bytes read from storage:"  },
18049       { "write_bytes: ",            "Bytes written to storage:" },
18050       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
18051     };
18052     int i;
18053     for(i=0; i<ArraySize(aTrans); i++){
18054       int n = strlen30(aTrans[i].zPattern);
18055       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
18056         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
18057         break;
18058       }
18059     }
18060   }
18061   fclose(in);
18062 }
18063 #endif
18064 
18065 /*
18066 ** Display a single line of status using 64-bit values.
18067 */
18068 static void displayStatLine(
18069   ShellState *p,            /* The shell context */
18070   char *zLabel,             /* Label for this one line */
18071   char *zFormat,            /* Format for the result */
18072   int iStatusCtrl,          /* Which status to display */
18073   int bReset                /* True to reset the stats */
18074 ){
18075   sqlite3_int64 iCur = -1;
18076   sqlite3_int64 iHiwtr = -1;
18077   int i, nPercent;
18078   char zLine[200];
18079   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
18080   for(i=0, nPercent=0; zFormat[i]; i++){
18081     if( zFormat[i]=='%' ) nPercent++;
18082   }
18083   if( nPercent>1 ){
18084     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
18085   }else{
18086     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
18087   }
18088   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
18089 }
18090 
18091 /*
18092 ** Display memory stats.
18093 */
18094 static int display_stats(
18095   sqlite3 *db,                /* Database to query */
18096   ShellState *pArg,           /* Pointer to ShellState */
18097   int bReset                  /* True to reset the stats */
18098 ){
18099   int iCur;
18100   int iHiwtr;
18101   FILE *out;
18102   if( pArg==0 || pArg->out==0 ) return 0;
18103   out = pArg->out;
18104 
18105   if( pArg->pStmt && pArg->statsOn==2 ){
18106     int nCol, i, x;
18107     sqlite3_stmt *pStmt = pArg->pStmt;
18108     char z[100];
18109     nCol = sqlite3_column_count(pStmt);
18110     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
18111     for(i=0; i<nCol; i++){
18112       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
18113       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
18114 #ifndef SQLITE_OMIT_DECLTYPE
18115       sqlite3_snprintf(30, z+x, "declared type:");
18116       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
18117 #endif
18118 #ifdef SQLITE_ENABLE_COLUMN_METADATA
18119       sqlite3_snprintf(30, z+x, "database name:");
18120       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
18121       sqlite3_snprintf(30, z+x, "table name:");
18122       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
18123       sqlite3_snprintf(30, z+x, "origin name:");
18124       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
18125 #endif
18126     }
18127   }
18128 
18129   if( pArg->statsOn==3 ){
18130     if( pArg->pStmt ){
18131       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
18132       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
18133     }
18134     return 0;
18135   }
18136 
18137   displayStatLine(pArg, "Memory Used:",
18138      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
18139   displayStatLine(pArg, "Number of Outstanding Allocations:",
18140      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
18141   if( pArg->shellFlgs & SHFLG_Pagecache ){
18142     displayStatLine(pArg, "Number of Pcache Pages Used:",
18143        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
18144   }
18145   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
18146      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
18147   displayStatLine(pArg, "Largest Allocation:",
18148      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
18149   displayStatLine(pArg, "Largest Pcache Allocation:",
18150      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
18151 #ifdef YYTRACKMAXSTACKDEPTH
18152   displayStatLine(pArg, "Deepest Parser Stack:",
18153      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
18154 #endif
18155 
18156   if( db ){
18157     if( pArg->shellFlgs & SHFLG_Lookaside ){
18158       iHiwtr = iCur = -1;
18159       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
18160                         &iCur, &iHiwtr, bReset);
18161       raw_printf(pArg->out,
18162               "Lookaside Slots Used:                %d (max %d)\n",
18163               iCur, iHiwtr);
18164       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
18165                         &iCur, &iHiwtr, bReset);
18166       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
18167               iHiwtr);
18168       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
18169                         &iCur, &iHiwtr, bReset);
18170       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
18171               iHiwtr);
18172       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
18173                         &iCur, &iHiwtr, bReset);
18174       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
18175               iHiwtr);
18176     }
18177     iHiwtr = iCur = -1;
18178     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
18179     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
18180             iCur);
18181     iHiwtr = iCur = -1;
18182     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
18183     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
18184     iHiwtr = iCur = -1;
18185     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
18186     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
18187     iHiwtr = iCur = -1;
18188     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
18189     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
18190     iHiwtr = iCur = -1;
18191     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
18192     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
18193     iHiwtr = iCur = -1;
18194     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
18195     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
18196             iCur);
18197     iHiwtr = iCur = -1;
18198     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
18199     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
18200             iCur);
18201   }
18202 
18203   if( pArg->pStmt ){
18204     int iHit, iMiss;
18205     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
18206                                bReset);
18207     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
18208     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
18209     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
18210     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
18211     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
18212     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
18213                                bReset);
18214     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
18215                                 bReset);
18216     if( iHit || iMiss ){
18217       raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
18218             iHit, iHit+iMiss);
18219     }
18220     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
18221     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
18222     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
18223     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
18224     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
18225     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
18226     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
18227     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
18228   }
18229 
18230 #ifdef __linux__
18231   displayLinuxIoStats(pArg->out);
18232 #endif
18233 
18234   /* Do not remove this machine readable comment: extra-stats-output-here */
18235 
18236   return 0;
18237 }
18238 
18239 
18240 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18241 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
18242   int iPid = 0;
18243   int ret = 1;
18244   sqlite3_stmt_scanstatus_v2(p, iEntry,
18245       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
18246   );
18247   while( iPid!=0 ){
18248     int ii;
18249     for(ii=0; 1; ii++){
18250       int iId;
18251       int res;
18252       res = sqlite3_stmt_scanstatus_v2(p, ii,
18253           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
18254       );
18255       if( res ) break;
18256       if( iId==iPid ){
18257         sqlite3_stmt_scanstatus_v2(p, ii,
18258             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
18259         );
18260       }
18261     }
18262     ret++;
18263   }
18264   return ret;
18265 }
18266 #endif
18267 
18268 /*
18269 ** Display scan stats.
18270 */
18271 static void display_scanstats(
18272   sqlite3 *db,                    /* Database to query */
18273   ShellState *pArg                /* Pointer to ShellState */
18274 ){
18275 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
18276   UNUSED_PARAMETER(db);
18277   UNUSED_PARAMETER(pArg);
18278 #else
18279   static const int f = SQLITE_SCANSTAT_COMPLEX;
18280   sqlite3_stmt *p = pArg->pStmt;
18281   int ii = 0;
18282   i64 nTotal = 0;
18283   int nWidth = 0;
18284   eqp_reset(pArg);
18285 
18286   for(ii=0; 1; ii++){
18287     const char *z = 0;
18288     int n = 0;
18289     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
18290       break;
18291     }
18292     n = strlen(z) + scanStatsHeight(p, ii)*3;
18293     if( n>nWidth ) nWidth = n;
18294   }
18295   nWidth += 4;
18296 
18297   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
18298   for(ii=0; 1; ii++){
18299     i64 nLoop = 0;
18300     i64 nRow = 0;
18301     i64 nCycle = 0;
18302     int iId = 0;
18303     int iPid = 0;
18304     const char *z = 0;
18305     const char *zName = 0;
18306     char *zText = 0;
18307     double rEst = 0.0;
18308 
18309     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
18310       break;
18311     }
18312     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
18313     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
18314     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
18315     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
18316     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
18317     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
18318     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
18319 
18320     zText = sqlite3_mprintf("%s", z);
18321     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
18322       char *z = 0;
18323       if( nCycle>=0 && nTotal>0 ){
18324         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
18325             nCycle, ((nCycle*100)+nTotal/2) / nTotal
18326         );
18327       }
18328       if( nLoop>=0 ){
18329         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
18330       }
18331       if( nRow>=0 ){
18332         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
18333       }
18334 
18335       if( zName && pArg->scanstatsOn>1 ){
18336         double rpl = (double)nRow / (double)nLoop;
18337         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
18338       }
18339 
18340       zText = sqlite3_mprintf(
18341           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
18342       );
18343     }
18344 
18345     eqp_append(pArg, iId, iPid, zText);
18346     sqlite3_free(zText);
18347   }
18348 
18349   eqp_render(pArg, nTotal);
18350 #endif
18351 }
18352 
18353 /*
18354 ** Parameter azArray points to a zero-terminated array of strings. zStr
18355 ** points to a single nul-terminated string. Return non-zero if zStr
18356 ** is equal, according to strcmp(), to any of the strings in the array.
18357 ** Otherwise, return zero.
18358 */
18359 static int str_in_array(const char *zStr, const char **azArray){
18360   int i;
18361   for(i=0; azArray[i]; i++){
18362     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
18363   }
18364   return 0;
18365 }
18366 
18367 /*
18368 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
18369 ** and populate the ShellState.aiIndent[] array with the number of
18370 ** spaces each opcode should be indented before it is output.
18371 **
18372 ** The indenting rules are:
18373 **
18374 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
18375 **       all opcodes that occur between the p2 jump destination and the opcode
18376 **       itself by 2 spaces.
18377 **
18378 **     * Do the previous for "Return" instructions for when P2 is positive.
18379 **       See tag-20220407a in wherecode.c and vdbe.c.
18380 **
18381 **     * For each "Goto", if the jump destination is earlier in the program
18382 **       and ends on one of:
18383 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
18384 **       or if the P1 parameter is one instead of zero,
18385 **       then indent all opcodes between the earlier instruction
18386 **       and "Goto" by 2 spaces.
18387 */
18388 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
18389   const char *zSql;               /* The text of the SQL statement */
18390   const char *z;                  /* Used to check if this is an EXPLAIN */
18391   int *abYield = 0;               /* True if op is an OP_Yield */
18392   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
18393   int iOp;                        /* Index of operation in p->aiIndent[] */
18394 
18395   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
18396                            "Return", 0 };
18397   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
18398                             "Rewind", 0 };
18399   const char *azGoto[] = { "Goto", 0 };
18400 
18401   /* Try to figure out if this is really an EXPLAIN statement. If this
18402   ** cannot be verified, return early.  */
18403   if( sqlite3_column_count(pSql)!=8 ){
18404     p->cMode = p->mode;
18405     return;
18406   }
18407   zSql = sqlite3_sql(pSql);
18408   if( zSql==0 ) return;
18409   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
18410   if( sqlite3_strnicmp(z, "explain", 7) ){
18411     p->cMode = p->mode;
18412     return;
18413   }
18414 
18415   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
18416     int i;
18417     int iAddr = sqlite3_column_int(pSql, 0);
18418     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
18419 
18420     /* Set p2 to the P2 field of the current opcode. Then, assuming that
18421     ** p2 is an instruction address, set variable p2op to the index of that
18422     ** instruction in the aiIndent[] array. p2 and p2op may be different if
18423     ** the current instruction is part of a sub-program generated by an
18424     ** SQL trigger or foreign key.  */
18425     int p2 = sqlite3_column_int(pSql, 3);
18426     int p2op = (p2 + (iOp-iAddr));
18427 
18428     /* Grow the p->aiIndent array as required */
18429     if( iOp>=nAlloc ){
18430       if( iOp==0 ){
18431         /* Do further verfication that this is explain output.  Abort if
18432         ** it is not */
18433         static const char *explainCols[] = {
18434            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
18435         int jj;
18436         for(jj=0; jj<ArraySize(explainCols); jj++){
18437           if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
18438             p->cMode = p->mode;
18439             sqlite3_reset(pSql);
18440             return;
18441           }
18442         }
18443       }
18444       nAlloc += 100;
18445       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
18446       shell_check_oom(p->aiIndent);
18447       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
18448       shell_check_oom(abYield);
18449     }
18450     abYield[iOp] = str_in_array(zOp, azYield);
18451     p->aiIndent[iOp] = 0;
18452     p->nIndent = iOp+1;
18453 
18454     if( str_in_array(zOp, azNext) && p2op>0 ){
18455       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
18456     }
18457     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
18458      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
18459     ){
18460       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
18461     }
18462   }
18463 
18464   p->iIndent = 0;
18465   sqlite3_free(abYield);
18466   sqlite3_reset(pSql);
18467 }
18468 
18469 /*
18470 ** Free the array allocated by explain_data_prepare().
18471 */
18472 static void explain_data_delete(ShellState *p){
18473   sqlite3_free(p->aiIndent);
18474   p->aiIndent = 0;
18475   p->nIndent = 0;
18476   p->iIndent = 0;
18477 }
18478 
18479 /*
18480 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
18481 */
18482 static unsigned int savedSelectTrace;
18483 static unsigned int savedWhereTrace;
18484 static void disable_debug_trace_modes(void){
18485   unsigned int zero = 0;
18486   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
18487   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
18488   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
18489   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
18490 }
18491 static void restore_debug_trace_modes(void){
18492   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
18493   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
18494 }
18495 
18496 /* Create the TEMP table used to store parameter bindings */
18497 static void bind_table_init(ShellState *p){
18498   int wrSchema = 0;
18499   int defensiveMode = 0;
18500   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
18501   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
18502   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
18503   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
18504   sqlite3_exec(p->db,
18505     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
18506     "  key TEXT PRIMARY KEY,\n"
18507     "  value\n"
18508     ") WITHOUT ROWID;",
18509     0, 0, 0);
18510   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
18511   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
18512 }
18513 
18514 /*
18515 ** Bind parameters on a prepared statement.
18516 **
18517 ** Parameter bindings are taken from a TEMP table of the form:
18518 **
18519 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
18520 **    WITHOUT ROWID;
18521 **
18522 ** No bindings occur if this table does not exist.  The name of the table
18523 ** begins with "sqlite_" so that it will not collide with ordinary application
18524 ** tables.  The table must be in the TEMP schema.
18525 */
18526 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
18527   int nVar;
18528   int i;
18529   int rc;
18530   sqlite3_stmt *pQ = 0;
18531 
18532   nVar = sqlite3_bind_parameter_count(pStmt);
18533   if( nVar==0 ) return;  /* Nothing to do */
18534   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
18535                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
18536     return; /* Parameter table does not exist */
18537   }
18538   rc = sqlite3_prepare_v2(pArg->db,
18539           "SELECT value FROM temp.sqlite_parameters"
18540           " WHERE key=?1", -1, &pQ, 0);
18541   if( rc || pQ==0 ) return;
18542   for(i=1; i<=nVar; i++){
18543     char zNum[30];
18544     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
18545     if( zVar==0 ){
18546       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
18547       zVar = zNum;
18548     }
18549     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
18550     if( sqlite3_step(pQ)==SQLITE_ROW ){
18551       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
18552     }else{
18553       sqlite3_bind_null(pStmt, i);
18554     }
18555     sqlite3_reset(pQ);
18556   }
18557   sqlite3_finalize(pQ);
18558 }
18559 
18560 /*
18561 ** UTF8 box-drawing characters.  Imagine box lines like this:
18562 **
18563 **           1
18564 **           |
18565 **       4 --+-- 2
18566 **           |
18567 **           3
18568 **
18569 ** Each box characters has between 2 and 4 of the lines leading from
18570 ** the center.  The characters are here identified by the numbers of
18571 ** their corresponding lines.
18572 */
18573 #define BOX_24   "\342\224\200"  /* U+2500 --- */
18574 #define BOX_13   "\342\224\202"  /* U+2502  |  */
18575 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
18576 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
18577 #define BOX_12   "\342\224\224"  /* U+2514  '- */
18578 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
18579 #define BOX_123  "\342\224\234"  /* U+251c  |- */
18580 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
18581 #define BOX_234  "\342\224\254"  /* U+252c -,- */
18582 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
18583 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
18584 
18585 /* Draw horizontal line N characters long using unicode box
18586 ** characters
18587 */
18588 static void print_box_line(FILE *out, int N){
18589   const char zDash[] =
18590       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
18591       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
18592   const int nDash = sizeof(zDash) - 1;
18593   N *= 3;
18594   while( N>nDash ){
18595     utf8_printf(out, zDash);
18596     N -= nDash;
18597   }
18598   utf8_printf(out, "%.*s", N, zDash);
18599 }
18600 
18601 /*
18602 ** Draw a horizontal separator for a MODE_Box table.
18603 */
18604 static void print_box_row_separator(
18605   ShellState *p,
18606   int nArg,
18607   const char *zSep1,
18608   const char *zSep2,
18609   const char *zSep3
18610 ){
18611   int i;
18612   if( nArg>0 ){
18613     utf8_printf(p->out, "%s", zSep1);
18614     print_box_line(p->out, p->actualWidth[0]+2);
18615     for(i=1; i<nArg; i++){
18616       utf8_printf(p->out, "%s", zSep2);
18617       print_box_line(p->out, p->actualWidth[i]+2);
18618     }
18619     utf8_printf(p->out, "%s", zSep3);
18620   }
18621   fputs("\n", p->out);
18622 }
18623 
18624 /*
18625 ** z[] is a line of text that is to be displayed the .mode box or table or
18626 ** similar tabular formats.  z[] might contain control characters such
18627 ** as \n, \t, \f, or \r.
18628 **
18629 ** Compute characters to display on the first line of z[].  Stop at the
18630 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
18631 ** from malloc()) of that first line, which caller should free sometime.
18632 ** Write anything to display on the next line into *pzTail.  If this is
18633 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
18634 */
18635 static char *translateForDisplayAndDup(
18636   const unsigned char *z,            /* Input text to be transformed */
18637   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
18638   int mxWidth,                       /* Max width.  0 means no limit */
18639   u8 bWordWrap                       /* If true, avoid breaking mid-word */
18640 ){
18641   int i;                 /* Input bytes consumed */
18642   int j;                 /* Output bytes generated */
18643   int k;                 /* Input bytes to be displayed */
18644   int n;                 /* Output column number */
18645   unsigned char *zOut;   /* Output text */
18646 
18647   if( z==0 ){
18648     *pzTail = 0;
18649     return 0;
18650   }
18651   if( mxWidth<0 ) mxWidth = -mxWidth;
18652   if( mxWidth==0 ) mxWidth = 1000000;
18653   i = j = n = 0;
18654   while( n<mxWidth ){
18655     if( z[i]>=' ' ){
18656       n++;
18657       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
18658       continue;
18659     }
18660     if( z[i]=='\t' ){
18661       do{
18662         n++;
18663         j++;
18664       }while( (n&7)!=0 && n<mxWidth );
18665       i++;
18666       continue;
18667     }
18668     break;
18669   }
18670   if( n>=mxWidth && bWordWrap  ){
18671     /* Perhaps try to back up to a better place to break the line */
18672     for(k=i; k>i/2; k--){
18673       if( isspace(z[k-1]) ) break;
18674     }
18675     if( k<=i/2 ){
18676       for(k=i; k>i/2; k--){
18677         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
18678       }
18679     }
18680     if( k<=i/2 ){
18681       k = i;
18682     }else{
18683       i = k;
18684       while( z[i]==' ' ) i++;
18685     }
18686   }else{
18687     k = i;
18688   }
18689   if( n>=mxWidth && z[i]>=' ' ){
18690    *pzTail = &z[i];
18691   }else if( z[i]=='\r' && z[i+1]=='\n' ){
18692     *pzTail = z[i+2] ? &z[i+2] : 0;
18693   }else if( z[i]==0 || z[i+1]==0 ){
18694     *pzTail = 0;
18695   }else{
18696     *pzTail = &z[i+1];
18697   }
18698   zOut = malloc( j+1 );
18699   shell_check_oom(zOut);
18700   i = j = n = 0;
18701   while( i<k ){
18702     if( z[i]>=' ' ){
18703       n++;
18704       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
18705       continue;
18706     }
18707     if( z[i]=='\t' ){
18708       do{
18709         n++;
18710         zOut[j++] = ' ';
18711       }while( (n&7)!=0 && n<mxWidth );
18712       i++;
18713       continue;
18714     }
18715     break;
18716   }
18717   zOut[j] = 0;
18718   return (char*)zOut;
18719 }
18720 
18721 /* Extract the value of the i-th current column for pStmt as an SQL literal
18722 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
18723 ** the caller.
18724 */
18725 static char *quoted_column(sqlite3_stmt *pStmt, int i){
18726   switch( sqlite3_column_type(pStmt, i) ){
18727     case SQLITE_NULL: {
18728       return sqlite3_mprintf("NULL");
18729     }
18730     case SQLITE_INTEGER:
18731     case SQLITE_FLOAT: {
18732       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
18733     }
18734     case SQLITE_TEXT: {
18735       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
18736     }
18737     case SQLITE_BLOB: {
18738       int j;
18739       sqlite3_str *pStr = sqlite3_str_new(0);
18740       const unsigned char *a = sqlite3_column_blob(pStmt,i);
18741       int n = sqlite3_column_bytes(pStmt,i);
18742       sqlite3_str_append(pStr, "x'", 2);
18743       for(j=0; j<n; j++){
18744         sqlite3_str_appendf(pStr, "%02x", a[j]);
18745       }
18746       sqlite3_str_append(pStr, "'", 1);
18747       return sqlite3_str_finish(pStr);
18748     }
18749   }
18750   return 0; /* Not reached */
18751 }
18752 
18753 /*
18754 ** Run a prepared statement and output the result in one of the
18755 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
18756 ** or MODE_Box.
18757 **
18758 ** This is different from ordinary exec_prepared_stmt() in that
18759 ** it has to run the entire query and gather the results into memory
18760 ** first, in order to determine column widths, before providing
18761 ** any output.
18762 */
18763 static void exec_prepared_stmt_columnar(
18764   ShellState *p,                        /* Pointer to ShellState */
18765   sqlite3_stmt *pStmt                   /* Statment to run */
18766 ){
18767   sqlite3_int64 nRow = 0;
18768   int nColumn = 0;
18769   char **azData = 0;
18770   sqlite3_int64 nAlloc = 0;
18771   char *abRowDiv = 0;
18772   const unsigned char *uz;
18773   const char *z;
18774   char **azQuoted = 0;
18775   int rc;
18776   sqlite3_int64 i, nData;
18777   int j, nTotal, w, n;
18778   const char *colSep = 0;
18779   const char *rowSep = 0;
18780   const unsigned char **azNextLine = 0;
18781   int bNextLine = 0;
18782   int bMultiLineRowExists = 0;
18783   int bw = p->cmOpts.bWordWrap;
18784   const char *zEmpty = "";
18785   const char *zShowNull = p->nullValue;
18786 
18787   rc = sqlite3_step(pStmt);
18788   if( rc!=SQLITE_ROW ) return;
18789   nColumn = sqlite3_column_count(pStmt);
18790   nAlloc = nColumn*4;
18791   if( nAlloc<=0 ) nAlloc = 1;
18792   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
18793   shell_check_oom(azData);
18794   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
18795   shell_check_oom((void*)azNextLine);
18796   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
18797   if( p->cmOpts.bQuote ){
18798     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
18799     shell_check_oom(azQuoted);
18800     memset(azQuoted, 0, nColumn*sizeof(char*) );
18801   }
18802   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
18803   shell_check_oom(abRowDiv);
18804   if( nColumn>p->nWidth ){
18805     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
18806     shell_check_oom(p->colWidth);
18807     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
18808     p->nWidth = nColumn;
18809     p->actualWidth = &p->colWidth[nColumn];
18810   }
18811   memset(p->actualWidth, 0, nColumn*sizeof(int));
18812   for(i=0; i<nColumn; i++){
18813     w = p->colWidth[i];
18814     if( w<0 ) w = -w;
18815     p->actualWidth[i] = w;
18816   }
18817   for(i=0; i<nColumn; i++){
18818     const unsigned char *zNotUsed;
18819     int wx = p->colWidth[i];
18820     if( wx==0 ){
18821       wx = p->cmOpts.iWrap;
18822     }
18823     if( wx<0 ) wx = -wx;
18824     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
18825     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
18826   }
18827   do{
18828     int useNextLine = bNextLine;
18829     bNextLine = 0;
18830     if( (nRow+2)*nColumn >= nAlloc ){
18831       nAlloc *= 2;
18832       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
18833       shell_check_oom(azData);
18834       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
18835       shell_check_oom(abRowDiv);
18836     }
18837     abRowDiv[nRow] = 1;
18838     nRow++;
18839     for(i=0; i<nColumn; i++){
18840       int wx = p->colWidth[i];
18841       if( wx==0 ){
18842         wx = p->cmOpts.iWrap;
18843       }
18844       if( wx<0 ) wx = -wx;
18845       if( useNextLine ){
18846         uz = azNextLine[i];
18847         if( uz==0 ) uz = (u8*)zEmpty;
18848       }else if( p->cmOpts.bQuote ){
18849         sqlite3_free(azQuoted[i]);
18850         azQuoted[i] = quoted_column(pStmt,i);
18851         uz = (const unsigned char*)azQuoted[i];
18852       }else{
18853         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
18854         if( uz==0 ) uz = (u8*)zShowNull;
18855       }
18856       azData[nRow*nColumn + i]
18857         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
18858       if( azNextLine[i] ){
18859         bNextLine = 1;
18860         abRowDiv[nRow-1] = 0;
18861         bMultiLineRowExists = 1;
18862       }
18863     }
18864   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
18865   nTotal = nColumn*(nRow+1);
18866   for(i=0; i<nTotal; i++){
18867     z = azData[i];
18868     if( z==0 ) z = (char*)zEmpty;
18869     n = strlenChar(z);
18870     j = i%nColumn;
18871     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
18872   }
18873   if( seenInterrupt ) goto columnar_end;
18874   if( nColumn==0 ) goto columnar_end;
18875   switch( p->cMode ){
18876     case MODE_Column: {
18877       colSep = "  ";
18878       rowSep = "\n";
18879       if( p->showHeader ){
18880         for(i=0; i<nColumn; i++){
18881           w = p->actualWidth[i];
18882           if( p->colWidth[i]<0 ) w = -w;
18883           utf8_width_print(p->out, w, azData[i]);
18884           fputs(i==nColumn-1?"\n":"  ", p->out);
18885         }
18886         for(i=0; i<nColumn; i++){
18887           print_dashes(p->out, p->actualWidth[i]);
18888           fputs(i==nColumn-1?"\n":"  ", p->out);
18889         }
18890       }
18891       break;
18892     }
18893     case MODE_Table: {
18894       colSep = " | ";
18895       rowSep = " |\n";
18896       print_row_separator(p, nColumn, "+");
18897       fputs("| ", p->out);
18898       for(i=0; i<nColumn; i++){
18899         w = p->actualWidth[i];
18900         n = strlenChar(azData[i]);
18901         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
18902         fputs(i==nColumn-1?" |\n":" | ", p->out);
18903       }
18904       print_row_separator(p, nColumn, "+");
18905       break;
18906     }
18907     case MODE_Markdown: {
18908       colSep = " | ";
18909       rowSep = " |\n";
18910       fputs("| ", p->out);
18911       for(i=0; i<nColumn; i++){
18912         w = p->actualWidth[i];
18913         n = strlenChar(azData[i]);
18914         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
18915         fputs(i==nColumn-1?" |\n":" | ", p->out);
18916       }
18917       print_row_separator(p, nColumn, "|");
18918       break;
18919     }
18920     case MODE_Box: {
18921       colSep = " " BOX_13 " ";
18922       rowSep = " " BOX_13 "\n";
18923       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
18924       utf8_printf(p->out, BOX_13 " ");
18925       for(i=0; i<nColumn; i++){
18926         w = p->actualWidth[i];
18927         n = strlenChar(azData[i]);
18928         utf8_printf(p->out, "%*s%s%*s%s",
18929             (w-n)/2, "", azData[i], (w-n+1)/2, "",
18930             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
18931       }
18932       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
18933       break;
18934     }
18935   }
18936   for(i=nColumn, j=0; i<nTotal; i++, j++){
18937     if( j==0 && p->cMode!=MODE_Column ){
18938       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
18939     }
18940     z = azData[i];
18941     if( z==0 ) z = p->nullValue;
18942     w = p->actualWidth[j];
18943     if( p->colWidth[j]<0 ) w = -w;
18944     utf8_width_print(p->out, w, z);
18945     if( j==nColumn-1 ){
18946       utf8_printf(p->out, "%s", rowSep);
18947       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
18948         if( p->cMode==MODE_Table ){
18949           print_row_separator(p, nColumn, "+");
18950         }else if( p->cMode==MODE_Box ){
18951           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
18952         }else if( p->cMode==MODE_Column ){
18953           raw_printf(p->out, "\n");
18954         }
18955       }
18956       j = -1;
18957       if( seenInterrupt ) goto columnar_end;
18958     }else{
18959       utf8_printf(p->out, "%s", colSep);
18960     }
18961   }
18962   if( p->cMode==MODE_Table ){
18963     print_row_separator(p, nColumn, "+");
18964   }else if( p->cMode==MODE_Box ){
18965     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
18966   }
18967 columnar_end:
18968   if( seenInterrupt ){
18969     utf8_printf(p->out, "Interrupt\n");
18970   }
18971   nData = (nRow+1)*nColumn;
18972   for(i=0; i<nData; i++){
18973     z = azData[i];
18974     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
18975   }
18976   sqlite3_free(azData);
18977   sqlite3_free((void*)azNextLine);
18978   sqlite3_free(abRowDiv);
18979   if( azQuoted ){
18980     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
18981     sqlite3_free(azQuoted);
18982   }
18983 }
18984 
18985 /*
18986 ** Run a prepared statement
18987 */
18988 static void exec_prepared_stmt(
18989   ShellState *pArg,                                /* Pointer to ShellState */
18990   sqlite3_stmt *pStmt                              /* Statment to run */
18991 ){
18992   int rc;
18993   sqlite3_uint64 nRow = 0;
18994 
18995   if( pArg->cMode==MODE_Column
18996    || pArg->cMode==MODE_Table
18997    || pArg->cMode==MODE_Box
18998    || pArg->cMode==MODE_Markdown
18999   ){
19000     exec_prepared_stmt_columnar(pArg, pStmt);
19001     return;
19002   }
19003 
19004   /* perform the first step.  this will tell us if we
19005   ** have a result set or not and how wide it is.
19006   */
19007   rc = sqlite3_step(pStmt);
19008   /* if we have a result set... */
19009   if( SQLITE_ROW == rc ){
19010     /* allocate space for col name ptr, value ptr, and type */
19011     int nCol = sqlite3_column_count(pStmt);
19012     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
19013     if( !pData ){
19014       shell_out_of_memory();
19015     }else{
19016       char **azCols = (char **)pData;      /* Names of result columns */
19017       char **azVals = &azCols[nCol];       /* Results */
19018       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
19019       int i, x;
19020       assert(sizeof(int) <= sizeof(char *));
19021       /* save off ptrs to column names */
19022       for(i=0; i<nCol; i++){
19023         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
19024       }
19025       do{
19026         nRow++;
19027         /* extract the data and data types */
19028         for(i=0; i<nCol; i++){
19029           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
19030           if( x==SQLITE_BLOB
19031            && pArg
19032            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
19033           ){
19034             azVals[i] = "";
19035           }else{
19036             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
19037           }
19038           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
19039             rc = SQLITE_NOMEM;
19040             break; /* from for */
19041           }
19042         } /* end for */
19043 
19044         /* if data and types extracted successfully... */
19045         if( SQLITE_ROW == rc ){
19046           /* call the supplied callback with the result row data */
19047           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
19048             rc = SQLITE_ABORT;
19049           }else{
19050             rc = sqlite3_step(pStmt);
19051           }
19052         }
19053       } while( SQLITE_ROW == rc );
19054       sqlite3_free(pData);
19055       if( pArg->cMode==MODE_Json ){
19056         fputs("]\n", pArg->out);
19057       }else if( pArg->cMode==MODE_Count ){
19058         char zBuf[200];
19059         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
19060                          nRow, nRow!=1 ? "s" : "");
19061         printf("%s", zBuf);
19062       }
19063     }
19064   }
19065 }
19066 
19067 #ifndef SQLITE_OMIT_VIRTUALTABLE
19068 /*
19069 ** This function is called to process SQL if the previous shell command
19070 ** was ".expert". It passes the SQL in the second argument directly to
19071 ** the sqlite3expert object.
19072 **
19073 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
19074 ** code. In this case, (*pzErr) may be set to point to a buffer containing
19075 ** an English language error message. It is the responsibility of the
19076 ** caller to eventually free this buffer using sqlite3_free().
19077 */
19078 static int expertHandleSQL(
19079   ShellState *pState,
19080   const char *zSql,
19081   char **pzErr
19082 ){
19083   assert( pState->expert.pExpert );
19084   assert( pzErr==0 || *pzErr==0 );
19085   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
19086 }
19087 
19088 /*
19089 ** This function is called either to silently clean up the object
19090 ** created by the ".expert" command (if bCancel==1), or to generate a
19091 ** report from it and then clean it up (if bCancel==0).
19092 **
19093 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
19094 ** code. In this case, (*pzErr) may be set to point to a buffer containing
19095 ** an English language error message. It is the responsibility of the
19096 ** caller to eventually free this buffer using sqlite3_free().
19097 */
19098 static int expertFinish(
19099   ShellState *pState,
19100   int bCancel,
19101   char **pzErr
19102 ){
19103   int rc = SQLITE_OK;
19104   sqlite3expert *p = pState->expert.pExpert;
19105   assert( p );
19106   assert( bCancel || pzErr==0 || *pzErr==0 );
19107   if( bCancel==0 ){
19108     FILE *out = pState->out;
19109     int bVerbose = pState->expert.bVerbose;
19110 
19111     rc = sqlite3_expert_analyze(p, pzErr);
19112     if( rc==SQLITE_OK ){
19113       int nQuery = sqlite3_expert_count(p);
19114       int i;
19115 
19116       if( bVerbose ){
19117         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
19118         raw_printf(out, "-- Candidates -----------------------------\n");
19119         raw_printf(out, "%s\n", zCand);
19120       }
19121       for(i=0; i<nQuery; i++){
19122         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
19123         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
19124         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
19125         if( zIdx==0 ) zIdx = "(no new indexes)\n";
19126         if( bVerbose ){
19127           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
19128           raw_printf(out, "%s\n\n", zSql);
19129         }
19130         raw_printf(out, "%s\n", zIdx);
19131         raw_printf(out, "%s\n", zEQP);
19132       }
19133     }
19134   }
19135   sqlite3_expert_destroy(p);
19136   pState->expert.pExpert = 0;
19137   return rc;
19138 }
19139 
19140 /*
19141 ** Implementation of ".expert" dot command.
19142 */
19143 static int expertDotCommand(
19144   ShellState *pState,             /* Current shell tool state */
19145   char **azArg,                   /* Array of arguments passed to dot command */
19146   int nArg                        /* Number of entries in azArg[] */
19147 ){
19148   int rc = SQLITE_OK;
19149   char *zErr = 0;
19150   int i;
19151   int iSample = 0;
19152 
19153   assert( pState->expert.pExpert==0 );
19154   memset(&pState->expert, 0, sizeof(ExpertInfo));
19155 
19156   for(i=1; rc==SQLITE_OK && i<nArg; i++){
19157     char *z = azArg[i];
19158     int n;
19159     if( z[0]=='-' && z[1]=='-' ) z++;
19160     n = strlen30(z);
19161     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
19162       pState->expert.bVerbose = 1;
19163     }
19164     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
19165       if( i==(nArg-1) ){
19166         raw_printf(stderr, "option requires an argument: %s\n", z);
19167         rc = SQLITE_ERROR;
19168       }else{
19169         iSample = (int)integerValue(azArg[++i]);
19170         if( iSample<0 || iSample>100 ){
19171           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
19172           rc = SQLITE_ERROR;
19173         }
19174       }
19175     }
19176     else{
19177       raw_printf(stderr, "unknown option: %s\n", z);
19178       rc = SQLITE_ERROR;
19179     }
19180   }
19181 
19182   if( rc==SQLITE_OK ){
19183     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
19184     if( pState->expert.pExpert==0 ){
19185       raw_printf(stderr, "sqlite3_expert_new: %s\n",
19186                  zErr ? zErr : "out of memory");
19187       rc = SQLITE_ERROR;
19188     }else{
19189       sqlite3_expert_config(
19190           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
19191       );
19192     }
19193   }
19194   sqlite3_free(zErr);
19195 
19196   return rc;
19197 }
19198 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
19199 
19200 /*
19201 ** Execute a statement or set of statements.  Print
19202 ** any result rows/columns depending on the current mode
19203 ** set via the supplied callback.
19204 **
19205 ** This is very similar to SQLite's built-in sqlite3_exec()
19206 ** function except it takes a slightly different callback
19207 ** and callback data argument.
19208 */
19209 static int shell_exec(
19210   ShellState *pArg,                         /* Pointer to ShellState */
19211   const char *zSql,                         /* SQL to be evaluated */
19212   char **pzErrMsg                           /* Error msg written here */
19213 ){
19214   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
19215   int rc = SQLITE_OK;             /* Return Code */
19216   int rc2;
19217   const char *zLeftover;          /* Tail of unprocessed SQL */
19218   sqlite3 *db = pArg->db;
19219 
19220   if( pzErrMsg ){
19221     *pzErrMsg = NULL;
19222   }
19223 
19224 #ifndef SQLITE_OMIT_VIRTUALTABLE
19225   if( pArg->expert.pExpert ){
19226     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
19227     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
19228   }
19229 #endif
19230 
19231   while( zSql[0] && (SQLITE_OK == rc) ){
19232     static const char *zStmtSql;
19233     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
19234     if( SQLITE_OK != rc ){
19235       if( pzErrMsg ){
19236         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
19237       }
19238     }else{
19239       if( !pStmt ){
19240         /* this happens for a comment or white-space */
19241         zSql = zLeftover;
19242         while( IsSpace(zSql[0]) ) zSql++;
19243         continue;
19244       }
19245       zStmtSql = sqlite3_sql(pStmt);
19246       if( zStmtSql==0 ) zStmtSql = "";
19247       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
19248 
19249       /* save off the prepared statment handle and reset row count */
19250       if( pArg ){
19251         pArg->pStmt = pStmt;
19252         pArg->cnt = 0;
19253       }
19254 
19255       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
19256       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
19257         sqlite3_stmt *pExplain;
19258         char *zEQP;
19259         int triggerEQP = 0;
19260         disable_debug_trace_modes();
19261         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
19262         if( pArg->autoEQP>=AUTOEQP_trigger ){
19263           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
19264         }
19265         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
19266         shell_check_oom(zEQP);
19267         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
19268         if( rc==SQLITE_OK ){
19269           while( sqlite3_step(pExplain)==SQLITE_ROW ){
19270             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
19271             int iEqpId = sqlite3_column_int(pExplain, 0);
19272             int iParentId = sqlite3_column_int(pExplain, 1);
19273             if( zEQPLine==0 ) zEQPLine = "";
19274             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
19275             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
19276           }
19277           eqp_render(pArg, 0);
19278         }
19279         sqlite3_finalize(pExplain);
19280         sqlite3_free(zEQP);
19281         if( pArg->autoEQP>=AUTOEQP_full ){
19282           /* Also do an EXPLAIN for ".eqp full" mode */
19283           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
19284           shell_check_oom(zEQP);
19285           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
19286           if( rc==SQLITE_OK ){
19287             pArg->cMode = MODE_Explain;
19288             explain_data_prepare(pArg, pExplain);
19289             exec_prepared_stmt(pArg, pExplain);
19290             explain_data_delete(pArg);
19291           }
19292           sqlite3_finalize(pExplain);
19293           sqlite3_free(zEQP);
19294         }
19295         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
19296           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
19297           /* Reprepare pStmt before reactiving trace modes */
19298           sqlite3_finalize(pStmt);
19299           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
19300           if( pArg ) pArg->pStmt = pStmt;
19301         }
19302         restore_debug_trace_modes();
19303       }
19304 
19305       if( pArg ){
19306         pArg->cMode = pArg->mode;
19307         if( pArg->autoExplain ){
19308           if( sqlite3_stmt_isexplain(pStmt)==1 ){
19309             pArg->cMode = MODE_Explain;
19310           }
19311           if( sqlite3_stmt_isexplain(pStmt)==2 ){
19312             pArg->cMode = MODE_EQP;
19313           }
19314         }
19315 
19316         /* If the shell is currently in ".explain" mode, gather the extra
19317         ** data required to add indents to the output.*/
19318         if( pArg->cMode==MODE_Explain ){
19319           explain_data_prepare(pArg, pStmt);
19320         }
19321       }
19322 
19323       bind_prepared_stmt(pArg, pStmt);
19324       exec_prepared_stmt(pArg, pStmt);
19325       explain_data_delete(pArg);
19326       eqp_render(pArg, 0);
19327 
19328       /* print usage stats if stats on */
19329       if( pArg && pArg->statsOn ){
19330         display_stats(db, pArg, 0);
19331       }
19332 
19333       /* print loop-counters if required */
19334       if( pArg && pArg->scanstatsOn ){
19335         display_scanstats(db, pArg);
19336       }
19337 
19338       /* Finalize the statement just executed. If this fails, save a
19339       ** copy of the error message. Otherwise, set zSql to point to the
19340       ** next statement to execute. */
19341       rc2 = sqlite3_finalize(pStmt);
19342       if( rc!=SQLITE_NOMEM ) rc = rc2;
19343       if( rc==SQLITE_OK ){
19344         zSql = zLeftover;
19345         while( IsSpace(zSql[0]) ) zSql++;
19346       }else if( pzErrMsg ){
19347         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
19348       }
19349 
19350       /* clear saved stmt handle */
19351       if( pArg ){
19352         pArg->pStmt = NULL;
19353       }
19354     }
19355   } /* end while */
19356 
19357   return rc;
19358 }
19359 
19360 /*
19361 ** Release memory previously allocated by tableColumnList().
19362 */
19363 static void freeColumnList(char **azCol){
19364   int i;
19365   for(i=1; azCol[i]; i++){
19366     sqlite3_free(azCol[i]);
19367   }
19368   /* azCol[0] is a static string */
19369   sqlite3_free(azCol);
19370 }
19371 
19372 /*
19373 ** Return a list of pointers to strings which are the names of all
19374 ** columns in table zTab.   The memory to hold the names is dynamically
19375 ** allocated and must be released by the caller using a subsequent call
19376 ** to freeColumnList().
19377 **
19378 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
19379 ** value that needs to be preserved, then azCol[0] is filled in with the
19380 ** name of the rowid column.
19381 **
19382 ** The first regular column in the table is azCol[1].  The list is terminated
19383 ** by an entry with azCol[i]==0.
19384 */
19385 static char **tableColumnList(ShellState *p, const char *zTab){
19386   char **azCol = 0;
19387   sqlite3_stmt *pStmt;
19388   char *zSql;
19389   int nCol = 0;
19390   int nAlloc = 0;
19391   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
19392   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
19393   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
19394   int rc;
19395 
19396   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
19397   shell_check_oom(zSql);
19398   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19399   sqlite3_free(zSql);
19400   if( rc ) return 0;
19401   while( sqlite3_step(pStmt)==SQLITE_ROW ){
19402     if( nCol>=nAlloc-2 ){
19403       nAlloc = nAlloc*2 + nCol + 10;
19404       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
19405       shell_check_oom(azCol);
19406     }
19407     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
19408     shell_check_oom(azCol[nCol]);
19409     if( sqlite3_column_int(pStmt, 5) ){
19410       nPK++;
19411       if( nPK==1
19412        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
19413                           "INTEGER")==0
19414       ){
19415         isIPK = 1;
19416       }else{
19417         isIPK = 0;
19418       }
19419     }
19420   }
19421   sqlite3_finalize(pStmt);
19422   if( azCol==0 ) return 0;
19423   azCol[0] = 0;
19424   azCol[nCol+1] = 0;
19425 
19426   /* The decision of whether or not a rowid really needs to be preserved
19427   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
19428   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
19429   ** rowids on tables where the rowid is inaccessible because there are other
19430   ** columns in the table named "rowid", "_rowid_", and "oid".
19431   */
19432   if( preserveRowid && isIPK ){
19433     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
19434     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
19435     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
19436     ** ROWID aliases.  To distinguish these cases, check to see if
19437     ** there is a "pk" entry in "PRAGMA index_list".  There will be
19438     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
19439     */
19440     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
19441                            " WHERE origin='pk'", zTab);
19442     shell_check_oom(zSql);
19443     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19444     sqlite3_free(zSql);
19445     if( rc ){
19446       freeColumnList(azCol);
19447       return 0;
19448     }
19449     rc = sqlite3_step(pStmt);
19450     sqlite3_finalize(pStmt);
19451     preserveRowid = rc==SQLITE_ROW;
19452   }
19453   if( preserveRowid ){
19454     /* Only preserve the rowid if we can find a name to use for the
19455     ** rowid */
19456     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
19457     int i, j;
19458     for(j=0; j<3; j++){
19459       for(i=1; i<=nCol; i++){
19460         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
19461       }
19462       if( i>nCol ){
19463         /* At this point, we know that azRowid[j] is not the name of any
19464         ** ordinary column in the table.  Verify that azRowid[j] is a valid
19465         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
19466         ** tables will fail this last check */
19467         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
19468         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
19469         break;
19470       }
19471     }
19472   }
19473   return azCol;
19474 }
19475 
19476 /*
19477 ** Toggle the reverse_unordered_selects setting.
19478 */
19479 static void toggleSelectOrder(sqlite3 *db){
19480   sqlite3_stmt *pStmt = 0;
19481   int iSetting = 0;
19482   char zStmt[100];
19483   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
19484   if( sqlite3_step(pStmt)==SQLITE_ROW ){
19485     iSetting = sqlite3_column_int(pStmt, 0);
19486   }
19487   sqlite3_finalize(pStmt);
19488   sqlite3_snprintf(sizeof(zStmt), zStmt,
19489        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
19490   sqlite3_exec(db, zStmt, 0, 0, 0);
19491 }
19492 
19493 /*
19494 ** This is a different callback routine used for dumping the database.
19495 ** Each row received by this callback consists of a table name,
19496 ** the table type ("index" or "table") and SQL to create the table.
19497 ** This routine should print text sufficient to recreate the table.
19498 */
19499 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
19500   int rc;
19501   const char *zTable;
19502   const char *zType;
19503   const char *zSql;
19504   ShellState *p = (ShellState *)pArg;
19505   int dataOnly;
19506   int noSys;
19507 
19508   UNUSED_PARAMETER(azNotUsed);
19509   if( nArg!=3 || azArg==0 ) return 0;
19510   zTable = azArg[0];
19511   zType = azArg[1];
19512   zSql = azArg[2];
19513   if( zTable==0 ) return 0;
19514   if( zType==0 ) return 0;
19515   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
19516   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
19517 
19518   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
19519     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
19520   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
19521     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19522   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
19523     return 0;
19524   }else if( dataOnly ){
19525     /* no-op */
19526   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
19527     char *zIns;
19528     if( !p->writableSchema ){
19529       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
19530       p->writableSchema = 1;
19531     }
19532     zIns = sqlite3_mprintf(
19533        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
19534        "VALUES('table','%q','%q',0,'%q');",
19535        zTable, zTable, zSql);
19536     shell_check_oom(zIns);
19537     utf8_printf(p->out, "%s\n", zIns);
19538     sqlite3_free(zIns);
19539     return 0;
19540   }else{
19541     printSchemaLine(p->out, zSql, ";\n");
19542   }
19543 
19544   if( cli_strcmp(zType, "table")==0 ){
19545     ShellText sSelect;
19546     ShellText sTable;
19547     char **azCol;
19548     int i;
19549     char *savedDestTable;
19550     int savedMode;
19551 
19552     azCol = tableColumnList(p, zTable);
19553     if( azCol==0 ){
19554       p->nErr++;
19555       return 0;
19556     }
19557 
19558     /* Always quote the table name, even if it appears to be pure ascii,
19559     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
19560     initText(&sTable);
19561     appendText(&sTable, zTable, quoteChar(zTable));
19562     /* If preserving the rowid, add a column list after the table name.
19563     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
19564     ** instead of the usual "INSERT INTO tab VALUES(...)".
19565     */
19566     if( azCol[0] ){
19567       appendText(&sTable, "(", 0);
19568       appendText(&sTable, azCol[0], 0);
19569       for(i=1; azCol[i]; i++){
19570         appendText(&sTable, ",", 0);
19571         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
19572       }
19573       appendText(&sTable, ")", 0);
19574     }
19575 
19576     /* Build an appropriate SELECT statement */
19577     initText(&sSelect);
19578     appendText(&sSelect, "SELECT ", 0);
19579     if( azCol[0] ){
19580       appendText(&sSelect, azCol[0], 0);
19581       appendText(&sSelect, ",", 0);
19582     }
19583     for(i=1; azCol[i]; i++){
19584       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
19585       if( azCol[i+1] ){
19586         appendText(&sSelect, ",", 0);
19587       }
19588     }
19589     freeColumnList(azCol);
19590     appendText(&sSelect, " FROM ", 0);
19591     appendText(&sSelect, zTable, quoteChar(zTable));
19592 
19593     savedDestTable = p->zDestTable;
19594     savedMode = p->mode;
19595     p->zDestTable = sTable.z;
19596     p->mode = p->cMode = MODE_Insert;
19597     rc = shell_exec(p, sSelect.z, 0);
19598     if( (rc&0xff)==SQLITE_CORRUPT ){
19599       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
19600       toggleSelectOrder(p->db);
19601       shell_exec(p, sSelect.z, 0);
19602       toggleSelectOrder(p->db);
19603     }
19604     p->zDestTable = savedDestTable;
19605     p->mode = savedMode;
19606     freeText(&sTable);
19607     freeText(&sSelect);
19608     if( rc ) p->nErr++;
19609   }
19610   return 0;
19611 }
19612 
19613 /*
19614 ** Run zQuery.  Use dump_callback() as the callback routine so that
19615 ** the contents of the query are output as SQL statements.
19616 **
19617 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
19618 ** "ORDER BY rowid DESC" to the end.
19619 */
19620 static int run_schema_dump_query(
19621   ShellState *p,
19622   const char *zQuery
19623 ){
19624   int rc;
19625   char *zErr = 0;
19626   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
19627   if( rc==SQLITE_CORRUPT ){
19628     char *zQ2;
19629     int len = strlen30(zQuery);
19630     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
19631     if( zErr ){
19632       utf8_printf(p->out, "/****** %s ******/\n", zErr);
19633       sqlite3_free(zErr);
19634       zErr = 0;
19635     }
19636     zQ2 = malloc( len+100 );
19637     if( zQ2==0 ) return rc;
19638     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
19639     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
19640     if( rc ){
19641       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
19642     }else{
19643       rc = SQLITE_CORRUPT;
19644     }
19645     sqlite3_free(zErr);
19646     free(zQ2);
19647   }
19648   return rc;
19649 }
19650 
19651 /*
19652 ** Text of help messages.
19653 **
19654 ** The help text for each individual command begins with a line that starts
19655 ** with ".".  Subsequent lines are supplemental information.
19656 **
19657 ** There must be two or more spaces between the end of the command and the
19658 ** start of the description of what that command does.
19659 */
19660 static const char *(azHelp[]) = {
19661 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
19662   && !defined(SQLITE_SHELL_FIDDLE)
19663   ".archive ...             Manage SQL archives",
19664   "   Each command must have exactly one of the following options:",
19665   "     -c, --create               Create a new archive",
19666   "     -u, --update               Add or update files with changed mtime",
19667   "     -i, --insert               Like -u but always add even if unchanged",
19668   "     -r, --remove               Remove files from archive",
19669   "     -t, --list                 List contents of archive",
19670   "     -x, --extract              Extract files from archive",
19671   "   Optional arguments:",
19672   "     -v, --verbose              Print each filename as it is processed",
19673   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
19674   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
19675   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
19676   "     -g, --glob                 Use glob matching for names in archive",
19677   "     -n, --dryrun               Show the SQL that would have occurred",
19678   "   Examples:",
19679   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
19680   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
19681   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
19682   "   See also:",
19683   "      http://sqlite.org/cli.html#sqlite_archive_support",
19684 #endif
19685 #ifndef SQLITE_OMIT_AUTHORIZATION
19686   ".auth ON|OFF             Show authorizer callbacks",
19687 #endif
19688 #ifndef SQLITE_SHELL_FIDDLE
19689   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
19690   "   Options:",
19691   "       --append            Use the appendvfs",
19692   "       --async             Write to FILE without journal and fsync()",
19693 #endif
19694   ".bail on|off             Stop after hitting an error.  Default OFF",
19695   ".binary on|off           Turn binary output on or off.  Default OFF",
19696 #ifndef SQLITE_SHELL_FIDDLE
19697   ".cd DIRECTORY            Change the working directory to DIRECTORY",
19698 #endif
19699   ".changes on|off          Show number of rows changed by SQL",
19700 #ifndef SQLITE_SHELL_FIDDLE
19701   ".check GLOB              Fail if output since .testcase does not match",
19702   ".clone NEWDB             Clone data into NEWDB from the existing database",
19703 #endif
19704   ".connection [close] [#]  Open or close an auxiliary database connection",
19705   ".databases               List names and files of attached databases",
19706   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
19707 #if SQLITE_SHELL_HAVE_RECOVER
19708   ".dbinfo ?DB?             Show status information about the database",
19709 #endif
19710   ".dump ?OBJECTS?          Render database content as SQL",
19711   "   Options:",
19712   "     --data-only            Output only INSERT statements",
19713   "     --newlines             Allow unescaped newline characters in output",
19714   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
19715   "     --preserve-rowids      Include ROWID values in the output",
19716   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
19717   "   Additional LIKE patterns can be given in subsequent arguments",
19718   ".echo on|off             Turn command echo on or off",
19719   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
19720   "   Other Modes:",
19721 #ifdef SQLITE_DEBUG
19722   "      test                  Show raw EXPLAIN QUERY PLAN output",
19723   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
19724 #endif
19725   "      trigger               Like \"full\" but also show trigger bytecode",
19726 #ifndef SQLITE_SHELL_FIDDLE
19727   ".excel                   Display the output of next command in spreadsheet",
19728   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
19729 #endif
19730 #ifndef SQLITE_SHELL_FIDDLE
19731   ".exit ?CODE?             Exit this program with return-code CODE",
19732 #endif
19733   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
19734   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
19735   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
19736   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
19737   "   --help                  Show CMD details",
19738   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
19739   ".headers on|off          Turn display of headers on or off",
19740   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
19741 #ifndef SQLITE_SHELL_FIDDLE
19742   ".import FILE TABLE       Import data from FILE into TABLE",
19743   "   Options:",
19744   "     --ascii               Use \\037 and \\036 as column and row separators",
19745   "     --csv                 Use , and \\n as column and row separators",
19746   "     --skip N              Skip the first N rows of input",
19747   "     --schema S            Target table to be S.TABLE",
19748   "     -v                    \"Verbose\" - increase auxiliary output",
19749   "   Notes:",
19750   "     *  If TABLE does not exist, it is created.  The first row of input",
19751   "        determines the column names.",
19752   "     *  If neither --csv or --ascii are used, the input mode is derived",
19753   "        from the \".mode\" output mode",
19754   "     *  If FILE begins with \"|\" then it is a command that generates the",
19755   "        input text.",
19756 #endif
19757 #ifndef SQLITE_OMIT_TEST_CONTROL
19758   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
19759 #endif
19760   ".indexes ?TABLE?         Show names of indexes",
19761   "                           If TABLE is specified, only show indexes for",
19762   "                           tables matching TABLE using the LIKE operator.",
19763 #ifdef SQLITE_ENABLE_IOTRACE
19764   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
19765 #endif
19766   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
19767   ".lint OPTIONS            Report potential schema issues.",
19768   "     Options:",
19769   "        fkey-indexes     Find missing foreign key indexes",
19770 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
19771   ".load FILE ?ENTRY?       Load an extension library",
19772 #endif
19773 #ifndef SQLITE_SHELL_FIDDLE
19774   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
19775 #endif
19776   ".mode MODE ?OPTIONS?     Set output mode",
19777   "   MODE is one of:",
19778   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
19779   "     box         Tables using unicode box-drawing characters",
19780   "     csv         Comma-separated values",
19781   "     column      Output in columns.  (See .width)",
19782   "     html        HTML <table> code",
19783   "     insert      SQL insert statements for TABLE",
19784   "     json        Results in a JSON array",
19785   "     line        One value per line",
19786   "     list        Values delimited by \"|\"",
19787   "     markdown    Markdown table format",
19788   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
19789   "     quote       Escape answers as for SQL",
19790   "     table       ASCII-art table",
19791   "     tabs        Tab-separated values",
19792   "     tcl         TCL list elements",
19793   "   OPTIONS: (for columnar modes or insert mode):",
19794   "     --wrap N       Wrap output lines to no longer than N characters",
19795   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
19796   "     --ww           Shorthand for \"--wordwrap 1\"",
19797   "     --quote        Quote output text as SQL literals",
19798   "     --noquote      Do not quote output text",
19799   "     TABLE          The name of SQL table used for \"insert\" mode",
19800 #ifndef SQLITE_SHELL_FIDDLE
19801   ".nonce STRING            Suspend safe mode for one command if nonce matches",
19802 #endif
19803   ".nullvalue STRING        Use STRING in place of NULL values",
19804 #ifndef SQLITE_SHELL_FIDDLE
19805   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
19806   "     If FILE begins with '|' then open as a pipe",
19807   "       --bom  Put a UTF8 byte-order mark at the beginning",
19808   "       -e     Send output to the system text editor",
19809   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
19810   /* Note that .open is (partially) available in WASM builds but is
19811   ** currently only intended to be used by the fiddle tool, not
19812   ** end users, so is "undocumented." */
19813   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
19814   "     Options:",
19815   "        --append        Use appendvfs to append database to the end of FILE",
19816 #endif
19817 #ifndef SQLITE_OMIT_DESERIALIZE
19818   "        --deserialize   Load into memory using sqlite3_deserialize()",
19819   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
19820   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
19821 #endif
19822   "        --new           Initialize FILE to an empty database",
19823   "        --nofollow      Do not follow symbolic links",
19824   "        --readonly      Open FILE readonly",
19825   "        --zip           FILE is a ZIP archive",
19826 #ifndef SQLITE_SHELL_FIDDLE
19827   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
19828   "   If FILE begins with '|' then open it as a pipe.",
19829   "   Options:",
19830   "     --bom                 Prefix output with a UTF8 byte-order mark",
19831   "     -e                    Send output to the system text editor",
19832   "     -x                    Send output as CSV to a spreadsheet",
19833 #endif
19834   ".parameter CMD ...       Manage SQL parameter bindings",
19835   "   clear                   Erase all bindings",
19836   "   init                    Initialize the TEMP table that holds bindings",
19837   "   list                    List the current parameter bindings",
19838   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
19839   "                           PARAMETER should start with one of: $ : @ ?",
19840   "   unset PARAMETER         Remove PARAMETER from the binding table",
19841   ".print STRING...         Print literal STRING",
19842 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19843   ".progress N              Invoke progress handler after every N opcodes",
19844   "   --limit N                 Interrupt after N progress callbacks",
19845   "   --once                    Do no more than one progress interrupt",
19846   "   --quiet|-q                No output except at interrupts",
19847   "   --reset                   Reset the count for each input and interrupt",
19848 #endif
19849   ".prompt MAIN CONTINUE    Replace the standard prompts",
19850 #ifndef SQLITE_SHELL_FIDDLE
19851   ".quit                    Stop interpreting input stream, exit if primary.",
19852   ".read FILE               Read input from FILE or command output",
19853   "    If FILE begins with \"|\", it is a command that generates the input.",
19854 #endif
19855 #if SQLITE_SHELL_HAVE_RECOVER
19856   ".recover                 Recover as much data as possible from corrupt db.",
19857   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
19858   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
19859   "   --no-rowids              Do not attempt to recover rowid values",
19860   "                            that are not also INTEGER PRIMARY KEYs",
19861 #endif
19862 #ifndef SQLITE_SHELL_FIDDLE
19863   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
19864   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
19865 #endif
19866   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
19867   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
19868   "   Options:",
19869   "      --indent             Try to pretty-print the schema",
19870   "      --nosys              Omit objects whose names start with \"sqlite_\"",
19871   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
19872   "    Options:",
19873   "       --init               Create a new SELFTEST table",
19874   "       -v                   Verbose output",
19875   ".separator COL ?ROW?     Change the column and row separators",
19876 #if defined(SQLITE_ENABLE_SESSION)
19877   ".session ?NAME? CMD ...  Create or control sessions",
19878   "   Subcommands:",
19879   "     attach TABLE             Attach TABLE",
19880   "     changeset FILE           Write a changeset into FILE",
19881   "     close                    Close one session",
19882   "     enable ?BOOLEAN?         Set or query the enable bit",
19883   "     filter GLOB...           Reject tables matching GLOBs",
19884   "     indirect ?BOOLEAN?       Mark or query the indirect status",
19885   "     isempty                  Query whether the session is empty",
19886   "     list                     List currently open session names",
19887   "     open DB NAME             Open a new session on DB",
19888   "     patchset FILE            Write a patchset into FILE",
19889   "   If ?NAME? is omitted, the first defined session is used.",
19890 #endif
19891   ".sha3sum ...             Compute a SHA3 hash of database content",
19892   "    Options:",
19893   "      --schema              Also hash the sqlite_schema table",
19894   "      --sha3-224            Use the sha3-224 algorithm",
19895   "      --sha3-256            Use the sha3-256 algorithm (default)",
19896   "      --sha3-384            Use the sha3-384 algorithm",
19897   "      --sha3-512            Use the sha3-512 algorithm",
19898   "    Any other argument is a LIKE pattern for tables to hash",
19899 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
19900   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
19901 #endif
19902   ".show                    Show the current values for various settings",
19903   ".stats ?ARG?             Show stats or turn stats on or off",
19904   "   off                      Turn off automatic stat display",
19905   "   on                       Turn on automatic stat display",
19906   "   stmt                     Show statement stats",
19907   "   vmstep                   Show the virtual machine step count only",
19908 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
19909   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
19910 #endif
19911   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
19912 #ifndef SQLITE_SHELL_FIDDLE
19913   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
19914 #endif
19915   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
19916   "                           Run \".testctrl\" with no arguments for details",
19917   ".timeout MS              Try opening locked tables for MS milliseconds",
19918   ".timer on|off            Turn SQL timer on or off",
19919 #ifndef SQLITE_OMIT_TRACE
19920   ".trace ?OPTIONS?         Output each SQL statement as it is run",
19921   "    FILE                    Send output to FILE",
19922   "    stdout                  Send output to stdout",
19923   "    stderr                  Send output to stderr",
19924   "    off                     Disable tracing",
19925   "    --expanded              Expand query parameters",
19926 #ifdef SQLITE_ENABLE_NORMALIZE
19927   "    --normalized            Normal the SQL statements",
19928 #endif
19929   "    --plain                 Show SQL as it is input",
19930   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
19931   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
19932   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
19933   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
19934 #endif /* SQLITE_OMIT_TRACE */
19935 #ifdef SQLITE_DEBUG
19936   ".unmodule NAME ...       Unregister virtual table modules",
19937   "    --allexcept             Unregister everything except those named",
19938 #endif
19939   ".version                 Show source, library and compiler versions",
19940   ".vfsinfo ?AUX?           Information about the top-level VFS",
19941   ".vfslist                 List all available VFSes",
19942   ".vfsname ?AUX?           Print the name of the VFS stack",
19943   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
19944   "     Negative values right-justify",
19945 };
19946 
19947 /*
19948 ** Output help text.
19949 **
19950 ** zPattern describes the set of commands for which help text is provided.
19951 ** If zPattern is NULL, then show all commands, but only give a one-line
19952 ** description of each.
19953 **
19954 ** Return the number of matches.
19955 */
19956 static int showHelp(FILE *out, const char *zPattern){
19957   int i = 0;
19958   int j = 0;
19959   int n = 0;
19960   char *zPat;
19961   if( zPattern==0
19962    || zPattern[0]=='0'
19963    || cli_strcmp(zPattern,"-a")==0
19964    || cli_strcmp(zPattern,"-all")==0
19965    || cli_strcmp(zPattern,"--all")==0
19966   ){
19967     /* Show all commands, but only one line per command */
19968     if( zPattern==0 ) zPattern = "";
19969     for(i=0; i<ArraySize(azHelp); i++){
19970       if( azHelp[i][0]=='.' || zPattern[0] ){
19971         utf8_printf(out, "%s\n", azHelp[i]);
19972         n++;
19973       }
19974     }
19975   }else{
19976     /* Look for commands that for which zPattern is an exact prefix */
19977     zPat = sqlite3_mprintf(".%s*", zPattern);
19978     shell_check_oom(zPat);
19979     for(i=0; i<ArraySize(azHelp); i++){
19980       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
19981         utf8_printf(out, "%s\n", azHelp[i]);
19982         j = i+1;
19983         n++;
19984       }
19985     }
19986     sqlite3_free(zPat);
19987     if( n ){
19988       if( n==1 ){
19989         /* when zPattern is a prefix of exactly one command, then include the
19990         ** details of that command, which should begin at offset j */
19991         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
19992           utf8_printf(out, "%s\n", azHelp[j]);
19993           j++;
19994         }
19995       }
19996       return n;
19997     }
19998     /* Look for commands that contain zPattern anywhere.  Show the complete
19999     ** text of all commands that match. */
20000     zPat = sqlite3_mprintf("%%%s%%", zPattern);
20001     shell_check_oom(zPat);
20002     for(i=0; i<ArraySize(azHelp); i++){
20003       if( azHelp[i][0]=='.' ) j = i;
20004       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
20005         utf8_printf(out, "%s\n", azHelp[j]);
20006         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
20007           j++;
20008           utf8_printf(out, "%s\n", azHelp[j]);
20009         }
20010         i = j;
20011         n++;
20012       }
20013     }
20014     sqlite3_free(zPat);
20015   }
20016   return n;
20017 }
20018 
20019 /* Forward reference */
20020 static int process_input(ShellState *p);
20021 
20022 /*
20023 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
20024 ** and return a pointer to the buffer. The caller is responsible for freeing
20025 ** the memory.
20026 **
20027 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
20028 ** read.
20029 **
20030 ** For convenience, a nul-terminator byte is always appended to the data read
20031 ** from the file before the buffer is returned. This byte is not included in
20032 ** the final value of (*pnByte), if applicable.
20033 **
20034 ** NULL is returned if any error is encountered. The final value of *pnByte
20035 ** is undefined in this case.
20036 */
20037 static char *readFile(const char *zName, int *pnByte){
20038   FILE *in = fopen(zName, "rb");
20039   long nIn;
20040   size_t nRead;
20041   char *pBuf;
20042   if( in==0 ) return 0;
20043   fseek(in, 0, SEEK_END);
20044   nIn = ftell(in);
20045   rewind(in);
20046   pBuf = sqlite3_malloc64( nIn+1 );
20047   if( pBuf==0 ){ fclose(in); return 0; }
20048   nRead = fread(pBuf, nIn, 1, in);
20049   fclose(in);
20050   if( nRead!=1 ){
20051     sqlite3_free(pBuf);
20052     return 0;
20053   }
20054   pBuf[nIn] = 0;
20055   if( pnByte ) *pnByte = nIn;
20056   return pBuf;
20057 }
20058 
20059 #if defined(SQLITE_ENABLE_SESSION)
20060 /*
20061 ** Close a single OpenSession object and release all of its associated
20062 ** resources.
20063 */
20064 static void session_close(OpenSession *pSession){
20065   int i;
20066   sqlite3session_delete(pSession->p);
20067   sqlite3_free(pSession->zName);
20068   for(i=0; i<pSession->nFilter; i++){
20069     sqlite3_free(pSession->azFilter[i]);
20070   }
20071   sqlite3_free(pSession->azFilter);
20072   memset(pSession, 0, sizeof(OpenSession));
20073 }
20074 #endif
20075 
20076 /*
20077 ** Close all OpenSession objects and release all associated resources.
20078 */
20079 #if defined(SQLITE_ENABLE_SESSION)
20080 static void session_close_all(ShellState *p, int i){
20081   int j;
20082   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
20083   for(j=0; j<pAuxDb->nSession; j++){
20084     session_close(&pAuxDb->aSession[j]);
20085   }
20086   pAuxDb->nSession = 0;
20087 }
20088 #else
20089 # define session_close_all(X,Y)
20090 #endif
20091 
20092 /*
20093 ** Implementation of the xFilter function for an open session.  Omit
20094 ** any tables named by ".session filter" but let all other table through.
20095 */
20096 #if defined(SQLITE_ENABLE_SESSION)
20097 static int session_filter(void *pCtx, const char *zTab){
20098   OpenSession *pSession = (OpenSession*)pCtx;
20099   int i;
20100   for(i=0; i<pSession->nFilter; i++){
20101     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
20102   }
20103   return 1;
20104 }
20105 #endif
20106 
20107 /*
20108 ** Try to deduce the type of file for zName based on its content.  Return
20109 ** one of the SHELL_OPEN_* constants.
20110 **
20111 ** If the file does not exist or is empty but its name looks like a ZIP
20112 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
20113 ** Otherwise, assume an ordinary database regardless of the filename if
20114 ** the type cannot be determined from content.
20115 */
20116 int deduceDatabaseType(const char *zName, int dfltZip){
20117   FILE *f = fopen(zName, "rb");
20118   size_t n;
20119   int rc = SHELL_OPEN_UNSPEC;
20120   char zBuf[100];
20121   if( f==0 ){
20122     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
20123        return SHELL_OPEN_ZIPFILE;
20124     }else{
20125        return SHELL_OPEN_NORMAL;
20126     }
20127   }
20128   n = fread(zBuf, 16, 1, f);
20129   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
20130     fclose(f);
20131     return SHELL_OPEN_NORMAL;
20132   }
20133   fseek(f, -25, SEEK_END);
20134   n = fread(zBuf, 25, 1, f);
20135   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
20136     rc = SHELL_OPEN_APPENDVFS;
20137   }else{
20138     fseek(f, -22, SEEK_END);
20139     n = fread(zBuf, 22, 1, f);
20140     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
20141        && zBuf[3]==0x06 ){
20142       rc = SHELL_OPEN_ZIPFILE;
20143     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
20144       rc = SHELL_OPEN_ZIPFILE;
20145     }
20146   }
20147   fclose(f);
20148   return rc;
20149 }
20150 
20151 #ifndef SQLITE_OMIT_DESERIALIZE
20152 /*
20153 ** Reconstruct an in-memory database using the output from the "dbtotxt"
20154 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
20155 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
20156 */
20157 static unsigned char *readHexDb(ShellState *p, int *pnData){
20158   unsigned char *a = 0;
20159   int nLine;
20160   int n = 0;
20161   int pgsz = 0;
20162   int iOffset = 0;
20163   int j, k;
20164   int rc;
20165   FILE *in;
20166   const char *zDbFilename = p->pAuxDb->zDbFilename;
20167   unsigned int x[16];
20168   char zLine[1000];
20169   if( zDbFilename ){
20170     in = fopen(zDbFilename, "r");
20171     if( in==0 ){
20172       utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
20173       return 0;
20174     }
20175     nLine = 0;
20176   }else{
20177     in = p->in;
20178     nLine = p->lineno;
20179     if( in==0 ) in = stdin;
20180   }
20181   *pnData = 0;
20182   nLine++;
20183   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
20184   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
20185   if( rc!=2 ) goto readHexDb_error;
20186   if( n<0 ) goto readHexDb_error;
20187   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
20188   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
20189   a = sqlite3_malloc( n ? n : 1 );
20190   shell_check_oom(a);
20191   memset(a, 0, n);
20192   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
20193     utf8_printf(stderr, "invalid pagesize\n");
20194     goto readHexDb_error;
20195   }
20196   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
20197     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
20198     if( rc==2 ){
20199       iOffset = k;
20200       continue;
20201     }
20202     if( cli_strncmp(zLine, "| end ", 6)==0 ){
20203       break;
20204     }
20205     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
20206                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
20207                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
20208     if( rc==17 ){
20209       k = iOffset+j;
20210       if( k+16<=n && k>=0 ){
20211         int ii;
20212         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
20213       }
20214     }
20215   }
20216   *pnData = n;
20217   if( in!=p->in ){
20218     fclose(in);
20219   }else{
20220     p->lineno = nLine;
20221   }
20222   return a;
20223 
20224 readHexDb_error:
20225   if( in!=p->in ){
20226     fclose(in);
20227   }else{
20228     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
20229       nLine++;
20230       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
20231     }
20232     p->lineno = nLine;
20233   }
20234   sqlite3_free(a);
20235   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
20236   return 0;
20237 }
20238 #endif /* SQLITE_OMIT_DESERIALIZE */
20239 
20240 /*
20241 ** Scalar function "shell_int32". The first argument to this function
20242 ** must be a blob. The second a non-negative integer. This function
20243 ** reads and returns a 32-bit big-endian integer from byte
20244 ** offset (4*<arg2>) of the blob.
20245 */
20246 static void shellInt32(
20247   sqlite3_context *context,
20248   int argc,
20249   sqlite3_value **argv
20250 ){
20251   const unsigned char *pBlob;
20252   int nBlob;
20253   int iInt;
20254 
20255   UNUSED_PARAMETER(argc);
20256   nBlob = sqlite3_value_bytes(argv[0]);
20257   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
20258   iInt = sqlite3_value_int(argv[1]);
20259 
20260   if( iInt>=0 && (iInt+1)*4<=nBlob ){
20261     const unsigned char *a = &pBlob[iInt*4];
20262     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
20263                        + ((sqlite3_int64)a[1]<<16)
20264                        + ((sqlite3_int64)a[2]<< 8)
20265                        + ((sqlite3_int64)a[3]<< 0);
20266     sqlite3_result_int64(context, iVal);
20267   }
20268 }
20269 
20270 /*
20271 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
20272 ** using "..." with internal double-quote characters doubled.
20273 */
20274 static void shellIdQuote(
20275   sqlite3_context *context,
20276   int argc,
20277   sqlite3_value **argv
20278 ){
20279   const char *zName = (const char*)sqlite3_value_text(argv[0]);
20280   UNUSED_PARAMETER(argc);
20281   if( zName ){
20282     char *z = sqlite3_mprintf("\"%w\"", zName);
20283     sqlite3_result_text(context, z, -1, sqlite3_free);
20284   }
20285 }
20286 
20287 /*
20288 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
20289 */
20290 static void shellUSleepFunc(
20291   sqlite3_context *context,
20292   int argcUnused,
20293   sqlite3_value **argv
20294 ){
20295   int sleep = sqlite3_value_int(argv[0]);
20296   (void)argcUnused;
20297   sqlite3_sleep(sleep/1000);
20298   sqlite3_result_int(context, sleep);
20299 }
20300 
20301 /*
20302 ** Scalar function "shell_escape_crnl" used by the .recover command.
20303 ** The argument passed to this function is the output of built-in
20304 ** function quote(). If the first character of the input is "'",
20305 ** indicating that the value passed to quote() was a text value,
20306 ** then this function searches the input for "\n" and "\r" characters
20307 ** and adds a wrapper similar to the following:
20308 **
20309 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
20310 **
20311 ** Or, if the first character of the input is not "'", then a copy
20312 ** of the input is returned.
20313 */
20314 static void shellEscapeCrnl(
20315   sqlite3_context *context,
20316   int argc,
20317   sqlite3_value **argv
20318 ){
20319   const char *zText = (const char*)sqlite3_value_text(argv[0]);
20320   UNUSED_PARAMETER(argc);
20321   if( zText && zText[0]=='\'' ){
20322     i64 nText = sqlite3_value_bytes(argv[0]);
20323     i64 i;
20324     char zBuf1[20];
20325     char zBuf2[20];
20326     const char *zNL = 0;
20327     const char *zCR = 0;
20328     i64 nCR = 0;
20329     i64 nNL = 0;
20330 
20331     for(i=0; zText[i]; i++){
20332       if( zNL==0 && zText[i]=='\n' ){
20333         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
20334         nNL = strlen(zNL);
20335       }
20336       if( zCR==0 && zText[i]=='\r' ){
20337         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
20338         nCR = strlen(zCR);
20339       }
20340     }
20341 
20342     if( zNL || zCR ){
20343       i64 iOut = 0;
20344       i64 nMax = (nNL > nCR) ? nNL : nCR;
20345       i64 nAlloc = nMax * nText + (nMax+64)*2;
20346       char *zOut = (char*)sqlite3_malloc64(nAlloc);
20347       if( zOut==0 ){
20348         sqlite3_result_error_nomem(context);
20349         return;
20350       }
20351 
20352       if( zNL && zCR ){
20353         memcpy(&zOut[iOut], "replace(replace(", 16);
20354         iOut += 16;
20355       }else{
20356         memcpy(&zOut[iOut], "replace(", 8);
20357         iOut += 8;
20358       }
20359       for(i=0; zText[i]; i++){
20360         if( zText[i]=='\n' ){
20361           memcpy(&zOut[iOut], zNL, nNL);
20362           iOut += nNL;
20363         }else if( zText[i]=='\r' ){
20364           memcpy(&zOut[iOut], zCR, nCR);
20365           iOut += nCR;
20366         }else{
20367           zOut[iOut] = zText[i];
20368           iOut++;
20369         }
20370       }
20371 
20372       if( zNL ){
20373         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
20374         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
20375         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
20376       }
20377       if( zCR ){
20378         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
20379         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
20380         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
20381       }
20382 
20383       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
20384       sqlite3_free(zOut);
20385       return;
20386     }
20387   }
20388 
20389   sqlite3_result_value(context, argv[0]);
20390 }
20391 
20392 /* Flags for open_db().
20393 **
20394 ** The default behavior of open_db() is to exit(1) if the database fails to
20395 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
20396 ** but still returns without calling exit.
20397 **
20398 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
20399 ** ZIP archive if the file does not exist or is empty and its name matches
20400 ** the *.zip pattern.
20401 */
20402 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
20403 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
20404 
20405 /*
20406 ** Make sure the database is open.  If it is not, then open it.  If
20407 ** the database fails to open, print an error message and exit.
20408 */
20409 static void open_db(ShellState *p, int openFlags){
20410   if( p->db==0 ){
20411     const char *zDbFilename = p->pAuxDb->zDbFilename;
20412     if( p->openMode==SHELL_OPEN_UNSPEC ){
20413       if( zDbFilename==0 || zDbFilename[0]==0 ){
20414         p->openMode = SHELL_OPEN_NORMAL;
20415       }else{
20416         p->openMode = (u8)deduceDatabaseType(zDbFilename,
20417                              (openFlags & OPEN_DB_ZIPFILE)!=0);
20418       }
20419     }
20420     switch( p->openMode ){
20421       case SHELL_OPEN_APPENDVFS: {
20422         sqlite3_open_v2(zDbFilename, &p->db,
20423            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
20424         break;
20425       }
20426       case SHELL_OPEN_HEXDB:
20427       case SHELL_OPEN_DESERIALIZE: {
20428         sqlite3_open(0, &p->db);
20429         break;
20430       }
20431       case SHELL_OPEN_ZIPFILE: {
20432         sqlite3_open(":memory:", &p->db);
20433         break;
20434       }
20435       case SHELL_OPEN_READONLY: {
20436         sqlite3_open_v2(zDbFilename, &p->db,
20437             SQLITE_OPEN_READONLY|p->openFlags, 0);
20438         break;
20439       }
20440       case SHELL_OPEN_UNSPEC:
20441       case SHELL_OPEN_NORMAL: {
20442         sqlite3_open_v2(zDbFilename, &p->db,
20443            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
20444         break;
20445       }
20446     }
20447     globalDb = p->db;
20448     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
20449       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
20450           zDbFilename, sqlite3_errmsg(p->db));
20451       if( openFlags & OPEN_DB_KEEPALIVE ){
20452         sqlite3_open(":memory:", &p->db);
20453         return;
20454       }
20455       exit(1);
20456     }
20457 
20458 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20459     sqlite3_enable_load_extension(p->db, 1);
20460 #endif
20461     sqlite3_shathree_init(p->db, 0, 0);
20462     sqlite3_uint_init(p->db, 0, 0);
20463     sqlite3_decimal_init(p->db, 0, 0);
20464     sqlite3_base64_init(p->db, 0, 0);
20465     sqlite3_base85_init(p->db, 0, 0);
20466     sqlite3_regexp_init(p->db, 0, 0);
20467     sqlite3_ieee_init(p->db, 0, 0);
20468     sqlite3_series_init(p->db, 0, 0);
20469 #ifndef SQLITE_SHELL_FIDDLE
20470     sqlite3_fileio_init(p->db, 0, 0);
20471     sqlite3_completion_init(p->db, 0, 0);
20472 #endif
20473 #if SQLITE_SHELL_HAVE_RECOVER
20474     sqlite3_dbdata_init(p->db, 0, 0);
20475 #endif
20476 #ifdef SQLITE_HAVE_ZLIB
20477     if( !p->bSafeModePersist ){
20478       sqlite3_zipfile_init(p->db, 0, 0);
20479       sqlite3_sqlar_init(p->db, 0, 0);
20480     }
20481 #endif
20482 #ifdef SQLITE_SHELL_EXTFUNCS
20483     /* Create a preprocessing mechanism for extensions to make
20484      * their own provisions for being built into the shell.
20485      * This is a short-span macro. See further below for usage.
20486      */
20487 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
20488 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
20489     /* Let custom-included extensions get their ..._init() called.
20490      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
20491      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
20492      * inititialization routine to be called.
20493      */
20494     {
20495       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
20496     /* Let custom-included extensions expose their functionality.
20497      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
20498      * the SQL functions, virtual tables, collating sequences or
20499      * VFS's implemented by the extension to be registered.
20500      */
20501       if( irc==SQLITE_OK
20502           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
20503         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
20504       }
20505 #undef SHELL_SUB_MACRO
20506 #undef SHELL_SUBMACRO
20507     }
20508 #endif
20509 
20510     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
20511                             shellAddSchemaName, 0, 0);
20512     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
20513                             shellModuleSchema, 0, 0);
20514     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
20515                             shellPutsFunc, 0, 0);
20516     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
20517                             shellEscapeCrnl, 0, 0);
20518     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
20519                             shellInt32, 0, 0);
20520     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
20521                             shellIdQuote, 0, 0);
20522     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
20523                             shellUSleepFunc, 0, 0);
20524 #ifndef SQLITE_NOHAVE_SYSTEM
20525     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
20526                             editFunc, 0, 0);
20527     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
20528                             editFunc, 0, 0);
20529 #endif
20530 
20531     if( p->openMode==SHELL_OPEN_ZIPFILE ){
20532       char *zSql = sqlite3_mprintf(
20533          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
20534       shell_check_oom(zSql);
20535       sqlite3_exec(p->db, zSql, 0, 0, 0);
20536       sqlite3_free(zSql);
20537     }
20538 #ifndef SQLITE_OMIT_DESERIALIZE
20539     else
20540     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
20541       int rc;
20542       int nData = 0;
20543       unsigned char *aData;
20544       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
20545         aData = (unsigned char*)readFile(zDbFilename, &nData);
20546       }else{
20547         aData = readHexDb(p, &nData);
20548         if( aData==0 ){
20549           return;
20550         }
20551       }
20552       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
20553                    SQLITE_DESERIALIZE_RESIZEABLE |
20554                    SQLITE_DESERIALIZE_FREEONCLOSE);
20555       if( rc ){
20556         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
20557       }
20558       if( p->szMax>0 ){
20559         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
20560       }
20561     }
20562 #endif
20563   }
20564   if( p->bSafeModePersist && p->db!=0 ){
20565     sqlite3_set_authorizer(p->db, safeModeAuth, p);
20566   }
20567 }
20568 
20569 /*
20570 ** Attempt to close the databaes connection.  Report errors.
20571 */
20572 void close_db(sqlite3 *db){
20573   int rc = sqlite3_close(db);
20574   if( rc ){
20575     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
20576         rc, sqlite3_errmsg(db));
20577   }
20578 }
20579 
20580 #if HAVE_READLINE || HAVE_EDITLINE
20581 /*
20582 ** Readline completion callbacks
20583 */
20584 static char *readline_completion_generator(const char *text, int state){
20585   static sqlite3_stmt *pStmt = 0;
20586   char *zRet;
20587   if( state==0 ){
20588     char *zSql;
20589     sqlite3_finalize(pStmt);
20590     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
20591                            "  FROM completion(%Q) ORDER BY 1", text);
20592     shell_check_oom(zSql);
20593     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
20594     sqlite3_free(zSql);
20595   }
20596   if( sqlite3_step(pStmt)==SQLITE_ROW ){
20597     const char *z = (const char*)sqlite3_column_text(pStmt,0);
20598     zRet = z ? strdup(z) : 0;
20599   }else{
20600     sqlite3_finalize(pStmt);
20601     pStmt = 0;
20602     zRet = 0;
20603   }
20604   return zRet;
20605 }
20606 static char **readline_completion(const char *zText, int iStart, int iEnd){
20607   (void)iStart;
20608   (void)iEnd;
20609   rl_attempted_completion_over = 1;
20610   return rl_completion_matches(zText, readline_completion_generator);
20611 }
20612 
20613 #elif HAVE_LINENOISE
20614 /*
20615 ** Linenoise completion callback
20616 */
20617 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
20618   i64 nLine = strlen(zLine);
20619   i64 i, iStart;
20620   sqlite3_stmt *pStmt = 0;
20621   char *zSql;
20622   char zBuf[1000];
20623 
20624   if( nLine>(i64)sizeof(zBuf)-30 ) return;
20625   if( zLine[0]=='.' || zLine[0]=='#') return;
20626   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
20627   if( i==nLine-1 ) return;
20628   iStart = i+1;
20629   memcpy(zBuf, zLine, iStart);
20630   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
20631                          "  FROM completion(%Q,%Q) ORDER BY 1",
20632                          &zLine[iStart], zLine);
20633   shell_check_oom(zSql);
20634   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
20635   sqlite3_free(zSql);
20636   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
20637   while( sqlite3_step(pStmt)==SQLITE_ROW ){
20638     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
20639     int nCompletion = sqlite3_column_bytes(pStmt, 0);
20640     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
20641       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
20642       linenoiseAddCompletion(lc, zBuf);
20643     }
20644   }
20645   sqlite3_finalize(pStmt);
20646 }
20647 #endif
20648 
20649 /*
20650 ** Do C-language style dequoting.
20651 **
20652 **    \a    -> alarm
20653 **    \b    -> backspace
20654 **    \t    -> tab
20655 **    \n    -> newline
20656 **    \v    -> vertical tab
20657 **    \f    -> form feed
20658 **    \r    -> carriage return
20659 **    \s    -> space
20660 **    \"    -> "
20661 **    \'    -> '
20662 **    \\    -> backslash
20663 **    \NNN  -> ascii character NNN in octal
20664 */
20665 static void resolve_backslashes(char *z){
20666   int i, j;
20667   char c;
20668   while( *z && *z!='\\' ) z++;
20669   for(i=j=0; (c = z[i])!=0; i++, j++){
20670     if( c=='\\' && z[i+1]!=0 ){
20671       c = z[++i];
20672       if( c=='a' ){
20673         c = '\a';
20674       }else if( c=='b' ){
20675         c = '\b';
20676       }else if( c=='t' ){
20677         c = '\t';
20678       }else if( c=='n' ){
20679         c = '\n';
20680       }else if( c=='v' ){
20681         c = '\v';
20682       }else if( c=='f' ){
20683         c = '\f';
20684       }else if( c=='r' ){
20685         c = '\r';
20686       }else if( c=='"' ){
20687         c = '"';
20688       }else if( c=='\'' ){
20689         c = '\'';
20690       }else if( c=='\\' ){
20691         c = '\\';
20692       }else if( c>='0' && c<='7' ){
20693         c -= '0';
20694         if( z[i+1]>='0' && z[i+1]<='7' ){
20695           i++;
20696           c = (c<<3) + z[i] - '0';
20697           if( z[i+1]>='0' && z[i+1]<='7' ){
20698             i++;
20699             c = (c<<3) + z[i] - '0';
20700           }
20701         }
20702       }
20703     }
20704     z[j] = c;
20705   }
20706   if( j<i ) z[j] = 0;
20707 }
20708 
20709 /*
20710 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
20711 ** for TRUE and FALSE.  Return the integer value if appropriate.
20712 */
20713 static int booleanValue(const char *zArg){
20714   int i;
20715   if( zArg[0]=='0' && zArg[1]=='x' ){
20716     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
20717   }else{
20718     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
20719   }
20720   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
20721   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
20722     return 1;
20723   }
20724   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
20725     return 0;
20726   }
20727   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
20728           zArg);
20729   return 0;
20730 }
20731 
20732 /*
20733 ** Set or clear a shell flag according to a boolean value.
20734 */
20735 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
20736   if( booleanValue(zArg) ){
20737     ShellSetFlag(p, mFlag);
20738   }else{
20739     ShellClearFlag(p, mFlag);
20740   }
20741 }
20742 
20743 /*
20744 ** Close an output file, assuming it is not stderr or stdout
20745 */
20746 static void output_file_close(FILE *f){
20747   if( f && f!=stdout && f!=stderr ) fclose(f);
20748 }
20749 
20750 /*
20751 ** Try to open an output file.   The names "stdout" and "stderr" are
20752 ** recognized and do the right thing.  NULL is returned if the output
20753 ** filename is "off".
20754 */
20755 static FILE *output_file_open(const char *zFile, int bTextMode){
20756   FILE *f;
20757   if( cli_strcmp(zFile,"stdout")==0 ){
20758     f = stdout;
20759   }else if( cli_strcmp(zFile, "stderr")==0 ){
20760     f = stderr;
20761   }else if( cli_strcmp(zFile, "off")==0 ){
20762     f = 0;
20763   }else{
20764     f = fopen(zFile, bTextMode ? "w" : "wb");
20765     if( f==0 ){
20766       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
20767     }
20768   }
20769   return f;
20770 }
20771 
20772 #ifndef SQLITE_OMIT_TRACE
20773 /*
20774 ** A routine for handling output from sqlite3_trace().
20775 */
20776 static int sql_trace_callback(
20777   unsigned mType,         /* The trace type */
20778   void *pArg,             /* The ShellState pointer */
20779   void *pP,               /* Usually a pointer to sqlite_stmt */
20780   void *pX                /* Auxiliary output */
20781 ){
20782   ShellState *p = (ShellState*)pArg;
20783   sqlite3_stmt *pStmt;
20784   const char *zSql;
20785   i64 nSql;
20786   if( p->traceOut==0 ) return 0;
20787   if( mType==SQLITE_TRACE_CLOSE ){
20788     utf8_printf(p->traceOut, "-- closing database connection\n");
20789     return 0;
20790   }
20791   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
20792     zSql = (const char*)pX;
20793   }else{
20794     pStmt = (sqlite3_stmt*)pP;
20795     switch( p->eTraceType ){
20796       case SHELL_TRACE_EXPANDED: {
20797         zSql = sqlite3_expanded_sql(pStmt);
20798         break;
20799       }
20800 #ifdef SQLITE_ENABLE_NORMALIZE
20801       case SHELL_TRACE_NORMALIZED: {
20802         zSql = sqlite3_normalized_sql(pStmt);
20803         break;
20804       }
20805 #endif
20806       default: {
20807         zSql = sqlite3_sql(pStmt);
20808         break;
20809       }
20810     }
20811   }
20812   if( zSql==0 ) return 0;
20813   nSql = strlen(zSql);
20814   if( nSql>1000000000 ) nSql = 1000000000;
20815   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
20816   switch( mType ){
20817     case SQLITE_TRACE_ROW:
20818     case SQLITE_TRACE_STMT: {
20819       utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
20820       break;
20821     }
20822     case SQLITE_TRACE_PROFILE: {
20823       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
20824       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
20825       break;
20826     }
20827   }
20828   return 0;
20829 }
20830 #endif
20831 
20832 /*
20833 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
20834 ** a useful spot to set a debugger breakpoint.
20835 **
20836 ** This routine does not do anything practical.  The code are there simply
20837 ** to prevent the compiler from optimizing this routine out.
20838 */
20839 static void test_breakpoint(void){
20840   static unsigned int nCall = 0;
20841   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
20842 }
20843 
20844 /*
20845 ** An object used to read a CSV and other files for import.
20846 */
20847 typedef struct ImportCtx ImportCtx;
20848 struct ImportCtx {
20849   const char *zFile;  /* Name of the input file */
20850   FILE *in;           /* Read the CSV text from this input stream */
20851   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
20852   char *z;            /* Accumulated text for a field */
20853   int n;              /* Number of bytes in z */
20854   int nAlloc;         /* Space allocated for z[] */
20855   int nLine;          /* Current line number */
20856   int nRow;           /* Number of rows imported */
20857   int nErr;           /* Number of errors encountered */
20858   int bNotFirst;      /* True if one or more bytes already read */
20859   int cTerm;          /* Character that terminated the most recent field */
20860   int cColSep;        /* The column separator character.  (Usually ",") */
20861   int cRowSep;        /* The row separator character.  (Usually "\n") */
20862 };
20863 
20864 /* Clean up resourced used by an ImportCtx */
20865 static void import_cleanup(ImportCtx *p){
20866   if( p->in!=0 && p->xCloser!=0 ){
20867     p->xCloser(p->in);
20868     p->in = 0;
20869   }
20870   sqlite3_free(p->z);
20871   p->z = 0;
20872 }
20873 
20874 /* Append a single byte to z[] */
20875 static void import_append_char(ImportCtx *p, int c){
20876   if( p->n+1>=p->nAlloc ){
20877     p->nAlloc += p->nAlloc + 100;
20878     p->z = sqlite3_realloc64(p->z, p->nAlloc);
20879     shell_check_oom(p->z);
20880   }
20881   p->z[p->n++] = (char)c;
20882 }
20883 
20884 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
20885 ** with the option of having a separator other than ",".
20886 **
20887 **   +  Input comes from p->in.
20888 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
20889 **      from sqlite3_malloc64().
20890 **   +  Use p->cSep as the column separator.  The default is ",".
20891 **   +  Use p->rSep as the row separator.  The default is "\n".
20892 **   +  Keep track of the line number in p->nLine.
20893 **   +  Store the character that terminates the field in p->cTerm.  Store
20894 **      EOF on end-of-file.
20895 **   +  Report syntax errors on stderr
20896 */
20897 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
20898   int c;
20899   int cSep = p->cColSep;
20900   int rSep = p->cRowSep;
20901   p->n = 0;
20902   c = fgetc(p->in);
20903   if( c==EOF || seenInterrupt ){
20904     p->cTerm = EOF;
20905     return 0;
20906   }
20907   if( c=='"' ){
20908     int pc, ppc;
20909     int startLine = p->nLine;
20910     int cQuote = c;
20911     pc = ppc = 0;
20912     while( 1 ){
20913       c = fgetc(p->in);
20914       if( c==rSep ) p->nLine++;
20915       if( c==cQuote ){
20916         if( pc==cQuote ){
20917           pc = 0;
20918           continue;
20919         }
20920       }
20921       if( (c==cSep && pc==cQuote)
20922        || (c==rSep && pc==cQuote)
20923        || (c==rSep && pc=='\r' && ppc==cQuote)
20924        || (c==EOF && pc==cQuote)
20925       ){
20926         do{ p->n--; }while( p->z[p->n]!=cQuote );
20927         p->cTerm = c;
20928         break;
20929       }
20930       if( pc==cQuote && c!='\r' ){
20931         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
20932                 p->zFile, p->nLine, cQuote);
20933       }
20934       if( c==EOF ){
20935         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
20936                 p->zFile, startLine, cQuote);
20937         p->cTerm = c;
20938         break;
20939       }
20940       import_append_char(p, c);
20941       ppc = pc;
20942       pc = c;
20943     }
20944   }else{
20945     /* If this is the first field being parsed and it begins with the
20946     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
20947     if( (c&0xff)==0xef && p->bNotFirst==0 ){
20948       import_append_char(p, c);
20949       c = fgetc(p->in);
20950       if( (c&0xff)==0xbb ){
20951         import_append_char(p, c);
20952         c = fgetc(p->in);
20953         if( (c&0xff)==0xbf ){
20954           p->bNotFirst = 1;
20955           p->n = 0;
20956           return csv_read_one_field(p);
20957         }
20958       }
20959     }
20960     while( c!=EOF && c!=cSep && c!=rSep ){
20961       import_append_char(p, c);
20962       c = fgetc(p->in);
20963     }
20964     if( c==rSep ){
20965       p->nLine++;
20966       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
20967     }
20968     p->cTerm = c;
20969   }
20970   if( p->z ) p->z[p->n] = 0;
20971   p->bNotFirst = 1;
20972   return p->z;
20973 }
20974 
20975 /* Read a single field of ASCII delimited text.
20976 **
20977 **   +  Input comes from p->in.
20978 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
20979 **      from sqlite3_malloc64().
20980 **   +  Use p->cSep as the column separator.  The default is "\x1F".
20981 **   +  Use p->rSep as the row separator.  The default is "\x1E".
20982 **   +  Keep track of the row number in p->nLine.
20983 **   +  Store the character that terminates the field in p->cTerm.  Store
20984 **      EOF on end-of-file.
20985 **   +  Report syntax errors on stderr
20986 */
20987 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
20988   int c;
20989   int cSep = p->cColSep;
20990   int rSep = p->cRowSep;
20991   p->n = 0;
20992   c = fgetc(p->in);
20993   if( c==EOF || seenInterrupt ){
20994     p->cTerm = EOF;
20995     return 0;
20996   }
20997   while( c!=EOF && c!=cSep && c!=rSep ){
20998     import_append_char(p, c);
20999     c = fgetc(p->in);
21000   }
21001   if( c==rSep ){
21002     p->nLine++;
21003   }
21004   p->cTerm = c;
21005   if( p->z ) p->z[p->n] = 0;
21006   return p->z;
21007 }
21008 
21009 /*
21010 ** Try to transfer data for table zTable.  If an error is seen while
21011 ** moving forward, try to go backwards.  The backwards movement won't
21012 ** work for WITHOUT ROWID tables.
21013 */
21014 static void tryToCloneData(
21015   ShellState *p,
21016   sqlite3 *newDb,
21017   const char *zTable
21018 ){
21019   sqlite3_stmt *pQuery = 0;
21020   sqlite3_stmt *pInsert = 0;
21021   char *zQuery = 0;
21022   char *zInsert = 0;
21023   int rc;
21024   int i, j, n;
21025   int nTable = strlen30(zTable);
21026   int k = 0;
21027   int cnt = 0;
21028   const int spinRate = 10000;
21029 
21030   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
21031   shell_check_oom(zQuery);
21032   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21033   if( rc ){
21034     utf8_printf(stderr, "Error %d: %s on [%s]\n",
21035             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21036             zQuery);
21037     goto end_data_xfer;
21038   }
21039   n = sqlite3_column_count(pQuery);
21040   zInsert = sqlite3_malloc64(200 + nTable + n*3);
21041   shell_check_oom(zInsert);
21042   sqlite3_snprintf(200+nTable,zInsert,
21043                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
21044   i = strlen30(zInsert);
21045   for(j=1; j<n; j++){
21046     memcpy(zInsert+i, ",?", 2);
21047     i += 2;
21048   }
21049   memcpy(zInsert+i, ");", 3);
21050   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
21051   if( rc ){
21052     utf8_printf(stderr, "Error %d: %s on [%s]\n",
21053             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
21054             zQuery);
21055     goto end_data_xfer;
21056   }
21057   for(k=0; k<2; k++){
21058     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
21059       for(i=0; i<n; i++){
21060         switch( sqlite3_column_type(pQuery, i) ){
21061           case SQLITE_NULL: {
21062             sqlite3_bind_null(pInsert, i+1);
21063             break;
21064           }
21065           case SQLITE_INTEGER: {
21066             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
21067             break;
21068           }
21069           case SQLITE_FLOAT: {
21070             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
21071             break;
21072           }
21073           case SQLITE_TEXT: {
21074             sqlite3_bind_text(pInsert, i+1,
21075                              (const char*)sqlite3_column_text(pQuery,i),
21076                              -1, SQLITE_STATIC);
21077             break;
21078           }
21079           case SQLITE_BLOB: {
21080             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
21081                                             sqlite3_column_bytes(pQuery,i),
21082                                             SQLITE_STATIC);
21083             break;
21084           }
21085         }
21086       } /* End for */
21087       rc = sqlite3_step(pInsert);
21088       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
21089         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
21090                         sqlite3_errmsg(newDb));
21091       }
21092       sqlite3_reset(pInsert);
21093       cnt++;
21094       if( (cnt%spinRate)==0 ){
21095         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
21096         fflush(stdout);
21097       }
21098     } /* End while */
21099     if( rc==SQLITE_DONE ) break;
21100     sqlite3_finalize(pQuery);
21101     sqlite3_free(zQuery);
21102     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
21103                              zTable);
21104     shell_check_oom(zQuery);
21105     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21106     if( rc ){
21107       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
21108       break;
21109     }
21110   } /* End for(k=0...) */
21111 
21112 end_data_xfer:
21113   sqlite3_finalize(pQuery);
21114   sqlite3_finalize(pInsert);
21115   sqlite3_free(zQuery);
21116   sqlite3_free(zInsert);
21117 }
21118 
21119 
21120 /*
21121 ** Try to transfer all rows of the schema that match zWhere.  For
21122 ** each row, invoke xForEach() on the object defined by that row.
21123 ** If an error is encountered while moving forward through the
21124 ** sqlite_schema table, try again moving backwards.
21125 */
21126 static void tryToCloneSchema(
21127   ShellState *p,
21128   sqlite3 *newDb,
21129   const char *zWhere,
21130   void (*xForEach)(ShellState*,sqlite3*,const char*)
21131 ){
21132   sqlite3_stmt *pQuery = 0;
21133   char *zQuery = 0;
21134   int rc;
21135   const unsigned char *zName;
21136   const unsigned char *zSql;
21137   char *zErrMsg = 0;
21138 
21139   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
21140                            " WHERE %s ORDER BY rowid ASC", zWhere);
21141   shell_check_oom(zQuery);
21142   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21143   if( rc ){
21144     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
21145                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21146                     zQuery);
21147     goto end_schema_xfer;
21148   }
21149   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
21150     zName = sqlite3_column_text(pQuery, 0);
21151     zSql = sqlite3_column_text(pQuery, 1);
21152     if( zName==0 || zSql==0 ) continue;
21153     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
21154       printf("%s... ", zName); fflush(stdout);
21155       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
21156       if( zErrMsg ){
21157         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
21158         sqlite3_free(zErrMsg);
21159         zErrMsg = 0;
21160       }
21161     }
21162     if( xForEach ){
21163       xForEach(p, newDb, (const char*)zName);
21164     }
21165     printf("done\n");
21166   }
21167   if( rc!=SQLITE_DONE ){
21168     sqlite3_finalize(pQuery);
21169     sqlite3_free(zQuery);
21170     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
21171                              " WHERE %s ORDER BY rowid DESC", zWhere);
21172     shell_check_oom(zQuery);
21173     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21174     if( rc ){
21175       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
21176                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21177                       zQuery);
21178       goto end_schema_xfer;
21179     }
21180     while( sqlite3_step(pQuery)==SQLITE_ROW ){
21181       zName = sqlite3_column_text(pQuery, 0);
21182       zSql = sqlite3_column_text(pQuery, 1);
21183       if( zName==0 || zSql==0 ) continue;
21184       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ) continue;
21185       printf("%s... ", zName); fflush(stdout);
21186       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
21187       if( zErrMsg ){
21188         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
21189         sqlite3_free(zErrMsg);
21190         zErrMsg = 0;
21191       }
21192       if( xForEach ){
21193         xForEach(p, newDb, (const char*)zName);
21194       }
21195       printf("done\n");
21196     }
21197   }
21198 end_schema_xfer:
21199   sqlite3_finalize(pQuery);
21200   sqlite3_free(zQuery);
21201 }
21202 
21203 /*
21204 ** Open a new database file named "zNewDb".  Try to recover as much information
21205 ** as possible out of the main database (which might be corrupt) and write it
21206 ** into zNewDb.
21207 */
21208 static void tryToClone(ShellState *p, const char *zNewDb){
21209   int rc;
21210   sqlite3 *newDb = 0;
21211   if( access(zNewDb,0)==0 ){
21212     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
21213     return;
21214   }
21215   rc = sqlite3_open(zNewDb, &newDb);
21216   if( rc ){
21217     utf8_printf(stderr, "Cannot create output database: %s\n",
21218             sqlite3_errmsg(newDb));
21219   }else{
21220     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
21221     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
21222     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
21223     tryToCloneSchema(p, newDb, "type!='table'", 0);
21224     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
21225     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
21226   }
21227   close_db(newDb);
21228 }
21229 
21230 /*
21231 ** Change the output file back to stdout.
21232 **
21233 ** If the p->doXdgOpen flag is set, that means the output was being
21234 ** redirected to a temporary file named by p->zTempFile.  In that case,
21235 ** launch start/open/xdg-open on that temporary file.
21236 */
21237 static void output_reset(ShellState *p){
21238   if( p->outfile[0]=='|' ){
21239 #ifndef SQLITE_OMIT_POPEN
21240     pclose(p->out);
21241 #endif
21242   }else{
21243     output_file_close(p->out);
21244 #ifndef SQLITE_NOHAVE_SYSTEM
21245     if( p->doXdgOpen ){
21246       const char *zXdgOpenCmd =
21247 #if defined(_WIN32)
21248       "start";
21249 #elif defined(__APPLE__)
21250       "open";
21251 #else
21252       "xdg-open";
21253 #endif
21254       char *zCmd;
21255       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
21256       if( system(zCmd) ){
21257         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
21258       }else{
21259         /* Give the start/open/xdg-open command some time to get
21260         ** going before we continue, and potential delete the
21261         ** p->zTempFile data file out from under it */
21262         sqlite3_sleep(2000);
21263       }
21264       sqlite3_free(zCmd);
21265       outputModePop(p);
21266       p->doXdgOpen = 0;
21267     }
21268 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
21269   }
21270   p->outfile[0] = 0;
21271   p->out = stdout;
21272 }
21273 
21274 /*
21275 ** Run an SQL command and return the single integer result.
21276 */
21277 static int db_int(sqlite3 *db, const char *zSql){
21278   sqlite3_stmt *pStmt;
21279   int res = 0;
21280   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
21281   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
21282     res = sqlite3_column_int(pStmt,0);
21283   }
21284   sqlite3_finalize(pStmt);
21285   return res;
21286 }
21287 
21288 #if defined(SQLITE_SHELL_HAVE_RECOVER)
21289 /*
21290 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
21291 */
21292 static unsigned int get2byteInt(unsigned char *a){
21293   return (a[0]<<8) + a[1];
21294 }
21295 static unsigned int get4byteInt(unsigned char *a){
21296   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
21297 }
21298 
21299 /*
21300 ** Implementation of the ".dbinfo" command.
21301 **
21302 ** Return 1 on error, 2 to exit, and 0 otherwise.
21303 */
21304 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
21305   static const struct { const char *zName; int ofst; } aField[] = {
21306      { "file change counter:",  24  },
21307      { "database page count:",  28  },
21308      { "freelist page count:",  36  },
21309      { "schema cookie:",        40  },
21310      { "schema format:",        44  },
21311      { "default cache size:",   48  },
21312      { "autovacuum top root:",  52  },
21313      { "incremental vacuum:",   64  },
21314      { "text encoding:",        56  },
21315      { "user version:",         60  },
21316      { "application id:",       68  },
21317      { "software version:",     96  },
21318   };
21319   static const struct { const char *zName; const char *zSql; } aQuery[] = {
21320      { "number of tables:",
21321        "SELECT count(*) FROM %s WHERE type='table'" },
21322      { "number of indexes:",
21323        "SELECT count(*) FROM %s WHERE type='index'" },
21324      { "number of triggers:",
21325        "SELECT count(*) FROM %s WHERE type='trigger'" },
21326      { "number of views:",
21327        "SELECT count(*) FROM %s WHERE type='view'" },
21328      { "schema size:",
21329        "SELECT total(length(sql)) FROM %s" },
21330   };
21331   int i, rc;
21332   unsigned iDataVersion;
21333   char *zSchemaTab;
21334   char *zDb = nArg>=2 ? azArg[1] : "main";
21335   sqlite3_stmt *pStmt = 0;
21336   unsigned char aHdr[100];
21337   open_db(p, 0);
21338   if( p->db==0 ) return 1;
21339   rc = sqlite3_prepare_v2(p->db,
21340              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
21341              -1, &pStmt, 0);
21342   if( rc ){
21343     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
21344     sqlite3_finalize(pStmt);
21345     return 1;
21346   }
21347   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
21348   if( sqlite3_step(pStmt)==SQLITE_ROW
21349    && sqlite3_column_bytes(pStmt,0)>100
21350   ){
21351     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
21352     sqlite3_finalize(pStmt);
21353   }else{
21354     raw_printf(stderr, "unable to read database header\n");
21355     sqlite3_finalize(pStmt);
21356     return 1;
21357   }
21358   i = get2byteInt(aHdr+16);
21359   if( i==1 ) i = 65536;
21360   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
21361   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
21362   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
21363   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
21364   for(i=0; i<ArraySize(aField); i++){
21365     int ofst = aField[i].ofst;
21366     unsigned int val = get4byteInt(aHdr + ofst);
21367     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
21368     switch( ofst ){
21369       case 56: {
21370         if( val==1 ) raw_printf(p->out, " (utf8)");
21371         if( val==2 ) raw_printf(p->out, " (utf16le)");
21372         if( val==3 ) raw_printf(p->out, " (utf16be)");
21373       }
21374     }
21375     raw_printf(p->out, "\n");
21376   }
21377   if( zDb==0 ){
21378     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
21379   }else if( cli_strcmp(zDb,"temp")==0 ){
21380     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
21381   }else{
21382     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
21383   }
21384   for(i=0; i<ArraySize(aQuery); i++){
21385     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
21386     int val = db_int(p->db, zSql);
21387     sqlite3_free(zSql);
21388     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
21389   }
21390   sqlite3_free(zSchemaTab);
21391   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
21392   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
21393   return 0;
21394 }
21395 #endif /* SQLITE_SHELL_HAVE_RECOVER */
21396 
21397 /*
21398 ** Print the current sqlite3_errmsg() value to stderr and return 1.
21399 */
21400 static int shellDatabaseError(sqlite3 *db){
21401   const char *zErr = sqlite3_errmsg(db);
21402   utf8_printf(stderr, "Error: %s\n", zErr);
21403   return 1;
21404 }
21405 
21406 /*
21407 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
21408 ** if they match and FALSE (0) if they do not match.
21409 **
21410 ** Globbing rules:
21411 **
21412 **      '*'       Matches any sequence of zero or more characters.
21413 **
21414 **      '?'       Matches exactly one character.
21415 **
21416 **     [...]      Matches one character from the enclosed list of
21417 **                characters.
21418 **
21419 **     [^...]     Matches one character not in the enclosed list.
21420 **
21421 **      '#'       Matches any sequence of one or more digits with an
21422 **                optional + or - sign in front
21423 **
21424 **      ' '       Any span of whitespace matches any other span of
21425 **                whitespace.
21426 **
21427 ** Extra whitespace at the end of z[] is ignored.
21428 */
21429 static int testcase_glob(const char *zGlob, const char *z){
21430   int c, c2;
21431   int invert;
21432   int seen;
21433 
21434   while( (c = (*(zGlob++)))!=0 ){
21435     if( IsSpace(c) ){
21436       if( !IsSpace(*z) ) return 0;
21437       while( IsSpace(*zGlob) ) zGlob++;
21438       while( IsSpace(*z) ) z++;
21439     }else if( c=='*' ){
21440       while( (c=(*(zGlob++))) == '*' || c=='?' ){
21441         if( c=='?' && (*(z++))==0 ) return 0;
21442       }
21443       if( c==0 ){
21444         return 1;
21445       }else if( c=='[' ){
21446         while( *z && testcase_glob(zGlob-1,z)==0 ){
21447           z++;
21448         }
21449         return (*z)!=0;
21450       }
21451       while( (c2 = (*(z++)))!=0 ){
21452         while( c2!=c ){
21453           c2 = *(z++);
21454           if( c2==0 ) return 0;
21455         }
21456         if( testcase_glob(zGlob,z) ) return 1;
21457       }
21458       return 0;
21459     }else if( c=='?' ){
21460       if( (*(z++))==0 ) return 0;
21461     }else if( c=='[' ){
21462       int prior_c = 0;
21463       seen = 0;
21464       invert = 0;
21465       c = *(z++);
21466       if( c==0 ) return 0;
21467       c2 = *(zGlob++);
21468       if( c2=='^' ){
21469         invert = 1;
21470         c2 = *(zGlob++);
21471       }
21472       if( c2==']' ){
21473         if( c==']' ) seen = 1;
21474         c2 = *(zGlob++);
21475       }
21476       while( c2 && c2!=']' ){
21477         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
21478           c2 = *(zGlob++);
21479           if( c>=prior_c && c<=c2 ) seen = 1;
21480           prior_c = 0;
21481         }else{
21482           if( c==c2 ){
21483             seen = 1;
21484           }
21485           prior_c = c2;
21486         }
21487         c2 = *(zGlob++);
21488       }
21489       if( c2==0 || (seen ^ invert)==0 ) return 0;
21490     }else if( c=='#' ){
21491       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
21492       if( !IsDigit(z[0]) ) return 0;
21493       z++;
21494       while( IsDigit(z[0]) ){ z++; }
21495     }else{
21496       if( c!=(*(z++)) ) return 0;
21497     }
21498   }
21499   while( IsSpace(*z) ){ z++; }
21500   return *z==0;
21501 }
21502 
21503 
21504 /*
21505 ** Compare the string as a command-line option with either one or two
21506 ** initial "-" characters.
21507 */
21508 static int optionMatch(const char *zStr, const char *zOpt){
21509   if( zStr[0]!='-' ) return 0;
21510   zStr++;
21511   if( zStr[0]=='-' ) zStr++;
21512   return cli_strcmp(zStr, zOpt)==0;
21513 }
21514 
21515 /*
21516 ** Delete a file.
21517 */
21518 int shellDeleteFile(const char *zFilename){
21519   int rc;
21520 #ifdef _WIN32
21521   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
21522   rc = _wunlink(z);
21523   sqlite3_free(z);
21524 #else
21525   rc = unlink(zFilename);
21526 #endif
21527   return rc;
21528 }
21529 
21530 /*
21531 ** Try to delete the temporary file (if there is one) and free the
21532 ** memory used to hold the name of the temp file.
21533 */
21534 static void clearTempFile(ShellState *p){
21535   if( p->zTempFile==0 ) return;
21536   if( p->doXdgOpen ) return;
21537   if( shellDeleteFile(p->zTempFile) ) return;
21538   sqlite3_free(p->zTempFile);
21539   p->zTempFile = 0;
21540 }
21541 
21542 /*
21543 ** Create a new temp file name with the given suffix.
21544 */
21545 static void newTempFile(ShellState *p, const char *zSuffix){
21546   clearTempFile(p);
21547   sqlite3_free(p->zTempFile);
21548   p->zTempFile = 0;
21549   if( p->db ){
21550     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
21551   }
21552   if( p->zTempFile==0 ){
21553     /* If p->db is an in-memory database then the TEMPFILENAME file-control
21554     ** will not work and we will need to fallback to guessing */
21555     char *zTemp;
21556     sqlite3_uint64 r;
21557     sqlite3_randomness(sizeof(r), &r);
21558     zTemp = getenv("TEMP");
21559     if( zTemp==0 ) zTemp = getenv("TMP");
21560     if( zTemp==0 ){
21561 #ifdef _WIN32
21562       zTemp = "\\tmp";
21563 #else
21564       zTemp = "/tmp";
21565 #endif
21566     }
21567     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
21568   }else{
21569     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
21570   }
21571   shell_check_oom(p->zTempFile);
21572 }
21573 
21574 
21575 /*
21576 ** The implementation of SQL scalar function fkey_collate_clause(), used
21577 ** by the ".lint fkey-indexes" command. This scalar function is always
21578 ** called with four arguments - the parent table name, the parent column name,
21579 ** the child table name and the child column name.
21580 **
21581 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
21582 **
21583 ** If either of the named tables or columns do not exist, this function
21584 ** returns an empty string. An empty string is also returned if both tables
21585 ** and columns exist but have the same default collation sequence. Or,
21586 ** if both exist but the default collation sequences are different, this
21587 ** function returns the string " COLLATE <parent-collation>", where
21588 ** <parent-collation> is the default collation sequence of the parent column.
21589 */
21590 static void shellFkeyCollateClause(
21591   sqlite3_context *pCtx,
21592   int nVal,
21593   sqlite3_value **apVal
21594 ){
21595   sqlite3 *db = sqlite3_context_db_handle(pCtx);
21596   const char *zParent;
21597   const char *zParentCol;
21598   const char *zParentSeq;
21599   const char *zChild;
21600   const char *zChildCol;
21601   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
21602   int rc;
21603 
21604   assert( nVal==4 );
21605   zParent = (const char*)sqlite3_value_text(apVal[0]);
21606   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
21607   zChild = (const char*)sqlite3_value_text(apVal[2]);
21608   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
21609 
21610   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
21611   rc = sqlite3_table_column_metadata(
21612       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
21613   );
21614   if( rc==SQLITE_OK ){
21615     rc = sqlite3_table_column_metadata(
21616         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
21617     );
21618   }
21619 
21620   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
21621     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
21622     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
21623     sqlite3_free(z);
21624   }
21625 }
21626 
21627 
21628 /*
21629 ** The implementation of dot-command ".lint fkey-indexes".
21630 */
21631 static int lintFkeyIndexes(
21632   ShellState *pState,             /* Current shell tool state */
21633   char **azArg,                   /* Array of arguments passed to dot command */
21634   int nArg                        /* Number of entries in azArg[] */
21635 ){
21636   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
21637   FILE *out = pState->out;        /* Stream to write non-error output to */
21638   int bVerbose = 0;               /* If -verbose is present */
21639   int bGroupByParent = 0;         /* If -groupbyparent is present */
21640   int i;                          /* To iterate through azArg[] */
21641   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
21642   int rc;                         /* Return code */
21643   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
21644 
21645   /*
21646   ** This SELECT statement returns one row for each foreign key constraint
21647   ** in the schema of the main database. The column values are:
21648   **
21649   ** 0. The text of an SQL statement similar to:
21650   **
21651   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
21652   **
21653   **    This SELECT is similar to the one that the foreign keys implementation
21654   **    needs to run internally on child tables. If there is an index that can
21655   **    be used to optimize this query, then it can also be used by the FK
21656   **    implementation to optimize DELETE or UPDATE statements on the parent
21657   **    table.
21658   **
21659   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
21660   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
21661   **    contains an index that can be used to optimize the query.
21662   **
21663   ** 2. Human readable text that describes the child table and columns. e.g.
21664   **
21665   **       "child_table(child_key1, child_key2)"
21666   **
21667   ** 3. Human readable text that describes the parent table and columns. e.g.
21668   **
21669   **       "parent_table(parent_key1, parent_key2)"
21670   **
21671   ** 4. A full CREATE INDEX statement for an index that could be used to
21672   **    optimize DELETE or UPDATE statements on the parent table. e.g.
21673   **
21674   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
21675   **
21676   ** 5. The name of the parent table.
21677   **
21678   ** These six values are used by the C logic below to generate the report.
21679   */
21680   const char *zSql =
21681   "SELECT "
21682     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
21683     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
21684     "  || fkey_collate_clause("
21685     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
21686     ", "
21687     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
21688     "  || group_concat('*=?', ' AND ') || ')'"
21689     ", "
21690     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
21691     ", "
21692     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
21693     ", "
21694     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
21695     "  || ' ON ' || quote(s.name) || '('"
21696     "  || group_concat(quote(f.[from]) ||"
21697     "        fkey_collate_clause("
21698     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
21699     "  || ');'"
21700     ", "
21701     "     f.[table] "
21702     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
21703     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
21704     "GROUP BY s.name, f.id "
21705     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
21706   ;
21707   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
21708 
21709   for(i=2; i<nArg; i++){
21710     int n = strlen30(azArg[i]);
21711     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
21712       bVerbose = 1;
21713     }
21714     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
21715       bGroupByParent = 1;
21716       zIndent = "    ";
21717     }
21718     else{
21719       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
21720           azArg[0], azArg[1]
21721       );
21722       return SQLITE_ERROR;
21723     }
21724   }
21725 
21726   /* Register the fkey_collate_clause() SQL function */
21727   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
21728       0, shellFkeyCollateClause, 0, 0
21729   );
21730 
21731 
21732   if( rc==SQLITE_OK ){
21733     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
21734   }
21735   if( rc==SQLITE_OK ){
21736     sqlite3_bind_int(pSql, 1, bGroupByParent);
21737   }
21738 
21739   if( rc==SQLITE_OK ){
21740     int rc2;
21741     char *zPrev = 0;
21742     while( SQLITE_ROW==sqlite3_step(pSql) ){
21743       int res = -1;
21744       sqlite3_stmt *pExplain = 0;
21745       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
21746       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
21747       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
21748       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
21749       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
21750       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
21751 
21752       if( zEQP==0 ) continue;
21753       if( zGlob==0 ) continue;
21754       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
21755       if( rc!=SQLITE_OK ) break;
21756       if( SQLITE_ROW==sqlite3_step(pExplain) ){
21757         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
21758         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
21759                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
21760       }
21761       rc = sqlite3_finalize(pExplain);
21762       if( rc!=SQLITE_OK ) break;
21763 
21764       if( res<0 ){
21765         raw_printf(stderr, "Error: internal error");
21766         break;
21767       }else{
21768         if( bGroupByParent
21769         && (bVerbose || res==0)
21770         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
21771         ){
21772           raw_printf(out, "-- Parent table %s\n", zParent);
21773           sqlite3_free(zPrev);
21774           zPrev = sqlite3_mprintf("%s", zParent);
21775         }
21776 
21777         if( res==0 ){
21778           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
21779         }else if( bVerbose ){
21780           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
21781               zIndent, zFrom, zTarget
21782           );
21783         }
21784       }
21785     }
21786     sqlite3_free(zPrev);
21787 
21788     if( rc!=SQLITE_OK ){
21789       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
21790     }
21791 
21792     rc2 = sqlite3_finalize(pSql);
21793     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
21794       rc = rc2;
21795       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
21796     }
21797   }else{
21798     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
21799   }
21800 
21801   return rc;
21802 }
21803 
21804 /*
21805 ** Implementation of ".lint" dot command.
21806 */
21807 static int lintDotCommand(
21808   ShellState *pState,             /* Current shell tool state */
21809   char **azArg,                   /* Array of arguments passed to dot command */
21810   int nArg                        /* Number of entries in azArg[] */
21811 ){
21812   int n;
21813   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
21814   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
21815   return lintFkeyIndexes(pState, azArg, nArg);
21816 
21817  usage:
21818   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
21819   raw_printf(stderr, "Where sub-commands are:\n");
21820   raw_printf(stderr, "    fkey-indexes\n");
21821   return SQLITE_ERROR;
21822 }
21823 
21824 #if !defined SQLITE_OMIT_VIRTUALTABLE
21825 static void shellPrepare(
21826   sqlite3 *db,
21827   int *pRc,
21828   const char *zSql,
21829   sqlite3_stmt **ppStmt
21830 ){
21831   *ppStmt = 0;
21832   if( *pRc==SQLITE_OK ){
21833     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
21834     if( rc!=SQLITE_OK ){
21835       raw_printf(stderr, "sql error: %s (%d)\n",
21836           sqlite3_errmsg(db), sqlite3_errcode(db)
21837       );
21838       *pRc = rc;
21839     }
21840   }
21841 }
21842 
21843 /*
21844 ** Create a prepared statement using printf-style arguments for the SQL.
21845 **
21846 ** This routine is could be marked "static".  But it is not always used,
21847 ** depending on compile-time options.  By omitting the "static", we avoid
21848 ** nuisance compiler warnings about "defined but not used".
21849 */
21850 void shellPreparePrintf(
21851   sqlite3 *db,
21852   int *pRc,
21853   sqlite3_stmt **ppStmt,
21854   const char *zFmt,
21855   ...
21856 ){
21857   *ppStmt = 0;
21858   if( *pRc==SQLITE_OK ){
21859     va_list ap;
21860     char *z;
21861     va_start(ap, zFmt);
21862     z = sqlite3_vmprintf(zFmt, ap);
21863     va_end(ap);
21864     if( z==0 ){
21865       *pRc = SQLITE_NOMEM;
21866     }else{
21867       shellPrepare(db, pRc, z, ppStmt);
21868       sqlite3_free(z);
21869     }
21870   }
21871 }
21872 
21873 /* Finalize the prepared statement created using shellPreparePrintf().
21874 **
21875 ** This routine is could be marked "static".  But it is not always used,
21876 ** depending on compile-time options.  By omitting the "static", we avoid
21877 ** nuisance compiler warnings about "defined but not used".
21878 */
21879 void shellFinalize(
21880   int *pRc,
21881   sqlite3_stmt *pStmt
21882 ){
21883   if( pStmt ){
21884     sqlite3 *db = sqlite3_db_handle(pStmt);
21885     int rc = sqlite3_finalize(pStmt);
21886     if( *pRc==SQLITE_OK ){
21887       if( rc!=SQLITE_OK ){
21888         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
21889       }
21890       *pRc = rc;
21891     }
21892   }
21893 }
21894 
21895 /* Reset the prepared statement created using shellPreparePrintf().
21896 **
21897 ** This routine is could be marked "static".  But it is not always used,
21898 ** depending on compile-time options.  By omitting the "static", we avoid
21899 ** nuisance compiler warnings about "defined but not used".
21900 */
21901 void shellReset(
21902   int *pRc,
21903   sqlite3_stmt *pStmt
21904 ){
21905   int rc = sqlite3_reset(pStmt);
21906   if( *pRc==SQLITE_OK ){
21907     if( rc!=SQLITE_OK ){
21908       sqlite3 *db = sqlite3_db_handle(pStmt);
21909       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
21910     }
21911     *pRc = rc;
21912   }
21913 }
21914 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
21915 
21916 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
21917 /******************************************************************************
21918 ** The ".archive" or ".ar" command.
21919 */
21920 /*
21921 ** Structure representing a single ".ar" command.
21922 */
21923 typedef struct ArCommand ArCommand;
21924 struct ArCommand {
21925   u8 eCmd;                        /* An AR_CMD_* value */
21926   u8 bVerbose;                    /* True if --verbose */
21927   u8 bZip;                        /* True if the archive is a ZIP */
21928   u8 bDryRun;                     /* True if --dry-run */
21929   u8 bAppend;                     /* True if --append */
21930   u8 bGlob;                       /* True if --glob */
21931   u8 fromCmdLine;                 /* Run from -A instead of .archive */
21932   int nArg;                       /* Number of command arguments */
21933   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
21934   const char *zFile;              /* --file argument, or NULL */
21935   const char *zDir;               /* --directory argument, or NULL */
21936   char **azArg;                   /* Array of command arguments */
21937   ShellState *p;                  /* Shell state */
21938   sqlite3 *db;                    /* Database containing the archive */
21939 };
21940 
21941 /*
21942 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
21943 */
21944 static int arUsage(FILE *f){
21945   showHelp(f,"archive");
21946   return SQLITE_ERROR;
21947 }
21948 
21949 /*
21950 ** Print an error message for the .ar command to stderr and return
21951 ** SQLITE_ERROR.
21952 */
21953 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
21954   va_list ap;
21955   char *z;
21956   va_start(ap, zFmt);
21957   z = sqlite3_vmprintf(zFmt, ap);
21958   va_end(ap);
21959   utf8_printf(stderr, "Error: %s\n", z);
21960   if( pAr->fromCmdLine ){
21961     utf8_printf(stderr, "Use \"-A\" for more help\n");
21962   }else{
21963     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
21964   }
21965   sqlite3_free(z);
21966   return SQLITE_ERROR;
21967 }
21968 
21969 /*
21970 ** Values for ArCommand.eCmd.
21971 */
21972 #define AR_CMD_CREATE       1
21973 #define AR_CMD_UPDATE       2
21974 #define AR_CMD_INSERT       3
21975 #define AR_CMD_EXTRACT      4
21976 #define AR_CMD_LIST         5
21977 #define AR_CMD_HELP         6
21978 #define AR_CMD_REMOVE       7
21979 
21980 /*
21981 ** Other (non-command) switches.
21982 */
21983 #define AR_SWITCH_VERBOSE     8
21984 #define AR_SWITCH_FILE        9
21985 #define AR_SWITCH_DIRECTORY  10
21986 #define AR_SWITCH_APPEND     11
21987 #define AR_SWITCH_DRYRUN     12
21988 #define AR_SWITCH_GLOB       13
21989 
21990 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
21991   switch( eSwitch ){
21992     case AR_CMD_CREATE:
21993     case AR_CMD_EXTRACT:
21994     case AR_CMD_LIST:
21995     case AR_CMD_REMOVE:
21996     case AR_CMD_UPDATE:
21997     case AR_CMD_INSERT:
21998     case AR_CMD_HELP:
21999       if( pAr->eCmd ){
22000         return arErrorMsg(pAr, "multiple command options");
22001       }
22002       pAr->eCmd = eSwitch;
22003       break;
22004 
22005     case AR_SWITCH_DRYRUN:
22006       pAr->bDryRun = 1;
22007       break;
22008     case AR_SWITCH_GLOB:
22009       pAr->bGlob = 1;
22010       break;
22011     case AR_SWITCH_VERBOSE:
22012       pAr->bVerbose = 1;
22013       break;
22014     case AR_SWITCH_APPEND:
22015       pAr->bAppend = 1;
22016       deliberate_fall_through;
22017     case AR_SWITCH_FILE:
22018       pAr->zFile = zArg;
22019       break;
22020     case AR_SWITCH_DIRECTORY:
22021       pAr->zDir = zArg;
22022       break;
22023   }
22024 
22025   return SQLITE_OK;
22026 }
22027 
22028 /*
22029 ** Parse the command line for an ".ar" command. The results are written into
22030 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
22031 ** successfully, otherwise an error message is written to stderr and
22032 ** SQLITE_ERROR returned.
22033 */
22034 static int arParseCommand(
22035   char **azArg,                   /* Array of arguments passed to dot command */
22036   int nArg,                       /* Number of entries in azArg[] */
22037   ArCommand *pAr                  /* Populate this object */
22038 ){
22039   struct ArSwitch {
22040     const char *zLong;
22041     char cShort;
22042     u8 eSwitch;
22043     u8 bArg;
22044   } aSwitch[] = {
22045     { "create",    'c', AR_CMD_CREATE,       0 },
22046     { "extract",   'x', AR_CMD_EXTRACT,      0 },
22047     { "insert",    'i', AR_CMD_INSERT,       0 },
22048     { "list",      't', AR_CMD_LIST,         0 },
22049     { "remove",    'r', AR_CMD_REMOVE,       0 },
22050     { "update",    'u', AR_CMD_UPDATE,       0 },
22051     { "help",      'h', AR_CMD_HELP,         0 },
22052     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
22053     { "file",      'f', AR_SWITCH_FILE,      1 },
22054     { "append",    'a', AR_SWITCH_APPEND,    1 },
22055     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
22056     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
22057     { "glob",      'g', AR_SWITCH_GLOB,      0 },
22058   };
22059   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
22060   struct ArSwitch *pEnd = &aSwitch[nSwitch];
22061 
22062   if( nArg<=1 ){
22063     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
22064     return arUsage(stderr);
22065   }else{
22066     char *z = azArg[1];
22067     if( z[0]!='-' ){
22068       /* Traditional style [tar] invocation */
22069       int i;
22070       int iArg = 2;
22071       for(i=0; z[i]; i++){
22072         const char *zArg = 0;
22073         struct ArSwitch *pOpt;
22074         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22075           if( z[i]==pOpt->cShort ) break;
22076         }
22077         if( pOpt==pEnd ){
22078           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
22079         }
22080         if( pOpt->bArg ){
22081           if( iArg>=nArg ){
22082             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
22083           }
22084           zArg = azArg[iArg++];
22085         }
22086         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
22087       }
22088       pAr->nArg = nArg-iArg;
22089       if( pAr->nArg>0 ){
22090         pAr->azArg = &azArg[iArg];
22091       }
22092     }else{
22093       /* Non-traditional invocation */
22094       int iArg;
22095       for(iArg=1; iArg<nArg; iArg++){
22096         int n;
22097         z = azArg[iArg];
22098         if( z[0]!='-' ){
22099           /* All remaining command line words are command arguments. */
22100           pAr->azArg = &azArg[iArg];
22101           pAr->nArg = nArg-iArg;
22102           break;
22103         }
22104         n = strlen30(z);
22105 
22106         if( z[1]!='-' ){
22107           int i;
22108           /* One or more short options */
22109           for(i=1; i<n; i++){
22110             const char *zArg = 0;
22111             struct ArSwitch *pOpt;
22112             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22113               if( z[i]==pOpt->cShort ) break;
22114             }
22115             if( pOpt==pEnd ){
22116               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
22117             }
22118             if( pOpt->bArg ){
22119               if( i<(n-1) ){
22120                 zArg = &z[i+1];
22121                 i = n;
22122               }else{
22123                 if( iArg>=(nArg-1) ){
22124                   return arErrorMsg(pAr, "option requires an argument: %c",
22125                                     z[i]);
22126                 }
22127                 zArg = azArg[++iArg];
22128               }
22129             }
22130             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
22131           }
22132         }else if( z[2]=='\0' ){
22133           /* A -- option, indicating that all remaining command line words
22134           ** are command arguments.  */
22135           pAr->azArg = &azArg[iArg+1];
22136           pAr->nArg = nArg-iArg-1;
22137           break;
22138         }else{
22139           /* A long option */
22140           const char *zArg = 0;             /* Argument for option, if any */
22141           struct ArSwitch *pMatch = 0;      /* Matching option */
22142           struct ArSwitch *pOpt;            /* Iterator */
22143           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22144             const char *zLong = pOpt->zLong;
22145             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
22146               if( pMatch ){
22147                 return arErrorMsg(pAr, "ambiguous option: %s",z);
22148               }else{
22149                 pMatch = pOpt;
22150               }
22151             }
22152           }
22153 
22154           if( pMatch==0 ){
22155             return arErrorMsg(pAr, "unrecognized option: %s", z);
22156           }
22157           if( pMatch->bArg ){
22158             if( iArg>=(nArg-1) ){
22159               return arErrorMsg(pAr, "option requires an argument: %s", z);
22160             }
22161             zArg = azArg[++iArg];
22162           }
22163           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
22164         }
22165       }
22166     }
22167   }
22168 
22169   return SQLITE_OK;
22170 }
22171 
22172 /*
22173 ** This function assumes that all arguments within the ArCommand.azArg[]
22174 ** array refer to archive members, as for the --extract, --list or --remove
22175 ** commands. It checks that each of them are "present". If any specified
22176 ** file is not present in the archive, an error is printed to stderr and an
22177 ** error code returned. Otherwise, if all specified arguments are present
22178 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
22179 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
22180 ** when pAr->bGlob is true.
22181 **
22182 ** This function strips any trailing '/' characters from each argument.
22183 ** This is consistent with the way the [tar] command seems to work on
22184 ** Linux.
22185 */
22186 static int arCheckEntries(ArCommand *pAr){
22187   int rc = SQLITE_OK;
22188   if( pAr->nArg ){
22189     int i, j;
22190     sqlite3_stmt *pTest = 0;
22191     const char *zSel = (pAr->bGlob)
22192       ? "SELECT name FROM %s WHERE glob($name,name)"
22193       : "SELECT name FROM %s WHERE name=$name";
22194 
22195     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
22196     j = sqlite3_bind_parameter_index(pTest, "$name");
22197     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
22198       char *z = pAr->azArg[i];
22199       int n = strlen30(z);
22200       int bOk = 0;
22201       while( n>0 && z[n-1]=='/' ) n--;
22202       z[n] = '\0';
22203       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
22204       if( SQLITE_ROW==sqlite3_step(pTest) ){
22205         bOk = 1;
22206       }
22207       shellReset(&rc, pTest);
22208       if( rc==SQLITE_OK && bOk==0 ){
22209         utf8_printf(stderr, "not found in archive: %s\n", z);
22210         rc = SQLITE_ERROR;
22211       }
22212     }
22213     shellFinalize(&rc, pTest);
22214   }
22215   return rc;
22216 }
22217 
22218 /*
22219 ** Format a WHERE clause that can be used against the "sqlar" table to
22220 ** identify all archive members that match the command arguments held
22221 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
22222 ** The caller is responsible for eventually calling sqlite3_free() on
22223 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
22224 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
22225 */
22226 static void arWhereClause(
22227   int *pRc,
22228   ArCommand *pAr,
22229   char **pzWhere                  /* OUT: New WHERE clause */
22230 ){
22231   char *zWhere = 0;
22232   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
22233   if( *pRc==SQLITE_OK ){
22234     if( pAr->nArg==0 ){
22235       zWhere = sqlite3_mprintf("1");
22236     }else{
22237       int i;
22238       const char *zSep = "";
22239       for(i=0; i<pAr->nArg; i++){
22240         const char *z = pAr->azArg[i];
22241         zWhere = sqlite3_mprintf(
22242           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
22243           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
22244         );
22245         if( zWhere==0 ){
22246           *pRc = SQLITE_NOMEM;
22247           break;
22248         }
22249         zSep = " OR ";
22250       }
22251     }
22252   }
22253   *pzWhere = zWhere;
22254 }
22255 
22256 /*
22257 ** Implementation of .ar "lisT" command.
22258 */
22259 static int arListCommand(ArCommand *pAr){
22260   const char *zSql = "SELECT %s FROM %s WHERE %s";
22261   const char *azCols[] = {
22262     "name",
22263     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
22264   };
22265 
22266   char *zWhere = 0;
22267   sqlite3_stmt *pSql = 0;
22268   int rc;
22269 
22270   rc = arCheckEntries(pAr);
22271   arWhereClause(&rc, pAr, &zWhere);
22272 
22273   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
22274                      pAr->zSrcTable, zWhere);
22275   if( pAr->bDryRun ){
22276     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
22277   }else{
22278     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
22279       if( pAr->bVerbose ){
22280         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
22281             sqlite3_column_text(pSql, 0),
22282             sqlite3_column_int(pSql, 1),
22283             sqlite3_column_text(pSql, 2),
22284             sqlite3_column_text(pSql, 3)
22285         );
22286       }else{
22287         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
22288       }
22289     }
22290   }
22291   shellFinalize(&rc, pSql);
22292   sqlite3_free(zWhere);
22293   return rc;
22294 }
22295 
22296 
22297 /*
22298 ** Implementation of .ar "Remove" command.
22299 */
22300 static int arRemoveCommand(ArCommand *pAr){
22301   int rc = 0;
22302   char *zSql = 0;
22303   char *zWhere = 0;
22304 
22305   if( pAr->nArg ){
22306     /* Verify that args actually exist within the archive before proceeding.
22307     ** And formulate a WHERE clause to match them.  */
22308     rc = arCheckEntries(pAr);
22309     arWhereClause(&rc, pAr, &zWhere);
22310   }
22311   if( rc==SQLITE_OK ){
22312     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
22313                            pAr->zSrcTable, zWhere);
22314     if( pAr->bDryRun ){
22315       utf8_printf(pAr->p->out, "%s\n", zSql);
22316     }else{
22317       char *zErr = 0;
22318       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
22319       if( rc==SQLITE_OK ){
22320         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
22321         if( rc!=SQLITE_OK ){
22322           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
22323         }else{
22324           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
22325         }
22326       }
22327       if( zErr ){
22328         utf8_printf(stdout, "ERROR: %s\n", zErr);
22329         sqlite3_free(zErr);
22330       }
22331     }
22332   }
22333   sqlite3_free(zWhere);
22334   sqlite3_free(zSql);
22335   return rc;
22336 }
22337 
22338 /*
22339 ** Implementation of .ar "eXtract" command.
22340 */
22341 static int arExtractCommand(ArCommand *pAr){
22342   const char *zSql1 =
22343     "SELECT "
22344     " ($dir || name),"
22345     " writefile(($dir || name), %s, mode, mtime) "
22346     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
22347     " AND name NOT GLOB '*..[/\\]*'";
22348 
22349   const char *azExtraArg[] = {
22350     "sqlar_uncompress(data, sz)",
22351     "data"
22352   };
22353 
22354   sqlite3_stmt *pSql = 0;
22355   int rc = SQLITE_OK;
22356   char *zDir = 0;
22357   char *zWhere = 0;
22358   int i, j;
22359 
22360   /* If arguments are specified, check that they actually exist within
22361   ** the archive before proceeding. And formulate a WHERE clause to
22362   ** match them.  */
22363   rc = arCheckEntries(pAr);
22364   arWhereClause(&rc, pAr, &zWhere);
22365 
22366   if( rc==SQLITE_OK ){
22367     if( pAr->zDir ){
22368       zDir = sqlite3_mprintf("%s/", pAr->zDir);
22369     }else{
22370       zDir = sqlite3_mprintf("");
22371     }
22372     if( zDir==0 ) rc = SQLITE_NOMEM;
22373   }
22374 
22375   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
22376       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
22377   );
22378 
22379   if( rc==SQLITE_OK ){
22380     j = sqlite3_bind_parameter_index(pSql, "$dir");
22381     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
22382 
22383     /* Run the SELECT statement twice. The first time, writefile() is called
22384     ** for all archive members that should be extracted. The second time,
22385     ** only for the directories. This is because the timestamps for
22386     ** extracted directories must be reset after they are populated (as
22387     ** populating them changes the timestamp).  */
22388     for(i=0; i<2; i++){
22389       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
22390       sqlite3_bind_int(pSql, j, i);
22391       if( pAr->bDryRun ){
22392         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
22393       }else{
22394         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
22395           if( i==0 && pAr->bVerbose ){
22396             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
22397           }
22398         }
22399       }
22400       shellReset(&rc, pSql);
22401     }
22402     shellFinalize(&rc, pSql);
22403   }
22404 
22405   sqlite3_free(zDir);
22406   sqlite3_free(zWhere);
22407   return rc;
22408 }
22409 
22410 /*
22411 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
22412 */
22413 static int arExecSql(ArCommand *pAr, const char *zSql){
22414   int rc;
22415   if( pAr->bDryRun ){
22416     utf8_printf(pAr->p->out, "%s\n", zSql);
22417     rc = SQLITE_OK;
22418   }else{
22419     char *zErr = 0;
22420     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
22421     if( zErr ){
22422       utf8_printf(stdout, "ERROR: %s\n", zErr);
22423       sqlite3_free(zErr);
22424     }
22425   }
22426   return rc;
22427 }
22428 
22429 
22430 /*
22431 ** Implementation of .ar "create", "insert", and "update" commands.
22432 **
22433 **     create    ->     Create a new SQL archive
22434 **     insert    ->     Insert or reinsert all files listed
22435 **     update    ->     Insert files that have changed or that were not
22436 **                      previously in the archive
22437 **
22438 ** Create the "sqlar" table in the database if it does not already exist.
22439 ** Then add each file in the azFile[] array to the archive. Directories
22440 ** are added recursively. If argument bVerbose is non-zero, a message is
22441 ** printed on stdout for each file archived.
22442 **
22443 ** The create command is the same as update, except that it drops
22444 ** any existing "sqlar" table before beginning.  The "insert" command
22445 ** always overwrites every file named on the command-line, where as
22446 ** "update" only overwrites if the size or mtime or mode has changed.
22447 */
22448 static int arCreateOrUpdateCommand(
22449   ArCommand *pAr,                 /* Command arguments and options */
22450   int bUpdate,                    /* true for a --create. */
22451   int bOnlyIfChanged              /* Only update if file has changed */
22452 ){
22453   const char *zCreate =
22454       "CREATE TABLE IF NOT EXISTS sqlar(\n"
22455       "  name TEXT PRIMARY KEY,  -- name of the file\n"
22456       "  mode INT,               -- access permissions\n"
22457       "  mtime INT,              -- last modification time\n"
22458       "  sz INT,                 -- original file size\n"
22459       "  data BLOB               -- compressed content\n"
22460       ")";
22461   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
22462   const char *zInsertFmt[2] = {
22463      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
22464      "  SELECT\n"
22465      "    %s,\n"
22466      "    mode,\n"
22467      "    mtime,\n"
22468      "    CASE substr(lsmode(mode),1,1)\n"
22469      "      WHEN '-' THEN length(data)\n"
22470      "      WHEN 'd' THEN 0\n"
22471      "      ELSE -1 END,\n"
22472      "    sqlar_compress(data)\n"
22473      "  FROM fsdir(%Q,%Q) AS disk\n"
22474      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
22475      ,
22476      "REPLACE INTO %s(name,mode,mtime,data)\n"
22477      "  SELECT\n"
22478      "    %s,\n"
22479      "    mode,\n"
22480      "    mtime,\n"
22481      "    data\n"
22482      "  FROM fsdir(%Q,%Q) AS disk\n"
22483      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
22484   };
22485   int i;                          /* For iterating through azFile[] */
22486   int rc;                         /* Return code */
22487   const char *zTab = 0;           /* SQL table into which to insert */
22488   char *zSql;
22489   char zTemp[50];
22490   char *zExists = 0;
22491 
22492   arExecSql(pAr, "PRAGMA page_size=512");
22493   rc = arExecSql(pAr, "SAVEPOINT ar;");
22494   if( rc!=SQLITE_OK ) return rc;
22495   zTemp[0] = 0;
22496   if( pAr->bZip ){
22497     /* Initialize the zipfile virtual table, if necessary */
22498     if( pAr->zFile ){
22499       sqlite3_uint64 r;
22500       sqlite3_randomness(sizeof(r),&r);
22501       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
22502       zTab = zTemp;
22503       zSql = sqlite3_mprintf(
22504          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
22505          zTab, pAr->zFile
22506       );
22507       rc = arExecSql(pAr, zSql);
22508       sqlite3_free(zSql);
22509     }else{
22510       zTab = "zip";
22511     }
22512   }else{
22513     /* Initialize the table for an SQLAR */
22514     zTab = "sqlar";
22515     if( bUpdate==0 ){
22516       rc = arExecSql(pAr, zDrop);
22517       if( rc!=SQLITE_OK ) goto end_ar_transaction;
22518     }
22519     rc = arExecSql(pAr, zCreate);
22520   }
22521   if( bOnlyIfChanged ){
22522     zExists = sqlite3_mprintf(
22523       " AND NOT EXISTS("
22524           "SELECT 1 FROM %s AS mem"
22525           " WHERE mem.name=disk.name"
22526           " AND mem.mtime=disk.mtime"
22527           " AND mem.mode=disk.mode)", zTab);
22528   }else{
22529     zExists = sqlite3_mprintf("");
22530   }
22531   if( zExists==0 ) rc = SQLITE_NOMEM;
22532   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
22533     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
22534         pAr->bVerbose ? "shell_putsnl(name)" : "name",
22535         pAr->azArg[i], pAr->zDir, zExists);
22536     rc = arExecSql(pAr, zSql2);
22537     sqlite3_free(zSql2);
22538   }
22539 end_ar_transaction:
22540   if( rc!=SQLITE_OK ){
22541     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
22542   }else{
22543     rc = arExecSql(pAr, "RELEASE ar;");
22544     if( pAr->bZip && pAr->zFile ){
22545       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
22546       arExecSql(pAr, zSql);
22547       sqlite3_free(zSql);
22548     }
22549   }
22550   sqlite3_free(zExists);
22551   return rc;
22552 }
22553 
22554 /*
22555 ** Implementation of ".ar" dot command.
22556 */
22557 static int arDotCommand(
22558   ShellState *pState,          /* Current shell tool state */
22559   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
22560   char **azArg,                /* Array of arguments passed to dot command */
22561   int nArg                     /* Number of entries in azArg[] */
22562 ){
22563   ArCommand cmd;
22564   int rc;
22565   memset(&cmd, 0, sizeof(cmd));
22566   cmd.fromCmdLine = fromCmdLine;
22567   rc = arParseCommand(azArg, nArg, &cmd);
22568   if( rc==SQLITE_OK ){
22569     int eDbType = SHELL_OPEN_UNSPEC;
22570     cmd.p = pState;
22571     cmd.db = pState->db;
22572     if( cmd.zFile ){
22573       eDbType = deduceDatabaseType(cmd.zFile, 1);
22574     }else{
22575       eDbType = pState->openMode;
22576     }
22577     if( eDbType==SHELL_OPEN_ZIPFILE ){
22578       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
22579         if( cmd.zFile==0 ){
22580           cmd.zSrcTable = sqlite3_mprintf("zip");
22581         }else{
22582           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
22583         }
22584       }
22585       cmd.bZip = 1;
22586     }else if( cmd.zFile ){
22587       int flags;
22588       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
22589       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
22590            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
22591         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
22592       }else{
22593         flags = SQLITE_OPEN_READONLY;
22594       }
22595       cmd.db = 0;
22596       if( cmd.bDryRun ){
22597         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
22598              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
22599       }
22600       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
22601              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
22602       if( rc!=SQLITE_OK ){
22603         utf8_printf(stderr, "cannot open file: %s (%s)\n",
22604             cmd.zFile, sqlite3_errmsg(cmd.db)
22605         );
22606         goto end_ar_command;
22607       }
22608       sqlite3_fileio_init(cmd.db, 0, 0);
22609       sqlite3_sqlar_init(cmd.db, 0, 0);
22610       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
22611                               shellPutsFunc, 0, 0);
22612 
22613     }
22614     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
22615       if( cmd.eCmd!=AR_CMD_CREATE
22616        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
22617       ){
22618         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
22619         rc = SQLITE_ERROR;
22620         goto end_ar_command;
22621       }
22622       cmd.zSrcTable = sqlite3_mprintf("sqlar");
22623     }
22624 
22625     switch( cmd.eCmd ){
22626       case AR_CMD_CREATE:
22627         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
22628         break;
22629 
22630       case AR_CMD_EXTRACT:
22631         rc = arExtractCommand(&cmd);
22632         break;
22633 
22634       case AR_CMD_LIST:
22635         rc = arListCommand(&cmd);
22636         break;
22637 
22638       case AR_CMD_HELP:
22639         arUsage(pState->out);
22640         break;
22641 
22642       case AR_CMD_INSERT:
22643         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
22644         break;
22645 
22646       case AR_CMD_REMOVE:
22647         rc = arRemoveCommand(&cmd);
22648         break;
22649 
22650       default:
22651         assert( cmd.eCmd==AR_CMD_UPDATE );
22652         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
22653         break;
22654     }
22655   }
22656 end_ar_command:
22657   if( cmd.db!=pState->db ){
22658     close_db(cmd.db);
22659   }
22660   sqlite3_free(cmd.zSrcTable);
22661 
22662   return rc;
22663 }
22664 /* End of the ".archive" or ".ar" command logic
22665 *******************************************************************************/
22666 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
22667 
22668 #if SQLITE_SHELL_HAVE_RECOVER
22669 
22670 /*
22671 ** This function is used as a callback by the recover extension. Simply
22672 ** print the supplied SQL statement to stdout.
22673 */
22674 static int recoverSqlCb(void *pCtx, const char *zSql){
22675   ShellState *pState = (ShellState*)pCtx;
22676   utf8_printf(pState->out, "%s;\n", zSql);
22677   return SQLITE_OK;
22678 }
22679 
22680 /*
22681 ** This function is called to recover data from the database. A script
22682 ** to construct a new database containing all recovered data is output
22683 ** on stream pState->out.
22684 */
22685 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
22686   int rc = SQLITE_OK;
22687   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
22688   const char *zLAF = "lost_and_found";
22689   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
22690   int bRowids = 1;                /* 0 if --no-rowids */
22691   sqlite3_recover *p = 0;
22692   int i = 0;
22693 
22694   for(i=1; i<nArg; i++){
22695     char *z = azArg[i];
22696     int n;
22697     if( z[0]=='-' && z[1]=='-' ) z++;
22698     n = strlen30(z);
22699     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
22700       bFreelist = 0;
22701     }else
22702     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
22703       /* This option determines the name of the ATTACH-ed database used
22704       ** internally by the recovery extension.  The default is "" which
22705       ** means to use a temporary database that is automatically deleted
22706       ** when closed.  This option is undocumented and might disappear at
22707       ** any moment. */
22708       i++;
22709       zRecoveryDb = azArg[i];
22710     }else
22711     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
22712       i++;
22713       zLAF = azArg[i];
22714     }else
22715     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
22716       bRowids = 0;
22717     }
22718     else{
22719       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
22720       showHelp(pState->out, azArg[0]);
22721       return 1;
22722     }
22723   }
22724 
22725   p = sqlite3_recover_init_sql(
22726       pState->db, "main", recoverSqlCb, (void*)pState
22727   );
22728 
22729   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
22730   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
22731   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
22732   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
22733 
22734   sqlite3_recover_run(p);
22735   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
22736     const char *zErr = sqlite3_recover_errmsg(p);
22737     int errCode = sqlite3_recover_errcode(p);
22738     raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
22739   }
22740   rc = sqlite3_recover_finish(p);
22741   return rc;
22742 }
22743 #endif /* SQLITE_SHELL_HAVE_RECOVER */
22744 
22745 
22746 /*
22747  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
22748  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
22749  *   close db and set it to 0, and return the columns spec, to later
22750  *   be sqlite3_free()'ed by the caller.
22751  * The return is 0 when either:
22752  *   (a) The db was not initialized and zCol==0 (There are no columns.)
22753  *   (b) zCol!=0  (Column was added, db initialized as needed.)
22754  * The 3rd argument, pRenamed, references an out parameter. If the
22755  * pointer is non-zero, its referent will be set to a summary of renames
22756  * done if renaming was necessary, or set to 0 if none was done. The out
22757  * string (if any) must be sqlite3_free()'ed by the caller.
22758  */
22759 #ifdef SHELL_DEBUG
22760 #define rc_err_oom_die(rc) \
22761   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
22762   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
22763     fprintf(stderr,"E:%d\n",rc), assert(0)
22764 #else
22765 static void rc_err_oom_die(int rc){
22766   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
22767   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
22768 }
22769 #endif
22770 
22771 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
22772 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
22773 #else  /* Otherwise, memory is faster/better for the transient DB. */
22774 static const char *zCOL_DB = ":memory:";
22775 #endif
22776 
22777 /* Define character (as C string) to separate generated column ordinal
22778  * from protected part of incoming column names. This defaults to "_"
22779  * so that incoming column identifiers that did not need not be quoted
22780  * remain usable without being quoted. It must be one character.
22781  */
22782 #ifndef SHELL_AUTOCOLUMN_SEP
22783 # define AUTOCOLUMN_SEP "_"
22784 #else
22785 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
22786 #endif
22787 
22788 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
22789   /* Queries and D{D,M}L used here */
22790   static const char * const zTabMake = "\
22791 CREATE TABLE ColNames(\
22792  cpos INTEGER PRIMARY KEY,\
22793  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
22794 CREATE VIEW RepeatedNames AS \
22795 SELECT DISTINCT t.name FROM ColNames t \
22796 WHERE t.name COLLATE NOCASE IN (\
22797  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
22798 );\
22799 ";
22800   static const char * const zTabFill = "\
22801 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
22802  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
22803 ";
22804   static const char * const zHasDupes = "\
22805 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
22806  <count(name) FROM ColNames\
22807 ";
22808 #ifdef SHELL_COLUMN_RENAME_CLEAN
22809   static const char * const zDedoctor = "\
22810 UPDATE ColNames SET chop=iif(\
22811   (substring(name,nlen,1) BETWEEN '0' AND '9')\
22812   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
22813  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
22814  0\
22815 )\
22816 ";
22817 #endif
22818   static const char * const zSetReps = "\
22819 UPDATE ColNames AS t SET reps=\
22820 (SELECT count(*) FROM ColNames d \
22821  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
22822  COLLATE NOCASE\
22823 )\
22824 ";
22825 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
22826   static const char * const zColDigits = "\
22827 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
22828 ";
22829 #else
22830   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
22831   static const char * const zColDigits = "\
22832 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
22833  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
22834  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
22835 ";
22836 #endif
22837   static const char * const zRenameRank =
22838 #ifdef SHELL_COLUMN_RENAME_CLEAN
22839     "UPDATE ColNames AS t SET suff="
22840     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
22841 #else /* ...RENAME_MINIMAL_ONE_PASS */
22842 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
22843 "  SELECT 0 AS nlz"
22844 "  UNION"
22845 "  SELECT nlz+1 AS nlz FROM Lzn"
22846 "  WHERE EXISTS("
22847 "   SELECT 1"
22848 "   FROM ColNames t, ColNames o"
22849 "   WHERE"
22850 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
22851 "     printf('%s"AUTOCOLUMN_SEP"%s',"
22852 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
22853 "     t.name"
22854 "    )"
22855 "    ="
22856 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
22857 "     printf('%s"AUTOCOLUMN_SEP"%s',"
22858 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
22859 "     o.name"
22860 "    )"
22861 "    COLLATE NOCASE"
22862 "    AND o.cpos<>t.cpos"
22863 "   GROUP BY t.cpos"
22864 "  )"
22865 ") UPDATE Colnames AS t SET"
22866 " chop = 0," /* No chopping, never touch incoming names. */
22867 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
22868 "  printf('"AUTOCOLUMN_SEP"%s', substring("
22869 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
22870 "  ''"
22871 " )"
22872 #endif
22873     ;
22874   static const char * const zCollectVar = "\
22875 SELECT\
22876  '('||x'0a'\
22877  || group_concat(\
22878   cname||' TEXT',\
22879   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
22880  ||')' AS ColsSpec \
22881 FROM (\
22882  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
22883  FROM ColNames ORDER BY cpos\
22884 )";
22885   static const char * const zRenamesDone =
22886     "SELECT group_concat("
22887     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
22888     " ','||x'0a')"
22889     "FROM ColNames WHERE suff<>'' OR chop!=0"
22890     ;
22891   int rc;
22892   sqlite3_stmt *pStmt = 0;
22893   assert(pDb!=0);
22894   if( zColNew ){
22895     /* Add initial or additional column. Init db if necessary. */
22896     if( *pDb==0 ){
22897       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
22898 #ifdef SHELL_COLFIX_DB
22899       if(*zCOL_DB!=':')
22900         sqlite3_exec(*pDb,"drop table if exists ColNames;"
22901                      "drop view if exists RepeatedNames;",0,0,0);
22902 #endif
22903       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
22904       rc_err_oom_die(rc);
22905     }
22906     assert(*pDb!=0);
22907     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
22908     rc_err_oom_die(rc);
22909     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
22910     rc_err_oom_die(rc);
22911     rc = sqlite3_step(pStmt);
22912     rc_err_oom_die(rc);
22913     sqlite3_finalize(pStmt);
22914     return 0;
22915   }else if( *pDb==0 ){
22916     return 0;
22917   }else{
22918     /* Formulate the columns spec, close the DB, zero *pDb. */
22919     char *zColsSpec = 0;
22920     int hasDupes = db_int(*pDb, zHasDupes);
22921     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
22922     if( hasDupes ){
22923 #ifdef SHELL_COLUMN_RENAME_CLEAN
22924       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
22925       rc_err_oom_die(rc);
22926 #endif
22927       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
22928       rc_err_oom_die(rc);
22929       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
22930       rc_err_oom_die(rc);
22931       sqlite3_bind_int(pStmt, 1, nDigits);
22932       rc = sqlite3_step(pStmt);
22933       sqlite3_finalize(pStmt);
22934       assert(rc==SQLITE_DONE);
22935     }
22936     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
22937     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
22938     rc_err_oom_die(rc);
22939     rc = sqlite3_step(pStmt);
22940     if( rc==SQLITE_ROW ){
22941       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
22942     }else{
22943       zColsSpec = 0;
22944     }
22945     if( pzRenamed!=0 ){
22946       if( !hasDupes ) *pzRenamed = 0;
22947       else{
22948         sqlite3_finalize(pStmt);
22949         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
22950             && SQLITE_ROW==sqlite3_step(pStmt) ){
22951           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
22952         }else
22953           *pzRenamed = 0;
22954       }
22955     }
22956     sqlite3_finalize(pStmt);
22957     sqlite3_close(*pDb);
22958     *pDb = 0;
22959     return zColsSpec;
22960   }
22961 }
22962 
22963 /*
22964 ** If an input line begins with "." then invoke this routine to
22965 ** process that line.
22966 **
22967 ** Return 1 on error, 2 to exit, and 0 otherwise.
22968 */
22969 static int do_meta_command(char *zLine, ShellState *p){
22970   int h = 1;
22971   int nArg = 0;
22972   int n, c;
22973   int rc = 0;
22974   char *azArg[52];
22975 
22976 #ifndef SQLITE_OMIT_VIRTUALTABLE
22977   if( p->expert.pExpert ){
22978     expertFinish(p, 1, 0);
22979   }
22980 #endif
22981 
22982   /* Parse the input line into tokens.
22983   */
22984   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
22985     while( IsSpace(zLine[h]) ){ h++; }
22986     if( zLine[h]==0 ) break;
22987     if( zLine[h]=='\'' || zLine[h]=='"' ){
22988       int delim = zLine[h++];
22989       azArg[nArg++] = &zLine[h];
22990       while( zLine[h] && zLine[h]!=delim ){
22991         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
22992         h++;
22993       }
22994       if( zLine[h]==delim ){
22995         zLine[h++] = 0;
22996       }
22997       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
22998     }else{
22999       azArg[nArg++] = &zLine[h];
23000       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
23001       if( zLine[h] ) zLine[h++] = 0;
23002       resolve_backslashes(azArg[nArg-1]);
23003     }
23004   }
23005   azArg[nArg] = 0;
23006 
23007   /* Process the input line.
23008   */
23009   if( nArg==0 ) return 0; /* no tokens, no error */
23010   n = strlen30(azArg[0]);
23011   c = azArg[0][0];
23012   clearTempFile(p);
23013 
23014 #ifndef SQLITE_OMIT_AUTHORIZATION
23015   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
23016     if( nArg!=2 ){
23017       raw_printf(stderr, "Usage: .auth ON|OFF\n");
23018       rc = 1;
23019       goto meta_command_exit;
23020     }
23021     open_db(p, 0);
23022     if( booleanValue(azArg[1]) ){
23023       sqlite3_set_authorizer(p->db, shellAuth, p);
23024     }else if( p->bSafeModePersist ){
23025       sqlite3_set_authorizer(p->db, safeModeAuth, p);
23026     }else{
23027       sqlite3_set_authorizer(p->db, 0, 0);
23028     }
23029   }else
23030 #endif
23031 
23032 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
23033   && !defined(SQLITE_SHELL_FIDDLE)
23034   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
23035     open_db(p, 0);
23036     failIfSafeMode(p, "cannot run .archive in safe mode");
23037     rc = arDotCommand(p, 0, azArg, nArg);
23038   }else
23039 #endif
23040 
23041 #ifndef SQLITE_SHELL_FIDDLE
23042   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
23043    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
23044   ){
23045     const char *zDestFile = 0;
23046     const char *zDb = 0;
23047     sqlite3 *pDest;
23048     sqlite3_backup *pBackup;
23049     int j;
23050     int bAsync = 0;
23051     const char *zVfs = 0;
23052     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
23053     for(j=1; j<nArg; j++){
23054       const char *z = azArg[j];
23055       if( z[0]=='-' ){
23056         if( z[1]=='-' ) z++;
23057         if( cli_strcmp(z, "-append")==0 ){
23058           zVfs = "apndvfs";
23059         }else
23060         if( cli_strcmp(z, "-async")==0 ){
23061           bAsync = 1;
23062         }else
23063         {
23064           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
23065           return 1;
23066         }
23067       }else if( zDestFile==0 ){
23068         zDestFile = azArg[j];
23069       }else if( zDb==0 ){
23070         zDb = zDestFile;
23071         zDestFile = azArg[j];
23072       }else{
23073         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
23074         return 1;
23075       }
23076     }
23077     if( zDestFile==0 ){
23078       raw_printf(stderr, "missing FILENAME argument on .backup\n");
23079       return 1;
23080     }
23081     if( zDb==0 ) zDb = "main";
23082     rc = sqlite3_open_v2(zDestFile, &pDest,
23083                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
23084     if( rc!=SQLITE_OK ){
23085       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
23086       close_db(pDest);
23087       return 1;
23088     }
23089     if( bAsync ){
23090       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
23091                    0, 0, 0);
23092     }
23093     open_db(p, 0);
23094     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
23095     if( pBackup==0 ){
23096       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
23097       close_db(pDest);
23098       return 1;
23099     }
23100     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
23101     sqlite3_backup_finish(pBackup);
23102     if( rc==SQLITE_DONE ){
23103       rc = 0;
23104     }else{
23105       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
23106       rc = 1;
23107     }
23108     close_db(pDest);
23109   }else
23110 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23111 
23112   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
23113     if( nArg==2 ){
23114       bail_on_error = booleanValue(azArg[1]);
23115     }else{
23116       raw_printf(stderr, "Usage: .bail on|off\n");
23117       rc = 1;
23118     }
23119   }else
23120 
23121   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
23122     if( nArg==2 ){
23123       if( booleanValue(azArg[1]) ){
23124         setBinaryMode(p->out, 1);
23125       }else{
23126         setTextMode(p->out, 1);
23127       }
23128     }else{
23129       raw_printf(stderr, "Usage: .binary on|off\n");
23130       rc = 1;
23131     }
23132   }else
23133 
23134   /* The undocumented ".breakpoint" command causes a call to the no-op
23135   ** routine named test_breakpoint().
23136   */
23137   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
23138     test_breakpoint();
23139   }else
23140 
23141 #ifndef SQLITE_SHELL_FIDDLE
23142   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
23143     failIfSafeMode(p, "cannot run .cd in safe mode");
23144     if( nArg==2 ){
23145 #if defined(_WIN32) || defined(WIN32)
23146       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
23147       rc = !SetCurrentDirectoryW(z);
23148       sqlite3_free(z);
23149 #else
23150       rc = chdir(azArg[1]);
23151 #endif
23152       if( rc ){
23153         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
23154         rc = 1;
23155       }
23156     }else{
23157       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
23158       rc = 1;
23159     }
23160   }else
23161 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23162 
23163   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
23164     if( nArg==2 ){
23165       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
23166     }else{
23167       raw_printf(stderr, "Usage: .changes on|off\n");
23168       rc = 1;
23169     }
23170   }else
23171 
23172 #ifndef SQLITE_SHELL_FIDDLE
23173   /* Cancel output redirection, if it is currently set (by .testcase)
23174   ** Then read the content of the testcase-out.txt file and compare against
23175   ** azArg[1].  If there are differences, report an error and exit.
23176   */
23177   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
23178     char *zRes = 0;
23179     output_reset(p);
23180     if( nArg!=2 ){
23181       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
23182       rc = 2;
23183     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
23184       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
23185       rc = 2;
23186     }else if( testcase_glob(azArg[1],zRes)==0 ){
23187       utf8_printf(stderr,
23188                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
23189                  p->zTestcase, azArg[1], zRes);
23190       rc = 1;
23191     }else{
23192       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
23193       p->nCheck++;
23194     }
23195     sqlite3_free(zRes);
23196   }else
23197 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23198 
23199 #ifndef SQLITE_SHELL_FIDDLE
23200   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
23201     failIfSafeMode(p, "cannot run .clone in safe mode");
23202     if( nArg==2 ){
23203       tryToClone(p, azArg[1]);
23204     }else{
23205       raw_printf(stderr, "Usage: .clone FILENAME\n");
23206       rc = 1;
23207     }
23208   }else
23209 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23210 
23211   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
23212     if( nArg==1 ){
23213       /* List available connections */
23214       int i;
23215       for(i=0; i<ArraySize(p->aAuxDb); i++){
23216         const char *zFile = p->aAuxDb[i].zDbFilename;
23217         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
23218           zFile = "(not open)";
23219         }else if( zFile==0 ){
23220           zFile = "(memory)";
23221         }else if( zFile[0]==0 ){
23222           zFile = "(temporary-file)";
23223         }
23224         if( p->pAuxDb == &p->aAuxDb[i] ){
23225           utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
23226         }else if( p->aAuxDb[i].db!=0 ){
23227           utf8_printf(stdout, "       %d: %s\n", i, zFile);
23228         }
23229       }
23230     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
23231       int i = azArg[1][0] - '0';
23232       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
23233         p->pAuxDb->db = p->db;
23234         p->pAuxDb = &p->aAuxDb[i];
23235         globalDb = p->db = p->pAuxDb->db;
23236         p->pAuxDb->db = 0;
23237       }
23238     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
23239            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
23240       int i = azArg[2][0] - '0';
23241       if( i<0 || i>=ArraySize(p->aAuxDb) ){
23242         /* No-op */
23243       }else if( p->pAuxDb == &p->aAuxDb[i] ){
23244         raw_printf(stderr, "cannot close the active database connection\n");
23245         rc = 1;
23246       }else if( p->aAuxDb[i].db ){
23247         session_close_all(p, i);
23248         close_db(p->aAuxDb[i].db);
23249         p->aAuxDb[i].db = 0;
23250       }
23251     }else{
23252       raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
23253       rc = 1;
23254     }
23255   }else
23256 
23257   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
23258     char **azName = 0;
23259     int nName = 0;
23260     sqlite3_stmt *pStmt;
23261     int i;
23262     open_db(p, 0);
23263     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
23264     if( rc ){
23265       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
23266       rc = 1;
23267     }else{
23268       while( sqlite3_step(pStmt)==SQLITE_ROW ){
23269         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
23270         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
23271         if( zSchema==0 || zFile==0 ) continue;
23272         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
23273         shell_check_oom(azName);
23274         azName[nName*2] = strdup(zSchema);
23275         azName[nName*2+1] = strdup(zFile);
23276         nName++;
23277       }
23278     }
23279     sqlite3_finalize(pStmt);
23280     for(i=0; i<nName; i++){
23281       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
23282       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
23283       const char *z = azName[i*2+1];
23284       utf8_printf(p->out, "%s: %s %s%s\n",
23285          azName[i*2],
23286          z && z[0] ? z : "\"\"",
23287          bRdonly ? "r/o" : "r/w",
23288          eTxn==SQLITE_TXN_NONE ? "" :
23289             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
23290       free(azName[i*2]);
23291       free(azName[i*2+1]);
23292     }
23293     sqlite3_free(azName);
23294   }else
23295 
23296   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
23297     static const struct DbConfigChoices {
23298       const char *zName;
23299       int op;
23300     } aDbConfig[] = {
23301         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
23302         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
23303         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
23304         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
23305         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
23306         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
23307         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
23308         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
23309         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
23310         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
23311         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
23312         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
23313         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
23314         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
23315         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
23316         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
23317     };
23318     int ii, v;
23319     open_db(p, 0);
23320     for(ii=0; ii<ArraySize(aDbConfig); ii++){
23321       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
23322       if( nArg>=3 ){
23323         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
23324       }
23325       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
23326       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
23327       if( nArg>1 ) break;
23328     }
23329     if( nArg>1 && ii==ArraySize(aDbConfig) ){
23330       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
23331       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
23332     }
23333   }else
23334 
23335 #if SQLITE_SHELL_HAVE_RECOVER
23336   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
23337     rc = shell_dbinfo_command(p, nArg, azArg);
23338   }else
23339 
23340   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
23341     open_db(p, 0);
23342     rc = recoverDatabaseCmd(p, nArg, azArg);
23343   }else
23344 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23345 
23346   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
23347     char *zLike = 0;
23348     char *zSql;
23349     int i;
23350     int savedShowHeader = p->showHeader;
23351     int savedShellFlags = p->shellFlgs;
23352     ShellClearFlag(p,
23353        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
23354        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
23355     for(i=1; i<nArg; i++){
23356       if( azArg[i][0]=='-' ){
23357         const char *z = azArg[i]+1;
23358         if( z[0]=='-' ) z++;
23359         if( cli_strcmp(z,"preserve-rowids")==0 ){
23360 #ifdef SQLITE_OMIT_VIRTUALTABLE
23361           raw_printf(stderr, "The --preserve-rowids option is not compatible"
23362                              " with SQLITE_OMIT_VIRTUALTABLE\n");
23363           rc = 1;
23364           sqlite3_free(zLike);
23365           goto meta_command_exit;
23366 #else
23367           ShellSetFlag(p, SHFLG_PreserveRowid);
23368 #endif
23369         }else
23370         if( cli_strcmp(z,"newlines")==0 ){
23371           ShellSetFlag(p, SHFLG_Newlines);
23372         }else
23373         if( cli_strcmp(z,"data-only")==0 ){
23374           ShellSetFlag(p, SHFLG_DumpDataOnly);
23375         }else
23376         if( cli_strcmp(z,"nosys")==0 ){
23377           ShellSetFlag(p, SHFLG_DumpNoSys);
23378         }else
23379         {
23380           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
23381           rc = 1;
23382           sqlite3_free(zLike);
23383           goto meta_command_exit;
23384         }
23385       }else{
23386         /* azArg[i] contains a LIKE pattern. This ".dump" request should
23387         ** only dump data for tables for which either the table name matches
23388         ** the LIKE pattern, or the table appears to be a shadow table of
23389         ** a virtual table for which the name matches the LIKE pattern.
23390         */
23391         char *zExpr = sqlite3_mprintf(
23392             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
23393             "  SELECT 1 FROM sqlite_schema WHERE "
23394             "    name LIKE %Q ESCAPE '\\' AND"
23395             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
23396             "    substr(o.name, 1, length(name)+1) == (name||'_')"
23397             ")", azArg[i], azArg[i]
23398         );
23399 
23400         if( zLike ){
23401           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
23402         }else{
23403           zLike = zExpr;
23404         }
23405       }
23406     }
23407 
23408     open_db(p, 0);
23409 
23410     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23411       /* When playing back a "dump", the content might appear in an order
23412       ** which causes immediate foreign key constraints to be violated.
23413       ** So disable foreign-key constraint enforcement to prevent problems. */
23414       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
23415       raw_printf(p->out, "BEGIN TRANSACTION;\n");
23416     }
23417     p->writableSchema = 0;
23418     p->showHeader = 0;
23419     /* Set writable_schema=ON since doing so forces SQLite to initialize
23420     ** as much of the schema as it can even if the sqlite_schema table is
23421     ** corrupt. */
23422     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
23423     p->nErr = 0;
23424     if( zLike==0 ) zLike = sqlite3_mprintf("true");
23425     zSql = sqlite3_mprintf(
23426       "SELECT name, type, sql FROM sqlite_schema AS o "
23427       "WHERE (%s) AND type=='table'"
23428       "  AND sql NOT NULL"
23429       " ORDER BY tbl_name='sqlite_sequence', rowid",
23430       zLike
23431     );
23432     run_schema_dump_query(p,zSql);
23433     sqlite3_free(zSql);
23434     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23435       zSql = sqlite3_mprintf(
23436         "SELECT sql FROM sqlite_schema AS o "
23437         "WHERE (%s) AND sql NOT NULL"
23438         "  AND type IN ('index','trigger','view')",
23439         zLike
23440       );
23441       run_table_dump_query(p, zSql);
23442       sqlite3_free(zSql);
23443     }
23444     sqlite3_free(zLike);
23445     if( p->writableSchema ){
23446       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
23447       p->writableSchema = 0;
23448     }
23449     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
23450     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
23451     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23452       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
23453     }
23454     p->showHeader = savedShowHeader;
23455     p->shellFlgs = savedShellFlags;
23456   }else
23457 
23458   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
23459     if( nArg==2 ){
23460       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
23461     }else{
23462       raw_printf(stderr, "Usage: .echo on|off\n");
23463       rc = 1;
23464     }
23465   }else
23466 
23467   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
23468     if( nArg==2 ){
23469       p->autoEQPtest = 0;
23470       if( p->autoEQPtrace ){
23471         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
23472         p->autoEQPtrace = 0;
23473       }
23474       if( cli_strcmp(azArg[1],"full")==0 ){
23475         p->autoEQP = AUTOEQP_full;
23476       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
23477         p->autoEQP = AUTOEQP_trigger;
23478 #ifdef SQLITE_DEBUG
23479       }else if( cli_strcmp(azArg[1],"test")==0 ){
23480         p->autoEQP = AUTOEQP_on;
23481         p->autoEQPtest = 1;
23482       }else if( cli_strcmp(azArg[1],"trace")==0 ){
23483         p->autoEQP = AUTOEQP_full;
23484         p->autoEQPtrace = 1;
23485         open_db(p, 0);
23486         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
23487         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
23488 #endif
23489       }else{
23490         p->autoEQP = (u8)booleanValue(azArg[1]);
23491       }
23492     }else{
23493       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
23494       rc = 1;
23495     }
23496   }else
23497 
23498 #ifndef SQLITE_SHELL_FIDDLE
23499   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
23500     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
23501     rc = 2;
23502   }else
23503 #endif
23504 
23505   /* The ".explain" command is automatic now.  It is largely pointless.  It
23506   ** retained purely for backwards compatibility */
23507   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
23508     int val = 1;
23509     if( nArg>=2 ){
23510       if( cli_strcmp(azArg[1],"auto")==0 ){
23511         val = 99;
23512       }else{
23513         val =  booleanValue(azArg[1]);
23514       }
23515     }
23516     if( val==1 && p->mode!=MODE_Explain ){
23517       p->normalMode = p->mode;
23518       p->mode = MODE_Explain;
23519       p->autoExplain = 0;
23520     }else if( val==0 ){
23521       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
23522       p->autoExplain = 0;
23523     }else if( val==99 ){
23524       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
23525       p->autoExplain = 1;
23526     }
23527   }else
23528 
23529 #ifndef SQLITE_OMIT_VIRTUALTABLE
23530   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
23531     if( p->bSafeMode ){
23532       raw_printf(stderr,
23533         "Cannot run experimental commands such as \"%s\" in safe mode\n",
23534         azArg[0]);
23535       rc = 1;
23536     }else{
23537       open_db(p, 0);
23538       expertDotCommand(p, azArg, nArg);
23539     }
23540   }else
23541 #endif
23542 
23543   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
23544     static const struct {
23545        const char *zCtrlName;   /* Name of a test-control option */
23546        int ctrlCode;            /* Integer code for that option */
23547        const char *zUsage;      /* Usage notes */
23548     } aCtrl[] = {
23549       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
23550       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
23551       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
23552       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
23553       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
23554    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
23555       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
23556       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
23557       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
23558       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
23559    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
23560     };
23561     int filectrl = -1;
23562     int iCtrl = -1;
23563     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
23564     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
23565     int n2, i;
23566     const char *zCmd = 0;
23567     const char *zSchema = 0;
23568 
23569     open_db(p, 0);
23570     zCmd = nArg>=2 ? azArg[1] : "help";
23571 
23572     if( zCmd[0]=='-'
23573      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
23574      && nArg>=4
23575     ){
23576       zSchema = azArg[2];
23577       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
23578       nArg -= 2;
23579       zCmd = azArg[1];
23580     }
23581 
23582     /* The argument can optionally begin with "-" or "--" */
23583     if( zCmd[0]=='-' && zCmd[1] ){
23584       zCmd++;
23585       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
23586     }
23587 
23588     /* --help lists all file-controls */
23589     if( cli_strcmp(zCmd,"help")==0 ){
23590       utf8_printf(p->out, "Available file-controls:\n");
23591       for(i=0; i<ArraySize(aCtrl); i++){
23592         utf8_printf(p->out, "  .filectrl %s %s\n",
23593                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
23594       }
23595       rc = 1;
23596       goto meta_command_exit;
23597     }
23598 
23599     /* convert filectrl text option to value. allow any unique prefix
23600     ** of the option name, or a numerical value. */
23601     n2 = strlen30(zCmd);
23602     for(i=0; i<ArraySize(aCtrl); i++){
23603       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
23604         if( filectrl<0 ){
23605           filectrl = aCtrl[i].ctrlCode;
23606           iCtrl = i;
23607         }else{
23608           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
23609                               "Use \".filectrl --help\" for help\n", zCmd);
23610           rc = 1;
23611           goto meta_command_exit;
23612         }
23613       }
23614     }
23615     if( filectrl<0 ){
23616       utf8_printf(stderr,"Error: unknown file-control: %s\n"
23617                          "Use \".filectrl --help\" for help\n", zCmd);
23618     }else{
23619       switch(filectrl){
23620         case SQLITE_FCNTL_SIZE_LIMIT: {
23621           if( nArg!=2 && nArg!=3 ) break;
23622           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
23623           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
23624           isOk = 1;
23625           break;
23626         }
23627         case SQLITE_FCNTL_LOCK_TIMEOUT:
23628         case SQLITE_FCNTL_CHUNK_SIZE: {
23629           int x;
23630           if( nArg!=3 ) break;
23631           x = (int)integerValue(azArg[2]);
23632           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23633           isOk = 2;
23634           break;
23635         }
23636         case SQLITE_FCNTL_PERSIST_WAL:
23637         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
23638           int x;
23639           if( nArg!=2 && nArg!=3 ) break;
23640           x = nArg==3 ? booleanValue(azArg[2]) : -1;
23641           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23642           iRes = x;
23643           isOk = 1;
23644           break;
23645         }
23646         case SQLITE_FCNTL_DATA_VERSION:
23647         case SQLITE_FCNTL_HAS_MOVED: {
23648           int x;
23649           if( nArg!=2 ) break;
23650           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23651           iRes = x;
23652           isOk = 1;
23653           break;
23654         }
23655         case SQLITE_FCNTL_TEMPFILENAME: {
23656           char *z = 0;
23657           if( nArg!=2 ) break;
23658           sqlite3_file_control(p->db, zSchema, filectrl, &z);
23659           if( z ){
23660             utf8_printf(p->out, "%s\n", z);
23661             sqlite3_free(z);
23662           }
23663           isOk = 2;
23664           break;
23665         }
23666         case SQLITE_FCNTL_RESERVE_BYTES: {
23667           int x;
23668           if( nArg>=3 ){
23669             x = atoi(azArg[2]);
23670             sqlite3_file_control(p->db, zSchema, filectrl, &x);
23671           }
23672           x = -1;
23673           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23674           utf8_printf(p->out,"%d\n", x);
23675           isOk = 2;
23676           break;
23677         }
23678       }
23679     }
23680     if( isOk==0 && iCtrl>=0 ){
23681       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
23682       rc = 1;
23683     }else if( isOk==1 ){
23684       char zBuf[100];
23685       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
23686       raw_printf(p->out, "%s\n", zBuf);
23687     }
23688   }else
23689 
23690   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
23691     ShellState data;
23692     int doStats = 0;
23693     memcpy(&data, p, sizeof(data));
23694     data.showHeader = 0;
23695     data.cMode = data.mode = MODE_Semi;
23696     if( nArg==2 && optionMatch(azArg[1], "indent") ){
23697       data.cMode = data.mode = MODE_Pretty;
23698       nArg = 1;
23699     }
23700     if( nArg!=1 ){
23701       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
23702       rc = 1;
23703       goto meta_command_exit;
23704     }
23705     open_db(p, 0);
23706     rc = sqlite3_exec(p->db,
23707        "SELECT sql FROM"
23708        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
23709        "     FROM sqlite_schema UNION ALL"
23710        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
23711        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
23712        "ORDER BY x",
23713        callback, &data, 0
23714     );
23715     if( rc==SQLITE_OK ){
23716       sqlite3_stmt *pStmt;
23717       rc = sqlite3_prepare_v2(p->db,
23718                "SELECT rowid FROM sqlite_schema"
23719                " WHERE name GLOB 'sqlite_stat[134]'",
23720                -1, &pStmt, 0);
23721       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
23722       sqlite3_finalize(pStmt);
23723     }
23724     if( doStats==0 ){
23725       raw_printf(p->out, "/* No STAT tables available */\n");
23726     }else{
23727       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
23728       data.cMode = data.mode = MODE_Insert;
23729       data.zDestTable = "sqlite_stat1";
23730       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
23731       data.zDestTable = "sqlite_stat4";
23732       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
23733       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
23734     }
23735   }else
23736 
23737   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
23738     if( nArg==2 ){
23739       p->showHeader = booleanValue(azArg[1]);
23740       p->shellFlgs |= SHFLG_HeaderSet;
23741     }else{
23742       raw_printf(stderr, "Usage: .headers on|off\n");
23743       rc = 1;
23744     }
23745   }else
23746 
23747   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
23748     if( nArg>=2 ){
23749       n = showHelp(p->out, azArg[1]);
23750       if( n==0 ){
23751         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
23752       }
23753     }else{
23754       showHelp(p->out, 0);
23755     }
23756   }else
23757 
23758 #ifndef SQLITE_SHELL_FIDDLE
23759   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
23760     char *zTable = 0;           /* Insert data into this table */
23761     char *zSchema = 0;          /* within this schema (may default to "main") */
23762     char *zFile = 0;            /* Name of file to extra content from */
23763     sqlite3_stmt *pStmt = NULL; /* A statement */
23764     int nCol;                   /* Number of columns in the table */
23765     int nByte;                  /* Number of bytes in an SQL string */
23766     int i, j;                   /* Loop counters */
23767     int needCommit;             /* True to COMMIT or ROLLBACK at end */
23768     int nSep;                   /* Number of bytes in p->colSeparator[] */
23769     char *zSql;                 /* An SQL statement */
23770     char *zFullTabName;         /* Table name with schema if applicable */
23771     ImportCtx sCtx;             /* Reader context */
23772     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
23773     int eVerbose = 0;           /* Larger for more console output */
23774     int nSkip = 0;              /* Initial lines to skip */
23775     int useOutputMode = 1;      /* Use output mode to determine separators */
23776     char *zCreate = 0;          /* CREATE TABLE statement text */
23777 
23778     failIfSafeMode(p, "cannot run .import in safe mode");
23779     memset(&sCtx, 0, sizeof(sCtx));
23780     if( p->mode==MODE_Ascii ){
23781       xRead = ascii_read_one_field;
23782     }else{
23783       xRead = csv_read_one_field;
23784     }
23785     rc = 1;
23786     for(i=1; i<nArg; i++){
23787       char *z = azArg[i];
23788       if( z[0]=='-' && z[1]=='-' ) z++;
23789       if( z[0]!='-' ){
23790         if( zFile==0 ){
23791           zFile = z;
23792         }else if( zTable==0 ){
23793           zTable = z;
23794         }else{
23795           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
23796           showHelp(p->out, "import");
23797           goto meta_command_exit;
23798         }
23799       }else if( cli_strcmp(z,"-v")==0 ){
23800         eVerbose++;
23801       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
23802         zSchema = azArg[++i];
23803       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
23804         nSkip = integerValue(azArg[++i]);
23805       }else if( cli_strcmp(z,"-ascii")==0 ){
23806         sCtx.cColSep = SEP_Unit[0];
23807         sCtx.cRowSep = SEP_Record[0];
23808         xRead = ascii_read_one_field;
23809         useOutputMode = 0;
23810       }else if( cli_strcmp(z,"-csv")==0 ){
23811         sCtx.cColSep = ',';
23812         sCtx.cRowSep = '\n';
23813         xRead = csv_read_one_field;
23814         useOutputMode = 0;
23815       }else{
23816         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
23817         showHelp(p->out, "import");
23818         goto meta_command_exit;
23819       }
23820     }
23821     if( zTable==0 ){
23822       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
23823                   zFile==0 ? "FILE" : "TABLE");
23824       showHelp(p->out, "import");
23825       goto meta_command_exit;
23826     }
23827     seenInterrupt = 0;
23828     open_db(p, 0);
23829     if( useOutputMode ){
23830       /* If neither the --csv or --ascii options are specified, then set
23831       ** the column and row separator characters from the output mode. */
23832       nSep = strlen30(p->colSeparator);
23833       if( nSep==0 ){
23834         raw_printf(stderr,
23835                    "Error: non-null column separator required for import\n");
23836         goto meta_command_exit;
23837       }
23838       if( nSep>1 ){
23839         raw_printf(stderr,
23840               "Error: multi-character column separators not allowed"
23841               " for import\n");
23842         goto meta_command_exit;
23843       }
23844       nSep = strlen30(p->rowSeparator);
23845       if( nSep==0 ){
23846         raw_printf(stderr,
23847             "Error: non-null row separator required for import\n");
23848         goto meta_command_exit;
23849       }
23850       if( nSep==2 && p->mode==MODE_Csv
23851        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
23852       ){
23853         /* When importing CSV (only), if the row separator is set to the
23854         ** default output row separator, change it to the default input
23855         ** row separator.  This avoids having to maintain different input
23856         ** and output row separators. */
23857         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
23858         nSep = strlen30(p->rowSeparator);
23859       }
23860       if( nSep>1 ){
23861         raw_printf(stderr, "Error: multi-character row separators not allowed"
23862                            " for import\n");
23863         goto meta_command_exit;
23864       }
23865       sCtx.cColSep = p->colSeparator[0];
23866       sCtx.cRowSep = p->rowSeparator[0];
23867     }
23868     sCtx.zFile = zFile;
23869     sCtx.nLine = 1;
23870     if( sCtx.zFile[0]=='|' ){
23871 #ifdef SQLITE_OMIT_POPEN
23872       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
23873       goto meta_command_exit;
23874 #else
23875       sCtx.in = popen(sCtx.zFile+1, "r");
23876       sCtx.zFile = "<pipe>";
23877       sCtx.xCloser = pclose;
23878 #endif
23879     }else{
23880       sCtx.in = fopen(sCtx.zFile, "rb");
23881       sCtx.xCloser = fclose;
23882     }
23883     if( sCtx.in==0 ){
23884       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
23885       goto meta_command_exit;
23886     }
23887     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
23888       char zSep[2];
23889       zSep[1] = 0;
23890       zSep[0] = sCtx.cColSep;
23891       utf8_printf(p->out, "Column separator ");
23892       output_c_string(p->out, zSep);
23893       utf8_printf(p->out, ", row separator ");
23894       zSep[0] = sCtx.cRowSep;
23895       output_c_string(p->out, zSep);
23896       utf8_printf(p->out, "\n");
23897     }
23898     sCtx.z = sqlite3_malloc64(120);
23899     if( sCtx.z==0 ){
23900       import_cleanup(&sCtx);
23901       shell_out_of_memory();
23902     }
23903     /* Below, resources must be freed before exit. */
23904     while( (nSkip--)>0 ){
23905       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
23906     }
23907     if( zSchema!=0 ){
23908       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
23909     }else{
23910       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
23911     }
23912     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
23913     if( zSql==0 || zFullTabName==0 ){
23914       import_cleanup(&sCtx);
23915       shell_out_of_memory();
23916     }
23917     nByte = strlen30(zSql);
23918     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
23919     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
23920     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
23921       sqlite3 *dbCols = 0;
23922       char *zRenames = 0;
23923       char *zColDefs;
23924       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
23925       while( xRead(&sCtx) ){
23926         zAutoColumn(sCtx.z, &dbCols, 0);
23927         if( sCtx.cTerm!=sCtx.cColSep ) break;
23928       }
23929       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
23930       if( zRenames!=0 ){
23931         utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
23932                     "Columns renamed during .import %s due to duplicates:\n"
23933                     "%s\n", sCtx.zFile, zRenames);
23934         sqlite3_free(zRenames);
23935       }
23936       assert(dbCols==0);
23937       if( zColDefs==0 ){
23938         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
23939       import_fail:
23940         sqlite3_free(zCreate);
23941         sqlite3_free(zSql);
23942         sqlite3_free(zFullTabName);
23943         import_cleanup(&sCtx);
23944         rc = 1;
23945         goto meta_command_exit;
23946       }
23947       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
23948       if( eVerbose>=1 ){
23949         utf8_printf(p->out, "%s\n", zCreate);
23950       }
23951       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
23952       if( rc ){
23953         utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
23954         goto import_fail;
23955       }
23956       sqlite3_free(zCreate);
23957       zCreate = 0;
23958       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
23959     }
23960     if( rc ){
23961       if (pStmt) sqlite3_finalize(pStmt);
23962       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
23963       goto import_fail;
23964     }
23965     sqlite3_free(zSql);
23966     nCol = sqlite3_column_count(pStmt);
23967     sqlite3_finalize(pStmt);
23968     pStmt = 0;
23969     if( nCol==0 ) return 0; /* no columns, no error */
23970     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
23971     if( zSql==0 ){
23972       import_cleanup(&sCtx);
23973       shell_out_of_memory();
23974     }
23975     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
23976     j = strlen30(zSql);
23977     for(i=1; i<nCol; i++){
23978       zSql[j++] = ',';
23979       zSql[j++] = '?';
23980     }
23981     zSql[j++] = ')';
23982     zSql[j] = 0;
23983     if( eVerbose>=2 ){
23984       utf8_printf(p->out, "Insert using: %s\n", zSql);
23985     }
23986     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
23987     if( rc ){
23988       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
23989       if (pStmt) sqlite3_finalize(pStmt);
23990       goto import_fail;
23991     }
23992     sqlite3_free(zSql);
23993     sqlite3_free(zFullTabName);
23994     needCommit = sqlite3_get_autocommit(p->db);
23995     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
23996     do{
23997       int startLine = sCtx.nLine;
23998       for(i=0; i<nCol; i++){
23999         char *z = xRead(&sCtx);
24000         /*
24001         ** Did we reach end-of-file before finding any columns?
24002         ** If so, stop instead of NULL filling the remaining columns.
24003         */
24004         if( z==0 && i==0 ) break;
24005         /*
24006         ** Did we reach end-of-file OR end-of-line before finding any
24007         ** columns in ASCII mode?  If so, stop instead of NULL filling
24008         ** the remaining columns.
24009         */
24010         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
24011         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
24012         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
24013           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
24014                           "filling the rest with NULL\n",
24015                           sCtx.zFile, startLine, nCol, i+1);
24016           i += 2;
24017           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
24018         }
24019       }
24020       if( sCtx.cTerm==sCtx.cColSep ){
24021         do{
24022           xRead(&sCtx);
24023           i++;
24024         }while( sCtx.cTerm==sCtx.cColSep );
24025         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
24026                         "extras ignored\n",
24027                         sCtx.zFile, startLine, nCol, i);
24028       }
24029       if( i>=nCol ){
24030         sqlite3_step(pStmt);
24031         rc = sqlite3_reset(pStmt);
24032         if( rc!=SQLITE_OK ){
24033           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
24034                       startLine, sqlite3_errmsg(p->db));
24035           sCtx.nErr++;
24036         }else{
24037           sCtx.nRow++;
24038         }
24039       }
24040     }while( sCtx.cTerm!=EOF );
24041 
24042     import_cleanup(&sCtx);
24043     sqlite3_finalize(pStmt);
24044     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
24045     if( eVerbose>0 ){
24046       utf8_printf(p->out,
24047           "Added %d rows with %d errors using %d lines of input\n",
24048           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
24049     }
24050   }else
24051 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24052 
24053 #ifndef SQLITE_UNTESTABLE
24054   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
24055     char *zSql;
24056     char *zCollist = 0;
24057     sqlite3_stmt *pStmt;
24058     int tnum = 0;
24059     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
24060     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
24061     int i;
24062     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
24063       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
24064                           "       .imposter off\n");
24065       /* Also allowed, but not documented:
24066       **
24067       **    .imposter TABLE IMPOSTER
24068       **
24069       ** where TABLE is a WITHOUT ROWID table.  In that case, the
24070       ** imposter is another WITHOUT ROWID table with the columns in
24071       ** storage order. */
24072       rc = 1;
24073       goto meta_command_exit;
24074     }
24075     open_db(p, 0);
24076     if( nArg==2 ){
24077       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
24078       goto meta_command_exit;
24079     }
24080     zSql = sqlite3_mprintf(
24081       "SELECT rootpage, 0 FROM sqlite_schema"
24082       " WHERE name='%q' AND type='index'"
24083       "UNION ALL "
24084       "SELECT rootpage, 1 FROM sqlite_schema"
24085       " WHERE name='%q' AND type='table'"
24086       "   AND sql LIKE '%%without%%rowid%%'",
24087       azArg[1], azArg[1]
24088     );
24089     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24090     sqlite3_free(zSql);
24091     if( sqlite3_step(pStmt)==SQLITE_ROW ){
24092       tnum = sqlite3_column_int(pStmt, 0);
24093       isWO = sqlite3_column_int(pStmt, 1);
24094     }
24095     sqlite3_finalize(pStmt);
24096     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
24097     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24098     sqlite3_free(zSql);
24099     i = 0;
24100     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24101       char zLabel[20];
24102       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
24103       i++;
24104       if( zCol==0 ){
24105         if( sqlite3_column_int(pStmt,1)==-1 ){
24106           zCol = "_ROWID_";
24107         }else{
24108           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
24109           zCol = zLabel;
24110         }
24111       }
24112       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
24113         lenPK = (int)strlen(zCollist);
24114       }
24115       if( zCollist==0 ){
24116         zCollist = sqlite3_mprintf("\"%w\"", zCol);
24117       }else{
24118         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
24119       }
24120     }
24121     sqlite3_finalize(pStmt);
24122     if( i==0 || tnum==0 ){
24123       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
24124       rc = 1;
24125       sqlite3_free(zCollist);
24126       goto meta_command_exit;
24127     }
24128     if( lenPK==0 ) lenPK = 100000;
24129     zSql = sqlite3_mprintf(
24130           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
24131           azArg[2], zCollist, lenPK, zCollist);
24132     sqlite3_free(zCollist);
24133     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
24134     if( rc==SQLITE_OK ){
24135       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
24136       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
24137       if( rc ){
24138         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
24139       }else{
24140         utf8_printf(stdout, "%s;\n", zSql);
24141         raw_printf(stdout,
24142           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
24143           azArg[1], isWO ? "table" : "index"
24144         );
24145       }
24146     }else{
24147       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
24148       rc = 1;
24149     }
24150     sqlite3_free(zSql);
24151   }else
24152 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
24153 
24154 #ifdef SQLITE_ENABLE_IOTRACE
24155   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
24156     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
24157     if( iotrace && iotrace!=stdout ) fclose(iotrace);
24158     iotrace = 0;
24159     if( nArg<2 ){
24160       sqlite3IoTrace = 0;
24161     }else if( cli_strcmp(azArg[1], "-")==0 ){
24162       sqlite3IoTrace = iotracePrintf;
24163       iotrace = stdout;
24164     }else{
24165       iotrace = fopen(azArg[1], "w");
24166       if( iotrace==0 ){
24167         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
24168         sqlite3IoTrace = 0;
24169         rc = 1;
24170       }else{
24171         sqlite3IoTrace = iotracePrintf;
24172       }
24173     }
24174   }else
24175 #endif
24176 
24177   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
24178     static const struct {
24179        const char *zLimitName;   /* Name of a limit */
24180        int limitCode;            /* Integer code for that limit */
24181     } aLimit[] = {
24182       { "length",                SQLITE_LIMIT_LENGTH                    },
24183       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
24184       { "column",                SQLITE_LIMIT_COLUMN                    },
24185       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
24186       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
24187       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
24188       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
24189       { "attached",              SQLITE_LIMIT_ATTACHED                  },
24190       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
24191       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
24192       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
24193       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
24194     };
24195     int i, n2;
24196     open_db(p, 0);
24197     if( nArg==1 ){
24198       for(i=0; i<ArraySize(aLimit); i++){
24199         printf("%20s %d\n", aLimit[i].zLimitName,
24200                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
24201       }
24202     }else if( nArg>3 ){
24203       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
24204       rc = 1;
24205       goto meta_command_exit;
24206     }else{
24207       int iLimit = -1;
24208       n2 = strlen30(azArg[1]);
24209       for(i=0; i<ArraySize(aLimit); i++){
24210         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
24211           if( iLimit<0 ){
24212             iLimit = i;
24213           }else{
24214             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
24215             rc = 1;
24216             goto meta_command_exit;
24217           }
24218         }
24219       }
24220       if( iLimit<0 ){
24221         utf8_printf(stderr, "unknown limit: \"%s\"\n"
24222                         "enter \".limits\" with no arguments for a list.\n",
24223                          azArg[1]);
24224         rc = 1;
24225         goto meta_command_exit;
24226       }
24227       if( nArg==3 ){
24228         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
24229                       (int)integerValue(azArg[2]));
24230       }
24231       printf("%20s %d\n", aLimit[iLimit].zLimitName,
24232              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
24233     }
24234   }else
24235 
24236   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
24237     open_db(p, 0);
24238     lintDotCommand(p, azArg, nArg);
24239   }else
24240 
24241 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
24242   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
24243     const char *zFile, *zProc;
24244     char *zErrMsg = 0;
24245     failIfSafeMode(p, "cannot run .load in safe mode");
24246     if( nArg<2 ){
24247       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
24248       rc = 1;
24249       goto meta_command_exit;
24250     }
24251     zFile = azArg[1];
24252     zProc = nArg>=3 ? azArg[2] : 0;
24253     open_db(p, 0);
24254     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
24255     if( rc!=SQLITE_OK ){
24256       utf8_printf(stderr, "Error: %s\n", zErrMsg);
24257       sqlite3_free(zErrMsg);
24258       rc = 1;
24259     }
24260   }else
24261 #endif
24262 
24263 #ifndef SQLITE_SHELL_FIDDLE
24264   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
24265     failIfSafeMode(p, "cannot run .log in safe mode");
24266     if( nArg!=2 ){
24267       raw_printf(stderr, "Usage: .log FILENAME\n");
24268       rc = 1;
24269     }else{
24270       const char *zFile = azArg[1];
24271       output_file_close(p->pLog);
24272       p->pLog = output_file_open(zFile, 0);
24273     }
24274   }else
24275 #endif
24276 
24277   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
24278     const char *zMode = 0;
24279     const char *zTabname = 0;
24280     int i, n2;
24281     ColModeOpts cmOpts = ColModeOpts_default;
24282     for(i=1; i<nArg; i++){
24283       const char *z = azArg[i];
24284       if( optionMatch(z,"wrap") && i+1<nArg ){
24285         cmOpts.iWrap = integerValue(azArg[++i]);
24286       }else if( optionMatch(z,"ww") ){
24287         cmOpts.bWordWrap = 1;
24288       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
24289         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
24290       }else if( optionMatch(z,"quote") ){
24291         cmOpts.bQuote = 1;
24292       }else if( optionMatch(z,"noquote") ){
24293         cmOpts.bQuote = 0;
24294       }else if( zMode==0 ){
24295         zMode = z;
24296         /* Apply defaults for qbox pseudo-mode.  If that
24297          * overwrites already-set values, user was informed of this.
24298          */
24299         if( cli_strcmp(z, "qbox")==0 ){
24300           ColModeOpts cmo = ColModeOpts_default_qbox;
24301           zMode = "box";
24302           cmOpts = cmo;
24303         }
24304       }else if( zTabname==0 ){
24305         zTabname = z;
24306       }else if( z[0]=='-' ){
24307         utf8_printf(stderr, "unknown option: %s\n", z);
24308         utf8_printf(stderr, "options:\n"
24309                             "  --noquote\n"
24310                             "  --quote\n"
24311                             "  --wordwrap on/off\n"
24312                             "  --wrap N\n"
24313                             "  --ww\n");
24314         rc = 1;
24315         goto meta_command_exit;
24316       }else{
24317         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
24318         rc = 1;
24319         goto meta_command_exit;
24320       }
24321     }
24322     if( zMode==0 ){
24323       if( p->mode==MODE_Column
24324        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
24325       ){
24326         raw_printf
24327           (p->out,
24328            "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
24329            modeDescr[p->mode], p->cmOpts.iWrap,
24330            p->cmOpts.bWordWrap ? "on" : "off",
24331            p->cmOpts.bQuote ? "" : "no");
24332       }else{
24333         raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
24334       }
24335       zMode = modeDescr[p->mode];
24336     }
24337     n2 = strlen30(zMode);
24338     if( cli_strncmp(zMode,"lines",n2)==0 ){
24339       p->mode = MODE_Line;
24340       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24341     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
24342       p->mode = MODE_Column;
24343       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
24344         p->showHeader = 1;
24345       }
24346       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24347       p->cmOpts = cmOpts;
24348     }else if( cli_strncmp(zMode,"list",n2)==0 ){
24349       p->mode = MODE_List;
24350       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
24351       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24352     }else if( cli_strncmp(zMode,"html",n2)==0 ){
24353       p->mode = MODE_Html;
24354     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
24355       p->mode = MODE_Tcl;
24356       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
24357       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24358     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
24359       p->mode = MODE_Csv;
24360       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24361       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
24362     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
24363       p->mode = MODE_List;
24364       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
24365     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
24366       p->mode = MODE_Insert;
24367       set_table_name(p, zTabname ? zTabname : "table");
24368     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
24369       p->mode = MODE_Quote;
24370       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24371       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24372     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
24373       p->mode = MODE_Ascii;
24374       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
24375       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
24376     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
24377       p->mode = MODE_Markdown;
24378       p->cmOpts = cmOpts;
24379     }else if( cli_strncmp(zMode,"table",n2)==0 ){
24380       p->mode = MODE_Table;
24381       p->cmOpts = cmOpts;
24382     }else if( cli_strncmp(zMode,"box",n2)==0 ){
24383       p->mode = MODE_Box;
24384       p->cmOpts = cmOpts;
24385     }else if( cli_strncmp(zMode,"count",n2)==0 ){
24386       p->mode = MODE_Count;
24387     }else if( cli_strncmp(zMode,"off",n2)==0 ){
24388       p->mode = MODE_Off;
24389     }else if( cli_strncmp(zMode,"json",n2)==0 ){
24390       p->mode = MODE_Json;
24391     }else{
24392       raw_printf(stderr, "Error: mode should be one of: "
24393          "ascii box column csv html insert json line list markdown "
24394          "qbox quote table tabs tcl\n");
24395       rc = 1;
24396     }
24397     p->cMode = p->mode;
24398   }else
24399 
24400 #ifndef SQLITE_SHELL_FIDDLE
24401   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
24402     if( nArg!=2 ){
24403       raw_printf(stderr, "Usage: .nonce NONCE\n");
24404       rc = 1;
24405     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
24406       raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
24407                  p->lineno, azArg[1]);
24408       exit(1);
24409     }else{
24410       p->bSafeMode = 0;
24411       return 0;  /* Return immediately to bypass the safe mode reset
24412                  ** at the end of this procedure */
24413     }
24414   }else
24415 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24416 
24417   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
24418     if( nArg==2 ){
24419       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
24420                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
24421     }else{
24422       raw_printf(stderr, "Usage: .nullvalue STRING\n");
24423       rc = 1;
24424     }
24425   }else
24426 
24427   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
24428     const char *zFN = 0;     /* Pointer to constant filename */
24429     char *zNewFilename = 0;  /* Name of the database file to open */
24430     int iName = 1;           /* Index in azArg[] of the filename */
24431     int newFlag = 0;         /* True to delete file before opening */
24432     int openMode = SHELL_OPEN_UNSPEC;
24433 
24434     /* Check for command-line arguments */
24435     for(iName=1; iName<nArg; iName++){
24436       const char *z = azArg[iName];
24437 #ifndef SQLITE_SHELL_FIDDLE
24438       if( optionMatch(z,"new") ){
24439         newFlag = 1;
24440 #ifdef SQLITE_HAVE_ZLIB
24441       }else if( optionMatch(z, "zip") ){
24442         openMode = SHELL_OPEN_ZIPFILE;
24443 #endif
24444       }else if( optionMatch(z, "append") ){
24445         openMode = SHELL_OPEN_APPENDVFS;
24446       }else if( optionMatch(z, "readonly") ){
24447         openMode = SHELL_OPEN_READONLY;
24448       }else if( optionMatch(z, "nofollow") ){
24449         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
24450 #ifndef SQLITE_OMIT_DESERIALIZE
24451       }else if( optionMatch(z, "deserialize") ){
24452         openMode = SHELL_OPEN_DESERIALIZE;
24453       }else if( optionMatch(z, "hexdb") ){
24454         openMode = SHELL_OPEN_HEXDB;
24455       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
24456         p->szMax = integerValue(azArg[++iName]);
24457 #endif /* SQLITE_OMIT_DESERIALIZE */
24458       }else
24459 #endif /* !SQLITE_SHELL_FIDDLE */
24460       if( z[0]=='-' ){
24461         utf8_printf(stderr, "unknown option: %s\n", z);
24462         rc = 1;
24463         goto meta_command_exit;
24464       }else if( zFN ){
24465         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
24466         rc = 1;
24467         goto meta_command_exit;
24468       }else{
24469         zFN = z;
24470       }
24471     }
24472 
24473     /* Close the existing database */
24474     session_close_all(p, -1);
24475     close_db(p->db);
24476     p->db = 0;
24477     p->pAuxDb->zDbFilename = 0;
24478     sqlite3_free(p->pAuxDb->zFreeOnClose);
24479     p->pAuxDb->zFreeOnClose = 0;
24480     p->openMode = openMode;
24481     p->openFlags = 0;
24482     p->szMax = 0;
24483 
24484     /* If a filename is specified, try to open it first */
24485     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
24486       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
24487 #ifndef SQLITE_SHELL_FIDDLE
24488       if( p->bSafeMode
24489        && p->openMode!=SHELL_OPEN_HEXDB
24490        && zFN
24491        && cli_strcmp(zFN,":memory:")!=0
24492       ){
24493         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
24494       }
24495 #else
24496       /* WASM mode has its own sandboxed pseudo-filesystem. */
24497 #endif
24498       if( zFN ){
24499         zNewFilename = sqlite3_mprintf("%s", zFN);
24500         shell_check_oom(zNewFilename);
24501       }else{
24502         zNewFilename = 0;
24503       }
24504       p->pAuxDb->zDbFilename = zNewFilename;
24505       open_db(p, OPEN_DB_KEEPALIVE);
24506       if( p->db==0 ){
24507         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
24508         sqlite3_free(zNewFilename);
24509       }else{
24510         p->pAuxDb->zFreeOnClose = zNewFilename;
24511       }
24512     }
24513     if( p->db==0 ){
24514       /* As a fall-back open a TEMP database */
24515       p->pAuxDb->zDbFilename = 0;
24516       open_db(p, 0);
24517     }
24518   }else
24519 
24520 #ifndef SQLITE_SHELL_FIDDLE
24521   if( (c=='o'
24522         && (cli_strncmp(azArg[0], "output", n)==0
24523             || cli_strncmp(azArg[0], "once", n)==0))
24524    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
24525   ){
24526     char *zFile = 0;
24527     int bTxtMode = 0;
24528     int i;
24529     int eMode = 0;
24530     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
24531     unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
24532 
24533     zBOM[0] = 0;
24534     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24535     if( c=='e' ){
24536       eMode = 'x';
24537       bOnce = 2;
24538     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
24539       bOnce = 1;
24540     }
24541     for(i=1; i<nArg; i++){
24542       char *z = azArg[i];
24543       if( z[0]=='-' ){
24544         if( z[1]=='-' ) z++;
24545         if( cli_strcmp(z,"-bom")==0 ){
24546           zBOM[0] = 0xef;
24547           zBOM[1] = 0xbb;
24548           zBOM[2] = 0xbf;
24549           zBOM[3] = 0;
24550         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
24551           eMode = 'x';  /* spreadsheet */
24552         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
24553           eMode = 'e';  /* text editor */
24554         }else{
24555           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
24556                       azArg[i]);
24557           showHelp(p->out, azArg[0]);
24558           rc = 1;
24559           goto meta_command_exit;
24560         }
24561       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
24562         zFile = sqlite3_mprintf("%s", z);
24563         if( zFile && zFile[0]=='|' ){
24564           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
24565           break;
24566         }
24567       }else{
24568         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
24569                     azArg[i]);
24570         showHelp(p->out, azArg[0]);
24571         rc = 1;
24572         sqlite3_free(zFile);
24573         goto meta_command_exit;
24574       }
24575     }
24576     if( zFile==0 ){
24577       zFile = sqlite3_mprintf("stdout");
24578     }
24579     if( bOnce ){
24580       p->outCount = 2;
24581     }else{
24582       p->outCount = 0;
24583     }
24584     output_reset(p);
24585 #ifndef SQLITE_NOHAVE_SYSTEM
24586     if( eMode=='e' || eMode=='x' ){
24587       p->doXdgOpen = 1;
24588       outputModePush(p);
24589       if( eMode=='x' ){
24590         /* spreadsheet mode.  Output as CSV. */
24591         newTempFile(p, "csv");
24592         ShellClearFlag(p, SHFLG_Echo);
24593         p->mode = MODE_Csv;
24594         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24595         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
24596       }else{
24597         /* text editor mode */
24598         newTempFile(p, "txt");
24599         bTxtMode = 1;
24600       }
24601       sqlite3_free(zFile);
24602       zFile = sqlite3_mprintf("%s", p->zTempFile);
24603     }
24604 #endif /* SQLITE_NOHAVE_SYSTEM */
24605     shell_check_oom(zFile);
24606     if( zFile[0]=='|' ){
24607 #ifdef SQLITE_OMIT_POPEN
24608       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24609       rc = 1;
24610       p->out = stdout;
24611 #else
24612       p->out = popen(zFile + 1, "w");
24613       if( p->out==0 ){
24614         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
24615         p->out = stdout;
24616         rc = 1;
24617       }else{
24618         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
24619         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
24620       }
24621 #endif
24622     }else{
24623       p->out = output_file_open(zFile, bTxtMode);
24624       if( p->out==0 ){
24625         if( cli_strcmp(zFile,"off")!=0 ){
24626           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
24627         }
24628         p->out = stdout;
24629         rc = 1;
24630       } else {
24631         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
24632         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
24633       }
24634     }
24635     sqlite3_free(zFile);
24636   }else
24637 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24638 
24639   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
24640     open_db(p,0);
24641     if( nArg<=1 ) goto parameter_syntax_error;
24642 
24643     /* .parameter clear
24644     ** Clear all bind parameters by dropping the TEMP table that holds them.
24645     */
24646     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
24647       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
24648                    0, 0, 0);
24649     }else
24650 
24651     /* .parameter list
24652     ** List all bind parameters.
24653     */
24654     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
24655       sqlite3_stmt *pStmt = 0;
24656       int rx;
24657       int len = 0;
24658       rx = sqlite3_prepare_v2(p->db,
24659              "SELECT max(length(key)) "
24660              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
24661       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24662         len = sqlite3_column_int(pStmt, 0);
24663         if( len>40 ) len = 40;
24664       }
24665       sqlite3_finalize(pStmt);
24666       pStmt = 0;
24667       if( len ){
24668         rx = sqlite3_prepare_v2(p->db,
24669              "SELECT key, quote(value) "
24670              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
24671         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24672           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
24673                       sqlite3_column_text(pStmt,1));
24674         }
24675         sqlite3_finalize(pStmt);
24676       }
24677     }else
24678 
24679     /* .parameter init
24680     ** Make sure the TEMP table used to hold bind parameters exists.
24681     ** Create it if necessary.
24682     */
24683     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
24684       bind_table_init(p);
24685     }else
24686 
24687     /* .parameter set NAME VALUE
24688     ** Set or reset a bind parameter.  NAME should be the full parameter
24689     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
24690     ** VALUE can be in either SQL literal notation, or if not it will be
24691     ** understood to be a text string.
24692     */
24693     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
24694       int rx;
24695       char *zSql;
24696       sqlite3_stmt *pStmt;
24697       const char *zKey = azArg[2];
24698       const char *zValue = azArg[3];
24699       bind_table_init(p);
24700       zSql = sqlite3_mprintf(
24701                   "REPLACE INTO temp.sqlite_parameters(key,value)"
24702                   "VALUES(%Q,%s);", zKey, zValue);
24703       shell_check_oom(zSql);
24704       pStmt = 0;
24705       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24706       sqlite3_free(zSql);
24707       if( rx!=SQLITE_OK ){
24708         sqlite3_finalize(pStmt);
24709         pStmt = 0;
24710         zSql = sqlite3_mprintf(
24711                    "REPLACE INTO temp.sqlite_parameters(key,value)"
24712                    "VALUES(%Q,%Q);", zKey, zValue);
24713         shell_check_oom(zSql);
24714         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24715         sqlite3_free(zSql);
24716         if( rx!=SQLITE_OK ){
24717           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
24718           sqlite3_finalize(pStmt);
24719           pStmt = 0;
24720           rc = 1;
24721         }
24722       }
24723       sqlite3_step(pStmt);
24724       sqlite3_finalize(pStmt);
24725     }else
24726 
24727     /* .parameter unset NAME
24728     ** Remove the NAME binding from the parameter binding table, if it
24729     ** exists.
24730     */
24731     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
24732       char *zSql = sqlite3_mprintf(
24733           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
24734       shell_check_oom(zSql);
24735       sqlite3_exec(p->db, zSql, 0, 0, 0);
24736       sqlite3_free(zSql);
24737     }else
24738     /* If no command name matches, show a syntax error */
24739     parameter_syntax_error:
24740     showHelp(p->out, "parameter");
24741   }else
24742 
24743   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
24744     int i;
24745     for(i=1; i<nArg; i++){
24746       if( i>1 ) raw_printf(p->out, " ");
24747       utf8_printf(p->out, "%s", azArg[i]);
24748     }
24749     raw_printf(p->out, "\n");
24750   }else
24751 
24752 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
24753   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
24754     int i;
24755     int nn = 0;
24756     p->flgProgress = 0;
24757     p->mxProgress = 0;
24758     p->nProgress = 0;
24759     for(i=1; i<nArg; i++){
24760       const char *z = azArg[i];
24761       if( z[0]=='-' ){
24762         z++;
24763         if( z[0]=='-' ) z++;
24764         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
24765           p->flgProgress |= SHELL_PROGRESS_QUIET;
24766           continue;
24767         }
24768         if( cli_strcmp(z,"reset")==0 ){
24769           p->flgProgress |= SHELL_PROGRESS_RESET;
24770           continue;
24771         }
24772         if( cli_strcmp(z,"once")==0 ){
24773           p->flgProgress |= SHELL_PROGRESS_ONCE;
24774           continue;
24775         }
24776         if( cli_strcmp(z,"limit")==0 ){
24777           if( i+1>=nArg ){
24778             utf8_printf(stderr, "Error: missing argument on --limit\n");
24779             rc = 1;
24780             goto meta_command_exit;
24781           }else{
24782             p->mxProgress = (int)integerValue(azArg[++i]);
24783           }
24784           continue;
24785         }
24786         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
24787         rc = 1;
24788         goto meta_command_exit;
24789       }else{
24790         nn = (int)integerValue(z);
24791       }
24792     }
24793     open_db(p, 0);
24794     sqlite3_progress_handler(p->db, nn, progress_handler, p);
24795   }else
24796 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
24797 
24798   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
24799     if( nArg >= 2) {
24800       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
24801     }
24802     if( nArg >= 3) {
24803       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
24804     }
24805   }else
24806 
24807 #ifndef SQLITE_SHELL_FIDDLE
24808   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
24809     rc = 2;
24810   }else
24811 #endif
24812 
24813 #ifndef SQLITE_SHELL_FIDDLE
24814   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
24815     FILE *inSaved = p->in;
24816     int savedLineno = p->lineno;
24817     failIfSafeMode(p, "cannot run .read in safe mode");
24818     if( nArg!=2 ){
24819       raw_printf(stderr, "Usage: .read FILE\n");
24820       rc = 1;
24821       goto meta_command_exit;
24822     }
24823     if( azArg[1][0]=='|' ){
24824 #ifdef SQLITE_OMIT_POPEN
24825       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24826       rc = 1;
24827       p->out = stdout;
24828 #else
24829       p->in = popen(azArg[1]+1, "r");
24830       if( p->in==0 ){
24831         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
24832         rc = 1;
24833       }else{
24834         rc = process_input(p);
24835         pclose(p->in);
24836       }
24837 #endif
24838     }else if( (p->in = openChrSource(azArg[1]))==0 ){
24839       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
24840       rc = 1;
24841     }else{
24842       rc = process_input(p);
24843       fclose(p->in);
24844     }
24845     p->in = inSaved;
24846     p->lineno = savedLineno;
24847   }else
24848 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24849 
24850 #ifndef SQLITE_SHELL_FIDDLE
24851   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
24852     const char *zSrcFile;
24853     const char *zDb;
24854     sqlite3 *pSrc;
24855     sqlite3_backup *pBackup;
24856     int nTimeout = 0;
24857 
24858     failIfSafeMode(p, "cannot run .restore in safe mode");
24859     if( nArg==2 ){
24860       zSrcFile = azArg[1];
24861       zDb = "main";
24862     }else if( nArg==3 ){
24863       zSrcFile = azArg[2];
24864       zDb = azArg[1];
24865     }else{
24866       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
24867       rc = 1;
24868       goto meta_command_exit;
24869     }
24870     rc = sqlite3_open(zSrcFile, &pSrc);
24871     if( rc!=SQLITE_OK ){
24872       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
24873       close_db(pSrc);
24874       return 1;
24875     }
24876     open_db(p, 0);
24877     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
24878     if( pBackup==0 ){
24879       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24880       close_db(pSrc);
24881       return 1;
24882     }
24883     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
24884           || rc==SQLITE_BUSY  ){
24885       if( rc==SQLITE_BUSY ){
24886         if( nTimeout++ >= 3 ) break;
24887         sqlite3_sleep(100);
24888       }
24889     }
24890     sqlite3_backup_finish(pBackup);
24891     if( rc==SQLITE_DONE ){
24892       rc = 0;
24893     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
24894       raw_printf(stderr, "Error: source database is busy\n");
24895       rc = 1;
24896     }else{
24897       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24898       rc = 1;
24899     }
24900     close_db(pSrc);
24901   }else
24902 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24903 
24904   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
24905     if( nArg==2 ){
24906       if( cli_strcmp(azArg[1], "est")==0 ){
24907         p->scanstatsOn = 2;
24908       }else{
24909         p->scanstatsOn = (u8)booleanValue(azArg[1]);
24910       }
24911 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
24912       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
24913 #endif
24914     }else{
24915       raw_printf(stderr, "Usage: .scanstats on|off|est\n");
24916       rc = 1;
24917     }
24918   }else
24919 
24920   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
24921     ShellText sSelect;
24922     ShellState data;
24923     char *zErrMsg = 0;
24924     const char *zDiv = "(";
24925     const char *zName = 0;
24926     int iSchema = 0;
24927     int bDebug = 0;
24928     int bNoSystemTabs = 0;
24929     int ii;
24930 
24931     open_db(p, 0);
24932     memcpy(&data, p, sizeof(data));
24933     data.showHeader = 0;
24934     data.cMode = data.mode = MODE_Semi;
24935     initText(&sSelect);
24936     for(ii=1; ii<nArg; ii++){
24937       if( optionMatch(azArg[ii],"indent") ){
24938         data.cMode = data.mode = MODE_Pretty;
24939       }else if( optionMatch(azArg[ii],"debug") ){
24940         bDebug = 1;
24941       }else if( optionMatch(azArg[ii],"nosys") ){
24942         bNoSystemTabs = 1;
24943       }else if( azArg[ii][0]=='-' ){
24944         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
24945         rc = 1;
24946         goto meta_command_exit;
24947       }else if( zName==0 ){
24948         zName = azArg[ii];
24949       }else{
24950         raw_printf(stderr,
24951                    "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
24952         rc = 1;
24953         goto meta_command_exit;
24954       }
24955     }
24956     if( zName!=0 ){
24957       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
24958                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
24959                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
24960                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
24961       if( isSchema ){
24962         char *new_argv[2], *new_colv[2];
24963         new_argv[0] = sqlite3_mprintf(
24964                       "CREATE TABLE %s (\n"
24965                       "  type text,\n"
24966                       "  name text,\n"
24967                       "  tbl_name text,\n"
24968                       "  rootpage integer,\n"
24969                       "  sql text\n"
24970                       ")", zName);
24971         shell_check_oom(new_argv[0]);
24972         new_argv[1] = 0;
24973         new_colv[0] = "sql";
24974         new_colv[1] = 0;
24975         callback(&data, 1, new_argv, new_colv);
24976         sqlite3_free(new_argv[0]);
24977       }
24978     }
24979     if( zDiv ){
24980       sqlite3_stmt *pStmt = 0;
24981       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
24982                               -1, &pStmt, 0);
24983       if( rc ){
24984         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24985         sqlite3_finalize(pStmt);
24986         rc = 1;
24987         goto meta_command_exit;
24988       }
24989       appendText(&sSelect, "SELECT sql FROM", 0);
24990       iSchema = 0;
24991       while( sqlite3_step(pStmt)==SQLITE_ROW ){
24992         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
24993         char zScNum[30];
24994         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
24995         appendText(&sSelect, zDiv, 0);
24996         zDiv = " UNION ALL ";
24997         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
24998         if( sqlite3_stricmp(zDb, "main")!=0 ){
24999           appendText(&sSelect, zDb, '\'');
25000         }else{
25001           appendText(&sSelect, "NULL", 0);
25002         }
25003         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
25004         appendText(&sSelect, zScNum, 0);
25005         appendText(&sSelect, " AS snum, ", 0);
25006         appendText(&sSelect, zDb, '\'');
25007         appendText(&sSelect, " AS sname FROM ", 0);
25008         appendText(&sSelect, zDb, quoteChar(zDb));
25009         appendText(&sSelect, ".sqlite_schema", 0);
25010       }
25011       sqlite3_finalize(pStmt);
25012 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
25013       if( zName ){
25014         appendText(&sSelect,
25015            " UNION ALL SELECT shell_module_schema(name),"
25016            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
25017         0);
25018       }
25019 #endif
25020       appendText(&sSelect, ") WHERE ", 0);
25021       if( zName ){
25022         char *zQarg = sqlite3_mprintf("%Q", zName);
25023         int bGlob;
25024         shell_check_oom(zQarg);
25025         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
25026                 strchr(zName, '[') != 0;
25027         if( strchr(zName, '.') ){
25028           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
25029         }else{
25030           appendText(&sSelect, "lower(tbl_name)", 0);
25031         }
25032         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
25033         appendText(&sSelect, zQarg, 0);
25034         if( !bGlob ){
25035           appendText(&sSelect, " ESCAPE '\\' ", 0);
25036         }
25037         appendText(&sSelect, " AND ", 0);
25038         sqlite3_free(zQarg);
25039       }
25040       if( bNoSystemTabs ){
25041         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
25042       }
25043       appendText(&sSelect, "sql IS NOT NULL"
25044                            " ORDER BY snum, rowid", 0);
25045       if( bDebug ){
25046         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
25047       }else{
25048         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
25049       }
25050       freeText(&sSelect);
25051     }
25052     if( zErrMsg ){
25053       utf8_printf(stderr,"Error: %s\n", zErrMsg);
25054       sqlite3_free(zErrMsg);
25055       rc = 1;
25056     }else if( rc != SQLITE_OK ){
25057       raw_printf(stderr,"Error: querying schema information\n");
25058       rc = 1;
25059     }else{
25060       rc = 0;
25061     }
25062   }else
25063 
25064   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
25065    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
25066   ){
25067     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
25068     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
25069   }else
25070 
25071 #if defined(SQLITE_ENABLE_SESSION)
25072   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
25073     struct AuxDb *pAuxDb = p->pAuxDb;
25074     OpenSession *pSession = &pAuxDb->aSession[0];
25075     char **azCmd = &azArg[1];
25076     int iSes = 0;
25077     int nCmd = nArg - 1;
25078     int i;
25079     if( nArg<=1 ) goto session_syntax_error;
25080     open_db(p, 0);
25081     if( nArg>=3 ){
25082       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
25083         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
25084       }
25085       if( iSes<pAuxDb->nSession ){
25086         pSession = &pAuxDb->aSession[iSes];
25087         azCmd++;
25088         nCmd--;
25089       }else{
25090         pSession = &pAuxDb->aSession[0];
25091         iSes = 0;
25092       }
25093     }
25094 
25095     /* .session attach TABLE
25096     ** Invoke the sqlite3session_attach() interface to attach a particular
25097     ** table so that it is never filtered.
25098     */
25099     if( cli_strcmp(azCmd[0],"attach")==0 ){
25100       if( nCmd!=2 ) goto session_syntax_error;
25101       if( pSession->p==0 ){
25102         session_not_open:
25103         raw_printf(stderr, "ERROR: No sessions are open\n");
25104       }else{
25105         rc = sqlite3session_attach(pSession->p, azCmd[1]);
25106         if( rc ){
25107           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
25108           rc = 0;
25109         }
25110       }
25111     }else
25112 
25113     /* .session changeset FILE
25114     ** .session patchset FILE
25115     ** Write a changeset or patchset into a file.  The file is overwritten.
25116     */
25117     if( cli_strcmp(azCmd[0],"changeset")==0
25118      || cli_strcmp(azCmd[0],"patchset")==0
25119     ){
25120       FILE *out = 0;
25121       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
25122       if( nCmd!=2 ) goto session_syntax_error;
25123       if( pSession->p==0 ) goto session_not_open;
25124       out = fopen(azCmd[1], "wb");
25125       if( out==0 ){
25126         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
25127                     azCmd[1]);
25128       }else{
25129         int szChng;
25130         void *pChng;
25131         if( azCmd[0][0]=='c' ){
25132           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
25133         }else{
25134           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
25135         }
25136         if( rc ){
25137           printf("Error: error code %d\n", rc);
25138           rc = 0;
25139         }
25140         if( pChng
25141           && fwrite(pChng, szChng, 1, out)!=1 ){
25142           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
25143                   szChng);
25144         }
25145         sqlite3_free(pChng);
25146         fclose(out);
25147       }
25148     }else
25149 
25150     /* .session close
25151     ** Close the identified session
25152     */
25153     if( cli_strcmp(azCmd[0], "close")==0 ){
25154       if( nCmd!=1 ) goto session_syntax_error;
25155       if( pAuxDb->nSession ){
25156         session_close(pSession);
25157         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
25158       }
25159     }else
25160 
25161     /* .session enable ?BOOLEAN?
25162     ** Query or set the enable flag
25163     */
25164     if( cli_strcmp(azCmd[0], "enable")==0 ){
25165       int ii;
25166       if( nCmd>2 ) goto session_syntax_error;
25167       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
25168       if( pAuxDb->nSession ){
25169         ii = sqlite3session_enable(pSession->p, ii);
25170         utf8_printf(p->out, "session %s enable flag = %d\n",
25171                     pSession->zName, ii);
25172       }
25173     }else
25174 
25175     /* .session filter GLOB ....
25176     ** Set a list of GLOB patterns of table names to be excluded.
25177     */
25178     if( cli_strcmp(azCmd[0], "filter")==0 ){
25179       int ii, nByte;
25180       if( nCmd<2 ) goto session_syntax_error;
25181       if( pAuxDb->nSession ){
25182         for(ii=0; ii<pSession->nFilter; ii++){
25183           sqlite3_free(pSession->azFilter[ii]);
25184         }
25185         sqlite3_free(pSession->azFilter);
25186         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
25187         pSession->azFilter = sqlite3_malloc( nByte );
25188         if( pSession->azFilter==0 ){
25189           raw_printf(stderr, "Error: out or memory\n");
25190           exit(1);
25191         }
25192         for(ii=1; ii<nCmd; ii++){
25193           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
25194           shell_check_oom(x);
25195         }
25196         pSession->nFilter = ii-1;
25197       }
25198     }else
25199 
25200     /* .session indirect ?BOOLEAN?
25201     ** Query or set the indirect flag
25202     */
25203     if( cli_strcmp(azCmd[0], "indirect")==0 ){
25204       int ii;
25205       if( nCmd>2 ) goto session_syntax_error;
25206       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
25207       if( pAuxDb->nSession ){
25208         ii = sqlite3session_indirect(pSession->p, ii);
25209         utf8_printf(p->out, "session %s indirect flag = %d\n",
25210                     pSession->zName, ii);
25211       }
25212     }else
25213 
25214     /* .session isempty
25215     ** Determine if the session is empty
25216     */
25217     if( cli_strcmp(azCmd[0], "isempty")==0 ){
25218       int ii;
25219       if( nCmd!=1 ) goto session_syntax_error;
25220       if( pAuxDb->nSession ){
25221         ii = sqlite3session_isempty(pSession->p);
25222         utf8_printf(p->out, "session %s isempty flag = %d\n",
25223                     pSession->zName, ii);
25224       }
25225     }else
25226 
25227     /* .session list
25228     ** List all currently open sessions
25229     */
25230     if( cli_strcmp(azCmd[0],"list")==0 ){
25231       for(i=0; i<pAuxDb->nSession; i++){
25232         utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
25233       }
25234     }else
25235 
25236     /* .session open DB NAME
25237     ** Open a new session called NAME on the attached database DB.
25238     ** DB is normally "main".
25239     */
25240     if( cli_strcmp(azCmd[0],"open")==0 ){
25241       char *zName;
25242       if( nCmd!=3 ) goto session_syntax_error;
25243       zName = azCmd[2];
25244       if( zName[0]==0 ) goto session_syntax_error;
25245       for(i=0; i<pAuxDb->nSession; i++){
25246         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
25247           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
25248           goto meta_command_exit;
25249         }
25250       }
25251       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
25252         raw_printf(stderr,
25253                    "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
25254         goto meta_command_exit;
25255       }
25256       pSession = &pAuxDb->aSession[pAuxDb->nSession];
25257       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
25258       if( rc ){
25259         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
25260         rc = 0;
25261         goto meta_command_exit;
25262       }
25263       pSession->nFilter = 0;
25264       sqlite3session_table_filter(pSession->p, session_filter, pSession);
25265       pAuxDb->nSession++;
25266       pSession->zName = sqlite3_mprintf("%s", zName);
25267       shell_check_oom(pSession->zName);
25268     }else
25269     /* If no command name matches, show a syntax error */
25270     session_syntax_error:
25271     showHelp(p->out, "session");
25272   }else
25273 #endif
25274 
25275 #ifdef SQLITE_DEBUG
25276   /* Undocumented commands for internal testing.  Subject to change
25277   ** without notice. */
25278   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
25279     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
25280       int i, v;
25281       for(i=1; i<nArg; i++){
25282         v = booleanValue(azArg[i]);
25283         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
25284       }
25285     }
25286     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
25287       int i; sqlite3_int64 v;
25288       for(i=1; i<nArg; i++){
25289         char zBuf[200];
25290         v = integerValue(azArg[i]);
25291         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
25292         utf8_printf(p->out, "%s", zBuf);
25293       }
25294     }
25295   }else
25296 #endif
25297 
25298   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
25299     int bIsInit = 0;         /* True to initialize the SELFTEST table */
25300     int bVerbose = 0;        /* Verbose output */
25301     int bSelftestExists;     /* True if SELFTEST already exists */
25302     int i, k;                /* Loop counters */
25303     int nTest = 0;           /* Number of tests runs */
25304     int nErr = 0;            /* Number of errors seen */
25305     ShellText str;           /* Answer for a query */
25306     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
25307 
25308     open_db(p,0);
25309     for(i=1; i<nArg; i++){
25310       const char *z = azArg[i];
25311       if( z[0]=='-' && z[1]=='-' ) z++;
25312       if( cli_strcmp(z,"-init")==0 ){
25313         bIsInit = 1;
25314       }else
25315       if( cli_strcmp(z,"-v")==0 ){
25316         bVerbose++;
25317       }else
25318       {
25319         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
25320                     azArg[i], azArg[0]);
25321         raw_printf(stderr, "Should be one of: --init -v\n");
25322         rc = 1;
25323         goto meta_command_exit;
25324       }
25325     }
25326     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
25327            != SQLITE_OK ){
25328       bSelftestExists = 0;
25329     }else{
25330       bSelftestExists = 1;
25331     }
25332     if( bIsInit ){
25333       createSelftestTable(p);
25334       bSelftestExists = 1;
25335     }
25336     initText(&str);
25337     appendText(&str, "x", 0);
25338     for(k=bSelftestExists; k>=0; k--){
25339       if( k==1 ){
25340         rc = sqlite3_prepare_v2(p->db,
25341             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
25342             -1, &pStmt, 0);
25343       }else{
25344         rc = sqlite3_prepare_v2(p->db,
25345           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
25346           "      (1,'run','PRAGMA integrity_check','ok')",
25347           -1, &pStmt, 0);
25348       }
25349       if( rc ){
25350         raw_printf(stderr, "Error querying the selftest table\n");
25351         rc = 1;
25352         sqlite3_finalize(pStmt);
25353         goto meta_command_exit;
25354       }
25355       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
25356         int tno = sqlite3_column_int(pStmt, 0);
25357         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
25358         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
25359         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
25360 
25361         if( zOp==0 ) continue;
25362         if( zSql==0 ) continue;
25363         if( zAns==0 ) continue;
25364         k = 0;
25365         if( bVerbose>0 ){
25366           printf("%d: %s %s\n", tno, zOp, zSql);
25367         }
25368         if( cli_strcmp(zOp,"memo")==0 ){
25369           utf8_printf(p->out, "%s\n", zSql);
25370         }else
25371         if( cli_strcmp(zOp,"run")==0 ){
25372           char *zErrMsg = 0;
25373           str.n = 0;
25374           str.z[0] = 0;
25375           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
25376           nTest++;
25377           if( bVerbose ){
25378             utf8_printf(p->out, "Result: %s\n", str.z);
25379           }
25380           if( rc || zErrMsg ){
25381             nErr++;
25382             rc = 1;
25383             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
25384             sqlite3_free(zErrMsg);
25385           }else if( cli_strcmp(zAns,str.z)!=0 ){
25386             nErr++;
25387             rc = 1;
25388             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
25389             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
25390           }
25391         }else
25392         {
25393           utf8_printf(stderr,
25394             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
25395           rc = 1;
25396           break;
25397         }
25398       } /* End loop over rows of content from SELFTEST */
25399       sqlite3_finalize(pStmt);
25400     } /* End loop over k */
25401     freeText(&str);
25402     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
25403   }else
25404 
25405   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
25406     if( nArg<2 || nArg>3 ){
25407       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
25408       rc = 1;
25409     }
25410     if( nArg>=2 ){
25411       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
25412                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
25413     }
25414     if( nArg>=3 ){
25415       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
25416                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
25417     }
25418   }else
25419 
25420   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
25421     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
25422     int i;                   /* Loop counter */
25423     int bSchema = 0;         /* Also hash the schema */
25424     int bSeparate = 0;       /* Hash each table separately */
25425     int iSize = 224;         /* Hash algorithm to use */
25426     int bDebug = 0;          /* Only show the query that would have run */
25427     sqlite3_stmt *pStmt;     /* For querying tables names */
25428     char *zSql;              /* SQL to be run */
25429     char *zSep;              /* Separator */
25430     ShellText sSql;          /* Complete SQL for the query to run the hash */
25431     ShellText sQuery;        /* Set of queries used to read all content */
25432     open_db(p, 0);
25433     for(i=1; i<nArg; i++){
25434       const char *z = azArg[i];
25435       if( z[0]=='-' ){
25436         z++;
25437         if( z[0]=='-' ) z++;
25438         if( cli_strcmp(z,"schema")==0 ){
25439           bSchema = 1;
25440         }else
25441         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
25442          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
25443         ){
25444           iSize = atoi(&z[5]);
25445         }else
25446         if( cli_strcmp(z,"debug")==0 ){
25447           bDebug = 1;
25448         }else
25449         {
25450           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
25451                       azArg[i], azArg[0]);
25452           showHelp(p->out, azArg[0]);
25453           rc = 1;
25454           goto meta_command_exit;
25455         }
25456       }else if( zLike ){
25457         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
25458         rc = 1;
25459         goto meta_command_exit;
25460       }else{
25461         zLike = z;
25462         bSeparate = 1;
25463         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
25464       }
25465     }
25466     if( bSchema ){
25467       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
25468              " WHERE type='table' AND coalesce(rootpage,0)>1"
25469              " UNION ALL SELECT 'sqlite_schema'"
25470              " ORDER BY 1 collate nocase";
25471     }else{
25472       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
25473              " WHERE type='table' AND coalesce(rootpage,0)>1"
25474              " AND name NOT LIKE 'sqlite_%'"
25475              " ORDER BY 1 collate nocase";
25476     }
25477     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25478     initText(&sQuery);
25479     initText(&sSql);
25480     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
25481     zSep = "VALUES(";
25482     while( SQLITE_ROW==sqlite3_step(pStmt) ){
25483       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
25484       if( zTab==0 ) continue;
25485       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
25486       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
25487         appendText(&sQuery,"SELECT * FROM ", 0);
25488         appendText(&sQuery,zTab,'"');
25489         appendText(&sQuery," NOT INDEXED;", 0);
25490       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
25491         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
25492                            " ORDER BY name;", 0);
25493       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
25494         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
25495                            " ORDER BY name;", 0);
25496       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
25497         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
25498                            " ORDER BY tbl,idx;", 0);
25499       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
25500         appendText(&sQuery, "SELECT * FROM ", 0);
25501         appendText(&sQuery, zTab, 0);
25502         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
25503       }
25504       appendText(&sSql, zSep, 0);
25505       appendText(&sSql, sQuery.z, '\'');
25506       sQuery.n = 0;
25507       appendText(&sSql, ",", 0);
25508       appendText(&sSql, zTab, '\'');
25509       zSep = "),(";
25510     }
25511     sqlite3_finalize(pStmt);
25512     if( bSeparate ){
25513       zSql = sqlite3_mprintf(
25514           "%s))"
25515           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
25516           "   FROM [sha3sum$query]",
25517           sSql.z, iSize);
25518     }else{
25519       zSql = sqlite3_mprintf(
25520           "%s))"
25521           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
25522           "   FROM [sha3sum$query]",
25523           sSql.z, iSize);
25524     }
25525     shell_check_oom(zSql);
25526     freeText(&sQuery);
25527     freeText(&sSql);
25528     if( bDebug ){
25529       utf8_printf(p->out, "%s\n", zSql);
25530     }else{
25531       shell_exec(p, zSql, 0);
25532     }
25533 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
25534     {
25535       int lrc;
25536       char *zRevText = /* Query for reversible to-blob-to-text check */
25537         "SELECT lower(name) as tname FROM sqlite_schema\n"
25538         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
25539         "AND name NOT LIKE 'sqlite_%%'%s\n"
25540         "ORDER BY 1 collate nocase";
25541       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
25542       zRevText = sqlite3_mprintf(
25543           /* lower-case query is first run, producing upper-case query. */
25544           "with tabcols as materialized(\n"
25545           "select tname, cname\n"
25546           "from ("
25547           " select ss.tname as tname, ti.name as cname\n"
25548           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
25549           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
25550           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
25551           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
25552           "FROM '||tname||' WHERE '\n"
25553           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
25554           "|| ' AND typeof('||cname||')=''text'' ',\n"
25555           "' OR ') as query, tname from tabcols group by tname)"
25556           , zRevText);
25557       shell_check_oom(zRevText);
25558       if( bDebug ) utf8_printf(p->out, "%s\n", zRevText);
25559       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
25560       assert(lrc==SQLITE_OK);
25561       if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
25562       lrc = SQLITE_ROW==sqlite3_step(pStmt);
25563       if( lrc ){
25564         const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
25565         sqlite3_stmt *pCheckStmt;
25566         lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
25567         if( bDebug ) utf8_printf(p->out, "%s\n", zGenQuery);
25568         if( SQLITE_OK==lrc ){
25569           if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
25570             double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
25571             if( countIrreversible>0 ){
25572               int sz = (int)(countIrreversible + 0.5);
25573               utf8_printf(stderr,
25574                  "Digest includes %d invalidly encoded text field%s.\n",
25575                  sz, (sz>1)? "s": "");
25576             }
25577           }
25578           sqlite3_finalize(pCheckStmt);
25579         }
25580         sqlite3_finalize(pStmt);
25581       }
25582       sqlite3_free(zRevText);
25583     }
25584 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
25585     sqlite3_free(zSql);
25586   }else
25587 
25588 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
25589   if( c=='s'
25590    && (cli_strncmp(azArg[0], "shell", n)==0
25591        || cli_strncmp(azArg[0],"system",n)==0)
25592   ){
25593     char *zCmd;
25594     int i, x;
25595     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
25596     if( nArg<2 ){
25597       raw_printf(stderr, "Usage: .system COMMAND\n");
25598       rc = 1;
25599       goto meta_command_exit;
25600     }
25601     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
25602     for(i=2; i<nArg && zCmd!=0; i++){
25603       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
25604                              zCmd, azArg[i]);
25605     }
25606     x = zCmd!=0 ? system(zCmd) : 1;
25607     sqlite3_free(zCmd);
25608     if( x ) raw_printf(stderr, "System command returns %d\n", x);
25609   }else
25610 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
25611 
25612   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
25613     static const char *azBool[] = { "off", "on", "trigger", "full"};
25614     const char *zOut;
25615     int i;
25616     if( nArg!=1 ){
25617       raw_printf(stderr, "Usage: .show\n");
25618       rc = 1;
25619       goto meta_command_exit;
25620     }
25621     utf8_printf(p->out, "%12.12s: %s\n","echo",
25622                 azBool[ShellHasFlag(p, SHFLG_Echo)]);
25623     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
25624     utf8_printf(p->out, "%12.12s: %s\n","explain",
25625          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
25626     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
25627     if( p->mode==MODE_Column
25628      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
25629     ){
25630       utf8_printf
25631         (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
25632          modeDescr[p->mode], p->cmOpts.iWrap,
25633          p->cmOpts.bWordWrap ? "on" : "off",
25634          p->cmOpts.bQuote ? "" : "no");
25635     }else{
25636       utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
25637     }
25638     utf8_printf(p->out, "%12.12s: ", "nullvalue");
25639       output_c_string(p->out, p->nullValue);
25640       raw_printf(p->out, "\n");
25641     utf8_printf(p->out,"%12.12s: %s\n","output",
25642             strlen30(p->outfile) ? p->outfile : "stdout");
25643     utf8_printf(p->out,"%12.12s: ", "colseparator");
25644       output_c_string(p->out, p->colSeparator);
25645       raw_printf(p->out, "\n");
25646     utf8_printf(p->out,"%12.12s: ", "rowseparator");
25647       output_c_string(p->out, p->rowSeparator);
25648       raw_printf(p->out, "\n");
25649     switch( p->statsOn ){
25650       case 0:  zOut = "off";     break;
25651       default: zOut = "on";      break;
25652       case 2:  zOut = "stmt";    break;
25653       case 3:  zOut = "vmstep";  break;
25654     }
25655     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
25656     utf8_printf(p->out, "%12.12s: ", "width");
25657     for (i=0;i<p->nWidth;i++) {
25658       raw_printf(p->out, "%d ", p->colWidth[i]);
25659     }
25660     raw_printf(p->out, "\n");
25661     utf8_printf(p->out, "%12.12s: %s\n", "filename",
25662                 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
25663   }else
25664 
25665   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
25666     if( nArg==2 ){
25667       if( cli_strcmp(azArg[1],"stmt")==0 ){
25668         p->statsOn = 2;
25669       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
25670         p->statsOn = 3;
25671       }else{
25672         p->statsOn = (u8)booleanValue(azArg[1]);
25673       }
25674     }else if( nArg==1 ){
25675       display_stats(p->db, p, 0);
25676     }else{
25677       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
25678       rc = 1;
25679     }
25680   }else
25681 
25682   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
25683    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
25684                  || cli_strncmp(azArg[0], "indexes", n)==0) )
25685   ){
25686     sqlite3_stmt *pStmt;
25687     char **azResult;
25688     int nRow, nAlloc;
25689     int ii;
25690     ShellText s;
25691     initText(&s);
25692     open_db(p, 0);
25693     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
25694     if( rc ){
25695       sqlite3_finalize(pStmt);
25696       return shellDatabaseError(p->db);
25697     }
25698 
25699     if( nArg>2 && c=='i' ){
25700       /* It is an historical accident that the .indexes command shows an error
25701       ** when called with the wrong number of arguments whereas the .tables
25702       ** command does not. */
25703       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
25704       rc = 1;
25705       sqlite3_finalize(pStmt);
25706       goto meta_command_exit;
25707     }
25708     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
25709       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
25710       if( zDbName==0 ) continue;
25711       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
25712       if( sqlite3_stricmp(zDbName, "main")==0 ){
25713         appendText(&s, "SELECT name FROM ", 0);
25714       }else{
25715         appendText(&s, "SELECT ", 0);
25716         appendText(&s, zDbName, '\'');
25717         appendText(&s, "||'.'||name FROM ", 0);
25718       }
25719       appendText(&s, zDbName, '"');
25720       appendText(&s, ".sqlite_schema ", 0);
25721       if( c=='t' ){
25722         appendText(&s," WHERE type IN ('table','view')"
25723                       "   AND name NOT LIKE 'sqlite_%'"
25724                       "   AND name LIKE ?1", 0);
25725       }else{
25726         appendText(&s," WHERE type='index'"
25727                       "   AND tbl_name LIKE ?1", 0);
25728       }
25729     }
25730     rc = sqlite3_finalize(pStmt);
25731     if( rc==SQLITE_OK ){
25732       appendText(&s, " ORDER BY 1", 0);
25733       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
25734     }
25735     freeText(&s);
25736     if( rc ) return shellDatabaseError(p->db);
25737 
25738     /* Run the SQL statement prepared by the above block. Store the results
25739     ** as an array of nul-terminated strings in azResult[].  */
25740     nRow = nAlloc = 0;
25741     azResult = 0;
25742     if( nArg>1 ){
25743       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
25744     }else{
25745       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
25746     }
25747     while( sqlite3_step(pStmt)==SQLITE_ROW ){
25748       if( nRow>=nAlloc ){
25749         char **azNew;
25750         int n2 = nAlloc*2 + 10;
25751         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
25752         shell_check_oom(azNew);
25753         nAlloc = n2;
25754         azResult = azNew;
25755       }
25756       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
25757       shell_check_oom(azResult[nRow]);
25758       nRow++;
25759     }
25760     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
25761       rc = shellDatabaseError(p->db);
25762     }
25763 
25764     /* Pretty-print the contents of array azResult[] to the output */
25765     if( rc==0 && nRow>0 ){
25766       int len, maxlen = 0;
25767       int i, j;
25768       int nPrintCol, nPrintRow;
25769       for(i=0; i<nRow; i++){
25770         len = strlen30(azResult[i]);
25771         if( len>maxlen ) maxlen = len;
25772       }
25773       nPrintCol = 80/(maxlen+2);
25774       if( nPrintCol<1 ) nPrintCol = 1;
25775       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
25776       for(i=0; i<nPrintRow; i++){
25777         for(j=i; j<nRow; j+=nPrintRow){
25778           char *zSp = j<nPrintRow ? "" : "  ";
25779           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
25780                       azResult[j] ? azResult[j]:"");
25781         }
25782         raw_printf(p->out, "\n");
25783       }
25784     }
25785 
25786     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
25787     sqlite3_free(azResult);
25788   }else
25789 
25790 #ifndef SQLITE_SHELL_FIDDLE
25791   /* Begin redirecting output to the file "testcase-out.txt" */
25792   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
25793     output_reset(p);
25794     p->out = output_file_open("testcase-out.txt", 0);
25795     if( p->out==0 ){
25796       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
25797     }
25798     if( nArg>=2 ){
25799       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
25800     }else{
25801       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
25802     }
25803   }else
25804 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25805 
25806 #ifndef SQLITE_UNTESTABLE
25807   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
25808     static const struct {
25809        const char *zCtrlName;   /* Name of a test-control option */
25810        int ctrlCode;            /* Integer code for that option */
25811        int unSafe;              /* Not valid for --safe mode */
25812        const char *zUsage;      /* Usage notes */
25813     } aCtrl[] = {
25814     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
25815     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
25816   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
25817   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
25818     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
25819     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
25820   /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
25821     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
25822     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
25823     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
25824     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
25825     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
25826 #ifdef YYCOVERAGE
25827     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
25828 #endif
25829     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
25830     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
25831     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
25832     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
25833     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
25834     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
25835     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
25836     };
25837     int testctrl = -1;
25838     int iCtrl = -1;
25839     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
25840     int isOk = 0;
25841     int i, n2;
25842     const char *zCmd = 0;
25843 
25844     open_db(p, 0);
25845     zCmd = nArg>=2 ? azArg[1] : "help";
25846 
25847     /* The argument can optionally begin with "-" or "--" */
25848     if( zCmd[0]=='-' && zCmd[1] ){
25849       zCmd++;
25850       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
25851     }
25852 
25853     /* --help lists all test-controls */
25854     if( cli_strcmp(zCmd,"help")==0 ){
25855       utf8_printf(p->out, "Available test-controls:\n");
25856       for(i=0; i<ArraySize(aCtrl); i++){
25857         utf8_printf(p->out, "  .testctrl %s %s\n",
25858                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
25859       }
25860       rc = 1;
25861       goto meta_command_exit;
25862     }
25863 
25864     /* convert testctrl text option to value. allow any unique prefix
25865     ** of the option name, or a numerical value. */
25866     n2 = strlen30(zCmd);
25867     for(i=0; i<ArraySize(aCtrl); i++){
25868       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
25869         if( testctrl<0 ){
25870           testctrl = aCtrl[i].ctrlCode;
25871           iCtrl = i;
25872         }else{
25873           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
25874                               "Use \".testctrl --help\" for help\n", zCmd);
25875           rc = 1;
25876           goto meta_command_exit;
25877         }
25878       }
25879     }
25880     if( testctrl<0 ){
25881       utf8_printf(stderr,"Error: unknown test-control: %s\n"
25882                          "Use \".testctrl --help\" for help\n", zCmd);
25883     }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
25884       utf8_printf(stderr,
25885          "line %d: \".testctrl %s\" may not be used in safe mode\n",
25886          p->lineno, aCtrl[iCtrl].zCtrlName);
25887       exit(1);
25888     }else{
25889       switch(testctrl){
25890 
25891         /* sqlite3_test_control(int, db, int) */
25892         case SQLITE_TESTCTRL_OPTIMIZATIONS:
25893           if( nArg==3 ){
25894             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
25895             rc2 = sqlite3_test_control(testctrl, p->db, opt);
25896             isOk = 3;
25897           }
25898           break;
25899 
25900         /* sqlite3_test_control(int) */
25901         case SQLITE_TESTCTRL_PRNG_SAVE:
25902         case SQLITE_TESTCTRL_PRNG_RESTORE:
25903         case SQLITE_TESTCTRL_BYTEORDER:
25904           if( nArg==2 ){
25905             rc2 = sqlite3_test_control(testctrl);
25906             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
25907           }
25908           break;
25909 
25910         /* sqlite3_test_control(int, uint) */
25911         case SQLITE_TESTCTRL_PENDING_BYTE:
25912           if( nArg==3 ){
25913             unsigned int opt = (unsigned int)integerValue(azArg[2]);
25914             rc2 = sqlite3_test_control(testctrl, opt);
25915             isOk = 3;
25916           }
25917           break;
25918 
25919         /* sqlite3_test_control(int, int, sqlite3*) */
25920         case SQLITE_TESTCTRL_PRNG_SEED:
25921           if( nArg==3 || nArg==4 ){
25922             int ii = (int)integerValue(azArg[2]);
25923             sqlite3 *db;
25924             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
25925               sqlite3_randomness(sizeof(ii),&ii);
25926               printf("-- random seed: %d\n", ii);
25927             }
25928             if( nArg==3 ){
25929               db = 0;
25930             }else{
25931               db = p->db;
25932               /* Make sure the schema has been loaded */
25933               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
25934             }
25935             rc2 = sqlite3_test_control(testctrl, ii, db);
25936             isOk = 3;
25937           }
25938           break;
25939 
25940         /* sqlite3_test_control(int, int) */
25941         case SQLITE_TESTCTRL_ASSERT:
25942         case SQLITE_TESTCTRL_ALWAYS:
25943           if( nArg==3 ){
25944             int opt = booleanValue(azArg[2]);
25945             rc2 = sqlite3_test_control(testctrl, opt);
25946             isOk = 1;
25947           }
25948           break;
25949 
25950         /* sqlite3_test_control(int, int) */
25951         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
25952         case SQLITE_TESTCTRL_NEVER_CORRUPT:
25953           if( nArg==3 ){
25954             int opt = booleanValue(azArg[2]);
25955             rc2 = sqlite3_test_control(testctrl, opt);
25956             isOk = 3;
25957           }
25958           break;
25959 
25960         /* sqlite3_test_control(sqlite3*) */
25961         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
25962           rc2 = sqlite3_test_control(testctrl, p->db);
25963           isOk = 3;
25964           break;
25965 
25966         case SQLITE_TESTCTRL_IMPOSTER:
25967           if( nArg==5 ){
25968             rc2 = sqlite3_test_control(testctrl, p->db,
25969                           azArg[2],
25970                           integerValue(azArg[3]),
25971                           integerValue(azArg[4]));
25972             isOk = 3;
25973           }
25974           break;
25975 
25976         case SQLITE_TESTCTRL_SEEK_COUNT: {
25977           u64 x = 0;
25978           rc2 = sqlite3_test_control(testctrl, p->db, &x);
25979           utf8_printf(p->out, "%llu\n", x);
25980           isOk = 3;
25981           break;
25982         }
25983 
25984 #ifdef YYCOVERAGE
25985         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
25986           if( nArg==2 ){
25987             sqlite3_test_control(testctrl, p->out);
25988             isOk = 3;
25989           }
25990           break;
25991         }
25992 #endif
25993 #ifdef SQLITE_DEBUG
25994         case SQLITE_TESTCTRL_TUNE: {
25995           if( nArg==4 ){
25996             int id = (int)integerValue(azArg[2]);
25997             int val = (int)integerValue(azArg[3]);
25998             sqlite3_test_control(testctrl, id, &val);
25999             isOk = 3;
26000           }else if( nArg==3 ){
26001             int id = (int)integerValue(azArg[2]);
26002             sqlite3_test_control(testctrl, -id, &rc2);
26003             isOk = 1;
26004           }else if( nArg==2 ){
26005             int id = 1;
26006             while(1){
26007               int val = 0;
26008               rc2 = sqlite3_test_control(testctrl, -id, &val);
26009               if( rc2!=SQLITE_OK ) break;
26010               if( id>1 ) utf8_printf(p->out, "  ");
26011               utf8_printf(p->out, "%d: %d", id, val);
26012               id++;
26013             }
26014             if( id>1 ) utf8_printf(p->out, "\n");
26015             isOk = 3;
26016           }
26017           break;
26018         }
26019 #endif
26020         case SQLITE_TESTCTRL_SORTER_MMAP:
26021           if( nArg==3 ){
26022             int opt = (unsigned int)integerValue(azArg[2]);
26023             rc2 = sqlite3_test_control(testctrl, p->db, opt);
26024             isOk = 3;
26025           }
26026           break;
26027       }
26028     }
26029     if( isOk==0 && iCtrl>=0 ){
26030       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
26031       rc = 1;
26032     }else if( isOk==1 ){
26033       raw_printf(p->out, "%d\n", rc2);
26034     }else if( isOk==2 ){
26035       raw_printf(p->out, "0x%08x\n", rc2);
26036     }
26037   }else
26038 #endif /* !defined(SQLITE_UNTESTABLE) */
26039 
26040   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
26041     open_db(p, 0);
26042     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
26043   }else
26044 
26045   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
26046     if( nArg==2 ){
26047       enableTimer = booleanValue(azArg[1]);
26048       if( enableTimer && !HAS_TIMER ){
26049         raw_printf(stderr, "Error: timer not available on this system.\n");
26050         enableTimer = 0;
26051       }
26052     }else{
26053       raw_printf(stderr, "Usage: .timer on|off\n");
26054       rc = 1;
26055     }
26056   }else
26057 
26058 #ifndef SQLITE_OMIT_TRACE
26059   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
26060     int mType = 0;
26061     int jj;
26062     open_db(p, 0);
26063     for(jj=1; jj<nArg; jj++){
26064       const char *z = azArg[jj];
26065       if( z[0]=='-' ){
26066         if( optionMatch(z, "expanded") ){
26067           p->eTraceType = SHELL_TRACE_EXPANDED;
26068         }
26069 #ifdef SQLITE_ENABLE_NORMALIZE
26070         else if( optionMatch(z, "normalized") ){
26071           p->eTraceType = SHELL_TRACE_NORMALIZED;
26072         }
26073 #endif
26074         else if( optionMatch(z, "plain") ){
26075           p->eTraceType = SHELL_TRACE_PLAIN;
26076         }
26077         else if( optionMatch(z, "profile") ){
26078           mType |= SQLITE_TRACE_PROFILE;
26079         }
26080         else if( optionMatch(z, "row") ){
26081           mType |= SQLITE_TRACE_ROW;
26082         }
26083         else if( optionMatch(z, "stmt") ){
26084           mType |= SQLITE_TRACE_STMT;
26085         }
26086         else if( optionMatch(z, "close") ){
26087           mType |= SQLITE_TRACE_CLOSE;
26088         }
26089         else {
26090           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
26091           rc = 1;
26092           goto meta_command_exit;
26093         }
26094       }else{
26095         output_file_close(p->traceOut);
26096         p->traceOut = output_file_open(z, 0);
26097       }
26098     }
26099     if( p->traceOut==0 ){
26100       sqlite3_trace_v2(p->db, 0, 0, 0);
26101     }else{
26102       if( mType==0 ) mType = SQLITE_TRACE_STMT;
26103       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
26104     }
26105   }else
26106 #endif /* !defined(SQLITE_OMIT_TRACE) */
26107 
26108 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
26109   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
26110     int ii;
26111     int lenOpt;
26112     char *zOpt;
26113     if( nArg<2 ){
26114       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
26115       rc = 1;
26116       goto meta_command_exit;
26117     }
26118     open_db(p, 0);
26119     zOpt = azArg[1];
26120     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
26121     lenOpt = (int)strlen(zOpt);
26122     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
26123       assert( azArg[nArg]==0 );
26124       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
26125     }else{
26126       for(ii=1; ii<nArg; ii++){
26127         sqlite3_create_module(p->db, azArg[ii], 0, 0);
26128       }
26129     }
26130   }else
26131 #endif
26132 
26133 #if SQLITE_USER_AUTHENTICATION
26134   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
26135     if( nArg<2 ){
26136       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
26137       rc = 1;
26138       goto meta_command_exit;
26139     }
26140     open_db(p, 0);
26141     if( cli_strcmp(azArg[1],"login")==0 ){
26142       if( nArg!=4 ){
26143         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
26144         rc = 1;
26145         goto meta_command_exit;
26146       }
26147       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
26148                                      strlen30(azArg[3]));
26149       if( rc ){
26150         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
26151         rc = 1;
26152       }
26153     }else if( cli_strcmp(azArg[1],"add")==0 ){
26154       if( nArg!=5 ){
26155         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
26156         rc = 1;
26157         goto meta_command_exit;
26158       }
26159       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
26160                             booleanValue(azArg[4]));
26161       if( rc ){
26162         raw_printf(stderr, "User-Add failed: %d\n", rc);
26163         rc = 1;
26164       }
26165     }else if( cli_strcmp(azArg[1],"edit")==0 ){
26166       if( nArg!=5 ){
26167         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
26168         rc = 1;
26169         goto meta_command_exit;
26170       }
26171       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
26172                               booleanValue(azArg[4]));
26173       if( rc ){
26174         raw_printf(stderr, "User-Edit failed: %d\n", rc);
26175         rc = 1;
26176       }
26177     }else if( cli_strcmp(azArg[1],"delete")==0 ){
26178       if( nArg!=3 ){
26179         raw_printf(stderr, "Usage: .user delete USER\n");
26180         rc = 1;
26181         goto meta_command_exit;
26182       }
26183       rc = sqlite3_user_delete(p->db, azArg[2]);
26184       if( rc ){
26185         raw_printf(stderr, "User-Delete failed: %d\n", rc);
26186         rc = 1;
26187       }
26188     }else{
26189       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
26190       rc = 1;
26191       goto meta_command_exit;
26192     }
26193   }else
26194 #endif /* SQLITE_USER_AUTHENTICATION */
26195 
26196   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
26197     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
26198         sqlite3_libversion(), sqlite3_sourceid());
26199 #if SQLITE_HAVE_ZLIB
26200     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
26201 #endif
26202 #define CTIMEOPT_VAL_(opt) #opt
26203 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
26204 #if defined(__clang__) && defined(__clang_major__)
26205     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
26206                     CTIMEOPT_VAL(__clang_minor__) "."
26207                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
26208 #elif defined(_MSC_VER)
26209     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
26210 #elif defined(__GNUC__) && defined(__VERSION__)
26211     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
26212 #endif
26213   }else
26214 
26215   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
26216     const char *zDbName = nArg==2 ? azArg[1] : "main";
26217     sqlite3_vfs *pVfs = 0;
26218     if( p->db ){
26219       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
26220       if( pVfs ){
26221         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
26222         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
26223         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
26224         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
26225       }
26226     }
26227   }else
26228 
26229   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
26230     sqlite3_vfs *pVfs;
26231     sqlite3_vfs *pCurrent = 0;
26232     if( p->db ){
26233       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
26234     }
26235     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
26236       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
26237            pVfs==pCurrent ? "  <--- CURRENT" : "");
26238       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
26239       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
26240       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
26241       if( pVfs->pNext ){
26242         raw_printf(p->out, "-----------------------------------\n");
26243       }
26244     }
26245   }else
26246 
26247   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
26248     const char *zDbName = nArg==2 ? azArg[1] : "main";
26249     char *zVfsName = 0;
26250     if( p->db ){
26251       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
26252       if( zVfsName ){
26253         utf8_printf(p->out, "%s\n", zVfsName);
26254         sqlite3_free(zVfsName);
26255       }
26256     }
26257   }else
26258 
26259   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
26260     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26261     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
26262   }else
26263 
26264   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
26265     int j;
26266     assert( nArg<=ArraySize(azArg) );
26267     p->nWidth = nArg-1;
26268     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
26269     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
26270     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
26271     for(j=1; j<nArg; j++){
26272       p->colWidth[j-1] = (int)integerValue(azArg[j]);
26273     }
26274   }else
26275 
26276   {
26277     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
26278       " \"%s\". Enter \".help\" for help\n", azArg[0]);
26279     rc = 1;
26280   }
26281 
26282 meta_command_exit:
26283   if( p->outCount ){
26284     p->outCount--;
26285     if( p->outCount==0 ) output_reset(p);
26286   }
26287   p->bSafeMode = p->bSafeModePersist;
26288   return rc;
26289 }
26290 
26291 /* Line scan result and intermediate states (supporting scan resumption)
26292 */
26293 #ifndef CHAR_BIT
26294 # define CHAR_BIT 8
26295 #endif
26296 typedef enum {
26297   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
26298   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
26299   QSS_Start = 0
26300 } QuickScanState;
26301 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
26302 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
26303 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
26304 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
26305 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
26306 
26307 /*
26308 ** Scan line for classification to guide shell's handling.
26309 ** The scan is resumable for subsequent lines when prior
26310 ** return values are passed as the 2nd argument.
26311 */
26312 static QuickScanState quickscan(char *zLine, QuickScanState qss,
26313                                 SCAN_TRACKER_REFTYPE pst){
26314   char cin;
26315   char cWait = (char)qss; /* intentional narrowing loss */
26316   if( cWait==0 ){
26317   PlainScan:
26318     assert( cWait==0 );
26319     while( (cin = *zLine++)!=0 ){
26320       if( IsSpace(cin) )
26321         continue;
26322       switch (cin){
26323       case '-':
26324         if( *zLine!='-' )
26325           break;
26326         while((cin = *++zLine)!=0 )
26327           if( cin=='\n')
26328             goto PlainScan;
26329         return qss;
26330       case ';':
26331         qss |= QSS_EndingSemi;
26332         continue;
26333       case '/':
26334         if( *zLine=='*' ){
26335           ++zLine;
26336           cWait = '*';
26337           CONTINUE_PROMPT_AWAITS(pst, "/*");
26338           qss = QSS_SETV(qss, cWait);
26339           goto TermScan;
26340         }
26341         break;
26342       case '[':
26343         cin = ']';
26344         deliberate_fall_through;
26345       case '`': case '\'': case '"':
26346         cWait = cin;
26347         qss = QSS_HasDark | cWait;
26348         CONTINUE_PROMPT_AWAITC(pst, cin);
26349         goto TermScan;
26350       case '(':
26351         CONTINUE_PAREN_INCR(pst, 1);
26352         break;
26353       case ')':
26354         CONTINUE_PAREN_INCR(pst, -1);
26355         break;
26356       default:
26357         break;
26358       }
26359       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
26360     }
26361   }else{
26362   TermScan:
26363     while( (cin = *zLine++)!=0 ){
26364       if( cin==cWait ){
26365         switch( cWait ){
26366         case '*':
26367           if( *zLine != '/' )
26368             continue;
26369           ++zLine;
26370           cWait = 0;
26371           CONTINUE_PROMPT_AWAITC(pst, 0);
26372           qss = QSS_SETV(qss, 0);
26373           goto PlainScan;
26374         case '`': case '\'': case '"':
26375           if(*zLine==cWait){
26376             /* Swallow doubled end-delimiter.*/
26377             ++zLine;
26378             continue;
26379           }
26380           deliberate_fall_through;
26381         case ']':
26382           cWait = 0;
26383           CONTINUE_PROMPT_AWAITC(pst, 0);
26384           qss = QSS_SETV(qss, 0);
26385           goto PlainScan;
26386         default: assert(0);
26387         }
26388       }
26389     }
26390   }
26391   return qss;
26392 }
26393 
26394 /*
26395 ** Return TRUE if the line typed in is an SQL command terminator other
26396 ** than a semi-colon.  The SQL Server style "go" command is understood
26397 ** as is the Oracle "/".
26398 */
26399 static int line_is_command_terminator(char *zLine){
26400   while( IsSpace(zLine[0]) ){ zLine++; };
26401   if( zLine[0]=='/' )
26402     zLine += 1; /* Oracle */
26403   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
26404     zLine += 2; /* SQL Server */
26405   else
26406     return 0;
26407   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
26408 }
26409 
26410 /*
26411 ** The CLI needs a working sqlite3_complete() to work properly.  So error
26412 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
26413 */
26414 #ifdef SQLITE_OMIT_COMPLETE
26415 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
26416 #endif
26417 
26418 /*
26419 ** Return true if zSql is a complete SQL statement.  Return false if it
26420 ** ends in the middle of a string literal or C-style comment.
26421 */
26422 static int line_is_complete(char *zSql, int nSql){
26423   int rc;
26424   if( zSql==0 ) return 1;
26425   zSql[nSql] = ';';
26426   zSql[nSql+1] = 0;
26427   rc = sqlite3_complete(zSql);
26428   zSql[nSql] = 0;
26429   return rc;
26430 }
26431 
26432 /*
26433 ** Run a single line of SQL.  Return the number of errors.
26434 */
26435 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
26436   int rc;
26437   char *zErrMsg = 0;
26438 
26439   open_db(p, 0);
26440   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
26441   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
26442   BEGIN_TIMER;
26443   rc = shell_exec(p, zSql, &zErrMsg);
26444   END_TIMER;
26445   if( rc || zErrMsg ){
26446     char zPrefix[100];
26447     const char *zErrorTail;
26448     const char *zErrorType;
26449     if( zErrMsg==0 ){
26450       zErrorType = "Error";
26451       zErrorTail = sqlite3_errmsg(p->db);
26452     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
26453       zErrorType = "Parse error";
26454       zErrorTail = &zErrMsg[12];
26455     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
26456       zErrorType = "Runtime error";
26457       zErrorTail = &zErrMsg[10];
26458     }else{
26459       zErrorType = "Error";
26460       zErrorTail = zErrMsg;
26461     }
26462     if( in!=0 || !stdin_is_interactive ){
26463       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
26464                        "%s near line %d:", zErrorType, startline);
26465     }else{
26466       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
26467     }
26468     utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
26469     sqlite3_free(zErrMsg);
26470     zErrMsg = 0;
26471     return 1;
26472   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
26473     char zLineBuf[2000];
26474     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
26475             "changes: %lld   total_changes: %lld",
26476             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
26477     raw_printf(p->out, "%s\n", zLineBuf);
26478   }
26479   return 0;
26480 }
26481 
26482 static void echo_group_input(ShellState *p, const char *zDo){
26483   if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
26484 }
26485 
26486 #ifdef SQLITE_SHELL_FIDDLE
26487 /*
26488 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
26489 ** impl because we need the global shellState and cannot access it from that
26490 ** function without moving lots of code around (creating a larger/messier diff).
26491 */
26492 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
26493   /* Parse the next line from shellState.wasm.zInput. */
26494   const char *zBegin = shellState.wasm.zPos;
26495   const char *z = zBegin;
26496   char *zLine = 0;
26497   i64 nZ = 0;
26498 
26499   UNUSED_PARAMETER(in);
26500   UNUSED_PARAMETER(isContinuation);
26501   if(!z || !*z){
26502     return 0;
26503   }
26504   while(*z && isspace(*z)) ++z;
26505   zBegin = z;
26506   for(; *z && '\n'!=*z; ++nZ, ++z){}
26507   if(nZ>0 && '\r'==zBegin[nZ-1]){
26508     --nZ;
26509   }
26510   shellState.wasm.zPos = z;
26511   zLine = realloc(zPrior, nZ+1);
26512   shell_check_oom(zLine);
26513   memcpy(zLine, zBegin, nZ);
26514   zLine[nZ] = 0;
26515   return zLine;
26516 }
26517 #endif /* SQLITE_SHELL_FIDDLE */
26518 
26519 /*
26520 ** Read input from *in and process it.  If *in==0 then input
26521 ** is interactive - the user is typing it it.  Otherwise, input
26522 ** is coming from a file or device.  A prompt is issued and history
26523 ** is saved only if input is interactive.  An interrupt signal will
26524 ** cause this routine to exit immediately, unless input is interactive.
26525 **
26526 ** Return the number of errors.
26527 */
26528 static int process_input(ShellState *p){
26529   char *zLine = 0;          /* A single input line */
26530   char *zSql = 0;           /* Accumulated SQL text */
26531   i64 nLine;                /* Length of current line */
26532   i64 nSql = 0;             /* Bytes of zSql[] used */
26533   i64 nAlloc = 0;           /* Allocated zSql[] space */
26534   int rc;                   /* Error code */
26535   int errCnt = 0;           /* Number of errors seen */
26536   i64 startline = 0;        /* Line number for start of current input */
26537   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
26538 
26539   if( p->inputNesting==MAX_INPUT_NESTING ){
26540     /* This will be more informative in a later version. */
26541     utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
26542                 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
26543     return 1;
26544   }
26545   ++p->inputNesting;
26546   p->lineno = 0;
26547   CONTINUE_PROMPT_RESET;
26548   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
26549     fflush(p->out);
26550     zLine = one_input_line(p->in, zLine, nSql>0);
26551     if( zLine==0 ){
26552       /* End of input */
26553       if( p->in==0 && stdin_is_interactive ) printf("\n");
26554       break;
26555     }
26556     if( seenInterrupt ){
26557       if( p->in!=0 ) break;
26558       seenInterrupt = 0;
26559     }
26560     p->lineno++;
26561     if( QSS_INPLAIN(qss)
26562         && line_is_command_terminator(zLine)
26563         && line_is_complete(zSql, nSql) ){
26564       memcpy(zLine,";",2);
26565     }
26566     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
26567     if( QSS_PLAINWHITE(qss) && nSql==0 ){
26568       /* Just swallow single-line whitespace */
26569       echo_group_input(p, zLine);
26570       qss = QSS_Start;
26571       continue;
26572     }
26573     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
26574       CONTINUE_PROMPT_RESET;
26575       echo_group_input(p, zLine);
26576       if( zLine[0]=='.' ){
26577         rc = do_meta_command(zLine, p);
26578         if( rc==2 ){ /* exit requested */
26579           break;
26580         }else if( rc ){
26581           errCnt++;
26582         }
26583       }
26584       qss = QSS_Start;
26585       continue;
26586     }
26587     /* No single-line dispositions remain; accumulate line(s). */
26588     nLine = strlen(zLine);
26589     if( nSql+nLine+2>=nAlloc ){
26590       /* Grow buffer by half-again increments when big. */
26591       nAlloc = nSql+(nSql>>1)+nLine+100;
26592       zSql = realloc(zSql, nAlloc);
26593       shell_check_oom(zSql);
26594     }
26595     if( nSql==0 ){
26596       i64 i;
26597       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
26598       assert( nAlloc>0 && zSql!=0 );
26599       memcpy(zSql, zLine+i, nLine+1-i);
26600       startline = p->lineno;
26601       nSql = nLine-i;
26602     }else{
26603       zSql[nSql++] = '\n';
26604       memcpy(zSql+nSql, zLine, nLine+1);
26605       nSql += nLine;
26606     }
26607     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
26608       echo_group_input(p, zSql);
26609       errCnt += runOneSqlLine(p, zSql, p->in, startline);
26610       CONTINUE_PROMPT_RESET;
26611       nSql = 0;
26612       if( p->outCount ){
26613         output_reset(p);
26614         p->outCount = 0;
26615       }else{
26616         clearTempFile(p);
26617       }
26618       p->bSafeMode = p->bSafeModePersist;
26619       qss = QSS_Start;
26620     }else if( nSql && QSS_PLAINWHITE(qss) ){
26621       echo_group_input(p, zSql);
26622       nSql = 0;
26623       qss = QSS_Start;
26624     }
26625   }
26626   if( nSql ){
26627     /* This may be incomplete. Let the SQL parser deal with that. */
26628     echo_group_input(p, zSql);
26629     errCnt += runOneSqlLine(p, zSql, p->in, startline);
26630     CONTINUE_PROMPT_RESET;
26631   }
26632   free(zSql);
26633   free(zLine);
26634   --p->inputNesting;
26635   return errCnt>0;
26636 }
26637 
26638 /*
26639 ** Return a pathname which is the user's home directory.  A
26640 ** 0 return indicates an error of some kind.
26641 */
26642 static char *find_home_dir(int clearFlag){
26643   static char *home_dir = NULL;
26644   if( clearFlag ){
26645     free(home_dir);
26646     home_dir = 0;
26647     return 0;
26648   }
26649   if( home_dir ) return home_dir;
26650 
26651 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
26652      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
26653   {
26654     struct passwd *pwent;
26655     uid_t uid = getuid();
26656     if( (pwent=getpwuid(uid)) != NULL) {
26657       home_dir = pwent->pw_dir;
26658     }
26659   }
26660 #endif
26661 
26662 #if defined(_WIN32_WCE)
26663   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
26664    */
26665   home_dir = "/";
26666 #else
26667 
26668 #if defined(_WIN32) || defined(WIN32)
26669   if (!home_dir) {
26670     home_dir = getenv("USERPROFILE");
26671   }
26672 #endif
26673 
26674   if (!home_dir) {
26675     home_dir = getenv("HOME");
26676   }
26677 
26678 #if defined(_WIN32) || defined(WIN32)
26679   if (!home_dir) {
26680     char *zDrive, *zPath;
26681     int n;
26682     zDrive = getenv("HOMEDRIVE");
26683     zPath = getenv("HOMEPATH");
26684     if( zDrive && zPath ){
26685       n = strlen30(zDrive) + strlen30(zPath) + 1;
26686       home_dir = malloc( n );
26687       if( home_dir==0 ) return 0;
26688       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
26689       return home_dir;
26690     }
26691     home_dir = "c:\\";
26692   }
26693 #endif
26694 
26695 #endif /* !_WIN32_WCE */
26696 
26697   if( home_dir ){
26698     i64 n = strlen(home_dir) + 1;
26699     char *z = malloc( n );
26700     if( z ) memcpy(z, home_dir, n);
26701     home_dir = z;
26702   }
26703 
26704   return home_dir;
26705 }
26706 
26707 /*
26708 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
26709 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
26710 ** the path to it, else return 0. The result is cached for
26711 ** subsequent calls.
26712 */
26713 static const char *find_xdg_config(void){
26714 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
26715      || defined(__RTP__) || defined(_WRS_KERNEL)
26716   return 0;
26717 #else
26718   static int alreadyTried = 0;
26719   static char *zConfig = 0;
26720   const char *zXdgHome;
26721 
26722   if( alreadyTried!=0 ){
26723     return zConfig;
26724   }
26725   alreadyTried = 1;
26726   zXdgHome = getenv("XDG_CONFIG_HOME");
26727   if( zXdgHome==0 ){
26728     return 0;
26729   }
26730   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
26731   shell_check_oom(zConfig);
26732   if( access(zConfig,0)!=0 ){
26733     sqlite3_free(zConfig);
26734     zConfig = 0;
26735   }
26736   return zConfig;
26737 #endif
26738 }
26739 
26740 /*
26741 ** Read input from the file given by sqliterc_override.  Or if that
26742 ** parameter is NULL, take input from the first of find_xdg_config()
26743 ** or ~/.sqliterc which is found.
26744 **
26745 ** Returns the number of errors.
26746 */
26747 static void process_sqliterc(
26748   ShellState *p,                  /* Configuration data */
26749   const char *sqliterc_override   /* Name of config file. NULL to use default */
26750 ){
26751   char *home_dir = NULL;
26752   const char *sqliterc = sqliterc_override;
26753   char *zBuf = 0;
26754   FILE *inSaved = p->in;
26755   int savedLineno = p->lineno;
26756 
26757   if( sqliterc == NULL ){
26758     sqliterc = find_xdg_config();
26759   }
26760   if( sqliterc == NULL ){
26761     home_dir = find_home_dir(0);
26762     if( home_dir==0 ){
26763       raw_printf(stderr, "-- warning: cannot find home directory;"
26764                       " cannot read ~/.sqliterc\n");
26765       return;
26766     }
26767     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
26768     shell_check_oom(zBuf);
26769     sqliterc = zBuf;
26770   }
26771   p->in = fopen(sqliterc,"rb");
26772   if( p->in ){
26773     if( stdin_is_interactive ){
26774       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
26775     }
26776     if( process_input(p) && bail_on_error ) exit(1);
26777     fclose(p->in);
26778   }else if( sqliterc_override!=0 ){
26779     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
26780     if( bail_on_error ) exit(1);
26781   }
26782   p->in = inSaved;
26783   p->lineno = savedLineno;
26784   sqlite3_free(zBuf);
26785 }
26786 
26787 /*
26788 ** Show available command line options
26789 */
26790 static const char zOptions[] =
26791 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
26792   "   -A ARGS...           run \".archive ARGS\" and exit\n"
26793 #endif
26794   "   -append              append the database to the end of the file\n"
26795   "   -ascii               set output mode to 'ascii'\n"
26796   "   -bail                stop after hitting an error\n"
26797   "   -batch               force batch I/O\n"
26798   "   -box                 set output mode to 'box'\n"
26799   "   -column              set output mode to 'column'\n"
26800   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
26801   "   -csv                 set output mode to 'csv'\n"
26802 #if !defined(SQLITE_OMIT_DESERIALIZE)
26803   "   -deserialize         open the database using sqlite3_deserialize()\n"
26804 #endif
26805   "   -echo                print inputs before execution\n"
26806   "   -init FILENAME       read/process named file\n"
26807   "   -[no]header          turn headers on or off\n"
26808 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
26809   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
26810 #endif
26811   "   -help                show this message\n"
26812   "   -html                set output mode to HTML\n"
26813   "   -interactive         force interactive I/O\n"
26814   "   -json                set output mode to 'json'\n"
26815   "   -line                set output mode to 'line'\n"
26816   "   -list                set output mode to 'list'\n"
26817   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
26818   "   -markdown            set output mode to 'markdown'\n"
26819 #if !defined(SQLITE_OMIT_DESERIALIZE)
26820   "   -maxsize N           maximum size for a --deserialize database\n"
26821 #endif
26822   "   -memtrace            trace all memory allocations and deallocations\n"
26823   "   -mmap N              default mmap size set to N\n"
26824 #ifdef SQLITE_ENABLE_MULTIPLEX
26825   "   -multiplex           enable the multiplexor VFS\n"
26826 #endif
26827   "   -newline SEP         set output row separator. Default: '\\n'\n"
26828   "   -nofollow            refuse to open symbolic links to database files\n"
26829   "   -nonce STRING        set the safe-mode escape nonce\n"
26830   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
26831   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
26832   "   -quote               set output mode to 'quote'\n"
26833   "   -readonly            open the database read-only\n"
26834   "   -safe                enable safe-mode\n"
26835   "   -separator SEP       set output column separator. Default: '|'\n"
26836 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
26837   "   -sorterref SIZE      sorter references threshold size\n"
26838 #endif
26839   "   -stats               print memory stats before each finalize\n"
26840   "   -table               set output mode to 'table'\n"
26841   "   -tabs                set output mode to 'tabs'\n"
26842   "   -version             show SQLite version\n"
26843   "   -vfs NAME            use NAME as the default VFS\n"
26844 #ifdef SQLITE_ENABLE_VFSTRACE
26845   "   -vfstrace            enable tracing of all VFS calls\n"
26846 #endif
26847 #ifdef SQLITE_HAVE_ZLIB
26848   "   -zip                 open the file as a ZIP Archive\n"
26849 #endif
26850 ;
26851 static void usage(int showDetail){
26852   utf8_printf(stderr,
26853       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
26854       "FILENAME is the name of an SQLite database. A new database is created\n"
26855       "if the file does not previously exist.\n", Argv0);
26856   if( showDetail ){
26857     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
26858   }else{
26859     raw_printf(stderr, "Use the -help option for additional information\n");
26860   }
26861   exit(1);
26862 }
26863 
26864 /*
26865 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
26866 ** error message if it is initialized.
26867 */
26868 static void verify_uninitialized(void){
26869   if( sqlite3_config(-1)==SQLITE_MISUSE ){
26870     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
26871                         " initialization.\n");
26872   }
26873 }
26874 
26875 /*
26876 ** Initialize the state information in data
26877 */
26878 static void main_init(ShellState *data) {
26879   memset(data, 0, sizeof(*data));
26880   data->normalMode = data->cMode = data->mode = MODE_List;
26881   data->autoExplain = 1;
26882   data->pAuxDb = &data->aAuxDb[0];
26883   memcpy(data->colSeparator,SEP_Column, 2);
26884   memcpy(data->rowSeparator,SEP_Row, 2);
26885   data->showHeader = 0;
26886   data->shellFlgs = SHFLG_Lookaside;
26887   verify_uninitialized();
26888   sqlite3_config(SQLITE_CONFIG_URI, 1);
26889   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
26890   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
26891   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
26892   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
26893 }
26894 
26895 /*
26896 ** Output text to the console in a font that attracts extra attention.
26897 */
26898 #ifdef _WIN32
26899 static void printBold(const char *zText){
26900 #if !SQLITE_OS_WINRT
26901   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
26902   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
26903   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
26904   SetConsoleTextAttribute(out,
26905          FOREGROUND_RED|FOREGROUND_INTENSITY
26906   );
26907 #endif
26908   printf("%s", zText);
26909 #if !SQLITE_OS_WINRT
26910   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
26911 #endif
26912 }
26913 #else
26914 static void printBold(const char *zText){
26915   printf("\033[1m%s\033[0m", zText);
26916 }
26917 #endif
26918 
26919 /*
26920 ** Get the argument to an --option.  Throw an error and die if no argument
26921 ** is available.
26922 */
26923 static char *cmdline_option_value(int argc, char **argv, int i){
26924   if( i==argc ){
26925     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
26926             argv[0], argv[argc-1]);
26927     exit(1);
26928   }
26929   return argv[i];
26930 }
26931 
26932 #ifndef SQLITE_SHELL_IS_UTF8
26933 #  if (defined(_WIN32) || defined(WIN32)) \
26934    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
26935 #    define SQLITE_SHELL_IS_UTF8          (0)
26936 #  else
26937 #    define SQLITE_SHELL_IS_UTF8          (1)
26938 #  endif
26939 #endif
26940 
26941 #ifdef SQLITE_SHELL_FIDDLE
26942 #  define main fiddle_main
26943 #endif
26944 
26945 #if SQLITE_SHELL_IS_UTF8
26946 int SQLITE_CDECL main(int argc, char **argv){
26947 #else
26948 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
26949   char **argv;
26950 #endif
26951 #ifdef SQLITE_DEBUG
26952   sqlite3_int64 mem_main_enter = sqlite3_memory_used();
26953 #endif
26954   char *zErrMsg = 0;
26955 #ifdef SQLITE_SHELL_FIDDLE
26956 #  define data shellState
26957 #else
26958   ShellState data;
26959 #endif
26960   const char *zInitFile = 0;
26961   int i;
26962   int rc = 0;
26963   int warnInmemoryDb = 0;
26964   int readStdin = 1;
26965   int nCmd = 0;
26966   char **azCmd = 0;
26967   const char *zVfs = 0;           /* Value of -vfs command-line option */
26968 #if !SQLITE_SHELL_IS_UTF8
26969   char **argvToFree = 0;
26970   int argcToFree = 0;
26971 #endif
26972 
26973   setBinaryMode(stdin, 0);
26974   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
26975 #ifdef SQLITE_SHELL_FIDDLE
26976   stdin_is_interactive = 0;
26977   stdout_is_console = 1;
26978   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
26979 #else
26980   stdin_is_interactive = isatty(0);
26981   stdout_is_console = isatty(1);
26982 #endif
26983 
26984 #if !defined(_WIN32_WCE)
26985   if( getenv("SQLITE_DEBUG_BREAK") ){
26986     if( isatty(0) && isatty(2) ){
26987       fprintf(stderr,
26988           "attach debugger to process %d and press any key to continue.\n",
26989           GETPID());
26990       fgetc(stdin);
26991     }else{
26992 #if defined(_WIN32) || defined(WIN32)
26993 #if SQLITE_OS_WINRT
26994       __debugbreak();
26995 #else
26996       DebugBreak();
26997 #endif
26998 #elif defined(SIGTRAP)
26999       raise(SIGTRAP);
27000 #endif
27001     }
27002   }
27003 #endif
27004 
27005 #if USE_SYSTEM_SQLITE+0!=1
27006   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
27007     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
27008             sqlite3_sourceid(), SQLITE_SOURCE_ID);
27009     exit(1);
27010   }
27011 #endif
27012   main_init(&data);
27013 
27014   /* On Windows, we must translate command-line arguments into UTF-8.
27015   ** The SQLite memory allocator subsystem has to be enabled in order to
27016   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
27017   ** subsequent sqlite3_config() calls will work.  So copy all results into
27018   ** memory that does not come from the SQLite memory allocator.
27019   */
27020 #if !SQLITE_SHELL_IS_UTF8
27021   sqlite3_initialize();
27022   argvToFree = malloc(sizeof(argv[0])*argc*2);
27023   shell_check_oom(argvToFree);
27024   argcToFree = argc;
27025   argv = argvToFree + argc;
27026   for(i=0; i<argc; i++){
27027     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
27028     i64 n;
27029     shell_check_oom(z);
27030     n = strlen(z);
27031     argv[i] = malloc( n+1 );
27032     shell_check_oom(argv[i]);
27033     memcpy(argv[i], z, n+1);
27034     argvToFree[i] = argv[i];
27035     sqlite3_free(z);
27036   }
27037   sqlite3_shutdown();
27038 #endif
27039 
27040   assert( argc>=1 && argv && argv[0] );
27041   Argv0 = argv[0];
27042 
27043   /* Make sure we have a valid signal handler early, before anything
27044   ** else is done.
27045   */
27046 #ifdef SIGINT
27047   signal(SIGINT, interrupt_handler);
27048 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
27049   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
27050 #endif
27051 
27052 #ifdef SQLITE_SHELL_DBNAME_PROC
27053   {
27054     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
27055     ** of a C-function that will provide the name of the database file.  Use
27056     ** this compile-time option to embed this shell program in larger
27057     ** applications. */
27058     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
27059     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
27060     warnInmemoryDb = 0;
27061   }
27062 #endif
27063 
27064   /* Do an initial pass through the command-line argument to locate
27065   ** the name of the database file, the name of the initialization file,
27066   ** the size of the alternative malloc heap,
27067   ** and the first command to execute.
27068   */
27069   verify_uninitialized();
27070   for(i=1; i<argc; i++){
27071     char *z;
27072     z = argv[i];
27073     if( z[0]!='-' ){
27074       if( data.aAuxDb->zDbFilename==0 ){
27075         data.aAuxDb->zDbFilename = z;
27076       }else{
27077         /* Excesss arguments are interpreted as SQL (or dot-commands) and
27078         ** mean that nothing is read from stdin */
27079         readStdin = 0;
27080         nCmd++;
27081         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
27082         shell_check_oom(azCmd);
27083         azCmd[nCmd-1] = z;
27084       }
27085     }
27086     if( z[1]=='-' ) z++;
27087     if( cli_strcmp(z,"-separator")==0
27088      || cli_strcmp(z,"-nullvalue")==0
27089      || cli_strcmp(z,"-newline")==0
27090      || cli_strcmp(z,"-cmd")==0
27091     ){
27092       (void)cmdline_option_value(argc, argv, ++i);
27093     }else if( cli_strcmp(z,"-init")==0 ){
27094       zInitFile = cmdline_option_value(argc, argv, ++i);
27095     }else if( cli_strcmp(z,"-batch")==0 ){
27096       /* Need to check for batch mode here to so we can avoid printing
27097       ** informational messages (like from process_sqliterc) before
27098       ** we do the actual processing of arguments later in a second pass.
27099       */
27100       stdin_is_interactive = 0;
27101     }else if( cli_strcmp(z,"-heap")==0 ){
27102 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
27103       const char *zSize;
27104       sqlite3_int64 szHeap;
27105 
27106       zSize = cmdline_option_value(argc, argv, ++i);
27107       szHeap = integerValue(zSize);
27108       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
27109       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
27110 #else
27111       (void)cmdline_option_value(argc, argv, ++i);
27112 #endif
27113     }else if( cli_strcmp(z,"-pagecache")==0 ){
27114       sqlite3_int64 n, sz;
27115       sz = integerValue(cmdline_option_value(argc,argv,++i));
27116       if( sz>70000 ) sz = 70000;
27117       if( sz<0 ) sz = 0;
27118       n = integerValue(cmdline_option_value(argc,argv,++i));
27119       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
27120         n = 0xffffffffffffLL/sz;
27121       }
27122       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
27123                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
27124       data.shellFlgs |= SHFLG_Pagecache;
27125     }else if( cli_strcmp(z,"-lookaside")==0 ){
27126       int n, sz;
27127       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
27128       if( sz<0 ) sz = 0;
27129       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
27130       if( n<0 ) n = 0;
27131       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
27132       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
27133     }else if( cli_strcmp(z,"-threadsafe")==0 ){
27134       int n;
27135       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
27136       switch( n ){
27137          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
27138          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
27139          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
27140       }
27141 #ifdef SQLITE_ENABLE_VFSTRACE
27142     }else if( cli_strcmp(z,"-vfstrace")==0 ){
27143       extern int vfstrace_register(
27144          const char *zTraceName,
27145          const char *zOldVfsName,
27146          int (*xOut)(const char*,void*),
27147          void *pOutArg,
27148          int makeDefault
27149       );
27150       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
27151 #endif
27152 #ifdef SQLITE_ENABLE_MULTIPLEX
27153     }else if( cli_strcmp(z,"-multiplex")==0 ){
27154       extern int sqlite3_multiple_initialize(const char*,int);
27155       sqlite3_multiplex_initialize(0, 1);
27156 #endif
27157     }else if( cli_strcmp(z,"-mmap")==0 ){
27158       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
27159       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
27160 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27161     }else if( cli_strcmp(z,"-sorterref")==0 ){
27162       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
27163       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
27164 #endif
27165     }else if( cli_strcmp(z,"-vfs")==0 ){
27166       zVfs = cmdline_option_value(argc, argv, ++i);
27167 #ifdef SQLITE_HAVE_ZLIB
27168     }else if( cli_strcmp(z,"-zip")==0 ){
27169       data.openMode = SHELL_OPEN_ZIPFILE;
27170 #endif
27171     }else if( cli_strcmp(z,"-append")==0 ){
27172       data.openMode = SHELL_OPEN_APPENDVFS;
27173 #ifndef SQLITE_OMIT_DESERIALIZE
27174     }else if( cli_strcmp(z,"-deserialize")==0 ){
27175       data.openMode = SHELL_OPEN_DESERIALIZE;
27176     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
27177       data.szMax = integerValue(argv[++i]);
27178 #endif
27179     }else if( cli_strcmp(z,"-readonly")==0 ){
27180       data.openMode = SHELL_OPEN_READONLY;
27181     }else if( cli_strcmp(z,"-nofollow")==0 ){
27182       data.openFlags = SQLITE_OPEN_NOFOLLOW;
27183 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27184     }else if( cli_strncmp(z, "-A",2)==0 ){
27185       /* All remaining command-line arguments are passed to the ".archive"
27186       ** command, so ignore them */
27187       break;
27188 #endif
27189     }else if( cli_strcmp(z, "-memtrace")==0 ){
27190       sqlite3MemTraceActivate(stderr);
27191     }else if( cli_strcmp(z,"-bail")==0 ){
27192       bail_on_error = 1;
27193     }else if( cli_strcmp(z,"-nonce")==0 ){
27194       free(data.zNonce);
27195       data.zNonce = strdup(argv[++i]);
27196     }else if( cli_strcmp(z,"-safe")==0 ){
27197       /* no-op - catch this on the second pass */
27198     }
27199   }
27200   verify_uninitialized();
27201 
27202 
27203 #ifdef SQLITE_SHELL_INIT_PROC
27204   {
27205     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
27206     ** of a C-function that will perform initialization actions on SQLite that
27207     ** occur just before or after sqlite3_initialize(). Use this compile-time
27208     ** option to embed this shell program in larger applications. */
27209     extern void SQLITE_SHELL_INIT_PROC(void);
27210     SQLITE_SHELL_INIT_PROC();
27211   }
27212 #else
27213   /* All the sqlite3_config() calls have now been made. So it is safe
27214   ** to call sqlite3_initialize() and process any command line -vfs option. */
27215   sqlite3_initialize();
27216 #endif
27217 
27218   if( zVfs ){
27219     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
27220     if( pVfs ){
27221       sqlite3_vfs_register(pVfs, 1);
27222     }else{
27223       utf8_printf(stderr, "no such VFS: \"%s\"\n", zVfs);
27224       exit(1);
27225     }
27226   }
27227 
27228   if( data.pAuxDb->zDbFilename==0 ){
27229 #ifndef SQLITE_OMIT_MEMORYDB
27230     data.pAuxDb->zDbFilename = ":memory:";
27231     warnInmemoryDb = argc==1;
27232 #else
27233     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
27234     return 1;
27235 #endif
27236   }
27237   data.out = stdout;
27238 #ifndef SQLITE_SHELL_FIDDLE
27239   sqlite3_appendvfs_init(0,0,0);
27240 #endif
27241 
27242   /* Go ahead and open the database file if it already exists.  If the
27243   ** file does not exist, delay opening it.  This prevents empty database
27244   ** files from being created if a user mistypes the database name argument
27245   ** to the sqlite command-line tool.
27246   */
27247   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
27248     open_db(&data, 0);
27249   }
27250 
27251   /* Process the initialization file if there is one.  If no -init option
27252   ** is given on the command line, look for a file named ~/.sqliterc and
27253   ** try to process it.
27254   */
27255   process_sqliterc(&data,zInitFile);
27256 
27257   /* Make a second pass through the command-line argument and set
27258   ** options.  This second pass is delayed until after the initialization
27259   ** file is processed so that the command-line arguments will override
27260   ** settings in the initialization file.
27261   */
27262   for(i=1; i<argc; i++){
27263     char *z = argv[i];
27264     if( z[0]!='-' ) continue;
27265     if( z[1]=='-' ){ z++; }
27266     if( cli_strcmp(z,"-init")==0 ){
27267       i++;
27268     }else if( cli_strcmp(z,"-html")==0 ){
27269       data.mode = MODE_Html;
27270     }else if( cli_strcmp(z,"-list")==0 ){
27271       data.mode = MODE_List;
27272     }else if( cli_strcmp(z,"-quote")==0 ){
27273       data.mode = MODE_Quote;
27274       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
27275       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
27276     }else if( cli_strcmp(z,"-line")==0 ){
27277       data.mode = MODE_Line;
27278     }else if( cli_strcmp(z,"-column")==0 ){
27279       data.mode = MODE_Column;
27280     }else if( cli_strcmp(z,"-json")==0 ){
27281       data.mode = MODE_Json;
27282     }else if( cli_strcmp(z,"-markdown")==0 ){
27283       data.mode = MODE_Markdown;
27284     }else if( cli_strcmp(z,"-table")==0 ){
27285       data.mode = MODE_Table;
27286     }else if( cli_strcmp(z,"-box")==0 ){
27287       data.mode = MODE_Box;
27288     }else if( cli_strcmp(z,"-csv")==0 ){
27289       data.mode = MODE_Csv;
27290       memcpy(data.colSeparator,",",2);
27291 #ifdef SQLITE_HAVE_ZLIB
27292     }else if( cli_strcmp(z,"-zip")==0 ){
27293       data.openMode = SHELL_OPEN_ZIPFILE;
27294 #endif
27295     }else if( cli_strcmp(z,"-append")==0 ){
27296       data.openMode = SHELL_OPEN_APPENDVFS;
27297 #ifndef SQLITE_OMIT_DESERIALIZE
27298     }else if( cli_strcmp(z,"-deserialize")==0 ){
27299       data.openMode = SHELL_OPEN_DESERIALIZE;
27300     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
27301       data.szMax = integerValue(argv[++i]);
27302 #endif
27303     }else if( cli_strcmp(z,"-readonly")==0 ){
27304       data.openMode = SHELL_OPEN_READONLY;
27305     }else if( cli_strcmp(z,"-nofollow")==0 ){
27306       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
27307     }else if( cli_strcmp(z,"-ascii")==0 ){
27308       data.mode = MODE_Ascii;
27309       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
27310       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
27311     }else if( cli_strcmp(z,"-tabs")==0 ){
27312       data.mode = MODE_List;
27313       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
27314       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
27315     }else if( cli_strcmp(z,"-separator")==0 ){
27316       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
27317                        "%s",cmdline_option_value(argc,argv,++i));
27318     }else if( cli_strcmp(z,"-newline")==0 ){
27319       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
27320                        "%s",cmdline_option_value(argc,argv,++i));
27321     }else if( cli_strcmp(z,"-nullvalue")==0 ){
27322       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
27323                        "%s",cmdline_option_value(argc,argv,++i));
27324     }else if( cli_strcmp(z,"-header")==0 ){
27325       data.showHeader = 1;
27326       ShellSetFlag(&data, SHFLG_HeaderSet);
27327      }else if( cli_strcmp(z,"-noheader")==0 ){
27328       data.showHeader = 0;
27329       ShellSetFlag(&data, SHFLG_HeaderSet);
27330     }else if( cli_strcmp(z,"-echo")==0 ){
27331       ShellSetFlag(&data, SHFLG_Echo);
27332     }else if( cli_strcmp(z,"-eqp")==0 ){
27333       data.autoEQP = AUTOEQP_on;
27334     }else if( cli_strcmp(z,"-eqpfull")==0 ){
27335       data.autoEQP = AUTOEQP_full;
27336     }else if( cli_strcmp(z,"-stats")==0 ){
27337       data.statsOn = 1;
27338     }else if( cli_strcmp(z,"-scanstats")==0 ){
27339       data.scanstatsOn = 1;
27340     }else if( cli_strcmp(z,"-backslash")==0 ){
27341       /* Undocumented command-line option: -backslash
27342       ** Causes C-style backslash escapes to be evaluated in SQL statements
27343       ** prior to sending the SQL into SQLite.  Useful for injecting
27344       ** crazy bytes in the middle of SQL statements for testing and debugging.
27345       */
27346       ShellSetFlag(&data, SHFLG_Backslash);
27347     }else if( cli_strcmp(z,"-bail")==0 ){
27348       /* No-op.  The bail_on_error flag should already be set. */
27349     }else if( cli_strcmp(z,"-version")==0 ){
27350       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
27351       return 0;
27352     }else if( cli_strcmp(z,"-interactive")==0 ){
27353       stdin_is_interactive = 1;
27354     }else if( cli_strcmp(z,"-batch")==0 ){
27355       stdin_is_interactive = 0;
27356     }else if( cli_strcmp(z,"-heap")==0 ){
27357       i++;
27358     }else if( cli_strcmp(z,"-pagecache")==0 ){
27359       i+=2;
27360     }else if( cli_strcmp(z,"-lookaside")==0 ){
27361       i+=2;
27362     }else if( cli_strcmp(z,"-threadsafe")==0 ){
27363       i+=2;
27364     }else if( cli_strcmp(z,"-nonce")==0 ){
27365       i += 2;
27366     }else if( cli_strcmp(z,"-mmap")==0 ){
27367       i++;
27368     }else if( cli_strcmp(z,"-memtrace")==0 ){
27369       i++;
27370 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27371     }else if( cli_strcmp(z,"-sorterref")==0 ){
27372       i++;
27373 #endif
27374     }else if( cli_strcmp(z,"-vfs")==0 ){
27375       i++;
27376 #ifdef SQLITE_ENABLE_VFSTRACE
27377     }else if( cli_strcmp(z,"-vfstrace")==0 ){
27378       i++;
27379 #endif
27380 #ifdef SQLITE_ENABLE_MULTIPLEX
27381     }else if( cli_strcmp(z,"-multiplex")==0 ){
27382       i++;
27383 #endif
27384     }else if( cli_strcmp(z,"-help")==0 ){
27385       usage(1);
27386     }else if( cli_strcmp(z,"-cmd")==0 ){
27387       /* Run commands that follow -cmd first and separately from commands
27388       ** that simply appear on the command-line.  This seems goofy.  It would
27389       ** be better if all commands ran in the order that they appear.  But
27390       ** we retain the goofy behavior for historical compatibility. */
27391       if( i==argc-1 ) break;
27392       z = cmdline_option_value(argc,argv,++i);
27393       if( z[0]=='.' ){
27394         rc = do_meta_command(z, &data);
27395         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
27396       }else{
27397         open_db(&data, 0);
27398         rc = shell_exec(&data, z, &zErrMsg);
27399         if( zErrMsg!=0 ){
27400           utf8_printf(stderr,"Error: %s\n", zErrMsg);
27401           if( bail_on_error ) return rc!=0 ? rc : 1;
27402         }else if( rc!=0 ){
27403           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
27404           if( bail_on_error ) return rc;
27405         }
27406       }
27407 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27408     }else if( cli_strncmp(z, "-A", 2)==0 ){
27409       if( nCmd>0 ){
27410         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
27411                             " with \"%s\"\n", z);
27412         return 1;
27413       }
27414       open_db(&data, OPEN_DB_ZIPFILE);
27415       if( z[2] ){
27416         argv[i] = &z[2];
27417         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
27418       }else{
27419         arDotCommand(&data, 1, argv+i, argc-i);
27420       }
27421       readStdin = 0;
27422       break;
27423 #endif
27424     }else if( cli_strcmp(z,"-safe")==0 ){
27425       data.bSafeMode = data.bSafeModePersist = 1;
27426     }else{
27427       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
27428       raw_printf(stderr,"Use -help for a list of options.\n");
27429       return 1;
27430     }
27431     data.cMode = data.mode;
27432   }
27433 
27434   if( !readStdin ){
27435     /* Run all arguments that do not begin with '-' as if they were separate
27436     ** command-line inputs, except for the argToSkip argument which contains
27437     ** the database filename.
27438     */
27439     for(i=0; i<nCmd; i++){
27440       if( azCmd[i][0]=='.' ){
27441         rc = do_meta_command(azCmd[i], &data);
27442         if( rc ){
27443           free(azCmd);
27444           return rc==2 ? 0 : rc;
27445         }
27446       }else{
27447         open_db(&data, 0);
27448         rc = shell_exec(&data, azCmd[i], &zErrMsg);
27449         if( zErrMsg || rc ){
27450           if( zErrMsg!=0 ){
27451             utf8_printf(stderr,"Error: %s\n", zErrMsg);
27452           }else{
27453             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
27454           }
27455           sqlite3_free(zErrMsg);
27456           free(azCmd);
27457           return rc!=0 ? rc : 1;
27458         }
27459       }
27460     }
27461   }else{
27462     /* Run commands received from standard input
27463     */
27464     if( stdin_is_interactive ){
27465       char *zHome;
27466       char *zHistory;
27467       int nHistory;
27468       printf(
27469         "SQLite version %s %.19s\n" /*extra-version-info*/
27470         "Enter \".help\" for usage hints.\n",
27471         sqlite3_libversion(), sqlite3_sourceid()
27472       );
27473       if( warnInmemoryDb ){
27474         printf("Connected to a ");
27475         printBold("transient in-memory database");
27476         printf(".\nUse \".open FILENAME\" to reopen on a "
27477                "persistent database.\n");
27478       }
27479       zHistory = getenv("SQLITE_HISTORY");
27480       if( zHistory ){
27481         zHistory = strdup(zHistory);
27482       }else if( (zHome = find_home_dir(0))!=0 ){
27483         nHistory = strlen30(zHome) + 20;
27484         if( (zHistory = malloc(nHistory))!=0 ){
27485           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
27486         }
27487       }
27488       if( zHistory ){ shell_read_history(zHistory); }
27489 #if HAVE_READLINE || HAVE_EDITLINE
27490       rl_attempted_completion_function = readline_completion;
27491 #elif HAVE_LINENOISE
27492       linenoiseSetCompletionCallback(linenoise_completion);
27493 #endif
27494       data.in = 0;
27495       rc = process_input(&data);
27496       if( zHistory ){
27497         shell_stifle_history(2000);
27498         shell_write_history(zHistory);
27499         free(zHistory);
27500       }
27501     }else{
27502       data.in = stdin;
27503       rc = process_input(&data);
27504     }
27505   }
27506 #ifndef SQLITE_SHELL_FIDDLE
27507   /* In WASM mode we have to leave the db state in place so that
27508   ** client code can "push" SQL into it after this call returns. */
27509   free(azCmd);
27510   set_table_name(&data, 0);
27511   if( data.db ){
27512     session_close_all(&data, -1);
27513     close_db(data.db);
27514   }
27515   for(i=0; i<ArraySize(data.aAuxDb); i++){
27516     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
27517     if( data.aAuxDb[i].db ){
27518       session_close_all(&data, i);
27519       close_db(data.aAuxDb[i].db);
27520     }
27521   }
27522   find_home_dir(1);
27523   output_reset(&data);
27524   data.doXdgOpen = 0;
27525   clearTempFile(&data);
27526 #if !SQLITE_SHELL_IS_UTF8
27527   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
27528   free(argvToFree);
27529 #endif
27530   free(data.colWidth);
27531   free(data.zNonce);
27532   /* Clear the global data structure so that valgrind will detect memory
27533   ** leaks */
27534   memset(&data, 0, sizeof(data));
27535 #ifdef SQLITE_DEBUG
27536   if( sqlite3_memory_used()>mem_main_enter ){
27537     utf8_printf(stderr, "Memory leaked: %u bytes\n",
27538                 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
27539   }
27540 #endif
27541 #endif /* !SQLITE_SHELL_FIDDLE */
27542   return rc;
27543 }
27544 
27545 
27546 #ifdef SQLITE_SHELL_FIDDLE
27547 /* Only for emcc experimentation purposes. */
27548 int fiddle_experiment(int a,int b){
27549   return a + b;
27550 }
27551 
27552 /*
27553 ** Returns a pointer to the current DB handle.
27554 */
27555 sqlite3 * fiddle_db_handle(){
27556   return globalDb;
27557 }
27558 
27559 /*
27560 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
27561 ** "main" is assumed. Returns 0 if no db with the given name is
27562 ** open.
27563 */
27564 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
27565   sqlite3_vfs * pVfs = 0;
27566   if(globalDb){
27567     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
27568                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
27569   }
27570   return pVfs;
27571 }
27572 
27573 /* Only for emcc experimentation purposes. */
27574 sqlite3 * fiddle_db_arg(sqlite3 *arg){
27575     printf("fiddle_db_arg(%p)\n", (const void*)arg);
27576     return arg;
27577 }
27578 
27579 /*
27580 ** Intended to be called via a SharedWorker() while a separate
27581 ** SharedWorker() (which manages the wasm module) is performing work
27582 ** which should be interrupted. Unfortunately, SharedWorker is not
27583 ** portable enough to make real use of.
27584 */
27585 void fiddle_interrupt(void){
27586   if( globalDb ) sqlite3_interrupt(globalDb);
27587 }
27588 
27589 /*
27590 ** Returns the filename of the given db name, assuming "main" if
27591 ** zDbName is NULL. Returns NULL if globalDb is not opened.
27592 */
27593 const char * fiddle_db_filename(const char * zDbName){
27594     return globalDb
27595       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
27596       : NULL;
27597 }
27598 
27599 /*
27600 ** Completely wipes out the contents of the currently-opened database
27601 ** but leaves its storage intact for reuse.
27602 */
27603 void fiddle_reset_db(void){
27604   if( globalDb ){
27605     int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
27606     if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
27607     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
27608   }
27609 }
27610 
27611 /*
27612 ** Uses the current database's VFS xRead to stream the db file's
27613 ** contents out to the given callback. The callback gets a single
27614 ** chunk of size n (its 2nd argument) on each call and must return 0
27615 ** on success, non-0 on error. This function returns 0 on success,
27616 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
27617 ** code from the callback. Note that this is not thread-friendly: it
27618 ** expects that it will be the only thread reading the db file and
27619 ** takes no measures to ensure that is the case.
27620 */
27621 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
27622   sqlite3_int64 nSize = 0;
27623   sqlite3_int64 nPos = 0;
27624   sqlite3_file * pFile = 0;
27625   unsigned char buf[1024 * 8];
27626   int nBuf = (int)sizeof(buf);
27627   int rc = shellState.db
27628     ? sqlite3_file_control(shellState.db, "main",
27629                            SQLITE_FCNTL_FILE_POINTER, &pFile)
27630     : SQLITE_NOTFOUND;
27631   if( rc ) return rc;
27632   rc = pFile->pMethods->xFileSize(pFile, &nSize);
27633   if( rc ) return rc;
27634   if(nSize % nBuf){
27635     /* DB size is not an even multiple of the buffer size. Reduce
27636     ** buffer size so that we do not unduly inflate the db size when
27637     ** exporting. */
27638     if(0 == nSize % 4096) nBuf = 4096;
27639     else if(0 == nSize % 2048) nBuf = 2048;
27640     else if(0 == nSize % 1024) nBuf = 1024;
27641     else nBuf = 512;
27642   }
27643   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
27644     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
27645     if(SQLITE_IOERR_SHORT_READ == rc){
27646       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
27647     }
27648     if( 0==rc ) rc = xCallback(buf, nBuf);
27649   }
27650   return rc;
27651 }
27652 
27653 /*
27654 ** Trivial exportable function for emscripten. It processes zSql as if
27655 ** it were input to the sqlite3 shell and redirects all output to the
27656 ** wasm binding. fiddle_main() must have been called before this
27657 ** is called, or results are undefined.
27658 */
27659 void fiddle_exec(const char * zSql){
27660   if(zSql && *zSql){
27661     if('.'==*zSql) puts(zSql);
27662     shellState.wasm.zInput = zSql;
27663     shellState.wasm.zPos = zSql;
27664     process_input(&shellState);
27665     shellState.wasm.zInput = shellState.wasm.zPos = 0;
27666   }
27667 }
27668 #endif /* SQLITE_SHELL_FIDDLE */
27669