xref: /freebsd/contrib/sqlite3/shell.c (revision 2a0c0aea42092f89c2a5345991e6e3ce4cbef99a)
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 <math.h>
121 #include "sqlite3.h"
122 typedef sqlite3_int64 i64;
123 typedef sqlite3_uint64 u64;
124 typedef unsigned char u8;
125 #if SQLITE_USER_AUTHENTICATION
126 # include "sqlite3userauth.h"
127 #endif
128 #include <ctype.h>
129 #include <stdarg.h>
130 
131 #if !defined(_WIN32) && !defined(WIN32)
132 # include <signal.h>
133 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
134 #  include <pwd.h>
135 # endif
136 #endif
137 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
138 # include <unistd.h>
139 # include <dirent.h>
140 # define GETPID getpid
141 # if defined(__MINGW32__)
142 #  define DIRENT dirent
143 #  ifndef S_ISLNK
144 #   define S_ISLNK(mode) (0)
145 #  endif
146 # endif
147 #else
148 # define GETPID (int)GetCurrentProcessId
149 #endif
150 #include <sys/types.h>
151 #include <sys/stat.h>
152 
153 #if HAVE_READLINE
154 # include <readline/readline.h>
155 # include <readline/history.h>
156 #endif
157 
158 #if HAVE_EDITLINE
159 # include <editline/readline.h>
160 #endif
161 
162 #if HAVE_EDITLINE || HAVE_READLINE
163 
164 # define shell_add_history(X) add_history(X)
165 # define shell_read_history(X) read_history(X)
166 # define shell_write_history(X) write_history(X)
167 # define shell_stifle_history(X) stifle_history(X)
168 # define shell_readline(X) readline(X)
169 
170 #elif HAVE_LINENOISE
171 
172 # include "linenoise.h"
173 # define shell_add_history(X) linenoiseHistoryAdd(X)
174 # define shell_read_history(X) linenoiseHistoryLoad(X)
175 # define shell_write_history(X) linenoiseHistorySave(X)
176 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
177 # define shell_readline(X) linenoise(X)
178 
179 #else
180 
181 # define shell_read_history(X)
182 # define shell_write_history(X)
183 # define shell_stifle_history(X)
184 
185 # define SHELL_USE_LOCAL_GETLINE 1
186 #endif
187 
188 #ifndef deliberate_fall_through
189 /* Quiet some compilers about some of our intentional code. */
190 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
191 #  define deliberate_fall_through __attribute__((fallthrough));
192 # else
193 #  define deliberate_fall_through
194 # endif
195 #endif
196 
197 #if defined(_WIN32) || defined(WIN32)
198 # if SQLITE_OS_WINRT
199 #  define SQLITE_OMIT_POPEN 1
200 # else
201 #  include <io.h>
202 #  include <fcntl.h>
203 #  define isatty(h) _isatty(h)
204 #  ifndef access
205 #   define access(f,m) _access((f),(m))
206 #  endif
207 #  ifndef unlink
208 #   define unlink _unlink
209 #  endif
210 #  ifndef strdup
211 #   define strdup _strdup
212 #  endif
213 #  undef popen
214 #  define popen _popen
215 #  undef pclose
216 #  define pclose _pclose
217 # endif
218 #else
219  /* Make sure isatty() has a prototype. */
220  extern int isatty(int);
221 
222 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
223   /* popen and pclose are not C89 functions and so are
224   ** sometimes omitted from the <stdio.h> header */
225    extern FILE *popen(const char*,const char*);
226    extern int pclose(FILE*);
227 # else
228 #  define SQLITE_OMIT_POPEN 1
229 # endif
230 #endif
231 
232 #if defined(_WIN32_WCE)
233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
234  * thus we always assume that we have a console. That can be
235  * overridden with the -batch command line option.
236  */
237 #define isatty(x) 1
238 #endif
239 
240 /* ctype macros that work with signed characters */
241 #define IsSpace(X)  isspace((unsigned char)X)
242 #define IsDigit(X)  isdigit((unsigned char)X)
243 #define ToLower(X)  (char)tolower((unsigned char)X)
244 
245 #if defined(_WIN32) || defined(WIN32)
246 #if SQLITE_OS_WINRT
247 #include <intrin.h>
248 #endif
249 #define WIN32_LEAN_AND_MEAN
250 #include <windows.h>
251 
252 /* string conversion routines only needed on Win32 */
253 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
254 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
255 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
256 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
257 #endif
258 
259 /* On Windows, we normally run with output mode of TEXT so that \n characters
260 ** are automatically translated into \r\n.  However, this behavior needs
261 ** to be disabled in some cases (ex: when generating CSV output and when
262 ** rendering quoted strings that contain \n characters).  The following
263 ** routines take care of that.
264 */
265 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
266 static void setBinaryMode(FILE *file, int isOutput){
267   if( isOutput ) fflush(file);
268   _setmode(_fileno(file), _O_BINARY);
269 }
270 static void setTextMode(FILE *file, int isOutput){
271   if( isOutput ) fflush(file);
272   _setmode(_fileno(file), _O_TEXT);
273 }
274 #else
275 # define setBinaryMode(X,Y)
276 # define setTextMode(X,Y)
277 #endif
278 
279 /* True if the timer is enabled */
280 static int enableTimer = 0;
281 
282 /* A version of strcmp() that works with NULL values */
283 static int cli_strcmp(const char *a, const char *b){
284   if( a==0 ) a = "";
285   if( b==0 ) b = "";
286   return strcmp(a,b);
287 }
288 static int cli_strncmp(const char *a, const char *b, size_t n){
289   if( a==0 ) a = "";
290   if( b==0 ) b = "";
291   return strncmp(a,b,n);
292 }
293 
294 /* Return the current wall-clock time */
295 static sqlite3_int64 timeOfDay(void){
296   static sqlite3_vfs *clockVfs = 0;
297   sqlite3_int64 t;
298   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
299   if( clockVfs==0 ) return 0;  /* Never actually happens */
300   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
301     clockVfs->xCurrentTimeInt64(clockVfs, &t);
302   }else{
303     double r;
304     clockVfs->xCurrentTime(clockVfs, &r);
305     t = (sqlite3_int64)(r*86400000.0);
306   }
307   return t;
308 }
309 
310 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
311 #include <sys/time.h>
312 #include <sys/resource.h>
313 
314 /* VxWorks does not support getrusage() as far as we can determine */
315 #if defined(_WRS_KERNEL) || defined(__RTP__)
316 struct rusage {
317   struct timeval ru_utime; /* user CPU time used */
318   struct timeval ru_stime; /* system CPU time used */
319 };
320 #define getrusage(A,B) memset(B,0,sizeof(*B))
321 #endif
322 
323 /* Saved resource information for the beginning of an operation */
324 static struct rusage sBegin;  /* CPU time at start */
325 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
326 
327 /*
328 ** Begin timing an operation
329 */
330 static void beginTimer(void){
331   if( enableTimer ){
332     getrusage(RUSAGE_SELF, &sBegin);
333     iBegin = timeOfDay();
334   }
335 }
336 
337 /* Return the difference of two time_structs in seconds */
338 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
339   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
340          (double)(pEnd->tv_sec - pStart->tv_sec);
341 }
342 
343 /*
344 ** Print the timing results.
345 */
346 static void endTimer(void){
347   if( enableTimer ){
348     sqlite3_int64 iEnd = timeOfDay();
349     struct rusage sEnd;
350     getrusage(RUSAGE_SELF, &sEnd);
351     printf("Run Time: real %.3f user %f sys %f\n",
352        (iEnd - iBegin)*0.001,
353        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
354        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
355   }
356 }
357 
358 #define BEGIN_TIMER beginTimer()
359 #define END_TIMER endTimer()
360 #define HAS_TIMER 1
361 
362 #elif (defined(_WIN32) || defined(WIN32))
363 
364 /* Saved resource information for the beginning of an operation */
365 static HANDLE hProcess;
366 static FILETIME ftKernelBegin;
367 static FILETIME ftUserBegin;
368 static sqlite3_int64 ftWallBegin;
369 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
370                                     LPFILETIME, LPFILETIME);
371 static GETPROCTIMES getProcessTimesAddr = NULL;
372 
373 /*
374 ** Check to see if we have timer support.  Return 1 if necessary
375 ** support found (or found previously).
376 */
377 static int hasTimer(void){
378   if( getProcessTimesAddr ){
379     return 1;
380   } else {
381 #if !SQLITE_OS_WINRT
382     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
383     ** versions. See if the version we are running on has it, and if it
384     ** does, save off a pointer to it and the current process handle.
385     */
386     hProcess = GetCurrentProcess();
387     if( hProcess ){
388       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
389       if( NULL != hinstLib ){
390         getProcessTimesAddr =
391             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
392         if( NULL != getProcessTimesAddr ){
393           return 1;
394         }
395         FreeLibrary(hinstLib);
396       }
397     }
398 #endif
399   }
400   return 0;
401 }
402 
403 /*
404 ** Begin timing an operation
405 */
406 static void beginTimer(void){
407   if( enableTimer && getProcessTimesAddr ){
408     FILETIME ftCreation, ftExit;
409     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
410                         &ftKernelBegin,&ftUserBegin);
411     ftWallBegin = timeOfDay();
412   }
413 }
414 
415 /* Return the difference of two FILETIME structs in seconds */
416 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
417   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
418   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
419   return (double) ((i64End - i64Start) / 10000000.0);
420 }
421 
422 /*
423 ** Print the timing results.
424 */
425 static void endTimer(void){
426   if( enableTimer && getProcessTimesAddr){
427     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
428     sqlite3_int64 ftWallEnd = timeOfDay();
429     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
430     printf("Run Time: real %.3f user %f sys %f\n",
431        (ftWallEnd - ftWallBegin)*0.001,
432        timeDiff(&ftUserBegin, &ftUserEnd),
433        timeDiff(&ftKernelBegin, &ftKernelEnd));
434   }
435 }
436 
437 #define BEGIN_TIMER beginTimer()
438 #define END_TIMER endTimer()
439 #define HAS_TIMER hasTimer()
440 
441 #else
442 #define BEGIN_TIMER
443 #define END_TIMER
444 #define HAS_TIMER 0
445 #endif
446 
447 /*
448 ** Used to prevent warnings about unused parameters
449 */
450 #define UNUSED_PARAMETER(x) (void)(x)
451 
452 /*
453 ** Number of elements in an array
454 */
455 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
456 
457 /*
458 ** If the following flag is set, then command execution stops
459 ** at an error if we are not interactive.
460 */
461 static int bail_on_error = 0;
462 
463 /*
464 ** Treat stdin as an interactive input if the following variable
465 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
466 */
467 static int stdin_is_interactive = 1;
468 
469 #if (defined(_WIN32) || defined(WIN32)) && SHELL_USE_LOCAL_GETLINE \
470   && !defined(SHELL_OMIT_WIN_UTF8)
471 # define SHELL_WIN_UTF8_OPT 1
472 #else
473 # define SHELL_WIN_UTF8_OPT 0
474 #endif
475 
476 #if SHELL_WIN_UTF8_OPT
477 /*
478 ** Setup console for UTF-8 input/output when following variable true.
479 */
480 static int console_utf8 = 0;
481 #endif
482 
483 /*
484 ** On Windows systems we have to know if standard output is a console
485 ** in order to translate UTF-8 into MBCS.  The following variable is
486 ** true if translation is required.
487 */
488 static int stdout_is_console = 1;
489 
490 /*
491 ** The following is the open SQLite database.  We make a pointer
492 ** to this database a static variable so that it can be accessed
493 ** by the SIGINT handler to interrupt database processing.
494 */
495 static sqlite3 *globalDb = 0;
496 
497 /*
498 ** True if an interrupt (Control-C) has been received.
499 */
500 static volatile int seenInterrupt = 0;
501 
502 /*
503 ** This is the name of our program. It is set in main(), used
504 ** in a number of other places, mostly for error messages.
505 */
506 static char *Argv0;
507 
508 /*
509 ** Prompt strings. Initialized in main. Settable with
510 **   .prompt main continue
511 */
512 #define PROMPT_LEN_MAX 20
513 /* First line prompt.   default: "sqlite> " */
514 static char mainPrompt[PROMPT_LEN_MAX];
515 /* Continuation prompt. default: "   ...> " */
516 static char continuePrompt[PROMPT_LEN_MAX];
517 
518 /* This is variant of the standard-library strncpy() routine with the
519 ** one change that the destination string is always zero-terminated, even
520 ** if there is no zero-terminator in the first n-1 characters of the source
521 ** string.
522 */
523 static char *shell_strncpy(char *dest, const char *src, size_t n){
524   size_t i;
525   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
526   dest[i] = 0;
527   return dest;
528 }
529 
530 /*
531 ** Optionally disable dynamic continuation prompt.
532 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
533 ** or open parentheses level if non-zero, or continuation prompt as set.
534 ** This facility interacts with the scanner and process_input() where the
535 ** below 5 macros are used.
536 */
537 #ifdef SQLITE_OMIT_DYNAPROMPT
538 # define CONTINUATION_PROMPT continuePrompt
539 # define CONTINUE_PROMPT_RESET
540 # define CONTINUE_PROMPT_AWAITS(p,s)
541 # define CONTINUE_PROMPT_AWAITC(p,c)
542 # define CONTINUE_PAREN_INCR(p,n)
543 # define CONTINUE_PROMPT_PSTATE 0
544 typedef void *t_NoDynaPrompt;
545 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
546 #else
547 # define CONTINUATION_PROMPT dynamicContinuePrompt()
548 # define CONTINUE_PROMPT_RESET \
549   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
550 # define CONTINUE_PROMPT_AWAITS(p,s) \
551   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
552 # define CONTINUE_PROMPT_AWAITC(p,c) \
553   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
554 # define CONTINUE_PAREN_INCR(p,n) \
555   if(p && stdin_is_interactive) (trackParenLevel(p,n))
556 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
557 typedef struct DynaPrompt *t_DynaPromptRef;
558 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
559 
560 static struct DynaPrompt {
561   char dynamicPrompt[PROMPT_LEN_MAX];
562   char acAwait[2];
563   int inParenLevel;
564   char *zScannerAwaits;
565 } dynPrompt = { {0}, {0}, 0, 0 };
566 
567 /* Record parenthesis nesting level change, or force level to 0. */
568 static void trackParenLevel(struct DynaPrompt *p, int ni){
569   p->inParenLevel += ni;
570   if( ni==0 ) p->inParenLevel = 0;
571   p->zScannerAwaits = 0;
572 }
573 
574 /* Record that a lexeme is opened, or closed with args==0. */
575 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
576   if( s!=0 || c==0 ){
577     p->zScannerAwaits = s;
578     p->acAwait[0] = 0;
579   }else{
580     p->acAwait[0] = c;
581     p->zScannerAwaits = p->acAwait;
582   }
583 }
584 
585 /* Upon demand, derive the continuation prompt to display. */
586 static char *dynamicContinuePrompt(void){
587   if( continuePrompt[0]==0
588       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
589     return continuePrompt;
590   }else{
591     if( dynPrompt.zScannerAwaits ){
592       size_t ncp = strlen(continuePrompt);
593       size_t ndp = strlen(dynPrompt.zScannerAwaits);
594       if( ndp > ncp-3 ) return continuePrompt;
595       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
596       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
597       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
598               PROMPT_LEN_MAX-4);
599     }else{
600       if( dynPrompt.inParenLevel>9 ){
601         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
602       }else if( dynPrompt.inParenLevel<0 ){
603         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
604       }else{
605         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
606         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
607       }
608       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, PROMPT_LEN_MAX-4);
609     }
610   }
611   return dynPrompt.dynamicPrompt;
612 }
613 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
614 
615 #if SHELL_WIN_UTF8_OPT
616 /* Following struct is used for -utf8 operation. */
617 static struct ConsoleState {
618   int stdinEof;      /* EOF has been seen on console input */
619   int infsMode;      /* Input file stream mode upon shell start */
620   UINT inCodePage;   /* Input code page upon shell start */
621   UINT outCodePage;  /* Output code page upon shell start */
622   HANDLE hConsoleIn; /* Console input handle */
623   DWORD consoleMode; /* Console mode upon shell start */
624 } conState = { 0, 0, 0, 0, INVALID_HANDLE_VALUE, 0 };
625 
626 #ifndef _O_U16TEXT /* For build environments lacking this constant: */
627 # define _O_U16TEXT 0x20000
628 #endif
629 
630 /*
631 ** Prepare console, (if known to be a WIN32 console), for UTF-8
632 ** input (from either typing or suitable paste operations) and for
633 ** UTF-8 rendering. This may "fail" with a message to stderr, where
634 ** the preparation is not done and common "code page" issues occur.
635 */
636 static void console_prepare(void){
637   HANDLE hCI = GetStdHandle(STD_INPUT_HANDLE);
638   DWORD consoleMode = 0;
639   if( isatty(0) && GetFileType(hCI)==FILE_TYPE_CHAR
640       && GetConsoleMode( hCI, &consoleMode) ){
641     if( !IsValidCodePage(CP_UTF8) ){
642       fprintf(stderr, "Cannot use UTF-8 code page.\n");
643       console_utf8 = 0;
644       return;
645     }
646     conState.hConsoleIn = hCI;
647     conState.consoleMode = consoleMode;
648     conState.inCodePage = GetConsoleCP();
649     conState.outCodePage = GetConsoleOutputCP();
650     SetConsoleCP(CP_UTF8);
651     SetConsoleOutputCP(CP_UTF8);
652     consoleMode |= ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
653     SetConsoleMode(conState.hConsoleIn, consoleMode);
654     conState.infsMode = _setmode(_fileno(stdin), _O_U16TEXT);
655     console_utf8 = 1;
656   }else{
657     console_utf8 = 0;
658   }
659 }
660 
661 /*
662 ** Undo the effects of console_prepare(), if any.
663 */
664 static void SQLITE_CDECL console_restore(void){
665   if( console_utf8 && conState.inCodePage!=0
666       && conState.hConsoleIn!=INVALID_HANDLE_VALUE ){
667     _setmode(_fileno(stdin), conState.infsMode);
668     SetConsoleCP(conState.inCodePage);
669     SetConsoleOutputCP(conState.outCodePage);
670     SetConsoleMode(conState.hConsoleIn, conState.consoleMode);
671     /* Avoid multiple calls. */
672     conState.hConsoleIn = INVALID_HANDLE_VALUE;
673     conState.consoleMode = 0;
674     console_utf8 = 0;
675   }
676 }
677 
678 /*
679 ** Collect input like fgets(...) with special provisions for input
680 ** from the Windows console to get around its strange coding issues.
681 ** Defers to plain fgets() when input is not interactive or when the
682 ** startup option, -utf8, has not been provided or taken effect.
683 */
684 static char* utf8_fgets(char *buf, int ncmax, FILE *fin){
685   if( fin==0 ) fin = stdin;
686   if( fin==stdin && stdin_is_interactive && console_utf8 ){
687 # define SQLITE_IALIM 150
688     wchar_t wbuf[SQLITE_IALIM];
689     int lend = 0;
690     int noc = 0;
691     if( ncmax==0 || conState.stdinEof ) return 0;
692     buf[0] = 0;
693     while( noc<ncmax-7-1 && !lend ){
694       /* There is room for at least 2 more characters and a 0-terminator. */
695       int na = (ncmax > SQLITE_IALIM*4+1 + noc)
696         ? SQLITE_IALIM : (ncmax-1 - noc)/4;
697 # undef SQLITE_IALIM
698       DWORD nbr = 0;
699       BOOL bRC = ReadConsoleW(conState.hConsoleIn, wbuf, na, &nbr, 0);
700       if( !bRC || (noc==0 && nbr==0) ) return 0;
701       if( nbr > 0 ){
702         int nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
703                                       wbuf,nbr,0,0,0,0);
704         if( nmb !=0 && noc+nmb <= ncmax ){
705           int iseg = noc;
706           nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
707                                     wbuf,nbr,buf+noc,nmb,0,0);
708           noc += nmb;
709           /* Fixup line-ends as coded by Windows for CR (or "Enter".)*/
710           if( noc > 0 ){
711             if( buf[noc-1]=='\n' ){
712               lend = 1;
713               if( noc > 1 && buf[noc-2]=='\r' ){
714                 buf[noc-2] = '\n';
715                 --noc;
716               }
717             }
718           }
719           /* Check for ^Z (anywhere in line) too. */
720           while( iseg < noc ){
721             if( buf[iseg]==0x1a ){
722               conState.stdinEof = 1;
723               noc = iseg; /* Chop ^Z and anything following. */
724               break;
725             }
726             ++iseg;
727           }
728         }else break; /* Drop apparent garbage in. (Could assert.) */
729       }else break;
730     }
731     /* If got nothing, (after ^Z chop), must be at end-of-file. */
732     if( noc == 0 ) return 0;
733     buf[noc] = 0;
734     return buf;
735   }else{
736     return fgets(buf, ncmax, fin);
737   }
738 }
739 
740 # define fgets(b,n,f) utf8_fgets(b,n,f)
741 #endif /* SHELL_WIN_UTF8_OPT */
742 
743 /*
744 ** Render output like fprintf().  Except, if the output is going to the
745 ** console and if this is running on a Windows machine, and if the -utf8
746 ** option is unavailable or (available and inactive), translate the
747 ** output from UTF-8 into MBCS for output through 8-bit stdout stream.
748 ** (With -utf8 active, no translation is needed and must not be done.)
749 */
750 #if defined(_WIN32) || defined(WIN32)
751 void utf8_printf(FILE *out, const char *zFormat, ...){
752   va_list ap;
753   va_start(ap, zFormat);
754   if( stdout_is_console && (out==stdout || out==stderr)
755 # if SHELL_WIN_UTF8_OPT
756       && !console_utf8
757 # endif
758   ){
759     char *z1 = sqlite3_vmprintf(zFormat, ap);
760     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
761     sqlite3_free(z1);
762     fputs(z2, out);
763     sqlite3_free(z2);
764   }else{
765     vfprintf(out, zFormat, ap);
766   }
767   va_end(ap);
768 }
769 #elif !defined(utf8_printf)
770 # define utf8_printf fprintf
771 #endif
772 
773 /*
774 ** Render output like fprintf().  This should not be used on anything that
775 ** includes string formatting (e.g. "%s").
776 */
777 #if !defined(raw_printf)
778 # define raw_printf fprintf
779 #endif
780 
781 /* Indicate out-of-memory and exit. */
782 static void shell_out_of_memory(void){
783   raw_printf(stderr,"Error: out of memory\n");
784   exit(1);
785 }
786 
787 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
788 ** out-of-memory error.
789 */
790 static void shell_check_oom(const void *p){
791   if( p==0 ) shell_out_of_memory();
792 }
793 
794 /*
795 ** Write I/O traces to the following stream.
796 */
797 #ifdef SQLITE_ENABLE_IOTRACE
798 static FILE *iotrace = 0;
799 #endif
800 
801 /*
802 ** This routine works like printf in that its first argument is a
803 ** format string and subsequent arguments are values to be substituted
804 ** in place of % fields.  The result of formatting this string
805 ** is written to iotrace.
806 */
807 #ifdef SQLITE_ENABLE_IOTRACE
808 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
809   va_list ap;
810   char *z;
811   if( iotrace==0 ) return;
812   va_start(ap, zFormat);
813   z = sqlite3_vmprintf(zFormat, ap);
814   va_end(ap);
815   utf8_printf(iotrace, "%s", z);
816   sqlite3_free(z);
817 }
818 #endif
819 
820 /*
821 ** Output string zUtf to stream pOut as w characters.  If w is negative,
822 ** then right-justify the text.  W is the width in UTF-8 characters, not
823 ** in bytes.  This is different from the %*.*s specification in printf
824 ** since with %*.*s the width is measured in bytes, not characters.
825 */
826 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
827   int i;
828   int n;
829   int aw = w<0 ? -w : w;
830   if( zUtf==0 ) zUtf = "";
831   for(i=n=0; zUtf[i]; i++){
832     if( (zUtf[i]&0xc0)!=0x80 ){
833       n++;
834       if( n==aw ){
835         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
836         break;
837       }
838     }
839   }
840   if( n>=aw ){
841     utf8_printf(pOut, "%.*s", i, zUtf);
842   }else if( w<0 ){
843     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
844   }else{
845     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
846   }
847 }
848 
849 
850 /*
851 ** Determines if a string is a number of not.
852 */
853 static int isNumber(const char *z, int *realnum){
854   if( *z=='-' || *z=='+' ) z++;
855   if( !IsDigit(*z) ){
856     return 0;
857   }
858   z++;
859   if( realnum ) *realnum = 0;
860   while( IsDigit(*z) ){ z++; }
861   if( *z=='.' ){
862     z++;
863     if( !IsDigit(*z) ) return 0;
864     while( IsDigit(*z) ){ z++; }
865     if( realnum ) *realnum = 1;
866   }
867   if( *z=='e' || *z=='E' ){
868     z++;
869     if( *z=='+' || *z=='-' ) z++;
870     if( !IsDigit(*z) ) return 0;
871     while( IsDigit(*z) ){ z++; }
872     if( realnum ) *realnum = 1;
873   }
874   return *z==0;
875 }
876 
877 /*
878 ** Compute a string length that is limited to what can be stored in
879 ** lower 30 bits of a 32-bit signed integer.
880 */
881 static int strlen30(const char *z){
882   const char *z2 = z;
883   while( *z2 ){ z2++; }
884   return 0x3fffffff & (int)(z2 - z);
885 }
886 
887 /*
888 ** Return the length of a string in characters.  Multibyte UTF8 characters
889 ** count as a single character.
890 */
891 static int strlenChar(const char *z){
892   int n = 0;
893   while( *z ){
894     if( (0xc0&*(z++))!=0x80 ) n++;
895   }
896   return n;
897 }
898 
899 /*
900 ** Return open FILE * if zFile exists, can be opened for read
901 ** and is an ordinary file or a character stream source.
902 ** Otherwise return 0.
903 */
904 static FILE * openChrSource(const char *zFile){
905 #ifdef _WIN32
906   struct _stat x = {0};
907 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
908   /* On Windows, open first, then check the stream nature. This order
909   ** is necessary because _stat() and sibs, when checking a named pipe,
910   ** effectively break the pipe as its supplier sees it. */
911   FILE *rv = fopen(zFile, "rb");
912   if( rv==0 ) return 0;
913   if( _fstat(_fileno(rv), &x) != 0
914       || !STAT_CHR_SRC(x.st_mode)){
915     fclose(rv);
916     rv = 0;
917   }
918   return rv;
919 #else
920   struct stat x = {0};
921   int rc = stat(zFile, &x);
922 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
923   if( rc!=0 ) return 0;
924   if( STAT_CHR_SRC(x.st_mode) ){
925     return fopen(zFile, "rb");
926   }else{
927     return 0;
928   }
929 #endif
930 #undef STAT_CHR_SRC
931 }
932 
933 /*
934 ** This routine reads a line of text from FILE in, stores
935 ** the text in memory obtained from malloc() and returns a pointer
936 ** to the text.  NULL is returned at end of file, or if malloc()
937 ** fails.
938 **
939 ** If zLine is not NULL then it is a malloced buffer returned from
940 ** a previous call to this routine that may be reused.
941 */
942 static char *local_getline(char *zLine, FILE *in){
943   int nLine = zLine==0 ? 0 : 100;
944   int n = 0;
945 
946   while( 1 ){
947     if( n+100>nLine ){
948       nLine = nLine*2 + 100;
949       zLine = realloc(zLine, nLine);
950       shell_check_oom(zLine);
951     }
952     if( fgets(&zLine[n], nLine - n, in)==0 ){
953       if( n==0 ){
954         free(zLine);
955         return 0;
956       }
957       zLine[n] = 0;
958       break;
959     }
960     while( zLine[n] ) n++;
961     if( n>0 && zLine[n-1]=='\n' ){
962       n--;
963       if( n>0 && zLine[n-1]=='\r' ) n--;
964       zLine[n] = 0;
965       break;
966     }
967   }
968 #if defined(_WIN32) || defined(WIN32)
969   /* For interactive input on Windows systems, without -utf8,
970   ** translate the multi-byte characterset characters into UTF-8.
971   ** This is the translation that predates the -utf8 option. */
972   if( stdin_is_interactive && in==stdin
973 # if SHELL_WIN_UTF8_OPT
974       && !console_utf8
975 # endif /* SHELL_WIN_UTF8_OPT */
976   ){
977     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
978     if( zTrans ){
979       i64 nTrans = strlen(zTrans)+1;
980       if( nTrans>nLine ){
981         zLine = realloc(zLine, nTrans);
982         shell_check_oom(zLine);
983       }
984       memcpy(zLine, zTrans, nTrans);
985       sqlite3_free(zTrans);
986     }
987   }
988 #endif /* defined(_WIN32) || defined(WIN32) */
989   return zLine;
990 }
991 
992 /*
993 ** Retrieve a single line of input text.
994 **
995 ** If in==0 then read from standard input and prompt before each line.
996 ** If isContinuation is true, then a continuation prompt is appropriate.
997 ** If isContinuation is zero, then the main prompt should be used.
998 **
999 ** If zPrior is not NULL then it is a buffer from a prior call to this
1000 ** routine that can be reused.
1001 **
1002 ** The result is stored in space obtained from malloc() and must either
1003 ** be freed by the caller or else passed back into this routine via the
1004 ** zPrior argument for reuse.
1005 */
1006 #ifndef SQLITE_SHELL_FIDDLE
1007 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1008   char *zPrompt;
1009   char *zResult;
1010   if( in!=0 ){
1011     zResult = local_getline(zPrior, in);
1012   }else{
1013     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1014 #if SHELL_USE_LOCAL_GETLINE
1015     printf("%s", zPrompt);
1016     fflush(stdout);
1017     do{
1018       zResult = local_getline(zPrior, stdin);
1019       zPrior = 0;
1020       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1021       if( zResult==0 ) sqlite3_sleep(50);
1022     }while( zResult==0 && seenInterrupt>0 );
1023 #else
1024     free(zPrior);
1025     zResult = shell_readline(zPrompt);
1026     while( zResult==0 ){
1027       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1028       sqlite3_sleep(50);
1029       if( seenInterrupt==0 ) break;
1030       zResult = shell_readline("");
1031     }
1032     if( zResult && *zResult ) shell_add_history(zResult);
1033 #endif
1034   }
1035   return zResult;
1036 }
1037 #endif /* !SQLITE_SHELL_FIDDLE */
1038 
1039 /*
1040 ** Return the value of a hexadecimal digit.  Return -1 if the input
1041 ** is not a hex digit.
1042 */
1043 static int hexDigitValue(char c){
1044   if( c>='0' && c<='9' ) return c - '0';
1045   if( c>='a' && c<='f' ) return c - 'a' + 10;
1046   if( c>='A' && c<='F' ) return c - 'A' + 10;
1047   return -1;
1048 }
1049 
1050 /*
1051 ** Interpret zArg as an integer value, possibly with suffixes.
1052 */
1053 static sqlite3_int64 integerValue(const char *zArg){
1054   sqlite3_int64 v = 0;
1055   static const struct { char *zSuffix; int iMult; } aMult[] = {
1056     { "KiB", 1024 },
1057     { "MiB", 1024*1024 },
1058     { "GiB", 1024*1024*1024 },
1059     { "KB",  1000 },
1060     { "MB",  1000000 },
1061     { "GB",  1000000000 },
1062     { "K",   1000 },
1063     { "M",   1000000 },
1064     { "G",   1000000000 },
1065   };
1066   int i;
1067   int isNeg = 0;
1068   if( zArg[0]=='-' ){
1069     isNeg = 1;
1070     zArg++;
1071   }else if( zArg[0]=='+' ){
1072     zArg++;
1073   }
1074   if( zArg[0]=='0' && zArg[1]=='x' ){
1075     int x;
1076     zArg += 2;
1077     while( (x = hexDigitValue(zArg[0]))>=0 ){
1078       v = (v<<4) + x;
1079       zArg++;
1080     }
1081   }else{
1082     while( IsDigit(zArg[0]) ){
1083       v = v*10 + zArg[0] - '0';
1084       zArg++;
1085     }
1086   }
1087   for(i=0; i<ArraySize(aMult); i++){
1088     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1089       v *= aMult[i].iMult;
1090       break;
1091     }
1092   }
1093   return isNeg? -v : v;
1094 }
1095 
1096 /*
1097 ** A variable length string to which one can append text.
1098 */
1099 typedef struct ShellText ShellText;
1100 struct ShellText {
1101   char *z;
1102   int n;
1103   int nAlloc;
1104 };
1105 
1106 /*
1107 ** Initialize and destroy a ShellText object
1108 */
1109 static void initText(ShellText *p){
1110   memset(p, 0, sizeof(*p));
1111 }
1112 static void freeText(ShellText *p){
1113   free(p->z);
1114   initText(p);
1115 }
1116 
1117 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1118 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1119 ** added to zIn, and the result returned in memory obtained from malloc().
1120 ** zIn, if it was not NULL, is freed.
1121 **
1122 ** If the third argument, quote, is not '\0', then it is used as a
1123 ** quote character for zAppend.
1124 */
1125 static void appendText(ShellText *p, const char *zAppend, char quote){
1126   i64 len;
1127   i64 i;
1128   i64 nAppend = strlen30(zAppend);
1129 
1130   len = nAppend+p->n+1;
1131   if( quote ){
1132     len += 2;
1133     for(i=0; i<nAppend; i++){
1134       if( zAppend[i]==quote ) len++;
1135     }
1136   }
1137 
1138   if( p->z==0 || p->n+len>=p->nAlloc ){
1139     p->nAlloc = p->nAlloc*2 + len + 20;
1140     p->z = realloc(p->z, p->nAlloc);
1141     shell_check_oom(p->z);
1142   }
1143 
1144   if( quote ){
1145     char *zCsr = p->z+p->n;
1146     *zCsr++ = quote;
1147     for(i=0; i<nAppend; i++){
1148       *zCsr++ = zAppend[i];
1149       if( zAppend[i]==quote ) *zCsr++ = quote;
1150     }
1151     *zCsr++ = quote;
1152     p->n = (int)(zCsr - p->z);
1153     *zCsr = '\0';
1154   }else{
1155     memcpy(p->z+p->n, zAppend, nAppend);
1156     p->n += nAppend;
1157     p->z[p->n] = '\0';
1158   }
1159 }
1160 
1161 /*
1162 ** Attempt to determine if identifier zName needs to be quoted, either
1163 ** because it contains non-alphanumeric characters, or because it is an
1164 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1165 ** that quoting is required.
1166 **
1167 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1168 */
1169 static char quoteChar(const char *zName){
1170   int i;
1171   if( zName==0 ) return '"';
1172   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1173   for(i=0; zName[i]; i++){
1174     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1175   }
1176   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1177 }
1178 
1179 /*
1180 ** Construct a fake object name and column list to describe the structure
1181 ** of the view, virtual table, or table valued function zSchema.zName.
1182 */
1183 static char *shellFakeSchema(
1184   sqlite3 *db,            /* The database connection containing the vtab */
1185   const char *zSchema,    /* Schema of the database holding the vtab */
1186   const char *zName       /* The name of the virtual table */
1187 ){
1188   sqlite3_stmt *pStmt = 0;
1189   char *zSql;
1190   ShellText s;
1191   char cQuote;
1192   char *zDiv = "(";
1193   int nRow = 0;
1194 
1195   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1196                          zSchema ? zSchema : "main", zName);
1197   shell_check_oom(zSql);
1198   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1199   sqlite3_free(zSql);
1200   initText(&s);
1201   if( zSchema ){
1202     cQuote = quoteChar(zSchema);
1203     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1204     appendText(&s, zSchema, cQuote);
1205     appendText(&s, ".", 0);
1206   }
1207   cQuote = quoteChar(zName);
1208   appendText(&s, zName, cQuote);
1209   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1210     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1211     nRow++;
1212     appendText(&s, zDiv, 0);
1213     zDiv = ",";
1214     if( zCol==0 ) zCol = "";
1215     cQuote = quoteChar(zCol);
1216     appendText(&s, zCol, cQuote);
1217   }
1218   appendText(&s, ")", 0);
1219   sqlite3_finalize(pStmt);
1220   if( nRow==0 ){
1221     freeText(&s);
1222     s.z = 0;
1223   }
1224   return s.z;
1225 }
1226 
1227 /*
1228 ** SQL function:  shell_module_schema(X)
1229 **
1230 ** Return a fake schema for the table-valued function or eponymous virtual
1231 ** table X.
1232 */
1233 static void shellModuleSchema(
1234   sqlite3_context *pCtx,
1235   int nVal,
1236   sqlite3_value **apVal
1237 ){
1238   const char *zName;
1239   char *zFake;
1240   UNUSED_PARAMETER(nVal);
1241   zName = (const char*)sqlite3_value_text(apVal[0]);
1242   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1243   if( zFake ){
1244     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1245                         -1, sqlite3_free);
1246     free(zFake);
1247   }
1248 }
1249 
1250 /*
1251 ** SQL function:  shell_add_schema(S,X)
1252 **
1253 ** Add the schema name X to the CREATE statement in S and return the result.
1254 ** Examples:
1255 **
1256 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
1257 **
1258 ** Also works on
1259 **
1260 **    CREATE INDEX
1261 **    CREATE UNIQUE INDEX
1262 **    CREATE VIEW
1263 **    CREATE TRIGGER
1264 **    CREATE VIRTUAL TABLE
1265 **
1266 ** This UDF is used by the .schema command to insert the schema name of
1267 ** attached databases into the middle of the sqlite_schema.sql field.
1268 */
1269 static void shellAddSchemaName(
1270   sqlite3_context *pCtx,
1271   int nVal,
1272   sqlite3_value **apVal
1273 ){
1274   static const char *aPrefix[] = {
1275      "TABLE",
1276      "INDEX",
1277      "UNIQUE INDEX",
1278      "VIEW",
1279      "TRIGGER",
1280      "VIRTUAL TABLE"
1281   };
1282   int i = 0;
1283   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1284   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1285   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1286   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1287   UNUSED_PARAMETER(nVal);
1288   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1289     for(i=0; i<ArraySize(aPrefix); i++){
1290       int n = strlen30(aPrefix[i]);
1291       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1292         char *z = 0;
1293         char *zFake = 0;
1294         if( zSchema ){
1295           char cQuote = quoteChar(zSchema);
1296           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1297             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1298           }else{
1299             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1300           }
1301         }
1302         if( zName
1303          && aPrefix[i][0]=='V'
1304          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1305         ){
1306           if( z==0 ){
1307             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1308           }else{
1309             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1310           }
1311           free(zFake);
1312         }
1313         if( z ){
1314           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1315           return;
1316         }
1317       }
1318     }
1319   }
1320   sqlite3_result_value(pCtx, apVal[0]);
1321 }
1322 
1323 /*
1324 ** The source code for several run-time loadable extensions is inserted
1325 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1326 ** code, we need to override some macros to make the included program code
1327 ** work here in the middle of this regular program.
1328 */
1329 #define SQLITE_EXTENSION_INIT1
1330 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1331 
1332 #if defined(_WIN32) && defined(_MSC_VER)
1333 /************************* Begin test_windirent.h ******************/
1334 /*
1335 ** 2015 November 30
1336 **
1337 ** The author disclaims copyright to this source code.  In place of
1338 ** a legal notice, here is a blessing:
1339 **
1340 **    May you do good and not evil.
1341 **    May you find forgiveness for yourself and forgive others.
1342 **    May you share freely, never taking more than you give.
1343 **
1344 *************************************************************************
1345 ** This file contains declarations for most of the opendir() family of
1346 ** POSIX functions on Win32 using the MSVCRT.
1347 */
1348 
1349 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1350 #define SQLITE_WINDIRENT_H
1351 
1352 /*
1353 ** We need several data types from the Windows SDK header.
1354 */
1355 
1356 #ifndef WIN32_LEAN_AND_MEAN
1357 #define WIN32_LEAN_AND_MEAN
1358 #endif
1359 
1360 #include "windows.h"
1361 
1362 /*
1363 ** We need several support functions from the SQLite core.
1364 */
1365 
1366 /* #include "sqlite3.h" */
1367 
1368 /*
1369 ** We need several things from the ANSI and MSVCRT headers.
1370 */
1371 
1372 #include <stdio.h>
1373 #include <stdlib.h>
1374 #include <errno.h>
1375 #include <io.h>
1376 #include <limits.h>
1377 #include <sys/types.h>
1378 #include <sys/stat.h>
1379 
1380 /*
1381 ** We may need several defines that should have been in "sys/stat.h".
1382 */
1383 
1384 #ifndef S_ISREG
1385 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1386 #endif
1387 
1388 #ifndef S_ISDIR
1389 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1390 #endif
1391 
1392 #ifndef S_ISLNK
1393 #define S_ISLNK(mode) (0)
1394 #endif
1395 
1396 /*
1397 ** We may need to provide the "mode_t" type.
1398 */
1399 
1400 #ifndef MODE_T_DEFINED
1401   #define MODE_T_DEFINED
1402   typedef unsigned short mode_t;
1403 #endif
1404 
1405 /*
1406 ** We may need to provide the "ino_t" type.
1407 */
1408 
1409 #ifndef INO_T_DEFINED
1410   #define INO_T_DEFINED
1411   typedef unsigned short ino_t;
1412 #endif
1413 
1414 /*
1415 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1416 */
1417 
1418 #ifndef NAME_MAX
1419 #  ifdef FILENAME_MAX
1420 #    define NAME_MAX (FILENAME_MAX)
1421 #  else
1422 #    define NAME_MAX (260)
1423 #  endif
1424 #endif
1425 
1426 /*
1427 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1428 */
1429 
1430 #ifndef NULL_INTPTR_T
1431 #  define NULL_INTPTR_T ((intptr_t)(0))
1432 #endif
1433 
1434 #ifndef BAD_INTPTR_T
1435 #  define BAD_INTPTR_T ((intptr_t)(-1))
1436 #endif
1437 
1438 /*
1439 ** We need to provide the necessary structures and related types.
1440 */
1441 
1442 #ifndef DIRENT_DEFINED
1443 #define DIRENT_DEFINED
1444 typedef struct DIRENT DIRENT;
1445 typedef DIRENT *LPDIRENT;
1446 struct DIRENT {
1447   ino_t d_ino;               /* Sequence number, do not use. */
1448   unsigned d_attributes;     /* Win32 file attributes. */
1449   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1450 };
1451 #endif
1452 
1453 #ifndef DIR_DEFINED
1454 #define DIR_DEFINED
1455 typedef struct DIR DIR;
1456 typedef DIR *LPDIR;
1457 struct DIR {
1458   intptr_t d_handle; /* Value returned by "_findfirst". */
1459   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1460   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1461 };
1462 #endif
1463 
1464 /*
1465 ** Provide a macro, for use by the implementation, to determine if a
1466 ** particular directory entry should be skipped over when searching for
1467 ** the next directory entry that should be returned by the readdir() or
1468 ** readdir_r() functions.
1469 */
1470 
1471 #ifndef is_filtered
1472 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1473 #endif
1474 
1475 /*
1476 ** Provide the function prototype for the POSIX compatiable getenv()
1477 ** function.  This function is not thread-safe.
1478 */
1479 
1480 extern const char *windirent_getenv(const char *name);
1481 
1482 /*
1483 ** Finally, we can provide the function prototypes for the opendir(),
1484 ** readdir(), readdir_r(), and closedir() POSIX functions.
1485 */
1486 
1487 extern LPDIR opendir(const char *dirname);
1488 extern LPDIRENT readdir(LPDIR dirp);
1489 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1490 extern INT closedir(LPDIR dirp);
1491 
1492 #endif /* defined(WIN32) && defined(_MSC_VER) */
1493 
1494 /************************* End test_windirent.h ********************/
1495 /************************* Begin test_windirent.c ******************/
1496 /*
1497 ** 2015 November 30
1498 **
1499 ** The author disclaims copyright to this source code.  In place of
1500 ** a legal notice, here is a blessing:
1501 **
1502 **    May you do good and not evil.
1503 **    May you find forgiveness for yourself and forgive others.
1504 **    May you share freely, never taking more than you give.
1505 **
1506 *************************************************************************
1507 ** This file contains code to implement most of the opendir() family of
1508 ** POSIX functions on Win32 using the MSVCRT.
1509 */
1510 
1511 #if defined(_WIN32) && defined(_MSC_VER)
1512 /* #include "test_windirent.h" */
1513 
1514 /*
1515 ** Implementation of the POSIX getenv() function using the Win32 API.
1516 ** This function is not thread-safe.
1517 */
1518 const char *windirent_getenv(
1519   const char *name
1520 ){
1521   static char value[32768]; /* Maximum length, per MSDN */
1522   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1523   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1524 
1525   memset(value, 0, sizeof(value));
1526   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1527   if( dwRet==0 || dwRet>dwSize ){
1528     /*
1529     ** The function call to GetEnvironmentVariableA() failed -OR-
1530     ** the buffer is not large enough.  Either way, return NULL.
1531     */
1532     return 0;
1533   }else{
1534     /*
1535     ** The function call to GetEnvironmentVariableA() succeeded
1536     ** -AND- the buffer contains the entire value.
1537     */
1538     return value;
1539   }
1540 }
1541 
1542 /*
1543 ** Implementation of the POSIX opendir() function using the MSVCRT.
1544 */
1545 LPDIR opendir(
1546   const char *dirname
1547 ){
1548   struct _finddata_t data;
1549   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1550   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1551 
1552   if( dirp==NULL ) return NULL;
1553   memset(dirp, 0, sizeof(DIR));
1554 
1555   /* TODO: Remove this if Unix-style root paths are not used. */
1556   if( sqlite3_stricmp(dirname, "/")==0 ){
1557     dirname = windirent_getenv("SystemDrive");
1558   }
1559 
1560   memset(&data, 0, sizeof(struct _finddata_t));
1561   _snprintf(data.name, namesize, "%s\\*", dirname);
1562   dirp->d_handle = _findfirst(data.name, &data);
1563 
1564   if( dirp->d_handle==BAD_INTPTR_T ){
1565     closedir(dirp);
1566     return NULL;
1567   }
1568 
1569   /* TODO: Remove this block to allow hidden and/or system files. */
1570   if( is_filtered(data) ){
1571 next:
1572 
1573     memset(&data, 0, sizeof(struct _finddata_t));
1574     if( _findnext(dirp->d_handle, &data)==-1 ){
1575       closedir(dirp);
1576       return NULL;
1577     }
1578 
1579     /* TODO: Remove this block to allow hidden and/or system files. */
1580     if( is_filtered(data) ) goto next;
1581   }
1582 
1583   dirp->d_first.d_attributes = data.attrib;
1584   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1585   dirp->d_first.d_name[NAME_MAX] = '\0';
1586 
1587   return dirp;
1588 }
1589 
1590 /*
1591 ** Implementation of the POSIX readdir() function using the MSVCRT.
1592 */
1593 LPDIRENT readdir(
1594   LPDIR dirp
1595 ){
1596   struct _finddata_t data;
1597 
1598   if( dirp==NULL ) return NULL;
1599 
1600   if( dirp->d_first.d_ino==0 ){
1601     dirp->d_first.d_ino++;
1602     dirp->d_next.d_ino++;
1603 
1604     return &dirp->d_first;
1605   }
1606 
1607 next:
1608 
1609   memset(&data, 0, sizeof(struct _finddata_t));
1610   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1611 
1612   /* TODO: Remove this block to allow hidden and/or system files. */
1613   if( is_filtered(data) ) goto next;
1614 
1615   dirp->d_next.d_ino++;
1616   dirp->d_next.d_attributes = data.attrib;
1617   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1618   dirp->d_next.d_name[NAME_MAX] = '\0';
1619 
1620   return &dirp->d_next;
1621 }
1622 
1623 /*
1624 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1625 */
1626 INT readdir_r(
1627   LPDIR dirp,
1628   LPDIRENT entry,
1629   LPDIRENT *result
1630 ){
1631   struct _finddata_t data;
1632 
1633   if( dirp==NULL ) return EBADF;
1634 
1635   if( dirp->d_first.d_ino==0 ){
1636     dirp->d_first.d_ino++;
1637     dirp->d_next.d_ino++;
1638 
1639     entry->d_ino = dirp->d_first.d_ino;
1640     entry->d_attributes = dirp->d_first.d_attributes;
1641     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1642     entry->d_name[NAME_MAX] = '\0';
1643 
1644     *result = entry;
1645     return 0;
1646   }
1647 
1648 next:
1649 
1650   memset(&data, 0, sizeof(struct _finddata_t));
1651   if( _findnext(dirp->d_handle, &data)==-1 ){
1652     *result = NULL;
1653     return ENOENT;
1654   }
1655 
1656   /* TODO: Remove this block to allow hidden and/or system files. */
1657   if( is_filtered(data) ) goto next;
1658 
1659   entry->d_ino = (ino_t)-1; /* not available */
1660   entry->d_attributes = data.attrib;
1661   strncpy(entry->d_name, data.name, NAME_MAX);
1662   entry->d_name[NAME_MAX] = '\0';
1663 
1664   *result = entry;
1665   return 0;
1666 }
1667 
1668 /*
1669 ** Implementation of the POSIX closedir() function using the MSVCRT.
1670 */
1671 INT closedir(
1672   LPDIR dirp
1673 ){
1674   INT result = 0;
1675 
1676   if( dirp==NULL ) return EINVAL;
1677 
1678   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1679     result = _findclose(dirp->d_handle);
1680   }
1681 
1682   sqlite3_free(dirp);
1683   return result;
1684 }
1685 
1686 #endif /* defined(WIN32) && defined(_MSC_VER) */
1687 
1688 /************************* End test_windirent.c ********************/
1689 #define dirent DIRENT
1690 #endif
1691 /************************* Begin ../ext/misc/memtrace.c ******************/
1692 /*
1693 ** 2019-01-21
1694 **
1695 ** The author disclaims copyright to this source code.  In place of
1696 ** a legal notice, here is a blessing:
1697 **
1698 **    May you do good and not evil.
1699 **    May you find forgiveness for yourself and forgive others.
1700 **    May you share freely, never taking more than you give.
1701 **
1702 *************************************************************************
1703 **
1704 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
1705 ** mechanism to add a tracing layer on top of SQLite.  If this extension
1706 ** is registered prior to sqlite3_initialize(), it will cause all memory
1707 ** allocation activities to be logged on standard output, or to some other
1708 ** FILE specified by the initializer.
1709 **
1710 ** This file needs to be compiled into the application that uses it.
1711 **
1712 ** This extension is used to implement the --memtrace option of the
1713 ** command-line shell.
1714 */
1715 #include <assert.h>
1716 #include <string.h>
1717 #include <stdio.h>
1718 
1719 /* The original memory allocation routines */
1720 static sqlite3_mem_methods memtraceBase;
1721 static FILE *memtraceOut;
1722 
1723 /* Methods that trace memory allocations */
1724 static void *memtraceMalloc(int n){
1725   if( memtraceOut ){
1726     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
1727             memtraceBase.xRoundup(n));
1728   }
1729   return memtraceBase.xMalloc(n);
1730 }
1731 static void memtraceFree(void *p){
1732   if( p==0 ) return;
1733   if( memtraceOut ){
1734     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
1735   }
1736   memtraceBase.xFree(p);
1737 }
1738 static void *memtraceRealloc(void *p, int n){
1739   if( p==0 ) return memtraceMalloc(n);
1740   if( n==0 ){
1741     memtraceFree(p);
1742     return 0;
1743   }
1744   if( memtraceOut ){
1745     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
1746             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
1747   }
1748   return memtraceBase.xRealloc(p, n);
1749 }
1750 static int memtraceSize(void *p){
1751   return memtraceBase.xSize(p);
1752 }
1753 static int memtraceRoundup(int n){
1754   return memtraceBase.xRoundup(n);
1755 }
1756 static int memtraceInit(void *p){
1757   return memtraceBase.xInit(p);
1758 }
1759 static void memtraceShutdown(void *p){
1760   memtraceBase.xShutdown(p);
1761 }
1762 
1763 /* The substitute memory allocator */
1764 static sqlite3_mem_methods ersaztMethods = {
1765   memtraceMalloc,
1766   memtraceFree,
1767   memtraceRealloc,
1768   memtraceSize,
1769   memtraceRoundup,
1770   memtraceInit,
1771   memtraceShutdown,
1772   0
1773 };
1774 
1775 /* Begin tracing memory allocations to out. */
1776 int sqlite3MemTraceActivate(FILE *out){
1777   int rc = SQLITE_OK;
1778   if( memtraceBase.xMalloc==0 ){
1779     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
1780     if( rc==SQLITE_OK ){
1781       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
1782     }
1783   }
1784   memtraceOut = out;
1785   return rc;
1786 }
1787 
1788 /* Deactivate memory tracing */
1789 int sqlite3MemTraceDeactivate(void){
1790   int rc = SQLITE_OK;
1791   if( memtraceBase.xMalloc!=0 ){
1792     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
1793     if( rc==SQLITE_OK ){
1794       memset(&memtraceBase, 0, sizeof(memtraceBase));
1795     }
1796   }
1797   memtraceOut = 0;
1798   return rc;
1799 }
1800 
1801 /************************* End ../ext/misc/memtrace.c ********************/
1802 /************************* Begin ../ext/misc/shathree.c ******************/
1803 /*
1804 ** 2017-03-08
1805 **
1806 ** The author disclaims copyright to this source code.  In place of
1807 ** a legal notice, here is a blessing:
1808 **
1809 **    May you do good and not evil.
1810 **    May you find forgiveness for yourself and forgive others.
1811 **    May you share freely, never taking more than you give.
1812 **
1813 ******************************************************************************
1814 **
1815 ** This SQLite extension implements functions that compute SHA3 hashes
1816 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
1817 ** Two SQL functions are implemented:
1818 **
1819 **     sha3(X,SIZE)
1820 **     sha3_query(Y,SIZE)
1821 **
1822 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1823 ** X is NULL.
1824 **
1825 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
1826 ** and returns a hash of their results.
1827 **
1828 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1829 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1830 ** 384, or 512, to determine SHA3 hash variant that is computed.
1831 */
1832 /* #include "sqlite3ext.h" */
1833 SQLITE_EXTENSION_INIT1
1834 #include <assert.h>
1835 #include <string.h>
1836 #include <stdarg.h>
1837 
1838 #ifndef SQLITE_AMALGAMATION
1839 /* typedef sqlite3_uint64 u64; */
1840 #endif /* SQLITE_AMALGAMATION */
1841 
1842 /******************************************************************************
1843 ** The Hash Engine
1844 */
1845 /*
1846 ** Macros to determine whether the machine is big or little endian,
1847 ** and whether or not that determination is run-time or compile-time.
1848 **
1849 ** For best performance, an attempt is made to guess at the byte-order
1850 ** using C-preprocessor macros.  If that is unsuccessful, or if
1851 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1852 ** at run-time.
1853 */
1854 #ifndef SHA3_BYTEORDER
1855 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1856      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1857      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1858      defined(__arm__)
1859 #   define SHA3_BYTEORDER    1234
1860 # elif defined(sparc)    || defined(__ppc__)
1861 #   define SHA3_BYTEORDER    4321
1862 # else
1863 #   define SHA3_BYTEORDER 0
1864 # endif
1865 #endif
1866 
1867 
1868 /*
1869 ** State structure for a SHA3 hash in progress
1870 */
1871 typedef struct SHA3Context SHA3Context;
1872 struct SHA3Context {
1873   union {
1874     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1875     unsigned char x[1600];    /* ... or 1600 bytes */
1876   } u;
1877   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1878   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1879   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1880 };
1881 
1882 /*
1883 ** A single step of the Keccak mixing function for a 1600-bit state
1884 */
1885 static void KeccakF1600Step(SHA3Context *p){
1886   int i;
1887   u64 b0, b1, b2, b3, b4;
1888   u64 c0, c1, c2, c3, c4;
1889   u64 d0, d1, d2, d3, d4;
1890   static const u64 RC[] = {
1891     0x0000000000000001ULL,  0x0000000000008082ULL,
1892     0x800000000000808aULL,  0x8000000080008000ULL,
1893     0x000000000000808bULL,  0x0000000080000001ULL,
1894     0x8000000080008081ULL,  0x8000000000008009ULL,
1895     0x000000000000008aULL,  0x0000000000000088ULL,
1896     0x0000000080008009ULL,  0x000000008000000aULL,
1897     0x000000008000808bULL,  0x800000000000008bULL,
1898     0x8000000000008089ULL,  0x8000000000008003ULL,
1899     0x8000000000008002ULL,  0x8000000000000080ULL,
1900     0x000000000000800aULL,  0x800000008000000aULL,
1901     0x8000000080008081ULL,  0x8000000000008080ULL,
1902     0x0000000080000001ULL,  0x8000000080008008ULL
1903   };
1904 # define a00 (p->u.s[0])
1905 # define a01 (p->u.s[1])
1906 # define a02 (p->u.s[2])
1907 # define a03 (p->u.s[3])
1908 # define a04 (p->u.s[4])
1909 # define a10 (p->u.s[5])
1910 # define a11 (p->u.s[6])
1911 # define a12 (p->u.s[7])
1912 # define a13 (p->u.s[8])
1913 # define a14 (p->u.s[9])
1914 # define a20 (p->u.s[10])
1915 # define a21 (p->u.s[11])
1916 # define a22 (p->u.s[12])
1917 # define a23 (p->u.s[13])
1918 # define a24 (p->u.s[14])
1919 # define a30 (p->u.s[15])
1920 # define a31 (p->u.s[16])
1921 # define a32 (p->u.s[17])
1922 # define a33 (p->u.s[18])
1923 # define a34 (p->u.s[19])
1924 # define a40 (p->u.s[20])
1925 # define a41 (p->u.s[21])
1926 # define a42 (p->u.s[22])
1927 # define a43 (p->u.s[23])
1928 # define a44 (p->u.s[24])
1929 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1930 
1931   for(i=0; i<24; i+=4){
1932     c0 = a00^a10^a20^a30^a40;
1933     c1 = a01^a11^a21^a31^a41;
1934     c2 = a02^a12^a22^a32^a42;
1935     c3 = a03^a13^a23^a33^a43;
1936     c4 = a04^a14^a24^a34^a44;
1937     d0 = c4^ROL64(c1, 1);
1938     d1 = c0^ROL64(c2, 1);
1939     d2 = c1^ROL64(c3, 1);
1940     d3 = c2^ROL64(c4, 1);
1941     d4 = c3^ROL64(c0, 1);
1942 
1943     b0 = (a00^d0);
1944     b1 = ROL64((a11^d1), 44);
1945     b2 = ROL64((a22^d2), 43);
1946     b3 = ROL64((a33^d3), 21);
1947     b4 = ROL64((a44^d4), 14);
1948     a00 =   b0 ^((~b1)&  b2 );
1949     a00 ^= RC[i];
1950     a11 =   b1 ^((~b2)&  b3 );
1951     a22 =   b2 ^((~b3)&  b4 );
1952     a33 =   b3 ^((~b4)&  b0 );
1953     a44 =   b4 ^((~b0)&  b1 );
1954 
1955     b2 = ROL64((a20^d0), 3);
1956     b3 = ROL64((a31^d1), 45);
1957     b4 = ROL64((a42^d2), 61);
1958     b0 = ROL64((a03^d3), 28);
1959     b1 = ROL64((a14^d4), 20);
1960     a20 =   b0 ^((~b1)&  b2 );
1961     a31 =   b1 ^((~b2)&  b3 );
1962     a42 =   b2 ^((~b3)&  b4 );
1963     a03 =   b3 ^((~b4)&  b0 );
1964     a14 =   b4 ^((~b0)&  b1 );
1965 
1966     b4 = ROL64((a40^d0), 18);
1967     b0 = ROL64((a01^d1), 1);
1968     b1 = ROL64((a12^d2), 6);
1969     b2 = ROL64((a23^d3), 25);
1970     b3 = ROL64((a34^d4), 8);
1971     a40 =   b0 ^((~b1)&  b2 );
1972     a01 =   b1 ^((~b2)&  b3 );
1973     a12 =   b2 ^((~b3)&  b4 );
1974     a23 =   b3 ^((~b4)&  b0 );
1975     a34 =   b4 ^((~b0)&  b1 );
1976 
1977     b1 = ROL64((a10^d0), 36);
1978     b2 = ROL64((a21^d1), 10);
1979     b3 = ROL64((a32^d2), 15);
1980     b4 = ROL64((a43^d3), 56);
1981     b0 = ROL64((a04^d4), 27);
1982     a10 =   b0 ^((~b1)&  b2 );
1983     a21 =   b1 ^((~b2)&  b3 );
1984     a32 =   b2 ^((~b3)&  b4 );
1985     a43 =   b3 ^((~b4)&  b0 );
1986     a04 =   b4 ^((~b0)&  b1 );
1987 
1988     b3 = ROL64((a30^d0), 41);
1989     b4 = ROL64((a41^d1), 2);
1990     b0 = ROL64((a02^d2), 62);
1991     b1 = ROL64((a13^d3), 55);
1992     b2 = ROL64((a24^d4), 39);
1993     a30 =   b0 ^((~b1)&  b2 );
1994     a41 =   b1 ^((~b2)&  b3 );
1995     a02 =   b2 ^((~b3)&  b4 );
1996     a13 =   b3 ^((~b4)&  b0 );
1997     a24 =   b4 ^((~b0)&  b1 );
1998 
1999     c0 = a00^a20^a40^a10^a30;
2000     c1 = a11^a31^a01^a21^a41;
2001     c2 = a22^a42^a12^a32^a02;
2002     c3 = a33^a03^a23^a43^a13;
2003     c4 = a44^a14^a34^a04^a24;
2004     d0 = c4^ROL64(c1, 1);
2005     d1 = c0^ROL64(c2, 1);
2006     d2 = c1^ROL64(c3, 1);
2007     d3 = c2^ROL64(c4, 1);
2008     d4 = c3^ROL64(c0, 1);
2009 
2010     b0 = (a00^d0);
2011     b1 = ROL64((a31^d1), 44);
2012     b2 = ROL64((a12^d2), 43);
2013     b3 = ROL64((a43^d3), 21);
2014     b4 = ROL64((a24^d4), 14);
2015     a00 =   b0 ^((~b1)&  b2 );
2016     a00 ^= RC[i+1];
2017     a31 =   b1 ^((~b2)&  b3 );
2018     a12 =   b2 ^((~b3)&  b4 );
2019     a43 =   b3 ^((~b4)&  b0 );
2020     a24 =   b4 ^((~b0)&  b1 );
2021 
2022     b2 = ROL64((a40^d0), 3);
2023     b3 = ROL64((a21^d1), 45);
2024     b4 = ROL64((a02^d2), 61);
2025     b0 = ROL64((a33^d3), 28);
2026     b1 = ROL64((a14^d4), 20);
2027     a40 =   b0 ^((~b1)&  b2 );
2028     a21 =   b1 ^((~b2)&  b3 );
2029     a02 =   b2 ^((~b3)&  b4 );
2030     a33 =   b3 ^((~b4)&  b0 );
2031     a14 =   b4 ^((~b0)&  b1 );
2032 
2033     b4 = ROL64((a30^d0), 18);
2034     b0 = ROL64((a11^d1), 1);
2035     b1 = ROL64((a42^d2), 6);
2036     b2 = ROL64((a23^d3), 25);
2037     b3 = ROL64((a04^d4), 8);
2038     a30 =   b0 ^((~b1)&  b2 );
2039     a11 =   b1 ^((~b2)&  b3 );
2040     a42 =   b2 ^((~b3)&  b4 );
2041     a23 =   b3 ^((~b4)&  b0 );
2042     a04 =   b4 ^((~b0)&  b1 );
2043 
2044     b1 = ROL64((a20^d0), 36);
2045     b2 = ROL64((a01^d1), 10);
2046     b3 = ROL64((a32^d2), 15);
2047     b4 = ROL64((a13^d3), 56);
2048     b0 = ROL64((a44^d4), 27);
2049     a20 =   b0 ^((~b1)&  b2 );
2050     a01 =   b1 ^((~b2)&  b3 );
2051     a32 =   b2 ^((~b3)&  b4 );
2052     a13 =   b3 ^((~b4)&  b0 );
2053     a44 =   b4 ^((~b0)&  b1 );
2054 
2055     b3 = ROL64((a10^d0), 41);
2056     b4 = ROL64((a41^d1), 2);
2057     b0 = ROL64((a22^d2), 62);
2058     b1 = ROL64((a03^d3), 55);
2059     b2 = ROL64((a34^d4), 39);
2060     a10 =   b0 ^((~b1)&  b2 );
2061     a41 =   b1 ^((~b2)&  b3 );
2062     a22 =   b2 ^((~b3)&  b4 );
2063     a03 =   b3 ^((~b4)&  b0 );
2064     a34 =   b4 ^((~b0)&  b1 );
2065 
2066     c0 = a00^a40^a30^a20^a10;
2067     c1 = a31^a21^a11^a01^a41;
2068     c2 = a12^a02^a42^a32^a22;
2069     c3 = a43^a33^a23^a13^a03;
2070     c4 = a24^a14^a04^a44^a34;
2071     d0 = c4^ROL64(c1, 1);
2072     d1 = c0^ROL64(c2, 1);
2073     d2 = c1^ROL64(c3, 1);
2074     d3 = c2^ROL64(c4, 1);
2075     d4 = c3^ROL64(c0, 1);
2076 
2077     b0 = (a00^d0);
2078     b1 = ROL64((a21^d1), 44);
2079     b2 = ROL64((a42^d2), 43);
2080     b3 = ROL64((a13^d3), 21);
2081     b4 = ROL64((a34^d4), 14);
2082     a00 =   b0 ^((~b1)&  b2 );
2083     a00 ^= RC[i+2];
2084     a21 =   b1 ^((~b2)&  b3 );
2085     a42 =   b2 ^((~b3)&  b4 );
2086     a13 =   b3 ^((~b4)&  b0 );
2087     a34 =   b4 ^((~b0)&  b1 );
2088 
2089     b2 = ROL64((a30^d0), 3);
2090     b3 = ROL64((a01^d1), 45);
2091     b4 = ROL64((a22^d2), 61);
2092     b0 = ROL64((a43^d3), 28);
2093     b1 = ROL64((a14^d4), 20);
2094     a30 =   b0 ^((~b1)&  b2 );
2095     a01 =   b1 ^((~b2)&  b3 );
2096     a22 =   b2 ^((~b3)&  b4 );
2097     a43 =   b3 ^((~b4)&  b0 );
2098     a14 =   b4 ^((~b0)&  b1 );
2099 
2100     b4 = ROL64((a10^d0), 18);
2101     b0 = ROL64((a31^d1), 1);
2102     b1 = ROL64((a02^d2), 6);
2103     b2 = ROL64((a23^d3), 25);
2104     b3 = ROL64((a44^d4), 8);
2105     a10 =   b0 ^((~b1)&  b2 );
2106     a31 =   b1 ^((~b2)&  b3 );
2107     a02 =   b2 ^((~b3)&  b4 );
2108     a23 =   b3 ^((~b4)&  b0 );
2109     a44 =   b4 ^((~b0)&  b1 );
2110 
2111     b1 = ROL64((a40^d0), 36);
2112     b2 = ROL64((a11^d1), 10);
2113     b3 = ROL64((a32^d2), 15);
2114     b4 = ROL64((a03^d3), 56);
2115     b0 = ROL64((a24^d4), 27);
2116     a40 =   b0 ^((~b1)&  b2 );
2117     a11 =   b1 ^((~b2)&  b3 );
2118     a32 =   b2 ^((~b3)&  b4 );
2119     a03 =   b3 ^((~b4)&  b0 );
2120     a24 =   b4 ^((~b0)&  b1 );
2121 
2122     b3 = ROL64((a20^d0), 41);
2123     b4 = ROL64((a41^d1), 2);
2124     b0 = ROL64((a12^d2), 62);
2125     b1 = ROL64((a33^d3), 55);
2126     b2 = ROL64((a04^d4), 39);
2127     a20 =   b0 ^((~b1)&  b2 );
2128     a41 =   b1 ^((~b2)&  b3 );
2129     a12 =   b2 ^((~b3)&  b4 );
2130     a33 =   b3 ^((~b4)&  b0 );
2131     a04 =   b4 ^((~b0)&  b1 );
2132 
2133     c0 = a00^a30^a10^a40^a20;
2134     c1 = a21^a01^a31^a11^a41;
2135     c2 = a42^a22^a02^a32^a12;
2136     c3 = a13^a43^a23^a03^a33;
2137     c4 = a34^a14^a44^a24^a04;
2138     d0 = c4^ROL64(c1, 1);
2139     d1 = c0^ROL64(c2, 1);
2140     d2 = c1^ROL64(c3, 1);
2141     d3 = c2^ROL64(c4, 1);
2142     d4 = c3^ROL64(c0, 1);
2143 
2144     b0 = (a00^d0);
2145     b1 = ROL64((a01^d1), 44);
2146     b2 = ROL64((a02^d2), 43);
2147     b3 = ROL64((a03^d3), 21);
2148     b4 = ROL64((a04^d4), 14);
2149     a00 =   b0 ^((~b1)&  b2 );
2150     a00 ^= RC[i+3];
2151     a01 =   b1 ^((~b2)&  b3 );
2152     a02 =   b2 ^((~b3)&  b4 );
2153     a03 =   b3 ^((~b4)&  b0 );
2154     a04 =   b4 ^((~b0)&  b1 );
2155 
2156     b2 = ROL64((a10^d0), 3);
2157     b3 = ROL64((a11^d1), 45);
2158     b4 = ROL64((a12^d2), 61);
2159     b0 = ROL64((a13^d3), 28);
2160     b1 = ROL64((a14^d4), 20);
2161     a10 =   b0 ^((~b1)&  b2 );
2162     a11 =   b1 ^((~b2)&  b3 );
2163     a12 =   b2 ^((~b3)&  b4 );
2164     a13 =   b3 ^((~b4)&  b0 );
2165     a14 =   b4 ^((~b0)&  b1 );
2166 
2167     b4 = ROL64((a20^d0), 18);
2168     b0 = ROL64((a21^d1), 1);
2169     b1 = ROL64((a22^d2), 6);
2170     b2 = ROL64((a23^d3), 25);
2171     b3 = ROL64((a24^d4), 8);
2172     a20 =   b0 ^((~b1)&  b2 );
2173     a21 =   b1 ^((~b2)&  b3 );
2174     a22 =   b2 ^((~b3)&  b4 );
2175     a23 =   b3 ^((~b4)&  b0 );
2176     a24 =   b4 ^((~b0)&  b1 );
2177 
2178     b1 = ROL64((a30^d0), 36);
2179     b2 = ROL64((a31^d1), 10);
2180     b3 = ROL64((a32^d2), 15);
2181     b4 = ROL64((a33^d3), 56);
2182     b0 = ROL64((a34^d4), 27);
2183     a30 =   b0 ^((~b1)&  b2 );
2184     a31 =   b1 ^((~b2)&  b3 );
2185     a32 =   b2 ^((~b3)&  b4 );
2186     a33 =   b3 ^((~b4)&  b0 );
2187     a34 =   b4 ^((~b0)&  b1 );
2188 
2189     b3 = ROL64((a40^d0), 41);
2190     b4 = ROL64((a41^d1), 2);
2191     b0 = ROL64((a42^d2), 62);
2192     b1 = ROL64((a43^d3), 55);
2193     b2 = ROL64((a44^d4), 39);
2194     a40 =   b0 ^((~b1)&  b2 );
2195     a41 =   b1 ^((~b2)&  b3 );
2196     a42 =   b2 ^((~b3)&  b4 );
2197     a43 =   b3 ^((~b4)&  b0 );
2198     a44 =   b4 ^((~b0)&  b1 );
2199   }
2200 }
2201 
2202 /*
2203 ** Initialize a new hash.  iSize determines the size of the hash
2204 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
2205 ** can be zero to use the default hash size of 256 bits.
2206 */
2207 static void SHA3Init(SHA3Context *p, int iSize){
2208   memset(p, 0, sizeof(*p));
2209   if( iSize>=128 && iSize<=512 ){
2210     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
2211   }else{
2212     p->nRate = (1600 - 2*256)/8;
2213   }
2214 #if SHA3_BYTEORDER==1234
2215   /* Known to be little-endian at compile-time. No-op */
2216 #elif SHA3_BYTEORDER==4321
2217   p->ixMask = 7;  /* Big-endian */
2218 #else
2219   {
2220     static unsigned int one = 1;
2221     if( 1==*(unsigned char*)&one ){
2222       /* Little endian.  No byte swapping. */
2223       p->ixMask = 0;
2224     }else{
2225       /* Big endian.  Byte swap. */
2226       p->ixMask = 7;
2227     }
2228   }
2229 #endif
2230 }
2231 
2232 /*
2233 ** Make consecutive calls to the SHA3Update function to add new content
2234 ** to the hash
2235 */
2236 static void SHA3Update(
2237   SHA3Context *p,
2238   const unsigned char *aData,
2239   unsigned int nData
2240 ){
2241   unsigned int i = 0;
2242   if( aData==0 ) return;
2243 #if SHA3_BYTEORDER==1234
2244   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
2245     for(; i+7<nData; i+=8){
2246       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
2247       p->nLoaded += 8;
2248       if( p->nLoaded>=p->nRate ){
2249         KeccakF1600Step(p);
2250         p->nLoaded = 0;
2251       }
2252     }
2253   }
2254 #endif
2255   for(; i<nData; i++){
2256 #if SHA3_BYTEORDER==1234
2257     p->u.x[p->nLoaded] ^= aData[i];
2258 #elif SHA3_BYTEORDER==4321
2259     p->u.x[p->nLoaded^0x07] ^= aData[i];
2260 #else
2261     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
2262 #endif
2263     p->nLoaded++;
2264     if( p->nLoaded==p->nRate ){
2265       KeccakF1600Step(p);
2266       p->nLoaded = 0;
2267     }
2268   }
2269 }
2270 
2271 /*
2272 ** After all content has been added, invoke SHA3Final() to compute
2273 ** the final hash.  The function returns a pointer to the binary
2274 ** hash value.
2275 */
2276 static unsigned char *SHA3Final(SHA3Context *p){
2277   unsigned int i;
2278   if( p->nLoaded==p->nRate-1 ){
2279     const unsigned char c1 = 0x86;
2280     SHA3Update(p, &c1, 1);
2281   }else{
2282     const unsigned char c2 = 0x06;
2283     const unsigned char c3 = 0x80;
2284     SHA3Update(p, &c2, 1);
2285     p->nLoaded = p->nRate - 1;
2286     SHA3Update(p, &c3, 1);
2287   }
2288   for(i=0; i<p->nRate; i++){
2289     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
2290   }
2291   return &p->u.x[p->nRate];
2292 }
2293 /* End of the hashing logic
2294 *****************************************************************************/
2295 
2296 /*
2297 ** Implementation of the sha3(X,SIZE) function.
2298 **
2299 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
2300 ** size is 256.  If X is a BLOB, it is hashed as is.
2301 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2302 ** and the string is hashed without the trailing 0x00 terminator.  The hash
2303 ** of a NULL value is NULL.
2304 */
2305 static void sha3Func(
2306   sqlite3_context *context,
2307   int argc,
2308   sqlite3_value **argv
2309 ){
2310   SHA3Context cx;
2311   int eType = sqlite3_value_type(argv[0]);
2312   int nByte = sqlite3_value_bytes(argv[0]);
2313   int iSize;
2314   if( argc==1 ){
2315     iSize = 256;
2316   }else{
2317     iSize = sqlite3_value_int(argv[1]);
2318     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2319       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2320                                     "384 512", -1);
2321       return;
2322     }
2323   }
2324   if( eType==SQLITE_NULL ) return;
2325   SHA3Init(&cx, iSize);
2326   if( eType==SQLITE_BLOB ){
2327     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
2328   }else{
2329     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
2330   }
2331   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2332 }
2333 
2334 /* Compute a string using sqlite3_vsnprintf() with a maximum length
2335 ** of 50 bytes and add it to the hash.
2336 */
2337 static void sha3_step_vformat(
2338   SHA3Context *p,                 /* Add content to this context */
2339   const char *zFormat,
2340   ...
2341 ){
2342   va_list ap;
2343   int n;
2344   char zBuf[50];
2345   va_start(ap, zFormat);
2346   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
2347   va_end(ap);
2348   n = (int)strlen(zBuf);
2349   SHA3Update(p, (unsigned char*)zBuf, n);
2350 }
2351 
2352 /*
2353 ** Implementation of the sha3_query(SQL,SIZE) function.
2354 **
2355 ** This function compiles and runs the SQL statement(s) given in the
2356 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
2357 ** size is 256.
2358 **
2359 ** The format of the byte stream that is hashed is summarized as follows:
2360 **
2361 **       S<n>:<sql>
2362 **       R
2363 **       N
2364 **       I<int>
2365 **       F<ieee-float>
2366 **       B<size>:<bytes>
2367 **       T<size>:<text>
2368 **
2369 ** <sql> is the original SQL text for each statement run and <n> is
2370 ** the size of that text.  The SQL text is UTF-8.  A single R character
2371 ** occurs before the start of each row.  N means a NULL value.
2372 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
2373 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
2374 ** B means blobs of <size> bytes.  T means text rendered as <size>
2375 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
2376 ** text integers.
2377 **
2378 ** For each SQL statement in the X input, there is one S segment.  Each
2379 ** S segment is followed by zero or more R segments, one for each row in the
2380 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
2381 ** one for each column in the result set.  Segments are concatentated directly
2382 ** with no delimiters of any kind.
2383 */
2384 static void sha3QueryFunc(
2385   sqlite3_context *context,
2386   int argc,
2387   sqlite3_value **argv
2388 ){
2389   sqlite3 *db = sqlite3_context_db_handle(context);
2390   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
2391   sqlite3_stmt *pStmt = 0;
2392   int nCol;                   /* Number of columns in the result set */
2393   int i;                      /* Loop counter */
2394   int rc;
2395   int n;
2396   const char *z;
2397   SHA3Context cx;
2398   int iSize;
2399 
2400   if( argc==1 ){
2401     iSize = 256;
2402   }else{
2403     iSize = sqlite3_value_int(argv[1]);
2404     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2405       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2406                                     "384 512", -1);
2407       return;
2408     }
2409   }
2410   if( zSql==0 ) return;
2411   SHA3Init(&cx, iSize);
2412   while( zSql[0] ){
2413     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2414     if( rc ){
2415       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2416                                    zSql, sqlite3_errmsg(db));
2417       sqlite3_finalize(pStmt);
2418       sqlite3_result_error(context, zMsg, -1);
2419       sqlite3_free(zMsg);
2420       return;
2421     }
2422     if( !sqlite3_stmt_readonly(pStmt) ){
2423       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2424       sqlite3_finalize(pStmt);
2425       sqlite3_result_error(context, zMsg, -1);
2426       sqlite3_free(zMsg);
2427       return;
2428     }
2429     nCol = sqlite3_column_count(pStmt);
2430     z = sqlite3_sql(pStmt);
2431     if( z ){
2432       n = (int)strlen(z);
2433       sha3_step_vformat(&cx,"S%d:",n);
2434       SHA3Update(&cx,(unsigned char*)z,n);
2435     }
2436 
2437     /* Compute a hash over the result of the query */
2438     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2439       SHA3Update(&cx,(const unsigned char*)"R",1);
2440       for(i=0; i<nCol; i++){
2441         switch( sqlite3_column_type(pStmt,i) ){
2442           case SQLITE_NULL: {
2443             SHA3Update(&cx, (const unsigned char*)"N",1);
2444             break;
2445           }
2446           case SQLITE_INTEGER: {
2447             sqlite3_uint64 u;
2448             int j;
2449             unsigned char x[9];
2450             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2451             memcpy(&u, &v, 8);
2452             for(j=8; j>=1; j--){
2453               x[j] = u & 0xff;
2454               u >>= 8;
2455             }
2456             x[0] = 'I';
2457             SHA3Update(&cx, x, 9);
2458             break;
2459           }
2460           case SQLITE_FLOAT: {
2461             sqlite3_uint64 u;
2462             int j;
2463             unsigned char x[9];
2464             double r = sqlite3_column_double(pStmt,i);
2465             memcpy(&u, &r, 8);
2466             for(j=8; j>=1; j--){
2467               x[j] = u & 0xff;
2468               u >>= 8;
2469             }
2470             x[0] = 'F';
2471             SHA3Update(&cx,x,9);
2472             break;
2473           }
2474           case SQLITE_TEXT: {
2475             int n2 = sqlite3_column_bytes(pStmt, i);
2476             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2477             sha3_step_vformat(&cx,"T%d:",n2);
2478             SHA3Update(&cx, z2, n2);
2479             break;
2480           }
2481           case SQLITE_BLOB: {
2482             int n2 = sqlite3_column_bytes(pStmt, i);
2483             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2484             sha3_step_vformat(&cx,"B%d:",n2);
2485             SHA3Update(&cx, z2, n2);
2486             break;
2487           }
2488         }
2489       }
2490     }
2491     sqlite3_finalize(pStmt);
2492   }
2493   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2494 }
2495 
2496 
2497 #ifdef _WIN32
2498 
2499 #endif
2500 int sqlite3_shathree_init(
2501   sqlite3 *db,
2502   char **pzErrMsg,
2503   const sqlite3_api_routines *pApi
2504 ){
2505   int rc = SQLITE_OK;
2506   SQLITE_EXTENSION_INIT2(pApi);
2507   (void)pzErrMsg;  /* Unused parameter */
2508   rc = sqlite3_create_function(db, "sha3", 1,
2509                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2510                       0, sha3Func, 0, 0);
2511   if( rc==SQLITE_OK ){
2512     rc = sqlite3_create_function(db, "sha3", 2,
2513                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2514                       0, sha3Func, 0, 0);
2515   }
2516   if( rc==SQLITE_OK ){
2517     rc = sqlite3_create_function(db, "sha3_query", 1,
2518                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2519                       0, sha3QueryFunc, 0, 0);
2520   }
2521   if( rc==SQLITE_OK ){
2522     rc = sqlite3_create_function(db, "sha3_query", 2,
2523                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2524                       0, sha3QueryFunc, 0, 0);
2525   }
2526   return rc;
2527 }
2528 
2529 /************************* End ../ext/misc/shathree.c ********************/
2530 /************************* Begin ../ext/misc/uint.c ******************/
2531 /*
2532 ** 2020-04-14
2533 **
2534 ** The author disclaims copyright to this source code.  In place of
2535 ** a legal notice, here is a blessing:
2536 **
2537 **    May you do good and not evil.
2538 **    May you find forgiveness for yourself and forgive others.
2539 **    May you share freely, never taking more than you give.
2540 **
2541 ******************************************************************************
2542 **
2543 ** This SQLite extension implements the UINT collating sequence.
2544 **
2545 ** UINT works like BINARY for text, except that embedded strings
2546 ** of digits compare in numeric order.
2547 **
2548 **     *   Leading zeros are handled properly, in the sense that
2549 **         they do not mess of the maginitude comparison of embedded
2550 **         strings of digits.  "x00123y" is equal to "x123y".
2551 **
2552 **     *   Only unsigned integers are recognized.  Plus and minus
2553 **         signs are ignored.  Decimal points and exponential notation
2554 **         are ignored.
2555 **
2556 **     *   Embedded integers can be of arbitrary length.  Comparison
2557 **         is *not* limited integers that can be expressed as a
2558 **         64-bit machine integer.
2559 */
2560 /* #include "sqlite3ext.h" */
2561 SQLITE_EXTENSION_INIT1
2562 #include <assert.h>
2563 #include <string.h>
2564 #include <ctype.h>
2565 
2566 /*
2567 ** Compare text in lexicographic order, except strings of digits
2568 ** compare in numeric order.
2569 */
2570 static int uintCollFunc(
2571   void *notUsed,
2572   int nKey1, const void *pKey1,
2573   int nKey2, const void *pKey2
2574 ){
2575   const unsigned char *zA = (const unsigned char*)pKey1;
2576   const unsigned char *zB = (const unsigned char*)pKey2;
2577   int i=0, j=0, x;
2578   (void)notUsed;
2579   while( i<nKey1 && j<nKey2 ){
2580     x = zA[i] - zB[j];
2581     if( isdigit(zA[i]) ){
2582       int k;
2583       if( !isdigit(zB[j]) ) return x;
2584       while( i<nKey1 && zA[i]=='0' ){ i++; }
2585       while( j<nKey2 && zB[j]=='0' ){ j++; }
2586       k = 0;
2587       while( i+k<nKey1 && isdigit(zA[i+k])
2588              && j+k<nKey2 && isdigit(zB[j+k]) ){
2589         k++;
2590       }
2591       if( i+k<nKey1 && isdigit(zA[i+k]) ){
2592         return +1;
2593       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
2594         return -1;
2595       }else{
2596         x = memcmp(zA+i, zB+j, k);
2597         if( x ) return x;
2598         i += k;
2599         j += k;
2600       }
2601     }else if( x ){
2602       return x;
2603     }else{
2604       i++;
2605       j++;
2606     }
2607   }
2608   return (nKey1 - i) - (nKey2 - j);
2609 }
2610 
2611 #ifdef _WIN32
2612 
2613 #endif
2614 int sqlite3_uint_init(
2615   sqlite3 *db,
2616   char **pzErrMsg,
2617   const sqlite3_api_routines *pApi
2618 ){
2619   SQLITE_EXTENSION_INIT2(pApi);
2620   (void)pzErrMsg;  /* Unused parameter */
2621   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
2622 }
2623 
2624 /************************* End ../ext/misc/uint.c ********************/
2625 /************************* Begin ../ext/misc/decimal.c ******************/
2626 /*
2627 ** 2020-06-22
2628 **
2629 ** The author disclaims copyright to this source code.  In place of
2630 ** a legal notice, here is a blessing:
2631 **
2632 **    May you do good and not evil.
2633 **    May you find forgiveness for yourself and forgive others.
2634 **    May you share freely, never taking more than you give.
2635 **
2636 ******************************************************************************
2637 **
2638 ** Routines to implement arbitrary-precision decimal math.
2639 **
2640 ** The focus here is on simplicity and correctness, not performance.
2641 */
2642 /* #include "sqlite3ext.h" */
2643 SQLITE_EXTENSION_INIT1
2644 #include <assert.h>
2645 #include <string.h>
2646 #include <ctype.h>
2647 #include <stdlib.h>
2648 
2649 /* Mark a function parameter as unused, to suppress nuisance compiler
2650 ** warnings. */
2651 #ifndef UNUSED_PARAMETER
2652 # define UNUSED_PARAMETER(X)  (void)(X)
2653 #endif
2654 
2655 
2656 /* A decimal object */
2657 typedef struct Decimal Decimal;
2658 struct Decimal {
2659   char sign;        /* 0 for positive, 1 for negative */
2660   char oom;         /* True if an OOM is encountered */
2661   char isNull;      /* True if holds a NULL rather than a number */
2662   char isInit;      /* True upon initialization */
2663   int nDigit;       /* Total number of digits */
2664   int nFrac;        /* Number of digits to the right of the decimal point */
2665   signed char *a;   /* Array of digits.  Most significant first. */
2666 };
2667 
2668 /*
2669 ** Release memory held by a Decimal, but do not free the object itself.
2670 */
2671 static void decimal_clear(Decimal *p){
2672   sqlite3_free(p->a);
2673 }
2674 
2675 /*
2676 ** Destroy a Decimal object
2677 */
2678 static void decimal_free(Decimal *p){
2679   if( p ){
2680     decimal_clear(p);
2681     sqlite3_free(p);
2682   }
2683 }
2684 
2685 /*
2686 ** Allocate a new Decimal object.  Initialize it to the number given
2687 ** by the input string.
2688 */
2689 static Decimal *decimal_new(
2690   sqlite3_context *pCtx,
2691   sqlite3_value *pIn,
2692   int nAlt,
2693   const unsigned char *zAlt
2694 ){
2695   Decimal *p;
2696   int n, i;
2697   const unsigned char *zIn;
2698   int iExp = 0;
2699   p = sqlite3_malloc( sizeof(*p) );
2700   if( p==0 ) goto new_no_mem;
2701   p->sign = 0;
2702   p->oom = 0;
2703   p->isInit = 1;
2704   p->isNull = 0;
2705   p->nDigit = 0;
2706   p->nFrac = 0;
2707   if( zAlt ){
2708     n = nAlt,
2709     zIn = zAlt;
2710   }else{
2711     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
2712       p->a = 0;
2713       p->isNull = 1;
2714       return p;
2715     }
2716     n = sqlite3_value_bytes(pIn);
2717     zIn = sqlite3_value_text(pIn);
2718   }
2719   p->a = sqlite3_malloc64( n+1 );
2720   if( p->a==0 ) goto new_no_mem;
2721   for(i=0; isspace(zIn[i]); i++){}
2722   if( zIn[i]=='-' ){
2723     p->sign = 1;
2724     i++;
2725   }else if( zIn[i]=='+' ){
2726     i++;
2727   }
2728   while( i<n && zIn[i]=='0' ) i++;
2729   while( i<n ){
2730     char c = zIn[i];
2731     if( c>='0' && c<='9' ){
2732       p->a[p->nDigit++] = c - '0';
2733     }else if( c=='.' ){
2734       p->nFrac = p->nDigit + 1;
2735     }else if( c=='e' || c=='E' ){
2736       int j = i+1;
2737       int neg = 0;
2738       if( j>=n ) break;
2739       if( zIn[j]=='-' ){
2740         neg = 1;
2741         j++;
2742       }else if( zIn[j]=='+' ){
2743         j++;
2744       }
2745       while( j<n && iExp<1000000 ){
2746         if( zIn[j]>='0' && zIn[j]<='9' ){
2747           iExp = iExp*10 + zIn[j] - '0';
2748         }
2749         j++;
2750       }
2751       if( neg ) iExp = -iExp;
2752       break;
2753     }
2754     i++;
2755   }
2756   if( p->nFrac ){
2757     p->nFrac = p->nDigit - (p->nFrac - 1);
2758   }
2759   if( iExp>0 ){
2760     if( p->nFrac>0 ){
2761       if( iExp<=p->nFrac ){
2762         p->nFrac -= iExp;
2763         iExp = 0;
2764       }else{
2765         iExp -= p->nFrac;
2766         p->nFrac = 0;
2767       }
2768     }
2769     if( iExp>0 ){
2770       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2771       if( p->a==0 ) goto new_no_mem;
2772       memset(p->a+p->nDigit, 0, iExp);
2773       p->nDigit += iExp;
2774     }
2775   }else if( iExp<0 ){
2776     int nExtra;
2777     iExp = -iExp;
2778     nExtra = p->nDigit - p->nFrac - 1;
2779     if( nExtra ){
2780       if( nExtra>=iExp ){
2781         p->nFrac += iExp;
2782         iExp  = 0;
2783       }else{
2784         iExp -= nExtra;
2785         p->nFrac = p->nDigit - 1;
2786       }
2787     }
2788     if( iExp>0 ){
2789       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2790       if( p->a==0 ) goto new_no_mem;
2791       memmove(p->a+iExp, p->a, p->nDigit);
2792       memset(p->a, 0, iExp);
2793       p->nDigit += iExp;
2794       p->nFrac += iExp;
2795     }
2796   }
2797   return p;
2798 
2799 new_no_mem:
2800   if( pCtx ) sqlite3_result_error_nomem(pCtx);
2801   sqlite3_free(p);
2802   return 0;
2803 }
2804 
2805 /*
2806 ** Make the given Decimal the result.
2807 */
2808 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
2809   char *z;
2810   int i, j;
2811   int n;
2812   if( p==0 || p->oom ){
2813     sqlite3_result_error_nomem(pCtx);
2814     return;
2815   }
2816   if( p->isNull ){
2817     sqlite3_result_null(pCtx);
2818     return;
2819   }
2820   z = sqlite3_malloc( p->nDigit+4 );
2821   if( z==0 ){
2822     sqlite3_result_error_nomem(pCtx);
2823     return;
2824   }
2825   i = 0;
2826   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
2827     p->sign = 0;
2828   }
2829   if( p->sign ){
2830     z[0] = '-';
2831     i = 1;
2832   }
2833   n = p->nDigit - p->nFrac;
2834   if( n<=0 ){
2835     z[i++] = '0';
2836   }
2837   j = 0;
2838   while( n>1 && p->a[j]==0 ){
2839     j++;
2840     n--;
2841   }
2842   while( n>0  ){
2843     z[i++] = p->a[j] + '0';
2844     j++;
2845     n--;
2846   }
2847   if( p->nFrac ){
2848     z[i++] = '.';
2849     do{
2850       z[i++] = p->a[j] + '0';
2851       j++;
2852     }while( j<p->nDigit );
2853   }
2854   z[i] = 0;
2855   sqlite3_result_text(pCtx, z, i, sqlite3_free);
2856 }
2857 
2858 /*
2859 ** SQL Function:   decimal(X)
2860 **
2861 ** Convert input X into decimal and then back into text
2862 */
2863 static void decimalFunc(
2864   sqlite3_context *context,
2865   int argc,
2866   sqlite3_value **argv
2867 ){
2868   Decimal *p = decimal_new(context, argv[0], 0, 0);
2869   UNUSED_PARAMETER(argc);
2870   decimal_result(context, p);
2871   decimal_free(p);
2872 }
2873 
2874 /*
2875 ** Compare to Decimal objects.  Return negative, 0, or positive if the
2876 ** first object is less than, equal to, or greater than the second.
2877 **
2878 ** Preconditions for this routine:
2879 **
2880 **    pA!=0
2881 **    pA->isNull==0
2882 **    pB!=0
2883 **    pB->isNull==0
2884 */
2885 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
2886   int nASig, nBSig, rc, n;
2887   if( pA->sign!=pB->sign ){
2888     return pA->sign ? -1 : +1;
2889   }
2890   if( pA->sign ){
2891     const Decimal *pTemp = pA;
2892     pA = pB;
2893     pB = pTemp;
2894   }
2895   nASig = pA->nDigit - pA->nFrac;
2896   nBSig = pB->nDigit - pB->nFrac;
2897   if( nASig!=nBSig ){
2898     return nASig - nBSig;
2899   }
2900   n = pA->nDigit;
2901   if( n>pB->nDigit ) n = pB->nDigit;
2902   rc = memcmp(pA->a, pB->a, n);
2903   if( rc==0 ){
2904     rc = pA->nDigit - pB->nDigit;
2905   }
2906   return rc;
2907 }
2908 
2909 /*
2910 ** SQL Function:   decimal_cmp(X, Y)
2911 **
2912 ** Return negative, zero, or positive if X is less then, equal to, or
2913 ** greater than Y.
2914 */
2915 static void decimalCmpFunc(
2916   sqlite3_context *context,
2917   int argc,
2918   sqlite3_value **argv
2919 ){
2920   Decimal *pA = 0, *pB = 0;
2921   int rc;
2922 
2923   UNUSED_PARAMETER(argc);
2924   pA = decimal_new(context, argv[0], 0, 0);
2925   if( pA==0 || pA->isNull ) goto cmp_done;
2926   pB = decimal_new(context, argv[1], 0, 0);
2927   if( pB==0 || pB->isNull ) goto cmp_done;
2928   rc = decimal_cmp(pA, pB);
2929   if( rc<0 ) rc = -1;
2930   else if( rc>0 ) rc = +1;
2931   sqlite3_result_int(context, rc);
2932 cmp_done:
2933   decimal_free(pA);
2934   decimal_free(pB);
2935 }
2936 
2937 /*
2938 ** Expand the Decimal so that it has a least nDigit digits and nFrac
2939 ** digits to the right of the decimal point.
2940 */
2941 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
2942   int nAddSig;
2943   int nAddFrac;
2944   if( p==0 ) return;
2945   nAddFrac = nFrac - p->nFrac;
2946   nAddSig = (nDigit - p->nDigit) - nAddFrac;
2947   if( nAddFrac==0 && nAddSig==0 ) return;
2948   p->a = sqlite3_realloc64(p->a, nDigit+1);
2949   if( p->a==0 ){
2950     p->oom = 1;
2951     return;
2952   }
2953   if( nAddSig ){
2954     memmove(p->a+nAddSig, p->a, p->nDigit);
2955     memset(p->a, 0, nAddSig);
2956     p->nDigit += nAddSig;
2957   }
2958   if( nAddFrac ){
2959     memset(p->a+p->nDigit, 0, nAddFrac);
2960     p->nDigit += nAddFrac;
2961     p->nFrac += nAddFrac;
2962   }
2963 }
2964 
2965 /*
2966 ** Add the value pB into pA.
2967 **
2968 ** Both pA and pB might become denormalized by this routine.
2969 */
2970 static void decimal_add(Decimal *pA, Decimal *pB){
2971   int nSig, nFrac, nDigit;
2972   int i, rc;
2973   if( pA==0 ){
2974     return;
2975   }
2976   if( pA->oom || pB==0 || pB->oom ){
2977     pA->oom = 1;
2978     return;
2979   }
2980   if( pA->isNull || pB->isNull ){
2981     pA->isNull = 1;
2982     return;
2983   }
2984   nSig = pA->nDigit - pA->nFrac;
2985   if( nSig && pA->a[0]==0 ) nSig--;
2986   if( nSig<pB->nDigit-pB->nFrac ){
2987     nSig = pB->nDigit - pB->nFrac;
2988   }
2989   nFrac = pA->nFrac;
2990   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
2991   nDigit = nSig + nFrac + 1;
2992   decimal_expand(pA, nDigit, nFrac);
2993   decimal_expand(pB, nDigit, nFrac);
2994   if( pA->oom || pB->oom ){
2995     pA->oom = 1;
2996   }else{
2997     if( pA->sign==pB->sign ){
2998       int carry = 0;
2999       for(i=nDigit-1; i>=0; i--){
3000         int x = pA->a[i] + pB->a[i] + carry;
3001         if( x>=10 ){
3002           carry = 1;
3003           pA->a[i] = x - 10;
3004         }else{
3005           carry = 0;
3006           pA->a[i] = x;
3007         }
3008       }
3009     }else{
3010       signed char *aA, *aB;
3011       int borrow = 0;
3012       rc = memcmp(pA->a, pB->a, nDigit);
3013       if( rc<0 ){
3014         aA = pB->a;
3015         aB = pA->a;
3016         pA->sign = !pA->sign;
3017       }else{
3018         aA = pA->a;
3019         aB = pB->a;
3020       }
3021       for(i=nDigit-1; i>=0; i--){
3022         int x = aA[i] - aB[i] - borrow;
3023         if( x<0 ){
3024           pA->a[i] = x+10;
3025           borrow = 1;
3026         }else{
3027           pA->a[i] = x;
3028           borrow = 0;
3029         }
3030       }
3031     }
3032   }
3033 }
3034 
3035 /*
3036 ** Compare text in decimal order.
3037 */
3038 static int decimalCollFunc(
3039   void *notUsed,
3040   int nKey1, const void *pKey1,
3041   int nKey2, const void *pKey2
3042 ){
3043   const unsigned char *zA = (const unsigned char*)pKey1;
3044   const unsigned char *zB = (const unsigned char*)pKey2;
3045   Decimal *pA = decimal_new(0, 0, nKey1, zA);
3046   Decimal *pB = decimal_new(0, 0, nKey2, zB);
3047   int rc;
3048   UNUSED_PARAMETER(notUsed);
3049   if( pA==0 || pB==0 ){
3050     rc = 0;
3051   }else{
3052     rc = decimal_cmp(pA, pB);
3053   }
3054   decimal_free(pA);
3055   decimal_free(pB);
3056   return rc;
3057 }
3058 
3059 
3060 /*
3061 ** SQL Function:   decimal_add(X, Y)
3062 **                 decimal_sub(X, Y)
3063 **
3064 ** Return the sum or difference of X and Y.
3065 */
3066 static void decimalAddFunc(
3067   sqlite3_context *context,
3068   int argc,
3069   sqlite3_value **argv
3070 ){
3071   Decimal *pA = decimal_new(context, argv[0], 0, 0);
3072   Decimal *pB = decimal_new(context, argv[1], 0, 0);
3073   UNUSED_PARAMETER(argc);
3074   decimal_add(pA, pB);
3075   decimal_result(context, pA);
3076   decimal_free(pA);
3077   decimal_free(pB);
3078 }
3079 static void decimalSubFunc(
3080   sqlite3_context *context,
3081   int argc,
3082   sqlite3_value **argv
3083 ){
3084   Decimal *pA = decimal_new(context, argv[0], 0, 0);
3085   Decimal *pB = decimal_new(context, argv[1], 0, 0);
3086   UNUSED_PARAMETER(argc);
3087   if( pB ){
3088     pB->sign = !pB->sign;
3089     decimal_add(pA, pB);
3090     decimal_result(context, pA);
3091   }
3092   decimal_free(pA);
3093   decimal_free(pB);
3094 }
3095 
3096 /* Aggregate funcion:   decimal_sum(X)
3097 **
3098 ** Works like sum() except that it uses decimal arithmetic for unlimited
3099 ** precision.
3100 */
3101 static void decimalSumStep(
3102   sqlite3_context *context,
3103   int argc,
3104   sqlite3_value **argv
3105 ){
3106   Decimal *p;
3107   Decimal *pArg;
3108   UNUSED_PARAMETER(argc);
3109   p = sqlite3_aggregate_context(context, sizeof(*p));
3110   if( p==0 ) return;
3111   if( !p->isInit ){
3112     p->isInit = 1;
3113     p->a = sqlite3_malloc(2);
3114     if( p->a==0 ){
3115       p->oom = 1;
3116     }else{
3117       p->a[0] = 0;
3118     }
3119     p->nDigit = 1;
3120     p->nFrac = 0;
3121   }
3122   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
3123   pArg = decimal_new(context, argv[0], 0, 0);
3124   decimal_add(p, pArg);
3125   decimal_free(pArg);
3126 }
3127 static void decimalSumInverse(
3128   sqlite3_context *context,
3129   int argc,
3130   sqlite3_value **argv
3131 ){
3132   Decimal *p;
3133   Decimal *pArg;
3134   UNUSED_PARAMETER(argc);
3135   p = sqlite3_aggregate_context(context, sizeof(*p));
3136   if( p==0 ) return;
3137   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
3138   pArg = decimal_new(context, argv[0], 0, 0);
3139   if( pArg ) pArg->sign = !pArg->sign;
3140   decimal_add(p, pArg);
3141   decimal_free(pArg);
3142 }
3143 static void decimalSumValue(sqlite3_context *context){
3144   Decimal *p = sqlite3_aggregate_context(context, 0);
3145   if( p==0 ) return;
3146   decimal_result(context, p);
3147 }
3148 static void decimalSumFinalize(sqlite3_context *context){
3149   Decimal *p = sqlite3_aggregate_context(context, 0);
3150   if( p==0 ) return;
3151   decimal_result(context, p);
3152   decimal_clear(p);
3153 }
3154 
3155 /*
3156 ** SQL Function:   decimal_mul(X, Y)
3157 **
3158 ** Return the product of X and Y.
3159 **
3160 ** All significant digits after the decimal point are retained.
3161 ** Trailing zeros after the decimal point are omitted as long as
3162 ** the number of digits after the decimal point is no less than
3163 ** either the number of digits in either input.
3164 */
3165 static void decimalMulFunc(
3166   sqlite3_context *context,
3167   int argc,
3168   sqlite3_value **argv
3169 ){
3170   Decimal *pA = decimal_new(context, argv[0], 0, 0);
3171   Decimal *pB = decimal_new(context, argv[1], 0, 0);
3172   signed char *acc = 0;
3173   int i, j, k;
3174   int minFrac;
3175   UNUSED_PARAMETER(argc);
3176   if( pA==0 || pA->oom || pA->isNull
3177    || pB==0 || pB->oom || pB->isNull
3178   ){
3179     goto mul_end;
3180   }
3181   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
3182   if( acc==0 ){
3183     sqlite3_result_error_nomem(context);
3184     goto mul_end;
3185   }
3186   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
3187   minFrac = pA->nFrac;
3188   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
3189   for(i=pA->nDigit-1; i>=0; i--){
3190     signed char f = pA->a[i];
3191     int carry = 0, x;
3192     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
3193       x = acc[k] + f*pB->a[j] + carry;
3194       acc[k] = x%10;
3195       carry = x/10;
3196     }
3197     x = acc[k] + carry;
3198     acc[k] = x%10;
3199     acc[k-1] += x/10;
3200   }
3201   sqlite3_free(pA->a);
3202   pA->a = acc;
3203   acc = 0;
3204   pA->nDigit += pB->nDigit + 2;
3205   pA->nFrac += pB->nFrac;
3206   pA->sign ^= pB->sign;
3207   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
3208     pA->nFrac--;
3209     pA->nDigit--;
3210   }
3211   decimal_result(context, pA);
3212 
3213 mul_end:
3214   sqlite3_free(acc);
3215   decimal_free(pA);
3216   decimal_free(pB);
3217 }
3218 
3219 #ifdef _WIN32
3220 
3221 #endif
3222 int sqlite3_decimal_init(
3223   sqlite3 *db,
3224   char **pzErrMsg,
3225   const sqlite3_api_routines *pApi
3226 ){
3227   int rc = SQLITE_OK;
3228   static const struct {
3229     const char *zFuncName;
3230     int nArg;
3231     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3232   } aFunc[] = {
3233     { "decimal",       1,   decimalFunc        },
3234     { "decimal_cmp",   2,   decimalCmpFunc     },
3235     { "decimal_add",   2,   decimalAddFunc     },
3236     { "decimal_sub",   2,   decimalSubFunc     },
3237     { "decimal_mul",   2,   decimalMulFunc     },
3238   };
3239   unsigned int i;
3240   (void)pzErrMsg;  /* Unused parameter */
3241 
3242   SQLITE_EXTENSION_INIT2(pApi);
3243 
3244   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
3245     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
3246                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
3247                    0, aFunc[i].xFunc, 0, 0);
3248   }
3249   if( rc==SQLITE_OK ){
3250     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
3251                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
3252                    decimalSumStep, decimalSumFinalize,
3253                    decimalSumValue, decimalSumInverse, 0);
3254   }
3255   if( rc==SQLITE_OK ){
3256     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
3257                                   0, decimalCollFunc);
3258   }
3259   return rc;
3260 }
3261 
3262 /************************* End ../ext/misc/decimal.c ********************/
3263 #undef sqlite3_base_init
3264 #define sqlite3_base_init sqlite3_base64_init
3265 /************************* Begin ../ext/misc/base64.c ******************/
3266 /*
3267 ** 2022-11-18
3268 **
3269 ** The author disclaims copyright to this source code.  In place of
3270 ** a legal notice, here is a blessing:
3271 **
3272 **    May you do good and not evil.
3273 **    May you find forgiveness for yourself and forgive others.
3274 **    May you share freely, never taking more than you give.
3275 **
3276 *************************************************************************
3277 **
3278 ** This is a SQLite extension for converting in either direction
3279 ** between a (binary) blob and base64 text. Base64 can transit a
3280 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3281 ** written as TCL brace-enclosed literals or SQL string literals,
3282 ** and can be used unmodified in XML-like documents.
3283 **
3284 ** This is an independent implementation of conversions specified in
3285 ** RFC 4648, done on the above date by the author (Larry Brasfield)
3286 ** who thereby has the right to put this into the public domain.
3287 **
3288 ** The conversions meet RFC 4648 requirements, provided that this
3289 ** C source specifies that line-feeds are included in the encoded
3290 ** data to limit visible line lengths to 72 characters and to
3291 ** terminate any encoded blob having non-zero length.
3292 **
3293 ** Length limitations are not imposed except that the runtime
3294 ** SQLite string or blob length limits are respected. Otherwise,
3295 ** any length binary sequence can be represented and recovered.
3296 ** Generated base64 sequences, with their line-feeds included,
3297 ** can be concatenated; the result converted back to binary will
3298 ** be the concatenation of the represented binary sequences.
3299 **
3300 ** This SQLite3 extension creates a function, base64(x), which
3301 ** either: converts text x containing base64 to a returned blob;
3302 ** or converts a blob x to returned text containing base64. An
3303 ** error will be thrown for other input argument types.
3304 **
3305 ** This code relies on UTF-8 encoding only with respect to the
3306 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
3307 ** It will fail miserably if somehow made to try to convert EBCDIC.
3308 ** Because it is table-driven, it could be enhanced to handle that,
3309 ** but the world and SQLite have moved on from that anachronism.
3310 **
3311 ** To build the extension:
3312 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3313 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
3314 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
3315 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
3316 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
3317 */
3318 
3319 #include <assert.h>
3320 
3321 /* #include "sqlite3ext.h" */
3322 
3323 #ifndef deliberate_fall_through
3324 /* Quiet some compilers about some of our intentional code. */
3325 # if GCC_VERSION>=7000000
3326 #  define deliberate_fall_through __attribute__((fallthrough));
3327 # else
3328 #  define deliberate_fall_through
3329 # endif
3330 #endif
3331 
3332 SQLITE_EXTENSION_INIT1;
3333 
3334 #define PC 0x80 /* pad character */
3335 #define WS 0x81 /* whitespace */
3336 #define ND 0x82 /* Not above or digit-value */
3337 #define PAD_CHAR '='
3338 
3339 #ifndef U8_TYPEDEF
3340 /* typedef unsigned char u8; */
3341 #define U8_TYPEDEF
3342 #endif
3343 
3344 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
3345 static const u8 b64DigitValues[128] = {
3346   /*                             HT LF VT  FF CR       */
3347     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
3348   /*                                                US */
3349     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
3350   /*sp                                  +            / */
3351     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
3352   /* 0  1            5            9            =       */
3353     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
3354   /*    A                                            O */
3355     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
3356   /* P                               Z                 */
3357     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
3358   /*    a                                            o */
3359     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
3360   /* p                               z                 */
3361     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
3362 };
3363 
3364 static const char b64Numerals[64+1]
3365 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3366 
3367 #define BX_DV_PROTO(c) \
3368   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
3369 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
3370 #define IS_BX_WS(bdp) ((bdp)==WS)
3371 #define IS_BX_PAD(bdp) ((bdp)==PC)
3372 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
3373 /* Width of base64 lines. Should be an integer multiple of 4. */
3374 #define B64_DARK_MAX 72
3375 
3376 /* Encode a byte buffer into base64 text with linefeeds appended to limit
3377 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
3378 */
3379 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
3380   int nCol = 0;
3381   while( nbIn >= 3 ){
3382     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
3383     pOut[0] = BX_NUMERAL(pIn[0]>>2);
3384     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
3385     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
3386     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
3387     pOut += 4;
3388     nbIn -= 3;
3389     pIn += 3;
3390     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
3391       *pOut++ = '\n';
3392       nCol = 0;
3393     }
3394   }
3395   if( nbIn > 0 ){
3396     signed char nco = nbIn+1;
3397     int nbe;
3398     unsigned long qv = *pIn++;
3399     for( nbe=1; nbe<3; ++nbe ){
3400       qv <<= 8;
3401       if( nbe<nbIn ) qv |= *pIn++;
3402     }
3403     for( nbe=3; nbe>=0; --nbe ){
3404       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
3405       qv >>= 6;
3406       pOut[nbe] = ce;
3407     }
3408     pOut += 4;
3409     *pOut++ = '\n';
3410   }
3411   *pOut = 0;
3412   return pOut;
3413 }
3414 
3415 /* Skip over text which is not base64 numeral(s). */
3416 static char * skipNonB64( char *s, int nc ){
3417   char c;
3418   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
3419   return s;
3420 }
3421 
3422 /* Decode base64 text into a byte buffer. */
3423 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
3424   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3425   while( ncIn>0 && *pIn!=PAD_CHAR ){
3426     static signed char nboi[] = { 0, 0, 1, 2, 3 };
3427     char *pUse = skipNonB64(pIn, ncIn);
3428     unsigned long qv = 0L;
3429     int nti, nbo, nac;
3430     ncIn -= (pUse - pIn);
3431     pIn = pUse;
3432     nti = (ncIn>4)? 4 : ncIn;
3433     ncIn -= nti;
3434     nbo = nboi[nti];
3435     if( nbo==0 ) break;
3436     for( nac=0; nac<4; ++nac ){
3437       char c = (nac<nti)? *pIn++ : b64Numerals[0];
3438       u8 bdp = BX_DV_PROTO(c);
3439       switch( bdp ){
3440       case ND:
3441         /*  Treat dark non-digits as pad, but they terminate decode too. */
3442         ncIn = 0;
3443         deliberate_fall_through;
3444       case WS:
3445         /* Treat whitespace as pad and terminate this group.*/
3446         nti = nac;
3447         deliberate_fall_through;
3448       case PC:
3449         bdp = 0;
3450         --nbo;
3451         deliberate_fall_through;
3452       default: /* bdp is the digit value. */
3453         qv = qv<<6 | bdp;
3454         break;
3455       }
3456     }
3457     switch( nbo ){
3458     case 3:
3459       pOut[2] = (qv) & 0xff;
3460     case 2:
3461       pOut[1] = (qv>>8) & 0xff;
3462     case 1:
3463       pOut[0] = (qv>>16) & 0xff;
3464     }
3465     pOut += nbo;
3466   }
3467   return pOut;
3468 }
3469 
3470 /* This function does the work for the SQLite base64(x) UDF. */
3471 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
3472   int nb, nc, nv = sqlite3_value_bytes(av[0]);
3473   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
3474                             SQLITE_LIMIT_LENGTH, -1);
3475   char *cBuf;
3476   u8 *bBuf;
3477   assert(na==1);
3478   switch( sqlite3_value_type(av[0]) ){
3479   case SQLITE_BLOB:
3480     nb = nv;
3481     nc = 4*(nv+2/3); /* quads needed */
3482     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
3483     if( nvMax < nc ){
3484       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
3485       return;
3486     }
3487     bBuf = (u8*)sqlite3_value_blob(av[0]);
3488     if( !bBuf ){
3489       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
3490         goto memFail;
3491       }
3492       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
3493       break;
3494     }
3495     cBuf = sqlite3_malloc(nc);
3496     if( !cBuf ) goto memFail;
3497     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
3498     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
3499     break;
3500   case SQLITE_TEXT:
3501     nc = nv;
3502     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
3503     if( nvMax < nb ){
3504       sqlite3_result_error(context, "blob from base64 may be too big", -1);
3505       return;
3506     }else if( nb<1 ){
3507       nb = 1;
3508     }
3509     cBuf = (char *)sqlite3_value_text(av[0]);
3510     if( !cBuf ){
3511       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
3512         goto memFail;
3513       }
3514       sqlite3_result_zeroblob(context, 0);
3515       break;
3516     }
3517     bBuf = sqlite3_malloc(nb);
3518     if( !bBuf ) goto memFail;
3519     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
3520     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
3521     break;
3522   default:
3523     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
3524     return;
3525   }
3526   return;
3527  memFail:
3528   sqlite3_result_error(context, "base64 OOM", -1);
3529 }
3530 
3531 /*
3532 ** Establish linkage to running SQLite library.
3533 */
3534 #ifndef SQLITE_SHELL_EXTFUNCS
3535 #ifdef _WIN32
3536 
3537 #endif
3538 int sqlite3_base_init
3539 #else
3540 static int sqlite3_base64_init
3541 #endif
3542 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
3543   SQLITE_EXTENSION_INIT2(pApi);
3544   (void)pzErr;
3545   return sqlite3_create_function
3546     (db, "base64", 1,
3547      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
3548      0, base64, 0, 0);
3549 }
3550 
3551 /*
3552 ** Define some macros to allow this extension to be built into the shell
3553 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
3554 ** allows shell.c, as distributed, to have this extension built in.
3555 */
3556 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
3557 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
3558 
3559 /************************* End ../ext/misc/base64.c ********************/
3560 #undef sqlite3_base_init
3561 #define sqlite3_base_init sqlite3_base85_init
3562 #define OMIT_BASE85_CHECKER
3563 /************************* Begin ../ext/misc/base85.c ******************/
3564 /*
3565 ** 2022-11-16
3566 **
3567 ** The author disclaims copyright to this source code.  In place of
3568 ** a legal notice, here is a blessing:
3569 **
3570 **    May you do good and not evil.
3571 **    May you find forgiveness for yourself and forgive others.
3572 **    May you share freely, never taking more than you give.
3573 **
3574 *************************************************************************
3575 **
3576 ** This is a utility for converting binary to base85 or vice-versa.
3577 ** It can be built as a standalone program or an SQLite3 extension.
3578 **
3579 ** Much like base64 representations, base85 can be sent through a
3580 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3581 ** written as TCL brace-enclosed literals or SQL string literals.
3582 ** It is not suited for unmodified use in XML-like documents.
3583 **
3584 ** The encoding used resembles Ascii85, but was devised by the author
3585 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
3586 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
3587 ** Further, this is an independent implementation of a base85 system.
3588 ** Hence, the author has rightfully put this into the public domain.
3589 **
3590 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
3591 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
3592 ** in code order representing digit values 0 to 84 (base 10.)
3593 **
3594 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
3595 ** are represented as 5-digit base85 numbers with MS to LS digit
3596 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
3597 ** still big-endian but 8-24 bit values. (Using big-endian yields
3598 ** the simplest transition to byte groups smaller than 4 bytes.
3599 ** These byte groups can also be considered base-256 numbers.)
3600 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
3601 ** No pad characters are used; Encoded base85 numeral sequence
3602 ** (aka "group") length maps 1-to-1 to the decoded binary length.
3603 **
3604 ** Any character not in the base85 numeral set delimits groups.
3605 ** When base85 is streamed or stored in containers of indefinite
3606 ** size, newline is used to separate it into sub-sequences of no
3607 ** more than 80 digits so that fgets() can be used to read it.
3608 **
3609 ** Length limitations are not imposed except that the runtime
3610 ** SQLite string or blob length limits are respected. Otherwise,
3611 ** any length binary sequence can be represented and recovered.
3612 ** Base85 sequences can be concatenated by separating them with
3613 ** a non-base85 character; the conversion to binary will then
3614 ** be the concatenation of the represented binary sequences.
3615 
3616 ** The standalone program either converts base85 on stdin to create
3617 ** a binary file or converts a binary file to base85 on stdout.
3618 ** Read or make it blurt its help for invocation details.
3619 **
3620 ** The SQLite3 extension creates a function, base85(x), which will
3621 ** either convert text base85 to a blob or a blob to text base85
3622 ** and return the result (or throw an error for other types.)
3623 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
3624 ** function, is_base85(t), which returns 1 iff the text t contains
3625 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
3626 **
3627 ** To build the extension:
3628 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3629 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
3630 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
3631 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
3632 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
3633 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
3634 **
3635 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
3636 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
3637 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
3638 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
3639 */
3640 
3641 #include <stdio.h>
3642 #include <memory.h>
3643 #include <string.h>
3644 #include <assert.h>
3645 #ifndef OMIT_BASE85_CHECKER
3646 # include <ctype.h>
3647 #endif
3648 
3649 #ifndef BASE85_STANDALONE
3650 
3651 /* # include "sqlite3ext.h" */
3652 
3653 SQLITE_EXTENSION_INIT1;
3654 
3655 #else
3656 
3657 # ifdef _WIN32
3658 #  include <io.h>
3659 #  include <fcntl.h>
3660 # else
3661 #  define setmode(fd,m)
3662 # endif
3663 
3664 static char *zHelp =
3665   "Usage: base85 <dirFlag> <binFile>\n"
3666   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
3667   "   content to be converted to/from base85 on stdout/stdin.\n"
3668   " <binFile> names a binary file to be rendered or created.\n"
3669   "   Or, the name '-' refers to the stdin or stdout stream.\n"
3670   ;
3671 
3672 static void sayHelp(){
3673   printf("%s", zHelp);
3674 }
3675 #endif
3676 
3677 #ifndef U8_TYPEDEF
3678 /* typedef unsigned char u8; */
3679 #define U8_TYPEDEF
3680 #endif
3681 
3682 /* Classify c according to interval within USASCII set w.r.t. base85
3683  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
3684  */
3685 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
3686 
3687 /* Provide digitValue to b85Numeral offset as a function of above class. */
3688 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
3689 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
3690 
3691 /* Say whether c is a base85 numeral. */
3692 #define IS_B85( c ) (B85_CLASS(c) & 1)
3693 
3694 #if 0 /* Not used, */
3695 static u8 base85DigitValue( char c ){
3696   u8 dv = (u8)(c - '#');
3697   if( dv>87 ) return 0xff;
3698   return (dv > 3)? dv-3 : dv;
3699 }
3700 #endif
3701 
3702 /* Width of base64 lines. Should be an integer multiple of 5. */
3703 #define B85_DARK_MAX 80
3704 
3705 
3706 static char * skipNonB85( char *s, int nc ){
3707   char c;
3708   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
3709   return s;
3710 }
3711 
3712 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
3713  * Do not use the macro form with argument expression having a side-effect.*/
3714 #if 0
3715 static char base85Numeral( u8 b ){
3716   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
3717 }
3718 #else
3719 # define base85Numeral( dn )\
3720   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
3721 #endif
3722 
3723 static char *putcs(char *pc, char *s){
3724   char c;
3725   while( (c = *s++)!=0 ) *pc++ = c;
3726   return pc;
3727 }
3728 
3729 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
3730 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
3731 ** or to terminate the last group (to aid concatenation.)
3732 */
3733 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
3734   int nCol = 0;
3735   while( nbIn >= 4 ){
3736     int nco = 5;
3737     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
3738                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
3739     while( nco > 0 ){
3740       unsigned nqv = (unsigned)(qbv/85UL);
3741       unsigned char dv = qbv - 85UL*nqv;
3742       qbv = nqv;
3743       pOut[--nco] = base85Numeral(dv);
3744     }
3745     nbIn -= 4;
3746     pIn += 4;
3747     pOut += 5;
3748     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
3749       pOut = putcs(pOut, pSep);
3750       nCol = 0;
3751     }
3752   }
3753   if( nbIn > 0 ){
3754     int nco = nbIn + 1;
3755     unsigned long qv = *pIn++;
3756     int nbe = 1;
3757     while( nbe++ < nbIn ){
3758       qv = (qv<<8) | *pIn++;
3759     }
3760     nCol += nco;
3761     while( nco > 0 ){
3762       u8 dv = (u8)(qv % 85);
3763       qv /= 85;
3764       pOut[--nco] = base85Numeral(dv);
3765     }
3766     pOut += (nbIn+1);
3767   }
3768   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
3769   *pOut = 0;
3770   return pOut;
3771 }
3772 
3773 /* Decode base85 text into a byte buffer. */
3774 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
3775   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3776   while( ncIn>0 ){
3777     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
3778     char *pUse = skipNonB85(pIn, ncIn);
3779     unsigned long qv = 0L;
3780     int nti, nbo;
3781     ncIn -= (pUse - pIn);
3782     pIn = pUse;
3783     nti = (ncIn>5)? 5 : ncIn;
3784     nbo = nboi[nti];
3785     if( nbo==0 ) break;
3786     while( nti>0 ){
3787       char c = *pIn++;
3788       u8 cdo = B85_DNOS(c);
3789       --ncIn;
3790       if( cdo==0 ) break;
3791       qv = 85 * qv + (c - cdo);
3792       --nti;
3793     }
3794     nbo -= nti; /* Adjust for early (non-digit) end of group. */
3795     switch( nbo ){
3796     case 4:
3797       *pOut++ = (qv >> 24)&0xff;
3798     case 3:
3799       *pOut++ = (qv >> 16)&0xff;
3800     case 2:
3801       *pOut++ = (qv >> 8)&0xff;
3802     case 1:
3803       *pOut++ = qv&0xff;
3804     case 0:
3805       break;
3806     }
3807   }
3808   return pOut;
3809 }
3810 
3811 #ifndef OMIT_BASE85_CHECKER
3812 /* Say whether input char sequence is all (base85 and/or whitespace).*/
3813 static int allBase85( char *p, int len ){
3814   char c;
3815   while( len-- > 0 && (c = *p++) != 0 ){
3816     if( !IS_B85(c) && !isspace(c) ) return 0;
3817   }
3818   return 1;
3819 }
3820 #endif
3821 
3822 #ifndef BASE85_STANDALONE
3823 
3824 # ifndef OMIT_BASE85_CHECKER
3825 /* This function does the work for the SQLite is_base85(t) UDF. */
3826 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
3827   assert(na==1);
3828   switch( sqlite3_value_type(av[0]) ){
3829   case SQLITE_TEXT:
3830     {
3831       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
3832                           sqlite3_value_bytes(av[0]) );
3833       sqlite3_result_int(context, rv);
3834     }
3835     break;
3836   case SQLITE_NULL:
3837     sqlite3_result_null(context);
3838     break;
3839   default:
3840     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
3841     return;
3842   }
3843 }
3844 # endif
3845 
3846 /* This function does the work for the SQLite base85(x) UDF. */
3847 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
3848   int nb, nc, nv = sqlite3_value_bytes(av[0]);
3849   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
3850                             SQLITE_LIMIT_LENGTH, -1);
3851   char *cBuf;
3852   u8 *bBuf;
3853   assert(na==1);
3854   switch( sqlite3_value_type(av[0]) ){
3855   case SQLITE_BLOB:
3856     nb = nv;
3857     /*    ulongs    tail   newlines  tailenc+nul*/
3858     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
3859     if( nvMax < nc ){
3860       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
3861       return;
3862     }
3863     bBuf = (u8*)sqlite3_value_blob(av[0]);
3864     if( !bBuf ){
3865       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
3866         goto memFail;
3867       }
3868       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
3869       break;
3870     }
3871     cBuf = sqlite3_malloc(nc);
3872     if( !cBuf ) goto memFail;
3873     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
3874     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
3875     break;
3876   case SQLITE_TEXT:
3877     nc = nv;
3878     nb = 4*(nv/5) + nv%5; /* may overestimate */
3879     if( nvMax < nb ){
3880       sqlite3_result_error(context, "blob from base85 may be too big", -1);
3881       return;
3882     }else if( nb<1 ){
3883       nb = 1;
3884     }
3885     cBuf = (char *)sqlite3_value_text(av[0]);
3886     if( !cBuf ){
3887       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
3888         goto memFail;
3889       }
3890       sqlite3_result_zeroblob(context, 0);
3891       break;
3892     }
3893     bBuf = sqlite3_malloc(nb);
3894     if( !bBuf ) goto memFail;
3895     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
3896     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
3897     break;
3898   default:
3899     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
3900     return;
3901   }
3902   return;
3903  memFail:
3904   sqlite3_result_error(context, "base85 OOM", -1);
3905 }
3906 
3907 /*
3908 ** Establish linkage to running SQLite library.
3909 */
3910 #ifndef SQLITE_SHELL_EXTFUNCS
3911 #ifdef _WIN32
3912 
3913 #endif
3914 int sqlite3_base_init
3915 #else
3916 static int sqlite3_base85_init
3917 #endif
3918 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
3919   SQLITE_EXTENSION_INIT2(pApi);
3920   (void)pzErr;
3921 # ifndef OMIT_BASE85_CHECKER
3922   {
3923     int rc = sqlite3_create_function
3924       (db, "is_base85", 1,
3925        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
3926        0, is_base85, 0, 0);
3927     if( rc!=SQLITE_OK ) return rc;
3928   }
3929 # endif
3930   return sqlite3_create_function
3931     (db, "base85", 1,
3932      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
3933      0, base85, 0, 0);
3934 }
3935 
3936 /*
3937 ** Define some macros to allow this extension to be built into the shell
3938 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
3939 ** allows shell.c, as distributed, to have this extension built in.
3940 */
3941 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
3942 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
3943 
3944 #else /* standalone program */
3945 
3946 int main(int na, char *av[]){
3947   int cin;
3948   int rc = 0;
3949   u8 bBuf[4*(B85_DARK_MAX/5)];
3950   char cBuf[5*(sizeof(bBuf)/4)+2];
3951   size_t nio;
3952 # ifndef OMIT_BASE85_CHECKER
3953   int b85Clean = 1;
3954 # endif
3955   char rw;
3956   FILE *fb = 0, *foc = 0;
3957   char fmode[3] = "xb";
3958   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
3959     sayHelp();
3960     return 0;
3961   }
3962   fmode[0] = rw;
3963   if( av[2][0]=='-' && av[2][1]==0 ){
3964     switch( rw ){
3965     case 'r':
3966       fb = stdin;
3967       setmode(fileno(stdin), O_BINARY);
3968       break;
3969     case 'w':
3970       fb = stdout;
3971       setmode(fileno(stdout), O_BINARY);
3972       break;
3973     }
3974   }else{
3975     fb = fopen(av[2], fmode);
3976     foc = fb;
3977   }
3978   if( !fb ){
3979     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
3980     rc = 1;
3981   }else{
3982     switch( rw ){
3983     case 'r':
3984       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
3985         toBase85( bBuf, (int)nio, cBuf, 0 );
3986         fprintf(stdout, "%s\n", cBuf);
3987       }
3988       break;
3989     case 'w':
3990       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
3991         int nc = strlen(cBuf);
3992         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
3993         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
3994 # ifndef OMIT_BASE85_CHECKER
3995         b85Clean &= allBase85( cBuf, nc );
3996 # endif
3997       }
3998       break;
3999     default:
4000       sayHelp();
4001       rc = 1;
4002     }
4003     if( foc ) fclose(foc);
4004   }
4005 # ifndef OMIT_BASE85_CHECKER
4006   if( !b85Clean ){
4007     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
4008   }
4009 # endif
4010   return rc;
4011 }
4012 
4013 #endif
4014 
4015 /************************* End ../ext/misc/base85.c ********************/
4016 /************************* Begin ../ext/misc/ieee754.c ******************/
4017 /*
4018 ** 2013-04-17
4019 **
4020 ** The author disclaims copyright to this source code.  In place of
4021 ** a legal notice, here is a blessing:
4022 **
4023 **    May you do good and not evil.
4024 **    May you find forgiveness for yourself and forgive others.
4025 **    May you share freely, never taking more than you give.
4026 **
4027 ******************************************************************************
4028 **
4029 ** This SQLite extension implements functions for the exact display
4030 ** and input of IEEE754 Binary64 floating-point numbers.
4031 **
4032 **   ieee754(X)
4033 **   ieee754(Y,Z)
4034 **
4035 ** In the first form, the value X should be a floating-point number.
4036 ** The function will return a string of the form 'ieee754(Y,Z)' where
4037 ** Y and Z are integers such that X==Y*pow(2,Z).
4038 **
4039 ** In the second form, Y and Z are integers which are the mantissa and
4040 ** base-2 exponent of a new floating point number.  The function returns
4041 ** a floating-point value equal to Y*pow(2,Z).
4042 **
4043 ** Examples:
4044 **
4045 **     ieee754(2.0)             ->     'ieee754(2,0)'
4046 **     ieee754(45.25)           ->     'ieee754(181,-2)'
4047 **     ieee754(2, 0)            ->     2.0
4048 **     ieee754(181, -2)         ->     45.25
4049 **
4050 ** Two additional functions break apart the one-argument ieee754()
4051 ** result into separate integer values:
4052 **
4053 **     ieee754_mantissa(45.25)  ->     181
4054 **     ieee754_exponent(45.25)  ->     -2
4055 **
4056 ** These functions convert binary64 numbers into blobs and back again.
4057 **
4058 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
4059 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
4060 **
4061 ** In all single-argument functions, if the argument is an 8-byte blob
4062 ** then that blob is interpreted as a big-endian binary64 value.
4063 **
4064 **
4065 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
4066 ** -----------------------------------------------
4067 **
4068 ** This extension in combination with the separate 'decimal' extension
4069 ** can be used to compute the exact decimal representation of binary64
4070 ** values.  To begin, first compute a table of exponent values:
4071 **
4072 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
4073 **    WITH RECURSIVE c(x,v) AS (
4074 **      VALUES(0,'1')
4075 **      UNION ALL
4076 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
4077 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
4078 **    WITH RECURSIVE c(x,v) AS (
4079 **      VALUES(-1,'0.5')
4080 **      UNION ALL
4081 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
4082 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
4083 **
4084 ** Then, to compute the exact decimal representation of a floating
4085 ** point value (the value 47.49 is used in the example) do:
4086 **
4087 **    WITH c(n) AS (VALUES(47.49))
4088 **          ---------------^^^^^---- Replace with whatever you want
4089 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
4090 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
4091 **
4092 ** Here is a query to show various boundry values for the binary64
4093 ** number format:
4094 **
4095 **    WITH c(name,bin) AS (VALUES
4096 **       ('minimum positive value',        x'0000000000000001'),
4097 **       ('maximum subnormal value',       x'000fffffffffffff'),
4098 **       ('mininum positive nornal value', x'0010000000000000'),
4099 **       ('maximum value',                 x'7fefffffffffffff'))
4100 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
4101 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
4102 **
4103 */
4104 /* #include "sqlite3ext.h" */
4105 SQLITE_EXTENSION_INIT1
4106 #include <assert.h>
4107 #include <string.h>
4108 
4109 /* Mark a function parameter as unused, to suppress nuisance compiler
4110 ** warnings. */
4111 #ifndef UNUSED_PARAMETER
4112 # define UNUSED_PARAMETER(X)  (void)(X)
4113 #endif
4114 
4115 /*
4116 ** Implementation of the ieee754() function
4117 */
4118 static void ieee754func(
4119   sqlite3_context *context,
4120   int argc,
4121   sqlite3_value **argv
4122 ){
4123   if( argc==1 ){
4124     sqlite3_int64 m, a;
4125     double r;
4126     int e;
4127     int isNeg;
4128     char zResult[100];
4129     assert( sizeof(m)==sizeof(r) );
4130     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
4131      && sqlite3_value_bytes(argv[0])==sizeof(r)
4132     ){
4133       const unsigned char *x = sqlite3_value_blob(argv[0]);
4134       unsigned int i;
4135       sqlite3_uint64 v = 0;
4136       for(i=0; i<sizeof(r); i++){
4137         v = (v<<8) | x[i];
4138       }
4139       memcpy(&r, &v, sizeof(r));
4140     }else{
4141       r = sqlite3_value_double(argv[0]);
4142     }
4143     if( r<0.0 ){
4144       isNeg = 1;
4145       r = -r;
4146     }else{
4147       isNeg = 0;
4148     }
4149     memcpy(&a,&r,sizeof(a));
4150     if( a==0 ){
4151       e = 0;
4152       m = 0;
4153     }else{
4154       e = a>>52;
4155       m = a & ((((sqlite3_int64)1)<<52)-1);
4156       if( e==0 ){
4157         m <<= 1;
4158       }else{
4159         m |= ((sqlite3_int64)1)<<52;
4160       }
4161       while( e<1075 && m>0 && (m&1)==0 ){
4162         m >>= 1;
4163         e++;
4164       }
4165       if( isNeg ) m = -m;
4166     }
4167     switch( *(int*)sqlite3_user_data(context) ){
4168       case 0:
4169         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
4170                          m, e-1075);
4171         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
4172         break;
4173       case 1:
4174         sqlite3_result_int64(context, m);
4175         break;
4176       case 2:
4177         sqlite3_result_int(context, e-1075);
4178         break;
4179     }
4180   }else{
4181     sqlite3_int64 m, e, a;
4182     double r;
4183     int isNeg = 0;
4184     m = sqlite3_value_int64(argv[0]);
4185     e = sqlite3_value_int64(argv[1]);
4186 
4187     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
4188     if( e>10000 ){
4189       e = 10000;
4190     }else if( e<-10000 ){
4191       e = -10000;
4192     }
4193 
4194     if( m<0 ){
4195       isNeg = 1;
4196       m = -m;
4197       if( m<0 ) return;
4198     }else if( m==0 && e>-1000 && e<1000 ){
4199       sqlite3_result_double(context, 0.0);
4200       return;
4201     }
4202     while( (m>>32)&0xffe00000 ){
4203       m >>= 1;
4204       e++;
4205     }
4206     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
4207       m <<= 1;
4208       e--;
4209     }
4210     e += 1075;
4211     if( e<=0 ){
4212       /* Subnormal */
4213       if( 1-e >= 64 ){
4214         m = 0;
4215       }else{
4216         m >>= 1-e;
4217       }
4218       e = 0;
4219     }else if( e>0x7ff ){
4220       e = 0x7ff;
4221     }
4222     a = m & ((((sqlite3_int64)1)<<52)-1);
4223     a |= e<<52;
4224     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
4225     memcpy(&r, &a, sizeof(r));
4226     sqlite3_result_double(context, r);
4227   }
4228 }
4229 
4230 /*
4231 ** Functions to convert between blobs and floats.
4232 */
4233 static void ieee754func_from_blob(
4234   sqlite3_context *context,
4235   int argc,
4236   sqlite3_value **argv
4237 ){
4238   UNUSED_PARAMETER(argc);
4239   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
4240    && sqlite3_value_bytes(argv[0])==sizeof(double)
4241   ){
4242     double r;
4243     const unsigned char *x = sqlite3_value_blob(argv[0]);
4244     unsigned int i;
4245     sqlite3_uint64 v = 0;
4246     for(i=0; i<sizeof(r); i++){
4247       v = (v<<8) | x[i];
4248     }
4249     memcpy(&r, &v, sizeof(r));
4250     sqlite3_result_double(context, r);
4251   }
4252 }
4253 static void ieee754func_to_blob(
4254   sqlite3_context *context,
4255   int argc,
4256   sqlite3_value **argv
4257 ){
4258   UNUSED_PARAMETER(argc);
4259   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
4260    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
4261   ){
4262     double r = sqlite3_value_double(argv[0]);
4263     sqlite3_uint64 v;
4264     unsigned char a[sizeof(r)];
4265     unsigned int i;
4266     memcpy(&v, &r, sizeof(r));
4267     for(i=1; i<=sizeof(r); i++){
4268       a[sizeof(r)-i] = v&0xff;
4269       v >>= 8;
4270     }
4271     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
4272   }
4273 }
4274 
4275 
4276 #ifdef _WIN32
4277 
4278 #endif
4279 int sqlite3_ieee_init(
4280   sqlite3 *db,
4281   char **pzErrMsg,
4282   const sqlite3_api_routines *pApi
4283 ){
4284   static const struct {
4285     char *zFName;
4286     int nArg;
4287     int iAux;
4288     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4289   } aFunc[] = {
4290     { "ieee754",           1,   0, ieee754func },
4291     { "ieee754",           2,   0, ieee754func },
4292     { "ieee754_mantissa",  1,   1, ieee754func },
4293     { "ieee754_exponent",  1,   2, ieee754func },
4294     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
4295     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
4296 
4297   };
4298   unsigned int i;
4299   int rc = SQLITE_OK;
4300   SQLITE_EXTENSION_INIT2(pApi);
4301   (void)pzErrMsg;  /* Unused parameter */
4302   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
4303     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
4304                                SQLITE_UTF8|SQLITE_INNOCUOUS,
4305                                (void*)&aFunc[i].iAux,
4306                                aFunc[i].xFunc, 0, 0);
4307   }
4308   return rc;
4309 }
4310 
4311 /************************* End ../ext/misc/ieee754.c ********************/
4312 /************************* Begin ../ext/misc/series.c ******************/
4313 /*
4314 ** 2015-08-18, 2023-04-28
4315 **
4316 ** The author disclaims copyright to this source code.  In place of
4317 ** a legal notice, here is a blessing:
4318 **
4319 **    May you do good and not evil.
4320 **    May you find forgiveness for yourself and forgive others.
4321 **    May you share freely, never taking more than you give.
4322 **
4323 *************************************************************************
4324 **
4325 ** This file demonstrates how to create a table-valued-function using
4326 ** a virtual table.  This demo implements the generate_series() function
4327 ** which gives the same results as the eponymous function in PostgreSQL,
4328 ** within the limitation that its arguments are signed 64-bit integers.
4329 **
4330 ** Considering its equivalents to generate_series(start,stop,step): A
4331 ** value V[n] sequence is produced for integer n ascending from 0 where
4332 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
4333 ** for each produced value (independent of production time ordering.)
4334 **
4335 ** All parameters must be either integer or convertable to integer.
4336 ** The start parameter is required.
4337 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
4338 ** The step parameter defaults to 1 and 0 is treated as 1.
4339 **
4340 ** Examples:
4341 **
4342 **      SELECT * FROM generate_series(0,100,5);
4343 **
4344 ** The query above returns integers from 0 through 100 counting by steps
4345 ** of 5.
4346 **
4347 **      SELECT * FROM generate_series(0,100);
4348 **
4349 ** Integers from 0 through 100 with a step size of 1.
4350 **
4351 **      SELECT * FROM generate_series(20) LIMIT 10;
4352 **
4353 ** Integers 20 through 29.
4354 **
4355 **      SELECT * FROM generate_series(0,-100,-5);
4356 **
4357 ** Integers 0 -5 -10 ... -100.
4358 **
4359 **      SELECT * FROM generate_series(0,-1);
4360 **
4361 ** Empty sequence.
4362 **
4363 ** HOW IT WORKS
4364 **
4365 ** The generate_series "function" is really a virtual table with the
4366 ** following schema:
4367 **
4368 **     CREATE TABLE generate_series(
4369 **       value,
4370 **       start HIDDEN,
4371 **       stop HIDDEN,
4372 **       step HIDDEN
4373 **     );
4374 **
4375 ** The virtual table also has a rowid, logically equivalent to n+1 where
4376 ** "n" is the ascending integer in the aforesaid production definition.
4377 **
4378 ** Function arguments in queries against this virtual table are translated
4379 ** into equality constraints against successive hidden columns.  In other
4380 ** words, the following pairs of queries are equivalent to each other:
4381 **
4382 **    SELECT * FROM generate_series(0,100,5);
4383 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
4384 **
4385 **    SELECT * FROM generate_series(0,100);
4386 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
4387 **
4388 **    SELECT * FROM generate_series(20) LIMIT 10;
4389 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
4390 **
4391 ** The generate_series virtual table implementation leaves the xCreate method
4392 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
4393 ** TABLE command with "generate_series" as the USING argument.  Instead, there
4394 ** is a single generate_series virtual table that is always available without
4395 ** having to be created first.
4396 **
4397 ** The xBestIndex method looks for equality constraints against the hidden
4398 ** start, stop, and step columns, and if present, it uses those constraints
4399 ** to bound the sequence of generated values.  If the equality constraints
4400 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
4401 ** xBestIndex returns a small cost when both start and stop are available,
4402 ** and a very large cost if either start or stop are unavailable.  This
4403 ** encourages the query planner to order joins such that the bounds of the
4404 ** series are well-defined.
4405 */
4406 /* #include "sqlite3ext.h" */
4407 SQLITE_EXTENSION_INIT1
4408 #include <assert.h>
4409 #include <string.h>
4410 #include <limits.h>
4411 
4412 #ifndef SQLITE_OMIT_VIRTUALTABLE
4413 /*
4414 ** Return that member of a generate_series(...) sequence whose 0-based
4415 ** index is ix. The 0th member is given by smBase. The sequence members
4416 ** progress per ix increment by smStep.
4417 */
4418 static sqlite3_int64 genSeqMember(sqlite3_int64 smBase,
4419                                   sqlite3_int64 smStep,
4420                                   sqlite3_uint64 ix){
4421   if( ix>=(sqlite3_uint64)LLONG_MAX ){
4422     /* Get ix into signed i64 range. */
4423     ix -= (sqlite3_uint64)LLONG_MAX;
4424     /* With 2's complement ALU, this next can be 1 step, but is split into
4425      * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
4426     smBase += (LLONG_MAX/2) * smStep;
4427     smBase += (LLONG_MAX - LLONG_MAX/2) * smStep;
4428   }
4429   /* Under UBSAN (or on 1's complement machines), must do this last term
4430    * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
4431   if( ix>=2 ){
4432     sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
4433     smBase += ix2*smStep;
4434     ix -= ix2;
4435   }
4436   return smBase + ((sqlite3_int64)ix)*smStep;
4437 }
4438 
4439 /* typedef unsigned char u8; */
4440 
4441 typedef struct SequenceSpec {
4442   sqlite3_int64 iBase;         /* Starting value ("start") */
4443   sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
4444   sqlite3_int64 iStep;         /* Increment ("step") */
4445   sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
4446   sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
4447   sqlite3_int64 iValueNow;     /* Current value during generation */
4448   u8 isNotEOF;                 /* Sequence generation not exhausted */
4449   u8 isReversing;              /* Sequence is being reverse generated */
4450 } SequenceSpec;
4451 
4452 /*
4453 ** Prepare a SequenceSpec for use in generating an integer series
4454 ** given initialized iBase, iTerm and iStep values. Sequence is
4455 ** initialized per given isReversing. Other members are computed.
4456 */
4457 static void setupSequence( SequenceSpec *pss ){
4458   int bSameSigns;
4459   pss->uSeqIndexMax = 0;
4460   pss->isNotEOF = 0;
4461   bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
4462   if( pss->iTerm < pss->iBase ){
4463     sqlite3_uint64 nuspan = 0;
4464     if( bSameSigns ){
4465       nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
4466     }else{
4467       /* Under UBSAN (or on 1's complement machines), must do this in steps.
4468        * In this clause, iBase>=0 and iTerm<0 . */
4469       nuspan = 1;
4470       nuspan += pss->iBase;
4471       nuspan += -(pss->iTerm+1);
4472     }
4473     if( pss->iStep<0 ){
4474       pss->isNotEOF = 1;
4475       if( nuspan==ULONG_MAX ){
4476         pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
4477       }else if( pss->iStep>LLONG_MIN ){
4478         pss->uSeqIndexMax = nuspan/-pss->iStep;
4479       }
4480     }
4481   }else if( pss->iTerm > pss->iBase ){
4482     sqlite3_uint64 puspan = 0;
4483     if( bSameSigns ){
4484       puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
4485     }else{
4486       /* Under UBSAN (or on 1's complement machines), must do this in steps.
4487        * In this clause, iTerm>=0 and iBase<0 . */
4488       puspan = 1;
4489       puspan += pss->iTerm;
4490       puspan += -(pss->iBase+1);
4491     }
4492     if( pss->iStep>0 ){
4493       pss->isNotEOF = 1;
4494       pss->uSeqIndexMax = puspan/pss->iStep;
4495     }
4496   }else if( pss->iTerm == pss->iBase ){
4497       pss->isNotEOF = 1;
4498       pss->uSeqIndexMax = 0;
4499   }
4500   pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
4501   pss->iValueNow = (pss->isReversing)
4502     ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
4503     : pss->iBase;
4504 }
4505 
4506 /*
4507 ** Progress sequence generator to yield next value, if any.
4508 ** Leave its state to either yield next value or be at EOF.
4509 ** Return whether there is a next value, or 0 at EOF.
4510 */
4511 static int progressSequence( SequenceSpec *pss ){
4512   if( !pss->isNotEOF ) return 0;
4513   if( pss->isReversing ){
4514     if( pss->uSeqIndexNow > 0 ){
4515       pss->uSeqIndexNow--;
4516       pss->iValueNow -= pss->iStep;
4517     }else{
4518       pss->isNotEOF = 0;
4519     }
4520   }else{
4521     if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
4522       pss->uSeqIndexNow++;
4523       pss->iValueNow += pss->iStep;
4524     }else{
4525       pss->isNotEOF = 0;
4526     }
4527   }
4528   return pss->isNotEOF;
4529 }
4530 
4531 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
4532 ** serve as the underlying representation of a cursor that scans
4533 ** over rows of the result
4534 */
4535 typedef struct series_cursor series_cursor;
4536 struct series_cursor {
4537   sqlite3_vtab_cursor base;  /* Base class - must be first */
4538   SequenceSpec ss;           /* (this) Derived class data */
4539 };
4540 
4541 /*
4542 ** The seriesConnect() method is invoked to create a new
4543 ** series_vtab that describes the generate_series virtual table.
4544 **
4545 ** Think of this routine as the constructor for series_vtab objects.
4546 **
4547 ** All this routine needs to do is:
4548 **
4549 **    (1) Allocate the series_vtab object and initialize all fields.
4550 **
4551 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
4552 **        result set of queries against generate_series will look like.
4553 */
4554 static int seriesConnect(
4555   sqlite3 *db,
4556   void *pUnused,
4557   int argcUnused, const char *const*argvUnused,
4558   sqlite3_vtab **ppVtab,
4559   char **pzErrUnused
4560 ){
4561   sqlite3_vtab *pNew;
4562   int rc;
4563 
4564 /* Column numbers */
4565 #define SERIES_COLUMN_VALUE 0
4566 #define SERIES_COLUMN_START 1
4567 #define SERIES_COLUMN_STOP  2
4568 #define SERIES_COLUMN_STEP  3
4569 
4570   (void)pUnused;
4571   (void)argcUnused;
4572   (void)argvUnused;
4573   (void)pzErrUnused;
4574   rc = sqlite3_declare_vtab(db,
4575      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
4576   if( rc==SQLITE_OK ){
4577     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
4578     if( pNew==0 ) return SQLITE_NOMEM;
4579     memset(pNew, 0, sizeof(*pNew));
4580     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
4581   }
4582   return rc;
4583 }
4584 
4585 /*
4586 ** This method is the destructor for series_cursor objects.
4587 */
4588 static int seriesDisconnect(sqlite3_vtab *pVtab){
4589   sqlite3_free(pVtab);
4590   return SQLITE_OK;
4591 }
4592 
4593 /*
4594 ** Constructor for a new series_cursor object.
4595 */
4596 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
4597   series_cursor *pCur;
4598   (void)pUnused;
4599   pCur = sqlite3_malloc( sizeof(*pCur) );
4600   if( pCur==0 ) return SQLITE_NOMEM;
4601   memset(pCur, 0, sizeof(*pCur));
4602   *ppCursor = &pCur->base;
4603   return SQLITE_OK;
4604 }
4605 
4606 /*
4607 ** Destructor for a series_cursor.
4608 */
4609 static int seriesClose(sqlite3_vtab_cursor *cur){
4610   sqlite3_free(cur);
4611   return SQLITE_OK;
4612 }
4613 
4614 
4615 /*
4616 ** Advance a series_cursor to its next row of output.
4617 */
4618 static int seriesNext(sqlite3_vtab_cursor *cur){
4619   series_cursor *pCur = (series_cursor*)cur;
4620   progressSequence( & pCur->ss );
4621   return SQLITE_OK;
4622 }
4623 
4624 /*
4625 ** Return values of columns for the row at which the series_cursor
4626 ** is currently pointing.
4627 */
4628 static int seriesColumn(
4629   sqlite3_vtab_cursor *cur,   /* The cursor */
4630   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
4631   int i                       /* Which column to return */
4632 ){
4633   series_cursor *pCur = (series_cursor*)cur;
4634   sqlite3_int64 x = 0;
4635   switch( i ){
4636     case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
4637     case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
4638     case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
4639     default:                   x = pCur->ss.iValueNow;  break;
4640   }
4641   sqlite3_result_int64(ctx, x);
4642   return SQLITE_OK;
4643 }
4644 
4645 /*
4646 ** Return the rowid for the current row, logically equivalent to n+1 where
4647 ** "n" is the ascending integer in the aforesaid production definition.
4648 */
4649 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
4650   series_cursor *pCur = (series_cursor*)cur;
4651   sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
4652   *pRowid = (sqlite3_int64)((n<0xffffffffffffffff)? n+1 : 0);
4653   return SQLITE_OK;
4654 }
4655 
4656 /*
4657 ** Return TRUE if the cursor has been moved off of the last
4658 ** row of output.
4659 */
4660 static int seriesEof(sqlite3_vtab_cursor *cur){
4661   series_cursor *pCur = (series_cursor*)cur;
4662   return !pCur->ss.isNotEOF;
4663 }
4664 
4665 /* True to cause run-time checking of the start=, stop=, and/or step=
4666 ** parameters.  The only reason to do this is for testing the
4667 ** constraint checking logic for virtual tables in the SQLite core.
4668 */
4669 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
4670 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
4671 #endif
4672 
4673 /*
4674 ** This method is called to "rewind" the series_cursor object back
4675 ** to the first row of output.  This method is always called at least
4676 ** once prior to any call to seriesColumn() or seriesRowid() or
4677 ** seriesEof().
4678 **
4679 ** The query plan selected by seriesBestIndex is passed in the idxNum
4680 ** parameter.  (idxStr is not used in this implementation.)  idxNum
4681 ** is a bitmask showing which constraints are available:
4682 **
4683 **    1:    start=VALUE
4684 **    2:    stop=VALUE
4685 **    4:    step=VALUE
4686 **
4687 ** Also, if bit 8 is set, that means that the series should be output
4688 ** in descending order rather than in ascending order.  If bit 16 is
4689 ** set, then output must appear in ascending order.
4690 **
4691 ** This routine should initialize the cursor and position it so that it
4692 ** is pointing at the first row, or pointing off the end of the table
4693 ** (so that seriesEof() will return true) if the table is empty.
4694 */
4695 static int seriesFilter(
4696   sqlite3_vtab_cursor *pVtabCursor,
4697   int idxNum, const char *idxStrUnused,
4698   int argc, sqlite3_value **argv
4699 ){
4700   series_cursor *pCur = (series_cursor *)pVtabCursor;
4701   int i = 0;
4702   (void)idxStrUnused;
4703   if( idxNum & 1 ){
4704     pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
4705   }else{
4706     pCur->ss.iBase = 0;
4707   }
4708   if( idxNum & 2 ){
4709     pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
4710   }else{
4711     pCur->ss.iTerm = 0xffffffff;
4712   }
4713   if( idxNum & 4 ){
4714     pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
4715     if( pCur->ss.iStep==0 ){
4716       pCur->ss.iStep = 1;
4717     }else if( pCur->ss.iStep<0 ){
4718       if( (idxNum & 16)==0 ) idxNum |= 8;
4719     }
4720   }else{
4721     pCur->ss.iStep = 1;
4722   }
4723   for(i=0; i<argc; i++){
4724     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
4725       /* If any of the constraints have a NULL value, then return no rows.
4726       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
4727       pCur->ss.iBase = 1;
4728       pCur->ss.iTerm = 0;
4729       pCur->ss.iStep = 1;
4730       break;
4731     }
4732   }
4733   if( idxNum & 8 ){
4734     pCur->ss.isReversing = pCur->ss.iStep > 0;
4735   }else{
4736     pCur->ss.isReversing = pCur->ss.iStep < 0;
4737   }
4738   setupSequence( &pCur->ss );
4739   return SQLITE_OK;
4740 }
4741 
4742 /*
4743 ** SQLite will invoke this method one or more times while planning a query
4744 ** that uses the generate_series virtual table.  This routine needs to create
4745 ** a query plan for each invocation and compute an estimated cost for that
4746 ** plan.
4747 **
4748 ** In this implementation idxNum is used to represent the
4749 ** query plan.  idxStr is unused.
4750 **
4751 ** The query plan is represented by bits in idxNum:
4752 **
4753 **  (1)  start = $value  -- constraint exists
4754 **  (2)  stop = $value   -- constraint exists
4755 **  (4)  step = $value   -- constraint exists
4756 **  (8)  output in descending order
4757 */
4758 static int seriesBestIndex(
4759   sqlite3_vtab *pVTab,
4760   sqlite3_index_info *pIdxInfo
4761 ){
4762   int i, j;              /* Loop over constraints */
4763   int idxNum = 0;        /* The query plan bitmask */
4764   int bStartSeen = 0;    /* EQ constraint seen on the START column */
4765   int unusableMask = 0;  /* Mask of unusable constraints */
4766   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
4767   int aIdx[3];           /* Constraints on start, stop, and step */
4768   const struct sqlite3_index_constraint *pConstraint;
4769 
4770   /* This implementation assumes that the start, stop, and step columns
4771   ** are the last three columns in the virtual table. */
4772   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
4773   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
4774 
4775   aIdx[0] = aIdx[1] = aIdx[2] = -1;
4776   pConstraint = pIdxInfo->aConstraint;
4777   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
4778     int iCol;    /* 0 for start, 1 for stop, 2 for step */
4779     int iMask;   /* bitmask for those column */
4780     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
4781     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
4782     assert( iCol>=0 && iCol<=2 );
4783     iMask = 1 << iCol;
4784     if( iCol==0 ) bStartSeen = 1;
4785     if( pConstraint->usable==0 ){
4786       unusableMask |=  iMask;
4787       continue;
4788     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
4789       idxNum |= iMask;
4790       aIdx[iCol] = i;
4791     }
4792   }
4793   for(i=0; i<3; i++){
4794     if( (j = aIdx[i])>=0 ){
4795       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
4796       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
4797     }
4798   }
4799   /* The current generate_column() implementation requires at least one
4800   ** argument (the START value).  Legacy versions assumed START=0 if the
4801   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
4802   ** to obtain the legacy behavior */
4803 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
4804   if( !bStartSeen ){
4805     sqlite3_free(pVTab->zErrMsg);
4806     pVTab->zErrMsg = sqlite3_mprintf(
4807         "first argument to \"generate_series()\" missing or unusable");
4808     return SQLITE_ERROR;
4809   }
4810 #endif
4811   if( (unusableMask & ~idxNum)!=0 ){
4812     /* The start, stop, and step columns are inputs.  Therefore if there
4813     ** are unusable constraints on any of start, stop, or step then
4814     ** this plan is unusable */
4815     return SQLITE_CONSTRAINT;
4816   }
4817   if( (idxNum & 3)==3 ){
4818     /* Both start= and stop= boundaries are available.  This is the
4819     ** the preferred case */
4820     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
4821     pIdxInfo->estimatedRows = 1000;
4822     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
4823       if( pIdxInfo->aOrderBy[0].desc ){
4824         idxNum |= 8;
4825       }else{
4826         idxNum |= 16;
4827       }
4828       pIdxInfo->orderByConsumed = 1;
4829     }
4830   }else{
4831     /* If either boundary is missing, we have to generate a huge span
4832     ** of numbers.  Make this case very expensive so that the query
4833     ** planner will work hard to avoid it. */
4834     pIdxInfo->estimatedRows = 2147483647;
4835   }
4836   pIdxInfo->idxNum = idxNum;
4837   return SQLITE_OK;
4838 }
4839 
4840 /*
4841 ** This following structure defines all the methods for the
4842 ** generate_series virtual table.
4843 */
4844 static sqlite3_module seriesModule = {
4845   0,                         /* iVersion */
4846   0,                         /* xCreate */
4847   seriesConnect,             /* xConnect */
4848   seriesBestIndex,           /* xBestIndex */
4849   seriesDisconnect,          /* xDisconnect */
4850   0,                         /* xDestroy */
4851   seriesOpen,                /* xOpen - open a cursor */
4852   seriesClose,               /* xClose - close a cursor */
4853   seriesFilter,              /* xFilter - configure scan constraints */
4854   seriesNext,                /* xNext - advance a cursor */
4855   seriesEof,                 /* xEof - check for end of scan */
4856   seriesColumn,              /* xColumn - read data */
4857   seriesRowid,               /* xRowid - read data */
4858   0,                         /* xUpdate */
4859   0,                         /* xBegin */
4860   0,                         /* xSync */
4861   0,                         /* xCommit */
4862   0,                         /* xRollback */
4863   0,                         /* xFindMethod */
4864   0,                         /* xRename */
4865   0,                         /* xSavepoint */
4866   0,                         /* xRelease */
4867   0,                         /* xRollbackTo */
4868   0                          /* xShadowName */
4869 };
4870 
4871 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4872 
4873 #ifdef _WIN32
4874 
4875 #endif
4876 int sqlite3_series_init(
4877   sqlite3 *db,
4878   char **pzErrMsg,
4879   const sqlite3_api_routines *pApi
4880 ){
4881   int rc = SQLITE_OK;
4882   SQLITE_EXTENSION_INIT2(pApi);
4883 #ifndef SQLITE_OMIT_VIRTUALTABLE
4884   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
4885     *pzErrMsg = sqlite3_mprintf(
4886         "generate_series() requires SQLite 3.8.12 or later");
4887     return SQLITE_ERROR;
4888   }
4889   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
4890 #endif
4891   return rc;
4892 }
4893 
4894 /************************* End ../ext/misc/series.c ********************/
4895 /************************* Begin ../ext/misc/regexp.c ******************/
4896 /*
4897 ** 2012-11-13
4898 **
4899 ** The author disclaims copyright to this source code.  In place of
4900 ** a legal notice, here is a blessing:
4901 **
4902 **    May you do good and not evil.
4903 **    May you find forgiveness for yourself and forgive others.
4904 **    May you share freely, never taking more than you give.
4905 **
4906 ******************************************************************************
4907 **
4908 ** The code in this file implements a compact but reasonably
4909 ** efficient regular-expression matcher for posix extended regular
4910 ** expressions against UTF8 text.
4911 **
4912 ** This file is an SQLite extension.  It registers a single function
4913 ** named "regexp(A,B)" where A is the regular expression and B is the
4914 ** string to be matched.  By registering this function, SQLite will also
4915 ** then implement the "B regexp A" operator.  Note that with the function
4916 ** the regular expression comes first, but with the operator it comes
4917 ** second.
4918 **
4919 **  The following regular expression syntax is supported:
4920 **
4921 **     X*      zero or more occurrences of X
4922 **     X+      one or more occurrences of X
4923 **     X?      zero or one occurrences of X
4924 **     X{p,q}  between p and q occurrences of X
4925 **     (X)     match X
4926 **     X|Y     X or Y
4927 **     ^X      X occurring at the beginning of the string
4928 **     X$      X occurring at the end of the string
4929 **     .       Match any single character
4930 **     \c      Character c where c is one of \{}()[]|*+?.
4931 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
4932 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
4933 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
4934 **     [abc]   Any single character from the set abc
4935 **     [^abc]  Any single character not in the set abc
4936 **     [a-z]   Any single character in the range a-z
4937 **     [^a-z]  Any single character not in the range a-z
4938 **     \b      Word boundary
4939 **     \w      Word character.  [A-Za-z0-9_]
4940 **     \W      Non-word character
4941 **     \d      Digit
4942 **     \D      Non-digit
4943 **     \s      Whitespace character
4944 **     \S      Non-whitespace character
4945 **
4946 ** A nondeterministic finite automaton (NFA) is used for matching, so the
4947 ** performance is bounded by O(N*M) where N is the size of the regular
4948 ** expression and M is the size of the input string.  The matcher never
4949 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
4950 ** to p copies of X following by q-p copies of X? and that the size of the
4951 ** regular expression in the O(N*M) performance bound is computed after
4952 ** this expansion.
4953 */
4954 #include <string.h>
4955 #include <stdlib.h>
4956 /* #include "sqlite3ext.h" */
4957 SQLITE_EXTENSION_INIT1
4958 
4959 /*
4960 ** The following #defines change the names of some functions implemented in
4961 ** this file to prevent name collisions with C-library functions of the
4962 ** same name.
4963 */
4964 #define re_match   sqlite3re_match
4965 #define re_compile sqlite3re_compile
4966 #define re_free    sqlite3re_free
4967 
4968 /* The end-of-input character */
4969 #define RE_EOF            0    /* End of input */
4970 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
4971 
4972 /* The NFA is implemented as sequence of opcodes taken from the following
4973 ** set.  Each opcode has a single integer argument.
4974 */
4975 #define RE_OP_MATCH       1    /* Match the one character in the argument */
4976 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
4977 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
4978 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
4979 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
4980 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
4981 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
4982 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
4983 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
4984 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
4985 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
4986 #define RE_OP_NOTWORD    12    /* Not a perl word character */
4987 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
4988 #define RE_OP_NOTDIGIT   14    /* Not a digit */
4989 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
4990 #define RE_OP_NOTSPACE   16    /* Not a digit */
4991 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
4992 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
4993 
4994 #if defined(SQLITE_DEBUG)
4995 /* Opcode names used for symbolic debugging */
4996 static const char *ReOpName[] = {
4997   "EOF",
4998   "MATCH",
4999   "ANY",
5000   "ANYSTAR",
5001   "FORK",
5002   "GOTO",
5003   "ACCEPT",
5004   "CC_INC",
5005   "CC_EXC",
5006   "CC_VALUE",
5007   "CC_RANGE",
5008   "WORD",
5009   "NOTWORD",
5010   "DIGIT",
5011   "NOTDIGIT",
5012   "SPACE",
5013   "NOTSPACE",
5014   "BOUNDARY",
5015   "ATSTART",
5016 };
5017 #endif /* SQLITE_DEBUG */
5018 
5019 
5020 /* Each opcode is a "state" in the NFA */
5021 typedef unsigned short ReStateNumber;
5022 
5023 /* Because this is an NFA and not a DFA, multiple states can be active at
5024 ** once.  An instance of the following object records all active states in
5025 ** the NFA.  The implementation is optimized for the common case where the
5026 ** number of actives states is small.
5027 */
5028 typedef struct ReStateSet {
5029   unsigned nState;            /* Number of current states */
5030   ReStateNumber *aState;      /* Current states */
5031 } ReStateSet;
5032 
5033 /* An input string read one character at a time.
5034 */
5035 typedef struct ReInput ReInput;
5036 struct ReInput {
5037   const unsigned char *z;  /* All text */
5038   int i;                   /* Next byte to read */
5039   int mx;                  /* EOF when i>=mx */
5040 };
5041 
5042 /* A compiled NFA (or an NFA that is in the process of being compiled) is
5043 ** an instance of the following object.
5044 */
5045 typedef struct ReCompiled ReCompiled;
5046 struct ReCompiled {
5047   ReInput sIn;                /* Regular expression text */
5048   const char *zErr;           /* Error message to return */
5049   char *aOp;                  /* Operators for the virtual machine */
5050   int *aArg;                  /* Arguments to each operator */
5051   unsigned (*xNextChar)(ReInput*);  /* Next character function */
5052   unsigned char zInit[12];    /* Initial text to match */
5053   int nInit;                  /* Number of bytes in zInit */
5054   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
5055   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
5056 };
5057 
5058 /* Add a state to the given state set if it is not already there */
5059 static void re_add_state(ReStateSet *pSet, int newState){
5060   unsigned i;
5061   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
5062   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
5063 }
5064 
5065 /* Extract the next unicode character from *pzIn and return it.  Advance
5066 ** *pzIn to the first byte past the end of the character returned.  To
5067 ** be clear:  this routine converts utf8 to unicode.  This routine is
5068 ** optimized for the common case where the next character is a single byte.
5069 */
5070 static unsigned re_next_char(ReInput *p){
5071   unsigned c;
5072   if( p->i>=p->mx ) return 0;
5073   c = p->z[p->i++];
5074   if( c>=0x80 ){
5075     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
5076       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
5077       if( c<0x80 ) c = 0xfffd;
5078     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
5079            && (p->z[p->i+1]&0xc0)==0x80 ){
5080       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
5081       p->i += 2;
5082       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
5083     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
5084            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
5085       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
5086                        | (p->z[p->i+2]&0x3f);
5087       p->i += 3;
5088       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
5089     }else{
5090       c = 0xfffd;
5091     }
5092   }
5093   return c;
5094 }
5095 static unsigned re_next_char_nocase(ReInput *p){
5096   unsigned c = re_next_char(p);
5097   if( c>='A' && c<='Z' ) c += 'a' - 'A';
5098   return c;
5099 }
5100 
5101 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
5102 static int re_word_char(int c){
5103   return (c>='0' && c<='9') || (c>='a' && c<='z')
5104       || (c>='A' && c<='Z') || c=='_';
5105 }
5106 
5107 /* Return true if c is a "digit" character:  [0-9] */
5108 static int re_digit_char(int c){
5109   return (c>='0' && c<='9');
5110 }
5111 
5112 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
5113 static int re_space_char(int c){
5114   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
5115 }
5116 
5117 /* Run a compiled regular expression on the zero-terminated input
5118 ** string zIn[].  Return true on a match and false if there is no match.
5119 */
5120 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
5121   ReStateSet aStateSet[2], *pThis, *pNext;
5122   ReStateNumber aSpace[100];
5123   ReStateNumber *pToFree;
5124   unsigned int i = 0;
5125   unsigned int iSwap = 0;
5126   int c = RE_START;
5127   int cPrev = 0;
5128   int rc = 0;
5129   ReInput in;
5130 
5131   in.z = zIn;
5132   in.i = 0;
5133   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
5134 
5135   /* Look for the initial prefix match, if there is one. */
5136   if( pRe->nInit ){
5137     unsigned char x = pRe->zInit[0];
5138     while( in.i+pRe->nInit<=in.mx
5139      && (zIn[in.i]!=x ||
5140          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
5141     ){
5142       in.i++;
5143     }
5144     if( in.i+pRe->nInit>in.mx ) return 0;
5145     c = RE_START-1;
5146   }
5147 
5148   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
5149     pToFree = 0;
5150     aStateSet[0].aState = aSpace;
5151   }else{
5152     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
5153     if( pToFree==0 ) return -1;
5154     aStateSet[0].aState = pToFree;
5155   }
5156   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
5157   pNext = &aStateSet[1];
5158   pNext->nState = 0;
5159   re_add_state(pNext, 0);
5160   while( c!=RE_EOF && pNext->nState>0 ){
5161     cPrev = c;
5162     c = pRe->xNextChar(&in);
5163     pThis = pNext;
5164     pNext = &aStateSet[iSwap];
5165     iSwap = 1 - iSwap;
5166     pNext->nState = 0;
5167     for(i=0; i<pThis->nState; i++){
5168       int x = pThis->aState[i];
5169       switch( pRe->aOp[x] ){
5170         case RE_OP_MATCH: {
5171           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
5172           break;
5173         }
5174         case RE_OP_ATSTART: {
5175           if( cPrev==RE_START ) re_add_state(pThis, x+1);
5176           break;
5177         }
5178         case RE_OP_ANY: {
5179           if( c!=0 ) re_add_state(pNext, x+1);
5180           break;
5181         }
5182         case RE_OP_WORD: {
5183           if( re_word_char(c) ) re_add_state(pNext, x+1);
5184           break;
5185         }
5186         case RE_OP_NOTWORD: {
5187           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
5188           break;
5189         }
5190         case RE_OP_DIGIT: {
5191           if( re_digit_char(c) ) re_add_state(pNext, x+1);
5192           break;
5193         }
5194         case RE_OP_NOTDIGIT: {
5195           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
5196           break;
5197         }
5198         case RE_OP_SPACE: {
5199           if( re_space_char(c) ) re_add_state(pNext, x+1);
5200           break;
5201         }
5202         case RE_OP_NOTSPACE: {
5203           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
5204           break;
5205         }
5206         case RE_OP_BOUNDARY: {
5207           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
5208           break;
5209         }
5210         case RE_OP_ANYSTAR: {
5211           re_add_state(pNext, x);
5212           re_add_state(pThis, x+1);
5213           break;
5214         }
5215         case RE_OP_FORK: {
5216           re_add_state(pThis, x+pRe->aArg[x]);
5217           re_add_state(pThis, x+1);
5218           break;
5219         }
5220         case RE_OP_GOTO: {
5221           re_add_state(pThis, x+pRe->aArg[x]);
5222           break;
5223         }
5224         case RE_OP_ACCEPT: {
5225           rc = 1;
5226           goto re_match_end;
5227         }
5228         case RE_OP_CC_EXC: {
5229           if( c==0 ) break;
5230           /* fall-through */ goto re_op_cc_inc;
5231         }
5232         case RE_OP_CC_INC: re_op_cc_inc: {
5233           int j = 1;
5234           int n = pRe->aArg[x];
5235           int hit = 0;
5236           for(j=1; j>0 && j<n; j++){
5237             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
5238               if( pRe->aArg[x+j]==c ){
5239                 hit = 1;
5240                 j = -1;
5241               }
5242             }else{
5243               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
5244                 hit = 1;
5245                 j = -1;
5246               }else{
5247                 j++;
5248               }
5249             }
5250           }
5251           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
5252           if( hit ) re_add_state(pNext, x+n);
5253           break;
5254         }
5255       }
5256     }
5257   }
5258   for(i=0; i<pNext->nState; i++){
5259     int x = pNext->aState[i];
5260     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
5261     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
5262   }
5263 re_match_end:
5264   sqlite3_free(pToFree);
5265   return rc;
5266 }
5267 
5268 /* Resize the opcode and argument arrays for an RE under construction.
5269 */
5270 static int re_resize(ReCompiled *p, int N){
5271   char *aOp;
5272   int *aArg;
5273   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
5274   if( aOp==0 ) return 1;
5275   p->aOp = aOp;
5276   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
5277   if( aArg==0 ) return 1;
5278   p->aArg = aArg;
5279   p->nAlloc = N;
5280   return 0;
5281 }
5282 
5283 /* Insert a new opcode and argument into an RE under construction.  The
5284 ** insertion point is just prior to existing opcode iBefore.
5285 */
5286 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
5287   int i;
5288   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
5289   for(i=p->nState; i>iBefore; i--){
5290     p->aOp[i] = p->aOp[i-1];
5291     p->aArg[i] = p->aArg[i-1];
5292   }
5293   p->nState++;
5294   p->aOp[iBefore] = (char)op;
5295   p->aArg[iBefore] = arg;
5296   return iBefore;
5297 }
5298 
5299 /* Append a new opcode and argument to the end of the RE under construction.
5300 */
5301 static int re_append(ReCompiled *p, int op, int arg){
5302   return re_insert(p, p->nState, op, arg);
5303 }
5304 
5305 /* Make a copy of N opcodes starting at iStart onto the end of the RE
5306 ** under construction.
5307 */
5308 static void re_copy(ReCompiled *p, int iStart, int N){
5309   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
5310   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
5311   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
5312   p->nState += N;
5313 }
5314 
5315 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
5316 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
5317 ** c is not a hex digit *pV is unchanged.
5318 */
5319 static int re_hex(int c, int *pV){
5320   if( c>='0' && c<='9' ){
5321     c -= '0';
5322   }else if( c>='a' && c<='f' ){
5323     c -= 'a' - 10;
5324   }else if( c>='A' && c<='F' ){
5325     c -= 'A' - 10;
5326   }else{
5327     return 0;
5328   }
5329   *pV = (*pV)*16 + (c & 0xff);
5330   return 1;
5331 }
5332 
5333 /* A backslash character has been seen, read the next character and
5334 ** return its interpretation.
5335 */
5336 static unsigned re_esc_char(ReCompiled *p){
5337   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
5338   static const char zTrans[] = "\a\f\n\r\t\v";
5339   int i, v = 0;
5340   char c;
5341   if( p->sIn.i>=p->sIn.mx ) return 0;
5342   c = p->sIn.z[p->sIn.i];
5343   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
5344     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5345     if( re_hex(zIn[1],&v)
5346      && re_hex(zIn[2],&v)
5347      && re_hex(zIn[3],&v)
5348      && re_hex(zIn[4],&v)
5349     ){
5350       p->sIn.i += 5;
5351       return v;
5352     }
5353   }
5354   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
5355     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5356     if( re_hex(zIn[1],&v)
5357      && re_hex(zIn[2],&v)
5358     ){
5359       p->sIn.i += 3;
5360       return v;
5361     }
5362   }
5363   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
5364   if( zEsc[i] ){
5365     if( i<6 ) c = zTrans[i];
5366     p->sIn.i++;
5367   }else{
5368     p->zErr = "unknown \\ escape";
5369   }
5370   return c;
5371 }
5372 
5373 /* Forward declaration */
5374 static const char *re_subcompile_string(ReCompiled*);
5375 
5376 /* Peek at the next byte of input */
5377 static unsigned char rePeek(ReCompiled *p){
5378   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
5379 }
5380 
5381 /* Compile RE text into a sequence of opcodes.  Continue up to the
5382 ** first unmatched ")" character, then return.  If an error is found,
5383 ** return a pointer to the error message string.
5384 */
5385 static const char *re_subcompile_re(ReCompiled *p){
5386   const char *zErr;
5387   int iStart, iEnd, iGoto;
5388   iStart = p->nState;
5389   zErr = re_subcompile_string(p);
5390   if( zErr ) return zErr;
5391   while( rePeek(p)=='|' ){
5392     iEnd = p->nState;
5393     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
5394     iGoto = re_append(p, RE_OP_GOTO, 0);
5395     p->sIn.i++;
5396     zErr = re_subcompile_string(p);
5397     if( zErr ) return zErr;
5398     p->aArg[iGoto] = p->nState - iGoto;
5399   }
5400   return 0;
5401 }
5402 
5403 /* Compile an element of regular expression text (anything that can be
5404 ** an operand to the "|" operator).  Return NULL on success or a pointer
5405 ** to the error message if there is a problem.
5406 */
5407 static const char *re_subcompile_string(ReCompiled *p){
5408   int iPrev = -1;
5409   int iStart;
5410   unsigned c;
5411   const char *zErr;
5412   while( (c = p->xNextChar(&p->sIn))!=0 ){
5413     iStart = p->nState;
5414     switch( c ){
5415       case '|':
5416       case ')': {
5417         p->sIn.i--;
5418         return 0;
5419       }
5420       case '(': {
5421         zErr = re_subcompile_re(p);
5422         if( zErr ) return zErr;
5423         if( rePeek(p)!=')' ) return "unmatched '('";
5424         p->sIn.i++;
5425         break;
5426       }
5427       case '.': {
5428         if( rePeek(p)=='*' ){
5429           re_append(p, RE_OP_ANYSTAR, 0);
5430           p->sIn.i++;
5431         }else{
5432           re_append(p, RE_OP_ANY, 0);
5433         }
5434         break;
5435       }
5436       case '*': {
5437         if( iPrev<0 ) return "'*' without operand";
5438         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
5439         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
5440         break;
5441       }
5442       case '+': {
5443         if( iPrev<0 ) return "'+' without operand";
5444         re_append(p, RE_OP_FORK, iPrev - p->nState);
5445         break;
5446       }
5447       case '?': {
5448         if( iPrev<0 ) return "'?' without operand";
5449         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
5450         break;
5451       }
5452       case '$': {
5453         re_append(p, RE_OP_MATCH, RE_EOF);
5454         break;
5455       }
5456       case '^': {
5457         re_append(p, RE_OP_ATSTART, 0);
5458         break;
5459       }
5460       case '{': {
5461         int m = 0, n = 0;
5462         int sz, j;
5463         if( iPrev<0 ) return "'{m,n}' without operand";
5464         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
5465         n = m;
5466         if( c==',' ){
5467           p->sIn.i++;
5468           n = 0;
5469           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
5470         }
5471         if( c!='}' ) return "unmatched '{'";
5472         if( n>0 && n<m ) return "n less than m in '{m,n}'";
5473         p->sIn.i++;
5474         sz = p->nState - iPrev;
5475         if( m==0 ){
5476           if( n==0 ) return "both m and n are zero in '{m,n}'";
5477           re_insert(p, iPrev, RE_OP_FORK, sz+1);
5478           iPrev++;
5479           n--;
5480         }else{
5481           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
5482         }
5483         for(j=m; j<n; j++){
5484           re_append(p, RE_OP_FORK, sz+1);
5485           re_copy(p, iPrev, sz);
5486         }
5487         if( n==0 && m>0 ){
5488           re_append(p, RE_OP_FORK, -sz);
5489         }
5490         break;
5491       }
5492       case '[': {
5493         unsigned int iFirst = p->nState;
5494         if( rePeek(p)=='^' ){
5495           re_append(p, RE_OP_CC_EXC, 0);
5496           p->sIn.i++;
5497         }else{
5498           re_append(p, RE_OP_CC_INC, 0);
5499         }
5500         while( (c = p->xNextChar(&p->sIn))!=0 ){
5501           if( c=='[' && rePeek(p)==':' ){
5502             return "POSIX character classes not supported";
5503           }
5504           if( c=='\\' ) c = re_esc_char(p);
5505           if( rePeek(p)=='-' ){
5506             re_append(p, RE_OP_CC_RANGE, c);
5507             p->sIn.i++;
5508             c = p->xNextChar(&p->sIn);
5509             if( c=='\\' ) c = re_esc_char(p);
5510             re_append(p, RE_OP_CC_RANGE, c);
5511           }else{
5512             re_append(p, RE_OP_CC_VALUE, c);
5513           }
5514           if( rePeek(p)==']' ){ p->sIn.i++; break; }
5515         }
5516         if( c==0 ) return "unclosed '['";
5517         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
5518         break;
5519       }
5520       case '\\': {
5521         int specialOp = 0;
5522         switch( rePeek(p) ){
5523           case 'b': specialOp = RE_OP_BOUNDARY;   break;
5524           case 'd': specialOp = RE_OP_DIGIT;      break;
5525           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
5526           case 's': specialOp = RE_OP_SPACE;      break;
5527           case 'S': specialOp = RE_OP_NOTSPACE;   break;
5528           case 'w': specialOp = RE_OP_WORD;       break;
5529           case 'W': specialOp = RE_OP_NOTWORD;    break;
5530         }
5531         if( specialOp ){
5532           p->sIn.i++;
5533           re_append(p, specialOp, 0);
5534         }else{
5535           c = re_esc_char(p);
5536           re_append(p, RE_OP_MATCH, c);
5537         }
5538         break;
5539       }
5540       default: {
5541         re_append(p, RE_OP_MATCH, c);
5542         break;
5543       }
5544     }
5545     iPrev = iStart;
5546   }
5547   return 0;
5548 }
5549 
5550 /* Free and reclaim all the memory used by a previously compiled
5551 ** regular expression.  Applications should invoke this routine once
5552 ** for every call to re_compile() to avoid memory leaks.
5553 */
5554 static void re_free(ReCompiled *pRe){
5555   if( pRe ){
5556     sqlite3_free(pRe->aOp);
5557     sqlite3_free(pRe->aArg);
5558     sqlite3_free(pRe);
5559   }
5560 }
5561 
5562 /*
5563 ** Compile a textual regular expression in zIn[] into a compiled regular
5564 ** expression suitable for us by re_match() and return a pointer to the
5565 ** compiled regular expression in *ppRe.  Return NULL on success or an
5566 ** error message if something goes wrong.
5567 */
5568 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
5569   ReCompiled *pRe;
5570   const char *zErr;
5571   int i, j;
5572 
5573   *ppRe = 0;
5574   pRe = sqlite3_malloc( sizeof(*pRe) );
5575   if( pRe==0 ){
5576     return "out of memory";
5577   }
5578   memset(pRe, 0, sizeof(*pRe));
5579   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
5580   if( re_resize(pRe, 30) ){
5581     re_free(pRe);
5582     return "out of memory";
5583   }
5584   if( zIn[0]=='^' ){
5585     zIn++;
5586   }else{
5587     re_append(pRe, RE_OP_ANYSTAR, 0);
5588   }
5589   pRe->sIn.z = (unsigned char*)zIn;
5590   pRe->sIn.i = 0;
5591   pRe->sIn.mx = (int)strlen(zIn);
5592   zErr = re_subcompile_re(pRe);
5593   if( zErr ){
5594     re_free(pRe);
5595     return zErr;
5596   }
5597   if( pRe->sIn.i>=pRe->sIn.mx ){
5598     re_append(pRe, RE_OP_ACCEPT, 0);
5599     *ppRe = pRe;
5600   }else{
5601     re_free(pRe);
5602     return "unrecognized character";
5603   }
5604 
5605   /* The following is a performance optimization.  If the regex begins with
5606   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
5607   ** one or more matching characters, enter those matching characters into
5608   ** zInit[].  The re_match() routine can then search ahead in the input
5609   ** string looking for the initial match without having to run the whole
5610   ** regex engine over the string.  Do not worry about trying to match
5611   ** unicode characters beyond plane 0 - those are very rare and this is
5612   ** just an optimization. */
5613   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
5614     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
5615       unsigned x = pRe->aArg[i];
5616       if( x<=0x7f ){
5617         pRe->zInit[j++] = (unsigned char)x;
5618       }else if( x<=0x7ff ){
5619         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
5620         pRe->zInit[j++] = 0x80 | (x&0x3f);
5621       }else if( x<=0xffff ){
5622         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
5623         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
5624         pRe->zInit[j++] = 0x80 | (x&0x3f);
5625       }else{
5626         break;
5627       }
5628     }
5629     if( j>0 && pRe->zInit[j-1]==0 ) j--;
5630     pRe->nInit = j;
5631   }
5632   return pRe->zErr;
5633 }
5634 
5635 /*
5636 ** Implementation of the regexp() SQL function.  This function implements
5637 ** the build-in REGEXP operator.  The first argument to the function is the
5638 ** pattern and the second argument is the string.  So, the SQL statements:
5639 **
5640 **       A REGEXP B
5641 **
5642 ** is implemented as regexp(B,A).
5643 */
5644 static void re_sql_func(
5645   sqlite3_context *context,
5646   int argc,
5647   sqlite3_value **argv
5648 ){
5649   ReCompiled *pRe;          /* Compiled regular expression */
5650   const char *zPattern;     /* The regular expression */
5651   const unsigned char *zStr;/* String being searched */
5652   const char *zErr;         /* Compile error message */
5653   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
5654 
5655   (void)argc;  /* Unused */
5656   pRe = sqlite3_get_auxdata(context, 0);
5657   if( pRe==0 ){
5658     zPattern = (const char*)sqlite3_value_text(argv[0]);
5659     if( zPattern==0 ) return;
5660     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
5661     if( zErr ){
5662       re_free(pRe);
5663       sqlite3_result_error(context, zErr, -1);
5664       return;
5665     }
5666     if( pRe==0 ){
5667       sqlite3_result_error_nomem(context);
5668       return;
5669     }
5670     setAux = 1;
5671   }
5672   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
5673   if( zStr!=0 ){
5674     sqlite3_result_int(context, re_match(pRe, zStr, -1));
5675   }
5676   if( setAux ){
5677     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
5678   }
5679 }
5680 
5681 #if defined(SQLITE_DEBUG)
5682 /*
5683 ** This function is used for testing and debugging only.  It is only available
5684 ** if the SQLITE_DEBUG compile-time option is used.
5685 **
5686 ** Compile a regular expression and then convert the compiled expression into
5687 ** text and return that text.
5688 */
5689 static void re_bytecode_func(
5690   sqlite3_context *context,
5691   int argc,
5692   sqlite3_value **argv
5693 ){
5694   const char *zPattern;
5695   const char *zErr;
5696   ReCompiled *pRe;
5697   sqlite3_str *pStr;
5698   int i;
5699   int n;
5700   char *z;
5701   (void)argc;
5702 
5703   zPattern = (const char*)sqlite3_value_text(argv[0]);
5704   if( zPattern==0 ) return;
5705   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
5706   if( zErr ){
5707     re_free(pRe);
5708     sqlite3_result_error(context, zErr, -1);
5709     return;
5710   }
5711   if( pRe==0 ){
5712     sqlite3_result_error_nomem(context);
5713     return;
5714   }
5715   pStr = sqlite3_str_new(0);
5716   if( pStr==0 ) goto re_bytecode_func_err;
5717   if( pRe->nInit>0 ){
5718     sqlite3_str_appendf(pStr, "INIT     ");
5719     for(i=0; i<pRe->nInit; i++){
5720       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
5721     }
5722     sqlite3_str_appendf(pStr, "\n");
5723   }
5724   for(i=0; (unsigned)i<pRe->nState; i++){
5725     sqlite3_str_appendf(pStr, "%-8s %4d\n",
5726          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
5727   }
5728   n = sqlite3_str_length(pStr);
5729   z = sqlite3_str_finish(pStr);
5730   if( n==0 ){
5731     sqlite3_free(z);
5732   }else{
5733     sqlite3_result_text(context, z, n-1, sqlite3_free);
5734   }
5735 
5736 re_bytecode_func_err:
5737   re_free(pRe);
5738 }
5739 
5740 #endif /* SQLITE_DEBUG */
5741 
5742 
5743 /*
5744 ** Invoke this routine to register the regexp() function with the
5745 ** SQLite database connection.
5746 */
5747 #ifdef _WIN32
5748 
5749 #endif
5750 int sqlite3_regexp_init(
5751   sqlite3 *db,
5752   char **pzErrMsg,
5753   const sqlite3_api_routines *pApi
5754 ){
5755   int rc = SQLITE_OK;
5756   SQLITE_EXTENSION_INIT2(pApi);
5757   (void)pzErrMsg;  /* Unused */
5758   rc = sqlite3_create_function(db, "regexp", 2,
5759                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5760                             0, re_sql_func, 0, 0);
5761   if( rc==SQLITE_OK ){
5762     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
5763     ** of regexp(PATTERN,STRING). */
5764     rc = sqlite3_create_function(db, "regexpi", 2,
5765                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5766                             (void*)db, re_sql_func, 0, 0);
5767 #if defined(SQLITE_DEBUG)
5768     if( rc==SQLITE_OK ){
5769       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
5770                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5771                             0, re_bytecode_func, 0, 0);
5772     }
5773 #endif /* SQLITE_DEBUG */
5774   }
5775   return rc;
5776 }
5777 
5778 /************************* End ../ext/misc/regexp.c ********************/
5779 #ifndef SQLITE_SHELL_FIDDLE
5780 /************************* Begin ../ext/misc/fileio.c ******************/
5781 /*
5782 ** 2014-06-13
5783 **
5784 ** The author disclaims copyright to this source code.  In place of
5785 ** a legal notice, here is a blessing:
5786 **
5787 **    May you do good and not evil.
5788 **    May you find forgiveness for yourself and forgive others.
5789 **    May you share freely, never taking more than you give.
5790 **
5791 ******************************************************************************
5792 **
5793 ** This SQLite extension implements SQL functions readfile() and
5794 ** writefile(), and eponymous virtual type "fsdir".
5795 **
5796 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
5797 **
5798 **   If neither of the optional arguments is present, then this UDF
5799 **   function writes blob DATA to file FILE. If successful, the number
5800 **   of bytes written is returned. If an error occurs, NULL is returned.
5801 **
5802 **   If the first option argument - MODE - is present, then it must
5803 **   be passed an integer value that corresponds to a POSIX mode
5804 **   value (file type + permissions, as returned in the stat.st_mode
5805 **   field by the stat() system call). Three types of files may
5806 **   be written/created:
5807 **
5808 **     regular files:  (mode & 0170000)==0100000
5809 **     symbolic links: (mode & 0170000)==0120000
5810 **     directories:    (mode & 0170000)==0040000
5811 **
5812 **   For a directory, the DATA is ignored. For a symbolic link, it is
5813 **   interpreted as text and used as the target of the link. For a
5814 **   regular file, it is interpreted as a blob and written into the
5815 **   named file. Regardless of the type of file, its permissions are
5816 **   set to (mode & 0777) before returning.
5817 **
5818 **   If the optional MTIME argument is present, then it is interpreted
5819 **   as an integer - the number of seconds since the unix epoch. The
5820 **   modification-time of the target file is set to this value before
5821 **   returning.
5822 **
5823 **   If three or more arguments are passed to this function and an
5824 **   error is encountered, an exception is raised.
5825 **
5826 ** READFILE(FILE):
5827 **
5828 **   Read and return the contents of file FILE (type blob) from disk.
5829 **
5830 ** FSDIR:
5831 **
5832 **   Used as follows:
5833 **
5834 **     SELECT * FROM fsdir($path [, $dir]);
5835 **
5836 **   Parameter $path is an absolute or relative pathname. If the file that it
5837 **   refers to does not exist, it is an error. If the path refers to a regular
5838 **   file or symbolic link, it returns a single row. Or, if the path refers
5839 **   to a directory, it returns one row for the directory, and one row for each
5840 **   file within the hierarchy rooted at $path.
5841 **
5842 **   Each row has the following columns:
5843 **
5844 **     name:  Path to file or directory (text value).
5845 **     mode:  Value of stat.st_mode for directory entry (an integer).
5846 **     mtime: Value of stat.st_mtime for directory entry (an integer).
5847 **     data:  For a regular file, a blob containing the file data. For a
5848 **            symlink, a text value containing the text of the link. For a
5849 **            directory, NULL.
5850 **
5851 **   If a non-NULL value is specified for the optional $dir parameter and
5852 **   $path is a relative path, then $path is interpreted relative to $dir.
5853 **   And the paths returned in the "name" column of the table are also
5854 **   relative to directory $dir.
5855 **
5856 ** Notes on building this extension for Windows:
5857 **   Unless linked statically with the SQLite library, a preprocessor
5858 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
5859 **   DLL form of this extension for WIN32. See its use below for details.
5860 */
5861 /* #include "sqlite3ext.h" */
5862 SQLITE_EXTENSION_INIT1
5863 #include <stdio.h>
5864 #include <string.h>
5865 #include <assert.h>
5866 
5867 #include <sys/types.h>
5868 #include <sys/stat.h>
5869 #include <fcntl.h>
5870 #if !defined(_WIN32) && !defined(WIN32)
5871 #  include <unistd.h>
5872 #  include <dirent.h>
5873 #  include <utime.h>
5874 #  include <sys/time.h>
5875 #else
5876 #  include "windows.h"
5877 #  include <io.h>
5878 #  include <direct.h>
5879 /* #  include "test_windirent.h" */
5880 #  define dirent DIRENT
5881 #  ifndef chmod
5882 #    define chmod _chmod
5883 #  endif
5884 #  ifndef stat
5885 #    define stat _stat
5886 #  endif
5887 #  define mkdir(path,mode) _mkdir(path)
5888 #  define lstat(path,buf) stat(path,buf)
5889 #endif
5890 #include <time.h>
5891 #include <errno.h>
5892 
5893 
5894 /*
5895 ** Structure of the fsdir() table-valued function
5896 */
5897                  /*    0    1    2     3    4           5             */
5898 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
5899 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
5900 #define FSDIR_COLUMN_MODE     1     /* Access mode */
5901 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
5902 #define FSDIR_COLUMN_DATA     3     /* File content */
5903 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
5904 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
5905 
5906 
5907 /*
5908 ** Set the result stored by context ctx to a blob containing the
5909 ** contents of file zName.  Or, leave the result unchanged (NULL)
5910 ** if the file does not exist or is unreadable.
5911 **
5912 ** If the file exceeds the SQLite blob size limit, through an
5913 ** SQLITE_TOOBIG error.
5914 **
5915 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
5916 ** off of disk.
5917 */
5918 static void readFileContents(sqlite3_context *ctx, const char *zName){
5919   FILE *in;
5920   sqlite3_int64 nIn;
5921   void *pBuf;
5922   sqlite3 *db;
5923   int mxBlob;
5924 
5925   in = fopen(zName, "rb");
5926   if( in==0 ){
5927     /* File does not exist or is unreadable. Leave the result set to NULL. */
5928     return;
5929   }
5930   fseek(in, 0, SEEK_END);
5931   nIn = ftell(in);
5932   rewind(in);
5933   db = sqlite3_context_db_handle(ctx);
5934   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
5935   if( nIn>mxBlob ){
5936     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
5937     fclose(in);
5938     return;
5939   }
5940   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
5941   if( pBuf==0 ){
5942     sqlite3_result_error_nomem(ctx);
5943     fclose(in);
5944     return;
5945   }
5946   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
5947     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
5948   }else{
5949     sqlite3_result_error_code(ctx, SQLITE_IOERR);
5950     sqlite3_free(pBuf);
5951   }
5952   fclose(in);
5953 }
5954 
5955 /*
5956 ** Implementation of the "readfile(X)" SQL function.  The entire content
5957 ** of the file named X is read and returned as a BLOB.  NULL is returned
5958 ** if the file does not exist or is unreadable.
5959 */
5960 static void readfileFunc(
5961   sqlite3_context *context,
5962   int argc,
5963   sqlite3_value **argv
5964 ){
5965   const char *zName;
5966   (void)(argc);  /* Unused parameter */
5967   zName = (const char*)sqlite3_value_text(argv[0]);
5968   if( zName==0 ) return;
5969   readFileContents(context, zName);
5970 }
5971 
5972 /*
5973 ** Set the error message contained in context ctx to the results of
5974 ** vprintf(zFmt, ...).
5975 */
5976 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
5977   char *zMsg = 0;
5978   va_list ap;
5979   va_start(ap, zFmt);
5980   zMsg = sqlite3_vmprintf(zFmt, ap);
5981   sqlite3_result_error(ctx, zMsg, -1);
5982   sqlite3_free(zMsg);
5983   va_end(ap);
5984 }
5985 
5986 #if defined(_WIN32)
5987 /*
5988 ** This function is designed to convert a Win32 FILETIME structure into the
5989 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
5990 */
5991 static sqlite3_uint64 fileTimeToUnixTime(
5992   LPFILETIME pFileTime
5993 ){
5994   SYSTEMTIME epochSystemTime;
5995   ULARGE_INTEGER epochIntervals;
5996   FILETIME epochFileTime;
5997   ULARGE_INTEGER fileIntervals;
5998 
5999   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
6000   epochSystemTime.wYear = 1970;
6001   epochSystemTime.wMonth = 1;
6002   epochSystemTime.wDay = 1;
6003   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
6004   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
6005   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
6006 
6007   fileIntervals.LowPart = pFileTime->dwLowDateTime;
6008   fileIntervals.HighPart = pFileTime->dwHighDateTime;
6009 
6010   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
6011 }
6012 
6013 
6014 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
6015 #  /* To allow a standalone DLL, use this next replacement function: */
6016 #  undef sqlite3_win32_utf8_to_unicode
6017 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
6018 #
6019 LPWSTR utf8_to_utf16(const char *z){
6020   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
6021   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
6022   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
6023     return rv;
6024   sqlite3_free(rv);
6025   return 0;
6026 }
6027 #endif
6028 
6029 /*
6030 ** This function attempts to normalize the time values found in the stat()
6031 ** buffer to UTC.  This is necessary on Win32, where the runtime library
6032 ** appears to return these values as local times.
6033 */
6034 static void statTimesToUtc(
6035   const char *zPath,
6036   struct stat *pStatBuf
6037 ){
6038   HANDLE hFindFile;
6039   WIN32_FIND_DATAW fd;
6040   LPWSTR zUnicodeName;
6041   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
6042   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
6043   if( zUnicodeName ){
6044     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
6045     hFindFile = FindFirstFileW(zUnicodeName, &fd);
6046     if( hFindFile!=NULL ){
6047       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
6048       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
6049       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
6050       FindClose(hFindFile);
6051     }
6052     sqlite3_free(zUnicodeName);
6053   }
6054 }
6055 #endif
6056 
6057 /*
6058 ** This function is used in place of stat().  On Windows, special handling
6059 ** is required in order for the included time to be returned as UTC.  On all
6060 ** other systems, this function simply calls stat().
6061 */
6062 static int fileStat(
6063   const char *zPath,
6064   struct stat *pStatBuf
6065 ){
6066 #if defined(_WIN32)
6067   int rc = stat(zPath, pStatBuf);
6068   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
6069   return rc;
6070 #else
6071   return stat(zPath, pStatBuf);
6072 #endif
6073 }
6074 
6075 /*
6076 ** This function is used in place of lstat().  On Windows, special handling
6077 ** is required in order for the included time to be returned as UTC.  On all
6078 ** other systems, this function simply calls lstat().
6079 */
6080 static int fileLinkStat(
6081   const char *zPath,
6082   struct stat *pStatBuf
6083 ){
6084 #if defined(_WIN32)
6085   int rc = lstat(zPath, pStatBuf);
6086   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
6087   return rc;
6088 #else
6089   return lstat(zPath, pStatBuf);
6090 #endif
6091 }
6092 
6093 /*
6094 ** Argument zFile is the name of a file that will be created and/or written
6095 ** by SQL function writefile(). This function ensures that the directory
6096 ** zFile will be written to exists, creating it if required. The permissions
6097 ** for any path components created by this function are set in accordance
6098 ** with the current umask.
6099 **
6100 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
6101 ** SQLITE_OK is returned if the directory is successfully created, or
6102 ** SQLITE_ERROR otherwise.
6103 */
6104 static int makeDirectory(
6105   const char *zFile
6106 ){
6107   char *zCopy = sqlite3_mprintf("%s", zFile);
6108   int rc = SQLITE_OK;
6109 
6110   if( zCopy==0 ){
6111     rc = SQLITE_NOMEM;
6112   }else{
6113     int nCopy = (int)strlen(zCopy);
6114     int i = 1;
6115 
6116     while( rc==SQLITE_OK ){
6117       struct stat sStat;
6118       int rc2;
6119 
6120       for(; zCopy[i]!='/' && i<nCopy; i++);
6121       if( i==nCopy ) break;
6122       zCopy[i] = '\0';
6123 
6124       rc2 = fileStat(zCopy, &sStat);
6125       if( rc2!=0 ){
6126         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
6127       }else{
6128         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
6129       }
6130       zCopy[i] = '/';
6131       i++;
6132     }
6133 
6134     sqlite3_free(zCopy);
6135   }
6136 
6137   return rc;
6138 }
6139 
6140 /*
6141 ** This function does the work for the writefile() UDF. Refer to
6142 ** header comments at the top of this file for details.
6143 */
6144 static int writeFile(
6145   sqlite3_context *pCtx,          /* Context to return bytes written in */
6146   const char *zFile,              /* File to write */
6147   sqlite3_value *pData,           /* Data to write */
6148   mode_t mode,                    /* MODE parameter passed to writefile() */
6149   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
6150 ){
6151   if( zFile==0 ) return 1;
6152 #if !defined(_WIN32) && !defined(WIN32)
6153   if( S_ISLNK(mode) ){
6154     const char *zTo = (const char*)sqlite3_value_text(pData);
6155     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
6156   }else
6157 #endif
6158   {
6159     if( S_ISDIR(mode) ){
6160       if( mkdir(zFile, mode) ){
6161         /* The mkdir() call to create the directory failed. This might not
6162         ** be an error though - if there is already a directory at the same
6163         ** path and either the permissions already match or can be changed
6164         ** to do so using chmod(), it is not an error.  */
6165         struct stat sStat;
6166         if( errno!=EEXIST
6167          || 0!=fileStat(zFile, &sStat)
6168          || !S_ISDIR(sStat.st_mode)
6169          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
6170         ){
6171           return 1;
6172         }
6173       }
6174     }else{
6175       sqlite3_int64 nWrite = 0;
6176       const char *z;
6177       int rc = 0;
6178       FILE *out = fopen(zFile, "wb");
6179       if( out==0 ) return 1;
6180       z = (const char*)sqlite3_value_blob(pData);
6181       if( z ){
6182         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
6183         nWrite = sqlite3_value_bytes(pData);
6184         if( nWrite!=n ){
6185           rc = 1;
6186         }
6187       }
6188       fclose(out);
6189       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
6190         rc = 1;
6191       }
6192       if( rc ) return 2;
6193       sqlite3_result_int64(pCtx, nWrite);
6194     }
6195   }
6196 
6197   if( mtime>=0 ){
6198 #if defined(_WIN32)
6199 #if !SQLITE_OS_WINRT
6200     /* Windows */
6201     FILETIME lastAccess;
6202     FILETIME lastWrite;
6203     SYSTEMTIME currentTime;
6204     LONGLONG intervals;
6205     HANDLE hFile;
6206     LPWSTR zUnicodeName;
6207     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
6208 
6209     GetSystemTime(&currentTime);
6210     SystemTimeToFileTime(&currentTime, &lastAccess);
6211     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
6212     lastWrite.dwLowDateTime = (DWORD)intervals;
6213     lastWrite.dwHighDateTime = intervals >> 32;
6214     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
6215     if( zUnicodeName==0 ){
6216       return 1;
6217     }
6218     hFile = CreateFileW(
6219       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
6220       FILE_FLAG_BACKUP_SEMANTICS, NULL
6221     );
6222     sqlite3_free(zUnicodeName);
6223     if( hFile!=INVALID_HANDLE_VALUE ){
6224       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
6225       CloseHandle(hFile);
6226       return !bResult;
6227     }else{
6228       return 1;
6229     }
6230 #endif
6231 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
6232     /* Recent unix */
6233     struct timespec times[2];
6234     times[0].tv_nsec = times[1].tv_nsec = 0;
6235     times[0].tv_sec = time(0);
6236     times[1].tv_sec = mtime;
6237     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
6238       return 1;
6239     }
6240 #else
6241     /* Legacy unix */
6242     struct timeval times[2];
6243     times[0].tv_usec = times[1].tv_usec = 0;
6244     times[0].tv_sec = time(0);
6245     times[1].tv_sec = mtime;
6246     if( utimes(zFile, times) ){
6247       return 1;
6248     }
6249 #endif
6250   }
6251 
6252   return 0;
6253 }
6254 
6255 /*
6256 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
6257 ** Refer to header comments at the top of this file for details.
6258 */
6259 static void writefileFunc(
6260   sqlite3_context *context,
6261   int argc,
6262   sqlite3_value **argv
6263 ){
6264   const char *zFile;
6265   mode_t mode = 0;
6266   int res;
6267   sqlite3_int64 mtime = -1;
6268 
6269   if( argc<2 || argc>4 ){
6270     sqlite3_result_error(context,
6271         "wrong number of arguments to function writefile()", -1
6272     );
6273     return;
6274   }
6275 
6276   zFile = (const char*)sqlite3_value_text(argv[0]);
6277   if( zFile==0 ) return;
6278   if( argc>=3 ){
6279     mode = (mode_t)sqlite3_value_int(argv[2]);
6280   }
6281   if( argc==4 ){
6282     mtime = sqlite3_value_int64(argv[3]);
6283   }
6284 
6285   res = writeFile(context, zFile, argv[1], mode, mtime);
6286   if( res==1 && errno==ENOENT ){
6287     if( makeDirectory(zFile)==SQLITE_OK ){
6288       res = writeFile(context, zFile, argv[1], mode, mtime);
6289     }
6290   }
6291 
6292   if( argc>2 && res!=0 ){
6293     if( S_ISLNK(mode) ){
6294       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
6295     }else if( S_ISDIR(mode) ){
6296       ctxErrorMsg(context, "failed to create directory: %s", zFile);
6297     }else{
6298       ctxErrorMsg(context, "failed to write file: %s", zFile);
6299     }
6300   }
6301 }
6302 
6303 /*
6304 ** SQL function:   lsmode(MODE)
6305 **
6306 ** Given a numberic st_mode from stat(), convert it into a human-readable
6307 ** text string in the style of "ls -l".
6308 */
6309 static void lsModeFunc(
6310   sqlite3_context *context,
6311   int argc,
6312   sqlite3_value **argv
6313 ){
6314   int i;
6315   int iMode = sqlite3_value_int(argv[0]);
6316   char z[16];
6317   (void)argc;
6318   if( S_ISLNK(iMode) ){
6319     z[0] = 'l';
6320   }else if( S_ISREG(iMode) ){
6321     z[0] = '-';
6322   }else if( S_ISDIR(iMode) ){
6323     z[0] = 'd';
6324   }else{
6325     z[0] = '?';
6326   }
6327   for(i=0; i<3; i++){
6328     int m = (iMode >> ((2-i)*3));
6329     char *a = &z[1 + i*3];
6330     a[0] = (m & 0x4) ? 'r' : '-';
6331     a[1] = (m & 0x2) ? 'w' : '-';
6332     a[2] = (m & 0x1) ? 'x' : '-';
6333   }
6334   z[10] = '\0';
6335   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
6336 }
6337 
6338 #ifndef SQLITE_OMIT_VIRTUALTABLE
6339 
6340 /*
6341 ** Cursor type for recursively iterating through a directory structure.
6342 */
6343 typedef struct fsdir_cursor fsdir_cursor;
6344 typedef struct FsdirLevel FsdirLevel;
6345 
6346 struct FsdirLevel {
6347   DIR *pDir;                 /* From opendir() */
6348   char *zDir;                /* Name of directory (nul-terminated) */
6349 };
6350 
6351 struct fsdir_cursor {
6352   sqlite3_vtab_cursor base;  /* Base class - must be first */
6353 
6354   int nLvl;                  /* Number of entries in aLvl[] array */
6355   int iLvl;                  /* Index of current entry */
6356   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
6357 
6358   const char *zBase;
6359   int nBase;
6360 
6361   struct stat sStat;         /* Current lstat() results */
6362   char *zPath;               /* Path to current entry */
6363   sqlite3_int64 iRowid;      /* Current rowid */
6364 };
6365 
6366 typedef struct fsdir_tab fsdir_tab;
6367 struct fsdir_tab {
6368   sqlite3_vtab base;         /* Base class - must be first */
6369 };
6370 
6371 /*
6372 ** Construct a new fsdir virtual table object.
6373 */
6374 static int fsdirConnect(
6375   sqlite3 *db,
6376   void *pAux,
6377   int argc, const char *const*argv,
6378   sqlite3_vtab **ppVtab,
6379   char **pzErr
6380 ){
6381   fsdir_tab *pNew = 0;
6382   int rc;
6383   (void)pAux;
6384   (void)argc;
6385   (void)argv;
6386   (void)pzErr;
6387   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
6388   if( rc==SQLITE_OK ){
6389     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
6390     if( pNew==0 ) return SQLITE_NOMEM;
6391     memset(pNew, 0, sizeof(*pNew));
6392     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
6393   }
6394   *ppVtab = (sqlite3_vtab*)pNew;
6395   return rc;
6396 }
6397 
6398 /*
6399 ** This method is the destructor for fsdir vtab objects.
6400 */
6401 static int fsdirDisconnect(sqlite3_vtab *pVtab){
6402   sqlite3_free(pVtab);
6403   return SQLITE_OK;
6404 }
6405 
6406 /*
6407 ** Constructor for a new fsdir_cursor object.
6408 */
6409 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6410   fsdir_cursor *pCur;
6411   (void)p;
6412   pCur = sqlite3_malloc( sizeof(*pCur) );
6413   if( pCur==0 ) return SQLITE_NOMEM;
6414   memset(pCur, 0, sizeof(*pCur));
6415   pCur->iLvl = -1;
6416   *ppCursor = &pCur->base;
6417   return SQLITE_OK;
6418 }
6419 
6420 /*
6421 ** Reset a cursor back to the state it was in when first returned
6422 ** by fsdirOpen().
6423 */
6424 static void fsdirResetCursor(fsdir_cursor *pCur){
6425   int i;
6426   for(i=0; i<=pCur->iLvl; i++){
6427     FsdirLevel *pLvl = &pCur->aLvl[i];
6428     if( pLvl->pDir ) closedir(pLvl->pDir);
6429     sqlite3_free(pLvl->zDir);
6430   }
6431   sqlite3_free(pCur->zPath);
6432   sqlite3_free(pCur->aLvl);
6433   pCur->aLvl = 0;
6434   pCur->zPath = 0;
6435   pCur->zBase = 0;
6436   pCur->nBase = 0;
6437   pCur->nLvl = 0;
6438   pCur->iLvl = -1;
6439   pCur->iRowid = 1;
6440 }
6441 
6442 /*
6443 ** Destructor for an fsdir_cursor.
6444 */
6445 static int fsdirClose(sqlite3_vtab_cursor *cur){
6446   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6447 
6448   fsdirResetCursor(pCur);
6449   sqlite3_free(pCur);
6450   return SQLITE_OK;
6451 }
6452 
6453 /*
6454 ** Set the error message for the virtual table associated with cursor
6455 ** pCur to the results of vprintf(zFmt, ...).
6456 */
6457 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
6458   va_list ap;
6459   va_start(ap, zFmt);
6460   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
6461   va_end(ap);
6462 }
6463 
6464 
6465 /*
6466 ** Advance an fsdir_cursor to its next row of output.
6467 */
6468 static int fsdirNext(sqlite3_vtab_cursor *cur){
6469   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6470   mode_t m = pCur->sStat.st_mode;
6471 
6472   pCur->iRowid++;
6473   if( S_ISDIR(m) ){
6474     /* Descend into this directory */
6475     int iNew = pCur->iLvl + 1;
6476     FsdirLevel *pLvl;
6477     if( iNew>=pCur->nLvl ){
6478       int nNew = iNew+1;
6479       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
6480       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
6481       if( aNew==0 ) return SQLITE_NOMEM;
6482       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
6483       pCur->aLvl = aNew;
6484       pCur->nLvl = nNew;
6485     }
6486     pCur->iLvl = iNew;
6487     pLvl = &pCur->aLvl[iNew];
6488 
6489     pLvl->zDir = pCur->zPath;
6490     pCur->zPath = 0;
6491     pLvl->pDir = opendir(pLvl->zDir);
6492     if( pLvl->pDir==0 ){
6493       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
6494       return SQLITE_ERROR;
6495     }
6496   }
6497 
6498   while( pCur->iLvl>=0 ){
6499     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
6500     struct dirent *pEntry = readdir(pLvl->pDir);
6501     if( pEntry ){
6502       if( pEntry->d_name[0]=='.' ){
6503        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
6504        if( pEntry->d_name[1]=='\0' ) continue;
6505       }
6506       sqlite3_free(pCur->zPath);
6507       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
6508       if( pCur->zPath==0 ) return SQLITE_NOMEM;
6509       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
6510         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
6511         return SQLITE_ERROR;
6512       }
6513       return SQLITE_OK;
6514     }
6515     closedir(pLvl->pDir);
6516     sqlite3_free(pLvl->zDir);
6517     pLvl->pDir = 0;
6518     pLvl->zDir = 0;
6519     pCur->iLvl--;
6520   }
6521 
6522   /* EOF */
6523   sqlite3_free(pCur->zPath);
6524   pCur->zPath = 0;
6525   return SQLITE_OK;
6526 }
6527 
6528 /*
6529 ** Return values of columns for the row at which the series_cursor
6530 ** is currently pointing.
6531 */
6532 static int fsdirColumn(
6533   sqlite3_vtab_cursor *cur,   /* The cursor */
6534   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6535   int i                       /* Which column to return */
6536 ){
6537   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6538   switch( i ){
6539     case FSDIR_COLUMN_NAME: {
6540       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
6541       break;
6542     }
6543 
6544     case FSDIR_COLUMN_MODE:
6545       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
6546       break;
6547 
6548     case FSDIR_COLUMN_MTIME:
6549       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
6550       break;
6551 
6552     case FSDIR_COLUMN_DATA: {
6553       mode_t m = pCur->sStat.st_mode;
6554       if( S_ISDIR(m) ){
6555         sqlite3_result_null(ctx);
6556 #if !defined(_WIN32) && !defined(WIN32)
6557       }else if( S_ISLNK(m) ){
6558         char aStatic[64];
6559         char *aBuf = aStatic;
6560         sqlite3_int64 nBuf = 64;
6561         int n;
6562 
6563         while( 1 ){
6564           n = readlink(pCur->zPath, aBuf, nBuf);
6565           if( n<nBuf ) break;
6566           if( aBuf!=aStatic ) sqlite3_free(aBuf);
6567           nBuf = nBuf*2;
6568           aBuf = sqlite3_malloc64(nBuf);
6569           if( aBuf==0 ){
6570             sqlite3_result_error_nomem(ctx);
6571             return SQLITE_NOMEM;
6572           }
6573         }
6574 
6575         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
6576         if( aBuf!=aStatic ) sqlite3_free(aBuf);
6577 #endif
6578       }else{
6579         readFileContents(ctx, pCur->zPath);
6580       }
6581     }
6582     case FSDIR_COLUMN_PATH:
6583     default: {
6584       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
6585       ** always return their values as NULL */
6586       break;
6587     }
6588   }
6589   return SQLITE_OK;
6590 }
6591 
6592 /*
6593 ** Return the rowid for the current row. In this implementation, the
6594 ** first row returned is assigned rowid value 1, and each subsequent
6595 ** row a value 1 more than that of the previous.
6596 */
6597 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
6598   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6599   *pRowid = pCur->iRowid;
6600   return SQLITE_OK;
6601 }
6602 
6603 /*
6604 ** Return TRUE if the cursor has been moved off of the last
6605 ** row of output.
6606 */
6607 static int fsdirEof(sqlite3_vtab_cursor *cur){
6608   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6609   return (pCur->zPath==0);
6610 }
6611 
6612 /*
6613 ** xFilter callback.
6614 **
6615 ** idxNum==1   PATH parameter only
6616 ** idxNum==2   Both PATH and DIR supplied
6617 */
6618 static int fsdirFilter(
6619   sqlite3_vtab_cursor *cur,
6620   int idxNum, const char *idxStr,
6621   int argc, sqlite3_value **argv
6622 ){
6623   const char *zDir = 0;
6624   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6625   (void)idxStr;
6626   fsdirResetCursor(pCur);
6627 
6628   if( idxNum==0 ){
6629     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
6630     return SQLITE_ERROR;
6631   }
6632 
6633   assert( argc==idxNum && (argc==1 || argc==2) );
6634   zDir = (const char*)sqlite3_value_text(argv[0]);
6635   if( zDir==0 ){
6636     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
6637     return SQLITE_ERROR;
6638   }
6639   if( argc==2 ){
6640     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
6641   }
6642   if( pCur->zBase ){
6643     pCur->nBase = (int)strlen(pCur->zBase)+1;
6644     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
6645   }else{
6646     pCur->zPath = sqlite3_mprintf("%s", zDir);
6647   }
6648 
6649   if( pCur->zPath==0 ){
6650     return SQLITE_NOMEM;
6651   }
6652   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
6653     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
6654     return SQLITE_ERROR;
6655   }
6656 
6657   return SQLITE_OK;
6658 }
6659 
6660 /*
6661 ** SQLite will invoke this method one or more times while planning a query
6662 ** that uses the generate_series virtual table.  This routine needs to create
6663 ** a query plan for each invocation and compute an estimated cost for that
6664 ** plan.
6665 **
6666 ** In this implementation idxNum is used to represent the
6667 ** query plan.  idxStr is unused.
6668 **
6669 ** The query plan is represented by values of idxNum:
6670 **
6671 **  (1)  The path value is supplied by argv[0]
6672 **  (2)  Path is in argv[0] and dir is in argv[1]
6673 */
6674 static int fsdirBestIndex(
6675   sqlite3_vtab *tab,
6676   sqlite3_index_info *pIdxInfo
6677 ){
6678   int i;                 /* Loop over constraints */
6679   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
6680   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
6681   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
6682   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
6683   const struct sqlite3_index_constraint *pConstraint;
6684 
6685   (void)tab;
6686   pConstraint = pIdxInfo->aConstraint;
6687   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6688     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
6689     switch( pConstraint->iColumn ){
6690       case FSDIR_COLUMN_PATH: {
6691         if( pConstraint->usable ){
6692           idxPath = i;
6693           seenPath = 0;
6694         }else if( idxPath<0 ){
6695           seenPath = 1;
6696         }
6697         break;
6698       }
6699       case FSDIR_COLUMN_DIR: {
6700         if( pConstraint->usable ){
6701           idxDir = i;
6702           seenDir = 0;
6703         }else if( idxDir<0 ){
6704           seenDir = 1;
6705         }
6706         break;
6707       }
6708     }
6709   }
6710   if( seenPath || seenDir ){
6711     /* If input parameters are unusable, disallow this plan */
6712     return SQLITE_CONSTRAINT;
6713   }
6714 
6715   if( idxPath<0 ){
6716     pIdxInfo->idxNum = 0;
6717     /* The pIdxInfo->estimatedCost should have been initialized to a huge
6718     ** number.  Leave it unchanged. */
6719     pIdxInfo->estimatedRows = 0x7fffffff;
6720   }else{
6721     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
6722     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
6723     if( idxDir>=0 ){
6724       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
6725       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
6726       pIdxInfo->idxNum = 2;
6727       pIdxInfo->estimatedCost = 10.0;
6728     }else{
6729       pIdxInfo->idxNum = 1;
6730       pIdxInfo->estimatedCost = 100.0;
6731     }
6732   }
6733 
6734   return SQLITE_OK;
6735 }
6736 
6737 /*
6738 ** Register the "fsdir" virtual table.
6739 */
6740 static int fsdirRegister(sqlite3 *db){
6741   static sqlite3_module fsdirModule = {
6742     0,                         /* iVersion */
6743     0,                         /* xCreate */
6744     fsdirConnect,              /* xConnect */
6745     fsdirBestIndex,            /* xBestIndex */
6746     fsdirDisconnect,           /* xDisconnect */
6747     0,                         /* xDestroy */
6748     fsdirOpen,                 /* xOpen - open a cursor */
6749     fsdirClose,                /* xClose - close a cursor */
6750     fsdirFilter,               /* xFilter - configure scan constraints */
6751     fsdirNext,                 /* xNext - advance a cursor */
6752     fsdirEof,                  /* xEof - check for end of scan */
6753     fsdirColumn,               /* xColumn - read data */
6754     fsdirRowid,                /* xRowid - read data */
6755     0,                         /* xUpdate */
6756     0,                         /* xBegin */
6757     0,                         /* xSync */
6758     0,                         /* xCommit */
6759     0,                         /* xRollback */
6760     0,                         /* xFindMethod */
6761     0,                         /* xRename */
6762     0,                         /* xSavepoint */
6763     0,                         /* xRelease */
6764     0,                         /* xRollbackTo */
6765     0,                         /* xShadowName */
6766   };
6767 
6768   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
6769   return rc;
6770 }
6771 #else         /* SQLITE_OMIT_VIRTUALTABLE */
6772 # define fsdirRegister(x) SQLITE_OK
6773 #endif
6774 
6775 #ifdef _WIN32
6776 
6777 #endif
6778 int sqlite3_fileio_init(
6779   sqlite3 *db,
6780   char **pzErrMsg,
6781   const sqlite3_api_routines *pApi
6782 ){
6783   int rc = SQLITE_OK;
6784   SQLITE_EXTENSION_INIT2(pApi);
6785   (void)pzErrMsg;  /* Unused parameter */
6786   rc = sqlite3_create_function(db, "readfile", 1,
6787                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
6788                                readfileFunc, 0, 0);
6789   if( rc==SQLITE_OK ){
6790     rc = sqlite3_create_function(db, "writefile", -1,
6791                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
6792                                  writefileFunc, 0, 0);
6793   }
6794   if( rc==SQLITE_OK ){
6795     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
6796                                  lsModeFunc, 0, 0);
6797   }
6798   if( rc==SQLITE_OK ){
6799     rc = fsdirRegister(db);
6800   }
6801   return rc;
6802 }
6803 
6804 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
6805 /* To allow a standalone DLL, make test_windirent.c use the same
6806  * redefined SQLite API calls as the above extension code does.
6807  * Just pull in this .c to accomplish this. As a beneficial side
6808  * effect, this extension becomes a single translation unit. */
6809 #  include "test_windirent.c"
6810 #endif
6811 
6812 /************************* End ../ext/misc/fileio.c ********************/
6813 /************************* Begin ../ext/misc/completion.c ******************/
6814 /*
6815 ** 2017-07-10
6816 **
6817 ** The author disclaims copyright to this source code.  In place of
6818 ** a legal notice, here is a blessing:
6819 **
6820 **    May you do good and not evil.
6821 **    May you find forgiveness for yourself and forgive others.
6822 **    May you share freely, never taking more than you give.
6823 **
6824 *************************************************************************
6825 **
6826 ** This file implements an eponymous virtual table that returns suggested
6827 ** completions for a partial SQL input.
6828 **
6829 ** Suggested usage:
6830 **
6831 **     SELECT DISTINCT candidate COLLATE nocase
6832 **       FROM completion($prefix,$wholeline)
6833 **      ORDER BY 1;
6834 **
6835 ** The two query parameters are optional.  $prefix is the text of the
6836 ** current word being typed and that is to be completed.  $wholeline is
6837 ** the complete input line, used for context.
6838 **
6839 ** The raw completion() table might return the same candidate multiple
6840 ** times, for example if the same column name is used to two or more
6841 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
6842 ** the DISTINCT and ORDER BY are recommended.
6843 **
6844 ** This virtual table operates at the speed of human typing, and so there
6845 ** is no attempt to make it fast.  Even a slow implementation will be much
6846 ** faster than any human can type.
6847 **
6848 */
6849 /* #include "sqlite3ext.h" */
6850 SQLITE_EXTENSION_INIT1
6851 #include <assert.h>
6852 #include <string.h>
6853 #include <ctype.h>
6854 
6855 #ifndef SQLITE_OMIT_VIRTUALTABLE
6856 
6857 /* completion_vtab is a subclass of sqlite3_vtab which will
6858 ** serve as the underlying representation of a completion virtual table
6859 */
6860 typedef struct completion_vtab completion_vtab;
6861 struct completion_vtab {
6862   sqlite3_vtab base;  /* Base class - must be first */
6863   sqlite3 *db;        /* Database connection for this completion vtab */
6864 };
6865 
6866 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
6867 ** serve as the underlying representation of a cursor that scans
6868 ** over rows of the result
6869 */
6870 typedef struct completion_cursor completion_cursor;
6871 struct completion_cursor {
6872   sqlite3_vtab_cursor base;  /* Base class - must be first */
6873   sqlite3 *db;               /* Database connection for this cursor */
6874   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
6875   char *zPrefix;             /* The prefix for the word we want to complete */
6876   char *zLine;               /* The whole that we want to complete */
6877   const char *zCurrentRow;   /* Current output row */
6878   int szRow;                 /* Length of the zCurrentRow string */
6879   sqlite3_stmt *pStmt;       /* Current statement */
6880   sqlite3_int64 iRowid;      /* The rowid */
6881   int ePhase;                /* Current phase */
6882   int j;                     /* inter-phase counter */
6883 };
6884 
6885 /* Values for ePhase:
6886 */
6887 #define COMPLETION_FIRST_PHASE   1
6888 #define COMPLETION_KEYWORDS      1
6889 #define COMPLETION_PRAGMAS       2
6890 #define COMPLETION_FUNCTIONS     3
6891 #define COMPLETION_COLLATIONS    4
6892 #define COMPLETION_INDEXES       5
6893 #define COMPLETION_TRIGGERS      6
6894 #define COMPLETION_DATABASES     7
6895 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
6896 #define COMPLETION_COLUMNS       9
6897 #define COMPLETION_MODULES       10
6898 #define COMPLETION_EOF           11
6899 
6900 /*
6901 ** The completionConnect() method is invoked to create a new
6902 ** completion_vtab that describes the completion virtual table.
6903 **
6904 ** Think of this routine as the constructor for completion_vtab objects.
6905 **
6906 ** All this routine needs to do is:
6907 **
6908 **    (1) Allocate the completion_vtab object and initialize all fields.
6909 **
6910 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
6911 **        result set of queries against completion will look like.
6912 */
6913 static int completionConnect(
6914   sqlite3 *db,
6915   void *pAux,
6916   int argc, const char *const*argv,
6917   sqlite3_vtab **ppVtab,
6918   char **pzErr
6919 ){
6920   completion_vtab *pNew;
6921   int rc;
6922 
6923   (void)(pAux);    /* Unused parameter */
6924   (void)(argc);    /* Unused parameter */
6925   (void)(argv);    /* Unused parameter */
6926   (void)(pzErr);   /* Unused parameter */
6927 
6928 /* Column numbers */
6929 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
6930 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
6931 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
6932 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
6933 
6934   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
6935   rc = sqlite3_declare_vtab(db,
6936       "CREATE TABLE x("
6937       "  candidate TEXT,"
6938       "  prefix TEXT HIDDEN,"
6939       "  wholeline TEXT HIDDEN,"
6940       "  phase INT HIDDEN"        /* Used for debugging only */
6941       ")");
6942   if( rc==SQLITE_OK ){
6943     pNew = sqlite3_malloc( sizeof(*pNew) );
6944     *ppVtab = (sqlite3_vtab*)pNew;
6945     if( pNew==0 ) return SQLITE_NOMEM;
6946     memset(pNew, 0, sizeof(*pNew));
6947     pNew->db = db;
6948   }
6949   return rc;
6950 }
6951 
6952 /*
6953 ** This method is the destructor for completion_cursor objects.
6954 */
6955 static int completionDisconnect(sqlite3_vtab *pVtab){
6956   sqlite3_free(pVtab);
6957   return SQLITE_OK;
6958 }
6959 
6960 /*
6961 ** Constructor for a new completion_cursor object.
6962 */
6963 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6964   completion_cursor *pCur;
6965   pCur = sqlite3_malloc( sizeof(*pCur) );
6966   if( pCur==0 ) return SQLITE_NOMEM;
6967   memset(pCur, 0, sizeof(*pCur));
6968   pCur->db = ((completion_vtab*)p)->db;
6969   *ppCursor = &pCur->base;
6970   return SQLITE_OK;
6971 }
6972 
6973 /*
6974 ** Reset the completion_cursor.
6975 */
6976 static void completionCursorReset(completion_cursor *pCur){
6977   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
6978   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
6979   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
6980   pCur->j = 0;
6981 }
6982 
6983 /*
6984 ** Destructor for a completion_cursor.
6985 */
6986 static int completionClose(sqlite3_vtab_cursor *cur){
6987   completionCursorReset((completion_cursor*)cur);
6988   sqlite3_free(cur);
6989   return SQLITE_OK;
6990 }
6991 
6992 /*
6993 ** Advance a completion_cursor to its next row of output.
6994 **
6995 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
6996 ** record the current state of the scan.  This routine sets ->zCurrentRow
6997 ** to the current row of output and then returns.  If no more rows remain,
6998 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
6999 ** table that has reached the end of its scan.
7000 **
7001 ** The current implementation just lists potential identifiers and
7002 ** keywords and filters them by zPrefix.  Future enhancements should
7003 ** take zLine into account to try to restrict the set of identifiers and
7004 ** keywords based on what would be legal at the current point of input.
7005 */
7006 static int completionNext(sqlite3_vtab_cursor *cur){
7007   completion_cursor *pCur = (completion_cursor*)cur;
7008   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
7009   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
7010   pCur->iRowid++;
7011   while( pCur->ePhase!=COMPLETION_EOF ){
7012     switch( pCur->ePhase ){
7013       case COMPLETION_KEYWORDS: {
7014         if( pCur->j >= sqlite3_keyword_count() ){
7015           pCur->zCurrentRow = 0;
7016           pCur->ePhase = COMPLETION_DATABASES;
7017         }else{
7018           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
7019         }
7020         iCol = -1;
7021         break;
7022       }
7023       case COMPLETION_DATABASES: {
7024         if( pCur->pStmt==0 ){
7025           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
7026                              &pCur->pStmt, 0);
7027         }
7028         iCol = 1;
7029         eNextPhase = COMPLETION_TABLES;
7030         break;
7031       }
7032       case COMPLETION_TABLES: {
7033         if( pCur->pStmt==0 ){
7034           sqlite3_stmt *pS2;
7035           char *zSql = 0;
7036           const char *zSep = "";
7037           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
7038           while( sqlite3_step(pS2)==SQLITE_ROW ){
7039             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
7040             zSql = sqlite3_mprintf(
7041                "%z%s"
7042                "SELECT name FROM \"%w\".sqlite_schema",
7043                zSql, zSep, zDb
7044             );
7045             if( zSql==0 ) return SQLITE_NOMEM;
7046             zSep = " UNION ";
7047           }
7048           sqlite3_finalize(pS2);
7049           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
7050           sqlite3_free(zSql);
7051         }
7052         iCol = 0;
7053         eNextPhase = COMPLETION_COLUMNS;
7054         break;
7055       }
7056       case COMPLETION_COLUMNS: {
7057         if( pCur->pStmt==0 ){
7058           sqlite3_stmt *pS2;
7059           char *zSql = 0;
7060           const char *zSep = "";
7061           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
7062           while( sqlite3_step(pS2)==SQLITE_ROW ){
7063             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
7064             zSql = sqlite3_mprintf(
7065                "%z%s"
7066                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
7067                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
7068                " WHERE sm.type='table'",
7069                zSql, zSep, zDb, zDb
7070             );
7071             if( zSql==0 ) return SQLITE_NOMEM;
7072             zSep = " UNION ";
7073           }
7074           sqlite3_finalize(pS2);
7075           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
7076           sqlite3_free(zSql);
7077         }
7078         iCol = 0;
7079         eNextPhase = COMPLETION_EOF;
7080         break;
7081       }
7082     }
7083     if( iCol<0 ){
7084       /* This case is when the phase presets zCurrentRow */
7085       if( pCur->zCurrentRow==0 ) continue;
7086     }else{
7087       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
7088         /* Extract the next row of content */
7089         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
7090         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
7091       }else{
7092         /* When all rows are finished, advance to the next phase */
7093         sqlite3_finalize(pCur->pStmt);
7094         pCur->pStmt = 0;
7095         pCur->ePhase = eNextPhase;
7096         continue;
7097       }
7098     }
7099     if( pCur->nPrefix==0 ) break;
7100     if( pCur->nPrefix<=pCur->szRow
7101      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
7102     ){
7103       break;
7104     }
7105   }
7106 
7107   return SQLITE_OK;
7108 }
7109 
7110 /*
7111 ** Return values of columns for the row at which the completion_cursor
7112 ** is currently pointing.
7113 */
7114 static int completionColumn(
7115   sqlite3_vtab_cursor *cur,   /* The cursor */
7116   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7117   int i                       /* Which column to return */
7118 ){
7119   completion_cursor *pCur = (completion_cursor*)cur;
7120   switch( i ){
7121     case COMPLETION_COLUMN_CANDIDATE: {
7122       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
7123       break;
7124     }
7125     case COMPLETION_COLUMN_PREFIX: {
7126       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
7127       break;
7128     }
7129     case COMPLETION_COLUMN_WHOLELINE: {
7130       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
7131       break;
7132     }
7133     case COMPLETION_COLUMN_PHASE: {
7134       sqlite3_result_int(ctx, pCur->ePhase);
7135       break;
7136     }
7137   }
7138   return SQLITE_OK;
7139 }
7140 
7141 /*
7142 ** Return the rowid for the current row.  In this implementation, the
7143 ** rowid is the same as the output value.
7144 */
7145 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7146   completion_cursor *pCur = (completion_cursor*)cur;
7147   *pRowid = pCur->iRowid;
7148   return SQLITE_OK;
7149 }
7150 
7151 /*
7152 ** Return TRUE if the cursor has been moved off of the last
7153 ** row of output.
7154 */
7155 static int completionEof(sqlite3_vtab_cursor *cur){
7156   completion_cursor *pCur = (completion_cursor*)cur;
7157   return pCur->ePhase >= COMPLETION_EOF;
7158 }
7159 
7160 /*
7161 ** This method is called to "rewind" the completion_cursor object back
7162 ** to the first row of output.  This method is always called at least
7163 ** once prior to any call to completionColumn() or completionRowid() or
7164 ** completionEof().
7165 */
7166 static int completionFilter(
7167   sqlite3_vtab_cursor *pVtabCursor,
7168   int idxNum, const char *idxStr,
7169   int argc, sqlite3_value **argv
7170 ){
7171   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
7172   int iArg = 0;
7173   (void)(idxStr);   /* Unused parameter */
7174   (void)(argc);     /* Unused parameter */
7175   completionCursorReset(pCur);
7176   if( idxNum & 1 ){
7177     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
7178     if( pCur->nPrefix>0 ){
7179       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
7180       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
7181     }
7182     iArg = 1;
7183   }
7184   if( idxNum & 2 ){
7185     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
7186     if( pCur->nLine>0 ){
7187       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
7188       if( pCur->zLine==0 ) return SQLITE_NOMEM;
7189     }
7190   }
7191   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
7192     int i = pCur->nLine;
7193     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
7194       i--;
7195     }
7196     pCur->nPrefix = pCur->nLine - i;
7197     if( pCur->nPrefix>0 ){
7198       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
7199       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
7200     }
7201   }
7202   pCur->iRowid = 0;
7203   pCur->ePhase = COMPLETION_FIRST_PHASE;
7204   return completionNext(pVtabCursor);
7205 }
7206 
7207 /*
7208 ** SQLite will invoke this method one or more times while planning a query
7209 ** that uses the completion virtual table.  This routine needs to create
7210 ** a query plan for each invocation and compute an estimated cost for that
7211 ** plan.
7212 **
7213 ** There are two hidden parameters that act as arguments to the table-valued
7214 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
7215 ** is available and bit 1 is set if "wholeline" is available.
7216 */
7217 static int completionBestIndex(
7218   sqlite3_vtab *tab,
7219   sqlite3_index_info *pIdxInfo
7220 ){
7221   int i;                 /* Loop over constraints */
7222   int idxNum = 0;        /* The query plan bitmask */
7223   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
7224   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
7225   int nArg = 0;          /* Number of arguments that completeFilter() expects */
7226   const struct sqlite3_index_constraint *pConstraint;
7227 
7228   (void)(tab);    /* Unused parameter */
7229   pConstraint = pIdxInfo->aConstraint;
7230   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
7231     if( pConstraint->usable==0 ) continue;
7232     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
7233     switch( pConstraint->iColumn ){
7234       case COMPLETION_COLUMN_PREFIX:
7235         prefixIdx = i;
7236         idxNum |= 1;
7237         break;
7238       case COMPLETION_COLUMN_WHOLELINE:
7239         wholelineIdx = i;
7240         idxNum |= 2;
7241         break;
7242     }
7243   }
7244   if( prefixIdx>=0 ){
7245     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
7246     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
7247   }
7248   if( wholelineIdx>=0 ){
7249     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
7250     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
7251   }
7252   pIdxInfo->idxNum = idxNum;
7253   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
7254   pIdxInfo->estimatedRows = 500 - 100*nArg;
7255   return SQLITE_OK;
7256 }
7257 
7258 /*
7259 ** This following structure defines all the methods for the
7260 ** completion virtual table.
7261 */
7262 static sqlite3_module completionModule = {
7263   0,                         /* iVersion */
7264   0,                         /* xCreate */
7265   completionConnect,         /* xConnect */
7266   completionBestIndex,       /* xBestIndex */
7267   completionDisconnect,      /* xDisconnect */
7268   0,                         /* xDestroy */
7269   completionOpen,            /* xOpen - open a cursor */
7270   completionClose,           /* xClose - close a cursor */
7271   completionFilter,          /* xFilter - configure scan constraints */
7272   completionNext,            /* xNext - advance a cursor */
7273   completionEof,             /* xEof - check for end of scan */
7274   completionColumn,          /* xColumn - read data */
7275   completionRowid,           /* xRowid - read data */
7276   0,                         /* xUpdate */
7277   0,                         /* xBegin */
7278   0,                         /* xSync */
7279   0,                         /* xCommit */
7280   0,                         /* xRollback */
7281   0,                         /* xFindMethod */
7282   0,                         /* xRename */
7283   0,                         /* xSavepoint */
7284   0,                         /* xRelease */
7285   0,                         /* xRollbackTo */
7286   0                          /* xShadowName */
7287 };
7288 
7289 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7290 
7291 int sqlite3CompletionVtabInit(sqlite3 *db){
7292   int rc = SQLITE_OK;
7293 #ifndef SQLITE_OMIT_VIRTUALTABLE
7294   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
7295 #endif
7296   return rc;
7297 }
7298 
7299 #ifdef _WIN32
7300 
7301 #endif
7302 int sqlite3_completion_init(
7303   sqlite3 *db,
7304   char **pzErrMsg,
7305   const sqlite3_api_routines *pApi
7306 ){
7307   int rc = SQLITE_OK;
7308   SQLITE_EXTENSION_INIT2(pApi);
7309   (void)(pzErrMsg);  /* Unused parameter */
7310 #ifndef SQLITE_OMIT_VIRTUALTABLE
7311   rc = sqlite3CompletionVtabInit(db);
7312 #endif
7313   return rc;
7314 }
7315 
7316 /************************* End ../ext/misc/completion.c ********************/
7317 /************************* Begin ../ext/misc/appendvfs.c ******************/
7318 /*
7319 ** 2017-10-20
7320 **
7321 ** The author disclaims copyright to this source code.  In place of
7322 ** a legal notice, here is a blessing:
7323 **
7324 **    May you do good and not evil.
7325 **    May you find forgiveness for yourself and forgive others.
7326 **    May you share freely, never taking more than you give.
7327 **
7328 ******************************************************************************
7329 **
7330 ** This file implements a VFS shim that allows an SQLite database to be
7331 ** appended onto the end of some other file, such as an executable.
7332 **
7333 ** A special record must appear at the end of the file that identifies the
7334 ** file as an appended database and provides the offset to the first page
7335 ** of the exposed content. (Or, it is the length of the content prefix.)
7336 ** For best performance page 1 should be located at a disk page boundary,
7337 ** though that is not required.
7338 **
7339 ** When opening a database using this VFS, the connection might treat
7340 ** the file as an ordinary SQLite database, or it might treat it as a
7341 ** database appended onto some other file.  The decision is made by
7342 ** applying the following rules in order:
7343 **
7344 **  (1)  An empty file is an ordinary database.
7345 **
7346 **  (2)  If the file ends with the appendvfs trailer string
7347 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
7348 **
7349 **  (3)  If the file begins with the standard SQLite prefix string
7350 **       "SQLite format 3", that file is an ordinary database.
7351 **
7352 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
7353 **       set, then a new database is appended to the already existing file.
7354 **
7355 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
7356 **
7357 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
7358 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
7359 ** This VFS will not read or write past the 1GiB mark.  This restriction
7360 ** might be lifted in future versions.  For now, if you need a larger
7361 ** database, then keep it in a separate file.
7362 **
7363 ** If the file being opened is a plain database (not an appended one), then
7364 ** this shim is a pass-through into the default underlying VFS. (rule 3)
7365 **/
7366 /* #include "sqlite3ext.h" */
7367 SQLITE_EXTENSION_INIT1
7368 #include <string.h>
7369 #include <assert.h>
7370 
7371 /* The append mark at the end of the database is:
7372 **
7373 **     Start-Of-SQLite3-NNNNNNNN
7374 **     123456789 123456789 12345
7375 **
7376 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
7377 ** the offset to page 1, and also the length of the prefix content.
7378 */
7379 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
7380 #define APND_MARK_PREFIX_SZ  17
7381 #define APND_MARK_FOS_SZ      8
7382 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
7383 
7384 /*
7385 ** Maximum size of the combined prefix + database + append-mark.  This
7386 ** must be less than 0x40000000 to avoid locking issues on Windows.
7387 */
7388 #define APND_MAX_SIZE  (0x40000000)
7389 
7390 /*
7391 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
7392 */
7393 #ifndef APND_ROUNDUP
7394 #define APND_ROUNDUP 4096
7395 #endif
7396 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
7397 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
7398 
7399 /*
7400 ** Forward declaration of objects used by this utility
7401 */
7402 typedef struct sqlite3_vfs ApndVfs;
7403 typedef struct ApndFile ApndFile;
7404 
7405 /* Access to a lower-level VFS that (might) implement dynamic loading,
7406 ** access to randomness, etc.
7407 */
7408 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
7409 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
7410 
7411 /* An open appendvfs file
7412 **
7413 ** An instance of this structure describes the appended database file.
7414 ** A separate sqlite3_file object is always appended. The appended
7415 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
7416 ** the entire file, including the prefix, the database, and the
7417 ** append-mark.
7418 **
7419 ** The structure of an AppendVFS database is like this:
7420 **
7421 **   +-------------+---------+----------+-------------+
7422 **   | prefix-file | padding | database | append-mark |
7423 **   +-------------+---------+----------+-------------+
7424 **                           ^          ^
7425 **                           |          |
7426 **                         iPgOne      iMark
7427 **
7428 **
7429 ** "prefix file" -  file onto which the database has been appended.
7430 ** "padding"     -  zero or more bytes inserted so that "database"
7431 **                  starts on an APND_ROUNDUP boundary
7432 ** "database"    -  The SQLite database file
7433 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
7434 **                  the offset from the start of prefix-file to the start
7435 **                  of "database".
7436 **
7437 ** The size of the database is iMark - iPgOne.
7438 **
7439 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
7440 ** of iPgOne stored as a big-ending 64-bit integer.
7441 **
7442 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
7443 ** Or, iMark is -1 to indicate that it has not yet been written.
7444 */
7445 struct ApndFile {
7446   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
7447   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
7448   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
7449   /* Always followed by another sqlite3_file that describes the whole file */
7450 };
7451 
7452 /*
7453 ** Methods for ApndFile
7454 */
7455 static int apndClose(sqlite3_file*);
7456 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
7457 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
7458 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
7459 static int apndSync(sqlite3_file*, int flags);
7460 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
7461 static int apndLock(sqlite3_file*, int);
7462 static int apndUnlock(sqlite3_file*, int);
7463 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
7464 static int apndFileControl(sqlite3_file*, int op, void *pArg);
7465 static int apndSectorSize(sqlite3_file*);
7466 static int apndDeviceCharacteristics(sqlite3_file*);
7467 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
7468 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
7469 static void apndShmBarrier(sqlite3_file*);
7470 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
7471 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
7472 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
7473 
7474 /*
7475 ** Methods for ApndVfs
7476 */
7477 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
7478 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
7479 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
7480 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
7481 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
7482 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
7483 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
7484 static void apndDlClose(sqlite3_vfs*, void*);
7485 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
7486 static int apndSleep(sqlite3_vfs*, int microseconds);
7487 static int apndCurrentTime(sqlite3_vfs*, double*);
7488 static int apndGetLastError(sqlite3_vfs*, int, char *);
7489 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
7490 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
7491 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
7492 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
7493 
7494 static sqlite3_vfs apnd_vfs = {
7495   3,                            /* iVersion (set when registered) */
7496   0,                            /* szOsFile (set when registered) */
7497   1024,                         /* mxPathname */
7498   0,                            /* pNext */
7499   "apndvfs",                    /* zName */
7500   0,                            /* pAppData (set when registered) */
7501   apndOpen,                     /* xOpen */
7502   apndDelete,                   /* xDelete */
7503   apndAccess,                   /* xAccess */
7504   apndFullPathname,             /* xFullPathname */
7505   apndDlOpen,                   /* xDlOpen */
7506   apndDlError,                  /* xDlError */
7507   apndDlSym,                    /* xDlSym */
7508   apndDlClose,                  /* xDlClose */
7509   apndRandomness,               /* xRandomness */
7510   apndSleep,                    /* xSleep */
7511   apndCurrentTime,              /* xCurrentTime */
7512   apndGetLastError,             /* xGetLastError */
7513   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
7514   apndSetSystemCall,            /* xSetSystemCall */
7515   apndGetSystemCall,            /* xGetSystemCall */
7516   apndNextSystemCall            /* xNextSystemCall */
7517 };
7518 
7519 static const sqlite3_io_methods apnd_io_methods = {
7520   3,                              /* iVersion */
7521   apndClose,                      /* xClose */
7522   apndRead,                       /* xRead */
7523   apndWrite,                      /* xWrite */
7524   apndTruncate,                   /* xTruncate */
7525   apndSync,                       /* xSync */
7526   apndFileSize,                   /* xFileSize */
7527   apndLock,                       /* xLock */
7528   apndUnlock,                     /* xUnlock */
7529   apndCheckReservedLock,          /* xCheckReservedLock */
7530   apndFileControl,                /* xFileControl */
7531   apndSectorSize,                 /* xSectorSize */
7532   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
7533   apndShmMap,                     /* xShmMap */
7534   apndShmLock,                    /* xShmLock */
7535   apndShmBarrier,                 /* xShmBarrier */
7536   apndShmUnmap,                   /* xShmUnmap */
7537   apndFetch,                      /* xFetch */
7538   apndUnfetch                     /* xUnfetch */
7539 };
7540 
7541 /*
7542 ** Close an apnd-file.
7543 */
7544 static int apndClose(sqlite3_file *pFile){
7545   pFile = ORIGFILE(pFile);
7546   return pFile->pMethods->xClose(pFile);
7547 }
7548 
7549 /*
7550 ** Read data from an apnd-file.
7551 */
7552 static int apndRead(
7553   sqlite3_file *pFile,
7554   void *zBuf,
7555   int iAmt,
7556   sqlite_int64 iOfst
7557 ){
7558   ApndFile *paf = (ApndFile *)pFile;
7559   pFile = ORIGFILE(pFile);
7560   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
7561 }
7562 
7563 /*
7564 ** Add the append-mark onto what should become the end of the file.
7565 *  If and only if this succeeds, internal ApndFile.iMark is updated.
7566 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
7567 */
7568 static int apndWriteMark(
7569   ApndFile *paf,
7570   sqlite3_file *pFile,
7571   sqlite_int64 iWriteEnd
7572 ){
7573   sqlite_int64 iPgOne = paf->iPgOne;
7574   unsigned char a[APND_MARK_SIZE];
7575   int i = APND_MARK_FOS_SZ;
7576   int rc;
7577   assert(pFile == ORIGFILE(paf));
7578   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
7579   while( --i >= 0 ){
7580     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
7581     iPgOne >>= 8;
7582   }
7583   iWriteEnd += paf->iPgOne;
7584   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
7585                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
7586     paf->iMark = iWriteEnd;
7587   }
7588   return rc;
7589 }
7590 
7591 /*
7592 ** Write data to an apnd-file.
7593 */
7594 static int apndWrite(
7595   sqlite3_file *pFile,
7596   const void *zBuf,
7597   int iAmt,
7598   sqlite_int64 iOfst
7599 ){
7600   ApndFile *paf = (ApndFile *)pFile;
7601   sqlite_int64 iWriteEnd = iOfst + iAmt;
7602   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
7603   pFile = ORIGFILE(pFile);
7604   /* If append-mark is absent or will be overwritten, write it. */
7605   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
7606     int rc = apndWriteMark(paf, pFile, iWriteEnd);
7607     if( SQLITE_OK!=rc ) return rc;
7608   }
7609   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
7610 }
7611 
7612 /*
7613 ** Truncate an apnd-file.
7614 */
7615 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
7616   ApndFile *paf = (ApndFile *)pFile;
7617   pFile = ORIGFILE(pFile);
7618   /* The append mark goes out first so truncate failure does not lose it. */
7619   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
7620   /* Truncate underlying file just past append mark */
7621   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
7622 }
7623 
7624 /*
7625 ** Sync an apnd-file.
7626 */
7627 static int apndSync(sqlite3_file *pFile, int flags){
7628   pFile = ORIGFILE(pFile);
7629   return pFile->pMethods->xSync(pFile, flags);
7630 }
7631 
7632 /*
7633 ** Return the current file-size of an apnd-file.
7634 ** If the append mark is not yet there, the file-size is 0.
7635 */
7636 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
7637   ApndFile *paf = (ApndFile *)pFile;
7638   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
7639   return SQLITE_OK;
7640 }
7641 
7642 /*
7643 ** Lock an apnd-file.
7644 */
7645 static int apndLock(sqlite3_file *pFile, int eLock){
7646   pFile = ORIGFILE(pFile);
7647   return pFile->pMethods->xLock(pFile, eLock);
7648 }
7649 
7650 /*
7651 ** Unlock an apnd-file.
7652 */
7653 static int apndUnlock(sqlite3_file *pFile, int eLock){
7654   pFile = ORIGFILE(pFile);
7655   return pFile->pMethods->xUnlock(pFile, eLock);
7656 }
7657 
7658 /*
7659 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
7660 */
7661 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
7662   pFile = ORIGFILE(pFile);
7663   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
7664 }
7665 
7666 /*
7667 ** File control method. For custom operations on an apnd-file.
7668 */
7669 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
7670   ApndFile *paf = (ApndFile *)pFile;
7671   int rc;
7672   pFile = ORIGFILE(pFile);
7673   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
7674   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
7675   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
7676     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
7677   }
7678   return rc;
7679 }
7680 
7681 /*
7682 ** Return the sector-size in bytes for an apnd-file.
7683 */
7684 static int apndSectorSize(sqlite3_file *pFile){
7685   pFile = ORIGFILE(pFile);
7686   return pFile->pMethods->xSectorSize(pFile);
7687 }
7688 
7689 /*
7690 ** Return the device characteristic flags supported by an apnd-file.
7691 */
7692 static int apndDeviceCharacteristics(sqlite3_file *pFile){
7693   pFile = ORIGFILE(pFile);
7694   return pFile->pMethods->xDeviceCharacteristics(pFile);
7695 }
7696 
7697 /* Create a shared memory file mapping */
7698 static int apndShmMap(
7699   sqlite3_file *pFile,
7700   int iPg,
7701   int pgsz,
7702   int bExtend,
7703   void volatile **pp
7704 ){
7705   pFile = ORIGFILE(pFile);
7706   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
7707 }
7708 
7709 /* Perform locking on a shared-memory segment */
7710 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
7711   pFile = ORIGFILE(pFile);
7712   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
7713 }
7714 
7715 /* Memory barrier operation on shared memory */
7716 static void apndShmBarrier(sqlite3_file *pFile){
7717   pFile = ORIGFILE(pFile);
7718   pFile->pMethods->xShmBarrier(pFile);
7719 }
7720 
7721 /* Unmap a shared memory segment */
7722 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
7723   pFile = ORIGFILE(pFile);
7724   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
7725 }
7726 
7727 /* Fetch a page of a memory-mapped file */
7728 static int apndFetch(
7729   sqlite3_file *pFile,
7730   sqlite3_int64 iOfst,
7731   int iAmt,
7732   void **pp
7733 ){
7734   ApndFile *p = (ApndFile *)pFile;
7735   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
7736     return SQLITE_IOERR; /* Cannot read what is not yet there. */
7737   }
7738   pFile = ORIGFILE(pFile);
7739   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
7740 }
7741 
7742 /* Release a memory-mapped page */
7743 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
7744   ApndFile *p = (ApndFile *)pFile;
7745   pFile = ORIGFILE(pFile);
7746   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
7747 }
7748 
7749 /*
7750 ** Try to read the append-mark off the end of a file.  Return the
7751 ** start of the appended database if the append-mark is present.
7752 ** If there is no valid append-mark, return -1;
7753 **
7754 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
7755 ** indicates that the appended database contains at least one page.  The
7756 ** start-of-database value must be a multiple of 512.
7757 */
7758 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
7759   int rc, i;
7760   sqlite3_int64 iMark;
7761   int msbs = 8 * (APND_MARK_FOS_SZ-1);
7762   unsigned char a[APND_MARK_SIZE];
7763 
7764   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
7765   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
7766   if( rc ) return -1;
7767   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
7768   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
7769   for(i=1; i<8; i++){
7770     msbs -= 8;
7771     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
7772   }
7773   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
7774   if( iMark & 0x1ff ) return -1;
7775   return iMark;
7776 }
7777 
7778 static const char apvfsSqliteHdr[] = "SQLite format 3";
7779 /*
7780 ** Check to see if the file is an appendvfs SQLite database file.
7781 ** Return true iff it is such. Parameter sz is the file's size.
7782 */
7783 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
7784   int rc;
7785   char zHdr[16];
7786   sqlite3_int64 iMark = apndReadMark(sz, pFile);
7787   if( iMark>=0 ){
7788     /* If file has the correct end-marker, the expected odd size, and the
7789     ** SQLite DB type marker where the end-marker puts it, then it
7790     ** is an appendvfs database.
7791     */
7792     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
7793     if( SQLITE_OK==rc
7794      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
7795      && (sz & 0x1ff) == APND_MARK_SIZE
7796      && sz>=512+APND_MARK_SIZE
7797     ){
7798       return 1; /* It's an appendvfs database */
7799     }
7800   }
7801   return 0;
7802 }
7803 
7804 /*
7805 ** Check to see if the file is an ordinary SQLite database file.
7806 ** Return true iff so. Parameter sz is the file's size.
7807 */
7808 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
7809   char zHdr[16];
7810   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
7811    || (sz & 0x1ff) != 0
7812    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
7813    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
7814   ){
7815     return 0;
7816   }else{
7817     return 1;
7818   }
7819 }
7820 
7821 /*
7822 ** Open an apnd file handle.
7823 */
7824 static int apndOpen(
7825   sqlite3_vfs *pApndVfs,
7826   const char *zName,
7827   sqlite3_file *pFile,
7828   int flags,
7829   int *pOutFlags
7830 ){
7831   ApndFile *pApndFile = (ApndFile*)pFile;
7832   sqlite3_file *pBaseFile = ORIGFILE(pFile);
7833   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
7834   int rc;
7835   sqlite3_int64 sz = 0;
7836   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
7837     /* The appendvfs is not to be used for transient or temporary databases.
7838     ** Just use the base VFS open to initialize the given file object and
7839     ** open the underlying file. (Appendvfs is then unused for this file.)
7840     */
7841     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
7842   }
7843   memset(pApndFile, 0, sizeof(ApndFile));
7844   pFile->pMethods = &apnd_io_methods;
7845   pApndFile->iMark = -1;    /* Append mark not yet written */
7846 
7847   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
7848   if( rc==SQLITE_OK ){
7849     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
7850     if( rc ){
7851       pBaseFile->pMethods->xClose(pBaseFile);
7852     }
7853   }
7854   if( rc ){
7855     pFile->pMethods = 0;
7856     return rc;
7857   }
7858   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
7859     /* The file being opened appears to be just an ordinary DB. Copy
7860     ** the base dispatch-table so this instance mimics the base VFS.
7861     */
7862     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
7863     return SQLITE_OK;
7864   }
7865   pApndFile->iPgOne = apndReadMark(sz, pFile);
7866   if( pApndFile->iPgOne>=0 ){
7867     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
7868     return SQLITE_OK;
7869   }
7870   if( (flags & SQLITE_OPEN_CREATE)==0 ){
7871     pBaseFile->pMethods->xClose(pBaseFile);
7872     rc = SQLITE_CANTOPEN;
7873     pFile->pMethods = 0;
7874   }else{
7875     /* Round newly added appendvfs location to #define'd page boundary.
7876     ** Note that nothing has yet been written to the underlying file.
7877     ** The append mark will be written along with first content write.
7878     ** Until then, paf->iMark value indicates it is not yet written.
7879     */
7880     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
7881   }
7882   return rc;
7883 }
7884 
7885 /*
7886 ** Delete an apnd file.
7887 ** For an appendvfs, this could mean delete the appendvfs portion,
7888 ** leaving the appendee as it was before it gained an appendvfs.
7889 ** For now, this code deletes the underlying file too.
7890 */
7891 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
7892   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
7893 }
7894 
7895 /*
7896 ** All other VFS methods are pass-thrus.
7897 */
7898 static int apndAccess(
7899   sqlite3_vfs *pVfs,
7900   const char *zPath,
7901   int flags,
7902   int *pResOut
7903 ){
7904   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
7905 }
7906 static int apndFullPathname(
7907   sqlite3_vfs *pVfs,
7908   const char *zPath,
7909   int nOut,
7910   char *zOut
7911 ){
7912   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
7913 }
7914 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
7915   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
7916 }
7917 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
7918   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
7919 }
7920 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
7921   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
7922 }
7923 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
7924   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
7925 }
7926 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
7927   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
7928 }
7929 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
7930   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
7931 }
7932 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
7933   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
7934 }
7935 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
7936   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
7937 }
7938 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
7939   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
7940 }
7941 static int apndSetSystemCall(
7942   sqlite3_vfs *pVfs,
7943   const char *zName,
7944   sqlite3_syscall_ptr pCall
7945 ){
7946   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
7947 }
7948 static sqlite3_syscall_ptr apndGetSystemCall(
7949   sqlite3_vfs *pVfs,
7950   const char *zName
7951 ){
7952   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
7953 }
7954 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
7955   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
7956 }
7957 
7958 
7959 #ifdef _WIN32
7960 
7961 #endif
7962 /*
7963 ** This routine is called when the extension is loaded.
7964 ** Register the new VFS.
7965 */
7966 int sqlite3_appendvfs_init(
7967   sqlite3 *db,
7968   char **pzErrMsg,
7969   const sqlite3_api_routines *pApi
7970 ){
7971   int rc = SQLITE_OK;
7972   sqlite3_vfs *pOrig;
7973   SQLITE_EXTENSION_INIT2(pApi);
7974   (void)pzErrMsg;
7975   (void)db;
7976   pOrig = sqlite3_vfs_find(0);
7977   if( pOrig==0 ) return SQLITE_ERROR;
7978   apnd_vfs.iVersion = pOrig->iVersion;
7979   apnd_vfs.pAppData = pOrig;
7980   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
7981   rc = sqlite3_vfs_register(&apnd_vfs, 0);
7982 #ifdef APPENDVFS_TEST
7983   if( rc==SQLITE_OK ){
7984     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
7985   }
7986 #endif
7987   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
7988   return rc;
7989 }
7990 
7991 /************************* End ../ext/misc/appendvfs.c ********************/
7992 #endif
7993 #ifdef SQLITE_HAVE_ZLIB
7994 /************************* Begin ../ext/misc/zipfile.c ******************/
7995 /*
7996 ** 2017-12-26
7997 **
7998 ** The author disclaims copyright to this source code.  In place of
7999 ** a legal notice, here is a blessing:
8000 **
8001 **    May you do good and not evil.
8002 **    May you find forgiveness for yourself and forgive others.
8003 **    May you share freely, never taking more than you give.
8004 **
8005 ******************************************************************************
8006 **
8007 ** This file implements a virtual table for reading and writing ZIP archive
8008 ** files.
8009 **
8010 ** Usage example:
8011 **
8012 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
8013 **
8014 ** Current limitations:
8015 **
8016 **    *  No support for encryption
8017 **    *  No support for ZIP archives spanning multiple files
8018 **    *  No support for zip64 extensions
8019 **    *  Only the "inflate/deflate" (zlib) compression method is supported
8020 */
8021 /* #include "sqlite3ext.h" */
8022 SQLITE_EXTENSION_INIT1
8023 #include <stdio.h>
8024 #include <string.h>
8025 #include <assert.h>
8026 
8027 #include <zlib.h>
8028 
8029 #ifndef SQLITE_OMIT_VIRTUALTABLE
8030 
8031 #ifndef SQLITE_AMALGAMATION
8032 
8033 #ifndef UINT32_TYPE
8034 # ifdef HAVE_UINT32_T
8035 #  define UINT32_TYPE uint32_t
8036 # else
8037 #  define UINT32_TYPE unsigned int
8038 # endif
8039 #endif
8040 #ifndef UINT16_TYPE
8041 # ifdef HAVE_UINT16_T
8042 #  define UINT16_TYPE uint16_t
8043 # else
8044 #  define UINT16_TYPE unsigned short int
8045 # endif
8046 #endif
8047 /* typedef sqlite3_int64 i64; */
8048 /* typedef unsigned char u8; */
8049 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
8050 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
8051 #define MIN(a,b) ((a)<(b) ? (a) : (b))
8052 
8053 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
8054 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
8055 #endif
8056 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
8057 # define ALWAYS(X)      (1)
8058 # define NEVER(X)       (0)
8059 #elif !defined(NDEBUG)
8060 # define ALWAYS(X)      ((X)?1:(assert(0),0))
8061 # define NEVER(X)       ((X)?(assert(0),1):0)
8062 #else
8063 # define ALWAYS(X)      (X)
8064 # define NEVER(X)       (X)
8065 #endif
8066 
8067 #endif   /* SQLITE_AMALGAMATION */
8068 
8069 /*
8070 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
8071 **
8072 ** In some ways it would be better to obtain these values from system
8073 ** header files. But, the dependency is undesirable and (a) these
8074 ** have been stable for decades, (b) the values are part of POSIX and
8075 ** are also made explicit in [man stat], and (c) are part of the
8076 ** file format for zip archives.
8077 */
8078 #ifndef S_IFDIR
8079 # define S_IFDIR 0040000
8080 #endif
8081 #ifndef S_IFREG
8082 # define S_IFREG 0100000
8083 #endif
8084 #ifndef S_IFLNK
8085 # define S_IFLNK 0120000
8086 #endif
8087 
8088 static const char ZIPFILE_SCHEMA[] =
8089   "CREATE TABLE y("
8090     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
8091     "mode,"              /* 1: POSIX mode for file */
8092     "mtime,"             /* 2: Last modification time (secs since 1970)*/
8093     "sz,"                /* 3: Size of object */
8094     "rawdata,"           /* 4: Raw data */
8095     "data,"              /* 5: Uncompressed data */
8096     "method,"            /* 6: Compression method (integer) */
8097     "z HIDDEN"           /* 7: Name of zip file */
8098   ") WITHOUT ROWID;";
8099 
8100 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
8101 #define ZIPFILE_BUFFER_SIZE (64*1024)
8102 
8103 
8104 /*
8105 ** Magic numbers used to read and write zip files.
8106 **
8107 ** ZIPFILE_NEWENTRY_MADEBY:
8108 **   Use this value for the "version-made-by" field in new zip file
8109 **   entries. The upper byte indicates "unix", and the lower byte
8110 **   indicates that the zip file matches pkzip specification 3.0.
8111 **   This is what info-zip seems to do.
8112 **
8113 ** ZIPFILE_NEWENTRY_REQUIRED:
8114 **   Value for "version-required-to-extract" field of new entries.
8115 **   Version 2.0 is required to support folders and deflate compression.
8116 **
8117 ** ZIPFILE_NEWENTRY_FLAGS:
8118 **   Value for "general-purpose-bit-flags" field of new entries. Bit
8119 **   11 means "utf-8 filename and comment".
8120 **
8121 ** ZIPFILE_SIGNATURE_CDS:
8122 **   First 4 bytes of a valid CDS record.
8123 **
8124 ** ZIPFILE_SIGNATURE_LFH:
8125 **   First 4 bytes of a valid LFH record.
8126 **
8127 ** ZIPFILE_SIGNATURE_EOCD
8128 **   First 4 bytes of a valid EOCD record.
8129 */
8130 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
8131 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
8132 #define ZIPFILE_NEWENTRY_REQUIRED 20
8133 #define ZIPFILE_NEWENTRY_FLAGS    0x800
8134 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
8135 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
8136 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
8137 
8138 /*
8139 ** The sizes of the fixed-size part of each of the three main data
8140 ** structures in a zip archive.
8141 */
8142 #define ZIPFILE_LFH_FIXED_SZ      30
8143 #define ZIPFILE_EOCD_FIXED_SZ     22
8144 #define ZIPFILE_CDS_FIXED_SZ      46
8145 
8146 /*
8147 *** 4.3.16  End of central directory record:
8148 ***
8149 ***   end of central dir signature    4 bytes  (0x06054b50)
8150 ***   number of this disk             2 bytes
8151 ***   number of the disk with the
8152 ***   start of the central directory  2 bytes
8153 ***   total number of entries in the
8154 ***   central directory on this disk  2 bytes
8155 ***   total number of entries in
8156 ***   the central directory           2 bytes
8157 ***   size of the central directory   4 bytes
8158 ***   offset of start of central
8159 ***   directory with respect to
8160 ***   the starting disk number        4 bytes
8161 ***   .ZIP file comment length        2 bytes
8162 ***   .ZIP file comment       (variable size)
8163 */
8164 typedef struct ZipfileEOCD ZipfileEOCD;
8165 struct ZipfileEOCD {
8166   u16 iDisk;
8167   u16 iFirstDisk;
8168   u16 nEntry;
8169   u16 nEntryTotal;
8170   u32 nSize;
8171   u32 iOffset;
8172 };
8173 
8174 /*
8175 *** 4.3.12  Central directory structure:
8176 ***
8177 *** ...
8178 ***
8179 ***   central file header signature   4 bytes  (0x02014b50)
8180 ***   version made by                 2 bytes
8181 ***   version needed to extract       2 bytes
8182 ***   general purpose bit flag        2 bytes
8183 ***   compression method              2 bytes
8184 ***   last mod file time              2 bytes
8185 ***   last mod file date              2 bytes
8186 ***   crc-32                          4 bytes
8187 ***   compressed size                 4 bytes
8188 ***   uncompressed size               4 bytes
8189 ***   file name length                2 bytes
8190 ***   extra field length              2 bytes
8191 ***   file comment length             2 bytes
8192 ***   disk number start               2 bytes
8193 ***   internal file attributes        2 bytes
8194 ***   external file attributes        4 bytes
8195 ***   relative offset of local header 4 bytes
8196 */
8197 typedef struct ZipfileCDS ZipfileCDS;
8198 struct ZipfileCDS {
8199   u16 iVersionMadeBy;
8200   u16 iVersionExtract;
8201   u16 flags;
8202   u16 iCompression;
8203   u16 mTime;
8204   u16 mDate;
8205   u32 crc32;
8206   u32 szCompressed;
8207   u32 szUncompressed;
8208   u16 nFile;
8209   u16 nExtra;
8210   u16 nComment;
8211   u16 iDiskStart;
8212   u16 iInternalAttr;
8213   u32 iExternalAttr;
8214   u32 iOffset;
8215   char *zFile;                    /* Filename (sqlite3_malloc()) */
8216 };
8217 
8218 /*
8219 *** 4.3.7  Local file header:
8220 ***
8221 ***   local file header signature     4 bytes  (0x04034b50)
8222 ***   version needed to extract       2 bytes
8223 ***   general purpose bit flag        2 bytes
8224 ***   compression method              2 bytes
8225 ***   last mod file time              2 bytes
8226 ***   last mod file date              2 bytes
8227 ***   crc-32                          4 bytes
8228 ***   compressed size                 4 bytes
8229 ***   uncompressed size               4 bytes
8230 ***   file name length                2 bytes
8231 ***   extra field length              2 bytes
8232 ***
8233 */
8234 typedef struct ZipfileLFH ZipfileLFH;
8235 struct ZipfileLFH {
8236   u16 iVersionExtract;
8237   u16 flags;
8238   u16 iCompression;
8239   u16 mTime;
8240   u16 mDate;
8241   u32 crc32;
8242   u32 szCompressed;
8243   u32 szUncompressed;
8244   u16 nFile;
8245   u16 nExtra;
8246 };
8247 
8248 typedef struct ZipfileEntry ZipfileEntry;
8249 struct ZipfileEntry {
8250   ZipfileCDS cds;            /* Parsed CDS record */
8251   u32 mUnixTime;             /* Modification time, in UNIX format */
8252   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
8253   i64 iDataOff;              /* Offset to data in file (if aData==0) */
8254   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
8255   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
8256 };
8257 
8258 /*
8259 ** Cursor type for zipfile tables.
8260 */
8261 typedef struct ZipfileCsr ZipfileCsr;
8262 struct ZipfileCsr {
8263   sqlite3_vtab_cursor base;  /* Base class - must be first */
8264   i64 iId;                   /* Cursor ID */
8265   u8 bEof;                   /* True when at EOF */
8266   u8 bNoop;                  /* If next xNext() call is no-op */
8267 
8268   /* Used outside of write transactions */
8269   FILE *pFile;               /* Zip file */
8270   i64 iNextOff;              /* Offset of next record in central directory */
8271   ZipfileEOCD eocd;          /* Parse of central directory record */
8272 
8273   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
8274   ZipfileEntry *pCurrent;    /* Current entry */
8275   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
8276 };
8277 
8278 typedef struct ZipfileTab ZipfileTab;
8279 struct ZipfileTab {
8280   sqlite3_vtab base;         /* Base class - must be first */
8281   char *zFile;               /* Zip file this table accesses (may be NULL) */
8282   sqlite3 *db;               /* Host database connection */
8283   u8 *aBuffer;               /* Temporary buffer used for various tasks */
8284 
8285   ZipfileCsr *pCsrList;      /* List of cursors */
8286   i64 iNextCsrid;
8287 
8288   /* The following are used by write transactions only */
8289   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
8290   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
8291   FILE *pWriteFd;            /* File handle open on zip archive */
8292   i64 szCurrent;             /* Current size of zip archive */
8293   i64 szOrig;                /* Size of archive at start of transaction */
8294 };
8295 
8296 /*
8297 ** Set the error message contained in context ctx to the results of
8298 ** vprintf(zFmt, ...).
8299 */
8300 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
8301   char *zMsg = 0;
8302   va_list ap;
8303   va_start(ap, zFmt);
8304   zMsg = sqlite3_vmprintf(zFmt, ap);
8305   sqlite3_result_error(ctx, zMsg, -1);
8306   sqlite3_free(zMsg);
8307   va_end(ap);
8308 }
8309 
8310 /*
8311 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
8312 ** is not quoted, do nothing.
8313 */
8314 static void zipfileDequote(char *zIn){
8315   char q = zIn[0];
8316   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
8317     int iIn = 1;
8318     int iOut = 0;
8319     if( q=='[' ) q = ']';
8320     while( ALWAYS(zIn[iIn]) ){
8321       char c = zIn[iIn++];
8322       if( c==q && zIn[iIn++]!=q ) break;
8323       zIn[iOut++] = c;
8324     }
8325     zIn[iOut] = '\0';
8326   }
8327 }
8328 
8329 /*
8330 ** Construct a new ZipfileTab virtual table object.
8331 **
8332 **   argv[0]   -> module name  ("zipfile")
8333 **   argv[1]   -> database name
8334 **   argv[2]   -> table name
8335 **   argv[...] -> "column name" and other module argument fields.
8336 */
8337 static int zipfileConnect(
8338   sqlite3 *db,
8339   void *pAux,
8340   int argc, const char *const*argv,
8341   sqlite3_vtab **ppVtab,
8342   char **pzErr
8343 ){
8344   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
8345   int nFile = 0;
8346   const char *zFile = 0;
8347   ZipfileTab *pNew = 0;
8348   int rc;
8349   (void)pAux;
8350 
8351   /* If the table name is not "zipfile", require that the argument be
8352   ** specified. This stops zipfile tables from being created as:
8353   **
8354   **   CREATE VIRTUAL TABLE zzz USING zipfile();
8355   **
8356   ** It does not prevent:
8357   **
8358   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
8359   */
8360   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
8361   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
8362     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
8363     return SQLITE_ERROR;
8364   }
8365 
8366   if( argc>3 ){
8367     zFile = argv[3];
8368     nFile = (int)strlen(zFile)+1;
8369   }
8370 
8371   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
8372   if( rc==SQLITE_OK ){
8373     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
8374     if( pNew==0 ) return SQLITE_NOMEM;
8375     memset(pNew, 0, nByte+nFile);
8376     pNew->db = db;
8377     pNew->aBuffer = (u8*)&pNew[1];
8378     if( zFile ){
8379       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
8380       memcpy(pNew->zFile, zFile, nFile);
8381       zipfileDequote(pNew->zFile);
8382     }
8383   }
8384   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
8385   *ppVtab = (sqlite3_vtab*)pNew;
8386   return rc;
8387 }
8388 
8389 /*
8390 ** Free the ZipfileEntry structure indicated by the only argument.
8391 */
8392 static void zipfileEntryFree(ZipfileEntry *p){
8393   if( p ){
8394     sqlite3_free(p->cds.zFile);
8395     sqlite3_free(p);
8396   }
8397 }
8398 
8399 /*
8400 ** Release resources that should be freed at the end of a write
8401 ** transaction.
8402 */
8403 static void zipfileCleanupTransaction(ZipfileTab *pTab){
8404   ZipfileEntry *pEntry;
8405   ZipfileEntry *pNext;
8406 
8407   if( pTab->pWriteFd ){
8408     fclose(pTab->pWriteFd);
8409     pTab->pWriteFd = 0;
8410   }
8411   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
8412     pNext = pEntry->pNext;
8413     zipfileEntryFree(pEntry);
8414   }
8415   pTab->pFirstEntry = 0;
8416   pTab->pLastEntry = 0;
8417   pTab->szCurrent = 0;
8418   pTab->szOrig = 0;
8419 }
8420 
8421 /*
8422 ** This method is the destructor for zipfile vtab objects.
8423 */
8424 static int zipfileDisconnect(sqlite3_vtab *pVtab){
8425   zipfileCleanupTransaction((ZipfileTab*)pVtab);
8426   sqlite3_free(pVtab);
8427   return SQLITE_OK;
8428 }
8429 
8430 /*
8431 ** Constructor for a new ZipfileCsr object.
8432 */
8433 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
8434   ZipfileTab *pTab = (ZipfileTab*)p;
8435   ZipfileCsr *pCsr;
8436   pCsr = sqlite3_malloc(sizeof(*pCsr));
8437   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
8438   if( pCsr==0 ){
8439     return SQLITE_NOMEM;
8440   }
8441   memset(pCsr, 0, sizeof(*pCsr));
8442   pCsr->iId = ++pTab->iNextCsrid;
8443   pCsr->pCsrNext = pTab->pCsrList;
8444   pTab->pCsrList = pCsr;
8445   return SQLITE_OK;
8446 }
8447 
8448 /*
8449 ** Reset a cursor back to the state it was in when first returned
8450 ** by zipfileOpen().
8451 */
8452 static void zipfileResetCursor(ZipfileCsr *pCsr){
8453   ZipfileEntry *p;
8454   ZipfileEntry *pNext;
8455 
8456   pCsr->bEof = 0;
8457   if( pCsr->pFile ){
8458     fclose(pCsr->pFile);
8459     pCsr->pFile = 0;
8460     zipfileEntryFree(pCsr->pCurrent);
8461     pCsr->pCurrent = 0;
8462   }
8463 
8464   for(p=pCsr->pFreeEntry; p; p=pNext){
8465     pNext = p->pNext;
8466     zipfileEntryFree(p);
8467   }
8468 }
8469 
8470 /*
8471 ** Destructor for an ZipfileCsr.
8472 */
8473 static int zipfileClose(sqlite3_vtab_cursor *cur){
8474   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8475   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
8476   ZipfileCsr **pp;
8477   zipfileResetCursor(pCsr);
8478 
8479   /* Remove this cursor from the ZipfileTab.pCsrList list. */
8480   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
8481   *pp = pCsr->pCsrNext;
8482 
8483   sqlite3_free(pCsr);
8484   return SQLITE_OK;
8485 }
8486 
8487 /*
8488 ** Set the error message for the virtual table associated with cursor
8489 ** pCsr to the results of vprintf(zFmt, ...).
8490 */
8491 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
8492   va_list ap;
8493   va_start(ap, zFmt);
8494   sqlite3_free(pTab->base.zErrMsg);
8495   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
8496   va_end(ap);
8497 }
8498 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
8499   va_list ap;
8500   va_start(ap, zFmt);
8501   sqlite3_free(pCsr->base.pVtab->zErrMsg);
8502   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
8503   va_end(ap);
8504 }
8505 
8506 /*
8507 ** Read nRead bytes of data from offset iOff of file pFile into buffer
8508 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
8509 ** otherwise.
8510 **
8511 ** If an error does occur, output variable (*pzErrmsg) may be set to point
8512 ** to an English language error message. It is the responsibility of the
8513 ** caller to eventually free this buffer using
8514 ** sqlite3_free().
8515 */
8516 static int zipfileReadData(
8517   FILE *pFile,                    /* Read from this file */
8518   u8 *aRead,                      /* Read into this buffer */
8519   int nRead,                      /* Number of bytes to read */
8520   i64 iOff,                       /* Offset to read from */
8521   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
8522 ){
8523   size_t n;
8524   fseek(pFile, (long)iOff, SEEK_SET);
8525   n = fread(aRead, 1, nRead, pFile);
8526   if( (int)n!=nRead ){
8527     *pzErrmsg = sqlite3_mprintf("error in fread()");
8528     return SQLITE_ERROR;
8529   }
8530   return SQLITE_OK;
8531 }
8532 
8533 static int zipfileAppendData(
8534   ZipfileTab *pTab,
8535   const u8 *aWrite,
8536   int nWrite
8537 ){
8538   if( nWrite>0 ){
8539     size_t n = nWrite;
8540     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
8541     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
8542     if( (int)n!=nWrite ){
8543       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
8544       return SQLITE_ERROR;
8545     }
8546     pTab->szCurrent += nWrite;
8547   }
8548   return SQLITE_OK;
8549 }
8550 
8551 /*
8552 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
8553 */
8554 static u16 zipfileGetU16(const u8 *aBuf){
8555   return (aBuf[1] << 8) + aBuf[0];
8556 }
8557 
8558 /*
8559 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
8560 */
8561 static u32 zipfileGetU32(const u8 *aBuf){
8562   if( aBuf==0 ) return 0;
8563   return ((u32)(aBuf[3]) << 24)
8564        + ((u32)(aBuf[2]) << 16)
8565        + ((u32)(aBuf[1]) <<  8)
8566        + ((u32)(aBuf[0]) <<  0);
8567 }
8568 
8569 /*
8570 ** Write a 16-bit little endiate integer into buffer aBuf.
8571 */
8572 static void zipfilePutU16(u8 *aBuf, u16 val){
8573   aBuf[0] = val & 0xFF;
8574   aBuf[1] = (val>>8) & 0xFF;
8575 }
8576 
8577 /*
8578 ** Write a 32-bit little endiate integer into buffer aBuf.
8579 */
8580 static void zipfilePutU32(u8 *aBuf, u32 val){
8581   aBuf[0] = val & 0xFF;
8582   aBuf[1] = (val>>8) & 0xFF;
8583   aBuf[2] = (val>>16) & 0xFF;
8584   aBuf[3] = (val>>24) & 0xFF;
8585 }
8586 
8587 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
8588 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
8589 
8590 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
8591 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
8592 
8593 /*
8594 ** Magic numbers used to read CDS records.
8595 */
8596 #define ZIPFILE_CDS_NFILE_OFF        28
8597 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
8598 
8599 /*
8600 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
8601 ** if the record is not well-formed, or SQLITE_OK otherwise.
8602 */
8603 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
8604   u8 *aRead = aBuf;
8605   u32 sig = zipfileRead32(aRead);
8606   int rc = SQLITE_OK;
8607   if( sig!=ZIPFILE_SIGNATURE_CDS ){
8608     rc = SQLITE_ERROR;
8609   }else{
8610     pCDS->iVersionMadeBy = zipfileRead16(aRead);
8611     pCDS->iVersionExtract = zipfileRead16(aRead);
8612     pCDS->flags = zipfileRead16(aRead);
8613     pCDS->iCompression = zipfileRead16(aRead);
8614     pCDS->mTime = zipfileRead16(aRead);
8615     pCDS->mDate = zipfileRead16(aRead);
8616     pCDS->crc32 = zipfileRead32(aRead);
8617     pCDS->szCompressed = zipfileRead32(aRead);
8618     pCDS->szUncompressed = zipfileRead32(aRead);
8619     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
8620     pCDS->nFile = zipfileRead16(aRead);
8621     pCDS->nExtra = zipfileRead16(aRead);
8622     pCDS->nComment = zipfileRead16(aRead);
8623     pCDS->iDiskStart = zipfileRead16(aRead);
8624     pCDS->iInternalAttr = zipfileRead16(aRead);
8625     pCDS->iExternalAttr = zipfileRead32(aRead);
8626     pCDS->iOffset = zipfileRead32(aRead);
8627     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
8628   }
8629 
8630   return rc;
8631 }
8632 
8633 /*
8634 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
8635 ** if the record is not well-formed, or SQLITE_OK otherwise.
8636 */
8637 static int zipfileReadLFH(
8638   u8 *aBuffer,
8639   ZipfileLFH *pLFH
8640 ){
8641   u8 *aRead = aBuffer;
8642   int rc = SQLITE_OK;
8643 
8644   u32 sig = zipfileRead32(aRead);
8645   if( sig!=ZIPFILE_SIGNATURE_LFH ){
8646     rc = SQLITE_ERROR;
8647   }else{
8648     pLFH->iVersionExtract = zipfileRead16(aRead);
8649     pLFH->flags = zipfileRead16(aRead);
8650     pLFH->iCompression = zipfileRead16(aRead);
8651     pLFH->mTime = zipfileRead16(aRead);
8652     pLFH->mDate = zipfileRead16(aRead);
8653     pLFH->crc32 = zipfileRead32(aRead);
8654     pLFH->szCompressed = zipfileRead32(aRead);
8655     pLFH->szUncompressed = zipfileRead32(aRead);
8656     pLFH->nFile = zipfileRead16(aRead);
8657     pLFH->nExtra = zipfileRead16(aRead);
8658   }
8659   return rc;
8660 }
8661 
8662 
8663 /*
8664 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
8665 ** Scan through this buffer to find an "extra-timestamp" field. If one
8666 ** exists, extract the 32-bit modification-timestamp from it and store
8667 ** the value in output parameter *pmTime.
8668 **
8669 ** Zero is returned if no extra-timestamp record could be found (and so
8670 ** *pmTime is left unchanged), or non-zero otherwise.
8671 **
8672 ** The general format of an extra field is:
8673 **
8674 **   Header ID    2 bytes
8675 **   Data Size    2 bytes
8676 **   Data         N bytes
8677 */
8678 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
8679   int ret = 0;
8680   u8 *p = aExtra;
8681   u8 *pEnd = &aExtra[nExtra];
8682 
8683   while( p<pEnd ){
8684     u16 id = zipfileRead16(p);
8685     u16 nByte = zipfileRead16(p);
8686 
8687     switch( id ){
8688       case ZIPFILE_EXTRA_TIMESTAMP: {
8689         u8 b = p[0];
8690         if( b & 0x01 ){     /* 0x01 -> modtime is present */
8691           *pmTime = zipfileGetU32(&p[1]);
8692           ret = 1;
8693         }
8694         break;
8695       }
8696     }
8697 
8698     p += nByte;
8699   }
8700   return ret;
8701 }
8702 
8703 /*
8704 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
8705 ** fields of the CDS structure passed as the only argument to a 32-bit
8706 ** UNIX seconds-since-the-epoch timestamp. Return the result.
8707 **
8708 ** "Standard" MS-DOS time format:
8709 **
8710 **   File modification time:
8711 **     Bits 00-04: seconds divided by 2
8712 **     Bits 05-10: minute
8713 **     Bits 11-15: hour
8714 **   File modification date:
8715 **     Bits 00-04: day
8716 **     Bits 05-08: month (1-12)
8717 **     Bits 09-15: years from 1980
8718 **
8719 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
8720 */
8721 static u32 zipfileMtime(ZipfileCDS *pCDS){
8722   int Y,M,D,X1,X2,A,B,sec,min,hr;
8723   i64 JDsec;
8724   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
8725   M = ((pCDS->mDate >> 5) & 0x0F);
8726   D = (pCDS->mDate & 0x1F);
8727   sec = (pCDS->mTime & 0x1F)*2;
8728   min = (pCDS->mTime >> 5) & 0x3F;
8729   hr = (pCDS->mTime >> 11) & 0x1F;
8730   if( M<=2 ){
8731     Y--;
8732     M += 12;
8733   }
8734   X1 = 36525*(Y+4716)/100;
8735   X2 = 306001*(M+1)/10000;
8736   A = Y/100;
8737   B = 2 - A + (A/4);
8738   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
8739   return (u32)(JDsec - (i64)24405875*(i64)8640);
8740 }
8741 
8742 /*
8743 ** The opposite of zipfileMtime(). This function populates the mTime and
8744 ** mDate fields of the CDS structure passed as the first argument according
8745 ** to the UNIX timestamp value passed as the second.
8746 */
8747 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
8748   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
8749   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
8750 
8751   int A, B, C, D, E;
8752   int yr, mon, day;
8753   int hr, min, sec;
8754 
8755   A = (int)((JD - 1867216.25)/36524.25);
8756   A = (int)(JD + 1 + A - (A/4));
8757   B = A + 1524;
8758   C = (int)((B - 122.1)/365.25);
8759   D = (36525*(C&32767))/100;
8760   E = (int)((B-D)/30.6001);
8761 
8762   day = B - D - (int)(30.6001*E);
8763   mon = (E<14 ? E-1 : E-13);
8764   yr = mon>2 ? C-4716 : C-4715;
8765 
8766   hr = (mUnixTime % (24*60*60)) / (60*60);
8767   min = (mUnixTime % (60*60)) / 60;
8768   sec = (mUnixTime % 60);
8769 
8770   if( yr>=1980 ){
8771     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
8772     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
8773   }else{
8774     pCds->mDate = pCds->mTime = 0;
8775   }
8776 
8777   assert( mUnixTime<315507600
8778        || mUnixTime==zipfileMtime(pCds)
8779        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
8780        /* || (mUnixTime % 2) */
8781   );
8782 }
8783 
8784 /*
8785 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
8786 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
8787 ** then pFile is a file-handle open on a zip file. In either case, this
8788 ** function creates a ZipfileEntry object based on the zip archive entry
8789 ** for which the CDS record is at offset iOff.
8790 **
8791 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
8792 ** the new object. Otherwise, an SQLite error code is returned and the
8793 ** final value of (*ppEntry) undefined.
8794 */
8795 static int zipfileGetEntry(
8796   ZipfileTab *pTab,               /* Store any error message here */
8797   const u8 *aBlob,                /* Pointer to in-memory file image */
8798   int nBlob,                      /* Size of aBlob[] in bytes */
8799   FILE *pFile,                    /* If aBlob==0, read from this file */
8800   i64 iOff,                       /* Offset of CDS record */
8801   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
8802 ){
8803   u8 *aRead;
8804   char **pzErr = &pTab->base.zErrMsg;
8805   int rc = SQLITE_OK;
8806   (void)nBlob;
8807 
8808   if( aBlob==0 ){
8809     aRead = pTab->aBuffer;
8810     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
8811   }else{
8812     aRead = (u8*)&aBlob[iOff];
8813   }
8814 
8815   if( rc==SQLITE_OK ){
8816     sqlite3_int64 nAlloc;
8817     ZipfileEntry *pNew;
8818 
8819     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
8820     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
8821     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
8822 
8823     nAlloc = sizeof(ZipfileEntry) + nExtra;
8824     if( aBlob ){
8825       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
8826     }
8827 
8828     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
8829     if( pNew==0 ){
8830       rc = SQLITE_NOMEM;
8831     }else{
8832       memset(pNew, 0, sizeof(ZipfileEntry));
8833       rc = zipfileReadCDS(aRead, &pNew->cds);
8834       if( rc!=SQLITE_OK ){
8835         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
8836       }else if( aBlob==0 ){
8837         rc = zipfileReadData(
8838             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
8839         );
8840       }else{
8841         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
8842       }
8843     }
8844 
8845     if( rc==SQLITE_OK ){
8846       u32 *pt = &pNew->mUnixTime;
8847       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
8848       pNew->aExtra = (u8*)&pNew[1];
8849       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
8850       if( pNew->cds.zFile==0 ){
8851         rc = SQLITE_NOMEM;
8852       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
8853         pNew->mUnixTime = zipfileMtime(&pNew->cds);
8854       }
8855     }
8856 
8857     if( rc==SQLITE_OK ){
8858       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
8859       ZipfileLFH lfh;
8860       if( pFile ){
8861         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
8862       }else{
8863         aRead = (u8*)&aBlob[pNew->cds.iOffset];
8864       }
8865 
8866       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
8867       if( rc==SQLITE_OK ){
8868         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
8869         pNew->iDataOff += lfh.nFile + lfh.nExtra;
8870         if( aBlob && pNew->cds.szCompressed ){
8871           pNew->aData = &pNew->aExtra[nExtra];
8872           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
8873         }
8874       }else{
8875         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
8876             (int)pNew->cds.iOffset
8877         );
8878       }
8879     }
8880 
8881     if( rc!=SQLITE_OK ){
8882       zipfileEntryFree(pNew);
8883     }else{
8884       *ppEntry = pNew;
8885     }
8886   }
8887 
8888   return rc;
8889 }
8890 
8891 /*
8892 ** Advance an ZipfileCsr to its next row of output.
8893 */
8894 static int zipfileNext(sqlite3_vtab_cursor *cur){
8895   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8896   int rc = SQLITE_OK;
8897 
8898   if( pCsr->pFile ){
8899     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
8900     zipfileEntryFree(pCsr->pCurrent);
8901     pCsr->pCurrent = 0;
8902     if( pCsr->iNextOff>=iEof ){
8903       pCsr->bEof = 1;
8904     }else{
8905       ZipfileEntry *p = 0;
8906       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
8907       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
8908       if( rc==SQLITE_OK ){
8909         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
8910         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
8911       }
8912       pCsr->pCurrent = p;
8913     }
8914   }else{
8915     if( !pCsr->bNoop ){
8916       pCsr->pCurrent = pCsr->pCurrent->pNext;
8917     }
8918     if( pCsr->pCurrent==0 ){
8919       pCsr->bEof = 1;
8920     }
8921   }
8922 
8923   pCsr->bNoop = 0;
8924   return rc;
8925 }
8926 
8927 static void zipfileFree(void *p) {
8928   sqlite3_free(p);
8929 }
8930 
8931 /*
8932 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
8933 ** size is nOut bytes. This function uncompresses the data and sets the
8934 ** return value in context pCtx to the result (a blob).
8935 **
8936 ** If an error occurs, an error code is left in pCtx instead.
8937 */
8938 static void zipfileInflate(
8939   sqlite3_context *pCtx,          /* Store result here */
8940   const u8 *aIn,                  /* Compressed data */
8941   int nIn,                        /* Size of buffer aIn[] in bytes */
8942   int nOut                        /* Expected output size */
8943 ){
8944   u8 *aRes = sqlite3_malloc(nOut);
8945   if( aRes==0 ){
8946     sqlite3_result_error_nomem(pCtx);
8947   }else{
8948     int err;
8949     z_stream str;
8950     memset(&str, 0, sizeof(str));
8951 
8952     str.next_in = (Byte*)aIn;
8953     str.avail_in = nIn;
8954     str.next_out = (Byte*)aRes;
8955     str.avail_out = nOut;
8956 
8957     err = inflateInit2(&str, -15);
8958     if( err!=Z_OK ){
8959       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
8960     }else{
8961       err = inflate(&str, Z_NO_FLUSH);
8962       if( err!=Z_STREAM_END ){
8963         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
8964       }else{
8965         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
8966         aRes = 0;
8967       }
8968     }
8969     sqlite3_free(aRes);
8970     inflateEnd(&str);
8971   }
8972 }
8973 
8974 /*
8975 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
8976 ** compresses it and sets (*ppOut) to point to a buffer containing the
8977 ** compressed data. The caller is responsible for eventually calling
8978 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
8979 ** is set to the size of buffer (*ppOut) in bytes.
8980 **
8981 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
8982 ** code is returned and an error message left in virtual-table handle
8983 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
8984 ** case.
8985 */
8986 static int zipfileDeflate(
8987   const u8 *aIn, int nIn,         /* Input */
8988   u8 **ppOut, int *pnOut,         /* Output */
8989   char **pzErr                    /* OUT: Error message */
8990 ){
8991   int rc = SQLITE_OK;
8992   sqlite3_int64 nAlloc;
8993   z_stream str;
8994   u8 *aOut;
8995 
8996   memset(&str, 0, sizeof(str));
8997   str.next_in = (Bytef*)aIn;
8998   str.avail_in = nIn;
8999   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
9000 
9001   nAlloc = deflateBound(&str, nIn);
9002   aOut = (u8*)sqlite3_malloc64(nAlloc);
9003   if( aOut==0 ){
9004     rc = SQLITE_NOMEM;
9005   }else{
9006     int res;
9007     str.next_out = aOut;
9008     str.avail_out = nAlloc;
9009     res = deflate(&str, Z_FINISH);
9010     if( res==Z_STREAM_END ){
9011       *ppOut = aOut;
9012       *pnOut = (int)str.total_out;
9013     }else{
9014       sqlite3_free(aOut);
9015       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
9016       rc = SQLITE_ERROR;
9017     }
9018     deflateEnd(&str);
9019   }
9020 
9021   return rc;
9022 }
9023 
9024 
9025 /*
9026 ** Return values of columns for the row at which the series_cursor
9027 ** is currently pointing.
9028 */
9029 static int zipfileColumn(
9030   sqlite3_vtab_cursor *cur,   /* The cursor */
9031   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
9032   int i                       /* Which column to return */
9033 ){
9034   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9035   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
9036   int rc = SQLITE_OK;
9037   switch( i ){
9038     case 0:   /* name */
9039       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
9040       break;
9041     case 1:   /* mode */
9042       /* TODO: Whether or not the following is correct surely depends on
9043       ** the platform on which the archive was created.  */
9044       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
9045       break;
9046     case 2: { /* mtime */
9047       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
9048       break;
9049     }
9050     case 3: { /* sz */
9051       if( sqlite3_vtab_nochange(ctx)==0 ){
9052         sqlite3_result_int64(ctx, pCDS->szUncompressed);
9053       }
9054       break;
9055     }
9056     case 4:   /* rawdata */
9057       if( sqlite3_vtab_nochange(ctx) ) break;
9058     case 5: { /* data */
9059       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
9060         int sz = pCDS->szCompressed;
9061         int szFinal = pCDS->szUncompressed;
9062         if( szFinal>0 ){
9063           u8 *aBuf;
9064           u8 *aFree = 0;
9065           if( pCsr->pCurrent->aData ){
9066             aBuf = pCsr->pCurrent->aData;
9067           }else{
9068             aBuf = aFree = sqlite3_malloc64(sz);
9069             if( aBuf==0 ){
9070               rc = SQLITE_NOMEM;
9071             }else{
9072               FILE *pFile = pCsr->pFile;
9073               if( pFile==0 ){
9074                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
9075               }
9076               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
9077                   &pCsr->base.pVtab->zErrMsg
9078               );
9079             }
9080           }
9081           if( rc==SQLITE_OK ){
9082             if( i==5 && pCDS->iCompression ){
9083               zipfileInflate(ctx, aBuf, sz, szFinal);
9084             }else{
9085               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
9086             }
9087           }
9088           sqlite3_free(aFree);
9089         }else{
9090           /* Figure out if this is a directory or a zero-sized file. Consider
9091           ** it to be a directory either if the mode suggests so, or if
9092           ** the final character in the name is '/'.  */
9093           u32 mode = pCDS->iExternalAttr >> 16;
9094           if( !(mode & S_IFDIR)
9095            && pCDS->nFile>=1
9096            && pCDS->zFile[pCDS->nFile-1]!='/'
9097           ){
9098             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
9099           }
9100         }
9101       }
9102       break;
9103     }
9104     case 6:   /* method */
9105       sqlite3_result_int(ctx, pCDS->iCompression);
9106       break;
9107     default:  /* z */
9108       assert( i==7 );
9109       sqlite3_result_int64(ctx, pCsr->iId);
9110       break;
9111   }
9112 
9113   return rc;
9114 }
9115 
9116 /*
9117 ** Return TRUE if the cursor is at EOF.
9118 */
9119 static int zipfileEof(sqlite3_vtab_cursor *cur){
9120   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9121   return pCsr->bEof;
9122 }
9123 
9124 /*
9125 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
9126 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
9127 ** is guaranteed to be a file-handle open on a zip file.
9128 **
9129 ** This function attempts to locate the EOCD record within the zip archive
9130 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
9131 ** returned if successful. Otherwise, an SQLite error code is returned and
9132 ** an English language error message may be left in virtual-table pTab.
9133 */
9134 static int zipfileReadEOCD(
9135   ZipfileTab *pTab,               /* Return errors here */
9136   const u8 *aBlob,                /* Pointer to in-memory file image */
9137   int nBlob,                      /* Size of aBlob[] in bytes */
9138   FILE *pFile,                    /* Read from this file if aBlob==0 */
9139   ZipfileEOCD *pEOCD              /* Object to populate */
9140 ){
9141   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
9142   int nRead;                      /* Bytes to read from file */
9143   int rc = SQLITE_OK;
9144 
9145   memset(pEOCD, 0, sizeof(ZipfileEOCD));
9146   if( aBlob==0 ){
9147     i64 iOff;                     /* Offset to read from */
9148     i64 szFile;                   /* Total size of file in bytes */
9149     fseek(pFile, 0, SEEK_END);
9150     szFile = (i64)ftell(pFile);
9151     if( szFile==0 ){
9152       return SQLITE_OK;
9153     }
9154     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
9155     iOff = szFile - nRead;
9156     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
9157   }else{
9158     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
9159     aRead = (u8*)&aBlob[nBlob-nRead];
9160   }
9161 
9162   if( rc==SQLITE_OK ){
9163     int i;
9164 
9165     /* Scan backwards looking for the signature bytes */
9166     for(i=nRead-20; i>=0; i--){
9167       if( aRead[i]==0x50 && aRead[i+1]==0x4b
9168        && aRead[i+2]==0x05 && aRead[i+3]==0x06
9169       ){
9170         break;
9171       }
9172     }
9173     if( i<0 ){
9174       pTab->base.zErrMsg = sqlite3_mprintf(
9175           "cannot find end of central directory record"
9176       );
9177       return SQLITE_ERROR;
9178     }
9179 
9180     aRead += i+4;
9181     pEOCD->iDisk = zipfileRead16(aRead);
9182     pEOCD->iFirstDisk = zipfileRead16(aRead);
9183     pEOCD->nEntry = zipfileRead16(aRead);
9184     pEOCD->nEntryTotal = zipfileRead16(aRead);
9185     pEOCD->nSize = zipfileRead32(aRead);
9186     pEOCD->iOffset = zipfileRead32(aRead);
9187   }
9188 
9189   return rc;
9190 }
9191 
9192 /*
9193 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
9194 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
9195 ** to the end of the list. Otherwise, it is added to the list immediately
9196 ** before pBefore (which is guaranteed to be a part of said list).
9197 */
9198 static void zipfileAddEntry(
9199   ZipfileTab *pTab,
9200   ZipfileEntry *pBefore,
9201   ZipfileEntry *pNew
9202 ){
9203   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
9204   assert( pNew->pNext==0 );
9205   if( pBefore==0 ){
9206     if( pTab->pFirstEntry==0 ){
9207       pTab->pFirstEntry = pTab->pLastEntry = pNew;
9208     }else{
9209       assert( pTab->pLastEntry->pNext==0 );
9210       pTab->pLastEntry->pNext = pNew;
9211       pTab->pLastEntry = pNew;
9212     }
9213   }else{
9214     ZipfileEntry **pp;
9215     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
9216     pNew->pNext = pBefore;
9217     *pp = pNew;
9218   }
9219 }
9220 
9221 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
9222   ZipfileEOCD eocd;
9223   int rc;
9224   int i;
9225   i64 iOff;
9226 
9227   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
9228   iOff = eocd.iOffset;
9229   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
9230     ZipfileEntry *pNew = 0;
9231     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
9232 
9233     if( rc==SQLITE_OK ){
9234       zipfileAddEntry(pTab, 0, pNew);
9235       iOff += ZIPFILE_CDS_FIXED_SZ;
9236       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
9237     }
9238   }
9239   return rc;
9240 }
9241 
9242 /*
9243 ** xFilter callback.
9244 */
9245 static int zipfileFilter(
9246   sqlite3_vtab_cursor *cur,
9247   int idxNum, const char *idxStr,
9248   int argc, sqlite3_value **argv
9249 ){
9250   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
9251   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9252   const char *zFile = 0;          /* Zip file to scan */
9253   int rc = SQLITE_OK;             /* Return Code */
9254   int bInMemory = 0;              /* True for an in-memory zipfile */
9255 
9256   (void)idxStr;
9257   (void)argc;
9258 
9259   zipfileResetCursor(pCsr);
9260 
9261   if( pTab->zFile ){
9262     zFile = pTab->zFile;
9263   }else if( idxNum==0 ){
9264     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
9265     return SQLITE_ERROR;
9266   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
9267     static const u8 aEmptyBlob = 0;
9268     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
9269     int nBlob = sqlite3_value_bytes(argv[0]);
9270     assert( pTab->pFirstEntry==0 );
9271     if( aBlob==0 ){
9272       aBlob = &aEmptyBlob;
9273       nBlob = 0;
9274     }
9275     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
9276     pCsr->pFreeEntry = pTab->pFirstEntry;
9277     pTab->pFirstEntry = pTab->pLastEntry = 0;
9278     if( rc!=SQLITE_OK ) return rc;
9279     bInMemory = 1;
9280   }else{
9281     zFile = (const char*)sqlite3_value_text(argv[0]);
9282   }
9283 
9284   if( 0==pTab->pWriteFd && 0==bInMemory ){
9285     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
9286     if( pCsr->pFile==0 ){
9287       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
9288       rc = SQLITE_ERROR;
9289     }else{
9290       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
9291       if( rc==SQLITE_OK ){
9292         if( pCsr->eocd.nEntry==0 ){
9293           pCsr->bEof = 1;
9294         }else{
9295           pCsr->iNextOff = pCsr->eocd.iOffset;
9296           rc = zipfileNext(cur);
9297         }
9298       }
9299     }
9300   }else{
9301     pCsr->bNoop = 1;
9302     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
9303     rc = zipfileNext(cur);
9304   }
9305 
9306   return rc;
9307 }
9308 
9309 /*
9310 ** xBestIndex callback.
9311 */
9312 static int zipfileBestIndex(
9313   sqlite3_vtab *tab,
9314   sqlite3_index_info *pIdxInfo
9315 ){
9316   int i;
9317   int idx = -1;
9318   int unusable = 0;
9319   (void)tab;
9320 
9321   for(i=0; i<pIdxInfo->nConstraint; i++){
9322     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
9323     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
9324     if( pCons->usable==0 ){
9325       unusable = 1;
9326     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9327       idx = i;
9328     }
9329   }
9330   pIdxInfo->estimatedCost = 1000.0;
9331   if( idx>=0 ){
9332     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
9333     pIdxInfo->aConstraintUsage[idx].omit = 1;
9334     pIdxInfo->idxNum = 1;
9335   }else if( unusable ){
9336     return SQLITE_CONSTRAINT;
9337   }
9338   return SQLITE_OK;
9339 }
9340 
9341 static ZipfileEntry *zipfileNewEntry(const char *zPath){
9342   ZipfileEntry *pNew;
9343   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
9344   if( pNew ){
9345     memset(pNew, 0, sizeof(ZipfileEntry));
9346     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
9347     if( pNew->cds.zFile==0 ){
9348       sqlite3_free(pNew);
9349       pNew = 0;
9350     }
9351   }
9352   return pNew;
9353 }
9354 
9355 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
9356   ZipfileCDS *pCds = &pEntry->cds;
9357   u8 *a = aBuf;
9358 
9359   pCds->nExtra = 9;
9360 
9361   /* Write the LFH itself */
9362   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
9363   zipfileWrite16(a, pCds->iVersionExtract);
9364   zipfileWrite16(a, pCds->flags);
9365   zipfileWrite16(a, pCds->iCompression);
9366   zipfileWrite16(a, pCds->mTime);
9367   zipfileWrite16(a, pCds->mDate);
9368   zipfileWrite32(a, pCds->crc32);
9369   zipfileWrite32(a, pCds->szCompressed);
9370   zipfileWrite32(a, pCds->szUncompressed);
9371   zipfileWrite16(a, (u16)pCds->nFile);
9372   zipfileWrite16(a, pCds->nExtra);
9373   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
9374 
9375   /* Add the file name */
9376   memcpy(a, pCds->zFile, (int)pCds->nFile);
9377   a += (int)pCds->nFile;
9378 
9379   /* The "extra" data */
9380   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9381   zipfileWrite16(a, 5);
9382   *a++ = 0x01;
9383   zipfileWrite32(a, pEntry->mUnixTime);
9384 
9385   return a-aBuf;
9386 }
9387 
9388 static int zipfileAppendEntry(
9389   ZipfileTab *pTab,
9390   ZipfileEntry *pEntry,
9391   const u8 *pData,
9392   int nData
9393 ){
9394   u8 *aBuf = pTab->aBuffer;
9395   int nBuf;
9396   int rc;
9397 
9398   nBuf = zipfileSerializeLFH(pEntry, aBuf);
9399   rc = zipfileAppendData(pTab, aBuf, nBuf);
9400   if( rc==SQLITE_OK ){
9401     pEntry->iDataOff = pTab->szCurrent;
9402     rc = zipfileAppendData(pTab, pData, nData);
9403   }
9404 
9405   return rc;
9406 }
9407 
9408 static int zipfileGetMode(
9409   sqlite3_value *pVal,
9410   int bIsDir,                     /* If true, default to directory */
9411   u32 *pMode,                     /* OUT: Mode value */
9412   char **pzErr                    /* OUT: Error message */
9413 ){
9414   const char *z = (const char*)sqlite3_value_text(pVal);
9415   u32 mode = 0;
9416   if( z==0 ){
9417     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
9418   }else if( z[0]>='0' && z[0]<='9' ){
9419     mode = (unsigned int)sqlite3_value_int(pVal);
9420   }else{
9421     const char zTemplate[11] = "-rwxrwxrwx";
9422     int i;
9423     if( strlen(z)!=10 ) goto parse_error;
9424     switch( z[0] ){
9425       case '-': mode |= S_IFREG; break;
9426       case 'd': mode |= S_IFDIR; break;
9427       case 'l': mode |= S_IFLNK; break;
9428       default: goto parse_error;
9429     }
9430     for(i=1; i<10; i++){
9431       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
9432       else if( z[i]!='-' ) goto parse_error;
9433     }
9434   }
9435   if( ((mode & S_IFDIR)==0)==bIsDir ){
9436     /* The "mode" attribute is a directory, but data has been specified.
9437     ** Or vice-versa - no data but "mode" is a file or symlink.  */
9438     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
9439     return SQLITE_CONSTRAINT;
9440   }
9441   *pMode = mode;
9442   return SQLITE_OK;
9443 
9444  parse_error:
9445   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
9446   return SQLITE_ERROR;
9447 }
9448 
9449 /*
9450 ** Both (const char*) arguments point to nul-terminated strings. Argument
9451 ** nB is the value of strlen(zB). This function returns 0 if the strings are
9452 ** identical, ignoring any trailing '/' character in either path.  */
9453 static int zipfileComparePath(const char *zA, const char *zB, int nB){
9454   int nA = (int)strlen(zA);
9455   if( nA>0 && zA[nA-1]=='/' ) nA--;
9456   if( nB>0 && zB[nB-1]=='/' ) nB--;
9457   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
9458   return 1;
9459 }
9460 
9461 static int zipfileBegin(sqlite3_vtab *pVtab){
9462   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9463   int rc = SQLITE_OK;
9464 
9465   assert( pTab->pWriteFd==0 );
9466   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
9467     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
9468     return SQLITE_ERROR;
9469   }
9470 
9471   /* Open a write fd on the file. Also load the entire central directory
9472   ** structure into memory. During the transaction any new file data is
9473   ** appended to the archive file, but the central directory is accumulated
9474   ** in main-memory until the transaction is committed.  */
9475   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
9476   if( pTab->pWriteFd==0 ){
9477     pTab->base.zErrMsg = sqlite3_mprintf(
9478         "zipfile: failed to open file %s for writing", pTab->zFile
9479         );
9480     rc = SQLITE_ERROR;
9481   }else{
9482     fseek(pTab->pWriteFd, 0, SEEK_END);
9483     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
9484     rc = zipfileLoadDirectory(pTab, 0, 0);
9485   }
9486 
9487   if( rc!=SQLITE_OK ){
9488     zipfileCleanupTransaction(pTab);
9489   }
9490 
9491   return rc;
9492 }
9493 
9494 /*
9495 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
9496 ** time(2)).
9497 */
9498 static u32 zipfileTime(void){
9499   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
9500   u32 ret;
9501   if( pVfs==0 ) return 0;
9502   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
9503     i64 ms;
9504     pVfs->xCurrentTimeInt64(pVfs, &ms);
9505     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
9506   }else{
9507     double day;
9508     pVfs->xCurrentTime(pVfs, &day);
9509     ret = (u32)((day - 2440587.5) * 86400);
9510   }
9511   return ret;
9512 }
9513 
9514 /*
9515 ** Return a 32-bit timestamp in UNIX epoch format.
9516 **
9517 ** If the value passed as the only argument is either NULL or an SQL NULL,
9518 ** return the current time. Otherwise, return the value stored in (*pVal)
9519 ** cast to a 32-bit unsigned integer.
9520 */
9521 static u32 zipfileGetTime(sqlite3_value *pVal){
9522   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
9523     return zipfileTime();
9524   }
9525   return (u32)sqlite3_value_int64(pVal);
9526 }
9527 
9528 /*
9529 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
9530 ** linked list.  Remove it from the list and free the object.
9531 */
9532 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
9533   if( pOld ){
9534     if( pTab->pFirstEntry==pOld ){
9535       pTab->pFirstEntry = pOld->pNext;
9536       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
9537     }else{
9538       ZipfileEntry *p;
9539       for(p=pTab->pFirstEntry; p; p=p->pNext){
9540         if( p->pNext==pOld ){
9541           p->pNext = pOld->pNext;
9542           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
9543           break;
9544         }
9545       }
9546     }
9547     zipfileEntryFree(pOld);
9548   }
9549 }
9550 
9551 /*
9552 ** xUpdate method.
9553 */
9554 static int zipfileUpdate(
9555   sqlite3_vtab *pVtab,
9556   int nVal,
9557   sqlite3_value **apVal,
9558   sqlite_int64 *pRowid
9559 ){
9560   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9561   int rc = SQLITE_OK;             /* Return Code */
9562   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
9563 
9564   u32 mode = 0;                   /* Mode for new entry */
9565   u32 mTime = 0;                  /* Modification time for new entry */
9566   i64 sz = 0;                     /* Uncompressed size */
9567   const char *zPath = 0;          /* Path for new entry */
9568   int nPath = 0;                  /* strlen(zPath) */
9569   const u8 *pData = 0;            /* Pointer to buffer containing content */
9570   int nData = 0;                  /* Size of pData buffer in bytes */
9571   int iMethod = 0;                /* Compression method for new entry */
9572   u8 *pFree = 0;                  /* Free this */
9573   char *zFree = 0;                /* Also free this */
9574   ZipfileEntry *pOld = 0;
9575   ZipfileEntry *pOld2 = 0;
9576   int bUpdate = 0;                /* True for an update that modifies "name" */
9577   int bIsDir = 0;
9578   u32 iCrc32 = 0;
9579 
9580   (void)pRowid;
9581 
9582   if( pTab->pWriteFd==0 ){
9583     rc = zipfileBegin(pVtab);
9584     if( rc!=SQLITE_OK ) return rc;
9585   }
9586 
9587   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
9588   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
9589     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
9590     int nDelete = (int)strlen(zDelete);
9591     if( nVal>1 ){
9592       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
9593       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
9594         bUpdate = 1;
9595       }
9596     }
9597     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
9598       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
9599         break;
9600       }
9601       assert( pOld->pNext );
9602     }
9603   }
9604 
9605   if( nVal>1 ){
9606     /* Check that "sz" and "rawdata" are both NULL: */
9607     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
9608       zipfileTableErr(pTab, "sz must be NULL");
9609       rc = SQLITE_CONSTRAINT;
9610     }
9611     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
9612       zipfileTableErr(pTab, "rawdata must be NULL");
9613       rc = SQLITE_CONSTRAINT;
9614     }
9615 
9616     if( rc==SQLITE_OK ){
9617       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
9618         /* data=NULL. A directory */
9619         bIsDir = 1;
9620       }else{
9621         /* Value specified for "data", and possibly "method". This must be
9622         ** a regular file or a symlink. */
9623         const u8 *aIn = sqlite3_value_blob(apVal[7]);
9624         int nIn = sqlite3_value_bytes(apVal[7]);
9625         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
9626 
9627         iMethod = sqlite3_value_int(apVal[8]);
9628         sz = nIn;
9629         pData = aIn;
9630         nData = nIn;
9631         if( iMethod!=0 && iMethod!=8 ){
9632           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
9633           rc = SQLITE_CONSTRAINT;
9634         }else{
9635           if( bAuto || iMethod ){
9636             int nCmp;
9637             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
9638             if( rc==SQLITE_OK ){
9639               if( iMethod || nCmp<nIn ){
9640                 iMethod = 8;
9641                 pData = pFree;
9642                 nData = nCmp;
9643               }
9644             }
9645           }
9646           iCrc32 = crc32(0, aIn, nIn);
9647         }
9648       }
9649     }
9650 
9651     if( rc==SQLITE_OK ){
9652       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
9653     }
9654 
9655     if( rc==SQLITE_OK ){
9656       zPath = (const char*)sqlite3_value_text(apVal[2]);
9657       if( zPath==0 ) zPath = "";
9658       nPath = (int)strlen(zPath);
9659       mTime = zipfileGetTime(apVal[4]);
9660     }
9661 
9662     if( rc==SQLITE_OK && bIsDir ){
9663       /* For a directory, check that the last character in the path is a
9664       ** '/'. This appears to be required for compatibility with info-zip
9665       ** (the unzip command on unix). It does not create directories
9666       ** otherwise.  */
9667       if( nPath<=0 || zPath[nPath-1]!='/' ){
9668         zFree = sqlite3_mprintf("%s/", zPath);
9669         zPath = (const char*)zFree;
9670         if( zFree==0 ){
9671           rc = SQLITE_NOMEM;
9672           nPath = 0;
9673         }else{
9674           nPath = (int)strlen(zPath);
9675         }
9676       }
9677     }
9678 
9679     /* Check that we're not inserting a duplicate entry -OR- updating an
9680     ** entry with a path, thereby making it into a duplicate. */
9681     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
9682       ZipfileEntry *p;
9683       for(p=pTab->pFirstEntry; p; p=p->pNext){
9684         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
9685           switch( sqlite3_vtab_on_conflict(pTab->db) ){
9686             case SQLITE_IGNORE: {
9687               goto zipfile_update_done;
9688             }
9689             case SQLITE_REPLACE: {
9690               pOld2 = p;
9691               break;
9692             }
9693             default: {
9694               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
9695               rc = SQLITE_CONSTRAINT;
9696               break;
9697             }
9698           }
9699           break;
9700         }
9701       }
9702     }
9703 
9704     if( rc==SQLITE_OK ){
9705       /* Create the new CDS record. */
9706       pNew = zipfileNewEntry(zPath);
9707       if( pNew==0 ){
9708         rc = SQLITE_NOMEM;
9709       }else{
9710         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
9711         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
9712         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
9713         pNew->cds.iCompression = (u16)iMethod;
9714         zipfileMtimeToDos(&pNew->cds, mTime);
9715         pNew->cds.crc32 = iCrc32;
9716         pNew->cds.szCompressed = nData;
9717         pNew->cds.szUncompressed = (u32)sz;
9718         pNew->cds.iExternalAttr = (mode<<16);
9719         pNew->cds.iOffset = (u32)pTab->szCurrent;
9720         pNew->cds.nFile = (u16)nPath;
9721         pNew->mUnixTime = (u32)mTime;
9722         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
9723         zipfileAddEntry(pTab, pOld, pNew);
9724       }
9725     }
9726   }
9727 
9728   if( rc==SQLITE_OK && (pOld || pOld2) ){
9729     ZipfileCsr *pCsr;
9730     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
9731       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
9732         pCsr->pCurrent = pCsr->pCurrent->pNext;
9733         pCsr->bNoop = 1;
9734       }
9735     }
9736 
9737     zipfileRemoveEntryFromList(pTab, pOld);
9738     zipfileRemoveEntryFromList(pTab, pOld2);
9739   }
9740 
9741 zipfile_update_done:
9742   sqlite3_free(pFree);
9743   sqlite3_free(zFree);
9744   return rc;
9745 }
9746 
9747 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
9748   u8 *a = aBuf;
9749   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
9750   zipfileWrite16(a, p->iDisk);
9751   zipfileWrite16(a, p->iFirstDisk);
9752   zipfileWrite16(a, p->nEntry);
9753   zipfileWrite16(a, p->nEntryTotal);
9754   zipfileWrite32(a, p->nSize);
9755   zipfileWrite32(a, p->iOffset);
9756   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
9757 
9758   return a-aBuf;
9759 }
9760 
9761 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
9762   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
9763   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
9764   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
9765 }
9766 
9767 /*
9768 ** Serialize the CDS structure into buffer aBuf[]. Return the number
9769 ** of bytes written.
9770 */
9771 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
9772   u8 *a = aBuf;
9773   ZipfileCDS *pCDS = &pEntry->cds;
9774 
9775   if( pEntry->aExtra==0 ){
9776     pCDS->nExtra = 9;
9777   }
9778 
9779   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
9780   zipfileWrite16(a, pCDS->iVersionMadeBy);
9781   zipfileWrite16(a, pCDS->iVersionExtract);
9782   zipfileWrite16(a, pCDS->flags);
9783   zipfileWrite16(a, pCDS->iCompression);
9784   zipfileWrite16(a, pCDS->mTime);
9785   zipfileWrite16(a, pCDS->mDate);
9786   zipfileWrite32(a, pCDS->crc32);
9787   zipfileWrite32(a, pCDS->szCompressed);
9788   zipfileWrite32(a, pCDS->szUncompressed);
9789   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9790   zipfileWrite16(a, pCDS->nFile);
9791   zipfileWrite16(a, pCDS->nExtra);
9792   zipfileWrite16(a, pCDS->nComment);
9793   zipfileWrite16(a, pCDS->iDiskStart);
9794   zipfileWrite16(a, pCDS->iInternalAttr);
9795   zipfileWrite32(a, pCDS->iExternalAttr);
9796   zipfileWrite32(a, pCDS->iOffset);
9797 
9798   memcpy(a, pCDS->zFile, pCDS->nFile);
9799   a += pCDS->nFile;
9800 
9801   if( pEntry->aExtra ){
9802     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
9803     memcpy(a, pEntry->aExtra, n);
9804     a += n;
9805   }else{
9806     assert( pCDS->nExtra==9 );
9807     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9808     zipfileWrite16(a, 5);
9809     *a++ = 0x01;
9810     zipfileWrite32(a, pEntry->mUnixTime);
9811   }
9812 
9813   return a-aBuf;
9814 }
9815 
9816 static int zipfileCommit(sqlite3_vtab *pVtab){
9817   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9818   int rc = SQLITE_OK;
9819   if( pTab->pWriteFd ){
9820     i64 iOffset = pTab->szCurrent;
9821     ZipfileEntry *p;
9822     ZipfileEOCD eocd;
9823     int nEntry = 0;
9824 
9825     /* Write out all entries */
9826     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
9827       int n = zipfileSerializeCDS(p, pTab->aBuffer);
9828       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
9829       nEntry++;
9830     }
9831 
9832     /* Write out the EOCD record */
9833     eocd.iDisk = 0;
9834     eocd.iFirstDisk = 0;
9835     eocd.nEntry = (u16)nEntry;
9836     eocd.nEntryTotal = (u16)nEntry;
9837     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
9838     eocd.iOffset = (u32)iOffset;
9839     rc = zipfileAppendEOCD(pTab, &eocd);
9840 
9841     zipfileCleanupTransaction(pTab);
9842   }
9843   return rc;
9844 }
9845 
9846 static int zipfileRollback(sqlite3_vtab *pVtab){
9847   return zipfileCommit(pVtab);
9848 }
9849 
9850 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
9851   ZipfileCsr *pCsr;
9852   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
9853     if( iId==pCsr->iId ) break;
9854   }
9855   return pCsr;
9856 }
9857 
9858 static void zipfileFunctionCds(
9859   sqlite3_context *context,
9860   int argc,
9861   sqlite3_value **argv
9862 ){
9863   ZipfileCsr *pCsr;
9864   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
9865   assert( argc>0 );
9866 
9867   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
9868   if( pCsr ){
9869     ZipfileCDS *p = &pCsr->pCurrent->cds;
9870     char *zRes = sqlite3_mprintf("{"
9871         "\"version-made-by\" : %u, "
9872         "\"version-to-extract\" : %u, "
9873         "\"flags\" : %u, "
9874         "\"compression\" : %u, "
9875         "\"time\" : %u, "
9876         "\"date\" : %u, "
9877         "\"crc32\" : %u, "
9878         "\"compressed-size\" : %u, "
9879         "\"uncompressed-size\" : %u, "
9880         "\"file-name-length\" : %u, "
9881         "\"extra-field-length\" : %u, "
9882         "\"file-comment-length\" : %u, "
9883         "\"disk-number-start\" : %u, "
9884         "\"internal-attr\" : %u, "
9885         "\"external-attr\" : %u, "
9886         "\"offset\" : %u }",
9887         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
9888         (u32)p->flags, (u32)p->iCompression,
9889         (u32)p->mTime, (u32)p->mDate,
9890         (u32)p->crc32, (u32)p->szCompressed,
9891         (u32)p->szUncompressed, (u32)p->nFile,
9892         (u32)p->nExtra, (u32)p->nComment,
9893         (u32)p->iDiskStart, (u32)p->iInternalAttr,
9894         (u32)p->iExternalAttr, (u32)p->iOffset
9895     );
9896 
9897     if( zRes==0 ){
9898       sqlite3_result_error_nomem(context);
9899     }else{
9900       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
9901       sqlite3_free(zRes);
9902     }
9903   }
9904 }
9905 
9906 /*
9907 ** xFindFunction method.
9908 */
9909 static int zipfileFindFunction(
9910   sqlite3_vtab *pVtab,            /* Virtual table handle */
9911   int nArg,                       /* Number of SQL function arguments */
9912   const char *zName,              /* Name of SQL function */
9913   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
9914   void **ppArg                    /* OUT: User data for *pxFunc */
9915 ){
9916   (void)nArg;
9917   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
9918     *pxFunc = zipfileFunctionCds;
9919     *ppArg = (void*)pVtab;
9920     return 1;
9921   }
9922   return 0;
9923 }
9924 
9925 typedef struct ZipfileBuffer ZipfileBuffer;
9926 struct ZipfileBuffer {
9927   u8 *a;                          /* Pointer to buffer */
9928   int n;                          /* Size of buffer in bytes */
9929   int nAlloc;                     /* Byte allocated at a[] */
9930 };
9931 
9932 typedef struct ZipfileCtx ZipfileCtx;
9933 struct ZipfileCtx {
9934   int nEntry;
9935   ZipfileBuffer body;
9936   ZipfileBuffer cds;
9937 };
9938 
9939 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
9940   if( pBuf->n+nByte>pBuf->nAlloc ){
9941     u8 *aNew;
9942     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
9943     int nReq = pBuf->n + nByte;
9944 
9945     while( nNew<nReq ) nNew = nNew*2;
9946     aNew = sqlite3_realloc64(pBuf->a, nNew);
9947     if( aNew==0 ) return SQLITE_NOMEM;
9948     pBuf->a = aNew;
9949     pBuf->nAlloc = (int)nNew;
9950   }
9951   return SQLITE_OK;
9952 }
9953 
9954 /*
9955 ** xStep() callback for the zipfile() aggregate. This can be called in
9956 ** any of the following ways:
9957 **
9958 **   SELECT zipfile(name,data) ...
9959 **   SELECT zipfile(name,mode,mtime,data) ...
9960 **   SELECT zipfile(name,mode,mtime,data,method) ...
9961 */
9962 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
9963   ZipfileCtx *p;                  /* Aggregate function context */
9964   ZipfileEntry e;                 /* New entry to add to zip archive */
9965 
9966   sqlite3_value *pName = 0;
9967   sqlite3_value *pMode = 0;
9968   sqlite3_value *pMtime = 0;
9969   sqlite3_value *pData = 0;
9970   sqlite3_value *pMethod = 0;
9971 
9972   int bIsDir = 0;
9973   u32 mode;
9974   int rc = SQLITE_OK;
9975   char *zErr = 0;
9976 
9977   int iMethod = -1;               /* Compression method to use (0 or 8) */
9978 
9979   const u8 *aData = 0;            /* Possibly compressed data for new entry */
9980   int nData = 0;                  /* Size of aData[] in bytes */
9981   int szUncompressed = 0;         /* Size of data before compression */
9982   u8 *aFree = 0;                  /* Free this before returning */
9983   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
9984 
9985   char *zName = 0;                /* Path (name) of new entry */
9986   int nName = 0;                  /* Size of zName in bytes */
9987   char *zFree = 0;                /* Free this before returning */
9988   int nByte;
9989 
9990   memset(&e, 0, sizeof(e));
9991   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
9992   if( p==0 ) return;
9993 
9994   /* Martial the arguments into stack variables */
9995   if( nVal!=2 && nVal!=4 && nVal!=5 ){
9996     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
9997     rc = SQLITE_ERROR;
9998     goto zipfile_step_out;
9999   }
10000   pName = apVal[0];
10001   if( nVal==2 ){
10002     pData = apVal[1];
10003   }else{
10004     pMode = apVal[1];
10005     pMtime = apVal[2];
10006     pData = apVal[3];
10007     if( nVal==5 ){
10008       pMethod = apVal[4];
10009     }
10010   }
10011 
10012   /* Check that the 'name' parameter looks ok. */
10013   zName = (char*)sqlite3_value_text(pName);
10014   nName = sqlite3_value_bytes(pName);
10015   if( zName==0 ){
10016     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
10017     rc = SQLITE_ERROR;
10018     goto zipfile_step_out;
10019   }
10020 
10021   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
10022   ** deflate compression) or NULL (choose automatically).  */
10023   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
10024     iMethod = (int)sqlite3_value_int64(pMethod);
10025     if( iMethod!=0 && iMethod!=8 ){
10026       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
10027       rc = SQLITE_ERROR;
10028       goto zipfile_step_out;
10029     }
10030   }
10031 
10032   /* Now inspect the data. If this is NULL, then the new entry must be a
10033   ** directory.  Otherwise, figure out whether or not the data should
10034   ** be deflated or simply stored in the zip archive. */
10035   if( sqlite3_value_type(pData)==SQLITE_NULL ){
10036     bIsDir = 1;
10037     iMethod = 0;
10038   }else{
10039     aData = sqlite3_value_blob(pData);
10040     szUncompressed = nData = sqlite3_value_bytes(pData);
10041     iCrc32 = crc32(0, aData, nData);
10042     if( iMethod<0 || iMethod==8 ){
10043       int nOut = 0;
10044       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
10045       if( rc!=SQLITE_OK ){
10046         goto zipfile_step_out;
10047       }
10048       if( iMethod==8 || nOut<nData ){
10049         aData = aFree;
10050         nData = nOut;
10051         iMethod = 8;
10052       }else{
10053         iMethod = 0;
10054       }
10055     }
10056   }
10057 
10058   /* Decode the "mode" argument. */
10059   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
10060   if( rc ) goto zipfile_step_out;
10061 
10062   /* Decode the "mtime" argument. */
10063   e.mUnixTime = zipfileGetTime(pMtime);
10064 
10065   /* If this is a directory entry, ensure that there is exactly one '/'
10066   ** at the end of the path. Or, if this is not a directory and the path
10067   ** ends in '/' it is an error. */
10068   if( bIsDir==0 ){
10069     if( nName>0 && zName[nName-1]=='/' ){
10070       zErr = sqlite3_mprintf("non-directory name must not end with /");
10071       rc = SQLITE_ERROR;
10072       goto zipfile_step_out;
10073     }
10074   }else{
10075     if( nName==0 || zName[nName-1]!='/' ){
10076       zName = zFree = sqlite3_mprintf("%s/", zName);
10077       if( zName==0 ){
10078         rc = SQLITE_NOMEM;
10079         goto zipfile_step_out;
10080       }
10081       nName = (int)strlen(zName);
10082     }else{
10083       while( nName>1 && zName[nName-2]=='/' ) nName--;
10084     }
10085   }
10086 
10087   /* Assemble the ZipfileEntry object for the new zip archive entry */
10088   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
10089   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
10090   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
10091   e.cds.iCompression = (u16)iMethod;
10092   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
10093   e.cds.crc32 = iCrc32;
10094   e.cds.szCompressed = nData;
10095   e.cds.szUncompressed = szUncompressed;
10096   e.cds.iExternalAttr = (mode<<16);
10097   e.cds.iOffset = p->body.n;
10098   e.cds.nFile = (u16)nName;
10099   e.cds.zFile = zName;
10100 
10101   /* Append the LFH to the body of the new archive */
10102   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
10103   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
10104   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
10105 
10106   /* Append the data to the body of the new archive */
10107   if( nData>0 ){
10108     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
10109     memcpy(&p->body.a[p->body.n], aData, nData);
10110     p->body.n += nData;
10111   }
10112 
10113   /* Append the CDS record to the directory of the new archive */
10114   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
10115   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
10116   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
10117 
10118   /* Increment the count of entries in the archive */
10119   p->nEntry++;
10120 
10121  zipfile_step_out:
10122   sqlite3_free(aFree);
10123   sqlite3_free(zFree);
10124   if( rc ){
10125     if( zErr ){
10126       sqlite3_result_error(pCtx, zErr, -1);
10127     }else{
10128       sqlite3_result_error_code(pCtx, rc);
10129     }
10130   }
10131   sqlite3_free(zErr);
10132 }
10133 
10134 /*
10135 ** xFinalize() callback for zipfile aggregate function.
10136 */
10137 static void zipfileFinal(sqlite3_context *pCtx){
10138   ZipfileCtx *p;
10139   ZipfileEOCD eocd;
10140   sqlite3_int64 nZip;
10141   u8 *aZip;
10142 
10143   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
10144   if( p==0 ) return;
10145   if( p->nEntry>0 ){
10146     memset(&eocd, 0, sizeof(eocd));
10147     eocd.nEntry = (u16)p->nEntry;
10148     eocd.nEntryTotal = (u16)p->nEntry;
10149     eocd.nSize = p->cds.n;
10150     eocd.iOffset = p->body.n;
10151 
10152     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
10153     aZip = (u8*)sqlite3_malloc64(nZip);
10154     if( aZip==0 ){
10155       sqlite3_result_error_nomem(pCtx);
10156     }else{
10157       memcpy(aZip, p->body.a, p->body.n);
10158       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
10159       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
10160       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
10161     }
10162   }
10163 
10164   sqlite3_free(p->body.a);
10165   sqlite3_free(p->cds.a);
10166 }
10167 
10168 
10169 /*
10170 ** Register the "zipfile" virtual table.
10171 */
10172 static int zipfileRegister(sqlite3 *db){
10173   static sqlite3_module zipfileModule = {
10174     1,                         /* iVersion */
10175     zipfileConnect,            /* xCreate */
10176     zipfileConnect,            /* xConnect */
10177     zipfileBestIndex,          /* xBestIndex */
10178     zipfileDisconnect,         /* xDisconnect */
10179     zipfileDisconnect,         /* xDestroy */
10180     zipfileOpen,               /* xOpen - open a cursor */
10181     zipfileClose,              /* xClose - close a cursor */
10182     zipfileFilter,             /* xFilter - configure scan constraints */
10183     zipfileNext,               /* xNext - advance a cursor */
10184     zipfileEof,                /* xEof - check for end of scan */
10185     zipfileColumn,             /* xColumn - read data */
10186     0,                         /* xRowid - read data */
10187     zipfileUpdate,             /* xUpdate */
10188     zipfileBegin,              /* xBegin */
10189     0,                         /* xSync */
10190     zipfileCommit,             /* xCommit */
10191     zipfileRollback,           /* xRollback */
10192     zipfileFindFunction,       /* xFindMethod */
10193     0,                         /* xRename */
10194     0,                         /* xSavepoint */
10195     0,                         /* xRelease */
10196     0,                         /* xRollback */
10197     0                          /* xShadowName */
10198   };
10199 
10200   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
10201   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
10202   if( rc==SQLITE_OK ){
10203     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
10204         zipfileStep, zipfileFinal
10205     );
10206   }
10207   assert( sizeof(i64)==8 );
10208   assert( sizeof(u32)==4 );
10209   assert( sizeof(u16)==2 );
10210   assert( sizeof(u8)==1 );
10211   return rc;
10212 }
10213 #else         /* SQLITE_OMIT_VIRTUALTABLE */
10214 # define zipfileRegister(x) SQLITE_OK
10215 #endif
10216 
10217 #ifdef _WIN32
10218 
10219 #endif
10220 int sqlite3_zipfile_init(
10221   sqlite3 *db,
10222   char **pzErrMsg,
10223   const sqlite3_api_routines *pApi
10224 ){
10225   SQLITE_EXTENSION_INIT2(pApi);
10226   (void)pzErrMsg;  /* Unused parameter */
10227   return zipfileRegister(db);
10228 }
10229 
10230 /************************* End ../ext/misc/zipfile.c ********************/
10231 /************************* Begin ../ext/misc/sqlar.c ******************/
10232 /*
10233 ** 2017-12-17
10234 **
10235 ** The author disclaims copyright to this source code.  In place of
10236 ** a legal notice, here is a blessing:
10237 **
10238 **    May you do good and not evil.
10239 **    May you find forgiveness for yourself and forgive others.
10240 **    May you share freely, never taking more than you give.
10241 **
10242 ******************************************************************************
10243 **
10244 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
10245 ** for working with sqlar archives and used by the shell tool's built-in
10246 ** sqlar support.
10247 */
10248 /* #include "sqlite3ext.h" */
10249 SQLITE_EXTENSION_INIT1
10250 #include <zlib.h>
10251 #include <assert.h>
10252 
10253 /*
10254 ** Implementation of the "sqlar_compress(X)" SQL function.
10255 **
10256 ** If the type of X is SQLITE_BLOB, and compressing that blob using
10257 ** zlib utility function compress() yields a smaller blob, return the
10258 ** compressed blob. Otherwise, return a copy of X.
10259 **
10260 ** SQLar uses the "zlib format" for compressed content.  The zlib format
10261 ** contains a two-byte identification header and a four-byte checksum at
10262 ** the end.  This is different from ZIP which uses the raw deflate format.
10263 **
10264 ** Future enhancements to SQLar might add support for new compression formats.
10265 ** If so, those new formats will be identified by alternative headers in the
10266 ** compressed data.
10267 */
10268 static void sqlarCompressFunc(
10269   sqlite3_context *context,
10270   int argc,
10271   sqlite3_value **argv
10272 ){
10273   assert( argc==1 );
10274   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10275     const Bytef *pData = sqlite3_value_blob(argv[0]);
10276     uLong nData = sqlite3_value_bytes(argv[0]);
10277     uLongf nOut = compressBound(nData);
10278     Bytef *pOut;
10279 
10280     pOut = (Bytef*)sqlite3_malloc(nOut);
10281     if( pOut==0 ){
10282       sqlite3_result_error_nomem(context);
10283       return;
10284     }else{
10285       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
10286         sqlite3_result_error(context, "error in compress()", -1);
10287       }else if( nOut<nData ){
10288         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
10289       }else{
10290         sqlite3_result_value(context, argv[0]);
10291       }
10292       sqlite3_free(pOut);
10293     }
10294   }else{
10295     sqlite3_result_value(context, argv[0]);
10296   }
10297 }
10298 
10299 /*
10300 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
10301 **
10302 ** Parameter SZ is interpreted as an integer. If it is less than or
10303 ** equal to zero, then this function returns a copy of X. Or, if
10304 ** SZ is equal to the size of X when interpreted as a blob, also
10305 ** return a copy of X. Otherwise, decompress blob X using zlib
10306 ** utility function uncompress() and return the results (another
10307 ** blob).
10308 */
10309 static void sqlarUncompressFunc(
10310   sqlite3_context *context,
10311   int argc,
10312   sqlite3_value **argv
10313 ){
10314   uLong nData;
10315   uLongf sz;
10316 
10317   assert( argc==2 );
10318   sz = sqlite3_value_int(argv[1]);
10319 
10320   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
10321     sqlite3_result_value(context, argv[0]);
10322   }else{
10323     const Bytef *pData= sqlite3_value_blob(argv[0]);
10324     Bytef *pOut = sqlite3_malloc(sz);
10325     if( pOut==0 ){
10326       sqlite3_result_error_nomem(context);
10327     }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
10328       sqlite3_result_error(context, "error in uncompress()", -1);
10329     }else{
10330       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
10331     }
10332     sqlite3_free(pOut);
10333   }
10334 }
10335 
10336 #ifdef _WIN32
10337 
10338 #endif
10339 int sqlite3_sqlar_init(
10340   sqlite3 *db,
10341   char **pzErrMsg,
10342   const sqlite3_api_routines *pApi
10343 ){
10344   int rc = SQLITE_OK;
10345   SQLITE_EXTENSION_INIT2(pApi);
10346   (void)pzErrMsg;  /* Unused parameter */
10347   rc = sqlite3_create_function(db, "sqlar_compress", 1,
10348                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10349                                sqlarCompressFunc, 0, 0);
10350   if( rc==SQLITE_OK ){
10351     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
10352                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10353                                  sqlarUncompressFunc, 0, 0);
10354   }
10355   return rc;
10356 }
10357 
10358 /************************* End ../ext/misc/sqlar.c ********************/
10359 #endif
10360 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
10361 /*
10362 ** 2017 April 07
10363 **
10364 ** The author disclaims copyright to this source code.  In place of
10365 ** a legal notice, here is a blessing:
10366 **
10367 **    May you do good and not evil.
10368 **    May you find forgiveness for yourself and forgive others.
10369 **    May you share freely, never taking more than you give.
10370 **
10371 *************************************************************************
10372 */
10373 #if !defined(SQLITEEXPERT_H)
10374 #define SQLITEEXPERT_H 1
10375 /* #include "sqlite3.h" */
10376 
10377 typedef struct sqlite3expert sqlite3expert;
10378 
10379 /*
10380 ** Create a new sqlite3expert object.
10381 **
10382 ** If successful, a pointer to the new object is returned and (*pzErr) set
10383 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
10384 ** an English-language error message. In this case it is the responsibility
10385 ** of the caller to eventually free the error message buffer using
10386 ** sqlite3_free().
10387 */
10388 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
10389 
10390 /*
10391 ** Configure an sqlite3expert object.
10392 **
10393 ** EXPERT_CONFIG_SAMPLE:
10394 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
10395 **   each candidate index. This involves scanning and sorting the entire
10396 **   contents of each user database table once for each candidate index
10397 **   associated with the table. For large databases, this can be
10398 **   prohibitively slow. This option allows the sqlite3expert object to
10399 **   be configured so that sqlite_stat1 data is instead generated based on a
10400 **   subset of each table, or so that no sqlite_stat1 data is used at all.
10401 **
10402 **   A single integer argument is passed to this option. If the value is less
10403 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
10404 **   the analysis - indexes are recommended based on the database schema only.
10405 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
10406 **   generated for each candidate index (this is the default). Finally, if the
10407 **   value falls between 0 and 100, then it represents the percentage of user
10408 **   table rows that should be considered when generating sqlite_stat1 data.
10409 **
10410 **   Examples:
10411 **
10412 **     // Do not generate any sqlite_stat1 data
10413 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
10414 **
10415 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
10416 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
10417 */
10418 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
10419 
10420 #define EXPERT_CONFIG_SAMPLE 1    /* int */
10421 
10422 /*
10423 ** Specify zero or more SQL statements to be included in the analysis.
10424 **
10425 ** Buffer zSql must contain zero or more complete SQL statements. This
10426 ** function parses all statements contained in the buffer and adds them
10427 ** to the internal list of statements to analyze. If successful, SQLITE_OK
10428 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
10429 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
10430 ** may be set to point to an English language error message. In this case
10431 ** the caller is responsible for eventually freeing the error message buffer
10432 ** using sqlite3_free().
10433 **
10434 ** If an error does occur while processing one of the statements in the
10435 ** buffer passed as the second argument, none of the statements in the
10436 ** buffer are added to the analysis.
10437 **
10438 ** This function must be called before sqlite3_expert_analyze(). If a call
10439 ** to this function is made on an sqlite3expert object that has already
10440 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
10441 ** immediately and no statements are added to the analysis.
10442 */
10443 int sqlite3_expert_sql(
10444   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
10445   const char *zSql,               /* SQL statement(s) to add */
10446   char **pzErr                    /* OUT: Error message (if any) */
10447 );
10448 
10449 
10450 /*
10451 ** This function is called after the sqlite3expert object has been configured
10452 ** with all SQL statements using sqlite3_expert_sql() to actually perform
10453 ** the analysis. Once this function has been called, it is not possible to
10454 ** add further SQL statements to the analysis.
10455 **
10456 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
10457 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
10458 ** point to a buffer containing an English language error message. In this
10459 ** case it is the responsibility of the caller to eventually free the buffer
10460 ** using sqlite3_free().
10461 **
10462 ** If an error does occur within this function, the sqlite3expert object
10463 ** is no longer useful for any purpose. At that point it is no longer
10464 ** possible to add further SQL statements to the object or to re-attempt
10465 ** the analysis. The sqlite3expert object must still be freed using a call
10466 ** sqlite3_expert_destroy().
10467 */
10468 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
10469 
10470 /*
10471 ** Return the total number of statements loaded using sqlite3_expert_sql().
10472 ** The total number of SQL statements may be different from the total number
10473 ** to calls to sqlite3_expert_sql().
10474 */
10475 int sqlite3_expert_count(sqlite3expert*);
10476 
10477 /*
10478 ** Return a component of the report.
10479 **
10480 ** This function is called after sqlite3_expert_analyze() to extract the
10481 ** results of the analysis. Each call to this function returns either a
10482 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
10483 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
10484 ** #define constants defined below.
10485 **
10486 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
10487 ** information relating to a specific SQL statement. In these cases that
10488 ** SQL statement is identified by the value passed as the second argument.
10489 ** SQL statements are numbered from 0 in the order in which they are parsed.
10490 ** If an out-of-range value (less than zero or equal to or greater than the
10491 ** value returned by sqlite3_expert_count()) is passed as the second argument
10492 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
10493 **
10494 ** EXPERT_REPORT_SQL:
10495 **   Return the text of SQL statement iStmt.
10496 **
10497 ** EXPERT_REPORT_INDEXES:
10498 **   Return a buffer containing the CREATE INDEX statements for all recommended
10499 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
10500 **   is returned.
10501 **
10502 ** EXPERT_REPORT_PLAN:
10503 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
10504 **   iStmt after the proposed indexes have been added to the database schema.
10505 **
10506 ** EXPERT_REPORT_CANDIDATES:
10507 **   Return a pointer to a buffer containing the CREATE INDEX statements
10508 **   for all indexes that were tested (for all SQL statements). The iStmt
10509 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
10510 */
10511 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
10512 
10513 /*
10514 ** Values for the third argument passed to sqlite3_expert_report().
10515 */
10516 #define EXPERT_REPORT_SQL        1
10517 #define EXPERT_REPORT_INDEXES    2
10518 #define EXPERT_REPORT_PLAN       3
10519 #define EXPERT_REPORT_CANDIDATES 4
10520 
10521 /*
10522 ** Free an (sqlite3expert*) handle and all associated resources. There
10523 ** should be one call to this function for each successful call to
10524 ** sqlite3-expert_new().
10525 */
10526 void sqlite3_expert_destroy(sqlite3expert*);
10527 
10528 #endif  /* !defined(SQLITEEXPERT_H) */
10529 
10530 /************************* End ../ext/expert/sqlite3expert.h ********************/
10531 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
10532 /*
10533 ** 2017 April 09
10534 **
10535 ** The author disclaims copyright to this source code.  In place of
10536 ** a legal notice, here is a blessing:
10537 **
10538 **    May you do good and not evil.
10539 **    May you find forgiveness for yourself and forgive others.
10540 **    May you share freely, never taking more than you give.
10541 **
10542 *************************************************************************
10543 */
10544 /* #include "sqlite3expert.h" */
10545 #include <assert.h>
10546 #include <string.h>
10547 #include <stdio.h>
10548 
10549 #if !defined(SQLITE_AMALGAMATION)
10550 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
10551 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
10552 #endif
10553 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
10554 # define ALWAYS(X)      (1)
10555 # define NEVER(X)       (0)
10556 #elif !defined(NDEBUG)
10557 # define ALWAYS(X)      ((X)?1:(assert(0),0))
10558 # define NEVER(X)       ((X)?(assert(0),1):0)
10559 #else
10560 # define ALWAYS(X)      (X)
10561 # define NEVER(X)       (X)
10562 #endif
10563 #endif /* !defined(SQLITE_AMALGAMATION) */
10564 
10565 
10566 #ifndef SQLITE_OMIT_VIRTUALTABLE
10567 
10568 /* typedef sqlite3_int64 i64; */
10569 /* typedef sqlite3_uint64 u64; */
10570 
10571 typedef struct IdxColumn IdxColumn;
10572 typedef struct IdxConstraint IdxConstraint;
10573 typedef struct IdxScan IdxScan;
10574 typedef struct IdxStatement IdxStatement;
10575 typedef struct IdxTable IdxTable;
10576 typedef struct IdxWrite IdxWrite;
10577 
10578 #define STRLEN  (int)strlen
10579 
10580 /*
10581 ** A temp table name that we assume no user database will actually use.
10582 ** If this assumption proves incorrect triggers on the table with the
10583 ** conflicting name will be ignored.
10584 */
10585 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
10586 
10587 /*
10588 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
10589 ** any other type of single-ended range constraint on a column).
10590 **
10591 ** pLink:
10592 **   Used to temporarily link IdxConstraint objects into lists while
10593 **   creating candidate indexes.
10594 */
10595 struct IdxConstraint {
10596   char *zColl;                    /* Collation sequence */
10597   int bRange;                     /* True for range, false for eq */
10598   int iCol;                       /* Constrained table column */
10599   int bFlag;                      /* Used by idxFindCompatible() */
10600   int bDesc;                      /* True if ORDER BY <expr> DESC */
10601   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
10602   IdxConstraint *pLink;           /* See above */
10603 };
10604 
10605 /*
10606 ** A single scan of a single table.
10607 */
10608 struct IdxScan {
10609   IdxTable *pTab;                 /* Associated table object */
10610   int iDb;                        /* Database containing table zTable */
10611   i64 covering;                   /* Mask of columns required for cov. index */
10612   IdxConstraint *pOrder;          /* ORDER BY columns */
10613   IdxConstraint *pEq;             /* List of == constraints */
10614   IdxConstraint *pRange;          /* List of < constraints */
10615   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
10616 };
10617 
10618 /*
10619 ** Information regarding a single database table. Extracted from
10620 ** "PRAGMA table_info" by function idxGetTableInfo().
10621 */
10622 struct IdxColumn {
10623   char *zName;
10624   char *zColl;
10625   int iPk;
10626 };
10627 struct IdxTable {
10628   int nCol;
10629   char *zName;                    /* Table name */
10630   IdxColumn *aCol;
10631   IdxTable *pNext;                /* Next table in linked list of all tables */
10632 };
10633 
10634 /*
10635 ** An object of the following type is created for each unique table/write-op
10636 ** seen. The objects are stored in a singly-linked list beginning at
10637 ** sqlite3expert.pWrite.
10638 */
10639 struct IdxWrite {
10640   IdxTable *pTab;
10641   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
10642   IdxWrite *pNext;
10643 };
10644 
10645 /*
10646 ** Each statement being analyzed is represented by an instance of this
10647 ** structure.
10648 */
10649 struct IdxStatement {
10650   int iId;                        /* Statement number */
10651   char *zSql;                     /* SQL statement */
10652   char *zIdx;                     /* Indexes */
10653   char *zEQP;                     /* Plan */
10654   IdxStatement *pNext;
10655 };
10656 
10657 
10658 /*
10659 ** A hash table for storing strings. With space for a payload string
10660 ** with each entry. Methods are:
10661 **
10662 **   idxHashInit()
10663 **   idxHashClear()
10664 **   idxHashAdd()
10665 **   idxHashSearch()
10666 */
10667 #define IDX_HASH_SIZE 1023
10668 typedef struct IdxHashEntry IdxHashEntry;
10669 typedef struct IdxHash IdxHash;
10670 struct IdxHashEntry {
10671   char *zKey;                     /* nul-terminated key */
10672   char *zVal;                     /* nul-terminated value string */
10673   char *zVal2;                    /* nul-terminated value string 2 */
10674   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
10675   IdxHashEntry *pNext;            /* Next entry in hash */
10676 };
10677 struct IdxHash {
10678   IdxHashEntry *pFirst;
10679   IdxHashEntry *aHash[IDX_HASH_SIZE];
10680 };
10681 
10682 /*
10683 ** sqlite3expert object.
10684 */
10685 struct sqlite3expert {
10686   int iSample;                    /* Percentage of tables to sample for stat1 */
10687   sqlite3 *db;                    /* User database */
10688   sqlite3 *dbm;                   /* In-memory db for this analysis */
10689   sqlite3 *dbv;                   /* Vtab schema for this analysis */
10690   IdxTable *pTable;               /* List of all IdxTable objects */
10691   IdxScan *pScan;                 /* List of scan objects */
10692   IdxWrite *pWrite;               /* List of write objects */
10693   IdxStatement *pStatement;       /* List of IdxStatement objects */
10694   int bRun;                       /* True once analysis has run */
10695   char **pzErrmsg;
10696   int rc;                         /* Error code from whereinfo hook */
10697   IdxHash hIdx;                   /* Hash containing all candidate indexes */
10698   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
10699 };
10700 
10701 
10702 /*
10703 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
10704 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
10705 */
10706 static void *idxMalloc(int *pRc, int nByte){
10707   void *pRet;
10708   assert( *pRc==SQLITE_OK );
10709   assert( nByte>0 );
10710   pRet = sqlite3_malloc(nByte);
10711   if( pRet ){
10712     memset(pRet, 0, nByte);
10713   }else{
10714     *pRc = SQLITE_NOMEM;
10715   }
10716   return pRet;
10717 }
10718 
10719 /*
10720 ** Initialize an IdxHash hash table.
10721 */
10722 static void idxHashInit(IdxHash *pHash){
10723   memset(pHash, 0, sizeof(IdxHash));
10724 }
10725 
10726 /*
10727 ** Reset an IdxHash hash table.
10728 */
10729 static void idxHashClear(IdxHash *pHash){
10730   int i;
10731   for(i=0; i<IDX_HASH_SIZE; i++){
10732     IdxHashEntry *pEntry;
10733     IdxHashEntry *pNext;
10734     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
10735       pNext = pEntry->pHashNext;
10736       sqlite3_free(pEntry->zVal2);
10737       sqlite3_free(pEntry);
10738     }
10739   }
10740   memset(pHash, 0, sizeof(IdxHash));
10741 }
10742 
10743 /*
10744 ** Return the index of the hash bucket that the string specified by the
10745 ** arguments to this function belongs.
10746 */
10747 static int idxHashString(const char *z, int n){
10748   unsigned int ret = 0;
10749   int i;
10750   for(i=0; i<n; i++){
10751     ret += (ret<<3) + (unsigned char)(z[i]);
10752   }
10753   return (int)(ret % IDX_HASH_SIZE);
10754 }
10755 
10756 /*
10757 ** If zKey is already present in the hash table, return non-zero and do
10758 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
10759 ** the hash table passed as the second argument.
10760 */
10761 static int idxHashAdd(
10762   int *pRc,
10763   IdxHash *pHash,
10764   const char *zKey,
10765   const char *zVal
10766 ){
10767   int nKey = STRLEN(zKey);
10768   int iHash = idxHashString(zKey, nKey);
10769   int nVal = (zVal ? STRLEN(zVal) : 0);
10770   IdxHashEntry *pEntry;
10771   assert( iHash>=0 );
10772   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
10773     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
10774       return 1;
10775     }
10776   }
10777   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
10778   if( pEntry ){
10779     pEntry->zKey = (char*)&pEntry[1];
10780     memcpy(pEntry->zKey, zKey, nKey);
10781     if( zVal ){
10782       pEntry->zVal = &pEntry->zKey[nKey+1];
10783       memcpy(pEntry->zVal, zVal, nVal);
10784     }
10785     pEntry->pHashNext = pHash->aHash[iHash];
10786     pHash->aHash[iHash] = pEntry;
10787 
10788     pEntry->pNext = pHash->pFirst;
10789     pHash->pFirst = pEntry;
10790   }
10791   return 0;
10792 }
10793 
10794 /*
10795 ** If zKey/nKey is present in the hash table, return a pointer to the
10796 ** hash-entry object.
10797 */
10798 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
10799   int iHash;
10800   IdxHashEntry *pEntry;
10801   if( nKey<0 ) nKey = STRLEN(zKey);
10802   iHash = idxHashString(zKey, nKey);
10803   assert( iHash>=0 );
10804   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
10805     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
10806       return pEntry;
10807     }
10808   }
10809   return 0;
10810 }
10811 
10812 /*
10813 ** If the hash table contains an entry with a key equal to the string
10814 ** passed as the final two arguments to this function, return a pointer
10815 ** to the payload string. Otherwise, if zKey/nKey is not present in the
10816 ** hash table, return NULL.
10817 */
10818 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
10819   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
10820   if( pEntry ) return pEntry->zVal;
10821   return 0;
10822 }
10823 
10824 /*
10825 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
10826 ** variable to point to a copy of nul-terminated string zColl.
10827 */
10828 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
10829   IdxConstraint *pNew;
10830   int nColl = STRLEN(zColl);
10831 
10832   assert( *pRc==SQLITE_OK );
10833   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
10834   if( pNew ){
10835     pNew->zColl = (char*)&pNew[1];
10836     memcpy(pNew->zColl, zColl, nColl+1);
10837   }
10838   return pNew;
10839 }
10840 
10841 /*
10842 ** An error associated with database handle db has just occurred. Pass
10843 ** the error message to callback function xOut.
10844 */
10845 static void idxDatabaseError(
10846   sqlite3 *db,                    /* Database handle */
10847   char **pzErrmsg                 /* Write error here */
10848 ){
10849   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
10850 }
10851 
10852 /*
10853 ** Prepare an SQL statement.
10854 */
10855 static int idxPrepareStmt(
10856   sqlite3 *db,                    /* Database handle to compile against */
10857   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
10858   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
10859   const char *zSql                /* SQL statement to compile */
10860 ){
10861   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
10862   if( rc!=SQLITE_OK ){
10863     *ppStmt = 0;
10864     idxDatabaseError(db, pzErrmsg);
10865   }
10866   return rc;
10867 }
10868 
10869 /*
10870 ** Prepare an SQL statement using the results of a printf() formatting.
10871 */
10872 static int idxPrintfPrepareStmt(
10873   sqlite3 *db,                    /* Database handle to compile against */
10874   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
10875   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
10876   const char *zFmt,               /* printf() format of SQL statement */
10877   ...                             /* Trailing printf() arguments */
10878 ){
10879   va_list ap;
10880   int rc;
10881   char *zSql;
10882   va_start(ap, zFmt);
10883   zSql = sqlite3_vmprintf(zFmt, ap);
10884   if( zSql==0 ){
10885     rc = SQLITE_NOMEM;
10886   }else{
10887     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
10888     sqlite3_free(zSql);
10889   }
10890   va_end(ap);
10891   return rc;
10892 }
10893 
10894 
10895 /*************************************************************************
10896 ** Beginning of virtual table implementation.
10897 */
10898 typedef struct ExpertVtab ExpertVtab;
10899 struct ExpertVtab {
10900   sqlite3_vtab base;
10901   IdxTable *pTab;
10902   sqlite3expert *pExpert;
10903 };
10904 
10905 typedef struct ExpertCsr ExpertCsr;
10906 struct ExpertCsr {
10907   sqlite3_vtab_cursor base;
10908   sqlite3_stmt *pData;
10909 };
10910 
10911 static char *expertDequote(const char *zIn){
10912   int n = STRLEN(zIn);
10913   char *zRet = sqlite3_malloc(n);
10914 
10915   assert( zIn[0]=='\'' );
10916   assert( zIn[n-1]=='\'' );
10917 
10918   if( zRet ){
10919     int iOut = 0;
10920     int iIn = 0;
10921     for(iIn=1; iIn<(n-1); iIn++){
10922       if( zIn[iIn]=='\'' ){
10923         assert( zIn[iIn+1]=='\'' );
10924         iIn++;
10925       }
10926       zRet[iOut++] = zIn[iIn];
10927     }
10928     zRet[iOut] = '\0';
10929   }
10930 
10931   return zRet;
10932 }
10933 
10934 /*
10935 ** This function is the implementation of both the xConnect and xCreate
10936 ** methods of the r-tree virtual table.
10937 **
10938 **   argv[0]   -> module name
10939 **   argv[1]   -> database name
10940 **   argv[2]   -> table name
10941 **   argv[...] -> column names...
10942 */
10943 static int expertConnect(
10944   sqlite3 *db,
10945   void *pAux,
10946   int argc, const char *const*argv,
10947   sqlite3_vtab **ppVtab,
10948   char **pzErr
10949 ){
10950   sqlite3expert *pExpert = (sqlite3expert*)pAux;
10951   ExpertVtab *p = 0;
10952   int rc;
10953 
10954   if( argc!=4 ){
10955     *pzErr = sqlite3_mprintf("internal error!");
10956     rc = SQLITE_ERROR;
10957   }else{
10958     char *zCreateTable = expertDequote(argv[3]);
10959     if( zCreateTable ){
10960       rc = sqlite3_declare_vtab(db, zCreateTable);
10961       if( rc==SQLITE_OK ){
10962         p = idxMalloc(&rc, sizeof(ExpertVtab));
10963       }
10964       if( rc==SQLITE_OK ){
10965         p->pExpert = pExpert;
10966         p->pTab = pExpert->pTable;
10967         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
10968       }
10969       sqlite3_free(zCreateTable);
10970     }else{
10971       rc = SQLITE_NOMEM;
10972     }
10973   }
10974 
10975   *ppVtab = (sqlite3_vtab*)p;
10976   return rc;
10977 }
10978 
10979 static int expertDisconnect(sqlite3_vtab *pVtab){
10980   ExpertVtab *p = (ExpertVtab*)pVtab;
10981   sqlite3_free(p);
10982   return SQLITE_OK;
10983 }
10984 
10985 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
10986   ExpertVtab *p = (ExpertVtab*)pVtab;
10987   int rc = SQLITE_OK;
10988   int n = 0;
10989   IdxScan *pScan;
10990   const int opmask =
10991     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
10992     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
10993     SQLITE_INDEX_CONSTRAINT_LE;
10994 
10995   pScan = idxMalloc(&rc, sizeof(IdxScan));
10996   if( pScan ){
10997     int i;
10998 
10999     /* Link the new scan object into the list */
11000     pScan->pTab = p->pTab;
11001     pScan->pNextScan = p->pExpert->pScan;
11002     p->pExpert->pScan = pScan;
11003 
11004     /* Add the constraints to the IdxScan object */
11005     for(i=0; i<pIdxInfo->nConstraint; i++){
11006       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
11007       if( pCons->usable
11008        && pCons->iColumn>=0
11009        && p->pTab->aCol[pCons->iColumn].iPk==0
11010        && (pCons->op & opmask)
11011       ){
11012         IdxConstraint *pNew;
11013         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
11014         pNew = idxNewConstraint(&rc, zColl);
11015         if( pNew ){
11016           pNew->iCol = pCons->iColumn;
11017           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
11018             pNew->pNext = pScan->pEq;
11019             pScan->pEq = pNew;
11020           }else{
11021             pNew->bRange = 1;
11022             pNew->pNext = pScan->pRange;
11023             pScan->pRange = pNew;
11024           }
11025         }
11026         n++;
11027         pIdxInfo->aConstraintUsage[i].argvIndex = n;
11028       }
11029     }
11030 
11031     /* Add the ORDER BY to the IdxScan object */
11032     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
11033       int iCol = pIdxInfo->aOrderBy[i].iColumn;
11034       if( iCol>=0 ){
11035         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
11036         if( pNew ){
11037           pNew->iCol = iCol;
11038           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
11039           pNew->pNext = pScan->pOrder;
11040           pNew->pLink = pScan->pOrder;
11041           pScan->pOrder = pNew;
11042           n++;
11043         }
11044       }
11045     }
11046   }
11047 
11048   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
11049   return rc;
11050 }
11051 
11052 static int expertUpdate(
11053   sqlite3_vtab *pVtab,
11054   int nData,
11055   sqlite3_value **azData,
11056   sqlite_int64 *pRowid
11057 ){
11058   (void)pVtab;
11059   (void)nData;
11060   (void)azData;
11061   (void)pRowid;
11062   return SQLITE_OK;
11063 }
11064 
11065 /*
11066 ** Virtual table module xOpen method.
11067 */
11068 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
11069   int rc = SQLITE_OK;
11070   ExpertCsr *pCsr;
11071   (void)pVTab;
11072   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
11073   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
11074   return rc;
11075 }
11076 
11077 /*
11078 ** Virtual table module xClose method.
11079 */
11080 static int expertClose(sqlite3_vtab_cursor *cur){
11081   ExpertCsr *pCsr = (ExpertCsr*)cur;
11082   sqlite3_finalize(pCsr->pData);
11083   sqlite3_free(pCsr);
11084   return SQLITE_OK;
11085 }
11086 
11087 /*
11088 ** Virtual table module xEof method.
11089 **
11090 ** Return non-zero if the cursor does not currently point to a valid
11091 ** record (i.e if the scan has finished), or zero otherwise.
11092 */
11093 static int expertEof(sqlite3_vtab_cursor *cur){
11094   ExpertCsr *pCsr = (ExpertCsr*)cur;
11095   return pCsr->pData==0;
11096 }
11097 
11098 /*
11099 ** Virtual table module xNext method.
11100 */
11101 static int expertNext(sqlite3_vtab_cursor *cur){
11102   ExpertCsr *pCsr = (ExpertCsr*)cur;
11103   int rc = SQLITE_OK;
11104 
11105   assert( pCsr->pData );
11106   rc = sqlite3_step(pCsr->pData);
11107   if( rc!=SQLITE_ROW ){
11108     rc = sqlite3_finalize(pCsr->pData);
11109     pCsr->pData = 0;
11110   }else{
11111     rc = SQLITE_OK;
11112   }
11113 
11114   return rc;
11115 }
11116 
11117 /*
11118 ** Virtual table module xRowid method.
11119 */
11120 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
11121   (void)cur;
11122   *pRowid = 0;
11123   return SQLITE_OK;
11124 }
11125 
11126 /*
11127 ** Virtual table module xColumn method.
11128 */
11129 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
11130   ExpertCsr *pCsr = (ExpertCsr*)cur;
11131   sqlite3_value *pVal;
11132   pVal = sqlite3_column_value(pCsr->pData, i);
11133   if( pVal ){
11134     sqlite3_result_value(ctx, pVal);
11135   }
11136   return SQLITE_OK;
11137 }
11138 
11139 /*
11140 ** Virtual table module xFilter method.
11141 */
11142 static int expertFilter(
11143   sqlite3_vtab_cursor *cur,
11144   int idxNum, const char *idxStr,
11145   int argc, sqlite3_value **argv
11146 ){
11147   ExpertCsr *pCsr = (ExpertCsr*)cur;
11148   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
11149   sqlite3expert *pExpert = pVtab->pExpert;
11150   int rc;
11151 
11152   (void)idxNum;
11153   (void)idxStr;
11154   (void)argc;
11155   (void)argv;
11156   rc = sqlite3_finalize(pCsr->pData);
11157   pCsr->pData = 0;
11158   if( rc==SQLITE_OK ){
11159     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
11160         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
11161     );
11162   }
11163 
11164   if( rc==SQLITE_OK ){
11165     rc = expertNext(cur);
11166   }
11167   return rc;
11168 }
11169 
11170 static int idxRegisterVtab(sqlite3expert *p){
11171   static sqlite3_module expertModule = {
11172     2,                            /* iVersion */
11173     expertConnect,                /* xCreate - create a table */
11174     expertConnect,                /* xConnect - connect to an existing table */
11175     expertBestIndex,              /* xBestIndex - Determine search strategy */
11176     expertDisconnect,             /* xDisconnect - Disconnect from a table */
11177     expertDisconnect,             /* xDestroy - Drop a table */
11178     expertOpen,                   /* xOpen - open a cursor */
11179     expertClose,                  /* xClose - close a cursor */
11180     expertFilter,                 /* xFilter - configure scan constraints */
11181     expertNext,                   /* xNext - advance a cursor */
11182     expertEof,                    /* xEof */
11183     expertColumn,                 /* xColumn - read data */
11184     expertRowid,                  /* xRowid - read data */
11185     expertUpdate,                 /* xUpdate - write data */
11186     0,                            /* xBegin - begin transaction */
11187     0,                            /* xSync - sync transaction */
11188     0,                            /* xCommit - commit transaction */
11189     0,                            /* xRollback - rollback transaction */
11190     0,                            /* xFindFunction - function overloading */
11191     0,                            /* xRename - rename the table */
11192     0,                            /* xSavepoint */
11193     0,                            /* xRelease */
11194     0,                            /* xRollbackTo */
11195     0,                            /* xShadowName */
11196   };
11197 
11198   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
11199 }
11200 /*
11201 ** End of virtual table implementation.
11202 *************************************************************************/
11203 /*
11204 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
11205 ** is called, set it to the return value of sqlite3_finalize() before
11206 ** returning. Otherwise, discard the sqlite3_finalize() return value.
11207 */
11208 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
11209   int rc = sqlite3_finalize(pStmt);
11210   if( *pRc==SQLITE_OK ) *pRc = rc;
11211 }
11212 
11213 /*
11214 ** Attempt to allocate an IdxTable structure corresponding to table zTab
11215 ** in the main database of connection db. If successful, set (*ppOut) to
11216 ** point to the new object and return SQLITE_OK. Otherwise, return an
11217 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
11218 ** set to point to an error string.
11219 **
11220 ** It is the responsibility of the caller to eventually free either the
11221 ** IdxTable object or error message using sqlite3_free().
11222 */
11223 static int idxGetTableInfo(
11224   sqlite3 *db,                    /* Database connection to read details from */
11225   const char *zTab,               /* Table name */
11226   IdxTable **ppOut,               /* OUT: New object (if successful) */
11227   char **pzErrmsg                 /* OUT: Error message (if not) */
11228 ){
11229   sqlite3_stmt *p1 = 0;
11230   int nCol = 0;
11231   int nTab;
11232   int nByte;
11233   IdxTable *pNew = 0;
11234   int rc, rc2;
11235   char *pCsr = 0;
11236   int nPk = 0;
11237 
11238   *ppOut = 0;
11239   if( zTab==0 ) return SQLITE_ERROR;
11240   nTab = STRLEN(zTab);
11241   nByte = sizeof(IdxTable) + nTab + 1;
11242   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
11243   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
11244     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
11245     const char *zColSeq = 0;
11246     if( zCol==0 ){
11247       rc = SQLITE_ERROR;
11248       break;
11249     }
11250     nByte += 1 + STRLEN(zCol);
11251     rc = sqlite3_table_column_metadata(
11252         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
11253     );
11254     if( zColSeq==0 ) zColSeq = "binary";
11255     nByte += 1 + STRLEN(zColSeq);
11256     nCol++;
11257     nPk += (sqlite3_column_int(p1, 5)>0);
11258   }
11259   rc2 = sqlite3_reset(p1);
11260   if( rc==SQLITE_OK ) rc = rc2;
11261 
11262   nByte += sizeof(IdxColumn) * nCol;
11263   if( rc==SQLITE_OK ){
11264     pNew = idxMalloc(&rc, nByte);
11265   }
11266   if( rc==SQLITE_OK ){
11267     pNew->aCol = (IdxColumn*)&pNew[1];
11268     pNew->nCol = nCol;
11269     pCsr = (char*)&pNew->aCol[nCol];
11270   }
11271 
11272   nCol = 0;
11273   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
11274     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
11275     const char *zColSeq = 0;
11276     int nCopy;
11277     if( zCol==0 ) continue;
11278     nCopy = STRLEN(zCol) + 1;
11279     pNew->aCol[nCol].zName = pCsr;
11280     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
11281     memcpy(pCsr, zCol, nCopy);
11282     pCsr += nCopy;
11283 
11284     rc = sqlite3_table_column_metadata(
11285         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
11286     );
11287     if( rc==SQLITE_OK ){
11288       if( zColSeq==0 ) zColSeq = "binary";
11289       nCopy = STRLEN(zColSeq) + 1;
11290       pNew->aCol[nCol].zColl = pCsr;
11291       memcpy(pCsr, zColSeq, nCopy);
11292       pCsr += nCopy;
11293     }
11294 
11295     nCol++;
11296   }
11297   idxFinalize(&rc, p1);
11298 
11299   if( rc!=SQLITE_OK ){
11300     sqlite3_free(pNew);
11301     pNew = 0;
11302   }else if( ALWAYS(pNew!=0) ){
11303     pNew->zName = pCsr;
11304     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
11305   }
11306 
11307   *ppOut = pNew;
11308   return rc;
11309 }
11310 
11311 /*
11312 ** This function is a no-op if *pRc is set to anything other than
11313 ** SQLITE_OK when it is called.
11314 **
11315 ** If *pRc is initially set to SQLITE_OK, then the text specified by
11316 ** the printf() style arguments is appended to zIn and the result returned
11317 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
11318 ** zIn before returning.
11319 */
11320 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
11321   va_list ap;
11322   char *zAppend = 0;
11323   char *zRet = 0;
11324   int nIn = zIn ? STRLEN(zIn) : 0;
11325   int nAppend = 0;
11326   va_start(ap, zFmt);
11327   if( *pRc==SQLITE_OK ){
11328     zAppend = sqlite3_vmprintf(zFmt, ap);
11329     if( zAppend ){
11330       nAppend = STRLEN(zAppend);
11331       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
11332     }
11333     if( zAppend && zRet ){
11334       if( nIn ) memcpy(zRet, zIn, nIn);
11335       memcpy(&zRet[nIn], zAppend, nAppend+1);
11336     }else{
11337       sqlite3_free(zRet);
11338       zRet = 0;
11339       *pRc = SQLITE_NOMEM;
11340     }
11341     sqlite3_free(zAppend);
11342     sqlite3_free(zIn);
11343   }
11344   va_end(ap);
11345   return zRet;
11346 }
11347 
11348 /*
11349 ** Return true if zId must be quoted in order to use it as an SQL
11350 ** identifier, or false otherwise.
11351 */
11352 static int idxIdentifierRequiresQuotes(const char *zId){
11353   int i;
11354   int nId = STRLEN(zId);
11355 
11356   if( sqlite3_keyword_check(zId, nId) ) return 1;
11357 
11358   for(i=0; zId[i]; i++){
11359     if( !(zId[i]=='_')
11360      && !(zId[i]>='0' && zId[i]<='9')
11361      && !(zId[i]>='a' && zId[i]<='z')
11362      && !(zId[i]>='A' && zId[i]<='Z')
11363     ){
11364       return 1;
11365     }
11366   }
11367   return 0;
11368 }
11369 
11370 /*
11371 ** This function appends an index column definition suitable for constraint
11372 ** pCons to the string passed as zIn and returns the result.
11373 */
11374 static char *idxAppendColDefn(
11375   int *pRc,                       /* IN/OUT: Error code */
11376   char *zIn,                      /* Column defn accumulated so far */
11377   IdxTable *pTab,                 /* Table index will be created on */
11378   IdxConstraint *pCons
11379 ){
11380   char *zRet = zIn;
11381   IdxColumn *p = &pTab->aCol[pCons->iCol];
11382   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
11383 
11384   if( idxIdentifierRequiresQuotes(p->zName) ){
11385     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
11386   }else{
11387     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
11388   }
11389 
11390   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
11391     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
11392       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
11393     }else{
11394       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
11395     }
11396   }
11397 
11398   if( pCons->bDesc ){
11399     zRet = idxAppendText(pRc, zRet, " DESC");
11400   }
11401   return zRet;
11402 }
11403 
11404 /*
11405 ** Search database dbm for an index compatible with the one idxCreateFromCons()
11406 ** would create from arguments pScan, pEq and pTail. If no error occurs and
11407 ** such an index is found, return non-zero. Or, if no such index is found,
11408 ** return zero.
11409 **
11410 ** If an error occurs, set *pRc to an SQLite error code and return zero.
11411 */
11412 static int idxFindCompatible(
11413   int *pRc,                       /* OUT: Error code */
11414   sqlite3* dbm,                   /* Database to search */
11415   IdxScan *pScan,                 /* Scan for table to search for index on */
11416   IdxConstraint *pEq,             /* List of == constraints */
11417   IdxConstraint *pTail            /* List of range constraints */
11418 ){
11419   const char *zTbl = pScan->pTab->zName;
11420   sqlite3_stmt *pIdxList = 0;
11421   IdxConstraint *pIter;
11422   int nEq = 0;                    /* Number of elements in pEq */
11423   int rc;
11424 
11425   /* Count the elements in list pEq */
11426   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
11427 
11428   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
11429   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
11430     int bMatch = 1;
11431     IdxConstraint *pT = pTail;
11432     sqlite3_stmt *pInfo = 0;
11433     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
11434     if( zIdx==0 ) continue;
11435 
11436     /* Zero the IdxConstraint.bFlag values in the pEq list */
11437     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
11438 
11439     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
11440     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
11441       int iIdx = sqlite3_column_int(pInfo, 0);
11442       int iCol = sqlite3_column_int(pInfo, 1);
11443       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
11444 
11445       if( iIdx<nEq ){
11446         for(pIter=pEq; pIter; pIter=pIter->pLink){
11447           if( pIter->bFlag ) continue;
11448           if( pIter->iCol!=iCol ) continue;
11449           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
11450           pIter->bFlag = 1;
11451           break;
11452         }
11453         if( pIter==0 ){
11454           bMatch = 0;
11455           break;
11456         }
11457       }else{
11458         if( pT ){
11459           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
11460             bMatch = 0;
11461             break;
11462           }
11463           pT = pT->pLink;
11464         }
11465       }
11466     }
11467     idxFinalize(&rc, pInfo);
11468 
11469     if( rc==SQLITE_OK && bMatch ){
11470       sqlite3_finalize(pIdxList);
11471       return 1;
11472     }
11473   }
11474   idxFinalize(&rc, pIdxList);
11475 
11476   *pRc = rc;
11477   return 0;
11478 }
11479 
11480 /* Callback for sqlite3_exec() with query with leading count(*) column.
11481  * The first argument is expected to be an int*, referent to be incremented
11482  * if that leading column is not exactly '0'.
11483  */
11484 static int countNonzeros(void* pCount, int nc,
11485                          char* azResults[], char* azColumns[]){
11486   (void)azColumns;  /* Suppress unused parameter warning */
11487   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
11488     *((int *)pCount) += 1;
11489   }
11490   return 0;
11491 }
11492 
11493 static int idxCreateFromCons(
11494   sqlite3expert *p,
11495   IdxScan *pScan,
11496   IdxConstraint *pEq,
11497   IdxConstraint *pTail
11498 ){
11499   sqlite3 *dbm = p->dbm;
11500   int rc = SQLITE_OK;
11501   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
11502     IdxTable *pTab = pScan->pTab;
11503     char *zCols = 0;
11504     char *zIdx = 0;
11505     IdxConstraint *pCons;
11506     unsigned int h = 0;
11507     const char *zFmt;
11508 
11509     for(pCons=pEq; pCons; pCons=pCons->pLink){
11510       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
11511     }
11512     for(pCons=pTail; pCons; pCons=pCons->pLink){
11513       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
11514     }
11515 
11516     if( rc==SQLITE_OK ){
11517       /* Hash the list of columns to come up with a name for the index */
11518       const char *zTable = pScan->pTab->zName;
11519       int quoteTable = idxIdentifierRequiresQuotes(zTable);
11520       char *zName = 0;          /* Index name */
11521       int collisions = 0;
11522       do{
11523         int i;
11524         char *zFind;
11525         for(i=0; zCols[i]; i++){
11526           h += ((h<<3) + zCols[i]);
11527         }
11528         sqlite3_free(zName);
11529         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
11530         if( zName==0 ) break;
11531         /* Is is unique among table, view and index names? */
11532         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
11533           " AND type in ('index','table','view')";
11534         zFind = sqlite3_mprintf(zFmt, zName);
11535         i = 0;
11536         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
11537         assert(rc==SQLITE_OK);
11538         sqlite3_free(zFind);
11539         if( i==0 ){
11540           collisions = 0;
11541           break;
11542         }
11543         ++collisions;
11544       }while( collisions<50 && zName!=0 );
11545       if( collisions ){
11546         /* This return means "Gave up trying to find a unique index name." */
11547         rc = SQLITE_BUSY_TIMEOUT;
11548       }else if( zName==0 ){
11549         rc = SQLITE_NOMEM;
11550       }else{
11551         if( quoteTable ){
11552           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
11553         }else{
11554           zFmt = "CREATE INDEX %s ON %s(%s)";
11555         }
11556         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
11557         if( !zIdx ){
11558           rc = SQLITE_NOMEM;
11559         }else{
11560           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
11561           if( rc!=SQLITE_OK ){
11562             rc = SQLITE_BUSY_TIMEOUT;
11563           }else{
11564             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
11565           }
11566         }
11567         sqlite3_free(zName);
11568         sqlite3_free(zIdx);
11569       }
11570     }
11571 
11572     sqlite3_free(zCols);
11573   }
11574   return rc;
11575 }
11576 
11577 /*
11578 ** Return true if list pList (linked by IdxConstraint.pLink) contains
11579 ** a constraint compatible with *p. Otherwise return false.
11580 */
11581 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
11582   IdxConstraint *pCmp;
11583   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
11584     if( p->iCol==pCmp->iCol ) return 1;
11585   }
11586   return 0;
11587 }
11588 
11589 static int idxCreateFromWhere(
11590   sqlite3expert *p,
11591   IdxScan *pScan,                 /* Create indexes for this scan */
11592   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
11593 ){
11594   IdxConstraint *p1 = 0;
11595   IdxConstraint *pCon;
11596   int rc;
11597 
11598   /* Gather up all the == constraints. */
11599   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
11600     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
11601       pCon->pLink = p1;
11602       p1 = pCon;
11603     }
11604   }
11605 
11606   /* Create an index using the == constraints collected above. And the
11607   ** range constraint/ORDER BY terms passed in by the caller, if any. */
11608   rc = idxCreateFromCons(p, pScan, p1, pTail);
11609 
11610   /* If no range/ORDER BY passed by the caller, create a version of the
11611   ** index for each range constraint.  */
11612   if( pTail==0 ){
11613     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
11614       assert( pCon->pLink==0 );
11615       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
11616         rc = idxCreateFromCons(p, pScan, p1, pCon);
11617       }
11618     }
11619   }
11620 
11621   return rc;
11622 }
11623 
11624 /*
11625 ** Create candidate indexes in database [dbm] based on the data in
11626 ** linked-list pScan.
11627 */
11628 static int idxCreateCandidates(sqlite3expert *p){
11629   int rc = SQLITE_OK;
11630   IdxScan *pIter;
11631 
11632   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
11633     rc = idxCreateFromWhere(p, pIter, 0);
11634     if( rc==SQLITE_OK && pIter->pOrder ){
11635       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
11636     }
11637   }
11638 
11639   return rc;
11640 }
11641 
11642 /*
11643 ** Free all elements of the linked list starting at pConstraint.
11644 */
11645 static void idxConstraintFree(IdxConstraint *pConstraint){
11646   IdxConstraint *pNext;
11647   IdxConstraint *p;
11648 
11649   for(p=pConstraint; p; p=pNext){
11650     pNext = p->pNext;
11651     sqlite3_free(p);
11652   }
11653 }
11654 
11655 /*
11656 ** Free all elements of the linked list starting from pScan up until pLast
11657 ** (pLast is not freed).
11658 */
11659 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
11660   IdxScan *p;
11661   IdxScan *pNext;
11662   for(p=pScan; p!=pLast; p=pNext){
11663     pNext = p->pNextScan;
11664     idxConstraintFree(p->pOrder);
11665     idxConstraintFree(p->pEq);
11666     idxConstraintFree(p->pRange);
11667     sqlite3_free(p);
11668   }
11669 }
11670 
11671 /*
11672 ** Free all elements of the linked list starting from pStatement up
11673 ** until pLast (pLast is not freed).
11674 */
11675 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
11676   IdxStatement *p;
11677   IdxStatement *pNext;
11678   for(p=pStatement; p!=pLast; p=pNext){
11679     pNext = p->pNext;
11680     sqlite3_free(p->zEQP);
11681     sqlite3_free(p->zIdx);
11682     sqlite3_free(p);
11683   }
11684 }
11685 
11686 /*
11687 ** Free the linked list of IdxTable objects starting at pTab.
11688 */
11689 static void idxTableFree(IdxTable *pTab){
11690   IdxTable *pIter;
11691   IdxTable *pNext;
11692   for(pIter=pTab; pIter; pIter=pNext){
11693     pNext = pIter->pNext;
11694     sqlite3_free(pIter);
11695   }
11696 }
11697 
11698 /*
11699 ** Free the linked list of IdxWrite objects starting at pTab.
11700 */
11701 static void idxWriteFree(IdxWrite *pTab){
11702   IdxWrite *pIter;
11703   IdxWrite *pNext;
11704   for(pIter=pTab; pIter; pIter=pNext){
11705     pNext = pIter->pNext;
11706     sqlite3_free(pIter);
11707   }
11708 }
11709 
11710 
11711 
11712 /*
11713 ** This function is called after candidate indexes have been created. It
11714 ** runs all the queries to see which indexes they prefer, and populates
11715 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
11716 */
11717 static int idxFindIndexes(
11718   sqlite3expert *p,
11719   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
11720 ){
11721   IdxStatement *pStmt;
11722   sqlite3 *dbm = p->dbm;
11723   int rc = SQLITE_OK;
11724 
11725   IdxHash hIdx;
11726   idxHashInit(&hIdx);
11727 
11728   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
11729     IdxHashEntry *pEntry;
11730     sqlite3_stmt *pExplain = 0;
11731     idxHashClear(&hIdx);
11732     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
11733         "EXPLAIN QUERY PLAN %s", pStmt->zSql
11734     );
11735     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
11736       /* int iId = sqlite3_column_int(pExplain, 0); */
11737       /* int iParent = sqlite3_column_int(pExplain, 1); */
11738       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
11739       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
11740       int nDetail;
11741       int i;
11742 
11743       if( !zDetail ) continue;
11744       nDetail = STRLEN(zDetail);
11745 
11746       for(i=0; i<nDetail; i++){
11747         const char *zIdx = 0;
11748         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
11749           zIdx = &zDetail[i+13];
11750         }else if( i+22<nDetail
11751             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
11752         ){
11753           zIdx = &zDetail[i+22];
11754         }
11755         if( zIdx ){
11756           const char *zSql;
11757           int nIdx = 0;
11758           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
11759             nIdx++;
11760           }
11761           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
11762           if( zSql ){
11763             idxHashAdd(&rc, &hIdx, zSql, 0);
11764             if( rc ) goto find_indexes_out;
11765           }
11766           break;
11767         }
11768       }
11769 
11770       if( zDetail[0]!='-' ){
11771         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
11772       }
11773     }
11774 
11775     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
11776       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
11777     }
11778 
11779     idxFinalize(&rc, pExplain);
11780   }
11781 
11782  find_indexes_out:
11783   idxHashClear(&hIdx);
11784   return rc;
11785 }
11786 
11787 static int idxAuthCallback(
11788   void *pCtx,
11789   int eOp,
11790   const char *z3,
11791   const char *z4,
11792   const char *zDb,
11793   const char *zTrigger
11794 ){
11795   int rc = SQLITE_OK;
11796   (void)z4;
11797   (void)zTrigger;
11798   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
11799     if( sqlite3_stricmp(zDb, "main")==0 ){
11800       sqlite3expert *p = (sqlite3expert*)pCtx;
11801       IdxTable *pTab;
11802       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
11803         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
11804       }
11805       if( pTab ){
11806         IdxWrite *pWrite;
11807         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
11808           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
11809         }
11810         if( pWrite==0 ){
11811           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
11812           if( rc==SQLITE_OK ){
11813             pWrite->pTab = pTab;
11814             pWrite->eOp = eOp;
11815             pWrite->pNext = p->pWrite;
11816             p->pWrite = pWrite;
11817           }
11818         }
11819       }
11820     }
11821   }
11822   return rc;
11823 }
11824 
11825 static int idxProcessOneTrigger(
11826   sqlite3expert *p,
11827   IdxWrite *pWrite,
11828   char **pzErr
11829 ){
11830   static const char *zInt = UNIQUE_TABLE_NAME;
11831   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
11832   IdxTable *pTab = pWrite->pTab;
11833   const char *zTab = pTab->zName;
11834   const char *zSql =
11835     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
11836     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
11837     "ORDER BY type;";
11838   sqlite3_stmt *pSelect = 0;
11839   int rc = SQLITE_OK;
11840   char *zWrite = 0;
11841 
11842   /* Create the table and its triggers in the temp schema */
11843   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
11844   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
11845     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
11846     if( zCreate==0 ) continue;
11847     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
11848   }
11849   idxFinalize(&rc, pSelect);
11850 
11851   /* Rename the table in the temp schema to zInt */
11852   if( rc==SQLITE_OK ){
11853     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
11854     if( z==0 ){
11855       rc = SQLITE_NOMEM;
11856     }else{
11857       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
11858       sqlite3_free(z);
11859     }
11860   }
11861 
11862   switch( pWrite->eOp ){
11863     case SQLITE_INSERT: {
11864       int i;
11865       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
11866       for(i=0; i<pTab->nCol; i++){
11867         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
11868       }
11869       zWrite = idxAppendText(&rc, zWrite, ")");
11870       break;
11871     }
11872     case SQLITE_UPDATE: {
11873       int i;
11874       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
11875       for(i=0; i<pTab->nCol; i++){
11876         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
11877             pTab->aCol[i].zName
11878         );
11879       }
11880       break;
11881     }
11882     default: {
11883       assert( pWrite->eOp==SQLITE_DELETE );
11884       if( rc==SQLITE_OK ){
11885         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
11886         if( zWrite==0 ) rc = SQLITE_NOMEM;
11887       }
11888     }
11889   }
11890 
11891   if( rc==SQLITE_OK ){
11892     sqlite3_stmt *pX = 0;
11893     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
11894     idxFinalize(&rc, pX);
11895     if( rc!=SQLITE_OK ){
11896       idxDatabaseError(p->dbv, pzErr);
11897     }
11898   }
11899   sqlite3_free(zWrite);
11900 
11901   if( rc==SQLITE_OK ){
11902     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
11903   }
11904 
11905   return rc;
11906 }
11907 
11908 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
11909   int rc = SQLITE_OK;
11910   IdxWrite *pEnd = 0;
11911   IdxWrite *pFirst = p->pWrite;
11912 
11913   while( rc==SQLITE_OK && pFirst!=pEnd ){
11914     IdxWrite *pIter;
11915     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
11916       rc = idxProcessOneTrigger(p, pIter, pzErr);
11917     }
11918     pEnd = pFirst;
11919     pFirst = p->pWrite;
11920   }
11921 
11922   return rc;
11923 }
11924 
11925 
11926 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
11927   int rc = idxRegisterVtab(p);
11928   sqlite3_stmt *pSchema = 0;
11929 
11930   /* For each table in the main db schema:
11931   **
11932   **   1) Add an entry to the p->pTable list, and
11933   **   2) Create the equivalent virtual table in dbv.
11934   */
11935   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
11936       "SELECT type, name, sql, 1 FROM sqlite_schema "
11937       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
11938       " UNION ALL "
11939       "SELECT type, name, sql, 2 FROM sqlite_schema "
11940       "WHERE type = 'trigger'"
11941       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
11942       "ORDER BY 4, 1"
11943   );
11944   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
11945     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
11946     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
11947     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
11948 
11949     if( zType==0 || zName==0 ) continue;
11950     if( zType[0]=='v' || zType[1]=='r' ){
11951       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
11952     }else{
11953       IdxTable *pTab;
11954       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
11955       if( rc==SQLITE_OK ){
11956         int i;
11957         char *zInner = 0;
11958         char *zOuter = 0;
11959         pTab->pNext = p->pTable;
11960         p->pTable = pTab;
11961 
11962         /* The statement the vtab will pass to sqlite3_declare_vtab() */
11963         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
11964         for(i=0; i<pTab->nCol; i++){
11965           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
11966               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
11967           );
11968         }
11969         zInner = idxAppendText(&rc, zInner, ")");
11970 
11971         /* The CVT statement to create the vtab */
11972         zOuter = idxAppendText(&rc, 0,
11973             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
11974         );
11975         if( rc==SQLITE_OK ){
11976           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
11977         }
11978         sqlite3_free(zInner);
11979         sqlite3_free(zOuter);
11980       }
11981     }
11982   }
11983   idxFinalize(&rc, pSchema);
11984   return rc;
11985 }
11986 
11987 struct IdxSampleCtx {
11988   int iTarget;
11989   double target;                  /* Target nRet/nRow value */
11990   double nRow;                    /* Number of rows seen */
11991   double nRet;                    /* Number of rows returned */
11992 };
11993 
11994 static void idxSampleFunc(
11995   sqlite3_context *pCtx,
11996   int argc,
11997   sqlite3_value **argv
11998 ){
11999   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
12000   int bRet;
12001 
12002   (void)argv;
12003   assert( argc==0 );
12004   if( p->nRow==0.0 ){
12005     bRet = 1;
12006   }else{
12007     bRet = (p->nRet / p->nRow) <= p->target;
12008     if( bRet==0 ){
12009       unsigned short rnd;
12010       sqlite3_randomness(2, (void*)&rnd);
12011       bRet = ((int)rnd % 100) <= p->iTarget;
12012     }
12013   }
12014 
12015   sqlite3_result_int(pCtx, bRet);
12016   p->nRow += 1.0;
12017   p->nRet += (double)bRet;
12018 }
12019 
12020 struct IdxRemCtx {
12021   int nSlot;
12022   struct IdxRemSlot {
12023     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
12024     i64 iVal;                     /* SQLITE_INTEGER value */
12025     double rVal;                  /* SQLITE_FLOAT value */
12026     int nByte;                    /* Bytes of space allocated at z */
12027     int n;                        /* Size of buffer z */
12028     char *z;                      /* SQLITE_TEXT/BLOB value */
12029   } aSlot[1];
12030 };
12031 
12032 /*
12033 ** Implementation of scalar function rem().
12034 */
12035 static void idxRemFunc(
12036   sqlite3_context *pCtx,
12037   int argc,
12038   sqlite3_value **argv
12039 ){
12040   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
12041   struct IdxRemSlot *pSlot;
12042   int iSlot;
12043   assert( argc==2 );
12044 
12045   iSlot = sqlite3_value_int(argv[0]);
12046   assert( iSlot<=p->nSlot );
12047   pSlot = &p->aSlot[iSlot];
12048 
12049   switch( pSlot->eType ){
12050     case SQLITE_NULL:
12051       /* no-op */
12052       break;
12053 
12054     case SQLITE_INTEGER:
12055       sqlite3_result_int64(pCtx, pSlot->iVal);
12056       break;
12057 
12058     case SQLITE_FLOAT:
12059       sqlite3_result_double(pCtx, pSlot->rVal);
12060       break;
12061 
12062     case SQLITE_BLOB:
12063       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
12064       break;
12065 
12066     case SQLITE_TEXT:
12067       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
12068       break;
12069   }
12070 
12071   pSlot->eType = sqlite3_value_type(argv[1]);
12072   switch( pSlot->eType ){
12073     case SQLITE_NULL:
12074       /* no-op */
12075       break;
12076 
12077     case SQLITE_INTEGER:
12078       pSlot->iVal = sqlite3_value_int64(argv[1]);
12079       break;
12080 
12081     case SQLITE_FLOAT:
12082       pSlot->rVal = sqlite3_value_double(argv[1]);
12083       break;
12084 
12085     case SQLITE_BLOB:
12086     case SQLITE_TEXT: {
12087       int nByte = sqlite3_value_bytes(argv[1]);
12088       const void *pData = 0;
12089       if( nByte>pSlot->nByte ){
12090         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
12091         if( zNew==0 ){
12092           sqlite3_result_error_nomem(pCtx);
12093           return;
12094         }
12095         pSlot->nByte = nByte*2;
12096         pSlot->z = zNew;
12097       }
12098       pSlot->n = nByte;
12099       if( pSlot->eType==SQLITE_BLOB ){
12100         pData = sqlite3_value_blob(argv[1]);
12101         if( pData ) memcpy(pSlot->z, pData, nByte);
12102       }else{
12103         pData = sqlite3_value_text(argv[1]);
12104         memcpy(pSlot->z, pData, nByte);
12105       }
12106       break;
12107     }
12108   }
12109 }
12110 
12111 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
12112   int rc = SQLITE_OK;
12113   const char *zMax =
12114     "SELECT max(i.seqno) FROM "
12115     "  sqlite_schema AS s, "
12116     "  pragma_index_list(s.name) AS l, "
12117     "  pragma_index_info(l.name) AS i "
12118     "WHERE s.type = 'table'";
12119   sqlite3_stmt *pMax = 0;
12120 
12121   *pnMax = 0;
12122   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
12123   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
12124     *pnMax = sqlite3_column_int(pMax, 0) + 1;
12125   }
12126   idxFinalize(&rc, pMax);
12127 
12128   return rc;
12129 }
12130 
12131 static int idxPopulateOneStat1(
12132   sqlite3expert *p,
12133   sqlite3_stmt *pIndexXInfo,
12134   sqlite3_stmt *pWriteStat,
12135   const char *zTab,
12136   const char *zIdx,
12137   char **pzErr
12138 ){
12139   char *zCols = 0;
12140   char *zOrder = 0;
12141   char *zQuery = 0;
12142   int nCol = 0;
12143   int i;
12144   sqlite3_stmt *pQuery = 0;
12145   int *aStat = 0;
12146   int rc = SQLITE_OK;
12147 
12148   assert( p->iSample>0 );
12149 
12150   /* Formulate the query text */
12151   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
12152   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
12153     const char *zComma = zCols==0 ? "" : ", ";
12154     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
12155     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
12156     zCols = idxAppendText(&rc, zCols,
12157         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
12158     );
12159     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
12160   }
12161   sqlite3_reset(pIndexXInfo);
12162   if( rc==SQLITE_OK ){
12163     if( p->iSample==100 ){
12164       zQuery = sqlite3_mprintf(
12165           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
12166       );
12167     }else{
12168       zQuery = sqlite3_mprintf(
12169           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
12170       );
12171     }
12172   }
12173   sqlite3_free(zCols);
12174   sqlite3_free(zOrder);
12175 
12176   /* Formulate the query text */
12177   if( rc==SQLITE_OK ){
12178     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
12179     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
12180   }
12181   sqlite3_free(zQuery);
12182 
12183   if( rc==SQLITE_OK ){
12184     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
12185   }
12186   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
12187     IdxHashEntry *pEntry;
12188     char *zStat = 0;
12189     for(i=0; i<=nCol; i++) aStat[i] = 1;
12190     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
12191       aStat[0]++;
12192       for(i=0; i<nCol; i++){
12193         if( sqlite3_column_int(pQuery, i)==0 ) break;
12194       }
12195       for(/*no-op*/; i<nCol; i++){
12196         aStat[i+1]++;
12197       }
12198     }
12199 
12200     if( rc==SQLITE_OK ){
12201       int s0 = aStat[0];
12202       zStat = sqlite3_mprintf("%d", s0);
12203       if( zStat==0 ) rc = SQLITE_NOMEM;
12204       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
12205         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
12206       }
12207     }
12208 
12209     if( rc==SQLITE_OK ){
12210       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
12211       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
12212       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
12213       sqlite3_step(pWriteStat);
12214       rc = sqlite3_reset(pWriteStat);
12215     }
12216 
12217     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
12218     if( pEntry ){
12219       assert( pEntry->zVal2==0 );
12220       pEntry->zVal2 = zStat;
12221     }else{
12222       sqlite3_free(zStat);
12223     }
12224   }
12225   sqlite3_free(aStat);
12226   idxFinalize(&rc, pQuery);
12227 
12228   return rc;
12229 }
12230 
12231 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
12232   int rc;
12233   char *zSql;
12234 
12235   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
12236   if( rc!=SQLITE_OK ) return rc;
12237 
12238   zSql = sqlite3_mprintf(
12239       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
12240   );
12241   if( zSql==0 ) return SQLITE_NOMEM;
12242   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
12243   sqlite3_free(zSql);
12244 
12245   return rc;
12246 }
12247 
12248 /*
12249 ** This function is called as part of sqlite3_expert_analyze(). Candidate
12250 ** indexes have already been created in database sqlite3expert.dbm, this
12251 ** function populates sqlite_stat1 table in the same database.
12252 **
12253 ** The stat1 data is generated by querying the
12254 */
12255 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
12256   int rc = SQLITE_OK;
12257   int nMax =0;
12258   struct IdxRemCtx *pCtx = 0;
12259   struct IdxSampleCtx samplectx;
12260   int i;
12261   i64 iPrev = -100000;
12262   sqlite3_stmt *pAllIndex = 0;
12263   sqlite3_stmt *pIndexXInfo = 0;
12264   sqlite3_stmt *pWrite = 0;
12265 
12266   const char *zAllIndex =
12267     "SELECT s.rowid, s.name, l.name FROM "
12268     "  sqlite_schema AS s, "
12269     "  pragma_index_list(s.name) AS l "
12270     "WHERE s.type = 'table'";
12271   const char *zIndexXInfo =
12272     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
12273   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
12274 
12275   /* If iSample==0, no sqlite_stat1 data is required. */
12276   if( p->iSample==0 ) return SQLITE_OK;
12277 
12278   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
12279   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
12280 
12281   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
12282 
12283   if( rc==SQLITE_OK ){
12284     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
12285     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
12286   }
12287 
12288   if( rc==SQLITE_OK ){
12289     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
12290     rc = sqlite3_create_function(
12291         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
12292     );
12293   }
12294   if( rc==SQLITE_OK ){
12295     rc = sqlite3_create_function(
12296         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
12297     );
12298   }
12299 
12300   if( rc==SQLITE_OK ){
12301     pCtx->nSlot = nMax+1;
12302     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
12303   }
12304   if( rc==SQLITE_OK ){
12305     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
12306   }
12307   if( rc==SQLITE_OK ){
12308     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
12309   }
12310 
12311   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
12312     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
12313     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
12314     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
12315     if( zTab==0 || zIdx==0 ) continue;
12316     if( p->iSample<100 && iPrev!=iRowid ){
12317       samplectx.target = (double)p->iSample / 100.0;
12318       samplectx.iTarget = p->iSample;
12319       samplectx.nRow = 0.0;
12320       samplectx.nRet = 0.0;
12321       rc = idxBuildSampleTable(p, zTab);
12322       if( rc!=SQLITE_OK ) break;
12323     }
12324     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
12325     iPrev = iRowid;
12326   }
12327   if( rc==SQLITE_OK && p->iSample<100 ){
12328     rc = sqlite3_exec(p->dbv,
12329         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
12330     );
12331   }
12332 
12333   idxFinalize(&rc, pAllIndex);
12334   idxFinalize(&rc, pIndexXInfo);
12335   idxFinalize(&rc, pWrite);
12336 
12337   if( pCtx ){
12338     for(i=0; i<pCtx->nSlot; i++){
12339       sqlite3_free(pCtx->aSlot[i].z);
12340     }
12341     sqlite3_free(pCtx);
12342   }
12343 
12344   if( rc==SQLITE_OK ){
12345     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
12346   }
12347 
12348   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
12349   return rc;
12350 }
12351 
12352 /*
12353 ** Allocate a new sqlite3expert object.
12354 */
12355 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
12356   int rc = SQLITE_OK;
12357   sqlite3expert *pNew;
12358 
12359   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
12360 
12361   /* Open two in-memory databases to work with. The "vtab database" (dbv)
12362   ** will contain a virtual table corresponding to each real table in
12363   ** the user database schema, and a copy of each view. It is used to
12364   ** collect information regarding the WHERE, ORDER BY and other clauses
12365   ** of the user's query.
12366   */
12367   if( rc==SQLITE_OK ){
12368     pNew->db = db;
12369     pNew->iSample = 100;
12370     rc = sqlite3_open(":memory:", &pNew->dbv);
12371   }
12372   if( rc==SQLITE_OK ){
12373     rc = sqlite3_open(":memory:", &pNew->dbm);
12374     if( rc==SQLITE_OK ){
12375       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
12376     }
12377   }
12378 
12379 
12380   /* Copy the entire schema of database [db] into [dbm]. */
12381   if( rc==SQLITE_OK ){
12382     sqlite3_stmt *pSql = 0;
12383     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
12384         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
12385         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
12386     );
12387     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12388       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
12389       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
12390     }
12391     idxFinalize(&rc, pSql);
12392   }
12393 
12394   /* Create the vtab schema */
12395   if( rc==SQLITE_OK ){
12396     rc = idxCreateVtabSchema(pNew, pzErrmsg);
12397   }
12398 
12399   /* Register the auth callback with dbv */
12400   if( rc==SQLITE_OK ){
12401     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
12402   }
12403 
12404   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
12405   ** return the new sqlite3expert handle.  */
12406   if( rc!=SQLITE_OK ){
12407     sqlite3_expert_destroy(pNew);
12408     pNew = 0;
12409   }
12410   return pNew;
12411 }
12412 
12413 /*
12414 ** Configure an sqlite3expert object.
12415 */
12416 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
12417   int rc = SQLITE_OK;
12418   va_list ap;
12419   va_start(ap, op);
12420   switch( op ){
12421     case EXPERT_CONFIG_SAMPLE: {
12422       int iVal = va_arg(ap, int);
12423       if( iVal<0 ) iVal = 0;
12424       if( iVal>100 ) iVal = 100;
12425       p->iSample = iVal;
12426       break;
12427     }
12428     default:
12429       rc = SQLITE_NOTFOUND;
12430       break;
12431   }
12432 
12433   va_end(ap);
12434   return rc;
12435 }
12436 
12437 /*
12438 ** Add an SQL statement to the analysis.
12439 */
12440 int sqlite3_expert_sql(
12441   sqlite3expert *p,               /* From sqlite3_expert_new() */
12442   const char *zSql,               /* SQL statement to add */
12443   char **pzErr                    /* OUT: Error message (if any) */
12444 ){
12445   IdxScan *pScanOrig = p->pScan;
12446   IdxStatement *pStmtOrig = p->pStatement;
12447   int rc = SQLITE_OK;
12448   const char *zStmt = zSql;
12449 
12450   if( p->bRun ) return SQLITE_MISUSE;
12451 
12452   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
12453     sqlite3_stmt *pStmt = 0;
12454     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
12455     if( rc==SQLITE_OK ){
12456       if( pStmt ){
12457         IdxStatement *pNew;
12458         const char *z = sqlite3_sql(pStmt);
12459         int n = STRLEN(z);
12460         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
12461         if( rc==SQLITE_OK ){
12462           pNew->zSql = (char*)&pNew[1];
12463           memcpy(pNew->zSql, z, n+1);
12464           pNew->pNext = p->pStatement;
12465           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
12466           p->pStatement = pNew;
12467         }
12468         sqlite3_finalize(pStmt);
12469       }
12470     }else{
12471       idxDatabaseError(p->dbv, pzErr);
12472     }
12473   }
12474 
12475   if( rc!=SQLITE_OK ){
12476     idxScanFree(p->pScan, pScanOrig);
12477     idxStatementFree(p->pStatement, pStmtOrig);
12478     p->pScan = pScanOrig;
12479     p->pStatement = pStmtOrig;
12480   }
12481 
12482   return rc;
12483 }
12484 
12485 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
12486   int rc;
12487   IdxHashEntry *pEntry;
12488 
12489   /* Do trigger processing to collect any extra IdxScan structures */
12490   rc = idxProcessTriggers(p, pzErr);
12491 
12492   /* Create candidate indexes within the in-memory database file */
12493   if( rc==SQLITE_OK ){
12494     rc = idxCreateCandidates(p);
12495   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
12496     if( pzErr )
12497       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
12498     return rc;
12499   }
12500 
12501   /* Generate the stat1 data */
12502   if( rc==SQLITE_OK ){
12503     rc = idxPopulateStat1(p, pzErr);
12504   }
12505 
12506   /* Formulate the EXPERT_REPORT_CANDIDATES text */
12507   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
12508     p->zCandidates = idxAppendText(&rc, p->zCandidates,
12509         "%s;%s%s\n", pEntry->zVal,
12510         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
12511     );
12512   }
12513 
12514   /* Figure out which of the candidate indexes are preferred by the query
12515   ** planner and report the results to the user.  */
12516   if( rc==SQLITE_OK ){
12517     rc = idxFindIndexes(p, pzErr);
12518   }
12519 
12520   if( rc==SQLITE_OK ){
12521     p->bRun = 1;
12522   }
12523   return rc;
12524 }
12525 
12526 /*
12527 ** Return the total number of statements that have been added to this
12528 ** sqlite3expert using sqlite3_expert_sql().
12529 */
12530 int sqlite3_expert_count(sqlite3expert *p){
12531   int nRet = 0;
12532   if( p->pStatement ) nRet = p->pStatement->iId+1;
12533   return nRet;
12534 }
12535 
12536 /*
12537 ** Return a component of the report.
12538 */
12539 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
12540   const char *zRet = 0;
12541   IdxStatement *pStmt;
12542 
12543   if( p->bRun==0 ) return 0;
12544   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
12545   switch( eReport ){
12546     case EXPERT_REPORT_SQL:
12547       if( pStmt ) zRet = pStmt->zSql;
12548       break;
12549     case EXPERT_REPORT_INDEXES:
12550       if( pStmt ) zRet = pStmt->zIdx;
12551       break;
12552     case EXPERT_REPORT_PLAN:
12553       if( pStmt ) zRet = pStmt->zEQP;
12554       break;
12555     case EXPERT_REPORT_CANDIDATES:
12556       zRet = p->zCandidates;
12557       break;
12558   }
12559   return zRet;
12560 }
12561 
12562 /*
12563 ** Free an sqlite3expert object.
12564 */
12565 void sqlite3_expert_destroy(sqlite3expert *p){
12566   if( p ){
12567     sqlite3_close(p->dbm);
12568     sqlite3_close(p->dbv);
12569     idxScanFree(p->pScan, 0);
12570     idxStatementFree(p->pStatement, 0);
12571     idxTableFree(p->pTable);
12572     idxWriteFree(p->pWrite);
12573     idxHashClear(&p->hIdx);
12574     sqlite3_free(p->zCandidates);
12575     sqlite3_free(p);
12576   }
12577 }
12578 
12579 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
12580 
12581 /************************* End ../ext/expert/sqlite3expert.c ********************/
12582 
12583 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12584 #define SQLITE_SHELL_HAVE_RECOVER 1
12585 #else
12586 #define SQLITE_SHELL_HAVE_RECOVER 0
12587 #endif
12588 #if SQLITE_SHELL_HAVE_RECOVER
12589 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
12590 /*
12591 ** 2022-08-27
12592 **
12593 ** The author disclaims copyright to this source code.  In place of
12594 ** a legal notice, here is a blessing:
12595 **
12596 **    May you do good and not evil.
12597 **    May you find forgiveness for yourself and forgive others.
12598 **    May you share freely, never taking more than you give.
12599 **
12600 *************************************************************************
12601 **
12602 ** This file contains the public interface to the "recover" extension -
12603 ** an SQLite extension designed to recover data from corrupted database
12604 ** files.
12605 */
12606 
12607 /*
12608 ** OVERVIEW:
12609 **
12610 ** To use the API to recover data from a corrupted database, an
12611 ** application:
12612 **
12613 **   1) Creates an sqlite3_recover handle by calling either
12614 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
12615 **
12616 **   2) Configures the new handle using one or more calls to
12617 **      sqlite3_recover_config().
12618 **
12619 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
12620 **      the handle until it returns something other than SQLITE_OK. If it
12621 **      returns SQLITE_DONE, then the recovery operation completed without
12622 **      error. If it returns some other non-SQLITE_OK value, then an error
12623 **      has occurred.
12624 **
12625 **   4) Retrieves any error code and English language error message using the
12626 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
12627 **      respectively.
12628 **
12629 **   5) Destroys the sqlite3_recover handle and frees all resources
12630 **      using sqlite3_recover_finish().
12631 **
12632 ** The application may abandon the recovery operation at any point
12633 ** before it is finished by passing the sqlite3_recover handle to
12634 ** sqlite3_recover_finish(). This is not an error, but the final state
12635 ** of the output database, or the results of running the partial script
12636 ** delivered to the SQL callback, are undefined.
12637 */
12638 
12639 #ifndef _SQLITE_RECOVER_H
12640 #define _SQLITE_RECOVER_H
12641 
12642 /* #include "sqlite3.h" */
12643 
12644 #ifdef __cplusplus
12645 extern "C" {
12646 #endif
12647 
12648 /*
12649 ** An instance of the sqlite3_recover object represents a recovery
12650 ** operation in progress.
12651 **
12652 ** Constructors:
12653 **
12654 **    sqlite3_recover_init()
12655 **    sqlite3_recover_init_sql()
12656 **
12657 ** Destructor:
12658 **
12659 **    sqlite3_recover_finish()
12660 **
12661 ** Methods:
12662 **
12663 **    sqlite3_recover_config()
12664 **    sqlite3_recover_errcode()
12665 **    sqlite3_recover_errmsg()
12666 **    sqlite3_recover_run()
12667 **    sqlite3_recover_step()
12668 */
12669 typedef struct sqlite3_recover sqlite3_recover;
12670 
12671 /*
12672 ** These two APIs attempt to create and return a new sqlite3_recover object.
12673 ** In both cases the first two arguments identify the (possibly
12674 ** corrupt) database to recover data from. The first argument is an open
12675 ** database handle and the second the name of a database attached to that
12676 ** handle (i.e. "main", "temp" or the name of an attached database).
12677 **
12678 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
12679 ** handle, then data is recovered into a new database, identified by
12680 ** string parameter zUri. zUri may be an absolute or relative file path,
12681 ** or may be an SQLite URI. If the identified database file already exists,
12682 ** it is overwritten.
12683 **
12684 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
12685 ** be returned to the user as a series of SQL statements. Executing these
12686 ** SQL statements results in the same database as would have been created
12687 ** had sqlite3_recover_init() been used. For each SQL statement in the
12688 ** output, the callback function passed as the third argument (xSql) is
12689 ** invoked once. The first parameter is a passed a copy of the fourth argument
12690 ** to this function (pCtx) as its first parameter, and a pointer to a
12691 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
12692 ** the second. If the xSql callback returns any value other than SQLITE_OK,
12693 ** then processing is immediately abandoned and the value returned used as
12694 ** the recover handle error code (see below).
12695 **
12696 ** If an out-of-memory error occurs, NULL may be returned instead of
12697 ** a valid handle. In all other cases, it is the responsibility of the
12698 ** application to avoid resource leaks by ensuring that
12699 ** sqlite3_recover_finish() is called on all allocated handles.
12700 */
12701 sqlite3_recover *sqlite3_recover_init(
12702   sqlite3* db,
12703   const char *zDb,
12704   const char *zUri
12705 );
12706 sqlite3_recover *sqlite3_recover_init_sql(
12707   sqlite3* db,
12708   const char *zDb,
12709   int (*xSql)(void*, const char*),
12710   void *pCtx
12711 );
12712 
12713 /*
12714 ** Configure an sqlite3_recover object that has just been created using
12715 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
12716 ** may only be called before the first call to sqlite3_recover_step()
12717 ** or sqlite3_recover_run() on the object.
12718 **
12719 ** The second argument passed to this function must be one of the
12720 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
12721 ** depend on the specific SQLITE_RECOVER_* symbol in use.
12722 **
12723 ** SQLITE_OK is returned if the configuration operation was successful,
12724 ** or an SQLite error code otherwise.
12725 */
12726 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
12727 
12728 /*
12729 ** SQLITE_RECOVER_LOST_AND_FOUND:
12730 **   The pArg argument points to a string buffer containing the name
12731 **   of a "lost-and-found" table in the output database, or NULL. If
12732 **   the argument is non-NULL and the database contains seemingly
12733 **   valid pages that cannot be associated with any table in the
12734 **   recovered part of the schema, data is extracted from these
12735 **   pages to add to the lost-and-found table.
12736 **
12737 ** SQLITE_RECOVER_FREELIST_CORRUPT:
12738 **   The pArg value must actually be a pointer to a value of type
12739 **   int containing value 0 or 1 cast as a (void*). If this option is set
12740 **   (argument is 1) and a lost-and-found table has been configured using
12741 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
12742 **   corrupt and an attempt is made to recover records from pages that
12743 **   appear to be linked into the freelist. Otherwise, pages on the freelist
12744 **   are ignored. Setting this option can recover more data from the
12745 **   database, but often ends up "recovering" deleted records. The default
12746 **   value is 0 (clear).
12747 **
12748 ** SQLITE_RECOVER_ROWIDS:
12749 **   The pArg value must actually be a pointer to a value of type
12750 **   int containing value 0 or 1 cast as a (void*). If this option is set
12751 **   (argument is 1), then an attempt is made to recover rowid values
12752 **   that are not also INTEGER PRIMARY KEY values. If this option is
12753 **   clear, then new rowids are assigned to all recovered rows. The
12754 **   default value is 1 (set).
12755 **
12756 ** SQLITE_RECOVER_SLOWINDEXES:
12757 **   The pArg value must actually be a pointer to a value of type
12758 **   int containing value 0 or 1 cast as a (void*). If this option is clear
12759 **   (argument is 0), then when creating an output database, the recover
12760 **   module creates and populates non-UNIQUE indexes right at the end of the
12761 **   recovery operation - after all recoverable data has been inserted
12762 **   into the new database. This is faster overall, but means that the
12763 **   final call to sqlite3_recover_step() for a recovery operation may
12764 **   be need to create a large number of indexes, which may be very slow.
12765 **
12766 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
12767 **   are created in the output database before it is populated with
12768 **   recovered data. This is slower overall, but avoids the slow call
12769 **   to sqlite3_recover_step() at the end of the recovery operation.
12770 **
12771 **   The default option value is 0.
12772 */
12773 #define SQLITE_RECOVER_LOST_AND_FOUND   1
12774 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
12775 #define SQLITE_RECOVER_ROWIDS           3
12776 #define SQLITE_RECOVER_SLOWINDEXES      4
12777 
12778 /*
12779 ** Perform a unit of work towards the recovery operation. This function
12780 ** must normally be called multiple times to complete database recovery.
12781 **
12782 ** If no error occurs but the recovery operation is not completed, this
12783 ** function returns SQLITE_OK. If recovery has been completed successfully
12784 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
12785 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
12786 ** considered an error if some or all of the data cannot be recovered
12787 ** due to database corruption.
12788 **
12789 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
12790 ** all further such calls on the same recover handle are no-ops that return
12791 ** the same non-SQLITE_OK value.
12792 */
12793 int sqlite3_recover_step(sqlite3_recover*);
12794 
12795 /*
12796 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
12797 ** or an SQLite error code otherwise. Calling this function is the same
12798 ** as executing:
12799 **
12800 **     while( SQLITE_OK==sqlite3_recover_step(p) );
12801 **     return sqlite3_recover_errcode(p);
12802 */
12803 int sqlite3_recover_run(sqlite3_recover*);
12804 
12805 /*
12806 ** If an error has been encountered during a prior call to
12807 ** sqlite3_recover_step(), then this function attempts to return a
12808 ** pointer to a buffer containing an English language explanation of
12809 ** the error. If no error message is available, or if an out-of memory
12810 ** error occurs while attempting to allocate a buffer in which to format
12811 ** the error message, NULL is returned.
12812 **
12813 ** The returned buffer remains valid until the sqlite3_recover handle is
12814 ** destroyed using sqlite3_recover_finish().
12815 */
12816 const char *sqlite3_recover_errmsg(sqlite3_recover*);
12817 
12818 /*
12819 ** If this function is called on an sqlite3_recover handle after
12820 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
12821 */
12822 int sqlite3_recover_errcode(sqlite3_recover*);
12823 
12824 /*
12825 ** Clean up a recovery object created by a call to sqlite3_recover_init().
12826 ** The results of using a recovery object with any API after it has been
12827 ** passed to this function are undefined.
12828 **
12829 ** This function returns the same value as sqlite3_recover_errcode().
12830 */
12831 int sqlite3_recover_finish(sqlite3_recover*);
12832 
12833 
12834 #ifdef __cplusplus
12835 }  /* end of the 'extern "C"' block */
12836 #endif
12837 
12838 #endif /* ifndef _SQLITE_RECOVER_H */
12839 
12840 /************************* End ../ext/recover/sqlite3recover.h ********************/
12841 # ifndef SQLITE_HAVE_SQLITE3R
12842 /************************* Begin ../ext/recover/dbdata.c ******************/
12843 /*
12844 ** 2019-04-17
12845 **
12846 ** The author disclaims copyright to this source code.  In place of
12847 ** a legal notice, here is a blessing:
12848 **
12849 **    May you do good and not evil.
12850 **    May you find forgiveness for yourself and forgive others.
12851 **    May you share freely, never taking more than you give.
12852 **
12853 ******************************************************************************
12854 **
12855 ** This file contains an implementation of two eponymous virtual tables,
12856 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
12857 ** "sqlite_dbpage" eponymous virtual table be available.
12858 **
12859 ** SQLITE_DBDATA:
12860 **   sqlite_dbdata is used to extract data directly from a database b-tree
12861 **   page and its associated overflow pages, bypassing the b-tree layer.
12862 **   The table schema is equivalent to:
12863 **
12864 **     CREATE TABLE sqlite_dbdata(
12865 **       pgno INTEGER,
12866 **       cell INTEGER,
12867 **       field INTEGER,
12868 **       value ANY,
12869 **       schema TEXT HIDDEN
12870 **     );
12871 **
12872 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
12873 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
12874 **   "schema".
12875 **
12876 **   Each page of the database is inspected. If it cannot be interpreted as
12877 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
12878 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
12879 **   table contains one row for each field in the record associated with
12880 **   each cell on the page. For intkey b-trees, the key value is stored in
12881 **   field -1.
12882 **
12883 **   For example, for the database:
12884 **
12885 **     CREATE TABLE t1(a, b);     -- root page is page 2
12886 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
12887 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
12888 **
12889 **   the sqlite_dbdata table contains, as well as from entries related to
12890 **   page 1, content equivalent to:
12891 **
12892 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
12893 **         (2, 0, -1, 5     ),
12894 **         (2, 0,  0, 'v'   ),
12895 **         (2, 0,  1, 'five'),
12896 **         (2, 1, -1, 10    ),
12897 **         (2, 1,  0, 'x'   ),
12898 **         (2, 1,  1, 'ten' );
12899 **
12900 **   If database corruption is encountered, this module does not report an
12901 **   error. Instead, it attempts to extract as much data as possible and
12902 **   ignores the corruption.
12903 **
12904 ** SQLITE_DBPTR:
12905 **   The sqlite_dbptr table has the following schema:
12906 **
12907 **     CREATE TABLE sqlite_dbptr(
12908 **       pgno INTEGER,
12909 **       child INTEGER,
12910 **       schema TEXT HIDDEN
12911 **     );
12912 **
12913 **   It contains one entry for each b-tree pointer between a parent and
12914 **   child page in the database.
12915 */
12916 
12917 #if !defined(SQLITEINT_H)
12918 /* #include "sqlite3ext.h" */
12919 
12920 /* typedef unsigned char u8; */
12921 /* typedef unsigned int u32; */
12922 
12923 #endif
12924 SQLITE_EXTENSION_INIT1
12925 #include <string.h>
12926 #include <assert.h>
12927 
12928 #ifndef SQLITE_OMIT_VIRTUALTABLE
12929 
12930 #define DBDATA_PADDING_BYTES 100
12931 
12932 typedef struct DbdataTable DbdataTable;
12933 typedef struct DbdataCursor DbdataCursor;
12934 
12935 /* Cursor object */
12936 struct DbdataCursor {
12937   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
12938   sqlite3_stmt *pStmt;            /* For fetching database pages */
12939 
12940   int iPgno;                      /* Current page number */
12941   u8 *aPage;                      /* Buffer containing page */
12942   int nPage;                      /* Size of aPage[] in bytes */
12943   int nCell;                      /* Number of cells on aPage[] */
12944   int iCell;                      /* Current cell number */
12945   int bOnePage;                   /* True to stop after one page */
12946   int szDb;
12947   sqlite3_int64 iRowid;
12948 
12949   /* Only for the sqlite_dbdata table */
12950   u8 *pRec;                       /* Buffer containing current record */
12951   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
12952   sqlite3_int64 nHdr;             /* Size of header in bytes */
12953   int iField;                     /* Current field number */
12954   u8 *pHdrPtr;
12955   u8 *pPtr;
12956   u32 enc;                        /* Text encoding */
12957 
12958   sqlite3_int64 iIntkey;          /* Integer key value */
12959 };
12960 
12961 /* Table object */
12962 struct DbdataTable {
12963   sqlite3_vtab base;              /* Base class.  Must be first */
12964   sqlite3 *db;                    /* The database connection */
12965   sqlite3_stmt *pStmt;            /* For fetching database pages */
12966   int bPtr;                       /* True for sqlite3_dbptr table */
12967 };
12968 
12969 /* Column and schema definitions for sqlite_dbdata */
12970 #define DBDATA_COLUMN_PGNO        0
12971 #define DBDATA_COLUMN_CELL        1
12972 #define DBDATA_COLUMN_FIELD       2
12973 #define DBDATA_COLUMN_VALUE       3
12974 #define DBDATA_COLUMN_SCHEMA      4
12975 #define DBDATA_SCHEMA             \
12976       "CREATE TABLE x("           \
12977       "  pgno INTEGER,"           \
12978       "  cell INTEGER,"           \
12979       "  field INTEGER,"          \
12980       "  value ANY,"              \
12981       "  schema TEXT HIDDEN"      \
12982       ")"
12983 
12984 /* Column and schema definitions for sqlite_dbptr */
12985 #define DBPTR_COLUMN_PGNO         0
12986 #define DBPTR_COLUMN_CHILD        1
12987 #define DBPTR_COLUMN_SCHEMA       2
12988 #define DBPTR_SCHEMA              \
12989       "CREATE TABLE x("           \
12990       "  pgno INTEGER,"           \
12991       "  child INTEGER,"          \
12992       "  schema TEXT HIDDEN"      \
12993       ")"
12994 
12995 /*
12996 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
12997 ** table.
12998 */
12999 static int dbdataConnect(
13000   sqlite3 *db,
13001   void *pAux,
13002   int argc, const char *const*argv,
13003   sqlite3_vtab **ppVtab,
13004   char **pzErr
13005 ){
13006   DbdataTable *pTab = 0;
13007   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
13008 
13009   (void)argc;
13010   (void)argv;
13011   (void)pzErr;
13012   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
13013   if( rc==SQLITE_OK ){
13014     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
13015     if( pTab==0 ){
13016       rc = SQLITE_NOMEM;
13017     }else{
13018       memset(pTab, 0, sizeof(DbdataTable));
13019       pTab->db = db;
13020       pTab->bPtr = (pAux!=0);
13021     }
13022   }
13023 
13024   *ppVtab = (sqlite3_vtab*)pTab;
13025   return rc;
13026 }
13027 
13028 /*
13029 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
13030 */
13031 static int dbdataDisconnect(sqlite3_vtab *pVtab){
13032   DbdataTable *pTab = (DbdataTable*)pVtab;
13033   if( pTab ){
13034     sqlite3_finalize(pTab->pStmt);
13035     sqlite3_free(pVtab);
13036   }
13037   return SQLITE_OK;
13038 }
13039 
13040 /*
13041 ** This function interprets two types of constraints:
13042 **
13043 **       schema=?
13044 **       pgno=?
13045 **
13046 ** If neither are present, idxNum is set to 0. If schema=? is present,
13047 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
13048 ** in idxNum is set.
13049 **
13050 ** If both parameters are present, schema is in position 0 and pgno in
13051 ** position 1.
13052 */
13053 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
13054   DbdataTable *pTab = (DbdataTable*)tab;
13055   int i;
13056   int iSchema = -1;
13057   int iPgno = -1;
13058   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
13059 
13060   for(i=0; i<pIdx->nConstraint; i++){
13061     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
13062     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
13063       if( p->iColumn==colSchema ){
13064         if( p->usable==0 ) return SQLITE_CONSTRAINT;
13065         iSchema = i;
13066       }
13067       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
13068         iPgno = i;
13069       }
13070     }
13071   }
13072 
13073   if( iSchema>=0 ){
13074     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
13075     pIdx->aConstraintUsage[iSchema].omit = 1;
13076   }
13077   if( iPgno>=0 ){
13078     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
13079     pIdx->aConstraintUsage[iPgno].omit = 1;
13080     pIdx->estimatedCost = 100;
13081     pIdx->estimatedRows =  50;
13082 
13083     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
13084       int iCol = pIdx->aOrderBy[0].iColumn;
13085       if( pIdx->nOrderBy==1 ){
13086         pIdx->orderByConsumed = (iCol==0 || iCol==1);
13087       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
13088         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
13089       }
13090     }
13091 
13092   }else{
13093     pIdx->estimatedCost = 100000000;
13094     pIdx->estimatedRows = 1000000000;
13095   }
13096   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
13097   return SQLITE_OK;
13098 }
13099 
13100 /*
13101 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
13102 */
13103 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
13104   DbdataCursor *pCsr;
13105 
13106   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
13107   if( pCsr==0 ){
13108     return SQLITE_NOMEM;
13109   }else{
13110     memset(pCsr, 0, sizeof(DbdataCursor));
13111     pCsr->base.pVtab = pVTab;
13112   }
13113 
13114   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
13115   return SQLITE_OK;
13116 }
13117 
13118 /*
13119 ** Restore a cursor object to the state it was in when first allocated
13120 ** by dbdataOpen().
13121 */
13122 static void dbdataResetCursor(DbdataCursor *pCsr){
13123   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
13124   if( pTab->pStmt==0 ){
13125     pTab->pStmt = pCsr->pStmt;
13126   }else{
13127     sqlite3_finalize(pCsr->pStmt);
13128   }
13129   pCsr->pStmt = 0;
13130   pCsr->iPgno = 1;
13131   pCsr->iCell = 0;
13132   pCsr->iField = 0;
13133   pCsr->bOnePage = 0;
13134   sqlite3_free(pCsr->aPage);
13135   sqlite3_free(pCsr->pRec);
13136   pCsr->pRec = 0;
13137   pCsr->aPage = 0;
13138 }
13139 
13140 /*
13141 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
13142 */
13143 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
13144   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13145   dbdataResetCursor(pCsr);
13146   sqlite3_free(pCsr);
13147   return SQLITE_OK;
13148 }
13149 
13150 /*
13151 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
13152 */
13153 static u32 get_uint16(unsigned char *a){
13154   return (a[0]<<8)|a[1];
13155 }
13156 static u32 get_uint32(unsigned char *a){
13157   return ((u32)a[0]<<24)
13158        | ((u32)a[1]<<16)
13159        | ((u32)a[2]<<8)
13160        | ((u32)a[3]);
13161 }
13162 
13163 /*
13164 ** Load page pgno from the database via the sqlite_dbpage virtual table.
13165 ** If successful, set (*ppPage) to point to a buffer containing the page
13166 ** data, (*pnPage) to the size of that buffer in bytes and return
13167 ** SQLITE_OK. In this case it is the responsibility of the caller to
13168 ** eventually free the buffer using sqlite3_free().
13169 **
13170 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
13171 ** return an SQLite error code.
13172 */
13173 static int dbdataLoadPage(
13174   DbdataCursor *pCsr,             /* Cursor object */
13175   u32 pgno,                       /* Page number of page to load */
13176   u8 **ppPage,                    /* OUT: pointer to page buffer */
13177   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
13178 ){
13179   int rc2;
13180   int rc = SQLITE_OK;
13181   sqlite3_stmt *pStmt = pCsr->pStmt;
13182 
13183   *ppPage = 0;
13184   *pnPage = 0;
13185   if( pgno>0 ){
13186     sqlite3_bind_int64(pStmt, 2, pgno);
13187     if( SQLITE_ROW==sqlite3_step(pStmt) ){
13188       int nCopy = sqlite3_column_bytes(pStmt, 0);
13189       if( nCopy>0 ){
13190         u8 *pPage;
13191         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
13192         if( pPage==0 ){
13193           rc = SQLITE_NOMEM;
13194         }else{
13195           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
13196           memcpy(pPage, pCopy, nCopy);
13197           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
13198         }
13199         *ppPage = pPage;
13200         *pnPage = nCopy;
13201       }
13202     }
13203     rc2 = sqlite3_reset(pStmt);
13204     if( rc==SQLITE_OK ) rc = rc2;
13205   }
13206 
13207   return rc;
13208 }
13209 
13210 /*
13211 ** Read a varint.  Put the value in *pVal and return the number of bytes.
13212 */
13213 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
13214   sqlite3_uint64 u = 0;
13215   int i;
13216   for(i=0; i<8; i++){
13217     u = (u<<7) + (z[i]&0x7f);
13218     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
13219   }
13220   u = (u<<8) + (z[i]&0xff);
13221   *pVal = (sqlite3_int64)u;
13222   return 9;
13223 }
13224 
13225 /*
13226 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
13227 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
13228 ** SQLite database except for key values in intkey tables.
13229 */
13230 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
13231   sqlite3_int64 val;
13232   int nRet = dbdataGetVarint(z, &val);
13233   if( val<0 || val>0xFFFFFFFF ) val = 0;
13234   *pVal = val;
13235   return nRet;
13236 }
13237 
13238 /*
13239 ** Return the number of bytes of space used by an SQLite value of type
13240 ** eType.
13241 */
13242 static int dbdataValueBytes(int eType){
13243   switch( eType ){
13244     case 0: case 8: case 9:
13245     case 10: case 11:
13246       return 0;
13247     case 1:
13248       return 1;
13249     case 2:
13250       return 2;
13251     case 3:
13252       return 3;
13253     case 4:
13254       return 4;
13255     case 5:
13256       return 6;
13257     case 6:
13258     case 7:
13259       return 8;
13260     default:
13261       if( eType>0 ){
13262         return ((eType-12) / 2);
13263       }
13264       return 0;
13265   }
13266 }
13267 
13268 /*
13269 ** Load a value of type eType from buffer pData and use it to set the
13270 ** result of context object pCtx.
13271 */
13272 static void dbdataValue(
13273   sqlite3_context *pCtx,
13274   u32 enc,
13275   int eType,
13276   u8 *pData,
13277   sqlite3_int64 nData
13278 ){
13279   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
13280     switch( eType ){
13281       case 0:
13282       case 10:
13283       case 11:
13284         sqlite3_result_null(pCtx);
13285         break;
13286 
13287       case 8:
13288         sqlite3_result_int(pCtx, 0);
13289         break;
13290       case 9:
13291         sqlite3_result_int(pCtx, 1);
13292         break;
13293 
13294       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
13295         sqlite3_uint64 v = (signed char)pData[0];
13296         pData++;
13297         switch( eType ){
13298           case 7:
13299           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
13300           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
13301           case 4:  v = (v<<8) + pData[0];  pData++;
13302           case 3:  v = (v<<8) + pData[0];  pData++;
13303           case 2:  v = (v<<8) + pData[0];  pData++;
13304         }
13305 
13306         if( eType==7 ){
13307           double r;
13308           memcpy(&r, &v, sizeof(r));
13309           sqlite3_result_double(pCtx, r);
13310         }else{
13311           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
13312         }
13313         break;
13314       }
13315 
13316       default: {
13317         int n = ((eType-12) / 2);
13318         if( eType % 2 ){
13319           switch( enc ){
13320 #ifndef SQLITE_OMIT_UTF16
13321             case SQLITE_UTF16BE:
13322               sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
13323               break;
13324             case SQLITE_UTF16LE:
13325               sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
13326               break;
13327 #endif
13328             default:
13329               sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
13330               break;
13331           }
13332         }else{
13333           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
13334         }
13335       }
13336     }
13337   }
13338 }
13339 
13340 /*
13341 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
13342 */
13343 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
13344   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13345   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13346 
13347   pCsr->iRowid++;
13348   while( 1 ){
13349     int rc;
13350     int iOff = (pCsr->iPgno==1 ? 100 : 0);
13351     int bNextPage = 0;
13352 
13353     if( pCsr->aPage==0 ){
13354       while( 1 ){
13355         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
13356         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
13357         if( rc!=SQLITE_OK ) return rc;
13358         if( pCsr->aPage && pCsr->nPage>=256 ) break;
13359         sqlite3_free(pCsr->aPage);
13360         pCsr->aPage = 0;
13361         if( pCsr->bOnePage ) return SQLITE_OK;
13362         pCsr->iPgno++;
13363       }
13364 
13365       assert( iOff+3+2<=pCsr->nPage );
13366       pCsr->iCell = pTab->bPtr ? -2 : 0;
13367       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
13368     }
13369 
13370     if( pTab->bPtr ){
13371       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
13372         pCsr->iCell = pCsr->nCell;
13373       }
13374       pCsr->iCell++;
13375       if( pCsr->iCell>=pCsr->nCell ){
13376         sqlite3_free(pCsr->aPage);
13377         pCsr->aPage = 0;
13378         if( pCsr->bOnePage ) return SQLITE_OK;
13379         pCsr->iPgno++;
13380       }else{
13381         return SQLITE_OK;
13382       }
13383     }else{
13384       /* If there is no record loaded, load it now. */
13385       if( pCsr->pRec==0 ){
13386         int bHasRowid = 0;
13387         int nPointer = 0;
13388         sqlite3_int64 nPayload = 0;
13389         sqlite3_int64 nHdr = 0;
13390         int iHdr;
13391         int U, X;
13392         int nLocal;
13393 
13394         switch( pCsr->aPage[iOff] ){
13395           case 0x02:
13396             nPointer = 4;
13397             break;
13398           case 0x0a:
13399             break;
13400           case 0x0d:
13401             bHasRowid = 1;
13402             break;
13403           default:
13404             /* This is not a b-tree page with records on it. Continue. */
13405             pCsr->iCell = pCsr->nCell;
13406             break;
13407         }
13408 
13409         if( pCsr->iCell>=pCsr->nCell ){
13410           bNextPage = 1;
13411         }else{
13412 
13413           iOff += 8 + nPointer + pCsr->iCell*2;
13414           if( iOff>pCsr->nPage ){
13415             bNextPage = 1;
13416           }else{
13417             iOff = get_uint16(&pCsr->aPage[iOff]);
13418           }
13419 
13420           /* For an interior node cell, skip past the child-page number */
13421           iOff += nPointer;
13422 
13423           /* Load the "byte of payload including overflow" field */
13424           if( bNextPage || iOff>pCsr->nPage ){
13425             bNextPage = 1;
13426           }else{
13427             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
13428           }
13429 
13430           /* If this is a leaf intkey cell, load the rowid */
13431           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
13432             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
13433           }
13434 
13435           /* Figure out how much data to read from the local page */
13436           U = pCsr->nPage;
13437           if( bHasRowid ){
13438             X = U-35;
13439           }else{
13440             X = ((U-12)*64/255)-23;
13441           }
13442           if( nPayload<=X ){
13443             nLocal = nPayload;
13444           }else{
13445             int M, K;
13446             M = ((U-12)*32/255)-23;
13447             K = M+((nPayload-M)%(U-4));
13448             if( K<=X ){
13449               nLocal = K;
13450             }else{
13451               nLocal = M;
13452             }
13453           }
13454 
13455           if( bNextPage || nLocal+iOff>pCsr->nPage ){
13456             bNextPage = 1;
13457           }else{
13458 
13459             /* Allocate space for payload. And a bit more to catch small buffer
13460             ** overruns caused by attempting to read a varint or similar from
13461             ** near the end of a corrupt record.  */
13462             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
13463             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
13464             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
13465             pCsr->nRec = nPayload;
13466 
13467             /* Load the nLocal bytes of payload */
13468             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
13469             iOff += nLocal;
13470 
13471             /* Load content from overflow pages */
13472             if( nPayload>nLocal ){
13473               sqlite3_int64 nRem = nPayload - nLocal;
13474               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
13475               while( nRem>0 ){
13476                 u8 *aOvfl = 0;
13477                 int nOvfl = 0;
13478                 int nCopy;
13479                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
13480                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
13481                 if( rc!=SQLITE_OK ) return rc;
13482                 if( aOvfl==0 ) break;
13483 
13484                 nCopy = U-4;
13485                 if( nCopy>nRem ) nCopy = nRem;
13486                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
13487                 nRem -= nCopy;
13488 
13489                 pgnoOvfl = get_uint32(aOvfl);
13490                 sqlite3_free(aOvfl);
13491               }
13492             }
13493 
13494             iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
13495             if( nHdr>nPayload ) nHdr = 0;
13496             pCsr->nHdr = nHdr;
13497             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
13498             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
13499             pCsr->iField = (bHasRowid ? -1 : 0);
13500           }
13501         }
13502       }else{
13503         pCsr->iField++;
13504         if( pCsr->iField>0 ){
13505           sqlite3_int64 iType;
13506           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
13507             bNextPage = 1;
13508           }else{
13509             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
13510             pCsr->pPtr += dbdataValueBytes(iType);
13511           }
13512         }
13513       }
13514 
13515       if( bNextPage ){
13516         sqlite3_free(pCsr->aPage);
13517         sqlite3_free(pCsr->pRec);
13518         pCsr->aPage = 0;
13519         pCsr->pRec = 0;
13520         if( pCsr->bOnePage ) return SQLITE_OK;
13521         pCsr->iPgno++;
13522       }else{
13523         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
13524           return SQLITE_OK;
13525         }
13526 
13527         /* Advance to the next cell. The next iteration of the loop will load
13528         ** the record and so on. */
13529         sqlite3_free(pCsr->pRec);
13530         pCsr->pRec = 0;
13531         pCsr->iCell++;
13532       }
13533     }
13534   }
13535 
13536   assert( !"can't get here" );
13537   return SQLITE_OK;
13538 }
13539 
13540 /*
13541 ** Return true if the cursor is at EOF.
13542 */
13543 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
13544   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13545   return pCsr->aPage==0;
13546 }
13547 
13548 /*
13549 ** Return true if nul-terminated string zSchema ends in "()". Or false
13550 ** otherwise.
13551 */
13552 static int dbdataIsFunction(const char *zSchema){
13553   size_t n = strlen(zSchema);
13554   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
13555     return (int)n-2;
13556   }
13557   return 0;
13558 }
13559 
13560 /*
13561 ** Determine the size in pages of database zSchema (where zSchema is
13562 ** "main", "temp" or the name of an attached database) and set
13563 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
13564 ** an SQLite error code.
13565 */
13566 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
13567   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
13568   char *zSql = 0;
13569   int rc, rc2;
13570   int nFunc = 0;
13571   sqlite3_stmt *pStmt = 0;
13572 
13573   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
13574     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
13575   }else{
13576     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
13577   }
13578   if( zSql==0 ) return SQLITE_NOMEM;
13579 
13580   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
13581   sqlite3_free(zSql);
13582   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
13583     pCsr->szDb = sqlite3_column_int(pStmt, 0);
13584   }
13585   rc2 = sqlite3_finalize(pStmt);
13586   if( rc==SQLITE_OK ) rc = rc2;
13587   return rc;
13588 }
13589 
13590 /*
13591 ** Attempt to figure out the encoding of the database by retrieving page 1
13592 ** and inspecting the header field. If successful, set the pCsr->enc variable
13593 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
13594 */
13595 static int dbdataGetEncoding(DbdataCursor *pCsr){
13596   int rc = SQLITE_OK;
13597   int nPg1 = 0;
13598   u8 *aPg1 = 0;
13599   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
13600   if( rc==SQLITE_OK && nPg1>=(56+4) ){
13601     pCsr->enc = get_uint32(&aPg1[56]);
13602   }
13603   sqlite3_free(aPg1);
13604   return rc;
13605 }
13606 
13607 
13608 /*
13609 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
13610 */
13611 static int dbdataFilter(
13612   sqlite3_vtab_cursor *pCursor,
13613   int idxNum, const char *idxStr,
13614   int argc, sqlite3_value **argv
13615 ){
13616   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13617   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13618   int rc = SQLITE_OK;
13619   const char *zSchema = "main";
13620   (void)idxStr;
13621   (void)argc;
13622 
13623   dbdataResetCursor(pCsr);
13624   assert( pCsr->iPgno==1 );
13625   if( idxNum & 0x01 ){
13626     zSchema = (const char*)sqlite3_value_text(argv[0]);
13627     if( zSchema==0 ) zSchema = "";
13628   }
13629   if( idxNum & 0x02 ){
13630     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
13631     pCsr->bOnePage = 1;
13632   }else{
13633     rc = dbdataDbsize(pCsr, zSchema);
13634   }
13635 
13636   if( rc==SQLITE_OK ){
13637     int nFunc = 0;
13638     if( pTab->pStmt ){
13639       pCsr->pStmt = pTab->pStmt;
13640       pTab->pStmt = 0;
13641     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
13642       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
13643       if( zSql==0 ){
13644         rc = SQLITE_NOMEM;
13645       }else{
13646         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
13647         sqlite3_free(zSql);
13648       }
13649     }else{
13650       rc = sqlite3_prepare_v2(pTab->db,
13651           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
13652           &pCsr->pStmt, 0
13653       );
13654     }
13655   }
13656   if( rc==SQLITE_OK ){
13657     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
13658   }
13659 
13660   /* Try to determine the encoding of the db by inspecting the header
13661   ** field on page 1. */
13662   if( rc==SQLITE_OK ){
13663     rc = dbdataGetEncoding(pCsr);
13664   }
13665 
13666   if( rc!=SQLITE_OK ){
13667     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
13668   }
13669 
13670   if( rc==SQLITE_OK ){
13671     rc = dbdataNext(pCursor);
13672   }
13673   return rc;
13674 }
13675 
13676 /*
13677 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
13678 */
13679 static int dbdataColumn(
13680   sqlite3_vtab_cursor *pCursor,
13681   sqlite3_context *ctx,
13682   int i
13683 ){
13684   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13685   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13686   if( pTab->bPtr ){
13687     switch( i ){
13688       case DBPTR_COLUMN_PGNO:
13689         sqlite3_result_int64(ctx, pCsr->iPgno);
13690         break;
13691       case DBPTR_COLUMN_CHILD: {
13692         int iOff = pCsr->iPgno==1 ? 100 : 0;
13693         if( pCsr->iCell<0 ){
13694           iOff += 8;
13695         }else{
13696           iOff += 12 + pCsr->iCell*2;
13697           if( iOff>pCsr->nPage ) return SQLITE_OK;
13698           iOff = get_uint16(&pCsr->aPage[iOff]);
13699         }
13700         if( iOff<=pCsr->nPage ){
13701           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
13702         }
13703         break;
13704       }
13705     }
13706   }else{
13707     switch( i ){
13708       case DBDATA_COLUMN_PGNO:
13709         sqlite3_result_int64(ctx, pCsr->iPgno);
13710         break;
13711       case DBDATA_COLUMN_CELL:
13712         sqlite3_result_int(ctx, pCsr->iCell);
13713         break;
13714       case DBDATA_COLUMN_FIELD:
13715         sqlite3_result_int(ctx, pCsr->iField);
13716         break;
13717       case DBDATA_COLUMN_VALUE: {
13718         if( pCsr->iField<0 ){
13719           sqlite3_result_int64(ctx, pCsr->iIntkey);
13720         }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
13721           sqlite3_int64 iType;
13722           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
13723           dbdataValue(
13724               ctx, pCsr->enc, iType, pCsr->pPtr,
13725               &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
13726           );
13727         }
13728         break;
13729       }
13730     }
13731   }
13732   return SQLITE_OK;
13733 }
13734 
13735 /*
13736 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
13737 */
13738 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
13739   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13740   *pRowid = pCsr->iRowid;
13741   return SQLITE_OK;
13742 }
13743 
13744 
13745 /*
13746 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
13747 */
13748 static int sqlite3DbdataRegister(sqlite3 *db){
13749   static sqlite3_module dbdata_module = {
13750     0,                            /* iVersion */
13751     0,                            /* xCreate */
13752     dbdataConnect,                /* xConnect */
13753     dbdataBestIndex,              /* xBestIndex */
13754     dbdataDisconnect,             /* xDisconnect */
13755     0,                            /* xDestroy */
13756     dbdataOpen,                   /* xOpen - open a cursor */
13757     dbdataClose,                  /* xClose - close a cursor */
13758     dbdataFilter,                 /* xFilter - configure scan constraints */
13759     dbdataNext,                   /* xNext - advance a cursor */
13760     dbdataEof,                    /* xEof - check for end of scan */
13761     dbdataColumn,                 /* xColumn - read data */
13762     dbdataRowid,                  /* xRowid - read data */
13763     0,                            /* xUpdate */
13764     0,                            /* xBegin */
13765     0,                            /* xSync */
13766     0,                            /* xCommit */
13767     0,                            /* xRollback */
13768     0,                            /* xFindMethod */
13769     0,                            /* xRename */
13770     0,                            /* xSavepoint */
13771     0,                            /* xRelease */
13772     0,                            /* xRollbackTo */
13773     0                             /* xShadowName */
13774   };
13775 
13776   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
13777   if( rc==SQLITE_OK ){
13778     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
13779   }
13780   return rc;
13781 }
13782 
13783 #ifdef _WIN32
13784 
13785 #endif
13786 int sqlite3_dbdata_init(
13787   sqlite3 *db,
13788   char **pzErrMsg,
13789   const sqlite3_api_routines *pApi
13790 ){
13791   SQLITE_EXTENSION_INIT2(pApi);
13792   (void)pzErrMsg;
13793   return sqlite3DbdataRegister(db);
13794 }
13795 
13796 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13797 
13798 /************************* End ../ext/recover/dbdata.c ********************/
13799 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
13800 /*
13801 ** 2022-08-27
13802 **
13803 ** The author disclaims copyright to this source code.  In place of
13804 ** a legal notice, here is a blessing:
13805 **
13806 **    May you do good and not evil.
13807 **    May you find forgiveness for yourself and forgive others.
13808 **    May you share freely, never taking more than you give.
13809 **
13810 *************************************************************************
13811 **
13812 */
13813 
13814 
13815 /* #include "sqlite3recover.h" */
13816 #include <assert.h>
13817 #include <string.h>
13818 
13819 #ifndef SQLITE_OMIT_VIRTUALTABLE
13820 
13821 /*
13822 ** Declaration for public API function in file dbdata.c. This may be called
13823 ** with NULL as the final two arguments to register the sqlite_dbptr and
13824 ** sqlite_dbdata virtual tables with a database handle.
13825 */
13826 #ifdef _WIN32
13827 
13828 #endif
13829 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
13830 
13831 /* typedef unsigned int u32; */
13832 /* typedef unsigned char u8; */
13833 /* typedef sqlite3_int64 i64; */
13834 
13835 typedef struct RecoverTable RecoverTable;
13836 typedef struct RecoverColumn RecoverColumn;
13837 
13838 /*
13839 ** When recovering rows of data that can be associated with table
13840 ** definitions recovered from the sqlite_schema table, each table is
13841 ** represented by an instance of the following object.
13842 **
13843 ** iRoot:
13844 **   The root page in the original database. Not necessarily (and usually
13845 **   not) the same in the recovered database.
13846 **
13847 ** zTab:
13848 **   Name of the table.
13849 **
13850 ** nCol/aCol[]:
13851 **   aCol[] is an array of nCol columns. In the order in which they appear
13852 **   in the table.
13853 **
13854 ** bIntkey:
13855 **   Set to true for intkey tables, false for WITHOUT ROWID.
13856 **
13857 ** iRowidBind:
13858 **   Each column in the aCol[] array has associated with it the index of
13859 **   the bind parameter its values will be bound to in the INSERT statement
13860 **   used to construct the output database. If the table does has a rowid
13861 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
13862 **   index of the bind paramater to which the rowid value should be bound.
13863 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
13864 **   KEY column, then the rowid value should be bound to the index associated
13865 **   with the column.
13866 **
13867 ** pNext:
13868 **   All RecoverTable objects used by the recovery operation are allocated
13869 **   and populated as part of creating the recovered database schema in
13870 **   the output database, before any non-schema data are recovered. They
13871 **   are then stored in a singly-linked list linked by this variable beginning
13872 **   at sqlite3_recover.pTblList.
13873 */
13874 struct RecoverTable {
13875   u32 iRoot;                      /* Root page in original database */
13876   char *zTab;                     /* Name of table */
13877   int nCol;                       /* Number of columns in table */
13878   RecoverColumn *aCol;            /* Array of columns */
13879   int bIntkey;                    /* True for intkey, false for without rowid */
13880   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
13881   RecoverTable *pNext;
13882 };
13883 
13884 /*
13885 ** Each database column is represented by an instance of the following object
13886 ** stored in the RecoverTable.aCol[] array of the associated table.
13887 **
13888 ** iField:
13889 **   The index of the associated field within database records. Or -1 if
13890 **   there is no associated field (e.g. for virtual generated columns).
13891 **
13892 ** iBind:
13893 **   The bind index of the INSERT statement to bind this columns values
13894 **   to. Or 0 if there is no such index (iff (iField<0)).
13895 **
13896 ** bIPK:
13897 **   True if this is the INTEGER PRIMARY KEY column.
13898 **
13899 ** zCol:
13900 **   Name of column.
13901 **
13902 ** eHidden:
13903 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
13904 */
13905 struct RecoverColumn {
13906   int iField;                     /* Field in record on disk */
13907   int iBind;                      /* Binding to use in INSERT */
13908   int bIPK;                       /* True for IPK column */
13909   char *zCol;
13910   int eHidden;
13911 };
13912 
13913 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
13914 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
13915 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
13916 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
13917 
13918 /*
13919 ** Bitmap object used to track pages in the input database. Allocated
13920 ** and manipulated only by the following functions:
13921 **
13922 **     recoverBitmapAlloc()
13923 **     recoverBitmapFree()
13924 **     recoverBitmapSet()
13925 **     recoverBitmapQuery()
13926 **
13927 ** nPg:
13928 **   Largest page number that may be stored in the bitmap. The range
13929 **   of valid keys is 1 to nPg, inclusive.
13930 **
13931 ** aElem[]:
13932 **   Array large enough to contain a bit for each key. For key value
13933 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
13934 **   In other words, the following is true if bit iKey is set, or
13935 **   false if it is clear:
13936 **
13937 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
13938 */
13939 typedef struct RecoverBitmap RecoverBitmap;
13940 struct RecoverBitmap {
13941   i64 nPg;                        /* Size of bitmap */
13942   u32 aElem[1];                   /* Array of 32-bit bitmasks */
13943 };
13944 
13945 /*
13946 ** State variables (part of the sqlite3_recover structure) used while
13947 ** recovering data for tables identified in the recovered schema (state
13948 ** RECOVER_STATE_WRITING).
13949 */
13950 typedef struct RecoverStateW1 RecoverStateW1;
13951 struct RecoverStateW1 {
13952   sqlite3_stmt *pTbls;
13953   sqlite3_stmt *pSel;
13954   sqlite3_stmt *pInsert;
13955   int nInsert;
13956 
13957   RecoverTable *pTab;             /* Table currently being written */
13958   int nMax;                       /* Max column count in any schema table */
13959   sqlite3_value **apVal;          /* Array of nMax values */
13960   int nVal;                       /* Number of valid entries in apVal[] */
13961   int bHaveRowid;
13962   i64 iRowid;
13963   i64 iPrevPage;
13964   int iPrevCell;
13965 };
13966 
13967 /*
13968 ** State variables (part of the sqlite3_recover structure) used while
13969 ** recovering data destined for the lost and found table (states
13970 ** RECOVER_STATE_LOSTANDFOUND[123]).
13971 */
13972 typedef struct RecoverStateLAF RecoverStateLAF;
13973 struct RecoverStateLAF {
13974   RecoverBitmap *pUsed;
13975   i64 nPg;                        /* Size of db in pages */
13976   sqlite3_stmt *pAllAndParent;
13977   sqlite3_stmt *pMapInsert;
13978   sqlite3_stmt *pMaxField;
13979   sqlite3_stmt *pUsedPages;
13980   sqlite3_stmt *pFindRoot;
13981   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
13982   sqlite3_stmt *pAllPage;
13983   sqlite3_stmt *pPageData;
13984   sqlite3_value **apVal;
13985   int nMaxField;
13986 };
13987 
13988 /*
13989 ** Main recover handle structure.
13990 */
13991 struct sqlite3_recover {
13992   /* Copies of sqlite3_recover_init[_sql]() parameters */
13993   sqlite3 *dbIn;                  /* Input database */
13994   char *zDb;                      /* Name of input db ("main" etc.) */
13995   char *zUri;                     /* URI for output database */
13996   void *pSqlCtx;                  /* SQL callback context */
13997   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
13998 
13999   /* Values configured by sqlite3_recover_config() */
14000   char *zStateDb;                 /* State database to use (or NULL) */
14001   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
14002   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
14003   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
14004   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
14005 
14006   int pgsz;
14007   int detected_pgsz;
14008   int nReserve;
14009   u8 *pPage1Disk;
14010   u8 *pPage1Cache;
14011 
14012   /* Error code and error message */
14013   int errCode;                    /* For sqlite3_recover_errcode() */
14014   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
14015 
14016   int eState;
14017   int bCloseTransaction;
14018 
14019   /* Variables used with eState==RECOVER_STATE_WRITING */
14020   RecoverStateW1 w1;
14021 
14022   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
14023   RecoverStateLAF laf;
14024 
14025   /* Fields used within sqlite3_recover_run() */
14026   sqlite3 *dbOut;                 /* Output database */
14027   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
14028   RecoverTable *pTblList;         /* List of tables recovered from schema */
14029 };
14030 
14031 /*
14032 ** The various states in which an sqlite3_recover object may exist:
14033 **
14034 **   RECOVER_STATE_INIT:
14035 **    The object is initially created in this state. sqlite3_recover_step()
14036 **    has yet to be called. This is the only state in which it is permitted
14037 **    to call sqlite3_recover_config().
14038 **
14039 **   RECOVER_STATE_WRITING:
14040 **
14041 **   RECOVER_STATE_LOSTANDFOUND1:
14042 **    State to populate the bitmap of pages used by other tables or the
14043 **    database freelist.
14044 **
14045 **   RECOVER_STATE_LOSTANDFOUND2:
14046 **    Populate the recovery.map table - used to figure out a "root" page
14047 **    for each lost page from in the database from which records are
14048 **    extracted.
14049 **
14050 **   RECOVER_STATE_LOSTANDFOUND3:
14051 **    Populate the lost-and-found table itself.
14052 */
14053 #define RECOVER_STATE_INIT           0
14054 #define RECOVER_STATE_WRITING        1
14055 #define RECOVER_STATE_LOSTANDFOUND1  2
14056 #define RECOVER_STATE_LOSTANDFOUND2  3
14057 #define RECOVER_STATE_LOSTANDFOUND3  4
14058 #define RECOVER_STATE_SCHEMA2        5
14059 #define RECOVER_STATE_DONE           6
14060 
14061 
14062 /*
14063 ** Global variables used by this extension.
14064 */
14065 typedef struct RecoverGlobal RecoverGlobal;
14066 struct RecoverGlobal {
14067   const sqlite3_io_methods *pMethods;
14068   sqlite3_recover *p;
14069 };
14070 static RecoverGlobal recover_g;
14071 
14072 /*
14073 ** Use this static SQLite mutex to protect the globals during the
14074 ** first call to sqlite3_recover_step().
14075 */
14076 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
14077 
14078 
14079 /*
14080 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
14081 */
14082 #define RECOVER_ROWID_DEFAULT 1
14083 
14084 /*
14085 ** Mutex handling:
14086 **
14087 **    recoverEnterMutex()       -   Enter the recovery mutex
14088 **    recoverLeaveMutex()       -   Leave the recovery mutex
14089 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
14090 */
14091 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
14092 # define recoverEnterMutex()
14093 # define recoverLeaveMutex()
14094 #else
14095 static void recoverEnterMutex(void){
14096   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
14097 }
14098 static void recoverLeaveMutex(void){
14099   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
14100 }
14101 #endif
14102 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
14103 static void recoverAssertMutexHeld(void){
14104   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
14105 }
14106 #else
14107 # define recoverAssertMutexHeld()
14108 #endif
14109 
14110 
14111 /*
14112 ** Like strlen(). But handles NULL pointer arguments.
14113 */
14114 static int recoverStrlen(const char *zStr){
14115   if( zStr==0 ) return 0;
14116   return (int)(strlen(zStr)&0x7fffffff);
14117 }
14118 
14119 /*
14120 ** This function is a no-op if the recover handle passed as the first
14121 ** argument already contains an error (if p->errCode!=SQLITE_OK).
14122 **
14123 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
14124 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
14125 ** if an OOM error occurs, NULL is returned and the handle error code
14126 ** (p->errCode) set to SQLITE_NOMEM.
14127 */
14128 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
14129   void *pRet = 0;
14130   assert( nByte>0 );
14131   if( p->errCode==SQLITE_OK ){
14132     pRet = sqlite3_malloc64(nByte);
14133     if( pRet ){
14134       memset(pRet, 0, nByte);
14135     }else{
14136       p->errCode = SQLITE_NOMEM;
14137     }
14138   }
14139   return pRet;
14140 }
14141 
14142 /*
14143 ** Set the error code and error message for the recover handle passed as
14144 ** the first argument. The error code is set to the value of parameter
14145 ** errCode.
14146 **
14147 ** Parameter zFmt must be a printf() style formatting string. The handle
14148 ** error message is set to the result of using any trailing arguments for
14149 ** parameter substitutions in the formatting string.
14150 **
14151 ** For example:
14152 **
14153 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
14154 */
14155 static int recoverError(
14156   sqlite3_recover *p,
14157   int errCode,
14158   const char *zFmt, ...
14159 ){
14160   char *z = 0;
14161   va_list ap;
14162   va_start(ap, zFmt);
14163   if( zFmt ){
14164     z = sqlite3_vmprintf(zFmt, ap);
14165     va_end(ap);
14166   }
14167   sqlite3_free(p->zErrMsg);
14168   p->zErrMsg = z;
14169   p->errCode = errCode;
14170   return errCode;
14171 }
14172 
14173 
14174 /*
14175 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
14176 ** In this case it returns NULL.
14177 **
14178 ** Otherwise, an attempt is made to allocate and return a bitmap object
14179 ** large enough to store a bit for all page numbers between 1 and nPg,
14180 ** inclusive. The bitmap is initially zeroed.
14181 */
14182 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
14183   int nElem = (nPg+1+31) / 32;
14184   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
14185   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
14186 
14187   if( pRet ){
14188     pRet->nPg = nPg;
14189   }
14190   return pRet;
14191 }
14192 
14193 /*
14194 ** Free a bitmap object allocated by recoverBitmapAlloc().
14195 */
14196 static void recoverBitmapFree(RecoverBitmap *pMap){
14197   sqlite3_free(pMap);
14198 }
14199 
14200 /*
14201 ** Set the bit associated with page iPg in bitvec pMap.
14202 */
14203 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
14204   if( iPg<=pMap->nPg ){
14205     int iElem = (iPg / 32);
14206     int iBit = (iPg % 32);
14207     pMap->aElem[iElem] |= (((u32)1) << iBit);
14208   }
14209 }
14210 
14211 /*
14212 ** Query bitmap object pMap for the state of the bit associated with page
14213 ** iPg. Return 1 if it is set, or 0 otherwise.
14214 */
14215 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
14216   int ret = 1;
14217   if( iPg<=pMap->nPg && iPg>0 ){
14218     int iElem = (iPg / 32);
14219     int iBit = (iPg % 32);
14220     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
14221   }
14222   return ret;
14223 }
14224 
14225 /*
14226 ** Set the recover handle error to the error code and message returned by
14227 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
14228 ** handle db.
14229 */
14230 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
14231   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
14232 }
14233 
14234 /*
14235 ** This function is a no-op if recover handle p already contains an error
14236 ** (if p->errCode!=SQLITE_OK).
14237 **
14238 ** Otherwise, it attempts to prepare the SQL statement in zSql against
14239 ** database handle db. If successful, the statement handle is returned.
14240 ** Or, if an error occurs, NULL is returned and an error left in the
14241 ** recover handle.
14242 */
14243 static sqlite3_stmt *recoverPrepare(
14244   sqlite3_recover *p,
14245   sqlite3 *db,
14246   const char *zSql
14247 ){
14248   sqlite3_stmt *pStmt = 0;
14249   if( p->errCode==SQLITE_OK ){
14250     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
14251       recoverDbError(p, db);
14252     }
14253   }
14254   return pStmt;
14255 }
14256 
14257 /*
14258 ** This function is a no-op if recover handle p already contains an error
14259 ** (if p->errCode!=SQLITE_OK).
14260 **
14261 ** Otherwise, argument zFmt is used as a printf() style format string,
14262 ** along with any trailing arguments, to create an SQL statement. This
14263 ** SQL statement is prepared against database handle db and, if successful,
14264 ** the statment handle returned. Or, if an error occurs - either during
14265 ** the printf() formatting or when preparing the resulting SQL - an
14266 ** error code and message are left in the recover handle.
14267 */
14268 static sqlite3_stmt *recoverPreparePrintf(
14269   sqlite3_recover *p,
14270   sqlite3 *db,
14271   const char *zFmt, ...
14272 ){
14273   sqlite3_stmt *pStmt = 0;
14274   if( p->errCode==SQLITE_OK ){
14275     va_list ap;
14276     char *z;
14277     va_start(ap, zFmt);
14278     z = sqlite3_vmprintf(zFmt, ap);
14279     va_end(ap);
14280     if( z==0 ){
14281       p->errCode = SQLITE_NOMEM;
14282     }else{
14283       pStmt = recoverPrepare(p, db, z);
14284       sqlite3_free(z);
14285     }
14286   }
14287   return pStmt;
14288 }
14289 
14290 /*
14291 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
14292 ** indicates that an error occurred, and there is not already an error
14293 ** in the recover handle passed as the first argument, set the error
14294 ** code and error message appropriately.
14295 **
14296 ** This function returns a copy of the statement handle pointer passed
14297 ** as the second argument.
14298 */
14299 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
14300   int rc = sqlite3_reset(pStmt);
14301   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
14302     recoverDbError(p, sqlite3_db_handle(pStmt));
14303   }
14304   return pStmt;
14305 }
14306 
14307 /*
14308 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
14309 ** indicates that an error occurred, and there is not already an error
14310 ** in the recover handle passed as the first argument, set the error
14311 ** code and error message appropriately.
14312 */
14313 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
14314   sqlite3 *db = sqlite3_db_handle(pStmt);
14315   int rc = sqlite3_finalize(pStmt);
14316   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
14317     recoverDbError(p, db);
14318   }
14319 }
14320 
14321 /*
14322 ** This function is a no-op if recover handle p already contains an error
14323 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
14324 ** case.
14325 **
14326 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
14327 ** Or, if an error occurs, leave an error code and message in the recover
14328 ** handle and return a copy of the error code.
14329 */
14330 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
14331   if( p->errCode==SQLITE_OK ){
14332     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
14333     if( rc ){
14334       recoverDbError(p, db);
14335     }
14336   }
14337   return p->errCode;
14338 }
14339 
14340 /*
14341 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
14342 ** error in the recover handle passed as the first argument if an error
14343 ** (e.g. an OOM) occurs.
14344 */
14345 static void recoverBindValue(
14346   sqlite3_recover *p,
14347   sqlite3_stmt *pStmt,
14348   int iBind,
14349   sqlite3_value *pVal
14350 ){
14351   if( p->errCode==SQLITE_OK ){
14352     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
14353     if( rc ) recoverError(p, rc, 0);
14354   }
14355 }
14356 
14357 /*
14358 ** This function is a no-op if recover handle p already contains an error
14359 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
14360 **
14361 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
14362 ** formatting string and the result of using the trailing arguments for
14363 ** parameter substitution with it written into a buffer obtained from
14364 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
14365 ** It is the responsibility of the caller to eventually free the buffer
14366 ** using sqlite3_free().
14367 **
14368 ** Or, if an error occurs, an error code and message is left in the recover
14369 ** handle and NULL returned.
14370 */
14371 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
14372   va_list ap;
14373   char *z;
14374   va_start(ap, zFmt);
14375   z = sqlite3_vmprintf(zFmt, ap);
14376   va_end(ap);
14377   if( p->errCode==SQLITE_OK ){
14378     if( z==0 ) p->errCode = SQLITE_NOMEM;
14379   }else{
14380     sqlite3_free(z);
14381     z = 0;
14382   }
14383   return z;
14384 }
14385 
14386 /*
14387 ** This function is a no-op if recover handle p already contains an error
14388 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
14389 **
14390 ** Otherwise, execute "PRAGMA page_count" against the input database. If
14391 ** successful, return the integer result. Or, if an error occurs, leave an
14392 ** error code and error message in the sqlite3_recover handle and return
14393 ** zero.
14394 */
14395 static i64 recoverPageCount(sqlite3_recover *p){
14396   i64 nPg = 0;
14397   if( p->errCode==SQLITE_OK ){
14398     sqlite3_stmt *pStmt = 0;
14399     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
14400     if( pStmt ){
14401       sqlite3_step(pStmt);
14402       nPg = sqlite3_column_int64(pStmt, 0);
14403     }
14404     recoverFinalize(p, pStmt);
14405   }
14406   return nPg;
14407 }
14408 
14409 /*
14410 ** Implementation of SQL scalar function "read_i32". The first argument to
14411 ** this function must be a blob. The second a non-negative integer. This
14412 ** function reads and returns a 32-bit big-endian integer from byte
14413 ** offset (4*<arg2>) of the blob.
14414 **
14415 **     SELECT read_i32(<blob>, <idx>)
14416 */
14417 static void recoverReadI32(
14418   sqlite3_context *context,
14419   int argc,
14420   sqlite3_value **argv
14421 ){
14422   const unsigned char *pBlob;
14423   int nBlob;
14424   int iInt;
14425 
14426   assert( argc==2 );
14427   nBlob = sqlite3_value_bytes(argv[0]);
14428   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
14429   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
14430 
14431   if( (iInt+1)*4<=nBlob ){
14432     const unsigned char *a = &pBlob[iInt*4];
14433     i64 iVal = ((i64)a[0]<<24)
14434              + ((i64)a[1]<<16)
14435              + ((i64)a[2]<< 8)
14436              + ((i64)a[3]<< 0);
14437     sqlite3_result_int64(context, iVal);
14438   }
14439 }
14440 
14441 /*
14442 ** Implementation of SQL scalar function "page_is_used". This function
14443 ** is used as part of the procedure for locating orphan rows for the
14444 ** lost-and-found table, and it depends on those routines having populated
14445 ** the sqlite3_recover.laf.pUsed variable.
14446 **
14447 ** The only argument to this function is a page-number. It returns true
14448 ** if the page has already been used somehow during data recovery, or false
14449 ** otherwise.
14450 **
14451 **     SELECT page_is_used(<pgno>);
14452 */
14453 static void recoverPageIsUsed(
14454   sqlite3_context *pCtx,
14455   int nArg,
14456   sqlite3_value **apArg
14457 ){
14458   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
14459   i64 pgno = sqlite3_value_int64(apArg[0]);
14460   assert( nArg==1 );
14461   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
14462 }
14463 
14464 /*
14465 ** The implementation of a user-defined SQL function invoked by the
14466 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
14467 ** of the database being recovered.
14468 **
14469 ** This function always takes a single integer argument. If the argument
14470 ** is zero, then the value returned is the number of pages in the db being
14471 ** recovered. If the argument is greater than zero, it is a page number.
14472 ** The value returned in this case is an SQL blob containing the data for
14473 ** the identified page of the db being recovered. e.g.
14474 **
14475 **     SELECT getpage(0);       -- return number of pages in db
14476 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
14477 */
14478 static void recoverGetPage(
14479   sqlite3_context *pCtx,
14480   int nArg,
14481   sqlite3_value **apArg
14482 ){
14483   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
14484   i64 pgno = sqlite3_value_int64(apArg[0]);
14485   sqlite3_stmt *pStmt = 0;
14486 
14487   assert( nArg==1 );
14488   if( pgno==0 ){
14489     i64 nPg = recoverPageCount(p);
14490     sqlite3_result_int64(pCtx, nPg);
14491     return;
14492   }else{
14493     if( p->pGetPage==0 ){
14494       pStmt = p->pGetPage = recoverPreparePrintf(
14495           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
14496       );
14497     }else if( p->errCode==SQLITE_OK ){
14498       pStmt = p->pGetPage;
14499     }
14500 
14501     if( pStmt ){
14502       sqlite3_bind_int64(pStmt, 1, pgno);
14503       if( SQLITE_ROW==sqlite3_step(pStmt) ){
14504         const u8 *aPg;
14505         int nPg;
14506         assert( p->errCode==SQLITE_OK );
14507         aPg = sqlite3_column_blob(pStmt, 0);
14508         nPg = sqlite3_column_bytes(pStmt, 0);
14509         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
14510           aPg = p->pPage1Disk;
14511         }
14512         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
14513       }
14514       recoverReset(p, pStmt);
14515     }
14516   }
14517 
14518   if( p->errCode ){
14519     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
14520     sqlite3_result_error_code(pCtx, p->errCode);
14521   }
14522 }
14523 
14524 /*
14525 ** Find a string that is not found anywhere in z[].  Return a pointer
14526 ** to that string.
14527 **
14528 ** Try to use zA and zB first.  If both of those are already found in z[]
14529 ** then make up some string and store it in the buffer zBuf.
14530 */
14531 static const char *recoverUnusedString(
14532   const char *z,                    /* Result must not appear anywhere in z */
14533   const char *zA, const char *zB,   /* Try these first */
14534   char *zBuf                        /* Space to store a generated string */
14535 ){
14536   unsigned i = 0;
14537   if( strstr(z, zA)==0 ) return zA;
14538   if( strstr(z, zB)==0 ) return zB;
14539   do{
14540     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
14541   }while( strstr(z,zBuf)!=0 );
14542   return zBuf;
14543 }
14544 
14545 /*
14546 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
14547 ** this function is the output of built-in function quote(). If the first
14548 ** character of the input is "'", indicating that the value passed to quote()
14549 ** was a text value, then this function searches the input for "\n" and "\r"
14550 ** characters and adds a wrapper similar to the following:
14551 **
14552 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
14553 **
14554 ** Or, if the first character of the input is not "'", then a copy of the input
14555 ** is returned.
14556 */
14557 static void recoverEscapeCrnl(
14558   sqlite3_context *context,
14559   int argc,
14560   sqlite3_value **argv
14561 ){
14562   const char *zText = (const char*)sqlite3_value_text(argv[0]);
14563   (void)argc;
14564   if( zText && zText[0]=='\'' ){
14565     int nText = sqlite3_value_bytes(argv[0]);
14566     int i;
14567     char zBuf1[20];
14568     char zBuf2[20];
14569     const char *zNL = 0;
14570     const char *zCR = 0;
14571     int nCR = 0;
14572     int nNL = 0;
14573 
14574     for(i=0; zText[i]; i++){
14575       if( zNL==0 && zText[i]=='\n' ){
14576         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
14577         nNL = (int)strlen(zNL);
14578       }
14579       if( zCR==0 && zText[i]=='\r' ){
14580         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
14581         nCR = (int)strlen(zCR);
14582       }
14583     }
14584 
14585     if( zNL || zCR ){
14586       int iOut = 0;
14587       i64 nMax = (nNL > nCR) ? nNL : nCR;
14588       i64 nAlloc = nMax * nText + (nMax+64)*2;
14589       char *zOut = (char*)sqlite3_malloc64(nAlloc);
14590       if( zOut==0 ){
14591         sqlite3_result_error_nomem(context);
14592         return;
14593       }
14594 
14595       if( zNL && zCR ){
14596         memcpy(&zOut[iOut], "replace(replace(", 16);
14597         iOut += 16;
14598       }else{
14599         memcpy(&zOut[iOut], "replace(", 8);
14600         iOut += 8;
14601       }
14602       for(i=0; zText[i]; i++){
14603         if( zText[i]=='\n' ){
14604           memcpy(&zOut[iOut], zNL, nNL);
14605           iOut += nNL;
14606         }else if( zText[i]=='\r' ){
14607           memcpy(&zOut[iOut], zCR, nCR);
14608           iOut += nCR;
14609         }else{
14610           zOut[iOut] = zText[i];
14611           iOut++;
14612         }
14613       }
14614 
14615       if( zNL ){
14616         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14617         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
14618         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
14619       }
14620       if( zCR ){
14621         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14622         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
14623         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
14624       }
14625 
14626       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
14627       sqlite3_free(zOut);
14628       return;
14629     }
14630   }
14631 
14632   sqlite3_result_value(context, argv[0]);
14633 }
14634 
14635 /*
14636 ** This function is a no-op if recover handle p already contains an error
14637 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
14638 ** this case.
14639 **
14640 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
14641 ** parts of the database schema that can be extracted from the input database.
14642 **
14643 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
14644 ** and error message are left in the recover handle and a copy of the
14645 ** error code returned. It is not considered an error if part of all of
14646 ** the database schema cannot be recovered due to corruption.
14647 */
14648 static int recoverCacheSchema(sqlite3_recover *p){
14649   return recoverExec(p, p->dbOut,
14650     "WITH RECURSIVE pages(p) AS ("
14651     "  SELECT 1"
14652     "    UNION"
14653     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
14654     ")"
14655     "INSERT INTO recovery.schema SELECT"
14656     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
14657     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
14658     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
14659     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
14660     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
14661     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
14662     "  SELECT p FROM pages"
14663     ") GROUP BY pgno, cell"
14664   );
14665 }
14666 
14667 /*
14668 ** If this recover handle is not in SQL callback mode (i.e. was not created
14669 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
14670 ** this function is a no-op. Otherwise, issue a callback with SQL statement
14671 ** zSql as the parameter.
14672 **
14673 ** If the callback returns non-zero, set the recover handle error code to
14674 ** the value returned (so that the caller will abandon processing).
14675 */
14676 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
14677   if( p->errCode==SQLITE_OK && p->xSql ){
14678     int res = p->xSql(p->pSqlCtx, zSql);
14679     if( res ){
14680       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
14681     }
14682   }
14683 }
14684 
14685 /*
14686 ** Transfer the following settings from the input database to the output
14687 ** database:
14688 **
14689 **   + page-size,
14690 **   + auto-vacuum settings,
14691 **   + database encoding,
14692 **   + user-version (PRAGMA user_version), and
14693 **   + application-id (PRAGMA application_id), and
14694 */
14695 static void recoverTransferSettings(sqlite3_recover *p){
14696   const char *aPragma[] = {
14697     "encoding",
14698     "page_size",
14699     "auto_vacuum",
14700     "user_version",
14701     "application_id"
14702   };
14703   int ii;
14704 
14705   /* Truncate the output database to 0 pages in size. This is done by
14706   ** opening a new, empty, temp db, then using the backup API to clobber
14707   ** any existing output db with a copy of it. */
14708   if( p->errCode==SQLITE_OK ){
14709     sqlite3 *db2 = 0;
14710     int rc = sqlite3_open("", &db2);
14711     if( rc!=SQLITE_OK ){
14712       recoverDbError(p, db2);
14713       return;
14714     }
14715 
14716     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
14717       const char *zPrag = aPragma[ii];
14718       sqlite3_stmt *p1 = 0;
14719       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
14720       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
14721         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
14722         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
14723         recoverSqlCallback(p, z2);
14724         recoverExec(p, db2, z2);
14725         sqlite3_free(z2);
14726         if( zArg==0 ){
14727           recoverError(p, SQLITE_NOMEM, 0);
14728         }
14729       }
14730       recoverFinalize(p, p1);
14731     }
14732     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
14733 
14734     if( p->errCode==SQLITE_OK ){
14735       sqlite3 *db = p->dbOut;
14736       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
14737       if( pBackup ){
14738         sqlite3_backup_step(pBackup, -1);
14739         p->errCode = sqlite3_backup_finish(pBackup);
14740       }else{
14741         recoverDbError(p, db);
14742       }
14743     }
14744 
14745     sqlite3_close(db2);
14746   }
14747 }
14748 
14749 /*
14750 ** This function is a no-op if recover handle p already contains an error
14751 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
14752 ** this case.
14753 **
14754 ** Otherwise, an attempt is made to open the output database, attach
14755 ** and create the schema of the temporary database used to store
14756 ** intermediate data, and to register all required user functions and
14757 ** virtual table modules with the output handle.
14758 **
14759 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
14760 ** and error message are left in the recover handle and a copy of the
14761 ** error code returned.
14762 */
14763 static int recoverOpenOutput(sqlite3_recover *p){
14764   struct Func {
14765     const char *zName;
14766     int nArg;
14767     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
14768   } aFunc[] = {
14769     { "getpage", 1, recoverGetPage },
14770     { "page_is_used", 1, recoverPageIsUsed },
14771     { "read_i32", 2, recoverReadI32 },
14772     { "escape_crnl", 1, recoverEscapeCrnl },
14773   };
14774 
14775   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
14776   sqlite3 *db = 0;                /* New database handle */
14777   int ii;                         /* For iterating through aFunc[] */
14778 
14779   assert( p->dbOut==0 );
14780 
14781   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
14782     recoverDbError(p, db);
14783   }
14784 
14785   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
14786   ** These two are registered with the output database handle - this
14787   ** module depends on the input handle supporting the sqlite_dbpage
14788   ** virtual table only.  */
14789   if( p->errCode==SQLITE_OK ){
14790     p->errCode = sqlite3_dbdata_init(db, 0, 0);
14791   }
14792 
14793   /* Register the custom user-functions with the output handle. */
14794   for(ii=0;
14795       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
14796       ii++){
14797     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
14798         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
14799     );
14800   }
14801 
14802   p->dbOut = db;
14803   return p->errCode;
14804 }
14805 
14806 /*
14807 ** Attach the auxiliary database 'recovery' to the output database handle.
14808 ** This temporary database is used during the recovery process and then
14809 ** discarded.
14810 */
14811 static void recoverOpenRecovery(sqlite3_recover *p){
14812   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
14813   recoverExec(p, p->dbOut, zSql);
14814   recoverExec(p, p->dbOut,
14815       "PRAGMA writable_schema = 1;"
14816       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
14817       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
14818   );
14819   sqlite3_free(zSql);
14820 }
14821 
14822 
14823 /*
14824 ** This function is a no-op if recover handle p already contains an error
14825 ** (if p->errCode!=SQLITE_OK).
14826 **
14827 ** Otherwise, argument zName must be the name of a table that has just been
14828 ** created in the output database. This function queries the output db
14829 ** for the schema of said table, and creates a RecoverTable object to
14830 ** store the schema in memory. The new RecoverTable object is linked into
14831 ** the list at sqlite3_recover.pTblList.
14832 **
14833 ** Parameter iRoot must be the root page of table zName in the INPUT
14834 ** database.
14835 */
14836 static void recoverAddTable(
14837   sqlite3_recover *p,
14838   const char *zName,              /* Name of table created in output db */
14839   i64 iRoot                       /* Root page of same table in INPUT db */
14840 ){
14841   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
14842       "PRAGMA table_xinfo(%Q)", zName
14843   );
14844 
14845   if( pStmt ){
14846     int iPk = -1;
14847     int iBind = 1;
14848     RecoverTable *pNew = 0;
14849     int nCol = 0;
14850     int nName = recoverStrlen(zName);
14851     int nByte = 0;
14852     while( sqlite3_step(pStmt)==SQLITE_ROW ){
14853       nCol++;
14854       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
14855     }
14856     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
14857     recoverReset(p, pStmt);
14858 
14859     pNew = recoverMalloc(p, nByte);
14860     if( pNew ){
14861       int i = 0;
14862       int iField = 0;
14863       char *csr = 0;
14864       pNew->aCol = (RecoverColumn*)&pNew[1];
14865       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
14866       pNew->nCol = nCol;
14867       pNew->iRoot = iRoot;
14868       memcpy(csr, zName, nName);
14869       csr += nName+1;
14870 
14871       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
14872         int iPKF = sqlite3_column_int(pStmt, 5);
14873         int n = sqlite3_column_bytes(pStmt, 1);
14874         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
14875         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
14876         int eHidden = sqlite3_column_int(pStmt, 6);
14877 
14878         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
14879         if( iPKF>1 ) iPk = -2;
14880         pNew->aCol[i].zCol = csr;
14881         pNew->aCol[i].eHidden = eHidden;
14882         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
14883           pNew->aCol[i].iField = -1;
14884         }else{
14885           pNew->aCol[i].iField = iField++;
14886         }
14887         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
14888          && eHidden!=RECOVER_EHIDDEN_STORED
14889         ){
14890           pNew->aCol[i].iBind = iBind++;
14891         }
14892         memcpy(csr, z, n);
14893         csr += (n+1);
14894       }
14895 
14896       pNew->pNext = p->pTblList;
14897       p->pTblList = pNew;
14898       pNew->bIntkey = 1;
14899     }
14900 
14901     recoverFinalize(p, pStmt);
14902 
14903     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
14904     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
14905       int iField = sqlite3_column_int(pStmt, 0);
14906       int iCol = sqlite3_column_int(pStmt, 1);
14907 
14908       assert( iCol<pNew->nCol );
14909       pNew->aCol[iCol].iField = iField;
14910 
14911       pNew->bIntkey = 0;
14912       iPk = -2;
14913     }
14914     recoverFinalize(p, pStmt);
14915 
14916     if( p->errCode==SQLITE_OK ){
14917       if( iPk>=0 ){
14918         pNew->aCol[iPk].bIPK = 1;
14919       }else if( pNew->bIntkey ){
14920         pNew->iRowidBind = iBind++;
14921       }
14922     }
14923   }
14924 }
14925 
14926 /*
14927 ** This function is called after recoverCacheSchema() has cached those parts
14928 ** of the input database schema that could be recovered in temporary table
14929 ** "recovery.schema". This function creates in the output database copies
14930 ** of all parts of that schema that must be created before the tables can
14931 ** be populated. Specifically, this means:
14932 **
14933 **     * all tables that are not VIRTUAL, and
14934 **     * UNIQUE indexes.
14935 **
14936 ** If the recovery handle uses SQL callbacks, then callbacks containing
14937 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
14938 **
14939 ** Additionally, records are added to the sqlite_schema table of the
14940 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
14941 ** records are written directly to sqlite_schema, not actually executed.
14942 ** If the handle is in SQL callback mode, then callbacks are invoked
14943 ** with equivalent SQL statements.
14944 */
14945 static int recoverWriteSchema1(sqlite3_recover *p){
14946   sqlite3_stmt *pSelect = 0;
14947   sqlite3_stmt *pTblname = 0;
14948 
14949   pSelect = recoverPrepare(p, p->dbOut,
14950       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
14951       "  SELECT rootpage, name, sql, "
14952       "    type='table', "
14953       "    sql LIKE 'create virtual%',"
14954       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
14955       "  FROM recovery.schema"
14956       ")"
14957       "SELECT rootpage, tbl, isVirtual, name, sql"
14958       " FROM dbschema "
14959       "  WHERE tbl OR isIndex"
14960       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
14961   );
14962 
14963   pTblname = recoverPrepare(p, p->dbOut,
14964       "SELECT name FROM sqlite_schema "
14965       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
14966   );
14967 
14968   if( pSelect ){
14969     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
14970     while( sqlite3_step(pSelect)==SQLITE_ROW ){
14971       i64 iRoot = sqlite3_column_int64(pSelect, 0);
14972       int bTable = sqlite3_column_int(pSelect, 1);
14973       int bVirtual = sqlite3_column_int(pSelect, 2);
14974       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
14975       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
14976       char *zFree = 0;
14977       int rc = SQLITE_OK;
14978 
14979       if( bVirtual ){
14980         zSql = (const char*)(zFree = recoverMPrintf(p,
14981             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
14982             zName, zName, zSql
14983         ));
14984       }
14985       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
14986       if( rc==SQLITE_OK ){
14987         recoverSqlCallback(p, zSql);
14988         if( bTable && !bVirtual ){
14989           if( SQLITE_ROW==sqlite3_step(pTblname) ){
14990             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
14991             recoverAddTable(p, zTbl, iRoot);
14992           }
14993           recoverReset(p, pTblname);
14994         }
14995       }else if( rc!=SQLITE_ERROR ){
14996         recoverDbError(p, p->dbOut);
14997       }
14998       sqlite3_free(zFree);
14999     }
15000   }
15001   recoverFinalize(p, pSelect);
15002   recoverFinalize(p, pTblname);
15003 
15004   return p->errCode;
15005 }
15006 
15007 /*
15008 ** This function is called after the output database has been populated. It
15009 ** adds all recovered schema elements that were not created in the output
15010 ** database by recoverWriteSchema1() - everything except for tables and
15011 ** UNIQUE indexes. Specifically:
15012 **
15013 **     * views,
15014 **     * triggers,
15015 **     * non-UNIQUE indexes.
15016 **
15017 ** If the recover handle is in SQL callback mode, then equivalent callbacks
15018 ** are issued to create the schema elements.
15019 */
15020 static int recoverWriteSchema2(sqlite3_recover *p){
15021   sqlite3_stmt *pSelect = 0;
15022 
15023   pSelect = recoverPrepare(p, p->dbOut,
15024       p->bSlowIndexes ?
15025       "SELECT rootpage, sql FROM recovery.schema "
15026       "  WHERE type!='table' AND type!='index'"
15027       :
15028       "SELECT rootpage, sql FROM recovery.schema "
15029       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
15030   );
15031 
15032   if( pSelect ){
15033     while( sqlite3_step(pSelect)==SQLITE_ROW ){
15034       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
15035       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
15036       if( rc==SQLITE_OK ){
15037         recoverSqlCallback(p, zSql);
15038       }else if( rc!=SQLITE_ERROR ){
15039         recoverDbError(p, p->dbOut);
15040       }
15041     }
15042   }
15043   recoverFinalize(p, pSelect);
15044 
15045   return p->errCode;
15046 }
15047 
15048 /*
15049 ** This function is a no-op if recover handle p already contains an error
15050 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
15051 **
15052 ** Otherwise, if the recover handle is configured to create an output
15053 ** database (was created by sqlite3_recover_init()), then this function
15054 ** prepares and returns an SQL statement to INSERT a new record into table
15055 ** pTab, assuming the first nField fields of a record extracted from disk
15056 ** are valid.
15057 **
15058 ** For example, if table pTab is:
15059 **
15060 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
15061 **
15062 ** And nField is 4, then the SQL statement prepared and returned is:
15063 **
15064 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
15065 **
15066 ** In this case even though 4 values were extracted from the input db,
15067 ** only 3 are written to the output, as the generated STORED column
15068 ** cannot be written.
15069 **
15070 ** If the recover handle is in SQL callback mode, then the SQL statement
15071 ** prepared is such that evaluating it returns a single row containing
15072 ** a single text value - itself an SQL statement similar to the above,
15073 ** except with SQL literals in place of the variables. For example:
15074 **
15075 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
15076 **          || quote(?1) || ', '
15077 **          || quote(?2) || ', '
15078 **          || quote(?3) || ')';
15079 **
15080 ** In either case, it is the responsibility of the caller to eventually
15081 ** free the statement handle using sqlite3_finalize().
15082 */
15083 static sqlite3_stmt *recoverInsertStmt(
15084   sqlite3_recover *p,
15085   RecoverTable *pTab,
15086   int nField
15087 ){
15088   sqlite3_stmt *pRet = 0;
15089   const char *zSep = "";
15090   const char *zSqlSep = "";
15091   char *zSql = 0;
15092   char *zFinal = 0;
15093   char *zBind = 0;
15094   int ii;
15095   int bSql = p->xSql ? 1 : 0;
15096 
15097   if( nField<=0 ) return 0;
15098 
15099   assert( nField<=pTab->nCol );
15100 
15101   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
15102 
15103   if( pTab->iRowidBind ){
15104     assert( pTab->bIntkey );
15105     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
15106     if( bSql ){
15107       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
15108     }else{
15109       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
15110     }
15111     zSqlSep = "||', '||";
15112     zSep = ", ";
15113   }
15114 
15115   for(ii=0; ii<nField; ii++){
15116     int eHidden = pTab->aCol[ii].eHidden;
15117     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
15118      && eHidden!=RECOVER_EHIDDEN_STORED
15119     ){
15120       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
15121       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
15122 
15123       if( bSql ){
15124         zBind = recoverMPrintf(p,
15125             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
15126         );
15127         zSqlSep = "||', '||";
15128       }else{
15129         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
15130       }
15131       zSep = ", ";
15132     }
15133   }
15134 
15135   if( bSql ){
15136     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
15137         zSql, zBind
15138     );
15139   }else{
15140     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
15141   }
15142 
15143   pRet = recoverPrepare(p, p->dbOut, zFinal);
15144   sqlite3_free(zSql);
15145   sqlite3_free(zBind);
15146   sqlite3_free(zFinal);
15147 
15148   return pRet;
15149 }
15150 
15151 
15152 /*
15153 ** Search the list of RecoverTable objects at p->pTblList for one that
15154 ** has root page iRoot in the input database. If such an object is found,
15155 ** return a pointer to it. Otherwise, return NULL.
15156 */
15157 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
15158   RecoverTable *pRet = 0;
15159   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
15160   return pRet;
15161 }
15162 
15163 /*
15164 ** This function attempts to create a lost and found table within the
15165 ** output db. If successful, it returns a pointer to a buffer containing
15166 ** the name of the new table. It is the responsibility of the caller to
15167 ** eventually free this buffer using sqlite3_free().
15168 **
15169 ** If an error occurs, NULL is returned and an error code and error
15170 ** message left in the recover handle.
15171 */
15172 static char *recoverLostAndFoundCreate(
15173   sqlite3_recover *p,             /* Recover object */
15174   int nField                      /* Number of column fields in new table */
15175 ){
15176   char *zTbl = 0;
15177   sqlite3_stmt *pProbe = 0;
15178   int ii = 0;
15179 
15180   pProbe = recoverPrepare(p, p->dbOut,
15181     "SELECT 1 FROM sqlite_schema WHERE name=?"
15182   );
15183   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
15184     int bFail = 0;
15185     if( ii<0 ){
15186       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
15187     }else{
15188       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
15189     }
15190 
15191     if( p->errCode==SQLITE_OK ){
15192       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
15193       if( SQLITE_ROW==sqlite3_step(pProbe) ){
15194         bFail = 1;
15195       }
15196       recoverReset(p, pProbe);
15197     }
15198 
15199     if( bFail ){
15200       sqlite3_clear_bindings(pProbe);
15201       sqlite3_free(zTbl);
15202       zTbl = 0;
15203     }
15204   }
15205   recoverFinalize(p, pProbe);
15206 
15207   if( zTbl ){
15208     const char *zSep = 0;
15209     char *zField = 0;
15210     char *zSql = 0;
15211 
15212     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
15213     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
15214       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
15215       zSep = ", ";
15216     }
15217 
15218     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
15219     sqlite3_free(zField);
15220 
15221     recoverExec(p, p->dbOut, zSql);
15222     recoverSqlCallback(p, zSql);
15223     sqlite3_free(zSql);
15224   }else if( p->errCode==SQLITE_OK ){
15225     recoverError(
15226         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
15227     );
15228   }
15229 
15230   return zTbl;
15231 }
15232 
15233 /*
15234 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
15235 ** table in the output database. The name of the table is zTab, and it has
15236 ** nField c* fields.
15237 */
15238 static sqlite3_stmt *recoverLostAndFoundInsert(
15239   sqlite3_recover *p,
15240   const char *zTab,
15241   int nField
15242 ){
15243   int nTotal = nField + 4;
15244   int ii;
15245   char *zBind = 0;
15246   sqlite3_stmt *pRet = 0;
15247 
15248   if( p->xSql==0 ){
15249     for(ii=0; ii<nTotal; ii++){
15250       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
15251     }
15252     pRet = recoverPreparePrintf(
15253         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
15254     );
15255   }else{
15256     const char *zSep = "";
15257     for(ii=0; ii<nTotal; ii++){
15258       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
15259       zSep = "|| ', ' ||";
15260     }
15261     pRet = recoverPreparePrintf(
15262         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
15263     );
15264   }
15265 
15266   sqlite3_free(zBind);
15267   return pRet;
15268 }
15269 
15270 /*
15271 ** Input database page iPg contains data that will be written to the
15272 ** lost-and-found table of the output database. This function attempts
15273 ** to identify the root page of the tree that page iPg belonged to.
15274 ** If successful, it sets output variable (*piRoot) to the page number
15275 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
15276 ** an SQLite error code is returned and the final value of *piRoot
15277 ** undefined.
15278 */
15279 static int recoverLostAndFoundFindRoot(
15280   sqlite3_recover *p,
15281   i64 iPg,
15282   i64 *piRoot
15283 ){
15284   RecoverStateLAF *pLaf = &p->laf;
15285 
15286   if( pLaf->pFindRoot==0 ){
15287     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
15288         "WITH RECURSIVE p(pgno) AS ("
15289         "  SELECT ?"
15290         "    UNION"
15291         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
15292         ") "
15293         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
15294         "    AND m.parent IS NULL"
15295     );
15296   }
15297   if( p->errCode==SQLITE_OK ){
15298     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
15299     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
15300       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
15301     }else{
15302       *piRoot = iPg;
15303     }
15304     recoverReset(p, pLaf->pFindRoot);
15305   }
15306   return p->errCode;
15307 }
15308 
15309 /*
15310 ** Recover data from page iPage of the input database and write it to
15311 ** the lost-and-found table in the output database.
15312 */
15313 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
15314   RecoverStateLAF *pLaf = &p->laf;
15315   sqlite3_value **apVal = pLaf->apVal;
15316   sqlite3_stmt *pPageData = pLaf->pPageData;
15317   sqlite3_stmt *pInsert = pLaf->pInsert;
15318 
15319   int nVal = -1;
15320   int iPrevCell = 0;
15321   i64 iRoot = 0;
15322   int bHaveRowid = 0;
15323   i64 iRowid = 0;
15324   int ii = 0;
15325 
15326   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
15327   sqlite3_bind_int64(pPageData, 1, iPage);
15328   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
15329     int iCell = sqlite3_column_int64(pPageData, 0);
15330     int iField = sqlite3_column_int64(pPageData, 1);
15331 
15332     if( iPrevCell!=iCell && nVal>=0 ){
15333       /* Insert the new row */
15334       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
15335       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
15336       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
15337       if( bHaveRowid ){
15338         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
15339       }
15340       for(ii=0; ii<nVal; ii++){
15341         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
15342       }
15343       if( sqlite3_step(pInsert)==SQLITE_ROW ){
15344         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
15345       }
15346       recoverReset(p, pInsert);
15347 
15348       /* Discard the accumulated row data */
15349       for(ii=0; ii<nVal; ii++){
15350         sqlite3_value_free(apVal[ii]);
15351         apVal[ii] = 0;
15352       }
15353       sqlite3_clear_bindings(pInsert);
15354       bHaveRowid = 0;
15355       nVal = -1;
15356     }
15357 
15358     if( iCell<0 ) break;
15359 
15360     if( iField<0 ){
15361       assert( nVal==-1 );
15362       iRowid = sqlite3_column_int64(pPageData, 2);
15363       bHaveRowid = 1;
15364       nVal = 0;
15365     }else if( iField<pLaf->nMaxField ){
15366       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
15367       apVal[iField] = sqlite3_value_dup(pVal);
15368       assert( iField==nVal || (nVal==-1 && iField==0) );
15369       nVal = iField+1;
15370       if( apVal[iField]==0 ){
15371         recoverError(p, SQLITE_NOMEM, 0);
15372       }
15373     }
15374 
15375     iPrevCell = iCell;
15376   }
15377   recoverReset(p, pPageData);
15378 
15379   for(ii=0; ii<nVal; ii++){
15380     sqlite3_value_free(apVal[ii]);
15381     apVal[ii] = 0;
15382   }
15383 }
15384 
15385 /*
15386 ** Perform one step (sqlite3_recover_step()) of work for the connection
15387 ** passed as the only argument, which is guaranteed to be in
15388 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
15389 ** table of the output database is populated with recovered data that can
15390 ** not be assigned to any recovered schema object.
15391 */
15392 static int recoverLostAndFound3Step(sqlite3_recover *p){
15393   RecoverStateLAF *pLaf = &p->laf;
15394   if( p->errCode==SQLITE_OK ){
15395     if( pLaf->pInsert==0 ){
15396       return SQLITE_DONE;
15397     }else{
15398       if( p->errCode==SQLITE_OK ){
15399         int res = sqlite3_step(pLaf->pAllPage);
15400         if( res==SQLITE_ROW ){
15401           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
15402           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
15403             recoverLostAndFoundOnePage(p, iPage);
15404           }
15405         }else{
15406           recoverReset(p, pLaf->pAllPage);
15407           return SQLITE_DONE;
15408         }
15409       }
15410     }
15411   }
15412   return SQLITE_OK;
15413 }
15414 
15415 /*
15416 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
15417 ** state - during which the lost-and-found table of the output database
15418 ** is populated with recovered data that can not be assigned to any
15419 ** recovered schema object.
15420 */
15421 static void recoverLostAndFound3Init(sqlite3_recover *p){
15422   RecoverStateLAF *pLaf = &p->laf;
15423 
15424   if( pLaf->nMaxField>0 ){
15425     char *zTab = 0;               /* Name of lost_and_found table */
15426 
15427     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
15428     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
15429     sqlite3_free(zTab);
15430 
15431     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
15432         "WITH RECURSIVE seq(ii) AS ("
15433         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
15434         ")"
15435         "SELECT ii FROM seq" , p->laf.nPg
15436     );
15437     pLaf->pPageData = recoverPrepare(p, p->dbOut,
15438         "SELECT cell, field, value "
15439         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
15440         "UNION ALL "
15441         "SELECT -1, -1, -1"
15442     );
15443 
15444     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
15445         pLaf->nMaxField*sizeof(sqlite3_value*)
15446     );
15447   }
15448 }
15449 
15450 /*
15451 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
15452 ** tables recovered from the schema of the input database are populated with
15453 ** recovered data.
15454 */
15455 static int recoverWriteDataInit(sqlite3_recover *p){
15456   RecoverStateW1 *p1 = &p->w1;
15457   RecoverTable *pTbl = 0;
15458   int nByte = 0;
15459 
15460   /* Figure out the maximum number of columns for any table in the schema */
15461   assert( p1->nMax==0 );
15462   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
15463     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
15464   }
15465 
15466   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
15467   ** that will be written to the output database in a single row. */
15468   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
15469   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
15470   if( p1->apVal==0 ) return p->errCode;
15471 
15472   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
15473   ** to loop through cells that appear to belong to a single table (pSel). */
15474   p1->pTbls = recoverPrepare(p, p->dbOut,
15475       "SELECT rootpage FROM recovery.schema "
15476       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
15477       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
15478   );
15479   p1->pSel = recoverPrepare(p, p->dbOut,
15480       "WITH RECURSIVE pages(page) AS ("
15481       "  SELECT ?1"
15482       "    UNION"
15483       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
15484       "    WHERE pgno=page"
15485       ") "
15486       "SELECT page, cell, field, value "
15487       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
15488       "UNION ALL "
15489       "SELECT 0, 0, 0, 0"
15490   );
15491 
15492   return p->errCode;
15493 }
15494 
15495 /*
15496 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
15497 ** sqlite3_recover.w1).
15498 */
15499 static void recoverWriteDataCleanup(sqlite3_recover *p){
15500   RecoverStateW1 *p1 = &p->w1;
15501   int ii;
15502   for(ii=0; ii<p1->nVal; ii++){
15503     sqlite3_value_free(p1->apVal[ii]);
15504   }
15505   sqlite3_free(p1->apVal);
15506   recoverFinalize(p, p1->pInsert);
15507   recoverFinalize(p, p1->pTbls);
15508   recoverFinalize(p, p1->pSel);
15509   memset(p1, 0, sizeof(*p1));
15510 }
15511 
15512 /*
15513 ** Perform one step (sqlite3_recover_step()) of work for the connection
15514 ** passed as the only argument, which is guaranteed to be in
15515 ** RECOVER_STATE_WRITING state - during which tables recovered from the
15516 ** schema of the input database are populated with recovered data.
15517 */
15518 static int recoverWriteDataStep(sqlite3_recover *p){
15519   RecoverStateW1 *p1 = &p->w1;
15520   sqlite3_stmt *pSel = p1->pSel;
15521   sqlite3_value **apVal = p1->apVal;
15522 
15523   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
15524     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
15525       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
15526       p1->pTab = recoverFindTable(p, iRoot);
15527 
15528       recoverFinalize(p, p1->pInsert);
15529       p1->pInsert = 0;
15530 
15531       /* If this table is unknown, return early. The caller will invoke this
15532       ** function again and it will move on to the next table.  */
15533       if( p1->pTab==0 ) return p->errCode;
15534 
15535       /* If this is the sqlite_sequence table, delete any rows added by
15536       ** earlier INSERT statements on tables with AUTOINCREMENT primary
15537       ** keys before recovering its contents. The p1->pTbls SELECT statement
15538       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
15539       ** worry about it being modified after it is recovered. */
15540       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
15541         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
15542         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
15543       }
15544 
15545       /* Bind the root page of this table within the original database to
15546       ** SELECT statement p1->pSel. The SELECT statement will then iterate
15547       ** through cells that look like they belong to table pTab.  */
15548       sqlite3_bind_int64(pSel, 1, iRoot);
15549 
15550       p1->nVal = 0;
15551       p1->bHaveRowid = 0;
15552       p1->iPrevPage = -1;
15553       p1->iPrevCell = -1;
15554     }else{
15555       return SQLITE_DONE;
15556     }
15557   }
15558   assert( p->errCode!=SQLITE_OK || p1->pTab );
15559 
15560   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
15561     RecoverTable *pTab = p1->pTab;
15562 
15563     i64 iPage = sqlite3_column_int64(pSel, 0);
15564     int iCell = sqlite3_column_int(pSel, 1);
15565     int iField = sqlite3_column_int(pSel, 2);
15566     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
15567     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
15568 
15569     assert( bNewCell==0 || (iField==-1 || iField==0) );
15570     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
15571 
15572     if( bNewCell ){
15573       int ii = 0;
15574       if( p1->nVal>=0 ){
15575         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
15576           recoverFinalize(p, p1->pInsert);
15577           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
15578           p1->nInsert = p1->nVal;
15579         }
15580         if( p1->nVal>0 ){
15581           sqlite3_stmt *pInsert = p1->pInsert;
15582           for(ii=0; ii<pTab->nCol; ii++){
15583             RecoverColumn *pCol = &pTab->aCol[ii];
15584             int iBind = pCol->iBind;
15585             if( iBind>0 ){
15586               if( pCol->bIPK ){
15587                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
15588               }else if( pCol->iField<p1->nVal ){
15589                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
15590               }
15591             }
15592           }
15593           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
15594             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
15595           }
15596           if( SQLITE_ROW==sqlite3_step(pInsert) ){
15597             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
15598             recoverSqlCallback(p, z);
15599           }
15600           recoverReset(p, pInsert);
15601           assert( p->errCode || pInsert );
15602           if( pInsert ) sqlite3_clear_bindings(pInsert);
15603         }
15604       }
15605 
15606       for(ii=0; ii<p1->nVal; ii++){
15607         sqlite3_value_free(apVal[ii]);
15608         apVal[ii] = 0;
15609       }
15610       p1->nVal = -1;
15611       p1->bHaveRowid = 0;
15612     }
15613 
15614     if( iPage!=0 ){
15615       if( iField<0 ){
15616         p1->iRowid = sqlite3_column_int64(pSel, 3);
15617         assert( p1->nVal==-1 );
15618         p1->nVal = 0;
15619         p1->bHaveRowid = 1;
15620       }else if( iField<pTab->nCol ){
15621         assert( apVal[iField]==0 );
15622         apVal[iField] = sqlite3_value_dup( pVal );
15623         if( apVal[iField]==0 ){
15624           recoverError(p, SQLITE_NOMEM, 0);
15625         }
15626         p1->nVal = iField+1;
15627       }
15628       p1->iPrevCell = iCell;
15629       p1->iPrevPage = iPage;
15630     }
15631   }else{
15632     recoverReset(p, pSel);
15633     p1->pTab = 0;
15634   }
15635 
15636   return p->errCode;
15637 }
15638 
15639 /*
15640 ** Initialize resources required by sqlite3_recover_step() in
15641 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
15642 ** already allocated to a recovered schema element is determined.
15643 */
15644 static void recoverLostAndFound1Init(sqlite3_recover *p){
15645   RecoverStateLAF *pLaf = &p->laf;
15646   sqlite3_stmt *pStmt = 0;
15647 
15648   assert( p->laf.pUsed==0 );
15649   pLaf->nPg = recoverPageCount(p);
15650   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
15651 
15652   /* Prepare a statement to iterate through all pages that are part of any tree
15653   ** in the recoverable part of the input database schema to the bitmap. And,
15654   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
15655   ** freelist.  */
15656   pStmt = recoverPrepare(
15657       p, p->dbOut,
15658       "WITH trunk(pgno) AS ("
15659       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
15660       "    UNION"
15661       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
15662       "),"
15663       "trunkdata(pgno, data) AS ("
15664       "  SELECT pgno, getpage(pgno) FROM trunk"
15665       "),"
15666       "freelist(data, n, freepgno) AS ("
15667       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
15668       "    UNION ALL"
15669       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
15670       "),"
15671       ""
15672       "roots(r) AS ("
15673       "  SELECT 1 UNION ALL"
15674       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
15675       "),"
15676       "used(page) AS ("
15677       "  SELECT r FROM roots"
15678       "    UNION"
15679       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
15680       "    WHERE pgno=page"
15681       ") "
15682       "SELECT page FROM used"
15683       " UNION ALL "
15684       "SELECT freepgno FROM freelist WHERE NOT ?"
15685   );
15686   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
15687   pLaf->pUsedPages = pStmt;
15688 }
15689 
15690 /*
15691 ** Perform one step (sqlite3_recover_step()) of work for the connection
15692 ** passed as the only argument, which is guaranteed to be in
15693 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
15694 ** already allocated to a recovered schema element is determined.
15695 */
15696 static int recoverLostAndFound1Step(sqlite3_recover *p){
15697   RecoverStateLAF *pLaf = &p->laf;
15698   int rc = p->errCode;
15699   if( rc==SQLITE_OK ){
15700     rc = sqlite3_step(pLaf->pUsedPages);
15701     if( rc==SQLITE_ROW ){
15702       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
15703       recoverBitmapSet(pLaf->pUsed, iPg);
15704       rc = SQLITE_OK;
15705     }else{
15706       recoverFinalize(p, pLaf->pUsedPages);
15707       pLaf->pUsedPages = 0;
15708     }
15709   }
15710   return rc;
15711 }
15712 
15713 /*
15714 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
15715 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
15716 ** are sorted into sets that likely belonged to the same database tree.
15717 */
15718 static void recoverLostAndFound2Init(sqlite3_recover *p){
15719   RecoverStateLAF *pLaf = &p->laf;
15720 
15721   assert( p->laf.pAllAndParent==0 );
15722   assert( p->laf.pMapInsert==0 );
15723   assert( p->laf.pMaxField==0 );
15724   assert( p->laf.nMaxField==0 );
15725 
15726   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
15727       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
15728   );
15729   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
15730       "WITH RECURSIVE seq(ii) AS ("
15731       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
15732       ")"
15733       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
15734       " UNION ALL "
15735       "SELECT NULL, ii FROM seq", p->laf.nPg
15736   );
15737   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
15738       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
15739   );
15740 }
15741 
15742 /*
15743 ** Perform one step (sqlite3_recover_step()) of work for the connection
15744 ** passed as the only argument, which is guaranteed to be in
15745 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
15746 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
15747 ** to the same database tree.
15748 */
15749 static int recoverLostAndFound2Step(sqlite3_recover *p){
15750   RecoverStateLAF *pLaf = &p->laf;
15751   if( p->errCode==SQLITE_OK ){
15752     int res = sqlite3_step(pLaf->pAllAndParent);
15753     if( res==SQLITE_ROW ){
15754       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
15755       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
15756         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
15757         sqlite3_bind_value(pLaf->pMapInsert, 2,
15758             sqlite3_column_value(pLaf->pAllAndParent, 0)
15759         );
15760         sqlite3_step(pLaf->pMapInsert);
15761         recoverReset(p, pLaf->pMapInsert);
15762         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
15763         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
15764           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
15765           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
15766         }
15767         recoverReset(p, pLaf->pMaxField);
15768       }
15769     }else{
15770       recoverFinalize(p, pLaf->pAllAndParent);
15771       pLaf->pAllAndParent =0;
15772       return SQLITE_DONE;
15773     }
15774   }
15775   return p->errCode;
15776 }
15777 
15778 /*
15779 ** Free all resources allocated as part of sqlite3_recover_step() calls
15780 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
15781 */
15782 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
15783   recoverBitmapFree(p->laf.pUsed);
15784   p->laf.pUsed = 0;
15785   sqlite3_finalize(p->laf.pUsedPages);
15786   sqlite3_finalize(p->laf.pAllAndParent);
15787   sqlite3_finalize(p->laf.pMapInsert);
15788   sqlite3_finalize(p->laf.pMaxField);
15789   sqlite3_finalize(p->laf.pFindRoot);
15790   sqlite3_finalize(p->laf.pInsert);
15791   sqlite3_finalize(p->laf.pAllPage);
15792   sqlite3_finalize(p->laf.pPageData);
15793   p->laf.pUsedPages = 0;
15794   p->laf.pAllAndParent = 0;
15795   p->laf.pMapInsert = 0;
15796   p->laf.pMaxField = 0;
15797   p->laf.pFindRoot = 0;
15798   p->laf.pInsert = 0;
15799   p->laf.pAllPage = 0;
15800   p->laf.pPageData = 0;
15801   sqlite3_free(p->laf.apVal);
15802   p->laf.apVal = 0;
15803 }
15804 
15805 /*
15806 ** Free all resources allocated as part of sqlite3_recover_step() calls.
15807 */
15808 static void recoverFinalCleanup(sqlite3_recover *p){
15809   RecoverTable *pTab = 0;
15810   RecoverTable *pNext = 0;
15811 
15812   recoverWriteDataCleanup(p);
15813   recoverLostAndFoundCleanup(p);
15814 
15815   for(pTab=p->pTblList; pTab; pTab=pNext){
15816     pNext = pTab->pNext;
15817     sqlite3_free(pTab);
15818   }
15819   p->pTblList = 0;
15820   sqlite3_finalize(p->pGetPage);
15821   p->pGetPage = 0;
15822   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
15823 
15824   {
15825 #ifndef NDEBUG
15826     int res =
15827 #endif
15828        sqlite3_close(p->dbOut);
15829     assert( res==SQLITE_OK );
15830   }
15831   p->dbOut = 0;
15832 }
15833 
15834 /*
15835 ** Decode and return an unsigned 16-bit big-endian integer value from
15836 ** buffer a[].
15837 */
15838 static u32 recoverGetU16(const u8 *a){
15839   return (((u32)a[0])<<8) + ((u32)a[1]);
15840 }
15841 
15842 /*
15843 ** Decode and return an unsigned 32-bit big-endian integer value from
15844 ** buffer a[].
15845 */
15846 static u32 recoverGetU32(const u8 *a){
15847   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
15848 }
15849 
15850 /*
15851 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
15852 ** and return the number of bytes consumed.
15853 */
15854 static int recoverGetVarint(const u8 *a, i64 *pVal){
15855   sqlite3_uint64 u = 0;
15856   int i;
15857   for(i=0; i<8; i++){
15858     u = (u<<7) + (a[i]&0x7f);
15859     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
15860   }
15861   u = (u<<8) + (a[i]&0xff);
15862   *pVal = (sqlite3_int64)u;
15863   return 9;
15864 }
15865 
15866 /*
15867 ** The second argument points to a buffer n bytes in size. If this buffer
15868 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
15869 ** return the page-size in bytes. Otherwise, if the buffer does not
15870 ** appear to contain a well-formed b-tree page, return 0.
15871 */
15872 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
15873   u8 *aUsed = aTmp;
15874   int nFrag = 0;
15875   int nActual = 0;
15876   int iFree = 0;
15877   int nCell = 0;                  /* Number of cells on page */
15878   int iCellOff = 0;               /* Offset of cell array in page */
15879   int iContent = 0;
15880   int eType = 0;
15881   int ii = 0;
15882 
15883   eType = (int)a[0];
15884   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
15885 
15886   iFree = (int)recoverGetU16(&a[1]);
15887   nCell = (int)recoverGetU16(&a[3]);
15888   iContent = (int)recoverGetU16(&a[5]);
15889   if( iContent==0 ) iContent = 65536;
15890   nFrag = (int)a[7];
15891 
15892   if( iContent>n ) return 0;
15893 
15894   memset(aUsed, 0, n);
15895   memset(aUsed, 0xFF, iContent);
15896 
15897   /* Follow the free-list. This is the same format for all b-tree pages. */
15898   if( iFree && iFree<=iContent ) return 0;
15899   while( iFree ){
15900     int iNext = 0;
15901     int nByte = 0;
15902     if( iFree>(n-4) ) return 0;
15903     iNext = recoverGetU16(&a[iFree]);
15904     nByte = recoverGetU16(&a[iFree+2]);
15905     if( iFree+nByte>n ) return 0;
15906     if( iNext && iNext<iFree+nByte ) return 0;
15907     memset(&aUsed[iFree], 0xFF, nByte);
15908     iFree = iNext;
15909   }
15910 
15911   /* Run through the cells */
15912   if( eType==0x02 || eType==0x05 ){
15913     iCellOff = 12;
15914   }else{
15915     iCellOff = 8;
15916   }
15917   if( (iCellOff + 2*nCell)>iContent ) return 0;
15918   for(ii=0; ii<nCell; ii++){
15919     int iByte;
15920     i64 nPayload = 0;
15921     int nByte = 0;
15922     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
15923     if( iOff<iContent || iOff>n ){
15924       return 0;
15925     }
15926     if( eType==0x05 || eType==0x02 ) nByte += 4;
15927     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
15928     if( eType==0x0D ){
15929       i64 dummy = 0;
15930       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
15931     }
15932     if( eType!=0x05 ){
15933       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
15934       int M = ((n-12)*32/255)-23;
15935       int K = M+((nPayload-M)%(n-4));
15936 
15937       if( nPayload<X ){
15938         nByte += nPayload;
15939       }else if( K<=X ){
15940         nByte += K+4;
15941       }else{
15942         nByte += M+4;
15943       }
15944     }
15945 
15946     if( iOff+nByte>n ){
15947       return 0;
15948     }
15949     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
15950       if( aUsed[iByte]!=0 ){
15951         return 0;
15952       }
15953       aUsed[iByte] = 0xFF;
15954     }
15955   }
15956 
15957   nActual = 0;
15958   for(ii=0; ii<n; ii++){
15959     if( aUsed[ii]==0 ) nActual++;
15960   }
15961   return (nActual==nFrag);
15962 }
15963 
15964 
15965 static int recoverVfsClose(sqlite3_file*);
15966 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
15967 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
15968 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
15969 static int recoverVfsSync(sqlite3_file*, int flags);
15970 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
15971 static int recoverVfsLock(sqlite3_file*, int);
15972 static int recoverVfsUnlock(sqlite3_file*, int);
15973 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
15974 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
15975 static int recoverVfsSectorSize(sqlite3_file*);
15976 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
15977 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
15978 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
15979 static void recoverVfsShmBarrier(sqlite3_file*);
15980 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
15981 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
15982 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
15983 
15984 static sqlite3_io_methods recover_methods = {
15985   2, /* iVersion */
15986   recoverVfsClose,
15987   recoverVfsRead,
15988   recoverVfsWrite,
15989   recoverVfsTruncate,
15990   recoverVfsSync,
15991   recoverVfsFileSize,
15992   recoverVfsLock,
15993   recoverVfsUnlock,
15994   recoverVfsCheckReservedLock,
15995   recoverVfsFileControl,
15996   recoverVfsSectorSize,
15997   recoverVfsDeviceCharacteristics,
15998   recoverVfsShmMap,
15999   recoverVfsShmLock,
16000   recoverVfsShmBarrier,
16001   recoverVfsShmUnmap,
16002   recoverVfsFetch,
16003   recoverVfsUnfetch
16004 };
16005 
16006 static int recoverVfsClose(sqlite3_file *pFd){
16007   assert( pFd->pMethods!=&recover_methods );
16008   return pFd->pMethods->xClose(pFd);
16009 }
16010 
16011 /*
16012 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
16013 */
16014 static void recoverPutU16(u8 *a, u32 v){
16015   a[0] = (v>>8) & 0x00FF;
16016   a[1] = (v>>0) & 0x00FF;
16017 }
16018 
16019 /*
16020 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
16021 */
16022 static void recoverPutU32(u8 *a, u32 v){
16023   a[0] = (v>>24) & 0x00FF;
16024   a[1] = (v>>16) & 0x00FF;
16025   a[2] = (v>>8) & 0x00FF;
16026   a[3] = (v>>0) & 0x00FF;
16027 }
16028 
16029 /*
16030 ** Detect the page-size of the database opened by file-handle pFd by
16031 ** searching the first part of the file for a well-formed SQLite b-tree
16032 ** page. If parameter nReserve is non-zero, then as well as searching for
16033 ** a b-tree page with zero reserved bytes, this function searches for one
16034 ** with nReserve reserved bytes at the end of it.
16035 **
16036 ** If successful, set variable p->detected_pgsz to the detected page-size
16037 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
16038 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
16039 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
16040 ** is returned. The final value of p->detected_pgsz is undefined in this
16041 ** case.
16042 */
16043 static int recoverVfsDetectPagesize(
16044   sqlite3_recover *p,             /* Recover handle */
16045   sqlite3_file *pFd,              /* File-handle open on input database */
16046   u32 nReserve,                   /* Possible nReserve value */
16047   i64 nSz                         /* Size of database file in bytes */
16048 ){
16049   int rc = SQLITE_OK;
16050   const int nMin = 512;
16051   const int nMax = 65536;
16052   const int nMaxBlk = 4;
16053   u32 pgsz = 0;
16054   int iBlk = 0;
16055   u8 *aPg = 0;
16056   u8 *aTmp = 0;
16057   int nBlk = 0;
16058 
16059   aPg = (u8*)sqlite3_malloc(2*nMax);
16060   if( aPg==0 ) return SQLITE_NOMEM;
16061   aTmp = &aPg[nMax];
16062 
16063   nBlk = (nSz+nMax-1)/nMax;
16064   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
16065 
16066   do {
16067     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
16068       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
16069       memset(aPg, 0, nMax);
16070       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
16071       if( rc==SQLITE_OK ){
16072         int pgsz2;
16073         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
16074           int iOff;
16075           for(iOff=0; iOff<nMax; iOff+=pgsz2){
16076             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
16077               pgsz = pgsz2;
16078               break;
16079             }
16080           }
16081         }
16082       }
16083     }
16084     if( pgsz>(u32)p->detected_pgsz ){
16085       p->detected_pgsz = pgsz;
16086       p->nReserve = nReserve;
16087     }
16088     if( nReserve==0 ) break;
16089     nReserve = 0;
16090   }while( 1 );
16091 
16092   p->detected_pgsz = pgsz;
16093   sqlite3_free(aPg);
16094   return rc;
16095 }
16096 
16097 /*
16098 ** The xRead() method of the wrapper VFS. This is used to intercept calls
16099 ** to read page 1 of the input database.
16100 */
16101 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
16102   int rc = SQLITE_OK;
16103   if( pFd->pMethods==&recover_methods ){
16104     pFd->pMethods = recover_g.pMethods;
16105     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
16106     if( nByte==16 ){
16107       sqlite3_randomness(16, aBuf);
16108     }else
16109     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
16110       /* Ensure that the database has a valid header file. The only fields
16111       ** that really matter to recovery are:
16112       **
16113       **   + Database page size (16-bits at offset 16)
16114       **   + Size of db in pages (32-bits at offset 28)
16115       **   + Database encoding (32-bits at offset 56)
16116       **
16117       ** Also preserved are:
16118       **
16119       **   + first freelist page (32-bits at offset 32)
16120       **   + size of freelist (32-bits at offset 36)
16121       **   + the wal-mode flags (16-bits at offset 18)
16122       **
16123       ** We also try to preserve the auto-vacuum, incr-value, user-version
16124       ** and application-id fields - all 32 bit quantities at offsets
16125       ** 52, 60, 64 and 68. All other fields are set to known good values.
16126       **
16127       ** Byte offset 105 should also contain the page-size as a 16-bit
16128       ** integer.
16129       */
16130       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
16131       u8 aHdr[108] = {
16132         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
16133         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
16134         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
16135         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
16136         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
16137         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
16138         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
16139         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
16140         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
16141         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
16142         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
16143         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
16144         0x00, 0x2e, 0x5b, 0x30,
16145 
16146         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
16147       };
16148       u8 *a = (u8*)aBuf;
16149 
16150       u32 pgsz = recoverGetU16(&a[16]);
16151       u32 nReserve = a[20];
16152       u32 enc = recoverGetU32(&a[56]);
16153       u32 dbsz = 0;
16154       i64 dbFileSize = 0;
16155       int ii;
16156       sqlite3_recover *p = recover_g.p;
16157 
16158       if( pgsz==0x01 ) pgsz = 65536;
16159       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
16160 
16161       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
16162         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
16163       }
16164       if( p->detected_pgsz ){
16165         pgsz = p->detected_pgsz;
16166         nReserve = p->nReserve;
16167       }
16168 
16169       if( pgsz ){
16170         dbsz = dbFileSize / pgsz;
16171       }
16172       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
16173         enc = SQLITE_UTF8;
16174       }
16175 
16176       sqlite3_free(p->pPage1Cache);
16177       p->pPage1Cache = 0;
16178       p->pPage1Disk = 0;
16179 
16180       p->pgsz = nByte;
16181       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
16182       if( p->pPage1Cache ){
16183         p->pPage1Disk = &p->pPage1Cache[nByte];
16184         memcpy(p->pPage1Disk, aBuf, nByte);
16185         aHdr[18] = a[18];
16186         aHdr[19] = a[19];
16187         recoverPutU32(&aHdr[28], dbsz);
16188         recoverPutU32(&aHdr[56], enc);
16189         recoverPutU16(&aHdr[105], pgsz-nReserve);
16190         if( pgsz==65536 ) pgsz = 1;
16191         recoverPutU16(&aHdr[16], pgsz);
16192         aHdr[20] = nReserve;
16193         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
16194           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
16195         }
16196         memcpy(aBuf, aHdr, sizeof(aHdr));
16197         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
16198 
16199         memcpy(p->pPage1Cache, aBuf, nByte);
16200       }else{
16201         rc = p->errCode;
16202       }
16203 
16204     }
16205     pFd->pMethods = &recover_methods;
16206   }else{
16207     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
16208   }
16209   return rc;
16210 }
16211 
16212 /*
16213 ** Used to make sqlite3_io_methods wrapper methods less verbose.
16214 */
16215 #define RECOVER_VFS_WRAPPER(code)                         \
16216   int rc = SQLITE_OK;                                     \
16217   if( pFd->pMethods==&recover_methods ){                  \
16218     pFd->pMethods = recover_g.pMethods;                   \
16219     rc = code;                                            \
16220     pFd->pMethods = &recover_methods;                     \
16221   }else{                                                  \
16222     rc = code;                                            \
16223   }                                                       \
16224   return rc;
16225 
16226 /*
16227 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
16228 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
16229 ** method on the lower level VFS, then reinstall the wrapper before returning.
16230 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
16231 */
16232 static int recoverVfsWrite(
16233   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
16234 ){
16235   RECOVER_VFS_WRAPPER (
16236       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
16237   );
16238 }
16239 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
16240   RECOVER_VFS_WRAPPER (
16241       pFd->pMethods->xTruncate(pFd, size)
16242   );
16243 }
16244 static int recoverVfsSync(sqlite3_file *pFd, int flags){
16245   RECOVER_VFS_WRAPPER (
16246       pFd->pMethods->xSync(pFd, flags)
16247   );
16248 }
16249 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
16250   RECOVER_VFS_WRAPPER (
16251       pFd->pMethods->xFileSize(pFd, pSize)
16252   );
16253 }
16254 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
16255   RECOVER_VFS_WRAPPER (
16256       pFd->pMethods->xLock(pFd, eLock)
16257   );
16258 }
16259 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
16260   RECOVER_VFS_WRAPPER (
16261       pFd->pMethods->xUnlock(pFd, eLock)
16262   );
16263 }
16264 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
16265   RECOVER_VFS_WRAPPER (
16266       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
16267   );
16268 }
16269 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
16270   RECOVER_VFS_WRAPPER (
16271     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
16272   );
16273 }
16274 static int recoverVfsSectorSize(sqlite3_file *pFd){
16275   RECOVER_VFS_WRAPPER (
16276       pFd->pMethods->xSectorSize(pFd)
16277   );
16278 }
16279 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
16280   RECOVER_VFS_WRAPPER (
16281       pFd->pMethods->xDeviceCharacteristics(pFd)
16282   );
16283 }
16284 static int recoverVfsShmMap(
16285   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
16286 ){
16287   RECOVER_VFS_WRAPPER (
16288       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
16289   );
16290 }
16291 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
16292   RECOVER_VFS_WRAPPER (
16293       pFd->pMethods->xShmLock(pFd, offset, n, flags)
16294   );
16295 }
16296 static void recoverVfsShmBarrier(sqlite3_file *pFd){
16297   if( pFd->pMethods==&recover_methods ){
16298     pFd->pMethods = recover_g.pMethods;
16299     pFd->pMethods->xShmBarrier(pFd);
16300     pFd->pMethods = &recover_methods;
16301   }else{
16302     pFd->pMethods->xShmBarrier(pFd);
16303   }
16304 }
16305 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
16306   RECOVER_VFS_WRAPPER (
16307       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
16308   );
16309 }
16310 
16311 static int recoverVfsFetch(
16312   sqlite3_file *pFd,
16313   sqlite3_int64 iOff,
16314   int iAmt,
16315   void **pp
16316 ){
16317   (void)pFd;
16318   (void)iOff;
16319   (void)iAmt;
16320   *pp = 0;
16321   return SQLITE_OK;
16322 }
16323 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
16324   (void)pFd;
16325   (void)iOff;
16326   (void)p;
16327   return SQLITE_OK;
16328 }
16329 
16330 /*
16331 ** Install the VFS wrapper around the file-descriptor open on the input
16332 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
16333 ** when this function is called.
16334 */
16335 static void recoverInstallWrapper(sqlite3_recover *p){
16336   sqlite3_file *pFd = 0;
16337   assert( recover_g.pMethods==0 );
16338   recoverAssertMutexHeld();
16339   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
16340   assert( pFd==0 || pFd->pMethods!=&recover_methods );
16341   if( pFd && pFd->pMethods ){
16342     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
16343     recover_g.pMethods = pFd->pMethods;
16344     recover_g.p = p;
16345     recover_methods.iVersion = iVersion;
16346     pFd->pMethods = &recover_methods;
16347   }
16348 }
16349 
16350 /*
16351 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
16352 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
16353 ** held when this function is called.
16354 */
16355 static void recoverUninstallWrapper(sqlite3_recover *p){
16356   sqlite3_file *pFd = 0;
16357   recoverAssertMutexHeld();
16358   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
16359   if( pFd && pFd->pMethods ){
16360     pFd->pMethods = recover_g.pMethods;
16361     recover_g.pMethods = 0;
16362     recover_g.p = 0;
16363   }
16364 }
16365 
16366 /*
16367 ** This function does the work of a single sqlite3_recover_step() call. It
16368 ** is guaranteed that the handle is not in an error state when this
16369 ** function is called.
16370 */
16371 static void recoverStep(sqlite3_recover *p){
16372   assert( p && p->errCode==SQLITE_OK );
16373   switch( p->eState ){
16374     case RECOVER_STATE_INIT:
16375       /* This is the very first call to sqlite3_recover_step() on this object.
16376       */
16377       recoverSqlCallback(p, "BEGIN");
16378       recoverSqlCallback(p, "PRAGMA writable_schema = on");
16379 
16380       recoverEnterMutex();
16381       recoverInstallWrapper(p);
16382 
16383       /* Open the output database. And register required virtual tables and
16384       ** user functions with the new handle. */
16385       recoverOpenOutput(p);
16386 
16387       /* Open transactions on both the input and output databases. */
16388       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
16389       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
16390       recoverExec(p, p->dbIn, "BEGIN");
16391       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
16392       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
16393       recoverTransferSettings(p);
16394       recoverOpenRecovery(p);
16395       recoverCacheSchema(p);
16396 
16397       recoverUninstallWrapper(p);
16398       recoverLeaveMutex();
16399 
16400       recoverExec(p, p->dbOut, "BEGIN");
16401 
16402       recoverWriteSchema1(p);
16403       p->eState = RECOVER_STATE_WRITING;
16404       break;
16405 
16406     case RECOVER_STATE_WRITING: {
16407       if( p->w1.pTbls==0 ){
16408         recoverWriteDataInit(p);
16409       }
16410       if( SQLITE_DONE==recoverWriteDataStep(p) ){
16411         recoverWriteDataCleanup(p);
16412         if( p->zLostAndFound ){
16413           p->eState = RECOVER_STATE_LOSTANDFOUND1;
16414         }else{
16415           p->eState = RECOVER_STATE_SCHEMA2;
16416         }
16417       }
16418       break;
16419     }
16420 
16421     case RECOVER_STATE_LOSTANDFOUND1: {
16422       if( p->laf.pUsed==0 ){
16423         recoverLostAndFound1Init(p);
16424       }
16425       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
16426         p->eState = RECOVER_STATE_LOSTANDFOUND2;
16427       }
16428       break;
16429     }
16430     case RECOVER_STATE_LOSTANDFOUND2: {
16431       if( p->laf.pAllAndParent==0 ){
16432         recoverLostAndFound2Init(p);
16433       }
16434       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
16435         p->eState = RECOVER_STATE_LOSTANDFOUND3;
16436       }
16437       break;
16438     }
16439 
16440     case RECOVER_STATE_LOSTANDFOUND3: {
16441       if( p->laf.pInsert==0 ){
16442         recoverLostAndFound3Init(p);
16443       }
16444       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
16445         p->eState = RECOVER_STATE_SCHEMA2;
16446       }
16447       break;
16448     }
16449 
16450     case RECOVER_STATE_SCHEMA2: {
16451       int rc = SQLITE_OK;
16452 
16453       recoverWriteSchema2(p);
16454       p->eState = RECOVER_STATE_DONE;
16455 
16456       /* If no error has occurred, commit the write transaction on the output
16457       ** database. Regardless of whether or not an error has occurred, make
16458       ** an attempt to end the read transaction on the input database.  */
16459       recoverExec(p, p->dbOut, "COMMIT");
16460       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
16461       if( p->errCode==SQLITE_OK ) p->errCode = rc;
16462 
16463       recoverSqlCallback(p, "PRAGMA writable_schema = off");
16464       recoverSqlCallback(p, "COMMIT");
16465       p->eState = RECOVER_STATE_DONE;
16466       recoverFinalCleanup(p);
16467       break;
16468     };
16469 
16470     case RECOVER_STATE_DONE: {
16471       /* no-op */
16472       break;
16473     };
16474   }
16475 }
16476 
16477 
16478 /*
16479 ** This is a worker function that does the heavy lifting for both init
16480 ** functions:
16481 **
16482 **     sqlite3_recover_init()
16483 **     sqlite3_recover_init_sql()
16484 **
16485 ** All this function does is allocate space for the recover handle and
16486 ** take copies of the input parameters. All the real work is done within
16487 ** sqlite3_recover_run().
16488 */
16489 sqlite3_recover *recoverInit(
16490   sqlite3* db,
16491   const char *zDb,
16492   const char *zUri,               /* Output URI for _recover_init() */
16493   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
16494   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
16495 ){
16496   sqlite3_recover *pRet = 0;
16497   int nDb = 0;
16498   int nUri = 0;
16499   int nByte = 0;
16500 
16501   if( zDb==0 ){ zDb = "main"; }
16502 
16503   nDb = recoverStrlen(zDb);
16504   nUri = recoverStrlen(zUri);
16505 
16506   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
16507   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
16508   if( pRet ){
16509     memset(pRet, 0, nByte);
16510     pRet->dbIn = db;
16511     pRet->zDb = (char*)&pRet[1];
16512     pRet->zUri = &pRet->zDb[nDb+1];
16513     memcpy(pRet->zDb, zDb, nDb);
16514     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
16515     pRet->xSql = xSql;
16516     pRet->pSqlCtx = pSqlCtx;
16517     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
16518   }
16519 
16520   return pRet;
16521 }
16522 
16523 /*
16524 ** Initialize a recovery handle that creates a new database containing
16525 ** the recovered data.
16526 */
16527 sqlite3_recover *sqlite3_recover_init(
16528   sqlite3* db,
16529   const char *zDb,
16530   const char *zUri
16531 ){
16532   return recoverInit(db, zDb, zUri, 0, 0);
16533 }
16534 
16535 /*
16536 ** Initialize a recovery handle that returns recovered data in the
16537 ** form of SQL statements via a callback.
16538 */
16539 sqlite3_recover *sqlite3_recover_init_sql(
16540   sqlite3* db,
16541   const char *zDb,
16542   int (*xSql)(void*, const char*),
16543   void *pSqlCtx
16544 ){
16545   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
16546 }
16547 
16548 /*
16549 ** Return the handle error message, if any.
16550 */
16551 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
16552   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
16553 }
16554 
16555 /*
16556 ** Return the handle error code.
16557 */
16558 int sqlite3_recover_errcode(sqlite3_recover *p){
16559   return p ? p->errCode : SQLITE_NOMEM;
16560 }
16561 
16562 /*
16563 ** Configure the handle.
16564 */
16565 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
16566   int rc = SQLITE_OK;
16567   if( p==0 ){
16568     rc = SQLITE_NOMEM;
16569   }else if( p->eState!=RECOVER_STATE_INIT ){
16570     rc = SQLITE_MISUSE;
16571   }else{
16572     switch( op ){
16573       case 789:
16574         /* This undocumented magic configuration option is used to set the
16575         ** name of the auxiliary database that is ATTACH-ed to the database
16576         ** connection and used to hold state information during the
16577         ** recovery process.  This option is for debugging use only and
16578         ** is subject to change or removal at any time. */
16579         sqlite3_free(p->zStateDb);
16580         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
16581         break;
16582 
16583       case SQLITE_RECOVER_LOST_AND_FOUND: {
16584         const char *zArg = (const char*)pArg;
16585         sqlite3_free(p->zLostAndFound);
16586         if( zArg ){
16587           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
16588         }else{
16589           p->zLostAndFound = 0;
16590         }
16591         break;
16592       }
16593 
16594       case SQLITE_RECOVER_FREELIST_CORRUPT:
16595         p->bFreelistCorrupt = *(int*)pArg;
16596         break;
16597 
16598       case SQLITE_RECOVER_ROWIDS:
16599         p->bRecoverRowid = *(int*)pArg;
16600         break;
16601 
16602       case SQLITE_RECOVER_SLOWINDEXES:
16603         p->bSlowIndexes = *(int*)pArg;
16604         break;
16605 
16606       default:
16607         rc = SQLITE_NOTFOUND;
16608         break;
16609     }
16610   }
16611 
16612   return rc;
16613 }
16614 
16615 /*
16616 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
16617 ** no error has occurred but database recovery is not finished, SQLITE_DONE
16618 ** if database recovery has been successfully completed, or an SQLite
16619 ** error code if an error has occurred.
16620 */
16621 int sqlite3_recover_step(sqlite3_recover *p){
16622   if( p==0 ) return SQLITE_NOMEM;
16623   if( p->errCode==SQLITE_OK ) recoverStep(p);
16624   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
16625     return SQLITE_DONE;
16626   }
16627   return p->errCode;
16628 }
16629 
16630 /*
16631 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
16632 ** else an SQLite error code.
16633 */
16634 int sqlite3_recover_run(sqlite3_recover *p){
16635   while( SQLITE_OK==sqlite3_recover_step(p) );
16636   return sqlite3_recover_errcode(p);
16637 }
16638 
16639 
16640 /*
16641 ** Free all resources associated with the recover handle passed as the only
16642 ** argument. The results of using a handle with any sqlite3_recover_**
16643 ** API function after it has been passed to this function are undefined.
16644 **
16645 ** A copy of the value returned by the first call made to sqlite3_recover_run()
16646 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
16647 ** not been called on this handle.
16648 */
16649 int sqlite3_recover_finish(sqlite3_recover *p){
16650   int rc;
16651   if( p==0 ){
16652     rc = SQLITE_NOMEM;
16653   }else{
16654     recoverFinalCleanup(p);
16655     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
16656       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
16657       if( p->errCode==SQLITE_OK ) p->errCode = rc;
16658     }
16659     rc = p->errCode;
16660     sqlite3_free(p->zErrMsg);
16661     sqlite3_free(p->zStateDb);
16662     sqlite3_free(p->zLostAndFound);
16663     sqlite3_free(p->pPage1Cache);
16664     sqlite3_free(p);
16665   }
16666   return rc;
16667 }
16668 
16669 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
16670 
16671 /************************* End ../ext/recover/sqlite3recover.c ********************/
16672 # endif /* SQLITE_HAVE_SQLITE3R */
16673 #endif
16674 #ifdef SQLITE_SHELL_EXTSRC
16675 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
16676 #endif
16677 
16678 #if defined(SQLITE_ENABLE_SESSION)
16679 /*
16680 ** State information for a single open session
16681 */
16682 typedef struct OpenSession OpenSession;
16683 struct OpenSession {
16684   char *zName;             /* Symbolic name for this session */
16685   int nFilter;             /* Number of xFilter rejection GLOB patterns */
16686   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
16687   sqlite3_session *p;      /* The open session */
16688 };
16689 #endif
16690 
16691 typedef struct ExpertInfo ExpertInfo;
16692 struct ExpertInfo {
16693   sqlite3expert *pExpert;
16694   int bVerbose;
16695 };
16696 
16697 /* A single line in the EQP output */
16698 typedef struct EQPGraphRow EQPGraphRow;
16699 struct EQPGraphRow {
16700   int iEqpId;           /* ID for this row */
16701   int iParentId;        /* ID of the parent row */
16702   EQPGraphRow *pNext;   /* Next row in sequence */
16703   char zText[1];        /* Text to display for this row */
16704 };
16705 
16706 /* All EQP output is collected into an instance of the following */
16707 typedef struct EQPGraph EQPGraph;
16708 struct EQPGraph {
16709   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
16710   EQPGraphRow *pLast;   /* Last element of the pRow list */
16711   char zPrefix[100];    /* Graph prefix */
16712 };
16713 
16714 /* Parameters affecting columnar mode result display (defaulting together) */
16715 typedef struct ColModeOpts {
16716   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
16717   u8 bQuote;            /* Quote results for .mode box and table */
16718   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
16719 } ColModeOpts;
16720 #define ColModeOpts_default { 60, 0, 0 }
16721 #define ColModeOpts_default_qbox { 60, 1, 0 }
16722 
16723 /*
16724 ** State information about the database connection is contained in an
16725 ** instance of the following structure.
16726 */
16727 typedef struct ShellState ShellState;
16728 struct ShellState {
16729   sqlite3 *db;           /* The database */
16730   u8 autoExplain;        /* Automatically turn on .explain mode */
16731   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
16732   u8 autoEQPtest;        /* autoEQP is in test mode */
16733   u8 autoEQPtrace;       /* autoEQP is in trace mode */
16734   u8 scanstatsOn;        /* True to display scan stats before each finalize */
16735   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
16736   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
16737   u8 nEqpLevel;          /* Depth of the EQP output graph */
16738   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
16739   u8 bSafeMode;          /* True to prohibit unsafe operations */
16740   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
16741   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
16742   unsigned statsOn;      /* True to display memory stats before each finalize */
16743   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
16744   int inputNesting;      /* Track nesting level of .read and other redirects */
16745   int outCount;          /* Revert to stdout when reaching zero */
16746   int cnt;               /* Number of records displayed so far */
16747   int lineno;            /* Line number of last line read from in */
16748   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
16749   FILE *in;              /* Read commands from this stream */
16750   FILE *out;             /* Write results here */
16751   FILE *traceOut;        /* Output for sqlite3_trace() */
16752   int nErr;              /* Number of errors seen */
16753   int mode;              /* An output mode setting */
16754   int modePrior;         /* Saved mode */
16755   int cMode;             /* temporary output mode for the current query */
16756   int normalMode;        /* Output mode before ".explain on" */
16757   int writableSchema;    /* True if PRAGMA writable_schema=ON */
16758   int showHeader;        /* True to show column names in List or Column mode */
16759   int nCheck;            /* Number of ".check" commands run */
16760   unsigned nProgress;    /* Number of progress callbacks encountered */
16761   unsigned mxProgress;   /* Maximum progress callbacks before failing */
16762   unsigned flgProgress;  /* Flags for the progress callback */
16763   unsigned shellFlgs;    /* Various flags */
16764   unsigned priorShFlgs;  /* Saved copy of flags */
16765   sqlite3_int64 szMax;   /* --maxsize argument to .open */
16766   char *zDestTable;      /* Name of destination table when MODE_Insert */
16767   char *zTempFile;       /* Temporary file that might need deleting */
16768   char zTestcase[30];    /* Name of current test case */
16769   char colSeparator[20]; /* Column separator character for several modes */
16770   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
16771   char colSepPrior[20];  /* Saved column separator */
16772   char rowSepPrior[20];  /* Saved row separator */
16773   int *colWidth;         /* Requested width of each column in columnar modes */
16774   int *actualWidth;      /* Actual width of each column */
16775   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
16776   char nullValue[20];    /* The text to print when a NULL comes back from
16777                          ** the database */
16778   char outfile[FILENAME_MAX]; /* Filename for *out */
16779   sqlite3_stmt *pStmt;   /* Current statement if any. */
16780   FILE *pLog;            /* Write log output here */
16781   struct AuxDb {         /* Storage space for auxiliary database connections */
16782     sqlite3 *db;               /* Connection pointer */
16783     const char *zDbFilename;   /* Filename used to open the connection */
16784     char *zFreeOnClose;        /* Free this memory allocation on close */
16785 #if defined(SQLITE_ENABLE_SESSION)
16786     int nSession;              /* Number of active sessions */
16787     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
16788 #endif
16789   } aAuxDb[5],           /* Array of all database connections */
16790     *pAuxDb;             /* Currently active database connection */
16791   int *aiIndent;         /* Array of indents used in MODE_Explain */
16792   int nIndent;           /* Size of array aiIndent[] */
16793   int iIndent;           /* Index of current op in aiIndent[] */
16794   char *zNonce;          /* Nonce for temporary safe-mode excapes */
16795   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
16796   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
16797 #ifdef SQLITE_SHELL_FIDDLE
16798   struct {
16799     const char * zInput; /* Input string from wasm/JS proxy */
16800     const char * zPos;   /* Cursor pos into zInput */
16801     const char * zDefaultDbName; /* Default name for db file */
16802   } wasm;
16803 #endif
16804 };
16805 
16806 #ifdef SQLITE_SHELL_FIDDLE
16807 static ShellState shellState;
16808 #endif
16809 
16810 
16811 /* Allowed values for ShellState.autoEQP
16812 */
16813 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
16814 #define AUTOEQP_on       1           /* Automatic EQP is on */
16815 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
16816 #define AUTOEQP_full     3           /* Show full EXPLAIN */
16817 
16818 /* Allowed values for ShellState.openMode
16819 */
16820 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
16821 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
16822 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
16823 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
16824 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
16825 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
16826 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
16827 
16828 /* Allowed values for ShellState.eTraceType
16829 */
16830 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
16831 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
16832 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
16833 
16834 /* Bits in the ShellState.flgProgress variable */
16835 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
16836 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
16837                                    ** callback limit is reached, and for each
16838                                    ** top-level SQL statement */
16839 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
16840 
16841 /*
16842 ** These are the allowed shellFlgs values
16843 */
16844 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
16845 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
16846 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
16847 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
16848 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
16849 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
16850 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
16851 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
16852 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
16853 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
16854 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
16855 
16856 /*
16857 ** Macros for testing and setting shellFlgs
16858 */
16859 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
16860 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
16861 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
16862 
16863 /*
16864 ** These are the allowed modes.
16865 */
16866 #define MODE_Line     0  /* One column per line.  Blank line between records */
16867 #define MODE_Column   1  /* One record per line in neat columns */
16868 #define MODE_List     2  /* One record per line with a separator */
16869 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
16870 #define MODE_Html     4  /* Generate an XHTML table */
16871 #define MODE_Insert   5  /* Generate SQL "insert" statements */
16872 #define MODE_Quote    6  /* Quote values as for SQL */
16873 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
16874 #define MODE_Csv      8  /* Quote strings, numbers are plain */
16875 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
16876 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
16877 #define MODE_Pretty  11  /* Pretty-print schemas */
16878 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
16879 #define MODE_Json    13  /* Output JSON */
16880 #define MODE_Markdown 14 /* Markdown formatting */
16881 #define MODE_Table   15  /* MySQL-style table formatting */
16882 #define MODE_Box     16  /* Unicode box-drawing characters */
16883 #define MODE_Count   17  /* Output only a count of the rows of output */
16884 #define MODE_Off     18  /* No query output shown */
16885 
16886 static const char *modeDescr[] = {
16887   "line",
16888   "column",
16889   "list",
16890   "semi",
16891   "html",
16892   "insert",
16893   "quote",
16894   "tcl",
16895   "csv",
16896   "explain",
16897   "ascii",
16898   "prettyprint",
16899   "eqp",
16900   "json",
16901   "markdown",
16902   "table",
16903   "box",
16904   "count",
16905   "off"
16906 };
16907 
16908 /*
16909 ** These are the column/row/line separators used by the various
16910 ** import/export modes.
16911 */
16912 #define SEP_Column    "|"
16913 #define SEP_Row       "\n"
16914 #define SEP_Tab       "\t"
16915 #define SEP_Space     " "
16916 #define SEP_Comma     ","
16917 #define SEP_CrLf      "\r\n"
16918 #define SEP_Unit      "\x1F"
16919 #define SEP_Record    "\x1E"
16920 
16921 /*
16922 ** Limit input nesting via .read or any other input redirect.
16923 ** It's not too expensive, so a generous allowance can be made.
16924 */
16925 #define MAX_INPUT_NESTING 25
16926 
16927 /*
16928 ** A callback for the sqlite3_log() interface.
16929 */
16930 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
16931   ShellState *p = (ShellState*)pArg;
16932   if( p->pLog==0 ) return;
16933   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
16934   fflush(p->pLog);
16935 }
16936 
16937 /*
16938 ** SQL function:  shell_putsnl(X)
16939 **
16940 ** Write the text X to the screen (or whatever output is being directed)
16941 ** adding a newline at the end, and then return X.
16942 */
16943 static void shellPutsFunc(
16944   sqlite3_context *pCtx,
16945   int nVal,
16946   sqlite3_value **apVal
16947 ){
16948   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
16949   (void)nVal;
16950   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
16951   sqlite3_result_value(pCtx, apVal[0]);
16952 }
16953 
16954 /*
16955 ** If in safe mode, print an error message described by the arguments
16956 ** and exit immediately.
16957 */
16958 static void failIfSafeMode(
16959   ShellState *p,
16960   const char *zErrMsg,
16961   ...
16962 ){
16963   if( p->bSafeMode ){
16964     va_list ap;
16965     char *zMsg;
16966     va_start(ap, zErrMsg);
16967     zMsg = sqlite3_vmprintf(zErrMsg, ap);
16968     va_end(ap);
16969     raw_printf(stderr, "line %d: ", p->lineno);
16970     utf8_printf(stderr, "%s\n", zMsg);
16971     exit(1);
16972   }
16973 }
16974 
16975 /*
16976 ** SQL function:   edit(VALUE)
16977 **                 edit(VALUE,EDITOR)
16978 **
16979 ** These steps:
16980 **
16981 **     (1) Write VALUE into a temporary file.
16982 **     (2) Run program EDITOR on that temporary file.
16983 **     (3) Read the temporary file back and return its content as the result.
16984 **     (4) Delete the temporary file
16985 **
16986 ** If the EDITOR argument is omitted, use the value in the VISUAL
16987 ** environment variable.  If still there is no EDITOR, through an error.
16988 **
16989 ** Also throw an error if the EDITOR program returns a non-zero exit code.
16990 */
16991 #ifndef SQLITE_NOHAVE_SYSTEM
16992 static void editFunc(
16993   sqlite3_context *context,
16994   int argc,
16995   sqlite3_value **argv
16996 ){
16997   const char *zEditor;
16998   char *zTempFile = 0;
16999   sqlite3 *db;
17000   char *zCmd = 0;
17001   int bBin;
17002   int rc;
17003   int hasCRNL = 0;
17004   FILE *f = 0;
17005   sqlite3_int64 sz;
17006   sqlite3_int64 x;
17007   unsigned char *p = 0;
17008 
17009   if( argc==2 ){
17010     zEditor = (const char*)sqlite3_value_text(argv[1]);
17011   }else{
17012     zEditor = getenv("VISUAL");
17013   }
17014   if( zEditor==0 ){
17015     sqlite3_result_error(context, "no editor for edit()", -1);
17016     return;
17017   }
17018   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
17019     sqlite3_result_error(context, "NULL input to edit()", -1);
17020     return;
17021   }
17022   db = sqlite3_context_db_handle(context);
17023   zTempFile = 0;
17024   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
17025   if( zTempFile==0 ){
17026     sqlite3_uint64 r = 0;
17027     sqlite3_randomness(sizeof(r), &r);
17028     zTempFile = sqlite3_mprintf("temp%llx", r);
17029     if( zTempFile==0 ){
17030       sqlite3_result_error_nomem(context);
17031       return;
17032     }
17033   }
17034   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
17035   /* When writing the file to be edited, do \n to \r\n conversions on systems
17036   ** that want \r\n line endings */
17037   f = fopen(zTempFile, bBin ? "wb" : "w");
17038   if( f==0 ){
17039     sqlite3_result_error(context, "edit() cannot open temp file", -1);
17040     goto edit_func_end;
17041   }
17042   sz = sqlite3_value_bytes(argv[0]);
17043   if( bBin ){
17044     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
17045   }else{
17046     const char *z = (const char*)sqlite3_value_text(argv[0]);
17047     /* Remember whether or not the value originally contained \r\n */
17048     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
17049     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
17050   }
17051   fclose(f);
17052   f = 0;
17053   if( x!=sz ){
17054     sqlite3_result_error(context, "edit() could not write the whole file", -1);
17055     goto edit_func_end;
17056   }
17057   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
17058   if( zCmd==0 ){
17059     sqlite3_result_error_nomem(context);
17060     goto edit_func_end;
17061   }
17062   rc = system(zCmd);
17063   sqlite3_free(zCmd);
17064   if( rc ){
17065     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
17066     goto edit_func_end;
17067   }
17068   f = fopen(zTempFile, "rb");
17069   if( f==0 ){
17070     sqlite3_result_error(context,
17071       "edit() cannot reopen temp file after edit", -1);
17072     goto edit_func_end;
17073   }
17074   fseek(f, 0, SEEK_END);
17075   sz = ftell(f);
17076   rewind(f);
17077   p = sqlite3_malloc64( sz+1 );
17078   if( p==0 ){
17079     sqlite3_result_error_nomem(context);
17080     goto edit_func_end;
17081   }
17082   x = fread(p, 1, (size_t)sz, f);
17083   fclose(f);
17084   f = 0;
17085   if( x!=sz ){
17086     sqlite3_result_error(context, "could not read back the whole file", -1);
17087     goto edit_func_end;
17088   }
17089   if( bBin ){
17090     sqlite3_result_blob64(context, p, sz, sqlite3_free);
17091   }else{
17092     sqlite3_int64 i, j;
17093     if( hasCRNL ){
17094       /* If the original contains \r\n then do no conversions back to \n */
17095     }else{
17096       /* If the file did not originally contain \r\n then convert any new
17097       ** \r\n back into \n */
17098       p[sz] = 0;
17099       for(i=j=0; i<sz; i++){
17100         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
17101         p[j++] = p[i];
17102       }
17103       sz = j;
17104       p[sz] = 0;
17105     }
17106     sqlite3_result_text64(context, (const char*)p, sz,
17107                           sqlite3_free, SQLITE_UTF8);
17108   }
17109   p = 0;
17110 
17111 edit_func_end:
17112   if( f ) fclose(f);
17113   unlink(zTempFile);
17114   sqlite3_free(zTempFile);
17115   sqlite3_free(p);
17116 }
17117 #endif /* SQLITE_NOHAVE_SYSTEM */
17118 
17119 /*
17120 ** Save or restore the current output mode
17121 */
17122 static void outputModePush(ShellState *p){
17123   p->modePrior = p->mode;
17124   p->priorShFlgs = p->shellFlgs;
17125   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
17126   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
17127 }
17128 static void outputModePop(ShellState *p){
17129   p->mode = p->modePrior;
17130   p->shellFlgs = p->priorShFlgs;
17131   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
17132   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
17133 }
17134 
17135 /*
17136 ** Output the given string as a hex-encoded blob (eg. X'1234' )
17137 */
17138 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
17139   int i;
17140   unsigned char *aBlob = (unsigned char*)pBlob;
17141 
17142   char *zStr = sqlite3_malloc(nBlob*2 + 1);
17143   shell_check_oom(zStr);
17144 
17145   for(i=0; i<nBlob; i++){
17146     static const char aHex[] = {
17147         '0', '1', '2', '3', '4', '5', '6', '7',
17148         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
17149     };
17150     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
17151     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
17152   }
17153   zStr[i*2] = '\0';
17154 
17155   raw_printf(out,"X'%s'", zStr);
17156   sqlite3_free(zStr);
17157 }
17158 
17159 /*
17160 ** Find a string that is not found anywhere in z[].  Return a pointer
17161 ** to that string.
17162 **
17163 ** Try to use zA and zB first.  If both of those are already found in z[]
17164 ** then make up some string and store it in the buffer zBuf.
17165 */
17166 static const char *unused_string(
17167   const char *z,                    /* Result must not appear anywhere in z */
17168   const char *zA, const char *zB,   /* Try these first */
17169   char *zBuf                        /* Space to store a generated string */
17170 ){
17171   unsigned i = 0;
17172   if( strstr(z, zA)==0 ) return zA;
17173   if( strstr(z, zB)==0 ) return zB;
17174   do{
17175     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
17176   }while( strstr(z,zBuf)!=0 );
17177   return zBuf;
17178 }
17179 
17180 /*
17181 ** Output the given string as a quoted string using SQL quoting conventions.
17182 **
17183 ** See also: output_quoted_escaped_string()
17184 */
17185 static void output_quoted_string(FILE *out, const char *z){
17186   int i;
17187   char c;
17188   setBinaryMode(out, 1);
17189   if( z==0 ) return;
17190   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
17191   if( c==0 ){
17192     utf8_printf(out,"'%s'",z);
17193   }else{
17194     raw_printf(out, "'");
17195     while( *z ){
17196       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
17197       if( c=='\'' ) i++;
17198       if( i ){
17199         utf8_printf(out, "%.*s", i, z);
17200         z += i;
17201       }
17202       if( c=='\'' ){
17203         raw_printf(out, "'");
17204         continue;
17205       }
17206       if( c==0 ){
17207         break;
17208       }
17209       z++;
17210     }
17211     raw_printf(out, "'");
17212   }
17213   setTextMode(out, 1);
17214 }
17215 
17216 /*
17217 ** Output the given string as a quoted string using SQL quoting conventions.
17218 ** Additionallly , escape the "\n" and "\r" characters so that they do not
17219 ** get corrupted by end-of-line translation facilities in some operating
17220 ** systems.
17221 **
17222 ** This is like output_quoted_string() but with the addition of the \r\n
17223 ** escape mechanism.
17224 */
17225 static void output_quoted_escaped_string(FILE *out, const char *z){
17226   int i;
17227   char c;
17228   setBinaryMode(out, 1);
17229   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
17230   if( c==0 ){
17231     utf8_printf(out,"'%s'",z);
17232   }else{
17233     const char *zNL = 0;
17234     const char *zCR = 0;
17235     int nNL = 0;
17236     int nCR = 0;
17237     char zBuf1[20], zBuf2[20];
17238     for(i=0; z[i]; i++){
17239       if( z[i]=='\n' ) nNL++;
17240       if( z[i]=='\r' ) nCR++;
17241     }
17242     if( nNL ){
17243       raw_printf(out, "replace(");
17244       zNL = unused_string(z, "\\n", "\\012", zBuf1);
17245     }
17246     if( nCR ){
17247       raw_printf(out, "replace(");
17248       zCR = unused_string(z, "\\r", "\\015", zBuf2);
17249     }
17250     raw_printf(out, "'");
17251     while( *z ){
17252       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
17253       if( c=='\'' ) i++;
17254       if( i ){
17255         utf8_printf(out, "%.*s", i, z);
17256         z += i;
17257       }
17258       if( c=='\'' ){
17259         raw_printf(out, "'");
17260         continue;
17261       }
17262       if( c==0 ){
17263         break;
17264       }
17265       z++;
17266       if( c=='\n' ){
17267         raw_printf(out, "%s", zNL);
17268         continue;
17269       }
17270       raw_printf(out, "%s", zCR);
17271     }
17272     raw_printf(out, "'");
17273     if( nCR ){
17274       raw_printf(out, ",'%s',char(13))", zCR);
17275     }
17276     if( nNL ){
17277       raw_printf(out, ",'%s',char(10))", zNL);
17278     }
17279   }
17280   setTextMode(out, 1);
17281 }
17282 
17283 /*
17284 ** Output the given string as a quoted according to C or TCL quoting rules.
17285 */
17286 static void output_c_string(FILE *out, const char *z){
17287   unsigned int c;
17288   fputc('"', out);
17289   while( (c = *(z++))!=0 ){
17290     if( c=='\\' ){
17291       fputc(c, out);
17292       fputc(c, out);
17293     }else if( c=='"' ){
17294       fputc('\\', out);
17295       fputc('"', out);
17296     }else if( c=='\t' ){
17297       fputc('\\', out);
17298       fputc('t', out);
17299     }else if( c=='\n' ){
17300       fputc('\\', out);
17301       fputc('n', out);
17302     }else if( c=='\r' ){
17303       fputc('\\', out);
17304       fputc('r', out);
17305     }else if( !isprint(c&0xff) ){
17306       raw_printf(out, "\\%03o", c&0xff);
17307     }else{
17308       fputc(c, out);
17309     }
17310   }
17311   fputc('"', out);
17312 }
17313 
17314 /*
17315 ** Output the given string as a quoted according to JSON quoting rules.
17316 */
17317 static void output_json_string(FILE *out, const char *z, i64 n){
17318   unsigned int c;
17319   if( z==0 ) z = "";
17320   if( n<0 ) n = strlen(z);
17321   fputc('"', out);
17322   while( n-- ){
17323     c = *(z++);
17324     if( c=='\\' || c=='"' ){
17325       fputc('\\', out);
17326       fputc(c, out);
17327     }else if( c<=0x1f ){
17328       fputc('\\', out);
17329       if( c=='\b' ){
17330         fputc('b', out);
17331       }else if( c=='\f' ){
17332         fputc('f', out);
17333       }else if( c=='\n' ){
17334         fputc('n', out);
17335       }else if( c=='\r' ){
17336         fputc('r', out);
17337       }else if( c=='\t' ){
17338         fputc('t', out);
17339       }else{
17340          raw_printf(out, "u%04x",c);
17341       }
17342     }else{
17343       fputc(c, out);
17344     }
17345   }
17346   fputc('"', out);
17347 }
17348 
17349 /*
17350 ** Output the given string with characters that are special to
17351 ** HTML escaped.
17352 */
17353 static void output_html_string(FILE *out, const char *z){
17354   int i;
17355   if( z==0 ) z = "";
17356   while( *z ){
17357     for(i=0;   z[i]
17358             && z[i]!='<'
17359             && z[i]!='&'
17360             && z[i]!='>'
17361             && z[i]!='\"'
17362             && z[i]!='\'';
17363         i++){}
17364     if( i>0 ){
17365       utf8_printf(out,"%.*s",i,z);
17366     }
17367     if( z[i]=='<' ){
17368       raw_printf(out,"&lt;");
17369     }else if( z[i]=='&' ){
17370       raw_printf(out,"&amp;");
17371     }else if( z[i]=='>' ){
17372       raw_printf(out,"&gt;");
17373     }else if( z[i]=='\"' ){
17374       raw_printf(out,"&quot;");
17375     }else if( z[i]=='\'' ){
17376       raw_printf(out,"&#39;");
17377     }else{
17378       break;
17379     }
17380     z += i + 1;
17381   }
17382 }
17383 
17384 /*
17385 ** If a field contains any character identified by a 1 in the following
17386 ** array, then the string must be quoted for CSV.
17387 */
17388 static const char needCsvQuote[] = {
17389   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17390   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17391   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
17392   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17393   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17394   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17395   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17396   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
17397   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17398   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17399   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17400   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17401   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17402   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17403   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17404   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17405 };
17406 
17407 /*
17408 ** Output a single term of CSV.  Actually, p->colSeparator is used for
17409 ** the separator, which may or may not be a comma.  p->nullValue is
17410 ** the null value.  Strings are quoted if necessary.  The separator
17411 ** is only issued if bSep is true.
17412 */
17413 static void output_csv(ShellState *p, const char *z, int bSep){
17414   FILE *out = p->out;
17415   if( z==0 ){
17416     utf8_printf(out,"%s",p->nullValue);
17417   }else{
17418     unsigned i;
17419     for(i=0; z[i]; i++){
17420       if( needCsvQuote[((unsigned char*)z)[i]] ){
17421         i = 0;
17422         break;
17423       }
17424     }
17425     if( i==0 || strstr(z, p->colSeparator)!=0 ){
17426       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
17427       shell_check_oom(zQuoted);
17428       utf8_printf(out, "%s", zQuoted);
17429       sqlite3_free(zQuoted);
17430     }else{
17431       utf8_printf(out, "%s", z);
17432     }
17433   }
17434   if( bSep ){
17435     utf8_printf(p->out, "%s", p->colSeparator);
17436   }
17437 }
17438 
17439 /*
17440 ** This routine runs when the user presses Ctrl-C
17441 */
17442 static void interrupt_handler(int NotUsed){
17443   UNUSED_PARAMETER(NotUsed);
17444   if( ++seenInterrupt>1 ) exit(1);
17445   if( globalDb ) sqlite3_interrupt(globalDb);
17446 }
17447 
17448 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
17449 /*
17450 ** This routine runs for console events (e.g. Ctrl-C) on Win32
17451 */
17452 static BOOL WINAPI ConsoleCtrlHandler(
17453   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
17454 ){
17455   if( dwCtrlType==CTRL_C_EVENT ){
17456     interrupt_handler(0);
17457     return TRUE;
17458   }
17459   return FALSE;
17460 }
17461 #endif
17462 
17463 #ifndef SQLITE_OMIT_AUTHORIZATION
17464 /*
17465 ** This authorizer runs in safe mode.
17466 */
17467 static int safeModeAuth(
17468   void *pClientData,
17469   int op,
17470   const char *zA1,
17471   const char *zA2,
17472   const char *zA3,
17473   const char *zA4
17474 ){
17475   ShellState *p = (ShellState*)pClientData;
17476   static const char *azProhibitedFunctions[] = {
17477     "edit",
17478     "fts3_tokenizer",
17479     "load_extension",
17480     "readfile",
17481     "writefile",
17482     "zipfile",
17483     "zipfile_cds",
17484   };
17485   UNUSED_PARAMETER(zA1);
17486   UNUSED_PARAMETER(zA3);
17487   UNUSED_PARAMETER(zA4);
17488   switch( op ){
17489     case SQLITE_ATTACH: {
17490 #ifndef SQLITE_SHELL_FIDDLE
17491       /* In WASM builds the filesystem is a virtual sandbox, so
17492       ** there's no harm in using ATTACH. */
17493       failIfSafeMode(p, "cannot run ATTACH in safe mode");
17494 #endif
17495       break;
17496     }
17497     case SQLITE_FUNCTION: {
17498       int i;
17499       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
17500         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
17501           failIfSafeMode(p, "cannot use the %s() function in safe mode",
17502                          azProhibitedFunctions[i]);
17503         }
17504       }
17505       break;
17506     }
17507   }
17508   return SQLITE_OK;
17509 }
17510 
17511 /*
17512 ** When the ".auth ON" is set, the following authorizer callback is
17513 ** invoked.  It always returns SQLITE_OK.
17514 */
17515 static int shellAuth(
17516   void *pClientData,
17517   int op,
17518   const char *zA1,
17519   const char *zA2,
17520   const char *zA3,
17521   const char *zA4
17522 ){
17523   ShellState *p = (ShellState*)pClientData;
17524   static const char *azAction[] = { 0,
17525      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
17526      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
17527      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
17528      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
17529      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
17530      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
17531      "PRAGMA",               "READ",                 "SELECT",
17532      "TRANSACTION",          "UPDATE",               "ATTACH",
17533      "DETACH",               "ALTER_TABLE",          "REINDEX",
17534      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
17535      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
17536   };
17537   int i;
17538   const char *az[4];
17539   az[0] = zA1;
17540   az[1] = zA2;
17541   az[2] = zA3;
17542   az[3] = zA4;
17543   utf8_printf(p->out, "authorizer: %s", azAction[op]);
17544   for(i=0; i<4; i++){
17545     raw_printf(p->out, " ");
17546     if( az[i] ){
17547       output_c_string(p->out, az[i]);
17548     }else{
17549       raw_printf(p->out, "NULL");
17550     }
17551   }
17552   raw_printf(p->out, "\n");
17553   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
17554   return SQLITE_OK;
17555 }
17556 #endif
17557 
17558 /*
17559 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
17560 **
17561 ** This routine converts some CREATE TABLE statements for shadow tables
17562 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
17563 **
17564 ** If the schema statement in z[] contains a start-of-comment and if
17565 ** sqlite3_complete() returns false, try to terminate the comment before
17566 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
17567 */
17568 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
17569   char *zToFree = 0;
17570   if( z==0 ) return;
17571   if( zTail==0 ) return;
17572   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
17573     const char *zOrig = z;
17574     static const char *azTerm[] = { "", "*/", "\n" };
17575     int i;
17576     for(i=0; i<ArraySize(azTerm); i++){
17577       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
17578       shell_check_oom(zNew);
17579       if( sqlite3_complete(zNew) ){
17580         size_t n = strlen(zNew);
17581         zNew[n-1] = 0;
17582         zToFree = zNew;
17583         z = zNew;
17584         break;
17585       }
17586       sqlite3_free(zNew);
17587     }
17588   }
17589   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
17590     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
17591   }else{
17592     utf8_printf(out, "%s%s", z, zTail);
17593   }
17594   sqlite3_free(zToFree);
17595 }
17596 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
17597   char c = z[n];
17598   z[n] = 0;
17599   printSchemaLine(out, z, zTail);
17600   z[n] = c;
17601 }
17602 
17603 /*
17604 ** Return true if string z[] has nothing but whitespace and comments to the
17605 ** end of the first line.
17606 */
17607 static int wsToEol(const char *z){
17608   int i;
17609   for(i=0; z[i]; i++){
17610     if( z[i]=='\n' ) return 1;
17611     if( IsSpace(z[i]) ) continue;
17612     if( z[i]=='-' && z[i+1]=='-' ) return 1;
17613     return 0;
17614   }
17615   return 1;
17616 }
17617 
17618 /*
17619 ** Add a new entry to the EXPLAIN QUERY PLAN data
17620 */
17621 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
17622   EQPGraphRow *pNew;
17623   i64 nText;
17624   if( zText==0 ) return;
17625   nText = strlen(zText);
17626   if( p->autoEQPtest ){
17627     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
17628   }
17629   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
17630   shell_check_oom(pNew);
17631   pNew->iEqpId = iEqpId;
17632   pNew->iParentId = p2;
17633   memcpy(pNew->zText, zText, nText+1);
17634   pNew->pNext = 0;
17635   if( p->sGraph.pLast ){
17636     p->sGraph.pLast->pNext = pNew;
17637   }else{
17638     p->sGraph.pRow = pNew;
17639   }
17640   p->sGraph.pLast = pNew;
17641 }
17642 
17643 /*
17644 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
17645 ** in p->sGraph.
17646 */
17647 static void eqp_reset(ShellState *p){
17648   EQPGraphRow *pRow, *pNext;
17649   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
17650     pNext = pRow->pNext;
17651     sqlite3_free(pRow);
17652   }
17653   memset(&p->sGraph, 0, sizeof(p->sGraph));
17654 }
17655 
17656 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
17657 ** pOld, or return the first such line if pOld is NULL
17658 */
17659 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
17660   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
17661   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
17662   return pRow;
17663 }
17664 
17665 /* Render a single level of the graph that has iEqpId as its parent.  Called
17666 ** recursively to render sublevels.
17667 */
17668 static void eqp_render_level(ShellState *p, int iEqpId){
17669   EQPGraphRow *pRow, *pNext;
17670   i64 n = strlen(p->sGraph.zPrefix);
17671   char *z;
17672   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
17673     pNext = eqp_next_row(p, iEqpId, pRow);
17674     z = pRow->zText;
17675     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
17676                 pNext ? "|--" : "`--", z);
17677     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
17678       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
17679       eqp_render_level(p, pRow->iEqpId);
17680       p->sGraph.zPrefix[n] = 0;
17681     }
17682   }
17683 }
17684 
17685 /*
17686 ** Display and reset the EXPLAIN QUERY PLAN data
17687 */
17688 static void eqp_render(ShellState *p, i64 nCycle){
17689   EQPGraphRow *pRow = p->sGraph.pRow;
17690   if( pRow ){
17691     if( pRow->zText[0]=='-' ){
17692       if( pRow->pNext==0 ){
17693         eqp_reset(p);
17694         return;
17695       }
17696       utf8_printf(p->out, "%s\n", pRow->zText+3);
17697       p->sGraph.pRow = pRow->pNext;
17698       sqlite3_free(pRow);
17699     }else if( nCycle>0 ){
17700       utf8_printf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
17701     }else{
17702       utf8_printf(p->out, "QUERY PLAN\n");
17703     }
17704     p->sGraph.zPrefix[0] = 0;
17705     eqp_render_level(p, 0);
17706     eqp_reset(p);
17707   }
17708 }
17709 
17710 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
17711 /*
17712 ** Progress handler callback.
17713 */
17714 static int progress_handler(void *pClientData) {
17715   ShellState *p = (ShellState*)pClientData;
17716   p->nProgress++;
17717   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
17718     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
17719     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
17720     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
17721     return 1;
17722   }
17723   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
17724     raw_printf(p->out, "Progress %u\n", p->nProgress);
17725   }
17726   return 0;
17727 }
17728 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
17729 
17730 /*
17731 ** Print N dashes
17732 */
17733 static void print_dashes(FILE *out, int N){
17734   const char zDash[] = "--------------------------------------------------";
17735   const int nDash = sizeof(zDash) - 1;
17736   while( N>nDash ){
17737     fputs(zDash, out);
17738     N -= nDash;
17739   }
17740   raw_printf(out, "%.*s", N, zDash);
17741 }
17742 
17743 /*
17744 ** Print a markdown or table-style row separator using ascii-art
17745 */
17746 static void print_row_separator(
17747   ShellState *p,
17748   int nArg,
17749   const char *zSep
17750 ){
17751   int i;
17752   if( nArg>0 ){
17753     fputs(zSep, p->out);
17754     print_dashes(p->out, p->actualWidth[0]+2);
17755     for(i=1; i<nArg; i++){
17756       fputs(zSep, p->out);
17757       print_dashes(p->out, p->actualWidth[i]+2);
17758     }
17759     fputs(zSep, p->out);
17760   }
17761   fputs("\n", p->out);
17762 }
17763 
17764 /*
17765 ** This is the callback routine that the shell
17766 ** invokes for each row of a query result.
17767 */
17768 static int shell_callback(
17769   void *pArg,
17770   int nArg,        /* Number of result columns */
17771   char **azArg,    /* Text of each result column */
17772   char **azCol,    /* Column names */
17773   int *aiType      /* Column types.  Might be NULL */
17774 ){
17775   int i;
17776   ShellState *p = (ShellState*)pArg;
17777 
17778   if( azArg==0 ) return 0;
17779   switch( p->cMode ){
17780     case MODE_Count:
17781     case MODE_Off: {
17782       break;
17783     }
17784     case MODE_Line: {
17785       int w = 5;
17786       if( azArg==0 ) break;
17787       for(i=0; i<nArg; i++){
17788         int len = strlen30(azCol[i] ? azCol[i] : "");
17789         if( len>w ) w = len;
17790       }
17791       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
17792       for(i=0; i<nArg; i++){
17793         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
17794                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
17795       }
17796       break;
17797     }
17798     case MODE_Explain: {
17799       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
17800       if( nArg>ArraySize(aExplainWidth) ){
17801         nArg = ArraySize(aExplainWidth);
17802       }
17803       if( p->cnt++==0 ){
17804         for(i=0; i<nArg; i++){
17805           int w = aExplainWidth[i];
17806           utf8_width_print(p->out, w, azCol[i]);
17807           fputs(i==nArg-1 ? "\n" : "  ", p->out);
17808         }
17809         for(i=0; i<nArg; i++){
17810           int w = aExplainWidth[i];
17811           print_dashes(p->out, w);
17812           fputs(i==nArg-1 ? "\n" : "  ", p->out);
17813         }
17814       }
17815       if( azArg==0 ) break;
17816       for(i=0; i<nArg; i++){
17817         int w = aExplainWidth[i];
17818         if( i==nArg-1 ) w = 0;
17819         if( azArg[i] && strlenChar(azArg[i])>w ){
17820           w = strlenChar(azArg[i]);
17821         }
17822         if( i==1 && p->aiIndent && p->pStmt ){
17823           if( p->iIndent<p->nIndent ){
17824             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
17825           }
17826           p->iIndent++;
17827         }
17828         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
17829         fputs(i==nArg-1 ? "\n" : "  ", p->out);
17830       }
17831       break;
17832     }
17833     case MODE_Semi: {   /* .schema and .fullschema output */
17834       printSchemaLine(p->out, azArg[0], ";\n");
17835       break;
17836     }
17837     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
17838       char *z;
17839       int j;
17840       int nParen = 0;
17841       char cEnd = 0;
17842       char c;
17843       int nLine = 0;
17844       assert( nArg==1 );
17845       if( azArg[0]==0 ) break;
17846       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
17847        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
17848       ){
17849         utf8_printf(p->out, "%s;\n", azArg[0]);
17850         break;
17851       }
17852       z = sqlite3_mprintf("%s", azArg[0]);
17853       shell_check_oom(z);
17854       j = 0;
17855       for(i=0; IsSpace(z[i]); i++){}
17856       for(; (c = z[i])!=0; i++){
17857         if( IsSpace(c) ){
17858           if( z[j-1]=='\r' ) z[j-1] = '\n';
17859           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
17860         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
17861           j--;
17862         }
17863         z[j++] = c;
17864       }
17865       while( j>0 && IsSpace(z[j-1]) ){ j--; }
17866       z[j] = 0;
17867       if( strlen30(z)>=79 ){
17868         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
17869           if( c==cEnd ){
17870             cEnd = 0;
17871           }else if( c=='"' || c=='\'' || c=='`' ){
17872             cEnd = c;
17873           }else if( c=='[' ){
17874             cEnd = ']';
17875           }else if( c=='-' && z[i+1]=='-' ){
17876             cEnd = '\n';
17877           }else if( c=='(' ){
17878             nParen++;
17879           }else if( c==')' ){
17880             nParen--;
17881             if( nLine>0 && nParen==0 && j>0 ){
17882               printSchemaLineN(p->out, z, j, "\n");
17883               j = 0;
17884             }
17885           }
17886           z[j++] = c;
17887           if( nParen==1 && cEnd==0
17888            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
17889           ){
17890             if( c=='\n' ) j--;
17891             printSchemaLineN(p->out, z, j, "\n  ");
17892             j = 0;
17893             nLine++;
17894             while( IsSpace(z[i+1]) ){ i++; }
17895           }
17896         }
17897         z[j] = 0;
17898       }
17899       printSchemaLine(p->out, z, ";\n");
17900       sqlite3_free(z);
17901       break;
17902     }
17903     case MODE_List: {
17904       if( p->cnt++==0 && p->showHeader ){
17905         for(i=0; i<nArg; i++){
17906           utf8_printf(p->out,"%s%s",azCol[i],
17907                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
17908         }
17909       }
17910       if( azArg==0 ) break;
17911       for(i=0; i<nArg; i++){
17912         char *z = azArg[i];
17913         if( z==0 ) z = p->nullValue;
17914         utf8_printf(p->out, "%s", z);
17915         if( i<nArg-1 ){
17916           utf8_printf(p->out, "%s", p->colSeparator);
17917         }else{
17918           utf8_printf(p->out, "%s", p->rowSeparator);
17919         }
17920       }
17921       break;
17922     }
17923     case MODE_Html: {
17924       if( p->cnt++==0 && p->showHeader ){
17925         raw_printf(p->out,"<TR>");
17926         for(i=0; i<nArg; i++){
17927           raw_printf(p->out,"<TH>");
17928           output_html_string(p->out, azCol[i]);
17929           raw_printf(p->out,"</TH>\n");
17930         }
17931         raw_printf(p->out,"</TR>\n");
17932       }
17933       if( azArg==0 ) break;
17934       raw_printf(p->out,"<TR>");
17935       for(i=0; i<nArg; i++){
17936         raw_printf(p->out,"<TD>");
17937         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
17938         raw_printf(p->out,"</TD>\n");
17939       }
17940       raw_printf(p->out,"</TR>\n");
17941       break;
17942     }
17943     case MODE_Tcl: {
17944       if( p->cnt++==0 && p->showHeader ){
17945         for(i=0; i<nArg; i++){
17946           output_c_string(p->out,azCol[i] ? azCol[i] : "");
17947           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
17948         }
17949         utf8_printf(p->out, "%s", p->rowSeparator);
17950       }
17951       if( azArg==0 ) break;
17952       for(i=0; i<nArg; i++){
17953         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
17954         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
17955       }
17956       utf8_printf(p->out, "%s", p->rowSeparator);
17957       break;
17958     }
17959     case MODE_Csv: {
17960       setBinaryMode(p->out, 1);
17961       if( p->cnt++==0 && p->showHeader ){
17962         for(i=0; i<nArg; i++){
17963           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
17964         }
17965         utf8_printf(p->out, "%s", p->rowSeparator);
17966       }
17967       if( nArg>0 ){
17968         for(i=0; i<nArg; i++){
17969           output_csv(p, azArg[i], i<nArg-1);
17970         }
17971         utf8_printf(p->out, "%s", p->rowSeparator);
17972       }
17973       setTextMode(p->out, 1);
17974       break;
17975     }
17976     case MODE_Insert: {
17977       if( azArg==0 ) break;
17978       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
17979       if( p->showHeader ){
17980         raw_printf(p->out,"(");
17981         for(i=0; i<nArg; i++){
17982           if( i>0 ) raw_printf(p->out, ",");
17983           if( quoteChar(azCol[i]) ){
17984             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
17985             shell_check_oom(z);
17986             utf8_printf(p->out, "%s", z);
17987             sqlite3_free(z);
17988           }else{
17989             raw_printf(p->out, "%s", azCol[i]);
17990           }
17991         }
17992         raw_printf(p->out,")");
17993       }
17994       p->cnt++;
17995       for(i=0; i<nArg; i++){
17996         raw_printf(p->out, i>0 ? "," : " VALUES(");
17997         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17998           utf8_printf(p->out,"NULL");
17999         }else if( aiType && aiType[i]==SQLITE_TEXT ){
18000           if( ShellHasFlag(p, SHFLG_Newlines) ){
18001             output_quoted_string(p->out, azArg[i]);
18002           }else{
18003             output_quoted_escaped_string(p->out, azArg[i]);
18004           }
18005         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
18006           utf8_printf(p->out,"%s", azArg[i]);
18007         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
18008           char z[50];
18009           double r = sqlite3_column_double(p->pStmt, i);
18010           sqlite3_uint64 ur;
18011           memcpy(&ur,&r,sizeof(r));
18012           if( ur==0x7ff0000000000000LL ){
18013             raw_printf(p->out, "9.0e+999");
18014           }else if( ur==0xfff0000000000000LL ){
18015             raw_printf(p->out, "-9.0e+999");
18016           }else{
18017             sqlite3_int64 ir = (sqlite3_int64)r;
18018             if( r==(double)ir ){
18019               sqlite3_snprintf(50,z,"%lld.0", ir);
18020             }else{
18021               sqlite3_snprintf(50,z,"%!.20g", r);
18022             }
18023             raw_printf(p->out, "%s", z);
18024           }
18025         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
18026           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
18027           int nBlob = sqlite3_column_bytes(p->pStmt, i);
18028           output_hex_blob(p->out, pBlob, nBlob);
18029         }else if( isNumber(azArg[i], 0) ){
18030           utf8_printf(p->out,"%s", azArg[i]);
18031         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
18032           output_quoted_string(p->out, azArg[i]);
18033         }else{
18034           output_quoted_escaped_string(p->out, azArg[i]);
18035         }
18036       }
18037       raw_printf(p->out,");\n");
18038       break;
18039     }
18040     case MODE_Json: {
18041       if( azArg==0 ) break;
18042       if( p->cnt==0 ){
18043         fputs("[{", p->out);
18044       }else{
18045         fputs(",\n{", p->out);
18046       }
18047       p->cnt++;
18048       for(i=0; i<nArg; i++){
18049         output_json_string(p->out, azCol[i], -1);
18050         putc(':', p->out);
18051         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
18052           fputs("null",p->out);
18053         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
18054           char z[50];
18055           double r = sqlite3_column_double(p->pStmt, i);
18056           sqlite3_uint64 ur;
18057           memcpy(&ur,&r,sizeof(r));
18058           if( ur==0x7ff0000000000000LL ){
18059             raw_printf(p->out, "9.0e+999");
18060           }else if( ur==0xfff0000000000000LL ){
18061             raw_printf(p->out, "-9.0e+999");
18062           }else{
18063             sqlite3_snprintf(50,z,"%!.20g", r);
18064             raw_printf(p->out, "%s", z);
18065           }
18066         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
18067           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
18068           int nBlob = sqlite3_column_bytes(p->pStmt, i);
18069           output_json_string(p->out, pBlob, nBlob);
18070         }else if( aiType && aiType[i]==SQLITE_TEXT ){
18071           output_json_string(p->out, azArg[i], -1);
18072         }else{
18073           utf8_printf(p->out,"%s", azArg[i]);
18074         }
18075         if( i<nArg-1 ){
18076           putc(',', p->out);
18077         }
18078       }
18079       putc('}', p->out);
18080       break;
18081     }
18082     case MODE_Quote: {
18083       if( azArg==0 ) break;
18084       if( p->cnt==0 && p->showHeader ){
18085         for(i=0; i<nArg; i++){
18086           if( i>0 ) fputs(p->colSeparator, p->out);
18087           output_quoted_string(p->out, azCol[i]);
18088         }
18089         fputs(p->rowSeparator, p->out);
18090       }
18091       p->cnt++;
18092       for(i=0; i<nArg; i++){
18093         if( i>0 ) fputs(p->colSeparator, p->out);
18094         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
18095           utf8_printf(p->out,"NULL");
18096         }else if( aiType && aiType[i]==SQLITE_TEXT ){
18097           output_quoted_string(p->out, azArg[i]);
18098         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
18099           utf8_printf(p->out,"%s", azArg[i]);
18100         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
18101           char z[50];
18102           double r = sqlite3_column_double(p->pStmt, i);
18103           sqlite3_snprintf(50,z,"%!.20g", r);
18104           raw_printf(p->out, "%s", z);
18105         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
18106           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
18107           int nBlob = sqlite3_column_bytes(p->pStmt, i);
18108           output_hex_blob(p->out, pBlob, nBlob);
18109         }else if( isNumber(azArg[i], 0) ){
18110           utf8_printf(p->out,"%s", azArg[i]);
18111         }else{
18112           output_quoted_string(p->out, azArg[i]);
18113         }
18114       }
18115       fputs(p->rowSeparator, p->out);
18116       break;
18117     }
18118     case MODE_Ascii: {
18119       if( p->cnt++==0 && p->showHeader ){
18120         for(i=0; i<nArg; i++){
18121           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
18122           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
18123         }
18124         utf8_printf(p->out, "%s", p->rowSeparator);
18125       }
18126       if( azArg==0 ) break;
18127       for(i=0; i<nArg; i++){
18128         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
18129         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
18130       }
18131       utf8_printf(p->out, "%s", p->rowSeparator);
18132       break;
18133     }
18134     case MODE_EQP: {
18135       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
18136       break;
18137     }
18138   }
18139   return 0;
18140 }
18141 
18142 /*
18143 ** This is the callback routine that the SQLite library
18144 ** invokes for each row of a query result.
18145 */
18146 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
18147   /* since we don't have type info, call the shell_callback with a NULL value */
18148   return shell_callback(pArg, nArg, azArg, azCol, NULL);
18149 }
18150 
18151 /*
18152 ** This is the callback routine from sqlite3_exec() that appends all
18153 ** output onto the end of a ShellText object.
18154 */
18155 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
18156   ShellText *p = (ShellText*)pArg;
18157   int i;
18158   UNUSED_PARAMETER(az);
18159   if( azArg==0 ) return 0;
18160   if( p->n ) appendText(p, "|", 0);
18161   for(i=0; i<nArg; i++){
18162     if( i ) appendText(p, ",", 0);
18163     if( azArg[i] ) appendText(p, azArg[i], 0);
18164   }
18165   return 0;
18166 }
18167 
18168 /*
18169 ** Generate an appropriate SELFTEST table in the main database.
18170 */
18171 static void createSelftestTable(ShellState *p){
18172   char *zErrMsg = 0;
18173   sqlite3_exec(p->db,
18174     "SAVEPOINT selftest_init;\n"
18175     "CREATE TABLE IF NOT EXISTS selftest(\n"
18176     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
18177     "  op TEXT,\n"                   /* Operator:  memo run */
18178     "  cmd TEXT,\n"                  /* Command text */
18179     "  ans TEXT\n"                   /* Desired answer */
18180     ");"
18181     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
18182     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
18183     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
18184     "         'memo','Tests generated by --init');\n"
18185     "INSERT INTO [_shell$self]\n"
18186     "  SELECT 'run',\n"
18187     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
18188                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
18189     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
18190                           "FROM sqlite_schema ORDER BY 2',224));\n"
18191     "INSERT INTO [_shell$self]\n"
18192     "  SELECT 'run',"
18193     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
18194     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
18195     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
18196     "  FROM (\n"
18197     "    SELECT name FROM sqlite_schema\n"
18198     "     WHERE type='table'\n"
18199     "       AND name<>'selftest'\n"
18200     "       AND coalesce(rootpage,0)>0\n"
18201     "  )\n"
18202     " ORDER BY name;\n"
18203     "INSERT INTO [_shell$self]\n"
18204     "  VALUES('run','PRAGMA integrity_check','ok');\n"
18205     "INSERT INTO selftest(tno,op,cmd,ans)"
18206     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
18207     "DROP TABLE [_shell$self];"
18208     ,0,0,&zErrMsg);
18209   if( zErrMsg ){
18210     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
18211     sqlite3_free(zErrMsg);
18212   }
18213   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
18214 }
18215 
18216 
18217 /*
18218 ** Set the destination table field of the ShellState structure to
18219 ** the name of the table given.  Escape any quote characters in the
18220 ** table name.
18221 */
18222 static void set_table_name(ShellState *p, const char *zName){
18223   int i, n;
18224   char cQuote;
18225   char *z;
18226 
18227   if( p->zDestTable ){
18228     free(p->zDestTable);
18229     p->zDestTable = 0;
18230   }
18231   if( zName==0 ) return;
18232   cQuote = quoteChar(zName);
18233   n = strlen30(zName);
18234   if( cQuote ) n += n+2;
18235   z = p->zDestTable = malloc( n+1 );
18236   shell_check_oom(z);
18237   n = 0;
18238   if( cQuote ) z[n++] = cQuote;
18239   for(i=0; zName[i]; i++){
18240     z[n++] = zName[i];
18241     if( zName[i]==cQuote ) z[n++] = cQuote;
18242   }
18243   if( cQuote ) z[n++] = cQuote;
18244   z[n] = 0;
18245 }
18246 
18247 /*
18248 ** Maybe construct two lines of text that point out the position of a
18249 ** syntax error.  Return a pointer to the text, in memory obtained from
18250 ** sqlite3_malloc().  Or, if the most recent error does not involve a
18251 ** specific token that we can point to, return an empty string.
18252 **
18253 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
18254 ** and should be released by the caller invoking sqlite3_free().
18255 */
18256 static char *shell_error_context(const char *zSql, sqlite3 *db){
18257   int iOffset;
18258   size_t len;
18259   char *zCode;
18260   char *zMsg;
18261   int i;
18262   if( db==0
18263    || zSql==0
18264    || (iOffset = sqlite3_error_offset(db))<0
18265    || iOffset>=(int)strlen(zSql)
18266   ){
18267     return sqlite3_mprintf("");
18268   }
18269   while( iOffset>50 ){
18270     iOffset--;
18271     zSql++;
18272     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
18273   }
18274   len = strlen(zSql);
18275   if( len>78 ){
18276     len = 78;
18277     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
18278   }
18279   zCode = sqlite3_mprintf("%.*s", len, zSql);
18280   shell_check_oom(zCode);
18281   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
18282   if( iOffset<25 ){
18283     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
18284   }else{
18285     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
18286   }
18287   return zMsg;
18288 }
18289 
18290 
18291 /*
18292 ** Execute a query statement that will generate SQL output.  Print
18293 ** the result columns, comma-separated, on a line and then add a
18294 ** semicolon terminator to the end of that line.
18295 **
18296 ** If the number of columns is 1 and that column contains text "--"
18297 ** then write the semicolon on a separate line.  That way, if a
18298 ** "--" comment occurs at the end of the statement, the comment
18299 ** won't consume the semicolon terminator.
18300 */
18301 static int run_table_dump_query(
18302   ShellState *p,           /* Query context */
18303   const char *zSelect      /* SELECT statement to extract content */
18304 ){
18305   sqlite3_stmt *pSelect;
18306   int rc;
18307   int nResult;
18308   int i;
18309   const char *z;
18310   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
18311   if( rc!=SQLITE_OK || !pSelect ){
18312     char *zContext = shell_error_context(zSelect, p->db);
18313     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
18314                 sqlite3_errmsg(p->db), zContext);
18315     sqlite3_free(zContext);
18316     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
18317     return rc;
18318   }
18319   rc = sqlite3_step(pSelect);
18320   nResult = sqlite3_column_count(pSelect);
18321   while( rc==SQLITE_ROW ){
18322     z = (const char*)sqlite3_column_text(pSelect, 0);
18323     utf8_printf(p->out, "%s", z);
18324     for(i=1; i<nResult; i++){
18325       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
18326     }
18327     if( z==0 ) z = "";
18328     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
18329     if( z[0] ){
18330       raw_printf(p->out, "\n;\n");
18331     }else{
18332       raw_printf(p->out, ";\n");
18333     }
18334     rc = sqlite3_step(pSelect);
18335   }
18336   rc = sqlite3_finalize(pSelect);
18337   if( rc!=SQLITE_OK ){
18338     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
18339                 sqlite3_errmsg(p->db));
18340     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
18341   }
18342   return rc;
18343 }
18344 
18345 /*
18346 ** Allocate space and save off string indicating current error.
18347 */
18348 static char *save_err_msg(
18349   sqlite3 *db,           /* Database to query */
18350   const char *zPhase,    /* When the error occcurs */
18351   int rc,                /* Error code returned from API */
18352   const char *zSql       /* SQL string, or NULL */
18353 ){
18354   char *zErr;
18355   char *zContext;
18356   sqlite3_str *pStr = sqlite3_str_new(0);
18357   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
18358   if( rc>1 ){
18359     sqlite3_str_appendf(pStr, " (%d)", rc);
18360   }
18361   zContext = shell_error_context(zSql, db);
18362   if( zContext ){
18363     sqlite3_str_appendall(pStr, zContext);
18364     sqlite3_free(zContext);
18365   }
18366   zErr = sqlite3_str_finish(pStr);
18367   shell_check_oom(zErr);
18368   return zErr;
18369 }
18370 
18371 #ifdef __linux__
18372 /*
18373 ** Attempt to display I/O stats on Linux using /proc/PID/io
18374 */
18375 static void displayLinuxIoStats(FILE *out){
18376   FILE *in;
18377   char z[200];
18378   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
18379   in = fopen(z, "rb");
18380   if( in==0 ) return;
18381   while( fgets(z, sizeof(z), in)!=0 ){
18382     static const struct {
18383       const char *zPattern;
18384       const char *zDesc;
18385     } aTrans[] = {
18386       { "rchar: ",                  "Bytes received by read():" },
18387       { "wchar: ",                  "Bytes sent to write():"    },
18388       { "syscr: ",                  "Read() system calls:"      },
18389       { "syscw: ",                  "Write() system calls:"     },
18390       { "read_bytes: ",             "Bytes read from storage:"  },
18391       { "write_bytes: ",            "Bytes written to storage:" },
18392       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
18393     };
18394     int i;
18395     for(i=0; i<ArraySize(aTrans); i++){
18396       int n = strlen30(aTrans[i].zPattern);
18397       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
18398         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
18399         break;
18400       }
18401     }
18402   }
18403   fclose(in);
18404 }
18405 #endif
18406 
18407 /*
18408 ** Display a single line of status using 64-bit values.
18409 */
18410 static void displayStatLine(
18411   ShellState *p,            /* The shell context */
18412   char *zLabel,             /* Label for this one line */
18413   char *zFormat,            /* Format for the result */
18414   int iStatusCtrl,          /* Which status to display */
18415   int bReset                /* True to reset the stats */
18416 ){
18417   sqlite3_int64 iCur = -1;
18418   sqlite3_int64 iHiwtr = -1;
18419   int i, nPercent;
18420   char zLine[200];
18421   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
18422   for(i=0, nPercent=0; zFormat[i]; i++){
18423     if( zFormat[i]=='%' ) nPercent++;
18424   }
18425   if( nPercent>1 ){
18426     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
18427   }else{
18428     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
18429   }
18430   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
18431 }
18432 
18433 /*
18434 ** Display memory stats.
18435 */
18436 static int display_stats(
18437   sqlite3 *db,                /* Database to query */
18438   ShellState *pArg,           /* Pointer to ShellState */
18439   int bReset                  /* True to reset the stats */
18440 ){
18441   int iCur;
18442   int iHiwtr;
18443   FILE *out;
18444   if( pArg==0 || pArg->out==0 ) return 0;
18445   out = pArg->out;
18446 
18447   if( pArg->pStmt && pArg->statsOn==2 ){
18448     int nCol, i, x;
18449     sqlite3_stmt *pStmt = pArg->pStmt;
18450     char z[100];
18451     nCol = sqlite3_column_count(pStmt);
18452     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
18453     for(i=0; i<nCol; i++){
18454       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
18455       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
18456 #ifndef SQLITE_OMIT_DECLTYPE
18457       sqlite3_snprintf(30, z+x, "declared type:");
18458       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
18459 #endif
18460 #ifdef SQLITE_ENABLE_COLUMN_METADATA
18461       sqlite3_snprintf(30, z+x, "database name:");
18462       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
18463       sqlite3_snprintf(30, z+x, "table name:");
18464       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
18465       sqlite3_snprintf(30, z+x, "origin name:");
18466       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
18467 #endif
18468     }
18469   }
18470 
18471   if( pArg->statsOn==3 ){
18472     if( pArg->pStmt ){
18473       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
18474       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
18475     }
18476     return 0;
18477   }
18478 
18479   displayStatLine(pArg, "Memory Used:",
18480      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
18481   displayStatLine(pArg, "Number of Outstanding Allocations:",
18482      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
18483   if( pArg->shellFlgs & SHFLG_Pagecache ){
18484     displayStatLine(pArg, "Number of Pcache Pages Used:",
18485        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
18486   }
18487   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
18488      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
18489   displayStatLine(pArg, "Largest Allocation:",
18490      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
18491   displayStatLine(pArg, "Largest Pcache Allocation:",
18492      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
18493 #ifdef YYTRACKMAXSTACKDEPTH
18494   displayStatLine(pArg, "Deepest Parser Stack:",
18495      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
18496 #endif
18497 
18498   if( db ){
18499     if( pArg->shellFlgs & SHFLG_Lookaside ){
18500       iHiwtr = iCur = -1;
18501       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
18502                         &iCur, &iHiwtr, bReset);
18503       raw_printf(pArg->out,
18504               "Lookaside Slots Used:                %d (max %d)\n",
18505               iCur, iHiwtr);
18506       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
18507                         &iCur, &iHiwtr, bReset);
18508       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
18509               iHiwtr);
18510       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
18511                         &iCur, &iHiwtr, bReset);
18512       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
18513               iHiwtr);
18514       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
18515                         &iCur, &iHiwtr, bReset);
18516       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
18517               iHiwtr);
18518     }
18519     iHiwtr = iCur = -1;
18520     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
18521     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
18522             iCur);
18523     iHiwtr = iCur = -1;
18524     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
18525     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
18526     iHiwtr = iCur = -1;
18527     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
18528     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
18529     iHiwtr = iCur = -1;
18530     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
18531     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
18532     iHiwtr = iCur = -1;
18533     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
18534     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
18535     iHiwtr = iCur = -1;
18536     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
18537     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
18538             iCur);
18539     iHiwtr = iCur = -1;
18540     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
18541     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
18542             iCur);
18543   }
18544 
18545   if( pArg->pStmt ){
18546     int iHit, iMiss;
18547     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
18548                                bReset);
18549     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
18550     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
18551     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
18552     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
18553     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
18554     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
18555                                bReset);
18556     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
18557                                 bReset);
18558     if( iHit || iMiss ){
18559       raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
18560             iHit, iHit+iMiss);
18561     }
18562     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
18563     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
18564     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
18565     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
18566     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
18567     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
18568     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
18569     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
18570   }
18571 
18572 #ifdef __linux__
18573   displayLinuxIoStats(pArg->out);
18574 #endif
18575 
18576   /* Do not remove this machine readable comment: extra-stats-output-here */
18577 
18578   return 0;
18579 }
18580 
18581 
18582 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18583 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
18584   int iPid = 0;
18585   int ret = 1;
18586   sqlite3_stmt_scanstatus_v2(p, iEntry,
18587       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
18588   );
18589   while( iPid!=0 ){
18590     int ii;
18591     for(ii=0; 1; ii++){
18592       int iId;
18593       int res;
18594       res = sqlite3_stmt_scanstatus_v2(p, ii,
18595           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
18596       );
18597       if( res ) break;
18598       if( iId==iPid ){
18599         sqlite3_stmt_scanstatus_v2(p, ii,
18600             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
18601         );
18602       }
18603     }
18604     ret++;
18605   }
18606   return ret;
18607 }
18608 #endif
18609 
18610 /*
18611 ** Display scan stats.
18612 */
18613 static void display_scanstats(
18614   sqlite3 *db,                    /* Database to query */
18615   ShellState *pArg                /* Pointer to ShellState */
18616 ){
18617 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
18618   UNUSED_PARAMETER(db);
18619   UNUSED_PARAMETER(pArg);
18620 #else
18621   static const int f = SQLITE_SCANSTAT_COMPLEX;
18622   sqlite3_stmt *p = pArg->pStmt;
18623   int ii = 0;
18624   i64 nTotal = 0;
18625   int nWidth = 0;
18626   eqp_reset(pArg);
18627 
18628   for(ii=0; 1; ii++){
18629     const char *z = 0;
18630     int n = 0;
18631     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
18632       break;
18633     }
18634     n = strlen(z) + scanStatsHeight(p, ii)*3;
18635     if( n>nWidth ) nWidth = n;
18636   }
18637   nWidth += 4;
18638 
18639   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
18640   for(ii=0; 1; ii++){
18641     i64 nLoop = 0;
18642     i64 nRow = 0;
18643     i64 nCycle = 0;
18644     int iId = 0;
18645     int iPid = 0;
18646     const char *z = 0;
18647     const char *zName = 0;
18648     char *zText = 0;
18649     double rEst = 0.0;
18650 
18651     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
18652       break;
18653     }
18654     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
18655     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
18656     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
18657     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
18658     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
18659     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
18660     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
18661 
18662     zText = sqlite3_mprintf("%s", z);
18663     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
18664       char *z = 0;
18665       if( nCycle>=0 && nTotal>0 ){
18666         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
18667             nCycle, ((nCycle*100)+nTotal/2) / nTotal
18668         );
18669       }
18670       if( nLoop>=0 ){
18671         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
18672       }
18673       if( nRow>=0 ){
18674         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
18675       }
18676 
18677       if( zName && pArg->scanstatsOn>1 ){
18678         double rpl = (double)nRow / (double)nLoop;
18679         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
18680       }
18681 
18682       zText = sqlite3_mprintf(
18683           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
18684       );
18685     }
18686 
18687     eqp_append(pArg, iId, iPid, zText);
18688     sqlite3_free(zText);
18689   }
18690 
18691   eqp_render(pArg, nTotal);
18692 #endif
18693 }
18694 
18695 /*
18696 ** Parameter azArray points to a zero-terminated array of strings. zStr
18697 ** points to a single nul-terminated string. Return non-zero if zStr
18698 ** is equal, according to strcmp(), to any of the strings in the array.
18699 ** Otherwise, return zero.
18700 */
18701 static int str_in_array(const char *zStr, const char **azArray){
18702   int i;
18703   for(i=0; azArray[i]; i++){
18704     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
18705   }
18706   return 0;
18707 }
18708 
18709 /*
18710 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
18711 ** and populate the ShellState.aiIndent[] array with the number of
18712 ** spaces each opcode should be indented before it is output.
18713 **
18714 ** The indenting rules are:
18715 **
18716 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
18717 **       all opcodes that occur between the p2 jump destination and the opcode
18718 **       itself by 2 spaces.
18719 **
18720 **     * Do the previous for "Return" instructions for when P2 is positive.
18721 **       See tag-20220407a in wherecode.c and vdbe.c.
18722 **
18723 **     * For each "Goto", if the jump destination is earlier in the program
18724 **       and ends on one of:
18725 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
18726 **       or if the P1 parameter is one instead of zero,
18727 **       then indent all opcodes between the earlier instruction
18728 **       and "Goto" by 2 spaces.
18729 */
18730 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
18731   const char *zSql;               /* The text of the SQL statement */
18732   const char *z;                  /* Used to check if this is an EXPLAIN */
18733   int *abYield = 0;               /* True if op is an OP_Yield */
18734   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
18735   int iOp;                        /* Index of operation in p->aiIndent[] */
18736 
18737   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
18738                            "Return", 0 };
18739   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
18740                             "Rewind", 0 };
18741   const char *azGoto[] = { "Goto", 0 };
18742 
18743   /* Try to figure out if this is really an EXPLAIN statement. If this
18744   ** cannot be verified, return early.  */
18745   if( sqlite3_column_count(pSql)!=8 ){
18746     p->cMode = p->mode;
18747     return;
18748   }
18749   zSql = sqlite3_sql(pSql);
18750   if( zSql==0 ) return;
18751   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
18752   if( sqlite3_strnicmp(z, "explain", 7) ){
18753     p->cMode = p->mode;
18754     return;
18755   }
18756 
18757   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
18758     int i;
18759     int iAddr = sqlite3_column_int(pSql, 0);
18760     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
18761 
18762     /* Set p2 to the P2 field of the current opcode. Then, assuming that
18763     ** p2 is an instruction address, set variable p2op to the index of that
18764     ** instruction in the aiIndent[] array. p2 and p2op may be different if
18765     ** the current instruction is part of a sub-program generated by an
18766     ** SQL trigger or foreign key.  */
18767     int p2 = sqlite3_column_int(pSql, 3);
18768     int p2op = (p2 + (iOp-iAddr));
18769 
18770     /* Grow the p->aiIndent array as required */
18771     if( iOp>=nAlloc ){
18772       if( iOp==0 ){
18773         /* Do further verfication that this is explain output.  Abort if
18774         ** it is not */
18775         static const char *explainCols[] = {
18776            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
18777         int jj;
18778         for(jj=0; jj<ArraySize(explainCols); jj++){
18779           if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
18780             p->cMode = p->mode;
18781             sqlite3_reset(pSql);
18782             return;
18783           }
18784         }
18785       }
18786       nAlloc += 100;
18787       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
18788       shell_check_oom(p->aiIndent);
18789       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
18790       shell_check_oom(abYield);
18791     }
18792     abYield[iOp] = str_in_array(zOp, azYield);
18793     p->aiIndent[iOp] = 0;
18794     p->nIndent = iOp+1;
18795 
18796     if( str_in_array(zOp, azNext) && p2op>0 ){
18797       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
18798     }
18799     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
18800      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
18801     ){
18802       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
18803     }
18804   }
18805 
18806   p->iIndent = 0;
18807   sqlite3_free(abYield);
18808   sqlite3_reset(pSql);
18809 }
18810 
18811 /*
18812 ** Free the array allocated by explain_data_prepare().
18813 */
18814 static void explain_data_delete(ShellState *p){
18815   sqlite3_free(p->aiIndent);
18816   p->aiIndent = 0;
18817   p->nIndent = 0;
18818   p->iIndent = 0;
18819 }
18820 
18821 /*
18822 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
18823 */
18824 static unsigned int savedSelectTrace;
18825 static unsigned int savedWhereTrace;
18826 static void disable_debug_trace_modes(void){
18827   unsigned int zero = 0;
18828   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
18829   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
18830   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
18831   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
18832 }
18833 static void restore_debug_trace_modes(void){
18834   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
18835   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
18836 }
18837 
18838 /* Create the TEMP table used to store parameter bindings */
18839 static void bind_table_init(ShellState *p){
18840   int wrSchema = 0;
18841   int defensiveMode = 0;
18842   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
18843   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
18844   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
18845   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
18846   sqlite3_exec(p->db,
18847     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
18848     "  key TEXT PRIMARY KEY,\n"
18849     "  value\n"
18850     ") WITHOUT ROWID;",
18851     0, 0, 0);
18852   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
18853   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
18854 }
18855 
18856 /*
18857 ** Bind parameters on a prepared statement.
18858 **
18859 ** Parameter bindings are taken from a TEMP table of the form:
18860 **
18861 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
18862 **    WITHOUT ROWID;
18863 **
18864 ** No bindings occur if this table does not exist.  The name of the table
18865 ** begins with "sqlite_" so that it will not collide with ordinary application
18866 ** tables.  The table must be in the TEMP schema.
18867 */
18868 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
18869   int nVar;
18870   int i;
18871   int rc;
18872   sqlite3_stmt *pQ = 0;
18873 
18874   nVar = sqlite3_bind_parameter_count(pStmt);
18875   if( nVar==0 ) return;  /* Nothing to do */
18876   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
18877                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
18878     rc = SQLITE_NOTFOUND;
18879     pQ = 0;
18880   }else{
18881     rc = sqlite3_prepare_v2(pArg->db,
18882             "SELECT value FROM temp.sqlite_parameters"
18883             " WHERE key=?1", -1, &pQ, 0);
18884   }
18885   for(i=1; i<=nVar; i++){
18886     char zNum[30];
18887     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
18888     if( zVar==0 ){
18889       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
18890       zVar = zNum;
18891     }
18892     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
18893     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
18894       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
18895 #ifdef NAN
18896     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
18897       sqlite3_bind_double(pStmt, i, NAN);
18898 #endif
18899 #ifdef INFINITY
18900     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
18901       sqlite3_bind_double(pStmt, i, INFINITY);
18902 #endif
18903     }else{
18904       sqlite3_bind_null(pStmt, i);
18905     }
18906     sqlite3_reset(pQ);
18907   }
18908   sqlite3_finalize(pQ);
18909 }
18910 
18911 /*
18912 ** UTF8 box-drawing characters.  Imagine box lines like this:
18913 **
18914 **           1
18915 **           |
18916 **       4 --+-- 2
18917 **           |
18918 **           3
18919 **
18920 ** Each box characters has between 2 and 4 of the lines leading from
18921 ** the center.  The characters are here identified by the numbers of
18922 ** their corresponding lines.
18923 */
18924 #define BOX_24   "\342\224\200"  /* U+2500 --- */
18925 #define BOX_13   "\342\224\202"  /* U+2502  |  */
18926 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
18927 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
18928 #define BOX_12   "\342\224\224"  /* U+2514  '- */
18929 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
18930 #define BOX_123  "\342\224\234"  /* U+251c  |- */
18931 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
18932 #define BOX_234  "\342\224\254"  /* U+252c -,- */
18933 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
18934 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
18935 
18936 /* Draw horizontal line N characters long using unicode box
18937 ** characters
18938 */
18939 static void print_box_line(FILE *out, int N){
18940   const char zDash[] =
18941       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
18942       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
18943   const int nDash = sizeof(zDash) - 1;
18944   N *= 3;
18945   while( N>nDash ){
18946     utf8_printf(out, zDash);
18947     N -= nDash;
18948   }
18949   utf8_printf(out, "%.*s", N, zDash);
18950 }
18951 
18952 /*
18953 ** Draw a horizontal separator for a MODE_Box table.
18954 */
18955 static void print_box_row_separator(
18956   ShellState *p,
18957   int nArg,
18958   const char *zSep1,
18959   const char *zSep2,
18960   const char *zSep3
18961 ){
18962   int i;
18963   if( nArg>0 ){
18964     utf8_printf(p->out, "%s", zSep1);
18965     print_box_line(p->out, p->actualWidth[0]+2);
18966     for(i=1; i<nArg; i++){
18967       utf8_printf(p->out, "%s", zSep2);
18968       print_box_line(p->out, p->actualWidth[i]+2);
18969     }
18970     utf8_printf(p->out, "%s", zSep3);
18971   }
18972   fputs("\n", p->out);
18973 }
18974 
18975 /*
18976 ** z[] is a line of text that is to be displayed the .mode box or table or
18977 ** similar tabular formats.  z[] might contain control characters such
18978 ** as \n, \t, \f, or \r.
18979 **
18980 ** Compute characters to display on the first line of z[].  Stop at the
18981 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
18982 ** from malloc()) of that first line, which caller should free sometime.
18983 ** Write anything to display on the next line into *pzTail.  If this is
18984 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
18985 */
18986 static char *translateForDisplayAndDup(
18987   const unsigned char *z,            /* Input text to be transformed */
18988   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
18989   int mxWidth,                       /* Max width.  0 means no limit */
18990   u8 bWordWrap                       /* If true, avoid breaking mid-word */
18991 ){
18992   int i;                 /* Input bytes consumed */
18993   int j;                 /* Output bytes generated */
18994   int k;                 /* Input bytes to be displayed */
18995   int n;                 /* Output column number */
18996   unsigned char *zOut;   /* Output text */
18997 
18998   if( z==0 ){
18999     *pzTail = 0;
19000     return 0;
19001   }
19002   if( mxWidth<0 ) mxWidth = -mxWidth;
19003   if( mxWidth==0 ) mxWidth = 1000000;
19004   i = j = n = 0;
19005   while( n<mxWidth ){
19006     if( z[i]>=' ' ){
19007       n++;
19008       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
19009       continue;
19010     }
19011     if( z[i]=='\t' ){
19012       do{
19013         n++;
19014         j++;
19015       }while( (n&7)!=0 && n<mxWidth );
19016       i++;
19017       continue;
19018     }
19019     break;
19020   }
19021   if( n>=mxWidth && bWordWrap  ){
19022     /* Perhaps try to back up to a better place to break the line */
19023     for(k=i; k>i/2; k--){
19024       if( isspace(z[k-1]) ) break;
19025     }
19026     if( k<=i/2 ){
19027       for(k=i; k>i/2; k--){
19028         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
19029       }
19030     }
19031     if( k<=i/2 ){
19032       k = i;
19033     }else{
19034       i = k;
19035       while( z[i]==' ' ) i++;
19036     }
19037   }else{
19038     k = i;
19039   }
19040   if( n>=mxWidth && z[i]>=' ' ){
19041    *pzTail = &z[i];
19042   }else if( z[i]=='\r' && z[i+1]=='\n' ){
19043     *pzTail = z[i+2] ? &z[i+2] : 0;
19044   }else if( z[i]==0 || z[i+1]==0 ){
19045     *pzTail = 0;
19046   }else{
19047     *pzTail = &z[i+1];
19048   }
19049   zOut = malloc( j+1 );
19050   shell_check_oom(zOut);
19051   i = j = n = 0;
19052   while( i<k ){
19053     if( z[i]>=' ' ){
19054       n++;
19055       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
19056       continue;
19057     }
19058     if( z[i]=='\t' ){
19059       do{
19060         n++;
19061         zOut[j++] = ' ';
19062       }while( (n&7)!=0 && n<mxWidth );
19063       i++;
19064       continue;
19065     }
19066     break;
19067   }
19068   zOut[j] = 0;
19069   return (char*)zOut;
19070 }
19071 
19072 /* Extract the value of the i-th current column for pStmt as an SQL literal
19073 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
19074 ** the caller.
19075 */
19076 static char *quoted_column(sqlite3_stmt *pStmt, int i){
19077   switch( sqlite3_column_type(pStmt, i) ){
19078     case SQLITE_NULL: {
19079       return sqlite3_mprintf("NULL");
19080     }
19081     case SQLITE_INTEGER:
19082     case SQLITE_FLOAT: {
19083       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
19084     }
19085     case SQLITE_TEXT: {
19086       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
19087     }
19088     case SQLITE_BLOB: {
19089       int j;
19090       sqlite3_str *pStr = sqlite3_str_new(0);
19091       const unsigned char *a = sqlite3_column_blob(pStmt,i);
19092       int n = sqlite3_column_bytes(pStmt,i);
19093       sqlite3_str_append(pStr, "x'", 2);
19094       for(j=0; j<n; j++){
19095         sqlite3_str_appendf(pStr, "%02x", a[j]);
19096       }
19097       sqlite3_str_append(pStr, "'", 1);
19098       return sqlite3_str_finish(pStr);
19099     }
19100   }
19101   return 0; /* Not reached */
19102 }
19103 
19104 /*
19105 ** Run a prepared statement and output the result in one of the
19106 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
19107 ** or MODE_Box.
19108 **
19109 ** This is different from ordinary exec_prepared_stmt() in that
19110 ** it has to run the entire query and gather the results into memory
19111 ** first, in order to determine column widths, before providing
19112 ** any output.
19113 */
19114 static void exec_prepared_stmt_columnar(
19115   ShellState *p,                        /* Pointer to ShellState */
19116   sqlite3_stmt *pStmt                   /* Statment to run */
19117 ){
19118   sqlite3_int64 nRow = 0;
19119   int nColumn = 0;
19120   char **azData = 0;
19121   sqlite3_int64 nAlloc = 0;
19122   char *abRowDiv = 0;
19123   const unsigned char *uz;
19124   const char *z;
19125   char **azQuoted = 0;
19126   int rc;
19127   sqlite3_int64 i, nData;
19128   int j, nTotal, w, n;
19129   const char *colSep = 0;
19130   const char *rowSep = 0;
19131   const unsigned char **azNextLine = 0;
19132   int bNextLine = 0;
19133   int bMultiLineRowExists = 0;
19134   int bw = p->cmOpts.bWordWrap;
19135   const char *zEmpty = "";
19136   const char *zShowNull = p->nullValue;
19137 
19138   rc = sqlite3_step(pStmt);
19139   if( rc!=SQLITE_ROW ) return;
19140   nColumn = sqlite3_column_count(pStmt);
19141   nAlloc = nColumn*4;
19142   if( nAlloc<=0 ) nAlloc = 1;
19143   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
19144   shell_check_oom(azData);
19145   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
19146   shell_check_oom(azNextLine);
19147   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
19148   if( p->cmOpts.bQuote ){
19149     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
19150     shell_check_oom(azQuoted);
19151     memset(azQuoted, 0, nColumn*sizeof(char*) );
19152   }
19153   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
19154   shell_check_oom(abRowDiv);
19155   if( nColumn>p->nWidth ){
19156     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
19157     shell_check_oom(p->colWidth);
19158     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
19159     p->nWidth = nColumn;
19160     p->actualWidth = &p->colWidth[nColumn];
19161   }
19162   memset(p->actualWidth, 0, nColumn*sizeof(int));
19163   for(i=0; i<nColumn; i++){
19164     w = p->colWidth[i];
19165     if( w<0 ) w = -w;
19166     p->actualWidth[i] = w;
19167   }
19168   for(i=0; i<nColumn; i++){
19169     const unsigned char *zNotUsed;
19170     int wx = p->colWidth[i];
19171     if( wx==0 ){
19172       wx = p->cmOpts.iWrap;
19173     }
19174     if( wx<0 ) wx = -wx;
19175     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
19176     if( uz==0 ) uz = (u8*)"";
19177     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
19178   }
19179   do{
19180     int useNextLine = bNextLine;
19181     bNextLine = 0;
19182     if( (nRow+2)*nColumn >= nAlloc ){
19183       nAlloc *= 2;
19184       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
19185       shell_check_oom(azData);
19186       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
19187       shell_check_oom(abRowDiv);
19188     }
19189     abRowDiv[nRow] = 1;
19190     nRow++;
19191     for(i=0; i<nColumn; i++){
19192       int wx = p->colWidth[i];
19193       if( wx==0 ){
19194         wx = p->cmOpts.iWrap;
19195       }
19196       if( wx<0 ) wx = -wx;
19197       if( useNextLine ){
19198         uz = azNextLine[i];
19199         if( uz==0 ) uz = (u8*)zEmpty;
19200       }else if( p->cmOpts.bQuote ){
19201         sqlite3_free(azQuoted[i]);
19202         azQuoted[i] = quoted_column(pStmt,i);
19203         uz = (const unsigned char*)azQuoted[i];
19204       }else{
19205         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
19206         if( uz==0 ) uz = (u8*)zShowNull;
19207       }
19208       azData[nRow*nColumn + i]
19209         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
19210       if( azNextLine[i] ){
19211         bNextLine = 1;
19212         abRowDiv[nRow-1] = 0;
19213         bMultiLineRowExists = 1;
19214       }
19215     }
19216   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
19217   nTotal = nColumn*(nRow+1);
19218   for(i=0; i<nTotal; i++){
19219     z = azData[i];
19220     if( z==0 ) z = (char*)zEmpty;
19221     n = strlenChar(z);
19222     j = i%nColumn;
19223     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
19224   }
19225   if( seenInterrupt ) goto columnar_end;
19226   if( nColumn==0 ) goto columnar_end;
19227   switch( p->cMode ){
19228     case MODE_Column: {
19229       colSep = "  ";
19230       rowSep = "\n";
19231       if( p->showHeader ){
19232         for(i=0; i<nColumn; i++){
19233           w = p->actualWidth[i];
19234           if( p->colWidth[i]<0 ) w = -w;
19235           utf8_width_print(p->out, w, azData[i]);
19236           fputs(i==nColumn-1?"\n":"  ", p->out);
19237         }
19238         for(i=0; i<nColumn; i++){
19239           print_dashes(p->out, p->actualWidth[i]);
19240           fputs(i==nColumn-1?"\n":"  ", p->out);
19241         }
19242       }
19243       break;
19244     }
19245     case MODE_Table: {
19246       colSep = " | ";
19247       rowSep = " |\n";
19248       print_row_separator(p, nColumn, "+");
19249       fputs("| ", p->out);
19250       for(i=0; i<nColumn; i++){
19251         w = p->actualWidth[i];
19252         n = strlenChar(azData[i]);
19253         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
19254         fputs(i==nColumn-1?" |\n":" | ", p->out);
19255       }
19256       print_row_separator(p, nColumn, "+");
19257       break;
19258     }
19259     case MODE_Markdown: {
19260       colSep = " | ";
19261       rowSep = " |\n";
19262       fputs("| ", p->out);
19263       for(i=0; i<nColumn; i++){
19264         w = p->actualWidth[i];
19265         n = strlenChar(azData[i]);
19266         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
19267         fputs(i==nColumn-1?" |\n":" | ", p->out);
19268       }
19269       print_row_separator(p, nColumn, "|");
19270       break;
19271     }
19272     case MODE_Box: {
19273       colSep = " " BOX_13 " ";
19274       rowSep = " " BOX_13 "\n";
19275       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
19276       utf8_printf(p->out, BOX_13 " ");
19277       for(i=0; i<nColumn; i++){
19278         w = p->actualWidth[i];
19279         n = strlenChar(azData[i]);
19280         utf8_printf(p->out, "%*s%s%*s%s",
19281             (w-n)/2, "", azData[i], (w-n+1)/2, "",
19282             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
19283       }
19284       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
19285       break;
19286     }
19287   }
19288   for(i=nColumn, j=0; i<nTotal; i++, j++){
19289     if( j==0 && p->cMode!=MODE_Column ){
19290       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
19291     }
19292     z = azData[i];
19293     if( z==0 ) z = p->nullValue;
19294     w = p->actualWidth[j];
19295     if( p->colWidth[j]<0 ) w = -w;
19296     utf8_width_print(p->out, w, z);
19297     if( j==nColumn-1 ){
19298       utf8_printf(p->out, "%s", rowSep);
19299       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
19300         if( p->cMode==MODE_Table ){
19301           print_row_separator(p, nColumn, "+");
19302         }else if( p->cMode==MODE_Box ){
19303           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
19304         }else if( p->cMode==MODE_Column ){
19305           raw_printf(p->out, "\n");
19306         }
19307       }
19308       j = -1;
19309       if( seenInterrupt ) goto columnar_end;
19310     }else{
19311       utf8_printf(p->out, "%s", colSep);
19312     }
19313   }
19314   if( p->cMode==MODE_Table ){
19315     print_row_separator(p, nColumn, "+");
19316   }else if( p->cMode==MODE_Box ){
19317     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
19318   }
19319 columnar_end:
19320   if( seenInterrupt ){
19321     utf8_printf(p->out, "Interrupt\n");
19322   }
19323   nData = (nRow+1)*nColumn;
19324   for(i=0; i<nData; i++){
19325     z = azData[i];
19326     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
19327   }
19328   sqlite3_free(azData);
19329   sqlite3_free((void*)azNextLine);
19330   sqlite3_free(abRowDiv);
19331   if( azQuoted ){
19332     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
19333     sqlite3_free(azQuoted);
19334   }
19335 }
19336 
19337 /*
19338 ** Run a prepared statement
19339 */
19340 static void exec_prepared_stmt(
19341   ShellState *pArg,                                /* Pointer to ShellState */
19342   sqlite3_stmt *pStmt                              /* Statment to run */
19343 ){
19344   int rc;
19345   sqlite3_uint64 nRow = 0;
19346 
19347   if( pArg->cMode==MODE_Column
19348    || pArg->cMode==MODE_Table
19349    || pArg->cMode==MODE_Box
19350    || pArg->cMode==MODE_Markdown
19351   ){
19352     exec_prepared_stmt_columnar(pArg, pStmt);
19353     return;
19354   }
19355 
19356   /* perform the first step.  this will tell us if we
19357   ** have a result set or not and how wide it is.
19358   */
19359   rc = sqlite3_step(pStmt);
19360   /* if we have a result set... */
19361   if( SQLITE_ROW == rc ){
19362     /* allocate space for col name ptr, value ptr, and type */
19363     int nCol = sqlite3_column_count(pStmt);
19364     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
19365     if( !pData ){
19366       shell_out_of_memory();
19367     }else{
19368       char **azCols = (char **)pData;      /* Names of result columns */
19369       char **azVals = &azCols[nCol];       /* Results */
19370       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
19371       int i, x;
19372       assert(sizeof(int) <= sizeof(char *));
19373       /* save off ptrs to column names */
19374       for(i=0; i<nCol; i++){
19375         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
19376       }
19377       do{
19378         nRow++;
19379         /* extract the data and data types */
19380         for(i=0; i<nCol; i++){
19381           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
19382           if( x==SQLITE_BLOB
19383            && pArg
19384            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
19385           ){
19386             azVals[i] = "";
19387           }else{
19388             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
19389           }
19390           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
19391             rc = SQLITE_NOMEM;
19392             break; /* from for */
19393           }
19394         } /* end for */
19395 
19396         /* if data and types extracted successfully... */
19397         if( SQLITE_ROW == rc ){
19398           /* call the supplied callback with the result row data */
19399           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
19400             rc = SQLITE_ABORT;
19401           }else{
19402             rc = sqlite3_step(pStmt);
19403           }
19404         }
19405       } while( SQLITE_ROW == rc );
19406       sqlite3_free(pData);
19407       if( pArg->cMode==MODE_Json ){
19408         fputs("]\n", pArg->out);
19409       }else if( pArg->cMode==MODE_Count ){
19410         char zBuf[200];
19411         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
19412                          nRow, nRow!=1 ? "s" : "");
19413         printf("%s", zBuf);
19414       }
19415     }
19416   }
19417 }
19418 
19419 #ifndef SQLITE_OMIT_VIRTUALTABLE
19420 /*
19421 ** This function is called to process SQL if the previous shell command
19422 ** was ".expert". It passes the SQL in the second argument directly to
19423 ** the sqlite3expert object.
19424 **
19425 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
19426 ** code. In this case, (*pzErr) may be set to point to a buffer containing
19427 ** an English language error message. It is the responsibility of the
19428 ** caller to eventually free this buffer using sqlite3_free().
19429 */
19430 static int expertHandleSQL(
19431   ShellState *pState,
19432   const char *zSql,
19433   char **pzErr
19434 ){
19435   assert( pState->expert.pExpert );
19436   assert( pzErr==0 || *pzErr==0 );
19437   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
19438 }
19439 
19440 /*
19441 ** This function is called either to silently clean up the object
19442 ** created by the ".expert" command (if bCancel==1), or to generate a
19443 ** report from it and then clean it up (if bCancel==0).
19444 **
19445 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
19446 ** code. In this case, (*pzErr) may be set to point to a buffer containing
19447 ** an English language error message. It is the responsibility of the
19448 ** caller to eventually free this buffer using sqlite3_free().
19449 */
19450 static int expertFinish(
19451   ShellState *pState,
19452   int bCancel,
19453   char **pzErr
19454 ){
19455   int rc = SQLITE_OK;
19456   sqlite3expert *p = pState->expert.pExpert;
19457   assert( p );
19458   assert( bCancel || pzErr==0 || *pzErr==0 );
19459   if( bCancel==0 ){
19460     FILE *out = pState->out;
19461     int bVerbose = pState->expert.bVerbose;
19462 
19463     rc = sqlite3_expert_analyze(p, pzErr);
19464     if( rc==SQLITE_OK ){
19465       int nQuery = sqlite3_expert_count(p);
19466       int i;
19467 
19468       if( bVerbose ){
19469         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
19470         raw_printf(out, "-- Candidates -----------------------------\n");
19471         raw_printf(out, "%s\n", zCand);
19472       }
19473       for(i=0; i<nQuery; i++){
19474         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
19475         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
19476         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
19477         if( zIdx==0 ) zIdx = "(no new indexes)\n";
19478         if( bVerbose ){
19479           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
19480           raw_printf(out, "%s\n\n", zSql);
19481         }
19482         raw_printf(out, "%s\n", zIdx);
19483         raw_printf(out, "%s\n", zEQP);
19484       }
19485     }
19486   }
19487   sqlite3_expert_destroy(p);
19488   pState->expert.pExpert = 0;
19489   return rc;
19490 }
19491 
19492 /*
19493 ** Implementation of ".expert" dot command.
19494 */
19495 static int expertDotCommand(
19496   ShellState *pState,             /* Current shell tool state */
19497   char **azArg,                   /* Array of arguments passed to dot command */
19498   int nArg                        /* Number of entries in azArg[] */
19499 ){
19500   int rc = SQLITE_OK;
19501   char *zErr = 0;
19502   int i;
19503   int iSample = 0;
19504 
19505   assert( pState->expert.pExpert==0 );
19506   memset(&pState->expert, 0, sizeof(ExpertInfo));
19507 
19508   for(i=1; rc==SQLITE_OK && i<nArg; i++){
19509     char *z = azArg[i];
19510     int n;
19511     if( z[0]=='-' && z[1]=='-' ) z++;
19512     n = strlen30(z);
19513     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
19514       pState->expert.bVerbose = 1;
19515     }
19516     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
19517       if( i==(nArg-1) ){
19518         raw_printf(stderr, "option requires an argument: %s\n", z);
19519         rc = SQLITE_ERROR;
19520       }else{
19521         iSample = (int)integerValue(azArg[++i]);
19522         if( iSample<0 || iSample>100 ){
19523           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
19524           rc = SQLITE_ERROR;
19525         }
19526       }
19527     }
19528     else{
19529       raw_printf(stderr, "unknown option: %s\n", z);
19530       rc = SQLITE_ERROR;
19531     }
19532   }
19533 
19534   if( rc==SQLITE_OK ){
19535     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
19536     if( pState->expert.pExpert==0 ){
19537       raw_printf(stderr, "sqlite3_expert_new: %s\n",
19538                  zErr ? zErr : "out of memory");
19539       rc = SQLITE_ERROR;
19540     }else{
19541       sqlite3_expert_config(
19542           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
19543       );
19544     }
19545   }
19546   sqlite3_free(zErr);
19547 
19548   return rc;
19549 }
19550 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
19551 
19552 /*
19553 ** Execute a statement or set of statements.  Print
19554 ** any result rows/columns depending on the current mode
19555 ** set via the supplied callback.
19556 **
19557 ** This is very similar to SQLite's built-in sqlite3_exec()
19558 ** function except it takes a slightly different callback
19559 ** and callback data argument.
19560 */
19561 static int shell_exec(
19562   ShellState *pArg,                         /* Pointer to ShellState */
19563   const char *zSql,                         /* SQL to be evaluated */
19564   char **pzErrMsg                           /* Error msg written here */
19565 ){
19566   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
19567   int rc = SQLITE_OK;             /* Return Code */
19568   int rc2;
19569   const char *zLeftover;          /* Tail of unprocessed SQL */
19570   sqlite3 *db = pArg->db;
19571 
19572   if( pzErrMsg ){
19573     *pzErrMsg = NULL;
19574   }
19575 
19576 #ifndef SQLITE_OMIT_VIRTUALTABLE
19577   if( pArg->expert.pExpert ){
19578     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
19579     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
19580   }
19581 #endif
19582 
19583   while( zSql[0] && (SQLITE_OK == rc) ){
19584     static const char *zStmtSql;
19585     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
19586     if( SQLITE_OK != rc ){
19587       if( pzErrMsg ){
19588         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
19589       }
19590     }else{
19591       if( !pStmt ){
19592         /* this happens for a comment or white-space */
19593         zSql = zLeftover;
19594         while( IsSpace(zSql[0]) ) zSql++;
19595         continue;
19596       }
19597       zStmtSql = sqlite3_sql(pStmt);
19598       if( zStmtSql==0 ) zStmtSql = "";
19599       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
19600 
19601       /* save off the prepared statment handle and reset row count */
19602       if( pArg ){
19603         pArg->pStmt = pStmt;
19604         pArg->cnt = 0;
19605       }
19606 
19607       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
19608       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
19609         sqlite3_stmt *pExplain;
19610         char *zEQP;
19611         int triggerEQP = 0;
19612         disable_debug_trace_modes();
19613         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
19614         if( pArg->autoEQP>=AUTOEQP_trigger ){
19615           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
19616         }
19617         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
19618         shell_check_oom(zEQP);
19619         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
19620         if( rc==SQLITE_OK ){
19621           while( sqlite3_step(pExplain)==SQLITE_ROW ){
19622             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
19623             int iEqpId = sqlite3_column_int(pExplain, 0);
19624             int iParentId = sqlite3_column_int(pExplain, 1);
19625             if( zEQPLine==0 ) zEQPLine = "";
19626             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
19627             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
19628           }
19629           eqp_render(pArg, 0);
19630         }
19631         sqlite3_finalize(pExplain);
19632         sqlite3_free(zEQP);
19633         if( pArg->autoEQP>=AUTOEQP_full ){
19634           /* Also do an EXPLAIN for ".eqp full" mode */
19635           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
19636           shell_check_oom(zEQP);
19637           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
19638           if( rc==SQLITE_OK ){
19639             pArg->cMode = MODE_Explain;
19640             explain_data_prepare(pArg, pExplain);
19641             exec_prepared_stmt(pArg, pExplain);
19642             explain_data_delete(pArg);
19643           }
19644           sqlite3_finalize(pExplain);
19645           sqlite3_free(zEQP);
19646         }
19647         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
19648           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
19649           /* Reprepare pStmt before reactiving trace modes */
19650           sqlite3_finalize(pStmt);
19651           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
19652           if( pArg ) pArg->pStmt = pStmt;
19653         }
19654         restore_debug_trace_modes();
19655       }
19656 
19657       if( pArg ){
19658         pArg->cMode = pArg->mode;
19659         if( pArg->autoExplain ){
19660           if( sqlite3_stmt_isexplain(pStmt)==1 ){
19661             pArg->cMode = MODE_Explain;
19662           }
19663           if( sqlite3_stmt_isexplain(pStmt)==2 ){
19664             pArg->cMode = MODE_EQP;
19665           }
19666         }
19667 
19668         /* If the shell is currently in ".explain" mode, gather the extra
19669         ** data required to add indents to the output.*/
19670         if( pArg->cMode==MODE_Explain ){
19671           explain_data_prepare(pArg, pStmt);
19672         }
19673       }
19674 
19675       bind_prepared_stmt(pArg, pStmt);
19676       exec_prepared_stmt(pArg, pStmt);
19677       explain_data_delete(pArg);
19678       eqp_render(pArg, 0);
19679 
19680       /* print usage stats if stats on */
19681       if( pArg && pArg->statsOn ){
19682         display_stats(db, pArg, 0);
19683       }
19684 
19685       /* print loop-counters if required */
19686       if( pArg && pArg->scanstatsOn ){
19687         display_scanstats(db, pArg);
19688       }
19689 
19690       /* Finalize the statement just executed. If this fails, save a
19691       ** copy of the error message. Otherwise, set zSql to point to the
19692       ** next statement to execute. */
19693       rc2 = sqlite3_finalize(pStmt);
19694       if( rc!=SQLITE_NOMEM ) rc = rc2;
19695       if( rc==SQLITE_OK ){
19696         zSql = zLeftover;
19697         while( IsSpace(zSql[0]) ) zSql++;
19698       }else if( pzErrMsg ){
19699         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
19700       }
19701 
19702       /* clear saved stmt handle */
19703       if( pArg ){
19704         pArg->pStmt = NULL;
19705       }
19706     }
19707   } /* end while */
19708 
19709   return rc;
19710 }
19711 
19712 /*
19713 ** Release memory previously allocated by tableColumnList().
19714 */
19715 static void freeColumnList(char **azCol){
19716   int i;
19717   for(i=1; azCol[i]; i++){
19718     sqlite3_free(azCol[i]);
19719   }
19720   /* azCol[0] is a static string */
19721   sqlite3_free(azCol);
19722 }
19723 
19724 /*
19725 ** Return a list of pointers to strings which are the names of all
19726 ** columns in table zTab.   The memory to hold the names is dynamically
19727 ** allocated and must be released by the caller using a subsequent call
19728 ** to freeColumnList().
19729 **
19730 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
19731 ** value that needs to be preserved, then azCol[0] is filled in with the
19732 ** name of the rowid column.
19733 **
19734 ** The first regular column in the table is azCol[1].  The list is terminated
19735 ** by an entry with azCol[i]==0.
19736 */
19737 static char **tableColumnList(ShellState *p, const char *zTab){
19738   char **azCol = 0;
19739   sqlite3_stmt *pStmt;
19740   char *zSql;
19741   int nCol = 0;
19742   int nAlloc = 0;
19743   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
19744   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
19745   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
19746   int rc;
19747 
19748   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
19749   shell_check_oom(zSql);
19750   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19751   sqlite3_free(zSql);
19752   if( rc ) return 0;
19753   while( sqlite3_step(pStmt)==SQLITE_ROW ){
19754     if( nCol>=nAlloc-2 ){
19755       nAlloc = nAlloc*2 + nCol + 10;
19756       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
19757       shell_check_oom(azCol);
19758     }
19759     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
19760     shell_check_oom(azCol[nCol]);
19761     if( sqlite3_column_int(pStmt, 5) ){
19762       nPK++;
19763       if( nPK==1
19764        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
19765                           "INTEGER")==0
19766       ){
19767         isIPK = 1;
19768       }else{
19769         isIPK = 0;
19770       }
19771     }
19772   }
19773   sqlite3_finalize(pStmt);
19774   if( azCol==0 ) return 0;
19775   azCol[0] = 0;
19776   azCol[nCol+1] = 0;
19777 
19778   /* The decision of whether or not a rowid really needs to be preserved
19779   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
19780   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
19781   ** rowids on tables where the rowid is inaccessible because there are other
19782   ** columns in the table named "rowid", "_rowid_", and "oid".
19783   */
19784   if( preserveRowid && isIPK ){
19785     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
19786     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
19787     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
19788     ** ROWID aliases.  To distinguish these cases, check to see if
19789     ** there is a "pk" entry in "PRAGMA index_list".  There will be
19790     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
19791     */
19792     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
19793                            " WHERE origin='pk'", zTab);
19794     shell_check_oom(zSql);
19795     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19796     sqlite3_free(zSql);
19797     if( rc ){
19798       freeColumnList(azCol);
19799       return 0;
19800     }
19801     rc = sqlite3_step(pStmt);
19802     sqlite3_finalize(pStmt);
19803     preserveRowid = rc==SQLITE_ROW;
19804   }
19805   if( preserveRowid ){
19806     /* Only preserve the rowid if we can find a name to use for the
19807     ** rowid */
19808     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
19809     int i, j;
19810     for(j=0; j<3; j++){
19811       for(i=1; i<=nCol; i++){
19812         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
19813       }
19814       if( i>nCol ){
19815         /* At this point, we know that azRowid[j] is not the name of any
19816         ** ordinary column in the table.  Verify that azRowid[j] is a valid
19817         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
19818         ** tables will fail this last check */
19819         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
19820         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
19821         break;
19822       }
19823     }
19824   }
19825   return azCol;
19826 }
19827 
19828 /*
19829 ** Toggle the reverse_unordered_selects setting.
19830 */
19831 static void toggleSelectOrder(sqlite3 *db){
19832   sqlite3_stmt *pStmt = 0;
19833   int iSetting = 0;
19834   char zStmt[100];
19835   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
19836   if( sqlite3_step(pStmt)==SQLITE_ROW ){
19837     iSetting = sqlite3_column_int(pStmt, 0);
19838   }
19839   sqlite3_finalize(pStmt);
19840   sqlite3_snprintf(sizeof(zStmt), zStmt,
19841        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
19842   sqlite3_exec(db, zStmt, 0, 0, 0);
19843 }
19844 
19845 /*
19846 ** This is a different callback routine used for dumping the database.
19847 ** Each row received by this callback consists of a table name,
19848 ** the table type ("index" or "table") and SQL to create the table.
19849 ** This routine should print text sufficient to recreate the table.
19850 */
19851 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
19852   int rc;
19853   const char *zTable;
19854   const char *zType;
19855   const char *zSql;
19856   ShellState *p = (ShellState *)pArg;
19857   int dataOnly;
19858   int noSys;
19859 
19860   UNUSED_PARAMETER(azNotUsed);
19861   if( nArg!=3 || azArg==0 ) return 0;
19862   zTable = azArg[0];
19863   zType = azArg[1];
19864   zSql = azArg[2];
19865   if( zTable==0 ) return 0;
19866   if( zType==0 ) return 0;
19867   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
19868   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
19869 
19870   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
19871     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
19872   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
19873     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19874   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
19875     return 0;
19876   }else if( dataOnly ){
19877     /* no-op */
19878   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
19879     char *zIns;
19880     if( !p->writableSchema ){
19881       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
19882       p->writableSchema = 1;
19883     }
19884     zIns = sqlite3_mprintf(
19885        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
19886        "VALUES('table','%q','%q',0,'%q');",
19887        zTable, zTable, zSql);
19888     shell_check_oom(zIns);
19889     utf8_printf(p->out, "%s\n", zIns);
19890     sqlite3_free(zIns);
19891     return 0;
19892   }else{
19893     printSchemaLine(p->out, zSql, ";\n");
19894   }
19895 
19896   if( cli_strcmp(zType, "table")==0 ){
19897     ShellText sSelect;
19898     ShellText sTable;
19899     char **azCol;
19900     int i;
19901     char *savedDestTable;
19902     int savedMode;
19903 
19904     azCol = tableColumnList(p, zTable);
19905     if( azCol==0 ){
19906       p->nErr++;
19907       return 0;
19908     }
19909 
19910     /* Always quote the table name, even if it appears to be pure ascii,
19911     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
19912     initText(&sTable);
19913     appendText(&sTable, zTable, quoteChar(zTable));
19914     /* If preserving the rowid, add a column list after the table name.
19915     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
19916     ** instead of the usual "INSERT INTO tab VALUES(...)".
19917     */
19918     if( azCol[0] ){
19919       appendText(&sTable, "(", 0);
19920       appendText(&sTable, azCol[0], 0);
19921       for(i=1; azCol[i]; i++){
19922         appendText(&sTable, ",", 0);
19923         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
19924       }
19925       appendText(&sTable, ")", 0);
19926     }
19927 
19928     /* Build an appropriate SELECT statement */
19929     initText(&sSelect);
19930     appendText(&sSelect, "SELECT ", 0);
19931     if( azCol[0] ){
19932       appendText(&sSelect, azCol[0], 0);
19933       appendText(&sSelect, ",", 0);
19934     }
19935     for(i=1; azCol[i]; i++){
19936       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
19937       if( azCol[i+1] ){
19938         appendText(&sSelect, ",", 0);
19939       }
19940     }
19941     freeColumnList(azCol);
19942     appendText(&sSelect, " FROM ", 0);
19943     appendText(&sSelect, zTable, quoteChar(zTable));
19944 
19945     savedDestTable = p->zDestTable;
19946     savedMode = p->mode;
19947     p->zDestTable = sTable.z;
19948     p->mode = p->cMode = MODE_Insert;
19949     rc = shell_exec(p, sSelect.z, 0);
19950     if( (rc&0xff)==SQLITE_CORRUPT ){
19951       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
19952       toggleSelectOrder(p->db);
19953       shell_exec(p, sSelect.z, 0);
19954       toggleSelectOrder(p->db);
19955     }
19956     p->zDestTable = savedDestTable;
19957     p->mode = savedMode;
19958     freeText(&sTable);
19959     freeText(&sSelect);
19960     if( rc ) p->nErr++;
19961   }
19962   return 0;
19963 }
19964 
19965 /*
19966 ** Run zQuery.  Use dump_callback() as the callback routine so that
19967 ** the contents of the query are output as SQL statements.
19968 **
19969 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
19970 ** "ORDER BY rowid DESC" to the end.
19971 */
19972 static int run_schema_dump_query(
19973   ShellState *p,
19974   const char *zQuery
19975 ){
19976   int rc;
19977   char *zErr = 0;
19978   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
19979   if( rc==SQLITE_CORRUPT ){
19980     char *zQ2;
19981     int len = strlen30(zQuery);
19982     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
19983     if( zErr ){
19984       utf8_printf(p->out, "/****** %s ******/\n", zErr);
19985       sqlite3_free(zErr);
19986       zErr = 0;
19987     }
19988     zQ2 = malloc( len+100 );
19989     if( zQ2==0 ) return rc;
19990     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
19991     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
19992     if( rc ){
19993       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
19994     }else{
19995       rc = SQLITE_CORRUPT;
19996     }
19997     sqlite3_free(zErr);
19998     free(zQ2);
19999   }
20000   return rc;
20001 }
20002 
20003 /*
20004 ** Text of help messages.
20005 **
20006 ** The help text for each individual command begins with a line that starts
20007 ** with ".".  Subsequent lines are supplemental information.
20008 **
20009 ** There must be two or more spaces between the end of the command and the
20010 ** start of the description of what that command does.
20011 */
20012 static const char *(azHelp[]) = {
20013 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
20014   && !defined(SQLITE_SHELL_FIDDLE)
20015   ".archive ...             Manage SQL archives",
20016   "   Each command must have exactly one of the following options:",
20017   "     -c, --create               Create a new archive",
20018   "     -u, --update               Add or update files with changed mtime",
20019   "     -i, --insert               Like -u but always add even if unchanged",
20020   "     -r, --remove               Remove files from archive",
20021   "     -t, --list                 List contents of archive",
20022   "     -x, --extract              Extract files from archive",
20023   "   Optional arguments:",
20024   "     -v, --verbose              Print each filename as it is processed",
20025   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
20026   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
20027   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
20028   "     -g, --glob                 Use glob matching for names in archive",
20029   "     -n, --dryrun               Show the SQL that would have occurred",
20030   "   Examples:",
20031   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
20032   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
20033   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
20034   "   See also:",
20035   "      http://sqlite.org/cli.html#sqlite_archive_support",
20036 #endif
20037 #ifndef SQLITE_OMIT_AUTHORIZATION
20038   ".auth ON|OFF             Show authorizer callbacks",
20039 #endif
20040 #ifndef SQLITE_SHELL_FIDDLE
20041   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
20042   "   Options:",
20043   "       --append            Use the appendvfs",
20044   "       --async             Write to FILE without journal and fsync()",
20045 #endif
20046   ".bail on|off             Stop after hitting an error.  Default OFF",
20047   ".binary on|off           Turn binary output on or off.  Default OFF",
20048 #ifndef SQLITE_SHELL_FIDDLE
20049   ".cd DIRECTORY            Change the working directory to DIRECTORY",
20050 #endif
20051   ".changes on|off          Show number of rows changed by SQL",
20052 #ifndef SQLITE_SHELL_FIDDLE
20053   ".check GLOB              Fail if output since .testcase does not match",
20054   ".clone NEWDB             Clone data into NEWDB from the existing database",
20055 #endif
20056   ".connection [close] [#]  Open or close an auxiliary database connection",
20057   ".databases               List names and files of attached databases",
20058   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
20059 #if SQLITE_SHELL_HAVE_RECOVER
20060   ".dbinfo ?DB?             Show status information about the database",
20061 #endif
20062   ".dump ?OBJECTS?          Render database content as SQL",
20063   "   Options:",
20064   "     --data-only            Output only INSERT statements",
20065   "     --newlines             Allow unescaped newline characters in output",
20066   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
20067   "     --preserve-rowids      Include ROWID values in the output",
20068   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
20069   "   Additional LIKE patterns can be given in subsequent arguments",
20070   ".echo on|off             Turn command echo on or off",
20071   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
20072   "   Other Modes:",
20073 #ifdef SQLITE_DEBUG
20074   "      test                  Show raw EXPLAIN QUERY PLAN output",
20075   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
20076 #endif
20077   "      trigger               Like \"full\" but also show trigger bytecode",
20078 #ifndef SQLITE_SHELL_FIDDLE
20079   ".excel                   Display the output of next command in spreadsheet",
20080   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
20081 #endif
20082 #ifndef SQLITE_SHELL_FIDDLE
20083   ".exit ?CODE?             Exit this program with return-code CODE",
20084 #endif
20085   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
20086   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
20087   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
20088   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
20089   "   --help                  Show CMD details",
20090   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
20091   ".headers on|off          Turn display of headers on or off",
20092   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
20093 #ifndef SQLITE_SHELL_FIDDLE
20094   ".import FILE TABLE       Import data from FILE into TABLE",
20095   "   Options:",
20096   "     --ascii               Use \\037 and \\036 as column and row separators",
20097   "     --csv                 Use , and \\n as column and row separators",
20098   "     --skip N              Skip the first N rows of input",
20099   "     --schema S            Target table to be S.TABLE",
20100   "     -v                    \"Verbose\" - increase auxiliary output",
20101   "   Notes:",
20102   "     *  If TABLE does not exist, it is created.  The first row of input",
20103   "        determines the column names.",
20104   "     *  If neither --csv or --ascii are used, the input mode is derived",
20105   "        from the \".mode\" output mode",
20106   "     *  If FILE begins with \"|\" then it is a command that generates the",
20107   "        input text.",
20108 #endif
20109 #ifndef SQLITE_OMIT_TEST_CONTROL
20110   ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
20111 #endif
20112   ".indexes ?TABLE?         Show names of indexes",
20113   "                           If TABLE is specified, only show indexes for",
20114   "                           tables matching TABLE using the LIKE operator.",
20115 #ifdef SQLITE_ENABLE_IOTRACE
20116   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
20117 #endif
20118   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
20119   ".lint OPTIONS            Report potential schema issues.",
20120   "     Options:",
20121   "        fkey-indexes     Find missing foreign key indexes",
20122 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
20123   ".load FILE ?ENTRY?       Load an extension library",
20124 #endif
20125 #if !defined(SQLITE_SHELL_FIDDLE)
20126   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
20127 #else
20128   ".log on|off              Turn logging on or off.",
20129 #endif
20130   ".mode MODE ?OPTIONS?     Set output mode",
20131   "   MODE is one of:",
20132   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
20133   "     box         Tables using unicode box-drawing characters",
20134   "     csv         Comma-separated values",
20135   "     column      Output in columns.  (See .width)",
20136   "     html        HTML <table> code",
20137   "     insert      SQL insert statements for TABLE",
20138   "     json        Results in a JSON array",
20139   "     line        One value per line",
20140   "     list        Values delimited by \"|\"",
20141   "     markdown    Markdown table format",
20142   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
20143   "     quote       Escape answers as for SQL",
20144   "     table       ASCII-art table",
20145   "     tabs        Tab-separated values",
20146   "     tcl         TCL list elements",
20147   "   OPTIONS: (for columnar modes or insert mode):",
20148   "     --wrap N       Wrap output lines to no longer than N characters",
20149   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
20150   "     --ww           Shorthand for \"--wordwrap 1\"",
20151   "     --quote        Quote output text as SQL literals",
20152   "     --noquote      Do not quote output text",
20153   "     TABLE          The name of SQL table used for \"insert\" mode",
20154 #ifndef SQLITE_SHELL_FIDDLE
20155   ".nonce STRING            Suspend safe mode for one command if nonce matches",
20156 #endif
20157   ".nullvalue STRING        Use STRING in place of NULL values",
20158 #ifndef SQLITE_SHELL_FIDDLE
20159   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
20160   "     If FILE begins with '|' then open as a pipe",
20161   "       --bom  Put a UTF8 byte-order mark at the beginning",
20162   "       -e     Send output to the system text editor",
20163   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
20164   /* Note that .open is (partially) available in WASM builds but is
20165   ** currently only intended to be used by the fiddle tool, not
20166   ** end users, so is "undocumented." */
20167   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
20168   "     Options:",
20169   "        --append        Use appendvfs to append database to the end of FILE",
20170 #endif
20171 #ifndef SQLITE_OMIT_DESERIALIZE
20172   "        --deserialize   Load into memory using sqlite3_deserialize()",
20173   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
20174   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
20175 #endif
20176   "        --new           Initialize FILE to an empty database",
20177   "        --nofollow      Do not follow symbolic links",
20178   "        --readonly      Open FILE readonly",
20179   "        --zip           FILE is a ZIP archive",
20180 #ifndef SQLITE_SHELL_FIDDLE
20181   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
20182   "   If FILE begins with '|' then open it as a pipe.",
20183   "   Options:",
20184   "     --bom                 Prefix output with a UTF8 byte-order mark",
20185   "     -e                    Send output to the system text editor",
20186   "     -x                    Send output as CSV to a spreadsheet",
20187 #endif
20188   ".parameter CMD ...       Manage SQL parameter bindings",
20189   "   clear                   Erase all bindings",
20190   "   init                    Initialize the TEMP table that holds bindings",
20191   "   list                    List the current parameter bindings",
20192   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
20193   "                           PARAMETER should start with one of: $ : @ ?",
20194   "   unset PARAMETER         Remove PARAMETER from the binding table",
20195   ".print STRING...         Print literal STRING",
20196 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
20197   ".progress N              Invoke progress handler after every N opcodes",
20198   "   --limit N                 Interrupt after N progress callbacks",
20199   "   --once                    Do no more than one progress interrupt",
20200   "   --quiet|-q                No output except at interrupts",
20201   "   --reset                   Reset the count for each input and interrupt",
20202 #endif
20203   ".prompt MAIN CONTINUE    Replace the standard prompts",
20204 #ifndef SQLITE_SHELL_FIDDLE
20205   ".quit                    Stop interpreting input stream, exit if primary.",
20206   ".read FILE               Read input from FILE or command output",
20207   "    If FILE begins with \"|\", it is a command that generates the input.",
20208 #endif
20209 #if SQLITE_SHELL_HAVE_RECOVER
20210   ".recover                 Recover as much data as possible from corrupt db.",
20211   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
20212   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
20213   "   --no-rowids              Do not attempt to recover rowid values",
20214   "                            that are not also INTEGER PRIMARY KEYs",
20215 #endif
20216 #ifndef SQLITE_SHELL_FIDDLE
20217   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
20218   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
20219 #endif
20220   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
20221   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
20222   "   Options:",
20223   "      --indent             Try to pretty-print the schema",
20224   "      --nosys              Omit objects whose names start with \"sqlite_\"",
20225   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
20226   "    Options:",
20227   "       --init               Create a new SELFTEST table",
20228   "       -v                   Verbose output",
20229   ".separator COL ?ROW?     Change the column and row separators",
20230 #if defined(SQLITE_ENABLE_SESSION)
20231   ".session ?NAME? CMD ...  Create or control sessions",
20232   "   Subcommands:",
20233   "     attach TABLE             Attach TABLE",
20234   "     changeset FILE           Write a changeset into FILE",
20235   "     close                    Close one session",
20236   "     enable ?BOOLEAN?         Set or query the enable bit",
20237   "     filter GLOB...           Reject tables matching GLOBs",
20238   "     indirect ?BOOLEAN?       Mark or query the indirect status",
20239   "     isempty                  Query whether the session is empty",
20240   "     list                     List currently open session names",
20241   "     open DB NAME             Open a new session on DB",
20242   "     patchset FILE            Write a patchset into FILE",
20243   "   If ?NAME? is omitted, the first defined session is used.",
20244 #endif
20245   ".sha3sum ...             Compute a SHA3 hash of database content",
20246   "    Options:",
20247   "      --schema              Also hash the sqlite_schema table",
20248   "      --sha3-224            Use the sha3-224 algorithm",
20249   "      --sha3-256            Use the sha3-256 algorithm (default)",
20250   "      --sha3-384            Use the sha3-384 algorithm",
20251   "      --sha3-512            Use the sha3-512 algorithm",
20252   "    Any other argument is a LIKE pattern for tables to hash",
20253 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
20254   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
20255 #endif
20256   ".show                    Show the current values for various settings",
20257   ".stats ?ARG?             Show stats or turn stats on or off",
20258   "   off                      Turn off automatic stat display",
20259   "   on                       Turn on automatic stat display",
20260   "   stmt                     Show statement stats",
20261   "   vmstep                   Show the virtual machine step count only",
20262 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
20263   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
20264 #endif
20265   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
20266 #ifndef SQLITE_SHELL_FIDDLE
20267   ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
20268 #endif
20269   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
20270   "                           Run \".testctrl\" with no arguments for details",
20271   ".timeout MS              Try opening locked tables for MS milliseconds",
20272   ".timer on|off            Turn SQL timer on or off",
20273 #ifndef SQLITE_OMIT_TRACE
20274   ".trace ?OPTIONS?         Output each SQL statement as it is run",
20275   "    FILE                    Send output to FILE",
20276   "    stdout                  Send output to stdout",
20277   "    stderr                  Send output to stderr",
20278   "    off                     Disable tracing",
20279   "    --expanded              Expand query parameters",
20280 #ifdef SQLITE_ENABLE_NORMALIZE
20281   "    --normalized            Normal the SQL statements",
20282 #endif
20283   "    --plain                 Show SQL as it is input",
20284   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
20285   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
20286   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
20287   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
20288 #endif /* SQLITE_OMIT_TRACE */
20289 #ifdef SQLITE_DEBUG
20290   ".unmodule NAME ...       Unregister virtual table modules",
20291   "    --allexcept             Unregister everything except those named",
20292 #endif
20293   ".version                 Show source, library and compiler versions",
20294   ".vfsinfo ?AUX?           Information about the top-level VFS",
20295   ".vfslist                 List all available VFSes",
20296   ".vfsname ?AUX?           Print the name of the VFS stack",
20297   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
20298   "     Negative values right-justify",
20299 };
20300 
20301 /*
20302 ** Output help text.
20303 **
20304 ** zPattern describes the set of commands for which help text is provided.
20305 ** If zPattern is NULL, then show all commands, but only give a one-line
20306 ** description of each.
20307 **
20308 ** Return the number of matches.
20309 */
20310 static int showHelp(FILE *out, const char *zPattern){
20311   int i = 0;
20312   int j = 0;
20313   int n = 0;
20314   char *zPat;
20315   if( zPattern==0
20316    || zPattern[0]=='0'
20317    || cli_strcmp(zPattern,"-a")==0
20318    || cli_strcmp(zPattern,"-all")==0
20319    || cli_strcmp(zPattern,"--all")==0
20320   ){
20321     enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
20322     enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
20323     /* Show all or most commands
20324     ** *zPattern==0   => summary of documented commands only
20325     ** *zPattern=='0' => whole help for undocumented commands
20326     ** Otherwise      => whole help for documented commands
20327     */
20328     enum HelpWanted hw = HW_SummaryOnly;
20329     enum HelpHave hh = HH_More;
20330     if( zPattern!=0 ){
20331       hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
20332     }
20333     for(i=0; i<ArraySize(azHelp); i++){
20334       switch( azHelp[i][0] ){
20335       case ',':
20336         hh = HH_Summary|HH_Undoc;
20337         break;
20338       case '.':
20339         hh = HH_Summary;
20340         break;
20341       default:
20342         hh &= ~HH_Summary;
20343         break;
20344       }
20345       if( ((hw^hh)&HH_Undoc)==0 ){
20346         if( (hh&HH_Summary)!=0 ){
20347           utf8_printf(out, ".%s\n", azHelp[i]+1);
20348           ++n;
20349         }else if( (hw&HW_SummaryOnly)==0 ){
20350           utf8_printf(out, "%s\n", azHelp[i]);
20351         }
20352       }
20353     }
20354   }else{
20355     /* Seek documented commands for which zPattern is an exact prefix */
20356     zPat = sqlite3_mprintf(".%s*", zPattern);
20357     shell_check_oom(zPat);
20358     for(i=0; i<ArraySize(azHelp); i++){
20359       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
20360         utf8_printf(out, "%s\n", azHelp[i]);
20361         j = i+1;
20362         n++;
20363       }
20364     }
20365     sqlite3_free(zPat);
20366     if( n ){
20367       if( n==1 ){
20368         /* when zPattern is a prefix of exactly one command, then include
20369         ** the details of that command, which should begin at offset j */
20370         while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
20371           utf8_printf(out, "%s\n", azHelp[j]);
20372           j++;
20373         }
20374       }
20375       return n;
20376     }
20377     /* Look for documented commands that contain zPattern anywhere.
20378     ** Show complete text of all documented commands that match. */
20379     zPat = sqlite3_mprintf("%%%s%%", zPattern);
20380     shell_check_oom(zPat);
20381     for(i=0; i<ArraySize(azHelp); i++){
20382       if( azHelp[i][0]==',' ){
20383         while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
20384         continue;
20385       }
20386       if( azHelp[i][0]=='.' ) j = i;
20387       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
20388         utf8_printf(out, "%s\n", azHelp[j]);
20389         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
20390           j++;
20391           utf8_printf(out, "%s\n", azHelp[j]);
20392         }
20393         i = j;
20394         n++;
20395       }
20396     }
20397     sqlite3_free(zPat);
20398   }
20399   return n;
20400 }
20401 
20402 /* Forward reference */
20403 static int process_input(ShellState *p);
20404 
20405 /*
20406 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
20407 ** and return a pointer to the buffer. The caller is responsible for freeing
20408 ** the memory.
20409 **
20410 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
20411 ** read.
20412 **
20413 ** For convenience, a nul-terminator byte is always appended to the data read
20414 ** from the file before the buffer is returned. This byte is not included in
20415 ** the final value of (*pnByte), if applicable.
20416 **
20417 ** NULL is returned if any error is encountered. The final value of *pnByte
20418 ** is undefined in this case.
20419 */
20420 static char *readFile(const char *zName, int *pnByte){
20421   FILE *in = fopen(zName, "rb");
20422   long nIn;
20423   size_t nRead;
20424   char *pBuf;
20425   int rc;
20426   if( in==0 ) return 0;
20427   rc = fseek(in, 0, SEEK_END);
20428   if( rc!=0 ){
20429     raw_printf(stderr, "Error: '%s' not seekable\n", zName);
20430     fclose(in);
20431     return 0;
20432   }
20433   nIn = ftell(in);
20434   rewind(in);
20435   pBuf = sqlite3_malloc64( nIn+1 );
20436   if( pBuf==0 ){
20437     raw_printf(stderr, "Error: out of memory\n");
20438     fclose(in);
20439     return 0;
20440   }
20441   nRead = fread(pBuf, nIn, 1, in);
20442   fclose(in);
20443   if( nRead!=1 ){
20444     sqlite3_free(pBuf);
20445     raw_printf(stderr, "Error: cannot read '%s'\n", zName);
20446     return 0;
20447   }
20448   pBuf[nIn] = 0;
20449   if( pnByte ) *pnByte = nIn;
20450   return pBuf;
20451 }
20452 
20453 #if defined(SQLITE_ENABLE_SESSION)
20454 /*
20455 ** Close a single OpenSession object and release all of its associated
20456 ** resources.
20457 */
20458 static void session_close(OpenSession *pSession){
20459   int i;
20460   sqlite3session_delete(pSession->p);
20461   sqlite3_free(pSession->zName);
20462   for(i=0; i<pSession->nFilter; i++){
20463     sqlite3_free(pSession->azFilter[i]);
20464   }
20465   sqlite3_free(pSession->azFilter);
20466   memset(pSession, 0, sizeof(OpenSession));
20467 }
20468 #endif
20469 
20470 /*
20471 ** Close all OpenSession objects and release all associated resources.
20472 */
20473 #if defined(SQLITE_ENABLE_SESSION)
20474 static void session_close_all(ShellState *p, int i){
20475   int j;
20476   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
20477   for(j=0; j<pAuxDb->nSession; j++){
20478     session_close(&pAuxDb->aSession[j]);
20479   }
20480   pAuxDb->nSession = 0;
20481 }
20482 #else
20483 # define session_close_all(X,Y)
20484 #endif
20485 
20486 /*
20487 ** Implementation of the xFilter function for an open session.  Omit
20488 ** any tables named by ".session filter" but let all other table through.
20489 */
20490 #if defined(SQLITE_ENABLE_SESSION)
20491 static int session_filter(void *pCtx, const char *zTab){
20492   OpenSession *pSession = (OpenSession*)pCtx;
20493   int i;
20494   for(i=0; i<pSession->nFilter; i++){
20495     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
20496   }
20497   return 1;
20498 }
20499 #endif
20500 
20501 /*
20502 ** Try to deduce the type of file for zName based on its content.  Return
20503 ** one of the SHELL_OPEN_* constants.
20504 **
20505 ** If the file does not exist or is empty but its name looks like a ZIP
20506 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
20507 ** Otherwise, assume an ordinary database regardless of the filename if
20508 ** the type cannot be determined from content.
20509 */
20510 int deduceDatabaseType(const char *zName, int dfltZip){
20511   FILE *f = fopen(zName, "rb");
20512   size_t n;
20513   int rc = SHELL_OPEN_UNSPEC;
20514   char zBuf[100];
20515   if( f==0 ){
20516     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
20517        return SHELL_OPEN_ZIPFILE;
20518     }else{
20519        return SHELL_OPEN_NORMAL;
20520     }
20521   }
20522   n = fread(zBuf, 16, 1, f);
20523   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
20524     fclose(f);
20525     return SHELL_OPEN_NORMAL;
20526   }
20527   fseek(f, -25, SEEK_END);
20528   n = fread(zBuf, 25, 1, f);
20529   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
20530     rc = SHELL_OPEN_APPENDVFS;
20531   }else{
20532     fseek(f, -22, SEEK_END);
20533     n = fread(zBuf, 22, 1, f);
20534     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
20535        && zBuf[3]==0x06 ){
20536       rc = SHELL_OPEN_ZIPFILE;
20537     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
20538       rc = SHELL_OPEN_ZIPFILE;
20539     }
20540   }
20541   fclose(f);
20542   return rc;
20543 }
20544 
20545 #ifndef SQLITE_OMIT_DESERIALIZE
20546 /*
20547 ** Reconstruct an in-memory database using the output from the "dbtotxt"
20548 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
20549 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
20550 */
20551 static unsigned char *readHexDb(ShellState *p, int *pnData){
20552   unsigned char *a = 0;
20553   int nLine;
20554   int n = 0;
20555   int pgsz = 0;
20556   int iOffset = 0;
20557   int j, k;
20558   int rc;
20559   FILE *in;
20560   const char *zDbFilename = p->pAuxDb->zDbFilename;
20561   unsigned int x[16];
20562   char zLine[1000];
20563   if( zDbFilename ){
20564     in = fopen(zDbFilename, "r");
20565     if( in==0 ){
20566       utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
20567       return 0;
20568     }
20569     nLine = 0;
20570   }else{
20571     in = p->in;
20572     nLine = p->lineno;
20573     if( in==0 ) in = stdin;
20574   }
20575   *pnData = 0;
20576   nLine++;
20577   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
20578   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
20579   if( rc!=2 ) goto readHexDb_error;
20580   if( n<0 ) goto readHexDb_error;
20581   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
20582   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
20583   a = sqlite3_malloc( n ? n : 1 );
20584   shell_check_oom(a);
20585   memset(a, 0, n);
20586   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
20587     utf8_printf(stderr, "invalid pagesize\n");
20588     goto readHexDb_error;
20589   }
20590   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
20591     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
20592     if( rc==2 ){
20593       iOffset = k;
20594       continue;
20595     }
20596     if( cli_strncmp(zLine, "| end ", 6)==0 ){
20597       break;
20598     }
20599     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
20600                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
20601                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
20602     if( rc==17 ){
20603       k = iOffset+j;
20604       if( k+16<=n && k>=0 ){
20605         int ii;
20606         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
20607       }
20608     }
20609   }
20610   *pnData = n;
20611   if( in!=p->in ){
20612     fclose(in);
20613   }else{
20614     p->lineno = nLine;
20615   }
20616   return a;
20617 
20618 readHexDb_error:
20619   if( in!=p->in ){
20620     fclose(in);
20621   }else{
20622     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
20623       nLine++;
20624       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
20625     }
20626     p->lineno = nLine;
20627   }
20628   sqlite3_free(a);
20629   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
20630   return 0;
20631 }
20632 #endif /* SQLITE_OMIT_DESERIALIZE */
20633 
20634 /*
20635 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
20636 */
20637 static void shellUSleepFunc(
20638   sqlite3_context *context,
20639   int argcUnused,
20640   sqlite3_value **argv
20641 ){
20642   int sleep = sqlite3_value_int(argv[0]);
20643   (void)argcUnused;
20644   sqlite3_sleep(sleep/1000);
20645   sqlite3_result_int(context, sleep);
20646 }
20647 
20648 /* Flags for open_db().
20649 **
20650 ** The default behavior of open_db() is to exit(1) if the database fails to
20651 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
20652 ** but still returns without calling exit.
20653 **
20654 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
20655 ** ZIP archive if the file does not exist or is empty and its name matches
20656 ** the *.zip pattern.
20657 */
20658 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
20659 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
20660 
20661 /*
20662 ** Make sure the database is open.  If it is not, then open it.  If
20663 ** the database fails to open, print an error message and exit.
20664 */
20665 static void open_db(ShellState *p, int openFlags){
20666   if( p->db==0 ){
20667     const char *zDbFilename = p->pAuxDb->zDbFilename;
20668     if( p->openMode==SHELL_OPEN_UNSPEC ){
20669       if( zDbFilename==0 || zDbFilename[0]==0 ){
20670         p->openMode = SHELL_OPEN_NORMAL;
20671       }else{
20672         p->openMode = (u8)deduceDatabaseType(zDbFilename,
20673                              (openFlags & OPEN_DB_ZIPFILE)!=0);
20674       }
20675     }
20676     switch( p->openMode ){
20677       case SHELL_OPEN_APPENDVFS: {
20678         sqlite3_open_v2(zDbFilename, &p->db,
20679            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
20680         break;
20681       }
20682       case SHELL_OPEN_HEXDB:
20683       case SHELL_OPEN_DESERIALIZE: {
20684         sqlite3_open(0, &p->db);
20685         break;
20686       }
20687       case SHELL_OPEN_ZIPFILE: {
20688         sqlite3_open(":memory:", &p->db);
20689         break;
20690       }
20691       case SHELL_OPEN_READONLY: {
20692         sqlite3_open_v2(zDbFilename, &p->db,
20693             SQLITE_OPEN_READONLY|p->openFlags, 0);
20694         break;
20695       }
20696       case SHELL_OPEN_UNSPEC:
20697       case SHELL_OPEN_NORMAL: {
20698         sqlite3_open_v2(zDbFilename, &p->db,
20699            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
20700         break;
20701       }
20702     }
20703     globalDb = p->db;
20704     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
20705       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
20706           zDbFilename, sqlite3_errmsg(p->db));
20707       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
20708         exit(1);
20709       }
20710       sqlite3_close(p->db);
20711       sqlite3_open(":memory:", &p->db);
20712       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
20713         utf8_printf(stderr,
20714           "Also: unable to open substitute in-memory database.\n"
20715         );
20716         exit(1);
20717       }else{
20718         utf8_printf(stderr,
20719           "Notice: using substitute in-memory database instead of \"%s\"\n",
20720           zDbFilename);
20721       }
20722     }
20723     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
20724 
20725     /* Reflect the use or absence of --unsafe-testing invocation. */
20726     {
20727       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
20728       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
20729       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
20730     }
20731 
20732 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20733     sqlite3_enable_load_extension(p->db, 1);
20734 #endif
20735     sqlite3_shathree_init(p->db, 0, 0);
20736     sqlite3_uint_init(p->db, 0, 0);
20737     sqlite3_decimal_init(p->db, 0, 0);
20738     sqlite3_base64_init(p->db, 0, 0);
20739     sqlite3_base85_init(p->db, 0, 0);
20740     sqlite3_regexp_init(p->db, 0, 0);
20741     sqlite3_ieee_init(p->db, 0, 0);
20742     sqlite3_series_init(p->db, 0, 0);
20743 #ifndef SQLITE_SHELL_FIDDLE
20744     sqlite3_fileio_init(p->db, 0, 0);
20745     sqlite3_completion_init(p->db, 0, 0);
20746 #endif
20747 #ifdef SQLITE_HAVE_ZLIB
20748     if( !p->bSafeModePersist ){
20749       sqlite3_zipfile_init(p->db, 0, 0);
20750       sqlite3_sqlar_init(p->db, 0, 0);
20751     }
20752 #endif
20753 #ifdef SQLITE_SHELL_EXTFUNCS
20754     /* Create a preprocessing mechanism for extensions to make
20755      * their own provisions for being built into the shell.
20756      * This is a short-span macro. See further below for usage.
20757      */
20758 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
20759 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
20760     /* Let custom-included extensions get their ..._init() called.
20761      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
20762      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
20763      * inititialization routine to be called.
20764      */
20765     {
20766       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
20767     /* Let custom-included extensions expose their functionality.
20768      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
20769      * the SQL functions, virtual tables, collating sequences or
20770      * VFS's implemented by the extension to be registered.
20771      */
20772       if( irc==SQLITE_OK
20773           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
20774         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
20775       }
20776 #undef SHELL_SUB_MACRO
20777 #undef SHELL_SUBMACRO
20778     }
20779 #endif
20780 
20781     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
20782                             shellAddSchemaName, 0, 0);
20783     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
20784                             shellModuleSchema, 0, 0);
20785     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
20786                             shellPutsFunc, 0, 0);
20787     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
20788                             shellUSleepFunc, 0, 0);
20789 #ifndef SQLITE_NOHAVE_SYSTEM
20790     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
20791                             editFunc, 0, 0);
20792     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
20793                             editFunc, 0, 0);
20794 #endif
20795 
20796     if( p->openMode==SHELL_OPEN_ZIPFILE ){
20797       char *zSql = sqlite3_mprintf(
20798          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
20799       shell_check_oom(zSql);
20800       sqlite3_exec(p->db, zSql, 0, 0, 0);
20801       sqlite3_free(zSql);
20802     }
20803 #ifndef SQLITE_OMIT_DESERIALIZE
20804     else
20805     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
20806       int rc;
20807       int nData = 0;
20808       unsigned char *aData;
20809       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
20810         aData = (unsigned char*)readFile(zDbFilename, &nData);
20811       }else{
20812         aData = readHexDb(p, &nData);
20813       }
20814       if( aData==0 ){
20815         return;
20816       }
20817       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
20818                    SQLITE_DESERIALIZE_RESIZEABLE |
20819                    SQLITE_DESERIALIZE_FREEONCLOSE);
20820       if( rc ){
20821         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
20822       }
20823       if( p->szMax>0 ){
20824         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
20825       }
20826     }
20827 #endif
20828   }
20829   if( p->db!=0 ){
20830     if( p->bSafeModePersist ){
20831       sqlite3_set_authorizer(p->db, safeModeAuth, p);
20832     }
20833     sqlite3_db_config(
20834         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
20835     );
20836   }
20837 }
20838 
20839 /*
20840 ** Attempt to close the databaes connection.  Report errors.
20841 */
20842 void close_db(sqlite3 *db){
20843   int rc = sqlite3_close(db);
20844   if( rc ){
20845     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
20846         rc, sqlite3_errmsg(db));
20847   }
20848 }
20849 
20850 #if HAVE_READLINE || HAVE_EDITLINE
20851 /*
20852 ** Readline completion callbacks
20853 */
20854 static char *readline_completion_generator(const char *text, int state){
20855   static sqlite3_stmt *pStmt = 0;
20856   char *zRet;
20857   if( state==0 ){
20858     char *zSql;
20859     sqlite3_finalize(pStmt);
20860     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
20861                            "  FROM completion(%Q) ORDER BY 1", text);
20862     shell_check_oom(zSql);
20863     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
20864     sqlite3_free(zSql);
20865   }
20866   if( sqlite3_step(pStmt)==SQLITE_ROW ){
20867     const char *z = (const char*)sqlite3_column_text(pStmt,0);
20868     zRet = z ? strdup(z) : 0;
20869   }else{
20870     sqlite3_finalize(pStmt);
20871     pStmt = 0;
20872     zRet = 0;
20873   }
20874   return zRet;
20875 }
20876 static char **readline_completion(const char *zText, int iStart, int iEnd){
20877   (void)iStart;
20878   (void)iEnd;
20879   rl_attempted_completion_over = 1;
20880   return rl_completion_matches(zText, readline_completion_generator);
20881 }
20882 
20883 #elif HAVE_LINENOISE
20884 /*
20885 ** Linenoise completion callback
20886 */
20887 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
20888   i64 nLine = strlen(zLine);
20889   i64 i, iStart;
20890   sqlite3_stmt *pStmt = 0;
20891   char *zSql;
20892   char zBuf[1000];
20893 
20894   if( nLine>(i64)sizeof(zBuf)-30 ) return;
20895   if( zLine[0]=='.' || zLine[0]=='#') return;
20896   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
20897   if( i==nLine-1 ) return;
20898   iStart = i+1;
20899   memcpy(zBuf, zLine, iStart);
20900   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
20901                          "  FROM completion(%Q,%Q) ORDER BY 1",
20902                          &zLine[iStart], zLine);
20903   shell_check_oom(zSql);
20904   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
20905   sqlite3_free(zSql);
20906   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
20907   while( sqlite3_step(pStmt)==SQLITE_ROW ){
20908     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
20909     int nCompletion = sqlite3_column_bytes(pStmt, 0);
20910     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
20911       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
20912       linenoiseAddCompletion(lc, zBuf);
20913     }
20914   }
20915   sqlite3_finalize(pStmt);
20916 }
20917 #endif
20918 
20919 /*
20920 ** Do C-language style dequoting.
20921 **
20922 **    \a    -> alarm
20923 **    \b    -> backspace
20924 **    \t    -> tab
20925 **    \n    -> newline
20926 **    \v    -> vertical tab
20927 **    \f    -> form feed
20928 **    \r    -> carriage return
20929 **    \s    -> space
20930 **    \"    -> "
20931 **    \'    -> '
20932 **    \\    -> backslash
20933 **    \NNN  -> ascii character NNN in octal
20934 **    \xHH  -> ascii character HH in hexadecimal
20935 */
20936 static void resolve_backslashes(char *z){
20937   int i, j;
20938   char c;
20939   while( *z && *z!='\\' ) z++;
20940   for(i=j=0; (c = z[i])!=0; i++, j++){
20941     if( c=='\\' && z[i+1]!=0 ){
20942       c = z[++i];
20943       if( c=='a' ){
20944         c = '\a';
20945       }else if( c=='b' ){
20946         c = '\b';
20947       }else if( c=='t' ){
20948         c = '\t';
20949       }else if( c=='n' ){
20950         c = '\n';
20951       }else if( c=='v' ){
20952         c = '\v';
20953       }else if( c=='f' ){
20954         c = '\f';
20955       }else if( c=='r' ){
20956         c = '\r';
20957       }else if( c=='"' ){
20958         c = '"';
20959       }else if( c=='\'' ){
20960         c = '\'';
20961       }else if( c=='\\' ){
20962         c = '\\';
20963       }else if( c=='x' ){
20964         int nhd = 0, hdv;
20965         u8 hv = 0;
20966         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
20967           hv = (u8)((hv<<4)|hdv);
20968           ++nhd;
20969         }
20970         i += nhd;
20971         c = (u8)hv;
20972       }else if( c>='0' && c<='7' ){
20973         c -= '0';
20974         if( z[i+1]>='0' && z[i+1]<='7' ){
20975           i++;
20976           c = (c<<3) + z[i] - '0';
20977           if( z[i+1]>='0' && z[i+1]<='7' ){
20978             i++;
20979             c = (c<<3) + z[i] - '0';
20980           }
20981         }
20982       }
20983     }
20984     z[j] = c;
20985   }
20986   if( j<i ) z[j] = 0;
20987 }
20988 
20989 /*
20990 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
20991 ** for TRUE and FALSE.  Return the integer value if appropriate.
20992 */
20993 static int booleanValue(const char *zArg){
20994   int i;
20995   if( zArg[0]=='0' && zArg[1]=='x' ){
20996     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
20997   }else{
20998     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
20999   }
21000   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
21001   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
21002     return 1;
21003   }
21004   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
21005     return 0;
21006   }
21007   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
21008           zArg);
21009   return 0;
21010 }
21011 
21012 /*
21013 ** Set or clear a shell flag according to a boolean value.
21014 */
21015 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
21016   if( booleanValue(zArg) ){
21017     ShellSetFlag(p, mFlag);
21018   }else{
21019     ShellClearFlag(p, mFlag);
21020   }
21021 }
21022 
21023 /*
21024 ** Close an output file, assuming it is not stderr or stdout
21025 */
21026 static void output_file_close(FILE *f){
21027   if( f && f!=stdout && f!=stderr ) fclose(f);
21028 }
21029 
21030 /*
21031 ** Try to open an output file.   The names "stdout" and "stderr" are
21032 ** recognized and do the right thing.  NULL is returned if the output
21033 ** filename is "off".
21034 */
21035 static FILE *output_file_open(const char *zFile, int bTextMode){
21036   FILE *f;
21037   if( cli_strcmp(zFile,"stdout")==0 ){
21038     f = stdout;
21039   }else if( cli_strcmp(zFile, "stderr")==0 ){
21040     f = stderr;
21041   }else if( cli_strcmp(zFile, "off")==0 ){
21042     f = 0;
21043   }else{
21044     f = fopen(zFile, bTextMode ? "w" : "wb");
21045     if( f==0 ){
21046       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
21047     }
21048   }
21049   return f;
21050 }
21051 
21052 #ifndef SQLITE_OMIT_TRACE
21053 /*
21054 ** A routine for handling output from sqlite3_trace().
21055 */
21056 static int sql_trace_callback(
21057   unsigned mType,         /* The trace type */
21058   void *pArg,             /* The ShellState pointer */
21059   void *pP,               /* Usually a pointer to sqlite_stmt */
21060   void *pX                /* Auxiliary output */
21061 ){
21062   ShellState *p = (ShellState*)pArg;
21063   sqlite3_stmt *pStmt;
21064   const char *zSql;
21065   i64 nSql;
21066   if( p->traceOut==0 ) return 0;
21067   if( mType==SQLITE_TRACE_CLOSE ){
21068     utf8_printf(p->traceOut, "-- closing database connection\n");
21069     return 0;
21070   }
21071   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
21072     zSql = (const char*)pX;
21073   }else{
21074     pStmt = (sqlite3_stmt*)pP;
21075     switch( p->eTraceType ){
21076       case SHELL_TRACE_EXPANDED: {
21077         zSql = sqlite3_expanded_sql(pStmt);
21078         break;
21079       }
21080 #ifdef SQLITE_ENABLE_NORMALIZE
21081       case SHELL_TRACE_NORMALIZED: {
21082         zSql = sqlite3_normalized_sql(pStmt);
21083         break;
21084       }
21085 #endif
21086       default: {
21087         zSql = sqlite3_sql(pStmt);
21088         break;
21089       }
21090     }
21091   }
21092   if( zSql==0 ) return 0;
21093   nSql = strlen(zSql);
21094   if( nSql>1000000000 ) nSql = 1000000000;
21095   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
21096   switch( mType ){
21097     case SQLITE_TRACE_ROW:
21098     case SQLITE_TRACE_STMT: {
21099       utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
21100       break;
21101     }
21102     case SQLITE_TRACE_PROFILE: {
21103       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
21104       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
21105       break;
21106     }
21107   }
21108   return 0;
21109 }
21110 #endif
21111 
21112 /*
21113 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
21114 ** a useful spot to set a debugger breakpoint.
21115 **
21116 ** This routine does not do anything practical.  The code are there simply
21117 ** to prevent the compiler from optimizing this routine out.
21118 */
21119 static void test_breakpoint(void){
21120   static unsigned int nCall = 0;
21121   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
21122 }
21123 
21124 /*
21125 ** An object used to read a CSV and other files for import.
21126 */
21127 typedef struct ImportCtx ImportCtx;
21128 struct ImportCtx {
21129   const char *zFile;  /* Name of the input file */
21130   FILE *in;           /* Read the CSV text from this input stream */
21131   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
21132   char *z;            /* Accumulated text for a field */
21133   int n;              /* Number of bytes in z */
21134   int nAlloc;         /* Space allocated for z[] */
21135   int nLine;          /* Current line number */
21136   int nRow;           /* Number of rows imported */
21137   int nErr;           /* Number of errors encountered */
21138   int bNotFirst;      /* True if one or more bytes already read */
21139   int cTerm;          /* Character that terminated the most recent field */
21140   int cColSep;        /* The column separator character.  (Usually ",") */
21141   int cRowSep;        /* The row separator character.  (Usually "\n") */
21142 };
21143 
21144 /* Clean up resourced used by an ImportCtx */
21145 static void import_cleanup(ImportCtx *p){
21146   if( p->in!=0 && p->xCloser!=0 ){
21147     p->xCloser(p->in);
21148     p->in = 0;
21149   }
21150   sqlite3_free(p->z);
21151   p->z = 0;
21152 }
21153 
21154 /* Append a single byte to z[] */
21155 static void import_append_char(ImportCtx *p, int c){
21156   if( p->n+1>=p->nAlloc ){
21157     p->nAlloc += p->nAlloc + 100;
21158     p->z = sqlite3_realloc64(p->z, p->nAlloc);
21159     shell_check_oom(p->z);
21160   }
21161   p->z[p->n++] = (char)c;
21162 }
21163 
21164 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
21165 ** with the option of having a separator other than ",".
21166 **
21167 **   +  Input comes from p->in.
21168 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
21169 **      from sqlite3_malloc64().
21170 **   +  Use p->cSep as the column separator.  The default is ",".
21171 **   +  Use p->rSep as the row separator.  The default is "\n".
21172 **   +  Keep track of the line number in p->nLine.
21173 **   +  Store the character that terminates the field in p->cTerm.  Store
21174 **      EOF on end-of-file.
21175 **   +  Report syntax errors on stderr
21176 */
21177 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
21178   int c;
21179   int cSep = (u8)p->cColSep;
21180   int rSep = (u8)p->cRowSep;
21181   p->n = 0;
21182   c = fgetc(p->in);
21183   if( c==EOF || seenInterrupt ){
21184     p->cTerm = EOF;
21185     return 0;
21186   }
21187   if( c=='"' ){
21188     int pc, ppc;
21189     int startLine = p->nLine;
21190     int cQuote = c;
21191     pc = ppc = 0;
21192     while( 1 ){
21193       c = fgetc(p->in);
21194       if( c==rSep ) p->nLine++;
21195       if( c==cQuote ){
21196         if( pc==cQuote ){
21197           pc = 0;
21198           continue;
21199         }
21200       }
21201       if( (c==cSep && pc==cQuote)
21202        || (c==rSep && pc==cQuote)
21203        || (c==rSep && pc=='\r' && ppc==cQuote)
21204        || (c==EOF && pc==cQuote)
21205       ){
21206         do{ p->n--; }while( p->z[p->n]!=cQuote );
21207         p->cTerm = c;
21208         break;
21209       }
21210       if( pc==cQuote && c!='\r' ){
21211         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
21212                 p->zFile, p->nLine, cQuote);
21213       }
21214       if( c==EOF ){
21215         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
21216                 p->zFile, startLine, cQuote);
21217         p->cTerm = c;
21218         break;
21219       }
21220       import_append_char(p, c);
21221       ppc = pc;
21222       pc = c;
21223     }
21224   }else{
21225     /* If this is the first field being parsed and it begins with the
21226     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
21227     if( (c&0xff)==0xef && p->bNotFirst==0 ){
21228       import_append_char(p, c);
21229       c = fgetc(p->in);
21230       if( (c&0xff)==0xbb ){
21231         import_append_char(p, c);
21232         c = fgetc(p->in);
21233         if( (c&0xff)==0xbf ){
21234           p->bNotFirst = 1;
21235           p->n = 0;
21236           return csv_read_one_field(p);
21237         }
21238       }
21239     }
21240     while( c!=EOF && c!=cSep && c!=rSep ){
21241       import_append_char(p, c);
21242       c = fgetc(p->in);
21243     }
21244     if( c==rSep ){
21245       p->nLine++;
21246       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
21247     }
21248     p->cTerm = c;
21249   }
21250   if( p->z ) p->z[p->n] = 0;
21251   p->bNotFirst = 1;
21252   return p->z;
21253 }
21254 
21255 /* Read a single field of ASCII delimited text.
21256 **
21257 **   +  Input comes from p->in.
21258 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
21259 **      from sqlite3_malloc64().
21260 **   +  Use p->cSep as the column separator.  The default is "\x1F".
21261 **   +  Use p->rSep as the row separator.  The default is "\x1E".
21262 **   +  Keep track of the row number in p->nLine.
21263 **   +  Store the character that terminates the field in p->cTerm.  Store
21264 **      EOF on end-of-file.
21265 **   +  Report syntax errors on stderr
21266 */
21267 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
21268   int c;
21269   int cSep = (u8)p->cColSep;
21270   int rSep = (u8)p->cRowSep;
21271   p->n = 0;
21272   c = fgetc(p->in);
21273   if( c==EOF || seenInterrupt ){
21274     p->cTerm = EOF;
21275     return 0;
21276   }
21277   while( c!=EOF && c!=cSep && c!=rSep ){
21278     import_append_char(p, c);
21279     c = fgetc(p->in);
21280   }
21281   if( c==rSep ){
21282     p->nLine++;
21283   }
21284   p->cTerm = c;
21285   if( p->z ) p->z[p->n] = 0;
21286   return p->z;
21287 }
21288 
21289 /*
21290 ** Try to transfer data for table zTable.  If an error is seen while
21291 ** moving forward, try to go backwards.  The backwards movement won't
21292 ** work for WITHOUT ROWID tables.
21293 */
21294 static void tryToCloneData(
21295   ShellState *p,
21296   sqlite3 *newDb,
21297   const char *zTable
21298 ){
21299   sqlite3_stmt *pQuery = 0;
21300   sqlite3_stmt *pInsert = 0;
21301   char *zQuery = 0;
21302   char *zInsert = 0;
21303   int rc;
21304   int i, j, n;
21305   int nTable = strlen30(zTable);
21306   int k = 0;
21307   int cnt = 0;
21308   const int spinRate = 10000;
21309 
21310   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
21311   shell_check_oom(zQuery);
21312   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21313   if( rc ){
21314     utf8_printf(stderr, "Error %d: %s on [%s]\n",
21315             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21316             zQuery);
21317     goto end_data_xfer;
21318   }
21319   n = sqlite3_column_count(pQuery);
21320   zInsert = sqlite3_malloc64(200 + nTable + n*3);
21321   shell_check_oom(zInsert);
21322   sqlite3_snprintf(200+nTable,zInsert,
21323                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
21324   i = strlen30(zInsert);
21325   for(j=1; j<n; j++){
21326     memcpy(zInsert+i, ",?", 2);
21327     i += 2;
21328   }
21329   memcpy(zInsert+i, ");", 3);
21330   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
21331   if( rc ){
21332     utf8_printf(stderr, "Error %d: %s on [%s]\n",
21333             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
21334             zQuery);
21335     goto end_data_xfer;
21336   }
21337   for(k=0; k<2; k++){
21338     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
21339       for(i=0; i<n; i++){
21340         switch( sqlite3_column_type(pQuery, i) ){
21341           case SQLITE_NULL: {
21342             sqlite3_bind_null(pInsert, i+1);
21343             break;
21344           }
21345           case SQLITE_INTEGER: {
21346             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
21347             break;
21348           }
21349           case SQLITE_FLOAT: {
21350             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
21351             break;
21352           }
21353           case SQLITE_TEXT: {
21354             sqlite3_bind_text(pInsert, i+1,
21355                              (const char*)sqlite3_column_text(pQuery,i),
21356                              -1, SQLITE_STATIC);
21357             break;
21358           }
21359           case SQLITE_BLOB: {
21360             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
21361                                             sqlite3_column_bytes(pQuery,i),
21362                                             SQLITE_STATIC);
21363             break;
21364           }
21365         }
21366       } /* End for */
21367       rc = sqlite3_step(pInsert);
21368       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
21369         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
21370                         sqlite3_errmsg(newDb));
21371       }
21372       sqlite3_reset(pInsert);
21373       cnt++;
21374       if( (cnt%spinRate)==0 ){
21375         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
21376         fflush(stdout);
21377       }
21378     } /* End while */
21379     if( rc==SQLITE_DONE ) break;
21380     sqlite3_finalize(pQuery);
21381     sqlite3_free(zQuery);
21382     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
21383                              zTable);
21384     shell_check_oom(zQuery);
21385     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21386     if( rc ){
21387       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
21388       break;
21389     }
21390   } /* End for(k=0...) */
21391 
21392 end_data_xfer:
21393   sqlite3_finalize(pQuery);
21394   sqlite3_finalize(pInsert);
21395   sqlite3_free(zQuery);
21396   sqlite3_free(zInsert);
21397 }
21398 
21399 
21400 /*
21401 ** Try to transfer all rows of the schema that match zWhere.  For
21402 ** each row, invoke xForEach() on the object defined by that row.
21403 ** If an error is encountered while moving forward through the
21404 ** sqlite_schema table, try again moving backwards.
21405 */
21406 static void tryToCloneSchema(
21407   ShellState *p,
21408   sqlite3 *newDb,
21409   const char *zWhere,
21410   void (*xForEach)(ShellState*,sqlite3*,const char*)
21411 ){
21412   sqlite3_stmt *pQuery = 0;
21413   char *zQuery = 0;
21414   int rc;
21415   const unsigned char *zName;
21416   const unsigned char *zSql;
21417   char *zErrMsg = 0;
21418 
21419   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
21420                            " WHERE %s ORDER BY rowid ASC", zWhere);
21421   shell_check_oom(zQuery);
21422   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21423   if( rc ){
21424     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
21425                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21426                     zQuery);
21427     goto end_schema_xfer;
21428   }
21429   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
21430     zName = sqlite3_column_text(pQuery, 0);
21431     zSql = sqlite3_column_text(pQuery, 1);
21432     if( zName==0 || zSql==0 ) continue;
21433     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
21434       printf("%s... ", zName); fflush(stdout);
21435       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
21436       if( zErrMsg ){
21437         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
21438         sqlite3_free(zErrMsg);
21439         zErrMsg = 0;
21440       }
21441     }
21442     if( xForEach ){
21443       xForEach(p, newDb, (const char*)zName);
21444     }
21445     printf("done\n");
21446   }
21447   if( rc!=SQLITE_DONE ){
21448     sqlite3_finalize(pQuery);
21449     sqlite3_free(zQuery);
21450     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
21451                              " WHERE %s ORDER BY rowid DESC", zWhere);
21452     shell_check_oom(zQuery);
21453     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21454     if( rc ){
21455       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
21456                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21457                       zQuery);
21458       goto end_schema_xfer;
21459     }
21460     while( sqlite3_step(pQuery)==SQLITE_ROW ){
21461       zName = sqlite3_column_text(pQuery, 0);
21462       zSql = sqlite3_column_text(pQuery, 1);
21463       if( zName==0 || zSql==0 ) continue;
21464       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
21465       printf("%s... ", zName); fflush(stdout);
21466       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
21467       if( zErrMsg ){
21468         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
21469         sqlite3_free(zErrMsg);
21470         zErrMsg = 0;
21471       }
21472       if( xForEach ){
21473         xForEach(p, newDb, (const char*)zName);
21474       }
21475       printf("done\n");
21476     }
21477   }
21478 end_schema_xfer:
21479   sqlite3_finalize(pQuery);
21480   sqlite3_free(zQuery);
21481 }
21482 
21483 /*
21484 ** Open a new database file named "zNewDb".  Try to recover as much information
21485 ** as possible out of the main database (which might be corrupt) and write it
21486 ** into zNewDb.
21487 */
21488 static void tryToClone(ShellState *p, const char *zNewDb){
21489   int rc;
21490   sqlite3 *newDb = 0;
21491   if( access(zNewDb,0)==0 ){
21492     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
21493     return;
21494   }
21495   rc = sqlite3_open(zNewDb, &newDb);
21496   if( rc ){
21497     utf8_printf(stderr, "Cannot create output database: %s\n",
21498             sqlite3_errmsg(newDb));
21499   }else{
21500     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
21501     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
21502     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
21503     tryToCloneSchema(p, newDb, "type!='table'", 0);
21504     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
21505     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
21506   }
21507   close_db(newDb);
21508 }
21509 
21510 /*
21511 ** Change the output file back to stdout.
21512 **
21513 ** If the p->doXdgOpen flag is set, that means the output was being
21514 ** redirected to a temporary file named by p->zTempFile.  In that case,
21515 ** launch start/open/xdg-open on that temporary file.
21516 */
21517 static void output_reset(ShellState *p){
21518   if( p->outfile[0]=='|' ){
21519 #ifndef SQLITE_OMIT_POPEN
21520     pclose(p->out);
21521 #endif
21522   }else{
21523     output_file_close(p->out);
21524 #ifndef SQLITE_NOHAVE_SYSTEM
21525     if( p->doXdgOpen ){
21526       const char *zXdgOpenCmd =
21527 #if defined(_WIN32)
21528       "start";
21529 #elif defined(__APPLE__)
21530       "open";
21531 #else
21532       "xdg-open";
21533 #endif
21534       char *zCmd;
21535       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
21536       if( system(zCmd) ){
21537         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
21538       }else{
21539         /* Give the start/open/xdg-open command some time to get
21540         ** going before we continue, and potential delete the
21541         ** p->zTempFile data file out from under it */
21542         sqlite3_sleep(2000);
21543       }
21544       sqlite3_free(zCmd);
21545       outputModePop(p);
21546       p->doXdgOpen = 0;
21547     }
21548 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
21549   }
21550   p->outfile[0] = 0;
21551   p->out = stdout;
21552 }
21553 
21554 /*
21555 ** Run an SQL command and return the single integer result.
21556 */
21557 static int db_int(sqlite3 *db, const char *zSql){
21558   sqlite3_stmt *pStmt;
21559   int res = 0;
21560   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
21561   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
21562     res = sqlite3_column_int(pStmt,0);
21563   }
21564   sqlite3_finalize(pStmt);
21565   return res;
21566 }
21567 
21568 #if SQLITE_SHELL_HAVE_RECOVER
21569 /*
21570 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
21571 */
21572 static unsigned int get2byteInt(unsigned char *a){
21573   return (a[0]<<8) + a[1];
21574 }
21575 static unsigned int get4byteInt(unsigned char *a){
21576   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
21577 }
21578 
21579 /*
21580 ** Implementation of the ".dbinfo" command.
21581 **
21582 ** Return 1 on error, 2 to exit, and 0 otherwise.
21583 */
21584 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
21585   static const struct { const char *zName; int ofst; } aField[] = {
21586      { "file change counter:",  24  },
21587      { "database page count:",  28  },
21588      { "freelist page count:",  36  },
21589      { "schema cookie:",        40  },
21590      { "schema format:",        44  },
21591      { "default cache size:",   48  },
21592      { "autovacuum top root:",  52  },
21593      { "incremental vacuum:",   64  },
21594      { "text encoding:",        56  },
21595      { "user version:",         60  },
21596      { "application id:",       68  },
21597      { "software version:",     96  },
21598   };
21599   static const struct { const char *zName; const char *zSql; } aQuery[] = {
21600      { "number of tables:",
21601        "SELECT count(*) FROM %s WHERE type='table'" },
21602      { "number of indexes:",
21603        "SELECT count(*) FROM %s WHERE type='index'" },
21604      { "number of triggers:",
21605        "SELECT count(*) FROM %s WHERE type='trigger'" },
21606      { "number of views:",
21607        "SELECT count(*) FROM %s WHERE type='view'" },
21608      { "schema size:",
21609        "SELECT total(length(sql)) FROM %s" },
21610   };
21611   int i, rc;
21612   unsigned iDataVersion;
21613   char *zSchemaTab;
21614   char *zDb = nArg>=2 ? azArg[1] : "main";
21615   sqlite3_stmt *pStmt = 0;
21616   unsigned char aHdr[100];
21617   open_db(p, 0);
21618   if( p->db==0 ) return 1;
21619   rc = sqlite3_prepare_v2(p->db,
21620              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
21621              -1, &pStmt, 0);
21622   if( rc ){
21623     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
21624     sqlite3_finalize(pStmt);
21625     return 1;
21626   }
21627   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
21628   if( sqlite3_step(pStmt)==SQLITE_ROW
21629    && sqlite3_column_bytes(pStmt,0)>100
21630   ){
21631     const u8 *pb = sqlite3_column_blob(pStmt,0);
21632     shell_check_oom(pb);
21633     memcpy(aHdr, pb, 100);
21634     sqlite3_finalize(pStmt);
21635   }else{
21636     raw_printf(stderr, "unable to read database header\n");
21637     sqlite3_finalize(pStmt);
21638     return 1;
21639   }
21640   i = get2byteInt(aHdr+16);
21641   if( i==1 ) i = 65536;
21642   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
21643   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
21644   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
21645   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
21646   for(i=0; i<ArraySize(aField); i++){
21647     int ofst = aField[i].ofst;
21648     unsigned int val = get4byteInt(aHdr + ofst);
21649     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
21650     switch( ofst ){
21651       case 56: {
21652         if( val==1 ) raw_printf(p->out, " (utf8)");
21653         if( val==2 ) raw_printf(p->out, " (utf16le)");
21654         if( val==3 ) raw_printf(p->out, " (utf16be)");
21655       }
21656     }
21657     raw_printf(p->out, "\n");
21658   }
21659   if( zDb==0 ){
21660     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
21661   }else if( cli_strcmp(zDb,"temp")==0 ){
21662     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
21663   }else{
21664     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
21665   }
21666   for(i=0; i<ArraySize(aQuery); i++){
21667     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
21668     int val = db_int(p->db, zSql);
21669     sqlite3_free(zSql);
21670     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
21671   }
21672   sqlite3_free(zSchemaTab);
21673   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
21674   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
21675   return 0;
21676 }
21677 #endif /* SQLITE_SHELL_HAVE_RECOVER */
21678 
21679 /*
21680 ** Print the current sqlite3_errmsg() value to stderr and return 1.
21681 */
21682 static int shellDatabaseError(sqlite3 *db){
21683   const char *zErr = sqlite3_errmsg(db);
21684   utf8_printf(stderr, "Error: %s\n", zErr);
21685   return 1;
21686 }
21687 
21688 /*
21689 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
21690 ** if they match and FALSE (0) if they do not match.
21691 **
21692 ** Globbing rules:
21693 **
21694 **      '*'       Matches any sequence of zero or more characters.
21695 **
21696 **      '?'       Matches exactly one character.
21697 **
21698 **     [...]      Matches one character from the enclosed list of
21699 **                characters.
21700 **
21701 **     [^...]     Matches one character not in the enclosed list.
21702 **
21703 **      '#'       Matches any sequence of one or more digits with an
21704 **                optional + or - sign in front
21705 **
21706 **      ' '       Any span of whitespace matches any other span of
21707 **                whitespace.
21708 **
21709 ** Extra whitespace at the end of z[] is ignored.
21710 */
21711 static int testcase_glob(const char *zGlob, const char *z){
21712   int c, c2;
21713   int invert;
21714   int seen;
21715 
21716   while( (c = (*(zGlob++)))!=0 ){
21717     if( IsSpace(c) ){
21718       if( !IsSpace(*z) ) return 0;
21719       while( IsSpace(*zGlob) ) zGlob++;
21720       while( IsSpace(*z) ) z++;
21721     }else if( c=='*' ){
21722       while( (c=(*(zGlob++))) == '*' || c=='?' ){
21723         if( c=='?' && (*(z++))==0 ) return 0;
21724       }
21725       if( c==0 ){
21726         return 1;
21727       }else if( c=='[' ){
21728         while( *z && testcase_glob(zGlob-1,z)==0 ){
21729           z++;
21730         }
21731         return (*z)!=0;
21732       }
21733       while( (c2 = (*(z++)))!=0 ){
21734         while( c2!=c ){
21735           c2 = *(z++);
21736           if( c2==0 ) return 0;
21737         }
21738         if( testcase_glob(zGlob,z) ) return 1;
21739       }
21740       return 0;
21741     }else if( c=='?' ){
21742       if( (*(z++))==0 ) return 0;
21743     }else if( c=='[' ){
21744       int prior_c = 0;
21745       seen = 0;
21746       invert = 0;
21747       c = *(z++);
21748       if( c==0 ) return 0;
21749       c2 = *(zGlob++);
21750       if( c2=='^' ){
21751         invert = 1;
21752         c2 = *(zGlob++);
21753       }
21754       if( c2==']' ){
21755         if( c==']' ) seen = 1;
21756         c2 = *(zGlob++);
21757       }
21758       while( c2 && c2!=']' ){
21759         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
21760           c2 = *(zGlob++);
21761           if( c>=prior_c && c<=c2 ) seen = 1;
21762           prior_c = 0;
21763         }else{
21764           if( c==c2 ){
21765             seen = 1;
21766           }
21767           prior_c = c2;
21768         }
21769         c2 = *(zGlob++);
21770       }
21771       if( c2==0 || (seen ^ invert)==0 ) return 0;
21772     }else if( c=='#' ){
21773       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
21774       if( !IsDigit(z[0]) ) return 0;
21775       z++;
21776       while( IsDigit(z[0]) ){ z++; }
21777     }else{
21778       if( c!=(*(z++)) ) return 0;
21779     }
21780   }
21781   while( IsSpace(*z) ){ z++; }
21782   return *z==0;
21783 }
21784 
21785 
21786 /*
21787 ** Compare the string as a command-line option with either one or two
21788 ** initial "-" characters.
21789 */
21790 static int optionMatch(const char *zStr, const char *zOpt){
21791   if( zStr[0]!='-' ) return 0;
21792   zStr++;
21793   if( zStr[0]=='-' ) zStr++;
21794   return cli_strcmp(zStr, zOpt)==0;
21795 }
21796 
21797 /*
21798 ** Delete a file.
21799 */
21800 int shellDeleteFile(const char *zFilename){
21801   int rc;
21802 #ifdef _WIN32
21803   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
21804   rc = _wunlink(z);
21805   sqlite3_free(z);
21806 #else
21807   rc = unlink(zFilename);
21808 #endif
21809   return rc;
21810 }
21811 
21812 /*
21813 ** Try to delete the temporary file (if there is one) and free the
21814 ** memory used to hold the name of the temp file.
21815 */
21816 static void clearTempFile(ShellState *p){
21817   if( p->zTempFile==0 ) return;
21818   if( p->doXdgOpen ) return;
21819   if( shellDeleteFile(p->zTempFile) ) return;
21820   sqlite3_free(p->zTempFile);
21821   p->zTempFile = 0;
21822 }
21823 
21824 /*
21825 ** Create a new temp file name with the given suffix.
21826 */
21827 static void newTempFile(ShellState *p, const char *zSuffix){
21828   clearTempFile(p);
21829   sqlite3_free(p->zTempFile);
21830   p->zTempFile = 0;
21831   if( p->db ){
21832     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
21833   }
21834   if( p->zTempFile==0 ){
21835     /* If p->db is an in-memory database then the TEMPFILENAME file-control
21836     ** will not work and we will need to fallback to guessing */
21837     char *zTemp;
21838     sqlite3_uint64 r;
21839     sqlite3_randomness(sizeof(r), &r);
21840     zTemp = getenv("TEMP");
21841     if( zTemp==0 ) zTemp = getenv("TMP");
21842     if( zTemp==0 ){
21843 #ifdef _WIN32
21844       zTemp = "\\tmp";
21845 #else
21846       zTemp = "/tmp";
21847 #endif
21848     }
21849     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
21850   }else{
21851     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
21852   }
21853   shell_check_oom(p->zTempFile);
21854 }
21855 
21856 
21857 /*
21858 ** The implementation of SQL scalar function fkey_collate_clause(), used
21859 ** by the ".lint fkey-indexes" command. This scalar function is always
21860 ** called with four arguments - the parent table name, the parent column name,
21861 ** the child table name and the child column name.
21862 **
21863 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
21864 **
21865 ** If either of the named tables or columns do not exist, this function
21866 ** returns an empty string. An empty string is also returned if both tables
21867 ** and columns exist but have the same default collation sequence. Or,
21868 ** if both exist but the default collation sequences are different, this
21869 ** function returns the string " COLLATE <parent-collation>", where
21870 ** <parent-collation> is the default collation sequence of the parent column.
21871 */
21872 static void shellFkeyCollateClause(
21873   sqlite3_context *pCtx,
21874   int nVal,
21875   sqlite3_value **apVal
21876 ){
21877   sqlite3 *db = sqlite3_context_db_handle(pCtx);
21878   const char *zParent;
21879   const char *zParentCol;
21880   const char *zParentSeq;
21881   const char *zChild;
21882   const char *zChildCol;
21883   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
21884   int rc;
21885 
21886   assert( nVal==4 );
21887   zParent = (const char*)sqlite3_value_text(apVal[0]);
21888   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
21889   zChild = (const char*)sqlite3_value_text(apVal[2]);
21890   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
21891 
21892   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
21893   rc = sqlite3_table_column_metadata(
21894       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
21895   );
21896   if( rc==SQLITE_OK ){
21897     rc = sqlite3_table_column_metadata(
21898         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
21899     );
21900   }
21901 
21902   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
21903     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
21904     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
21905     sqlite3_free(z);
21906   }
21907 }
21908 
21909 
21910 /*
21911 ** The implementation of dot-command ".lint fkey-indexes".
21912 */
21913 static int lintFkeyIndexes(
21914   ShellState *pState,             /* Current shell tool state */
21915   char **azArg,                   /* Array of arguments passed to dot command */
21916   int nArg                        /* Number of entries in azArg[] */
21917 ){
21918   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
21919   FILE *out = pState->out;        /* Stream to write non-error output to */
21920   int bVerbose = 0;               /* If -verbose is present */
21921   int bGroupByParent = 0;         /* If -groupbyparent is present */
21922   int i;                          /* To iterate through azArg[] */
21923   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
21924   int rc;                         /* Return code */
21925   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
21926 
21927   /*
21928   ** This SELECT statement returns one row for each foreign key constraint
21929   ** in the schema of the main database. The column values are:
21930   **
21931   ** 0. The text of an SQL statement similar to:
21932   **
21933   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
21934   **
21935   **    This SELECT is similar to the one that the foreign keys implementation
21936   **    needs to run internally on child tables. If there is an index that can
21937   **    be used to optimize this query, then it can also be used by the FK
21938   **    implementation to optimize DELETE or UPDATE statements on the parent
21939   **    table.
21940   **
21941   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
21942   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
21943   **    contains an index that can be used to optimize the query.
21944   **
21945   ** 2. Human readable text that describes the child table and columns. e.g.
21946   **
21947   **       "child_table(child_key1, child_key2)"
21948   **
21949   ** 3. Human readable text that describes the parent table and columns. e.g.
21950   **
21951   **       "parent_table(parent_key1, parent_key2)"
21952   **
21953   ** 4. A full CREATE INDEX statement for an index that could be used to
21954   **    optimize DELETE or UPDATE statements on the parent table. e.g.
21955   **
21956   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
21957   **
21958   ** 5. The name of the parent table.
21959   **
21960   ** These six values are used by the C logic below to generate the report.
21961   */
21962   const char *zSql =
21963   "SELECT "
21964     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
21965     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
21966     "  || fkey_collate_clause("
21967     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
21968     ", "
21969     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
21970     "  || group_concat('*=?', ' AND ') || ')'"
21971     ", "
21972     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
21973     ", "
21974     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
21975     ", "
21976     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
21977     "  || ' ON ' || quote(s.name) || '('"
21978     "  || group_concat(quote(f.[from]) ||"
21979     "        fkey_collate_clause("
21980     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
21981     "  || ');'"
21982     ", "
21983     "     f.[table] "
21984     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
21985     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
21986     "GROUP BY s.name, f.id "
21987     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
21988   ;
21989   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
21990 
21991   for(i=2; i<nArg; i++){
21992     int n = strlen30(azArg[i]);
21993     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
21994       bVerbose = 1;
21995     }
21996     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
21997       bGroupByParent = 1;
21998       zIndent = "    ";
21999     }
22000     else{
22001       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
22002           azArg[0], azArg[1]
22003       );
22004       return SQLITE_ERROR;
22005     }
22006   }
22007 
22008   /* Register the fkey_collate_clause() SQL function */
22009   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
22010       0, shellFkeyCollateClause, 0, 0
22011   );
22012 
22013 
22014   if( rc==SQLITE_OK ){
22015     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
22016   }
22017   if( rc==SQLITE_OK ){
22018     sqlite3_bind_int(pSql, 1, bGroupByParent);
22019   }
22020 
22021   if( rc==SQLITE_OK ){
22022     int rc2;
22023     char *zPrev = 0;
22024     while( SQLITE_ROW==sqlite3_step(pSql) ){
22025       int res = -1;
22026       sqlite3_stmt *pExplain = 0;
22027       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
22028       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
22029       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
22030       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
22031       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
22032       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
22033 
22034       if( zEQP==0 ) continue;
22035       if( zGlob==0 ) continue;
22036       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
22037       if( rc!=SQLITE_OK ) break;
22038       if( SQLITE_ROW==sqlite3_step(pExplain) ){
22039         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
22040         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
22041                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
22042       }
22043       rc = sqlite3_finalize(pExplain);
22044       if( rc!=SQLITE_OK ) break;
22045 
22046       if( res<0 ){
22047         raw_printf(stderr, "Error: internal error");
22048         break;
22049       }else{
22050         if( bGroupByParent
22051         && (bVerbose || res==0)
22052         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
22053         ){
22054           raw_printf(out, "-- Parent table %s\n", zParent);
22055           sqlite3_free(zPrev);
22056           zPrev = sqlite3_mprintf("%s", zParent);
22057         }
22058 
22059         if( res==0 ){
22060           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
22061         }else if( bVerbose ){
22062           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
22063               zIndent, zFrom, zTarget
22064           );
22065         }
22066       }
22067     }
22068     sqlite3_free(zPrev);
22069 
22070     if( rc!=SQLITE_OK ){
22071       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
22072     }
22073 
22074     rc2 = sqlite3_finalize(pSql);
22075     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
22076       rc = rc2;
22077       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
22078     }
22079   }else{
22080     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
22081   }
22082 
22083   return rc;
22084 }
22085 
22086 /*
22087 ** Implementation of ".lint" dot command.
22088 */
22089 static int lintDotCommand(
22090   ShellState *pState,             /* Current shell tool state */
22091   char **azArg,                   /* Array of arguments passed to dot command */
22092   int nArg                        /* Number of entries in azArg[] */
22093 ){
22094   int n;
22095   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
22096   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
22097   return lintFkeyIndexes(pState, azArg, nArg);
22098 
22099  usage:
22100   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
22101   raw_printf(stderr, "Where sub-commands are:\n");
22102   raw_printf(stderr, "    fkey-indexes\n");
22103   return SQLITE_ERROR;
22104 }
22105 
22106 #if !defined SQLITE_OMIT_VIRTUALTABLE
22107 static void shellPrepare(
22108   sqlite3 *db,
22109   int *pRc,
22110   const char *zSql,
22111   sqlite3_stmt **ppStmt
22112 ){
22113   *ppStmt = 0;
22114   if( *pRc==SQLITE_OK ){
22115     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
22116     if( rc!=SQLITE_OK ){
22117       raw_printf(stderr, "sql error: %s (%d)\n",
22118           sqlite3_errmsg(db), sqlite3_errcode(db)
22119       );
22120       *pRc = rc;
22121     }
22122   }
22123 }
22124 
22125 /*
22126 ** Create a prepared statement using printf-style arguments for the SQL.
22127 **
22128 ** This routine is could be marked "static".  But it is not always used,
22129 ** depending on compile-time options.  By omitting the "static", we avoid
22130 ** nuisance compiler warnings about "defined but not used".
22131 */
22132 void shellPreparePrintf(
22133   sqlite3 *db,
22134   int *pRc,
22135   sqlite3_stmt **ppStmt,
22136   const char *zFmt,
22137   ...
22138 ){
22139   *ppStmt = 0;
22140   if( *pRc==SQLITE_OK ){
22141     va_list ap;
22142     char *z;
22143     va_start(ap, zFmt);
22144     z = sqlite3_vmprintf(zFmt, ap);
22145     va_end(ap);
22146     if( z==0 ){
22147       *pRc = SQLITE_NOMEM;
22148     }else{
22149       shellPrepare(db, pRc, z, ppStmt);
22150       sqlite3_free(z);
22151     }
22152   }
22153 }
22154 
22155 /* Finalize the prepared statement created using shellPreparePrintf().
22156 **
22157 ** This routine is could be marked "static".  But it is not always used,
22158 ** depending on compile-time options.  By omitting the "static", we avoid
22159 ** nuisance compiler warnings about "defined but not used".
22160 */
22161 void shellFinalize(
22162   int *pRc,
22163   sqlite3_stmt *pStmt
22164 ){
22165   if( pStmt ){
22166     sqlite3 *db = sqlite3_db_handle(pStmt);
22167     int rc = sqlite3_finalize(pStmt);
22168     if( *pRc==SQLITE_OK ){
22169       if( rc!=SQLITE_OK ){
22170         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
22171       }
22172       *pRc = rc;
22173     }
22174   }
22175 }
22176 
22177 /* Reset the prepared statement created using shellPreparePrintf().
22178 **
22179 ** This routine is could be marked "static".  But it is not always used,
22180 ** depending on compile-time options.  By omitting the "static", we avoid
22181 ** nuisance compiler warnings about "defined but not used".
22182 */
22183 void shellReset(
22184   int *pRc,
22185   sqlite3_stmt *pStmt
22186 ){
22187   int rc = sqlite3_reset(pStmt);
22188   if( *pRc==SQLITE_OK ){
22189     if( rc!=SQLITE_OK ){
22190       sqlite3 *db = sqlite3_db_handle(pStmt);
22191       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
22192     }
22193     *pRc = rc;
22194   }
22195 }
22196 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
22197 
22198 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
22199 /******************************************************************************
22200 ** The ".archive" or ".ar" command.
22201 */
22202 /*
22203 ** Structure representing a single ".ar" command.
22204 */
22205 typedef struct ArCommand ArCommand;
22206 struct ArCommand {
22207   u8 eCmd;                        /* An AR_CMD_* value */
22208   u8 bVerbose;                    /* True if --verbose */
22209   u8 bZip;                        /* True if the archive is a ZIP */
22210   u8 bDryRun;                     /* True if --dry-run */
22211   u8 bAppend;                     /* True if --append */
22212   u8 bGlob;                       /* True if --glob */
22213   u8 fromCmdLine;                 /* Run from -A instead of .archive */
22214   int nArg;                       /* Number of command arguments */
22215   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
22216   const char *zFile;              /* --file argument, or NULL */
22217   const char *zDir;               /* --directory argument, or NULL */
22218   char **azArg;                   /* Array of command arguments */
22219   ShellState *p;                  /* Shell state */
22220   sqlite3 *db;                    /* Database containing the archive */
22221 };
22222 
22223 /*
22224 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
22225 */
22226 static int arUsage(FILE *f){
22227   showHelp(f,"archive");
22228   return SQLITE_ERROR;
22229 }
22230 
22231 /*
22232 ** Print an error message for the .ar command to stderr and return
22233 ** SQLITE_ERROR.
22234 */
22235 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
22236   va_list ap;
22237   char *z;
22238   va_start(ap, zFmt);
22239   z = sqlite3_vmprintf(zFmt, ap);
22240   va_end(ap);
22241   utf8_printf(stderr, "Error: %s\n", z);
22242   if( pAr->fromCmdLine ){
22243     utf8_printf(stderr, "Use \"-A\" for more help\n");
22244   }else{
22245     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
22246   }
22247   sqlite3_free(z);
22248   return SQLITE_ERROR;
22249 }
22250 
22251 /*
22252 ** Values for ArCommand.eCmd.
22253 */
22254 #define AR_CMD_CREATE       1
22255 #define AR_CMD_UPDATE       2
22256 #define AR_CMD_INSERT       3
22257 #define AR_CMD_EXTRACT      4
22258 #define AR_CMD_LIST         5
22259 #define AR_CMD_HELP         6
22260 #define AR_CMD_REMOVE       7
22261 
22262 /*
22263 ** Other (non-command) switches.
22264 */
22265 #define AR_SWITCH_VERBOSE     8
22266 #define AR_SWITCH_FILE        9
22267 #define AR_SWITCH_DIRECTORY  10
22268 #define AR_SWITCH_APPEND     11
22269 #define AR_SWITCH_DRYRUN     12
22270 #define AR_SWITCH_GLOB       13
22271 
22272 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
22273   switch( eSwitch ){
22274     case AR_CMD_CREATE:
22275     case AR_CMD_EXTRACT:
22276     case AR_CMD_LIST:
22277     case AR_CMD_REMOVE:
22278     case AR_CMD_UPDATE:
22279     case AR_CMD_INSERT:
22280     case AR_CMD_HELP:
22281       if( pAr->eCmd ){
22282         return arErrorMsg(pAr, "multiple command options");
22283       }
22284       pAr->eCmd = eSwitch;
22285       break;
22286 
22287     case AR_SWITCH_DRYRUN:
22288       pAr->bDryRun = 1;
22289       break;
22290     case AR_SWITCH_GLOB:
22291       pAr->bGlob = 1;
22292       break;
22293     case AR_SWITCH_VERBOSE:
22294       pAr->bVerbose = 1;
22295       break;
22296     case AR_SWITCH_APPEND:
22297       pAr->bAppend = 1;
22298       deliberate_fall_through;
22299     case AR_SWITCH_FILE:
22300       pAr->zFile = zArg;
22301       break;
22302     case AR_SWITCH_DIRECTORY:
22303       pAr->zDir = zArg;
22304       break;
22305   }
22306 
22307   return SQLITE_OK;
22308 }
22309 
22310 /*
22311 ** Parse the command line for an ".ar" command. The results are written into
22312 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
22313 ** successfully, otherwise an error message is written to stderr and
22314 ** SQLITE_ERROR returned.
22315 */
22316 static int arParseCommand(
22317   char **azArg,                   /* Array of arguments passed to dot command */
22318   int nArg,                       /* Number of entries in azArg[] */
22319   ArCommand *pAr                  /* Populate this object */
22320 ){
22321   struct ArSwitch {
22322     const char *zLong;
22323     char cShort;
22324     u8 eSwitch;
22325     u8 bArg;
22326   } aSwitch[] = {
22327     { "create",    'c', AR_CMD_CREATE,       0 },
22328     { "extract",   'x', AR_CMD_EXTRACT,      0 },
22329     { "insert",    'i', AR_CMD_INSERT,       0 },
22330     { "list",      't', AR_CMD_LIST,         0 },
22331     { "remove",    'r', AR_CMD_REMOVE,       0 },
22332     { "update",    'u', AR_CMD_UPDATE,       0 },
22333     { "help",      'h', AR_CMD_HELP,         0 },
22334     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
22335     { "file",      'f', AR_SWITCH_FILE,      1 },
22336     { "append",    'a', AR_SWITCH_APPEND,    1 },
22337     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
22338     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
22339     { "glob",      'g', AR_SWITCH_GLOB,      0 },
22340   };
22341   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
22342   struct ArSwitch *pEnd = &aSwitch[nSwitch];
22343 
22344   if( nArg<=1 ){
22345     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
22346     return arUsage(stderr);
22347   }else{
22348     char *z = azArg[1];
22349     if( z[0]!='-' ){
22350       /* Traditional style [tar] invocation */
22351       int i;
22352       int iArg = 2;
22353       for(i=0; z[i]; i++){
22354         const char *zArg = 0;
22355         struct ArSwitch *pOpt;
22356         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22357           if( z[i]==pOpt->cShort ) break;
22358         }
22359         if( pOpt==pEnd ){
22360           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
22361         }
22362         if( pOpt->bArg ){
22363           if( iArg>=nArg ){
22364             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
22365           }
22366           zArg = azArg[iArg++];
22367         }
22368         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
22369       }
22370       pAr->nArg = nArg-iArg;
22371       if( pAr->nArg>0 ){
22372         pAr->azArg = &azArg[iArg];
22373       }
22374     }else{
22375       /* Non-traditional invocation */
22376       int iArg;
22377       for(iArg=1; iArg<nArg; iArg++){
22378         int n;
22379         z = azArg[iArg];
22380         if( z[0]!='-' ){
22381           /* All remaining command line words are command arguments. */
22382           pAr->azArg = &azArg[iArg];
22383           pAr->nArg = nArg-iArg;
22384           break;
22385         }
22386         n = strlen30(z);
22387 
22388         if( z[1]!='-' ){
22389           int i;
22390           /* One or more short options */
22391           for(i=1; i<n; i++){
22392             const char *zArg = 0;
22393             struct ArSwitch *pOpt;
22394             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22395               if( z[i]==pOpt->cShort ) break;
22396             }
22397             if( pOpt==pEnd ){
22398               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
22399             }
22400             if( pOpt->bArg ){
22401               if( i<(n-1) ){
22402                 zArg = &z[i+1];
22403                 i = n;
22404               }else{
22405                 if( iArg>=(nArg-1) ){
22406                   return arErrorMsg(pAr, "option requires an argument: %c",
22407                                     z[i]);
22408                 }
22409                 zArg = azArg[++iArg];
22410               }
22411             }
22412             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
22413           }
22414         }else if( z[2]=='\0' ){
22415           /* A -- option, indicating that all remaining command line words
22416           ** are command arguments.  */
22417           pAr->azArg = &azArg[iArg+1];
22418           pAr->nArg = nArg-iArg-1;
22419           break;
22420         }else{
22421           /* A long option */
22422           const char *zArg = 0;             /* Argument for option, if any */
22423           struct ArSwitch *pMatch = 0;      /* Matching option */
22424           struct ArSwitch *pOpt;            /* Iterator */
22425           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22426             const char *zLong = pOpt->zLong;
22427             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
22428               if( pMatch ){
22429                 return arErrorMsg(pAr, "ambiguous option: %s",z);
22430               }else{
22431                 pMatch = pOpt;
22432               }
22433             }
22434           }
22435 
22436           if( pMatch==0 ){
22437             return arErrorMsg(pAr, "unrecognized option: %s", z);
22438           }
22439           if( pMatch->bArg ){
22440             if( iArg>=(nArg-1) ){
22441               return arErrorMsg(pAr, "option requires an argument: %s", z);
22442             }
22443             zArg = azArg[++iArg];
22444           }
22445           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
22446         }
22447       }
22448     }
22449   }
22450   if( pAr->eCmd==0 ){
22451     utf8_printf(stderr, "Required argument missing.  Usage:\n");
22452     return arUsage(stderr);
22453   }
22454   return SQLITE_OK;
22455 }
22456 
22457 /*
22458 ** This function assumes that all arguments within the ArCommand.azArg[]
22459 ** array refer to archive members, as for the --extract, --list or --remove
22460 ** commands. It checks that each of them are "present". If any specified
22461 ** file is not present in the archive, an error is printed to stderr and an
22462 ** error code returned. Otherwise, if all specified arguments are present
22463 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
22464 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
22465 ** when pAr->bGlob is true.
22466 **
22467 ** This function strips any trailing '/' characters from each argument.
22468 ** This is consistent with the way the [tar] command seems to work on
22469 ** Linux.
22470 */
22471 static int arCheckEntries(ArCommand *pAr){
22472   int rc = SQLITE_OK;
22473   if( pAr->nArg ){
22474     int i, j;
22475     sqlite3_stmt *pTest = 0;
22476     const char *zSel = (pAr->bGlob)
22477       ? "SELECT name FROM %s WHERE glob($name,name)"
22478       : "SELECT name FROM %s WHERE name=$name";
22479 
22480     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
22481     j = sqlite3_bind_parameter_index(pTest, "$name");
22482     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
22483       char *z = pAr->azArg[i];
22484       int n = strlen30(z);
22485       int bOk = 0;
22486       while( n>0 && z[n-1]=='/' ) n--;
22487       z[n] = '\0';
22488       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
22489       if( SQLITE_ROW==sqlite3_step(pTest) ){
22490         bOk = 1;
22491       }
22492       shellReset(&rc, pTest);
22493       if( rc==SQLITE_OK && bOk==0 ){
22494         utf8_printf(stderr, "not found in archive: %s\n", z);
22495         rc = SQLITE_ERROR;
22496       }
22497     }
22498     shellFinalize(&rc, pTest);
22499   }
22500   return rc;
22501 }
22502 
22503 /*
22504 ** Format a WHERE clause that can be used against the "sqlar" table to
22505 ** identify all archive members that match the command arguments held
22506 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
22507 ** The caller is responsible for eventually calling sqlite3_free() on
22508 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
22509 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
22510 */
22511 static void arWhereClause(
22512   int *pRc,
22513   ArCommand *pAr,
22514   char **pzWhere                  /* OUT: New WHERE clause */
22515 ){
22516   char *zWhere = 0;
22517   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
22518   if( *pRc==SQLITE_OK ){
22519     if( pAr->nArg==0 ){
22520       zWhere = sqlite3_mprintf("1");
22521     }else{
22522       int i;
22523       const char *zSep = "";
22524       for(i=0; i<pAr->nArg; i++){
22525         const char *z = pAr->azArg[i];
22526         zWhere = sqlite3_mprintf(
22527           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
22528           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
22529         );
22530         if( zWhere==0 ){
22531           *pRc = SQLITE_NOMEM;
22532           break;
22533         }
22534         zSep = " OR ";
22535       }
22536     }
22537   }
22538   *pzWhere = zWhere;
22539 }
22540 
22541 /*
22542 ** Implementation of .ar "lisT" command.
22543 */
22544 static int arListCommand(ArCommand *pAr){
22545   const char *zSql = "SELECT %s FROM %s WHERE %s";
22546   const char *azCols[] = {
22547     "name",
22548     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
22549   };
22550 
22551   char *zWhere = 0;
22552   sqlite3_stmt *pSql = 0;
22553   int rc;
22554 
22555   rc = arCheckEntries(pAr);
22556   arWhereClause(&rc, pAr, &zWhere);
22557 
22558   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
22559                      pAr->zSrcTable, zWhere);
22560   if( pAr->bDryRun ){
22561     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
22562   }else{
22563     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
22564       if( pAr->bVerbose ){
22565         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
22566             sqlite3_column_text(pSql, 0),
22567             sqlite3_column_int(pSql, 1),
22568             sqlite3_column_text(pSql, 2),
22569             sqlite3_column_text(pSql, 3)
22570         );
22571       }else{
22572         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
22573       }
22574     }
22575   }
22576   shellFinalize(&rc, pSql);
22577   sqlite3_free(zWhere);
22578   return rc;
22579 }
22580 
22581 
22582 /*
22583 ** Implementation of .ar "Remove" command.
22584 */
22585 static int arRemoveCommand(ArCommand *pAr){
22586   int rc = 0;
22587   char *zSql = 0;
22588   char *zWhere = 0;
22589 
22590   if( pAr->nArg ){
22591     /* Verify that args actually exist within the archive before proceeding.
22592     ** And formulate a WHERE clause to match them.  */
22593     rc = arCheckEntries(pAr);
22594     arWhereClause(&rc, pAr, &zWhere);
22595   }
22596   if( rc==SQLITE_OK ){
22597     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
22598                            pAr->zSrcTable, zWhere);
22599     if( pAr->bDryRun ){
22600       utf8_printf(pAr->p->out, "%s\n", zSql);
22601     }else{
22602       char *zErr = 0;
22603       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
22604       if( rc==SQLITE_OK ){
22605         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
22606         if( rc!=SQLITE_OK ){
22607           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
22608         }else{
22609           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
22610         }
22611       }
22612       if( zErr ){
22613         utf8_printf(stdout, "ERROR: %s\n", zErr);
22614         sqlite3_free(zErr);
22615       }
22616     }
22617   }
22618   sqlite3_free(zWhere);
22619   sqlite3_free(zSql);
22620   return rc;
22621 }
22622 
22623 /*
22624 ** Implementation of .ar "eXtract" command.
22625 */
22626 static int arExtractCommand(ArCommand *pAr){
22627   const char *zSql1 =
22628     "SELECT "
22629     " ($dir || name),"
22630     " writefile(($dir || name), %s, mode, mtime) "
22631     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
22632     " AND name NOT GLOB '*..[/\\]*'";
22633 
22634   const char *azExtraArg[] = {
22635     "sqlar_uncompress(data, sz)",
22636     "data"
22637   };
22638 
22639   sqlite3_stmt *pSql = 0;
22640   int rc = SQLITE_OK;
22641   char *zDir = 0;
22642   char *zWhere = 0;
22643   int i, j;
22644 
22645   /* If arguments are specified, check that they actually exist within
22646   ** the archive before proceeding. And formulate a WHERE clause to
22647   ** match them.  */
22648   rc = arCheckEntries(pAr);
22649   arWhereClause(&rc, pAr, &zWhere);
22650 
22651   if( rc==SQLITE_OK ){
22652     if( pAr->zDir ){
22653       zDir = sqlite3_mprintf("%s/", pAr->zDir);
22654     }else{
22655       zDir = sqlite3_mprintf("");
22656     }
22657     if( zDir==0 ) rc = SQLITE_NOMEM;
22658   }
22659 
22660   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
22661       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
22662   );
22663 
22664   if( rc==SQLITE_OK ){
22665     j = sqlite3_bind_parameter_index(pSql, "$dir");
22666     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
22667 
22668     /* Run the SELECT statement twice. The first time, writefile() is called
22669     ** for all archive members that should be extracted. The second time,
22670     ** only for the directories. This is because the timestamps for
22671     ** extracted directories must be reset after they are populated (as
22672     ** populating them changes the timestamp).  */
22673     for(i=0; i<2; i++){
22674       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
22675       sqlite3_bind_int(pSql, j, i);
22676       if( pAr->bDryRun ){
22677         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
22678       }else{
22679         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
22680           if( i==0 && pAr->bVerbose ){
22681             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
22682           }
22683         }
22684       }
22685       shellReset(&rc, pSql);
22686     }
22687     shellFinalize(&rc, pSql);
22688   }
22689 
22690   sqlite3_free(zDir);
22691   sqlite3_free(zWhere);
22692   return rc;
22693 }
22694 
22695 /*
22696 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
22697 */
22698 static int arExecSql(ArCommand *pAr, const char *zSql){
22699   int rc;
22700   if( pAr->bDryRun ){
22701     utf8_printf(pAr->p->out, "%s\n", zSql);
22702     rc = SQLITE_OK;
22703   }else{
22704     char *zErr = 0;
22705     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
22706     if( zErr ){
22707       utf8_printf(stdout, "ERROR: %s\n", zErr);
22708       sqlite3_free(zErr);
22709     }
22710   }
22711   return rc;
22712 }
22713 
22714 
22715 /*
22716 ** Implementation of .ar "create", "insert", and "update" commands.
22717 **
22718 **     create    ->     Create a new SQL archive
22719 **     insert    ->     Insert or reinsert all files listed
22720 **     update    ->     Insert files that have changed or that were not
22721 **                      previously in the archive
22722 **
22723 ** Create the "sqlar" table in the database if it does not already exist.
22724 ** Then add each file in the azFile[] array to the archive. Directories
22725 ** are added recursively. If argument bVerbose is non-zero, a message is
22726 ** printed on stdout for each file archived.
22727 **
22728 ** The create command is the same as update, except that it drops
22729 ** any existing "sqlar" table before beginning.  The "insert" command
22730 ** always overwrites every file named on the command-line, where as
22731 ** "update" only overwrites if the size or mtime or mode has changed.
22732 */
22733 static int arCreateOrUpdateCommand(
22734   ArCommand *pAr,                 /* Command arguments and options */
22735   int bUpdate,                    /* true for a --create. */
22736   int bOnlyIfChanged              /* Only update if file has changed */
22737 ){
22738   const char *zCreate =
22739       "CREATE TABLE IF NOT EXISTS sqlar(\n"
22740       "  name TEXT PRIMARY KEY,  -- name of the file\n"
22741       "  mode INT,               -- access permissions\n"
22742       "  mtime INT,              -- last modification time\n"
22743       "  sz INT,                 -- original file size\n"
22744       "  data BLOB               -- compressed content\n"
22745       ")";
22746   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
22747   const char *zInsertFmt[2] = {
22748      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
22749      "  SELECT\n"
22750      "    %s,\n"
22751      "    mode,\n"
22752      "    mtime,\n"
22753      "    CASE substr(lsmode(mode),1,1)\n"
22754      "      WHEN '-' THEN length(data)\n"
22755      "      WHEN 'd' THEN 0\n"
22756      "      ELSE -1 END,\n"
22757      "    sqlar_compress(data)\n"
22758      "  FROM fsdir(%Q,%Q) AS disk\n"
22759      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
22760      ,
22761      "REPLACE INTO %s(name,mode,mtime,data)\n"
22762      "  SELECT\n"
22763      "    %s,\n"
22764      "    mode,\n"
22765      "    mtime,\n"
22766      "    data\n"
22767      "  FROM fsdir(%Q,%Q) AS disk\n"
22768      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
22769   };
22770   int i;                          /* For iterating through azFile[] */
22771   int rc;                         /* Return code */
22772   const char *zTab = 0;           /* SQL table into which to insert */
22773   char *zSql;
22774   char zTemp[50];
22775   char *zExists = 0;
22776 
22777   arExecSql(pAr, "PRAGMA page_size=512");
22778   rc = arExecSql(pAr, "SAVEPOINT ar;");
22779   if( rc!=SQLITE_OK ) return rc;
22780   zTemp[0] = 0;
22781   if( pAr->bZip ){
22782     /* Initialize the zipfile virtual table, if necessary */
22783     if( pAr->zFile ){
22784       sqlite3_uint64 r;
22785       sqlite3_randomness(sizeof(r),&r);
22786       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
22787       zTab = zTemp;
22788       zSql = sqlite3_mprintf(
22789          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
22790          zTab, pAr->zFile
22791       );
22792       rc = arExecSql(pAr, zSql);
22793       sqlite3_free(zSql);
22794     }else{
22795       zTab = "zip";
22796     }
22797   }else{
22798     /* Initialize the table for an SQLAR */
22799     zTab = "sqlar";
22800     if( bUpdate==0 ){
22801       rc = arExecSql(pAr, zDrop);
22802       if( rc!=SQLITE_OK ) goto end_ar_transaction;
22803     }
22804     rc = arExecSql(pAr, zCreate);
22805   }
22806   if( bOnlyIfChanged ){
22807     zExists = sqlite3_mprintf(
22808       " AND NOT EXISTS("
22809           "SELECT 1 FROM %s AS mem"
22810           " WHERE mem.name=disk.name"
22811           " AND mem.mtime=disk.mtime"
22812           " AND mem.mode=disk.mode)", zTab);
22813   }else{
22814     zExists = sqlite3_mprintf("");
22815   }
22816   if( zExists==0 ) rc = SQLITE_NOMEM;
22817   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
22818     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
22819         pAr->bVerbose ? "shell_putsnl(name)" : "name",
22820         pAr->azArg[i], pAr->zDir, zExists);
22821     rc = arExecSql(pAr, zSql2);
22822     sqlite3_free(zSql2);
22823   }
22824 end_ar_transaction:
22825   if( rc!=SQLITE_OK ){
22826     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
22827   }else{
22828     rc = arExecSql(pAr, "RELEASE ar;");
22829     if( pAr->bZip && pAr->zFile ){
22830       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
22831       arExecSql(pAr, zSql);
22832       sqlite3_free(zSql);
22833     }
22834   }
22835   sqlite3_free(zExists);
22836   return rc;
22837 }
22838 
22839 /*
22840 ** Implementation of ".ar" dot command.
22841 */
22842 static int arDotCommand(
22843   ShellState *pState,          /* Current shell tool state */
22844   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
22845   char **azArg,                /* Array of arguments passed to dot command */
22846   int nArg                     /* Number of entries in azArg[] */
22847 ){
22848   ArCommand cmd;
22849   int rc;
22850   memset(&cmd, 0, sizeof(cmd));
22851   cmd.fromCmdLine = fromCmdLine;
22852   rc = arParseCommand(azArg, nArg, &cmd);
22853   if( rc==SQLITE_OK ){
22854     int eDbType = SHELL_OPEN_UNSPEC;
22855     cmd.p = pState;
22856     cmd.db = pState->db;
22857     if( cmd.zFile ){
22858       eDbType = deduceDatabaseType(cmd.zFile, 1);
22859     }else{
22860       eDbType = pState->openMode;
22861     }
22862     if( eDbType==SHELL_OPEN_ZIPFILE ){
22863       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
22864         if( cmd.zFile==0 ){
22865           cmd.zSrcTable = sqlite3_mprintf("zip");
22866         }else{
22867           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
22868         }
22869       }
22870       cmd.bZip = 1;
22871     }else if( cmd.zFile ){
22872       int flags;
22873       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
22874       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
22875            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
22876         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
22877       }else{
22878         flags = SQLITE_OPEN_READONLY;
22879       }
22880       cmd.db = 0;
22881       if( cmd.bDryRun ){
22882         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
22883              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
22884       }
22885       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
22886              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
22887       if( rc!=SQLITE_OK ){
22888         utf8_printf(stderr, "cannot open file: %s (%s)\n",
22889             cmd.zFile, sqlite3_errmsg(cmd.db)
22890         );
22891         goto end_ar_command;
22892       }
22893       sqlite3_fileio_init(cmd.db, 0, 0);
22894       sqlite3_sqlar_init(cmd.db, 0, 0);
22895       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
22896                               shellPutsFunc, 0, 0);
22897 
22898     }
22899     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
22900       if( cmd.eCmd!=AR_CMD_CREATE
22901        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
22902       ){
22903         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
22904         rc = SQLITE_ERROR;
22905         goto end_ar_command;
22906       }
22907       cmd.zSrcTable = sqlite3_mprintf("sqlar");
22908     }
22909 
22910     switch( cmd.eCmd ){
22911       case AR_CMD_CREATE:
22912         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
22913         break;
22914 
22915       case AR_CMD_EXTRACT:
22916         rc = arExtractCommand(&cmd);
22917         break;
22918 
22919       case AR_CMD_LIST:
22920         rc = arListCommand(&cmd);
22921         break;
22922 
22923       case AR_CMD_HELP:
22924         arUsage(pState->out);
22925         break;
22926 
22927       case AR_CMD_INSERT:
22928         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
22929         break;
22930 
22931       case AR_CMD_REMOVE:
22932         rc = arRemoveCommand(&cmd);
22933         break;
22934 
22935       default:
22936         assert( cmd.eCmd==AR_CMD_UPDATE );
22937         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
22938         break;
22939     }
22940   }
22941 end_ar_command:
22942   if( cmd.db!=pState->db ){
22943     close_db(cmd.db);
22944   }
22945   sqlite3_free(cmd.zSrcTable);
22946 
22947   return rc;
22948 }
22949 /* End of the ".archive" or ".ar" command logic
22950 *******************************************************************************/
22951 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
22952 
22953 #if SQLITE_SHELL_HAVE_RECOVER
22954 
22955 /*
22956 ** This function is used as a callback by the recover extension. Simply
22957 ** print the supplied SQL statement to stdout.
22958 */
22959 static int recoverSqlCb(void *pCtx, const char *zSql){
22960   ShellState *pState = (ShellState*)pCtx;
22961   utf8_printf(pState->out, "%s;\n", zSql);
22962   return SQLITE_OK;
22963 }
22964 
22965 /*
22966 ** This function is called to recover data from the database. A script
22967 ** to construct a new database containing all recovered data is output
22968 ** on stream pState->out.
22969 */
22970 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
22971   int rc = SQLITE_OK;
22972   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
22973   const char *zLAF = "lost_and_found";
22974   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
22975   int bRowids = 1;                /* 0 if --no-rowids */
22976   sqlite3_recover *p = 0;
22977   int i = 0;
22978 
22979   for(i=1; i<nArg; i++){
22980     char *z = azArg[i];
22981     int n;
22982     if( z[0]=='-' && z[1]=='-' ) z++;
22983     n = strlen30(z);
22984     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
22985       bFreelist = 0;
22986     }else
22987     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
22988       /* This option determines the name of the ATTACH-ed database used
22989       ** internally by the recovery extension.  The default is "" which
22990       ** means to use a temporary database that is automatically deleted
22991       ** when closed.  This option is undocumented and might disappear at
22992       ** any moment. */
22993       i++;
22994       zRecoveryDb = azArg[i];
22995     }else
22996     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
22997       i++;
22998       zLAF = azArg[i];
22999     }else
23000     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
23001       bRowids = 0;
23002     }
23003     else{
23004       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
23005       showHelp(pState->out, azArg[0]);
23006       return 1;
23007     }
23008   }
23009 
23010   p = sqlite3_recover_init_sql(
23011       pState->db, "main", recoverSqlCb, (void*)pState
23012   );
23013 
23014   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
23015   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
23016   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
23017   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
23018 
23019   sqlite3_recover_run(p);
23020   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
23021     const char *zErr = sqlite3_recover_errmsg(p);
23022     int errCode = sqlite3_recover_errcode(p);
23023     raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
23024   }
23025   rc = sqlite3_recover_finish(p);
23026   return rc;
23027 }
23028 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23029 
23030 
23031 /*
23032  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
23033  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
23034  *   close db and set it to 0, and return the columns spec, to later
23035  *   be sqlite3_free()'ed by the caller.
23036  * The return is 0 when either:
23037  *   (a) The db was not initialized and zCol==0 (There are no columns.)
23038  *   (b) zCol!=0  (Column was added, db initialized as needed.)
23039  * The 3rd argument, pRenamed, references an out parameter. If the
23040  * pointer is non-zero, its referent will be set to a summary of renames
23041  * done if renaming was necessary, or set to 0 if none was done. The out
23042  * string (if any) must be sqlite3_free()'ed by the caller.
23043  */
23044 #ifdef SHELL_DEBUG
23045 #define rc_err_oom_die(rc) \
23046   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
23047   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
23048     fprintf(stderr,"E:%d\n",rc), assert(0)
23049 #else
23050 static void rc_err_oom_die(int rc){
23051   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
23052   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
23053 }
23054 #endif
23055 
23056 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
23057 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
23058 #else  /* Otherwise, memory is faster/better for the transient DB. */
23059 static const char *zCOL_DB = ":memory:";
23060 #endif
23061 
23062 /* Define character (as C string) to separate generated column ordinal
23063  * from protected part of incoming column names. This defaults to "_"
23064  * so that incoming column identifiers that did not need not be quoted
23065  * remain usable without being quoted. It must be one character.
23066  */
23067 #ifndef SHELL_AUTOCOLUMN_SEP
23068 # define AUTOCOLUMN_SEP "_"
23069 #else
23070 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
23071 #endif
23072 
23073 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
23074   /* Queries and D{D,M}L used here */
23075   static const char * const zTabMake = "\
23076 CREATE TABLE ColNames(\
23077  cpos INTEGER PRIMARY KEY,\
23078  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
23079 CREATE VIEW RepeatedNames AS \
23080 SELECT DISTINCT t.name FROM ColNames t \
23081 WHERE t.name COLLATE NOCASE IN (\
23082  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
23083 );\
23084 ";
23085   static const char * const zTabFill = "\
23086 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
23087  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
23088 ";
23089   static const char * const zHasDupes = "\
23090 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
23091  <count(name) FROM ColNames\
23092 ";
23093 #ifdef SHELL_COLUMN_RENAME_CLEAN
23094   static const char * const zDedoctor = "\
23095 UPDATE ColNames SET chop=iif(\
23096   (substring(name,nlen,1) BETWEEN '0' AND '9')\
23097   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
23098  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
23099  0\
23100 )\
23101 ";
23102 #endif
23103   static const char * const zSetReps = "\
23104 UPDATE ColNames AS t SET reps=\
23105 (SELECT count(*) FROM ColNames d \
23106  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
23107  COLLATE NOCASE\
23108 )\
23109 ";
23110 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
23111   static const char * const zColDigits = "\
23112 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
23113 ";
23114 #else
23115   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
23116   static const char * const zColDigits = "\
23117 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
23118  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
23119  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
23120 ";
23121 #endif
23122   static const char * const zRenameRank =
23123 #ifdef SHELL_COLUMN_RENAME_CLEAN
23124     "UPDATE ColNames AS t SET suff="
23125     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
23126 #else /* ...RENAME_MINIMAL_ONE_PASS */
23127 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
23128 "  SELECT 0 AS nlz"
23129 "  UNION"
23130 "  SELECT nlz+1 AS nlz FROM Lzn"
23131 "  WHERE EXISTS("
23132 "   SELECT 1"
23133 "   FROM ColNames t, ColNames o"
23134 "   WHERE"
23135 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
23136 "     printf('%s"AUTOCOLUMN_SEP"%s',"
23137 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
23138 "     t.name"
23139 "    )"
23140 "    ="
23141 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
23142 "     printf('%s"AUTOCOLUMN_SEP"%s',"
23143 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
23144 "     o.name"
23145 "    )"
23146 "    COLLATE NOCASE"
23147 "    AND o.cpos<>t.cpos"
23148 "   GROUP BY t.cpos"
23149 "  )"
23150 ") UPDATE Colnames AS t SET"
23151 " chop = 0," /* No chopping, never touch incoming names. */
23152 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
23153 "  printf('"AUTOCOLUMN_SEP"%s', substring("
23154 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
23155 "  ''"
23156 " )"
23157 #endif
23158     ;
23159   static const char * const zCollectVar = "\
23160 SELECT\
23161  '('||x'0a'\
23162  || group_concat(\
23163   cname||' TEXT',\
23164   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
23165  ||')' AS ColsSpec \
23166 FROM (\
23167  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
23168  FROM ColNames ORDER BY cpos\
23169 )";
23170   static const char * const zRenamesDone =
23171     "SELECT group_concat("
23172     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
23173     " ','||x'0a')"
23174     "FROM ColNames WHERE suff<>'' OR chop!=0"
23175     ;
23176   int rc;
23177   sqlite3_stmt *pStmt = 0;
23178   assert(pDb!=0);
23179   if( zColNew ){
23180     /* Add initial or additional column. Init db if necessary. */
23181     if( *pDb==0 ){
23182       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
23183 #ifdef SHELL_COLFIX_DB
23184       if(*zCOL_DB!=':')
23185         sqlite3_exec(*pDb,"drop table if exists ColNames;"
23186                      "drop view if exists RepeatedNames;",0,0,0);
23187 #endif
23188       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
23189       rc_err_oom_die(rc);
23190     }
23191     assert(*pDb!=0);
23192     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
23193     rc_err_oom_die(rc);
23194     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
23195     rc_err_oom_die(rc);
23196     rc = sqlite3_step(pStmt);
23197     rc_err_oom_die(rc);
23198     sqlite3_finalize(pStmt);
23199     return 0;
23200   }else if( *pDb==0 ){
23201     return 0;
23202   }else{
23203     /* Formulate the columns spec, close the DB, zero *pDb. */
23204     char *zColsSpec = 0;
23205     int hasDupes = db_int(*pDb, zHasDupes);
23206     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
23207     if( hasDupes ){
23208 #ifdef SHELL_COLUMN_RENAME_CLEAN
23209       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
23210       rc_err_oom_die(rc);
23211 #endif
23212       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
23213       rc_err_oom_die(rc);
23214       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
23215       rc_err_oom_die(rc);
23216       sqlite3_bind_int(pStmt, 1, nDigits);
23217       rc = sqlite3_step(pStmt);
23218       sqlite3_finalize(pStmt);
23219       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
23220     }
23221     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
23222     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
23223     rc_err_oom_die(rc);
23224     rc = sqlite3_step(pStmt);
23225     if( rc==SQLITE_ROW ){
23226       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
23227     }else{
23228       zColsSpec = 0;
23229     }
23230     if( pzRenamed!=0 ){
23231       if( !hasDupes ) *pzRenamed = 0;
23232       else{
23233         sqlite3_finalize(pStmt);
23234         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
23235             && SQLITE_ROW==sqlite3_step(pStmt) ){
23236           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
23237         }else
23238           *pzRenamed = 0;
23239       }
23240     }
23241     sqlite3_finalize(pStmt);
23242     sqlite3_close(*pDb);
23243     *pDb = 0;
23244     return zColsSpec;
23245   }
23246 }
23247 
23248 /*
23249 ** If an input line begins with "." then invoke this routine to
23250 ** process that line.
23251 **
23252 ** Return 1 on error, 2 to exit, and 0 otherwise.
23253 */
23254 static int do_meta_command(char *zLine, ShellState *p){
23255   int h = 1;
23256   int nArg = 0;
23257   int n, c;
23258   int rc = 0;
23259   char *azArg[52];
23260 
23261 #ifndef SQLITE_OMIT_VIRTUALTABLE
23262   if( p->expert.pExpert ){
23263     expertFinish(p, 1, 0);
23264   }
23265 #endif
23266 
23267   /* Parse the input line into tokens.
23268   */
23269   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
23270     while( IsSpace(zLine[h]) ){ h++; }
23271     if( zLine[h]==0 ) break;
23272     if( zLine[h]=='\'' || zLine[h]=='"' ){
23273       int delim = zLine[h++];
23274       azArg[nArg++] = &zLine[h];
23275       while( zLine[h] && zLine[h]!=delim ){
23276         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
23277         h++;
23278       }
23279       if( zLine[h]==delim ){
23280         zLine[h++] = 0;
23281       }
23282       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
23283     }else{
23284       azArg[nArg++] = &zLine[h];
23285       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
23286       if( zLine[h] ) zLine[h++] = 0;
23287       resolve_backslashes(azArg[nArg-1]);
23288     }
23289   }
23290   azArg[nArg] = 0;
23291 
23292   /* Process the input line.
23293   */
23294   if( nArg==0 ) return 0; /* no tokens, no error */
23295   n = strlen30(azArg[0]);
23296   c = azArg[0][0];
23297   clearTempFile(p);
23298 
23299 #ifndef SQLITE_OMIT_AUTHORIZATION
23300   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
23301     if( nArg!=2 ){
23302       raw_printf(stderr, "Usage: .auth ON|OFF\n");
23303       rc = 1;
23304       goto meta_command_exit;
23305     }
23306     open_db(p, 0);
23307     if( booleanValue(azArg[1]) ){
23308       sqlite3_set_authorizer(p->db, shellAuth, p);
23309     }else if( p->bSafeModePersist ){
23310       sqlite3_set_authorizer(p->db, safeModeAuth, p);
23311     }else{
23312       sqlite3_set_authorizer(p->db, 0, 0);
23313     }
23314   }else
23315 #endif
23316 
23317 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
23318   && !defined(SQLITE_SHELL_FIDDLE)
23319   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
23320     open_db(p, 0);
23321     failIfSafeMode(p, "cannot run .archive in safe mode");
23322     rc = arDotCommand(p, 0, azArg, nArg);
23323   }else
23324 #endif
23325 
23326 #ifndef SQLITE_SHELL_FIDDLE
23327   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
23328    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
23329   ){
23330     const char *zDestFile = 0;
23331     const char *zDb = 0;
23332     sqlite3 *pDest;
23333     sqlite3_backup *pBackup;
23334     int j;
23335     int bAsync = 0;
23336     const char *zVfs = 0;
23337     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
23338     for(j=1; j<nArg; j++){
23339       const char *z = azArg[j];
23340       if( z[0]=='-' ){
23341         if( z[1]=='-' ) z++;
23342         if( cli_strcmp(z, "-append")==0 ){
23343           zVfs = "apndvfs";
23344         }else
23345         if( cli_strcmp(z, "-async")==0 ){
23346           bAsync = 1;
23347         }else
23348         {
23349           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
23350           return 1;
23351         }
23352       }else if( zDestFile==0 ){
23353         zDestFile = azArg[j];
23354       }else if( zDb==0 ){
23355         zDb = zDestFile;
23356         zDestFile = azArg[j];
23357       }else{
23358         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
23359         return 1;
23360       }
23361     }
23362     if( zDestFile==0 ){
23363       raw_printf(stderr, "missing FILENAME argument on .backup\n");
23364       return 1;
23365     }
23366     if( zDb==0 ) zDb = "main";
23367     rc = sqlite3_open_v2(zDestFile, &pDest,
23368                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
23369     if( rc!=SQLITE_OK ){
23370       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
23371       close_db(pDest);
23372       return 1;
23373     }
23374     if( bAsync ){
23375       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
23376                    0, 0, 0);
23377     }
23378     open_db(p, 0);
23379     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
23380     if( pBackup==0 ){
23381       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
23382       close_db(pDest);
23383       return 1;
23384     }
23385     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
23386     sqlite3_backup_finish(pBackup);
23387     if( rc==SQLITE_DONE ){
23388       rc = 0;
23389     }else{
23390       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
23391       rc = 1;
23392     }
23393     close_db(pDest);
23394   }else
23395 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23396 
23397   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
23398     if( nArg==2 ){
23399       bail_on_error = booleanValue(azArg[1]);
23400     }else{
23401       raw_printf(stderr, "Usage: .bail on|off\n");
23402       rc = 1;
23403     }
23404   }else
23405 
23406   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
23407     if( nArg==2 ){
23408       if( booleanValue(azArg[1]) ){
23409         setBinaryMode(p->out, 1);
23410       }else{
23411         setTextMode(p->out, 1);
23412       }
23413     }else{
23414       raw_printf(stderr, "Usage: .binary on|off\n");
23415       rc = 1;
23416     }
23417   }else
23418 
23419   /* The undocumented ".breakpoint" command causes a call to the no-op
23420   ** routine named test_breakpoint().
23421   */
23422   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
23423     test_breakpoint();
23424   }else
23425 
23426 #ifndef SQLITE_SHELL_FIDDLE
23427   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
23428     failIfSafeMode(p, "cannot run .cd in safe mode");
23429     if( nArg==2 ){
23430 #if defined(_WIN32) || defined(WIN32)
23431       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
23432       rc = !SetCurrentDirectoryW(z);
23433       sqlite3_free(z);
23434 #else
23435       rc = chdir(azArg[1]);
23436 #endif
23437       if( rc ){
23438         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
23439         rc = 1;
23440       }
23441     }else{
23442       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
23443       rc = 1;
23444     }
23445   }else
23446 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23447 
23448   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
23449     if( nArg==2 ){
23450       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
23451     }else{
23452       raw_printf(stderr, "Usage: .changes on|off\n");
23453       rc = 1;
23454     }
23455   }else
23456 
23457 #ifndef SQLITE_SHELL_FIDDLE
23458   /* Cancel output redirection, if it is currently set (by .testcase)
23459   ** Then read the content of the testcase-out.txt file and compare against
23460   ** azArg[1].  If there are differences, report an error and exit.
23461   */
23462   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
23463     char *zRes = 0;
23464     output_reset(p);
23465     if( nArg!=2 ){
23466       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
23467       rc = 2;
23468     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
23469       rc = 2;
23470     }else if( testcase_glob(azArg[1],zRes)==0 ){
23471       utf8_printf(stderr,
23472                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
23473                  p->zTestcase, azArg[1], zRes);
23474       rc = 1;
23475     }else{
23476       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
23477       p->nCheck++;
23478     }
23479     sqlite3_free(zRes);
23480   }else
23481 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23482 
23483 #ifndef SQLITE_SHELL_FIDDLE
23484   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
23485     failIfSafeMode(p, "cannot run .clone in safe mode");
23486     if( nArg==2 ){
23487       tryToClone(p, azArg[1]);
23488     }else{
23489       raw_printf(stderr, "Usage: .clone FILENAME\n");
23490       rc = 1;
23491     }
23492   }else
23493 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23494 
23495   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
23496     if( nArg==1 ){
23497       /* List available connections */
23498       int i;
23499       for(i=0; i<ArraySize(p->aAuxDb); i++){
23500         const char *zFile = p->aAuxDb[i].zDbFilename;
23501         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
23502           zFile = "(not open)";
23503         }else if( zFile==0 ){
23504           zFile = "(memory)";
23505         }else if( zFile[0]==0 ){
23506           zFile = "(temporary-file)";
23507         }
23508         if( p->pAuxDb == &p->aAuxDb[i] ){
23509           utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
23510         }else if( p->aAuxDb[i].db!=0 ){
23511           utf8_printf(stdout, "       %d: %s\n", i, zFile);
23512         }
23513       }
23514     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
23515       int i = azArg[1][0] - '0';
23516       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
23517         p->pAuxDb->db = p->db;
23518         p->pAuxDb = &p->aAuxDb[i];
23519         globalDb = p->db = p->pAuxDb->db;
23520         p->pAuxDb->db = 0;
23521       }
23522     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
23523            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
23524       int i = azArg[2][0] - '0';
23525       if( i<0 || i>=ArraySize(p->aAuxDb) ){
23526         /* No-op */
23527       }else if( p->pAuxDb == &p->aAuxDb[i] ){
23528         raw_printf(stderr, "cannot close the active database connection\n");
23529         rc = 1;
23530       }else if( p->aAuxDb[i].db ){
23531         session_close_all(p, i);
23532         close_db(p->aAuxDb[i].db);
23533         p->aAuxDb[i].db = 0;
23534       }
23535     }else{
23536       raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
23537       rc = 1;
23538     }
23539   }else
23540 
23541   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
23542     char **azName = 0;
23543     int nName = 0;
23544     sqlite3_stmt *pStmt;
23545     int i;
23546     open_db(p, 0);
23547     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
23548     if( rc ){
23549       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
23550       rc = 1;
23551     }else{
23552       while( sqlite3_step(pStmt)==SQLITE_ROW ){
23553         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
23554         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
23555         if( zSchema==0 || zFile==0 ) continue;
23556         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
23557         shell_check_oom(azName);
23558         azName[nName*2] = strdup(zSchema);
23559         azName[nName*2+1] = strdup(zFile);
23560         nName++;
23561       }
23562     }
23563     sqlite3_finalize(pStmt);
23564     for(i=0; i<nName; i++){
23565       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
23566       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
23567       const char *z = azName[i*2+1];
23568       utf8_printf(p->out, "%s: %s %s%s\n",
23569          azName[i*2],
23570          z && z[0] ? z : "\"\"",
23571          bRdonly ? "r/o" : "r/w",
23572          eTxn==SQLITE_TXN_NONE ? "" :
23573             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
23574       free(azName[i*2]);
23575       free(azName[i*2+1]);
23576     }
23577     sqlite3_free(azName);
23578   }else
23579 
23580   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
23581     static const struct DbConfigChoices {
23582       const char *zName;
23583       int op;
23584     } aDbConfig[] = {
23585         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
23586         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
23587         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
23588         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
23589         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
23590         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
23591         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
23592         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
23593         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
23594         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
23595         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
23596         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
23597         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
23598         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
23599         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
23600         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
23601         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
23602         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
23603     };
23604     int ii, v;
23605     open_db(p, 0);
23606     for(ii=0; ii<ArraySize(aDbConfig); ii++){
23607       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
23608       if( nArg>=3 ){
23609         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
23610       }
23611       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
23612       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
23613       if( nArg>1 ) break;
23614     }
23615     if( nArg>1 && ii==ArraySize(aDbConfig) ){
23616       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
23617       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
23618     }
23619   }else
23620 
23621 #if SQLITE_SHELL_HAVE_RECOVER
23622   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
23623     rc = shell_dbinfo_command(p, nArg, azArg);
23624   }else
23625 
23626   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
23627     open_db(p, 0);
23628     rc = recoverDatabaseCmd(p, nArg, azArg);
23629   }else
23630 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23631 
23632   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
23633     char *zLike = 0;
23634     char *zSql;
23635     int i;
23636     int savedShowHeader = p->showHeader;
23637     int savedShellFlags = p->shellFlgs;
23638     ShellClearFlag(p,
23639        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
23640        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
23641     for(i=1; i<nArg; i++){
23642       if( azArg[i][0]=='-' ){
23643         const char *z = azArg[i]+1;
23644         if( z[0]=='-' ) z++;
23645         if( cli_strcmp(z,"preserve-rowids")==0 ){
23646 #ifdef SQLITE_OMIT_VIRTUALTABLE
23647           raw_printf(stderr, "The --preserve-rowids option is not compatible"
23648                              " with SQLITE_OMIT_VIRTUALTABLE\n");
23649           rc = 1;
23650           sqlite3_free(zLike);
23651           goto meta_command_exit;
23652 #else
23653           ShellSetFlag(p, SHFLG_PreserveRowid);
23654 #endif
23655         }else
23656         if( cli_strcmp(z,"newlines")==0 ){
23657           ShellSetFlag(p, SHFLG_Newlines);
23658         }else
23659         if( cli_strcmp(z,"data-only")==0 ){
23660           ShellSetFlag(p, SHFLG_DumpDataOnly);
23661         }else
23662         if( cli_strcmp(z,"nosys")==0 ){
23663           ShellSetFlag(p, SHFLG_DumpNoSys);
23664         }else
23665         {
23666           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
23667           rc = 1;
23668           sqlite3_free(zLike);
23669           goto meta_command_exit;
23670         }
23671       }else{
23672         /* azArg[i] contains a LIKE pattern. This ".dump" request should
23673         ** only dump data for tables for which either the table name matches
23674         ** the LIKE pattern, or the table appears to be a shadow table of
23675         ** a virtual table for which the name matches the LIKE pattern.
23676         */
23677         char *zExpr = sqlite3_mprintf(
23678             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
23679             "  SELECT 1 FROM sqlite_schema WHERE "
23680             "    name LIKE %Q ESCAPE '\\' AND"
23681             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
23682             "    substr(o.name, 1, length(name)+1) == (name||'_')"
23683             ")", azArg[i], azArg[i]
23684         );
23685 
23686         if( zLike ){
23687           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
23688         }else{
23689           zLike = zExpr;
23690         }
23691       }
23692     }
23693 
23694     open_db(p, 0);
23695 
23696     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23697       /* When playing back a "dump", the content might appear in an order
23698       ** which causes immediate foreign key constraints to be violated.
23699       ** So disable foreign-key constraint enforcement to prevent problems. */
23700       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
23701       raw_printf(p->out, "BEGIN TRANSACTION;\n");
23702     }
23703     p->writableSchema = 0;
23704     p->showHeader = 0;
23705     /* Set writable_schema=ON since doing so forces SQLite to initialize
23706     ** as much of the schema as it can even if the sqlite_schema table is
23707     ** corrupt. */
23708     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
23709     p->nErr = 0;
23710     if( zLike==0 ) zLike = sqlite3_mprintf("true");
23711     zSql = sqlite3_mprintf(
23712       "SELECT name, type, sql FROM sqlite_schema AS o "
23713       "WHERE (%s) AND type=='table'"
23714       "  AND sql NOT NULL"
23715       " ORDER BY tbl_name='sqlite_sequence', rowid",
23716       zLike
23717     );
23718     run_schema_dump_query(p,zSql);
23719     sqlite3_free(zSql);
23720     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23721       zSql = sqlite3_mprintf(
23722         "SELECT sql FROM sqlite_schema AS o "
23723         "WHERE (%s) AND sql NOT NULL"
23724         "  AND type IN ('index','trigger','view')",
23725         zLike
23726       );
23727       run_table_dump_query(p, zSql);
23728       sqlite3_free(zSql);
23729     }
23730     sqlite3_free(zLike);
23731     if( p->writableSchema ){
23732       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
23733       p->writableSchema = 0;
23734     }
23735     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
23736     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
23737     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23738       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
23739     }
23740     p->showHeader = savedShowHeader;
23741     p->shellFlgs = savedShellFlags;
23742   }else
23743 
23744   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
23745     if( nArg==2 ){
23746       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
23747     }else{
23748       raw_printf(stderr, "Usage: .echo on|off\n");
23749       rc = 1;
23750     }
23751   }else
23752 
23753   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
23754     if( nArg==2 ){
23755       p->autoEQPtest = 0;
23756       if( p->autoEQPtrace ){
23757         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
23758         p->autoEQPtrace = 0;
23759       }
23760       if( cli_strcmp(azArg[1],"full")==0 ){
23761         p->autoEQP = AUTOEQP_full;
23762       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
23763         p->autoEQP = AUTOEQP_trigger;
23764 #ifdef SQLITE_DEBUG
23765       }else if( cli_strcmp(azArg[1],"test")==0 ){
23766         p->autoEQP = AUTOEQP_on;
23767         p->autoEQPtest = 1;
23768       }else if( cli_strcmp(azArg[1],"trace")==0 ){
23769         p->autoEQP = AUTOEQP_full;
23770         p->autoEQPtrace = 1;
23771         open_db(p, 0);
23772         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
23773         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
23774 #endif
23775       }else{
23776         p->autoEQP = (u8)booleanValue(azArg[1]);
23777       }
23778     }else{
23779       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
23780       rc = 1;
23781     }
23782   }else
23783 
23784 #ifndef SQLITE_SHELL_FIDDLE
23785   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
23786     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
23787     rc = 2;
23788   }else
23789 #endif
23790 
23791   /* The ".explain" command is automatic now.  It is largely pointless.  It
23792   ** retained purely for backwards compatibility */
23793   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
23794     int val = 1;
23795     if( nArg>=2 ){
23796       if( cli_strcmp(azArg[1],"auto")==0 ){
23797         val = 99;
23798       }else{
23799         val =  booleanValue(azArg[1]);
23800       }
23801     }
23802     if( val==1 && p->mode!=MODE_Explain ){
23803       p->normalMode = p->mode;
23804       p->mode = MODE_Explain;
23805       p->autoExplain = 0;
23806     }else if( val==0 ){
23807       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
23808       p->autoExplain = 0;
23809     }else if( val==99 ){
23810       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
23811       p->autoExplain = 1;
23812     }
23813   }else
23814 
23815 #ifndef SQLITE_OMIT_VIRTUALTABLE
23816   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
23817     if( p->bSafeMode ){
23818       raw_printf(stderr,
23819         "Cannot run experimental commands such as \"%s\" in safe mode\n",
23820         azArg[0]);
23821       rc = 1;
23822     }else{
23823       open_db(p, 0);
23824       expertDotCommand(p, azArg, nArg);
23825     }
23826   }else
23827 #endif
23828 
23829   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
23830     static const struct {
23831        const char *zCtrlName;   /* Name of a test-control option */
23832        int ctrlCode;            /* Integer code for that option */
23833        const char *zUsage;      /* Usage notes */
23834     } aCtrl[] = {
23835       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
23836       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
23837       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
23838       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
23839       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
23840    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
23841       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
23842       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
23843       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
23844       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
23845    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
23846     };
23847     int filectrl = -1;
23848     int iCtrl = -1;
23849     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
23850     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
23851     int n2, i;
23852     const char *zCmd = 0;
23853     const char *zSchema = 0;
23854 
23855     open_db(p, 0);
23856     zCmd = nArg>=2 ? azArg[1] : "help";
23857 
23858     if( zCmd[0]=='-'
23859      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
23860      && nArg>=4
23861     ){
23862       zSchema = azArg[2];
23863       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
23864       nArg -= 2;
23865       zCmd = azArg[1];
23866     }
23867 
23868     /* The argument can optionally begin with "-" or "--" */
23869     if( zCmd[0]=='-' && zCmd[1] ){
23870       zCmd++;
23871       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
23872     }
23873 
23874     /* --help lists all file-controls */
23875     if( cli_strcmp(zCmd,"help")==0 ){
23876       utf8_printf(p->out, "Available file-controls:\n");
23877       for(i=0; i<ArraySize(aCtrl); i++){
23878         utf8_printf(p->out, "  .filectrl %s %s\n",
23879                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
23880       }
23881       rc = 1;
23882       goto meta_command_exit;
23883     }
23884 
23885     /* convert filectrl text option to value. allow any unique prefix
23886     ** of the option name, or a numerical value. */
23887     n2 = strlen30(zCmd);
23888     for(i=0; i<ArraySize(aCtrl); i++){
23889       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
23890         if( filectrl<0 ){
23891           filectrl = aCtrl[i].ctrlCode;
23892           iCtrl = i;
23893         }else{
23894           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
23895                               "Use \".filectrl --help\" for help\n", zCmd);
23896           rc = 1;
23897           goto meta_command_exit;
23898         }
23899       }
23900     }
23901     if( filectrl<0 ){
23902       utf8_printf(stderr,"Error: unknown file-control: %s\n"
23903                          "Use \".filectrl --help\" for help\n", zCmd);
23904     }else{
23905       switch(filectrl){
23906         case SQLITE_FCNTL_SIZE_LIMIT: {
23907           if( nArg!=2 && nArg!=3 ) break;
23908           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
23909           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
23910           isOk = 1;
23911           break;
23912         }
23913         case SQLITE_FCNTL_LOCK_TIMEOUT:
23914         case SQLITE_FCNTL_CHUNK_SIZE: {
23915           int x;
23916           if( nArg!=3 ) break;
23917           x = (int)integerValue(azArg[2]);
23918           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23919           isOk = 2;
23920           break;
23921         }
23922         case SQLITE_FCNTL_PERSIST_WAL:
23923         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
23924           int x;
23925           if( nArg!=2 && nArg!=3 ) break;
23926           x = nArg==3 ? booleanValue(azArg[2]) : -1;
23927           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23928           iRes = x;
23929           isOk = 1;
23930           break;
23931         }
23932         case SQLITE_FCNTL_DATA_VERSION:
23933         case SQLITE_FCNTL_HAS_MOVED: {
23934           int x;
23935           if( nArg!=2 ) break;
23936           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23937           iRes = x;
23938           isOk = 1;
23939           break;
23940         }
23941         case SQLITE_FCNTL_TEMPFILENAME: {
23942           char *z = 0;
23943           if( nArg!=2 ) break;
23944           sqlite3_file_control(p->db, zSchema, filectrl, &z);
23945           if( z ){
23946             utf8_printf(p->out, "%s\n", z);
23947             sqlite3_free(z);
23948           }
23949           isOk = 2;
23950           break;
23951         }
23952         case SQLITE_FCNTL_RESERVE_BYTES: {
23953           int x;
23954           if( nArg>=3 ){
23955             x = atoi(azArg[2]);
23956             sqlite3_file_control(p->db, zSchema, filectrl, &x);
23957           }
23958           x = -1;
23959           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23960           utf8_printf(p->out,"%d\n", x);
23961           isOk = 2;
23962           break;
23963         }
23964       }
23965     }
23966     if( isOk==0 && iCtrl>=0 ){
23967       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
23968       rc = 1;
23969     }else if( isOk==1 ){
23970       char zBuf[100];
23971       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
23972       raw_printf(p->out, "%s\n", zBuf);
23973     }
23974   }else
23975 
23976   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
23977     ShellState data;
23978     int doStats = 0;
23979     memcpy(&data, p, sizeof(data));
23980     data.showHeader = 0;
23981     data.cMode = data.mode = MODE_Semi;
23982     if( nArg==2 && optionMatch(azArg[1], "indent") ){
23983       data.cMode = data.mode = MODE_Pretty;
23984       nArg = 1;
23985     }
23986     if( nArg!=1 ){
23987       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
23988       rc = 1;
23989       goto meta_command_exit;
23990     }
23991     open_db(p, 0);
23992     rc = sqlite3_exec(p->db,
23993        "SELECT sql FROM"
23994        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
23995        "     FROM sqlite_schema UNION ALL"
23996        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
23997        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
23998        "ORDER BY x",
23999        callback, &data, 0
24000     );
24001     if( rc==SQLITE_OK ){
24002       sqlite3_stmt *pStmt;
24003       rc = sqlite3_prepare_v2(p->db,
24004                "SELECT rowid FROM sqlite_schema"
24005                " WHERE name GLOB 'sqlite_stat[134]'",
24006                -1, &pStmt, 0);
24007       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
24008       sqlite3_finalize(pStmt);
24009     }
24010     if( doStats==0 ){
24011       raw_printf(p->out, "/* No STAT tables available */\n");
24012     }else{
24013       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
24014       data.cMode = data.mode = MODE_Insert;
24015       data.zDestTable = "sqlite_stat1";
24016       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
24017       data.zDestTable = "sqlite_stat4";
24018       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
24019       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
24020     }
24021   }else
24022 
24023   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
24024     if( nArg==2 ){
24025       p->showHeader = booleanValue(azArg[1]);
24026       p->shellFlgs |= SHFLG_HeaderSet;
24027     }else{
24028       raw_printf(stderr, "Usage: .headers on|off\n");
24029       rc = 1;
24030     }
24031   }else
24032 
24033   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
24034     if( nArg>=2 ){
24035       n = showHelp(p->out, azArg[1]);
24036       if( n==0 ){
24037         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
24038       }
24039     }else{
24040       showHelp(p->out, 0);
24041     }
24042   }else
24043 
24044 #ifndef SQLITE_SHELL_FIDDLE
24045   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
24046     char *zTable = 0;           /* Insert data into this table */
24047     char *zSchema = 0;          /* within this schema (may default to "main") */
24048     char *zFile = 0;            /* Name of file to extra content from */
24049     sqlite3_stmt *pStmt = NULL; /* A statement */
24050     int nCol;                   /* Number of columns in the table */
24051     int nByte;                  /* Number of bytes in an SQL string */
24052     int i, j;                   /* Loop counters */
24053     int needCommit;             /* True to COMMIT or ROLLBACK at end */
24054     int nSep;                   /* Number of bytes in p->colSeparator[] */
24055     char *zSql;                 /* An SQL statement */
24056     char *zFullTabName;         /* Table name with schema if applicable */
24057     ImportCtx sCtx;             /* Reader context */
24058     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
24059     int eVerbose = 0;           /* Larger for more console output */
24060     int nSkip = 0;              /* Initial lines to skip */
24061     int useOutputMode = 1;      /* Use output mode to determine separators */
24062     char *zCreate = 0;          /* CREATE TABLE statement text */
24063 
24064     failIfSafeMode(p, "cannot run .import in safe mode");
24065     memset(&sCtx, 0, sizeof(sCtx));
24066     if( p->mode==MODE_Ascii ){
24067       xRead = ascii_read_one_field;
24068     }else{
24069       xRead = csv_read_one_field;
24070     }
24071     rc = 1;
24072     for(i=1; i<nArg; i++){
24073       char *z = azArg[i];
24074       if( z[0]=='-' && z[1]=='-' ) z++;
24075       if( z[0]!='-' ){
24076         if( zFile==0 ){
24077           zFile = z;
24078         }else if( zTable==0 ){
24079           zTable = z;
24080         }else{
24081           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
24082           showHelp(p->out, "import");
24083           goto meta_command_exit;
24084         }
24085       }else if( cli_strcmp(z,"-v")==0 ){
24086         eVerbose++;
24087       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
24088         zSchema = azArg[++i];
24089       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
24090         nSkip = integerValue(azArg[++i]);
24091       }else if( cli_strcmp(z,"-ascii")==0 ){
24092         sCtx.cColSep = SEP_Unit[0];
24093         sCtx.cRowSep = SEP_Record[0];
24094         xRead = ascii_read_one_field;
24095         useOutputMode = 0;
24096       }else if( cli_strcmp(z,"-csv")==0 ){
24097         sCtx.cColSep = ',';
24098         sCtx.cRowSep = '\n';
24099         xRead = csv_read_one_field;
24100         useOutputMode = 0;
24101       }else{
24102         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
24103         showHelp(p->out, "import");
24104         goto meta_command_exit;
24105       }
24106     }
24107     if( zTable==0 ){
24108       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
24109                   zFile==0 ? "FILE" : "TABLE");
24110       showHelp(p->out, "import");
24111       goto meta_command_exit;
24112     }
24113     seenInterrupt = 0;
24114     open_db(p, 0);
24115     if( useOutputMode ){
24116       /* If neither the --csv or --ascii options are specified, then set
24117       ** the column and row separator characters from the output mode. */
24118       nSep = strlen30(p->colSeparator);
24119       if( nSep==0 ){
24120         raw_printf(stderr,
24121                    "Error: non-null column separator required for import\n");
24122         goto meta_command_exit;
24123       }
24124       if( nSep>1 ){
24125         raw_printf(stderr,
24126               "Error: multi-character column separators not allowed"
24127               " for import\n");
24128         goto meta_command_exit;
24129       }
24130       nSep = strlen30(p->rowSeparator);
24131       if( nSep==0 ){
24132         raw_printf(stderr,
24133             "Error: non-null row separator required for import\n");
24134         goto meta_command_exit;
24135       }
24136       if( nSep==2 && p->mode==MODE_Csv
24137        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
24138       ){
24139         /* When importing CSV (only), if the row separator is set to the
24140         ** default output row separator, change it to the default input
24141         ** row separator.  This avoids having to maintain different input
24142         ** and output row separators. */
24143         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24144         nSep = strlen30(p->rowSeparator);
24145       }
24146       if( nSep>1 ){
24147         raw_printf(stderr, "Error: multi-character row separators not allowed"
24148                            " for import\n");
24149         goto meta_command_exit;
24150       }
24151       sCtx.cColSep = (u8)p->colSeparator[0];
24152       sCtx.cRowSep = (u8)p->rowSeparator[0];
24153     }
24154     sCtx.zFile = zFile;
24155     sCtx.nLine = 1;
24156     if( sCtx.zFile[0]=='|' ){
24157 #ifdef SQLITE_OMIT_POPEN
24158       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24159       goto meta_command_exit;
24160 #else
24161       sCtx.in = popen(sCtx.zFile+1, "r");
24162       sCtx.zFile = "<pipe>";
24163       sCtx.xCloser = pclose;
24164 #endif
24165     }else{
24166       sCtx.in = fopen(sCtx.zFile, "rb");
24167       sCtx.xCloser = fclose;
24168     }
24169     if( sCtx.in==0 ){
24170       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
24171       goto meta_command_exit;
24172     }
24173     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
24174       char zSep[2];
24175       zSep[1] = 0;
24176       zSep[0] = sCtx.cColSep;
24177       utf8_printf(p->out, "Column separator ");
24178       output_c_string(p->out, zSep);
24179       utf8_printf(p->out, ", row separator ");
24180       zSep[0] = sCtx.cRowSep;
24181       output_c_string(p->out, zSep);
24182       utf8_printf(p->out, "\n");
24183     }
24184     sCtx.z = sqlite3_malloc64(120);
24185     if( sCtx.z==0 ){
24186       import_cleanup(&sCtx);
24187       shell_out_of_memory();
24188     }
24189     /* Below, resources must be freed before exit. */
24190     while( (nSkip--)>0 ){
24191       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
24192     }
24193     if( zSchema!=0 ){
24194       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
24195     }else{
24196       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
24197     }
24198     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
24199     if( zSql==0 || zFullTabName==0 ){
24200       import_cleanup(&sCtx);
24201       shell_out_of_memory();
24202     }
24203     nByte = strlen30(zSql);
24204     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24205     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
24206     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
24207       sqlite3 *dbCols = 0;
24208       char *zRenames = 0;
24209       char *zColDefs;
24210       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
24211       while( xRead(&sCtx) ){
24212         zAutoColumn(sCtx.z, &dbCols, 0);
24213         if( sCtx.cTerm!=sCtx.cColSep ) break;
24214       }
24215       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
24216       if( zRenames!=0 ){
24217         utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
24218                     "Columns renamed during .import %s due to duplicates:\n"
24219                     "%s\n", sCtx.zFile, zRenames);
24220         sqlite3_free(zRenames);
24221       }
24222       assert(dbCols==0);
24223       if( zColDefs==0 ){
24224         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
24225       import_fail:
24226         sqlite3_free(zCreate);
24227         sqlite3_free(zSql);
24228         sqlite3_free(zFullTabName);
24229         import_cleanup(&sCtx);
24230         rc = 1;
24231         goto meta_command_exit;
24232       }
24233       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
24234       if( eVerbose>=1 ){
24235         utf8_printf(p->out, "%s\n", zCreate);
24236       }
24237       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
24238       if( rc ){
24239         utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
24240         goto import_fail;
24241       }
24242       sqlite3_free(zCreate);
24243       zCreate = 0;
24244       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24245     }
24246     if( rc ){
24247       if (pStmt) sqlite3_finalize(pStmt);
24248       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
24249       goto import_fail;
24250     }
24251     sqlite3_free(zSql);
24252     nCol = sqlite3_column_count(pStmt);
24253     sqlite3_finalize(pStmt);
24254     pStmt = 0;
24255     if( nCol==0 ) return 0; /* no columns, no error */
24256     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
24257     if( zSql==0 ){
24258       import_cleanup(&sCtx);
24259       shell_out_of_memory();
24260     }
24261     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
24262     j = strlen30(zSql);
24263     for(i=1; i<nCol; i++){
24264       zSql[j++] = ',';
24265       zSql[j++] = '?';
24266     }
24267     zSql[j++] = ')';
24268     zSql[j] = 0;
24269     if( eVerbose>=2 ){
24270       utf8_printf(p->out, "Insert using: %s\n", zSql);
24271     }
24272     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24273     if( rc ){
24274       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24275       if (pStmt) sqlite3_finalize(pStmt);
24276       goto import_fail;
24277     }
24278     sqlite3_free(zSql);
24279     sqlite3_free(zFullTabName);
24280     needCommit = sqlite3_get_autocommit(p->db);
24281     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
24282     do{
24283       int startLine = sCtx.nLine;
24284       for(i=0; i<nCol; i++){
24285         char *z = xRead(&sCtx);
24286         /*
24287         ** Did we reach end-of-file before finding any columns?
24288         ** If so, stop instead of NULL filling the remaining columns.
24289         */
24290         if( z==0 && i==0 ) break;
24291         /*
24292         ** Did we reach end-of-file OR end-of-line before finding any
24293         ** columns in ASCII mode?  If so, stop instead of NULL filling
24294         ** the remaining columns.
24295         */
24296         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
24297         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
24298         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
24299           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
24300                           "filling the rest with NULL\n",
24301                           sCtx.zFile, startLine, nCol, i+1);
24302           i += 2;
24303           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
24304         }
24305       }
24306       if( sCtx.cTerm==sCtx.cColSep ){
24307         do{
24308           xRead(&sCtx);
24309           i++;
24310         }while( sCtx.cTerm==sCtx.cColSep );
24311         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
24312                         "extras ignored\n",
24313                         sCtx.zFile, startLine, nCol, i);
24314       }
24315       if( i>=nCol ){
24316         sqlite3_step(pStmt);
24317         rc = sqlite3_reset(pStmt);
24318         if( rc!=SQLITE_OK ){
24319           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
24320                       startLine, sqlite3_errmsg(p->db));
24321           sCtx.nErr++;
24322         }else{
24323           sCtx.nRow++;
24324         }
24325       }
24326     }while( sCtx.cTerm!=EOF );
24327 
24328     import_cleanup(&sCtx);
24329     sqlite3_finalize(pStmt);
24330     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
24331     if( eVerbose>0 ){
24332       utf8_printf(p->out,
24333           "Added %d rows with %d errors using %d lines of input\n",
24334           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
24335     }
24336   }else
24337 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24338 
24339 #ifndef SQLITE_UNTESTABLE
24340   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
24341     char *zSql;
24342     char *zCollist = 0;
24343     sqlite3_stmt *pStmt;
24344     int tnum = 0;
24345     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
24346     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
24347     int i;
24348     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
24349       utf8_printf(stderr, ".%s unavailable without --unsafe-testing\n",
24350                   "imposter");
24351       rc = 1;
24352       goto meta_command_exit;
24353     }
24354     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
24355       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
24356                           "       .imposter off\n");
24357       /* Also allowed, but not documented:
24358       **
24359       **    .imposter TABLE IMPOSTER
24360       **
24361       ** where TABLE is a WITHOUT ROWID table.  In that case, the
24362       ** imposter is another WITHOUT ROWID table with the columns in
24363       ** storage order. */
24364       rc = 1;
24365       goto meta_command_exit;
24366     }
24367     open_db(p, 0);
24368     if( nArg==2 ){
24369       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
24370       goto meta_command_exit;
24371     }
24372     zSql = sqlite3_mprintf(
24373       "SELECT rootpage, 0 FROM sqlite_schema"
24374       " WHERE name='%q' AND type='index'"
24375       "UNION ALL "
24376       "SELECT rootpage, 1 FROM sqlite_schema"
24377       " WHERE name='%q' AND type='table'"
24378       "   AND sql LIKE '%%without%%rowid%%'",
24379       azArg[1], azArg[1]
24380     );
24381     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24382     sqlite3_free(zSql);
24383     if( sqlite3_step(pStmt)==SQLITE_ROW ){
24384       tnum = sqlite3_column_int(pStmt, 0);
24385       isWO = sqlite3_column_int(pStmt, 1);
24386     }
24387     sqlite3_finalize(pStmt);
24388     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
24389     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24390     sqlite3_free(zSql);
24391     i = 0;
24392     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24393       char zLabel[20];
24394       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
24395       i++;
24396       if( zCol==0 ){
24397         if( sqlite3_column_int(pStmt,1)==-1 ){
24398           zCol = "_ROWID_";
24399         }else{
24400           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
24401           zCol = zLabel;
24402         }
24403       }
24404       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
24405         lenPK = (int)strlen(zCollist);
24406       }
24407       if( zCollist==0 ){
24408         zCollist = sqlite3_mprintf("\"%w\"", zCol);
24409       }else{
24410         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
24411       }
24412     }
24413     sqlite3_finalize(pStmt);
24414     if( i==0 || tnum==0 ){
24415       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
24416       rc = 1;
24417       sqlite3_free(zCollist);
24418       goto meta_command_exit;
24419     }
24420     if( lenPK==0 ) lenPK = 100000;
24421     zSql = sqlite3_mprintf(
24422           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
24423           azArg[2], zCollist, lenPK, zCollist);
24424     sqlite3_free(zCollist);
24425     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
24426     if( rc==SQLITE_OK ){
24427       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
24428       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
24429       if( rc ){
24430         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
24431       }else{
24432         utf8_printf(stdout, "%s;\n", zSql);
24433         raw_printf(stdout,
24434           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
24435           azArg[1], isWO ? "table" : "index"
24436         );
24437       }
24438     }else{
24439       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
24440       rc = 1;
24441     }
24442     sqlite3_free(zSql);
24443   }else
24444 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
24445 
24446 #ifdef SQLITE_ENABLE_IOTRACE
24447   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
24448     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
24449     if( iotrace && iotrace!=stdout ) fclose(iotrace);
24450     iotrace = 0;
24451     if( nArg<2 ){
24452       sqlite3IoTrace = 0;
24453     }else if( cli_strcmp(azArg[1], "-")==0 ){
24454       sqlite3IoTrace = iotracePrintf;
24455       iotrace = stdout;
24456     }else{
24457       iotrace = fopen(azArg[1], "w");
24458       if( iotrace==0 ){
24459         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
24460         sqlite3IoTrace = 0;
24461         rc = 1;
24462       }else{
24463         sqlite3IoTrace = iotracePrintf;
24464       }
24465     }
24466   }else
24467 #endif
24468 
24469   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
24470     static const struct {
24471        const char *zLimitName;   /* Name of a limit */
24472        int limitCode;            /* Integer code for that limit */
24473     } aLimit[] = {
24474       { "length",                SQLITE_LIMIT_LENGTH                    },
24475       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
24476       { "column",                SQLITE_LIMIT_COLUMN                    },
24477       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
24478       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
24479       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
24480       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
24481       { "attached",              SQLITE_LIMIT_ATTACHED                  },
24482       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
24483       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
24484       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
24485       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
24486     };
24487     int i, n2;
24488     open_db(p, 0);
24489     if( nArg==1 ){
24490       for(i=0; i<ArraySize(aLimit); i++){
24491         printf("%20s %d\n", aLimit[i].zLimitName,
24492                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
24493       }
24494     }else if( nArg>3 ){
24495       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
24496       rc = 1;
24497       goto meta_command_exit;
24498     }else{
24499       int iLimit = -1;
24500       n2 = strlen30(azArg[1]);
24501       for(i=0; i<ArraySize(aLimit); i++){
24502         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
24503           if( iLimit<0 ){
24504             iLimit = i;
24505           }else{
24506             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
24507             rc = 1;
24508             goto meta_command_exit;
24509           }
24510         }
24511       }
24512       if( iLimit<0 ){
24513         utf8_printf(stderr, "unknown limit: \"%s\"\n"
24514                         "enter \".limits\" with no arguments for a list.\n",
24515                          azArg[1]);
24516         rc = 1;
24517         goto meta_command_exit;
24518       }
24519       if( nArg==3 ){
24520         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
24521                       (int)integerValue(azArg[2]));
24522       }
24523       printf("%20s %d\n", aLimit[iLimit].zLimitName,
24524              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
24525     }
24526   }else
24527 
24528   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
24529     open_db(p, 0);
24530     lintDotCommand(p, azArg, nArg);
24531   }else
24532 
24533 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
24534   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
24535     const char *zFile, *zProc;
24536     char *zErrMsg = 0;
24537     failIfSafeMode(p, "cannot run .load in safe mode");
24538     if( nArg<2 || azArg[1][0]==0 ){
24539       /* Must have a non-empty FILE. (Will not load self.) */
24540       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
24541       rc = 1;
24542       goto meta_command_exit;
24543     }
24544     zFile = azArg[1];
24545     zProc = nArg>=3 ? azArg[2] : 0;
24546     open_db(p, 0);
24547     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
24548     if( rc!=SQLITE_OK ){
24549       utf8_printf(stderr, "Error: %s\n", zErrMsg);
24550       sqlite3_free(zErrMsg);
24551       rc = 1;
24552     }
24553   }else
24554 #endif
24555 
24556   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
24557     if( nArg!=2 ){
24558       raw_printf(stderr, "Usage: .log FILENAME\n");
24559       rc = 1;
24560     }else{
24561       const char *zFile = azArg[1];
24562       if( p->bSafeMode
24563        && cli_strcmp(zFile,"on")!=0
24564        && cli_strcmp(zFile,"off")!=0
24565       ){
24566         raw_printf(stdout, "cannot set .log to anything other "
24567                    "than \"on\" or \"off\"\n");
24568         zFile = "off";
24569       }
24570       output_file_close(p->pLog);
24571       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
24572       p->pLog = output_file_open(zFile, 0);
24573     }
24574   }else
24575 
24576   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
24577     const char *zMode = 0;
24578     const char *zTabname = 0;
24579     int i, n2;
24580     ColModeOpts cmOpts = ColModeOpts_default;
24581     for(i=1; i<nArg; i++){
24582       const char *z = azArg[i];
24583       if( optionMatch(z,"wrap") && i+1<nArg ){
24584         cmOpts.iWrap = integerValue(azArg[++i]);
24585       }else if( optionMatch(z,"ww") ){
24586         cmOpts.bWordWrap = 1;
24587       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
24588         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
24589       }else if( optionMatch(z,"quote") ){
24590         cmOpts.bQuote = 1;
24591       }else if( optionMatch(z,"noquote") ){
24592         cmOpts.bQuote = 0;
24593       }else if( zMode==0 ){
24594         zMode = z;
24595         /* Apply defaults for qbox pseudo-mode.  If that
24596          * overwrites already-set values, user was informed of this.
24597          */
24598         if( cli_strcmp(z, "qbox")==0 ){
24599           ColModeOpts cmo = ColModeOpts_default_qbox;
24600           zMode = "box";
24601           cmOpts = cmo;
24602         }
24603       }else if( zTabname==0 ){
24604         zTabname = z;
24605       }else if( z[0]=='-' ){
24606         utf8_printf(stderr, "unknown option: %s\n", z);
24607         utf8_printf(stderr, "options:\n"
24608                             "  --noquote\n"
24609                             "  --quote\n"
24610                             "  --wordwrap on/off\n"
24611                             "  --wrap N\n"
24612                             "  --ww\n");
24613         rc = 1;
24614         goto meta_command_exit;
24615       }else{
24616         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
24617         rc = 1;
24618         goto meta_command_exit;
24619       }
24620     }
24621     if( zMode==0 ){
24622       if( p->mode==MODE_Column
24623        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
24624       ){
24625         raw_printf
24626           (p->out,
24627            "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
24628            modeDescr[p->mode], p->cmOpts.iWrap,
24629            p->cmOpts.bWordWrap ? "on" : "off",
24630            p->cmOpts.bQuote ? "" : "no");
24631       }else{
24632         raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
24633       }
24634       zMode = modeDescr[p->mode];
24635     }
24636     n2 = strlen30(zMode);
24637     if( cli_strncmp(zMode,"lines",n2)==0 ){
24638       p->mode = MODE_Line;
24639       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24640     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
24641       p->mode = MODE_Column;
24642       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
24643         p->showHeader = 1;
24644       }
24645       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24646       p->cmOpts = cmOpts;
24647     }else if( cli_strncmp(zMode,"list",n2)==0 ){
24648       p->mode = MODE_List;
24649       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
24650       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24651     }else if( cli_strncmp(zMode,"html",n2)==0 ){
24652       p->mode = MODE_Html;
24653     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
24654       p->mode = MODE_Tcl;
24655       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
24656       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24657     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
24658       p->mode = MODE_Csv;
24659       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24660       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
24661     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
24662       p->mode = MODE_List;
24663       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
24664     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
24665       p->mode = MODE_Insert;
24666       set_table_name(p, zTabname ? zTabname : "table");
24667     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
24668       p->mode = MODE_Quote;
24669       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24670       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24671     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
24672       p->mode = MODE_Ascii;
24673       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
24674       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
24675     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
24676       p->mode = MODE_Markdown;
24677       p->cmOpts = cmOpts;
24678     }else if( cli_strncmp(zMode,"table",n2)==0 ){
24679       p->mode = MODE_Table;
24680       p->cmOpts = cmOpts;
24681     }else if( cli_strncmp(zMode,"box",n2)==0 ){
24682       p->mode = MODE_Box;
24683       p->cmOpts = cmOpts;
24684     }else if( cli_strncmp(zMode,"count",n2)==0 ){
24685       p->mode = MODE_Count;
24686     }else if( cli_strncmp(zMode,"off",n2)==0 ){
24687       p->mode = MODE_Off;
24688     }else if( cli_strncmp(zMode,"json",n2)==0 ){
24689       p->mode = MODE_Json;
24690     }else{
24691       raw_printf(stderr, "Error: mode should be one of: "
24692          "ascii box column csv html insert json line list markdown "
24693          "qbox quote table tabs tcl\n");
24694       rc = 1;
24695     }
24696     p->cMode = p->mode;
24697   }else
24698 
24699 #ifndef SQLITE_SHELL_FIDDLE
24700   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
24701     if( nArg!=2 ){
24702       raw_printf(stderr, "Usage: .nonce NONCE\n");
24703       rc = 1;
24704     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
24705       raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
24706                  p->lineno, azArg[1]);
24707       exit(1);
24708     }else{
24709       p->bSafeMode = 0;
24710       return 0;  /* Return immediately to bypass the safe mode reset
24711                  ** at the end of this procedure */
24712     }
24713   }else
24714 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24715 
24716   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
24717     if( nArg==2 ){
24718       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
24719                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
24720     }else{
24721       raw_printf(stderr, "Usage: .nullvalue STRING\n");
24722       rc = 1;
24723     }
24724   }else
24725 
24726   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
24727     const char *zFN = 0;     /* Pointer to constant filename */
24728     char *zNewFilename = 0;  /* Name of the database file to open */
24729     int iName = 1;           /* Index in azArg[] of the filename */
24730     int newFlag = 0;         /* True to delete file before opening */
24731     int openMode = SHELL_OPEN_UNSPEC;
24732 
24733     /* Check for command-line arguments */
24734     for(iName=1; iName<nArg; iName++){
24735       const char *z = azArg[iName];
24736 #ifndef SQLITE_SHELL_FIDDLE
24737       if( optionMatch(z,"new") ){
24738         newFlag = 1;
24739 #ifdef SQLITE_HAVE_ZLIB
24740       }else if( optionMatch(z, "zip") ){
24741         openMode = SHELL_OPEN_ZIPFILE;
24742 #endif
24743       }else if( optionMatch(z, "append") ){
24744         openMode = SHELL_OPEN_APPENDVFS;
24745       }else if( optionMatch(z, "readonly") ){
24746         openMode = SHELL_OPEN_READONLY;
24747       }else if( optionMatch(z, "nofollow") ){
24748         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
24749 #ifndef SQLITE_OMIT_DESERIALIZE
24750       }else if( optionMatch(z, "deserialize") ){
24751         openMode = SHELL_OPEN_DESERIALIZE;
24752       }else if( optionMatch(z, "hexdb") ){
24753         openMode = SHELL_OPEN_HEXDB;
24754       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
24755         p->szMax = integerValue(azArg[++iName]);
24756 #endif /* SQLITE_OMIT_DESERIALIZE */
24757       }else
24758 #endif /* !SQLITE_SHELL_FIDDLE */
24759       if( z[0]=='-' ){
24760         utf8_printf(stderr, "unknown option: %s\n", z);
24761         rc = 1;
24762         goto meta_command_exit;
24763       }else if( zFN ){
24764         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
24765         rc = 1;
24766         goto meta_command_exit;
24767       }else{
24768         zFN = z;
24769       }
24770     }
24771 
24772     /* Close the existing database */
24773     session_close_all(p, -1);
24774     close_db(p->db);
24775     p->db = 0;
24776     p->pAuxDb->zDbFilename = 0;
24777     sqlite3_free(p->pAuxDb->zFreeOnClose);
24778     p->pAuxDb->zFreeOnClose = 0;
24779     p->openMode = openMode;
24780     p->openFlags = 0;
24781     p->szMax = 0;
24782 
24783     /* If a filename is specified, try to open it first */
24784     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
24785       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
24786 #ifndef SQLITE_SHELL_FIDDLE
24787       if( p->bSafeMode
24788        && p->openMode!=SHELL_OPEN_HEXDB
24789        && zFN
24790        && cli_strcmp(zFN,":memory:")!=0
24791       ){
24792         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
24793       }
24794 #else
24795       /* WASM mode has its own sandboxed pseudo-filesystem. */
24796 #endif
24797       if( zFN ){
24798         zNewFilename = sqlite3_mprintf("%s", zFN);
24799         shell_check_oom(zNewFilename);
24800       }else{
24801         zNewFilename = 0;
24802       }
24803       p->pAuxDb->zDbFilename = zNewFilename;
24804       open_db(p, OPEN_DB_KEEPALIVE);
24805       if( p->db==0 ){
24806         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
24807         sqlite3_free(zNewFilename);
24808       }else{
24809         p->pAuxDb->zFreeOnClose = zNewFilename;
24810       }
24811     }
24812     if( p->db==0 ){
24813       /* As a fall-back open a TEMP database */
24814       p->pAuxDb->zDbFilename = 0;
24815       open_db(p, 0);
24816     }
24817   }else
24818 
24819 #ifndef SQLITE_SHELL_FIDDLE
24820   if( (c=='o'
24821         && (cli_strncmp(azArg[0], "output", n)==0
24822             || cli_strncmp(azArg[0], "once", n)==0))
24823    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
24824   ){
24825     char *zFile = 0;
24826     int bTxtMode = 0;
24827     int i;
24828     int eMode = 0;
24829     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
24830     unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
24831 
24832     zBOM[0] = 0;
24833     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24834     if( c=='e' ){
24835       eMode = 'x';
24836       bOnce = 2;
24837     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
24838       bOnce = 1;
24839     }
24840     for(i=1; i<nArg; i++){
24841       char *z = azArg[i];
24842       if( z[0]=='-' ){
24843         if( z[1]=='-' ) z++;
24844         if( cli_strcmp(z,"-bom")==0 ){
24845           zBOM[0] = 0xef;
24846           zBOM[1] = 0xbb;
24847           zBOM[2] = 0xbf;
24848           zBOM[3] = 0;
24849         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
24850           eMode = 'x';  /* spreadsheet */
24851         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
24852           eMode = 'e';  /* text editor */
24853         }else{
24854           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
24855                       azArg[i]);
24856           showHelp(p->out, azArg[0]);
24857           rc = 1;
24858           goto meta_command_exit;
24859         }
24860       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
24861         zFile = sqlite3_mprintf("%s", z);
24862         if( zFile && zFile[0]=='|' ){
24863           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
24864           break;
24865         }
24866       }else{
24867         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
24868                     azArg[i]);
24869         showHelp(p->out, azArg[0]);
24870         rc = 1;
24871         sqlite3_free(zFile);
24872         goto meta_command_exit;
24873       }
24874     }
24875     if( zFile==0 ){
24876       zFile = sqlite3_mprintf("stdout");
24877     }
24878     if( bOnce ){
24879       p->outCount = 2;
24880     }else{
24881       p->outCount = 0;
24882     }
24883     output_reset(p);
24884 #ifndef SQLITE_NOHAVE_SYSTEM
24885     if( eMode=='e' || eMode=='x' ){
24886       p->doXdgOpen = 1;
24887       outputModePush(p);
24888       if( eMode=='x' ){
24889         /* spreadsheet mode.  Output as CSV. */
24890         newTempFile(p, "csv");
24891         ShellClearFlag(p, SHFLG_Echo);
24892         p->mode = MODE_Csv;
24893         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24894         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
24895       }else{
24896         /* text editor mode */
24897         newTempFile(p, "txt");
24898         bTxtMode = 1;
24899       }
24900       sqlite3_free(zFile);
24901       zFile = sqlite3_mprintf("%s", p->zTempFile);
24902     }
24903 #endif /* SQLITE_NOHAVE_SYSTEM */
24904     shell_check_oom(zFile);
24905     if( zFile[0]=='|' ){
24906 #ifdef SQLITE_OMIT_POPEN
24907       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24908       rc = 1;
24909       p->out = stdout;
24910 #else
24911       p->out = popen(zFile + 1, "w");
24912       if( p->out==0 ){
24913         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
24914         p->out = stdout;
24915         rc = 1;
24916       }else{
24917         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
24918         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
24919       }
24920 #endif
24921     }else{
24922       p->out = output_file_open(zFile, bTxtMode);
24923       if( p->out==0 ){
24924         if( cli_strcmp(zFile,"off")!=0 ){
24925           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
24926         }
24927         p->out = stdout;
24928         rc = 1;
24929       } else {
24930         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
24931         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
24932       }
24933     }
24934     sqlite3_free(zFile);
24935   }else
24936 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24937 
24938   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
24939     open_db(p,0);
24940     if( nArg<=1 ) goto parameter_syntax_error;
24941 
24942     /* .parameter clear
24943     ** Clear all bind parameters by dropping the TEMP table that holds them.
24944     */
24945     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
24946       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
24947                    0, 0, 0);
24948     }else
24949 
24950     /* .parameter list
24951     ** List all bind parameters.
24952     */
24953     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
24954       sqlite3_stmt *pStmt = 0;
24955       int rx;
24956       int len = 0;
24957       rx = sqlite3_prepare_v2(p->db,
24958              "SELECT max(length(key)) "
24959              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
24960       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24961         len = sqlite3_column_int(pStmt, 0);
24962         if( len>40 ) len = 40;
24963       }
24964       sqlite3_finalize(pStmt);
24965       pStmt = 0;
24966       if( len ){
24967         rx = sqlite3_prepare_v2(p->db,
24968              "SELECT key, quote(value) "
24969              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
24970         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24971           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
24972                       sqlite3_column_text(pStmt,1));
24973         }
24974         sqlite3_finalize(pStmt);
24975       }
24976     }else
24977 
24978     /* .parameter init
24979     ** Make sure the TEMP table used to hold bind parameters exists.
24980     ** Create it if necessary.
24981     */
24982     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
24983       bind_table_init(p);
24984     }else
24985 
24986     /* .parameter set NAME VALUE
24987     ** Set or reset a bind parameter.  NAME should be the full parameter
24988     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
24989     ** VALUE can be in either SQL literal notation, or if not it will be
24990     ** understood to be a text string.
24991     */
24992     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
24993       int rx;
24994       char *zSql;
24995       sqlite3_stmt *pStmt;
24996       const char *zKey = azArg[2];
24997       const char *zValue = azArg[3];
24998       bind_table_init(p);
24999       zSql = sqlite3_mprintf(
25000                   "REPLACE INTO temp.sqlite_parameters(key,value)"
25001                   "VALUES(%Q,%s);", zKey, zValue);
25002       shell_check_oom(zSql);
25003       pStmt = 0;
25004       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25005       sqlite3_free(zSql);
25006       if( rx!=SQLITE_OK ){
25007         sqlite3_finalize(pStmt);
25008         pStmt = 0;
25009         zSql = sqlite3_mprintf(
25010                    "REPLACE INTO temp.sqlite_parameters(key,value)"
25011                    "VALUES(%Q,%Q);", zKey, zValue);
25012         shell_check_oom(zSql);
25013         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25014         sqlite3_free(zSql);
25015         if( rx!=SQLITE_OK ){
25016           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
25017           sqlite3_finalize(pStmt);
25018           pStmt = 0;
25019           rc = 1;
25020         }
25021       }
25022       sqlite3_step(pStmt);
25023       sqlite3_finalize(pStmt);
25024     }else
25025 
25026     /* .parameter unset NAME
25027     ** Remove the NAME binding from the parameter binding table, if it
25028     ** exists.
25029     */
25030     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
25031       char *zSql = sqlite3_mprintf(
25032           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
25033       shell_check_oom(zSql);
25034       sqlite3_exec(p->db, zSql, 0, 0, 0);
25035       sqlite3_free(zSql);
25036     }else
25037     /* If no command name matches, show a syntax error */
25038     parameter_syntax_error:
25039     showHelp(p->out, "parameter");
25040   }else
25041 
25042   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
25043     int i;
25044     for(i=1; i<nArg; i++){
25045       if( i>1 ) raw_printf(p->out, " ");
25046       utf8_printf(p->out, "%s", azArg[i]);
25047     }
25048     raw_printf(p->out, "\n");
25049   }else
25050 
25051 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
25052   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
25053     int i;
25054     int nn = 0;
25055     p->flgProgress = 0;
25056     p->mxProgress = 0;
25057     p->nProgress = 0;
25058     for(i=1; i<nArg; i++){
25059       const char *z = azArg[i];
25060       if( z[0]=='-' ){
25061         z++;
25062         if( z[0]=='-' ) z++;
25063         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
25064           p->flgProgress |= SHELL_PROGRESS_QUIET;
25065           continue;
25066         }
25067         if( cli_strcmp(z,"reset")==0 ){
25068           p->flgProgress |= SHELL_PROGRESS_RESET;
25069           continue;
25070         }
25071         if( cli_strcmp(z,"once")==0 ){
25072           p->flgProgress |= SHELL_PROGRESS_ONCE;
25073           continue;
25074         }
25075         if( cli_strcmp(z,"limit")==0 ){
25076           if( i+1>=nArg ){
25077             utf8_printf(stderr, "Error: missing argument on --limit\n");
25078             rc = 1;
25079             goto meta_command_exit;
25080           }else{
25081             p->mxProgress = (int)integerValue(azArg[++i]);
25082           }
25083           continue;
25084         }
25085         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
25086         rc = 1;
25087         goto meta_command_exit;
25088       }else{
25089         nn = (int)integerValue(z);
25090       }
25091     }
25092     open_db(p, 0);
25093     sqlite3_progress_handler(p->db, nn, progress_handler, p);
25094   }else
25095 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
25096 
25097   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
25098     if( nArg >= 2) {
25099       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
25100     }
25101     if( nArg >= 3) {
25102       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
25103     }
25104   }else
25105 
25106 #ifndef SQLITE_SHELL_FIDDLE
25107   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
25108     rc = 2;
25109   }else
25110 #endif
25111 
25112 #ifndef SQLITE_SHELL_FIDDLE
25113   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
25114     FILE *inSaved = p->in;
25115     int savedLineno = p->lineno;
25116     failIfSafeMode(p, "cannot run .read in safe mode");
25117     if( nArg!=2 ){
25118       raw_printf(stderr, "Usage: .read FILE\n");
25119       rc = 1;
25120       goto meta_command_exit;
25121     }
25122     if( azArg[1][0]=='|' ){
25123 #ifdef SQLITE_OMIT_POPEN
25124       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
25125       rc = 1;
25126       p->out = stdout;
25127 #else
25128       p->in = popen(azArg[1]+1, "r");
25129       if( p->in==0 ){
25130         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
25131         rc = 1;
25132       }else{
25133         rc = process_input(p);
25134         pclose(p->in);
25135       }
25136 #endif
25137     }else if( (p->in = openChrSource(azArg[1]))==0 ){
25138       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
25139       rc = 1;
25140     }else{
25141       rc = process_input(p);
25142       fclose(p->in);
25143     }
25144     p->in = inSaved;
25145     p->lineno = savedLineno;
25146   }else
25147 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25148 
25149 #ifndef SQLITE_SHELL_FIDDLE
25150   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
25151     const char *zSrcFile;
25152     const char *zDb;
25153     sqlite3 *pSrc;
25154     sqlite3_backup *pBackup;
25155     int nTimeout = 0;
25156 
25157     failIfSafeMode(p, "cannot run .restore in safe mode");
25158     if( nArg==2 ){
25159       zSrcFile = azArg[1];
25160       zDb = "main";
25161     }else if( nArg==3 ){
25162       zSrcFile = azArg[2];
25163       zDb = azArg[1];
25164     }else{
25165       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
25166       rc = 1;
25167       goto meta_command_exit;
25168     }
25169     rc = sqlite3_open(zSrcFile, &pSrc);
25170     if( rc!=SQLITE_OK ){
25171       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
25172       close_db(pSrc);
25173       return 1;
25174     }
25175     open_db(p, 0);
25176     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
25177     if( pBackup==0 ){
25178       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
25179       close_db(pSrc);
25180       return 1;
25181     }
25182     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
25183           || rc==SQLITE_BUSY  ){
25184       if( rc==SQLITE_BUSY ){
25185         if( nTimeout++ >= 3 ) break;
25186         sqlite3_sleep(100);
25187       }
25188     }
25189     sqlite3_backup_finish(pBackup);
25190     if( rc==SQLITE_DONE ){
25191       rc = 0;
25192     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
25193       raw_printf(stderr, "Error: source database is busy\n");
25194       rc = 1;
25195     }else{
25196       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
25197       rc = 1;
25198     }
25199     close_db(pSrc);
25200   }else
25201 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25202 
25203   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
25204     if( nArg==2 ){
25205       if( cli_strcmp(azArg[1], "est")==0 ){
25206         p->scanstatsOn = 2;
25207       }else{
25208         p->scanstatsOn = (u8)booleanValue(azArg[1]);
25209       }
25210       open_db(p, 0);
25211       sqlite3_db_config(
25212           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
25213       );
25214 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
25215       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
25216 #endif
25217     }else{
25218       raw_printf(stderr, "Usage: .scanstats on|off|est\n");
25219       rc = 1;
25220     }
25221   }else
25222 
25223   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
25224     ShellText sSelect;
25225     ShellState data;
25226     char *zErrMsg = 0;
25227     const char *zDiv = "(";
25228     const char *zName = 0;
25229     int iSchema = 0;
25230     int bDebug = 0;
25231     int bNoSystemTabs = 0;
25232     int ii;
25233 
25234     open_db(p, 0);
25235     memcpy(&data, p, sizeof(data));
25236     data.showHeader = 0;
25237     data.cMode = data.mode = MODE_Semi;
25238     initText(&sSelect);
25239     for(ii=1; ii<nArg; ii++){
25240       if( optionMatch(azArg[ii],"indent") ){
25241         data.cMode = data.mode = MODE_Pretty;
25242       }else if( optionMatch(azArg[ii],"debug") ){
25243         bDebug = 1;
25244       }else if( optionMatch(azArg[ii],"nosys") ){
25245         bNoSystemTabs = 1;
25246       }else if( azArg[ii][0]=='-' ){
25247         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
25248         rc = 1;
25249         goto meta_command_exit;
25250       }else if( zName==0 ){
25251         zName = azArg[ii];
25252       }else{
25253         raw_printf(stderr,
25254                    "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
25255         rc = 1;
25256         goto meta_command_exit;
25257       }
25258     }
25259     if( zName!=0 ){
25260       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
25261                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
25262                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
25263                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
25264       if( isSchema ){
25265         char *new_argv[2], *new_colv[2];
25266         new_argv[0] = sqlite3_mprintf(
25267                       "CREATE TABLE %s (\n"
25268                       "  type text,\n"
25269                       "  name text,\n"
25270                       "  tbl_name text,\n"
25271                       "  rootpage integer,\n"
25272                       "  sql text\n"
25273                       ")", zName);
25274         shell_check_oom(new_argv[0]);
25275         new_argv[1] = 0;
25276         new_colv[0] = "sql";
25277         new_colv[1] = 0;
25278         callback(&data, 1, new_argv, new_colv);
25279         sqlite3_free(new_argv[0]);
25280       }
25281     }
25282     if( zDiv ){
25283       sqlite3_stmt *pStmt = 0;
25284       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
25285                               -1, &pStmt, 0);
25286       if( rc ){
25287         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
25288         sqlite3_finalize(pStmt);
25289         rc = 1;
25290         goto meta_command_exit;
25291       }
25292       appendText(&sSelect, "SELECT sql FROM", 0);
25293       iSchema = 0;
25294       while( sqlite3_step(pStmt)==SQLITE_ROW ){
25295         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
25296         char zScNum[30];
25297         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
25298         appendText(&sSelect, zDiv, 0);
25299         zDiv = " UNION ALL ";
25300         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
25301         if( sqlite3_stricmp(zDb, "main")!=0 ){
25302           appendText(&sSelect, zDb, '\'');
25303         }else{
25304           appendText(&sSelect, "NULL", 0);
25305         }
25306         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
25307         appendText(&sSelect, zScNum, 0);
25308         appendText(&sSelect, " AS snum, ", 0);
25309         appendText(&sSelect, zDb, '\'');
25310         appendText(&sSelect, " AS sname FROM ", 0);
25311         appendText(&sSelect, zDb, quoteChar(zDb));
25312         appendText(&sSelect, ".sqlite_schema", 0);
25313       }
25314       sqlite3_finalize(pStmt);
25315 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
25316       if( zName ){
25317         appendText(&sSelect,
25318            " UNION ALL SELECT shell_module_schema(name),"
25319            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
25320         0);
25321       }
25322 #endif
25323       appendText(&sSelect, ") WHERE ", 0);
25324       if( zName ){
25325         char *zQarg = sqlite3_mprintf("%Q", zName);
25326         int bGlob;
25327         shell_check_oom(zQarg);
25328         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
25329                 strchr(zName, '[') != 0;
25330         if( strchr(zName, '.') ){
25331           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
25332         }else{
25333           appendText(&sSelect, "lower(tbl_name)", 0);
25334         }
25335         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
25336         appendText(&sSelect, zQarg, 0);
25337         if( !bGlob ){
25338           appendText(&sSelect, " ESCAPE '\\' ", 0);
25339         }
25340         appendText(&sSelect, " AND ", 0);
25341         sqlite3_free(zQarg);
25342       }
25343       if( bNoSystemTabs ){
25344         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
25345       }
25346       appendText(&sSelect, "sql IS NOT NULL"
25347                            " ORDER BY snum, rowid", 0);
25348       if( bDebug ){
25349         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
25350       }else{
25351         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
25352       }
25353       freeText(&sSelect);
25354     }
25355     if( zErrMsg ){
25356       utf8_printf(stderr,"Error: %s\n", zErrMsg);
25357       sqlite3_free(zErrMsg);
25358       rc = 1;
25359     }else if( rc != SQLITE_OK ){
25360       raw_printf(stderr,"Error: querying schema information\n");
25361       rc = 1;
25362     }else{
25363       rc = 0;
25364     }
25365   }else
25366 
25367   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
25368    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
25369   ){
25370     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
25371     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
25372   }else
25373 
25374 #if defined(SQLITE_ENABLE_SESSION)
25375   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
25376     struct AuxDb *pAuxDb = p->pAuxDb;
25377     OpenSession *pSession = &pAuxDb->aSession[0];
25378     char **azCmd = &azArg[1];
25379     int iSes = 0;
25380     int nCmd = nArg - 1;
25381     int i;
25382     if( nArg<=1 ) goto session_syntax_error;
25383     open_db(p, 0);
25384     if( nArg>=3 ){
25385       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
25386         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
25387       }
25388       if( iSes<pAuxDb->nSession ){
25389         pSession = &pAuxDb->aSession[iSes];
25390         azCmd++;
25391         nCmd--;
25392       }else{
25393         pSession = &pAuxDb->aSession[0];
25394         iSes = 0;
25395       }
25396     }
25397 
25398     /* .session attach TABLE
25399     ** Invoke the sqlite3session_attach() interface to attach a particular
25400     ** table so that it is never filtered.
25401     */
25402     if( cli_strcmp(azCmd[0],"attach")==0 ){
25403       if( nCmd!=2 ) goto session_syntax_error;
25404       if( pSession->p==0 ){
25405         session_not_open:
25406         raw_printf(stderr, "ERROR: No sessions are open\n");
25407       }else{
25408         rc = sqlite3session_attach(pSession->p, azCmd[1]);
25409         if( rc ){
25410           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
25411           rc = 0;
25412         }
25413       }
25414     }else
25415 
25416     /* .session changeset FILE
25417     ** .session patchset FILE
25418     ** Write a changeset or patchset into a file.  The file is overwritten.
25419     */
25420     if( cli_strcmp(azCmd[0],"changeset")==0
25421      || cli_strcmp(azCmd[0],"patchset")==0
25422     ){
25423       FILE *out = 0;
25424       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
25425       if( nCmd!=2 ) goto session_syntax_error;
25426       if( pSession->p==0 ) goto session_not_open;
25427       out = fopen(azCmd[1], "wb");
25428       if( out==0 ){
25429         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
25430                     azCmd[1]);
25431       }else{
25432         int szChng;
25433         void *pChng;
25434         if( azCmd[0][0]=='c' ){
25435           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
25436         }else{
25437           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
25438         }
25439         if( rc ){
25440           printf("Error: error code %d\n", rc);
25441           rc = 0;
25442         }
25443         if( pChng
25444           && fwrite(pChng, szChng, 1, out)!=1 ){
25445           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
25446                   szChng);
25447         }
25448         sqlite3_free(pChng);
25449         fclose(out);
25450       }
25451     }else
25452 
25453     /* .session close
25454     ** Close the identified session
25455     */
25456     if( cli_strcmp(azCmd[0], "close")==0 ){
25457       if( nCmd!=1 ) goto session_syntax_error;
25458       if( pAuxDb->nSession ){
25459         session_close(pSession);
25460         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
25461       }
25462     }else
25463 
25464     /* .session enable ?BOOLEAN?
25465     ** Query or set the enable flag
25466     */
25467     if( cli_strcmp(azCmd[0], "enable")==0 ){
25468       int ii;
25469       if( nCmd>2 ) goto session_syntax_error;
25470       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
25471       if( pAuxDb->nSession ){
25472         ii = sqlite3session_enable(pSession->p, ii);
25473         utf8_printf(p->out, "session %s enable flag = %d\n",
25474                     pSession->zName, ii);
25475       }
25476     }else
25477 
25478     /* .session filter GLOB ....
25479     ** Set a list of GLOB patterns of table names to be excluded.
25480     */
25481     if( cli_strcmp(azCmd[0], "filter")==0 ){
25482       int ii, nByte;
25483       if( nCmd<2 ) goto session_syntax_error;
25484       if( pAuxDb->nSession ){
25485         for(ii=0; ii<pSession->nFilter; ii++){
25486           sqlite3_free(pSession->azFilter[ii]);
25487         }
25488         sqlite3_free(pSession->azFilter);
25489         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
25490         pSession->azFilter = sqlite3_malloc( nByte );
25491         if( pSession->azFilter==0 ){
25492           raw_printf(stderr, "Error: out or memory\n");
25493           exit(1);
25494         }
25495         for(ii=1; ii<nCmd; ii++){
25496           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
25497           shell_check_oom(x);
25498         }
25499         pSession->nFilter = ii-1;
25500       }
25501     }else
25502 
25503     /* .session indirect ?BOOLEAN?
25504     ** Query or set the indirect flag
25505     */
25506     if( cli_strcmp(azCmd[0], "indirect")==0 ){
25507       int ii;
25508       if( nCmd>2 ) goto session_syntax_error;
25509       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
25510       if( pAuxDb->nSession ){
25511         ii = sqlite3session_indirect(pSession->p, ii);
25512         utf8_printf(p->out, "session %s indirect flag = %d\n",
25513                     pSession->zName, ii);
25514       }
25515     }else
25516 
25517     /* .session isempty
25518     ** Determine if the session is empty
25519     */
25520     if( cli_strcmp(azCmd[0], "isempty")==0 ){
25521       int ii;
25522       if( nCmd!=1 ) goto session_syntax_error;
25523       if( pAuxDb->nSession ){
25524         ii = sqlite3session_isempty(pSession->p);
25525         utf8_printf(p->out, "session %s isempty flag = %d\n",
25526                     pSession->zName, ii);
25527       }
25528     }else
25529 
25530     /* .session list
25531     ** List all currently open sessions
25532     */
25533     if( cli_strcmp(azCmd[0],"list")==0 ){
25534       for(i=0; i<pAuxDb->nSession; i++){
25535         utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
25536       }
25537     }else
25538 
25539     /* .session open DB NAME
25540     ** Open a new session called NAME on the attached database DB.
25541     ** DB is normally "main".
25542     */
25543     if( cli_strcmp(azCmd[0],"open")==0 ){
25544       char *zName;
25545       if( nCmd!=3 ) goto session_syntax_error;
25546       zName = azCmd[2];
25547       if( zName[0]==0 ) goto session_syntax_error;
25548       for(i=0; i<pAuxDb->nSession; i++){
25549         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
25550           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
25551           goto meta_command_exit;
25552         }
25553       }
25554       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
25555         raw_printf(stderr,
25556                    "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
25557         goto meta_command_exit;
25558       }
25559       pSession = &pAuxDb->aSession[pAuxDb->nSession];
25560       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
25561       if( rc ){
25562         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
25563         rc = 0;
25564         goto meta_command_exit;
25565       }
25566       pSession->nFilter = 0;
25567       sqlite3session_table_filter(pSession->p, session_filter, pSession);
25568       pAuxDb->nSession++;
25569       pSession->zName = sqlite3_mprintf("%s", zName);
25570       shell_check_oom(pSession->zName);
25571     }else
25572     /* If no command name matches, show a syntax error */
25573     session_syntax_error:
25574     showHelp(p->out, "session");
25575   }else
25576 #endif
25577 
25578 #ifdef SQLITE_DEBUG
25579   /* Undocumented commands for internal testing.  Subject to change
25580   ** without notice. */
25581   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
25582     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
25583       int i, v;
25584       for(i=1; i<nArg; i++){
25585         v = booleanValue(azArg[i]);
25586         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
25587       }
25588     }
25589     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
25590       int i; sqlite3_int64 v;
25591       for(i=1; i<nArg; i++){
25592         char zBuf[200];
25593         v = integerValue(azArg[i]);
25594         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
25595         utf8_printf(p->out, "%s", zBuf);
25596       }
25597     }
25598   }else
25599 #endif
25600 
25601   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
25602     int bIsInit = 0;         /* True to initialize the SELFTEST table */
25603     int bVerbose = 0;        /* Verbose output */
25604     int bSelftestExists;     /* True if SELFTEST already exists */
25605     int i, k;                /* Loop counters */
25606     int nTest = 0;           /* Number of tests runs */
25607     int nErr = 0;            /* Number of errors seen */
25608     ShellText str;           /* Answer for a query */
25609     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
25610 
25611     open_db(p,0);
25612     for(i=1; i<nArg; i++){
25613       const char *z = azArg[i];
25614       if( z[0]=='-' && z[1]=='-' ) z++;
25615       if( cli_strcmp(z,"-init")==0 ){
25616         bIsInit = 1;
25617       }else
25618       if( cli_strcmp(z,"-v")==0 ){
25619         bVerbose++;
25620       }else
25621       {
25622         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
25623                     azArg[i], azArg[0]);
25624         raw_printf(stderr, "Should be one of: --init -v\n");
25625         rc = 1;
25626         goto meta_command_exit;
25627       }
25628     }
25629     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
25630            != SQLITE_OK ){
25631       bSelftestExists = 0;
25632     }else{
25633       bSelftestExists = 1;
25634     }
25635     if( bIsInit ){
25636       createSelftestTable(p);
25637       bSelftestExists = 1;
25638     }
25639     initText(&str);
25640     appendText(&str, "x", 0);
25641     for(k=bSelftestExists; k>=0; k--){
25642       if( k==1 ){
25643         rc = sqlite3_prepare_v2(p->db,
25644             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
25645             -1, &pStmt, 0);
25646       }else{
25647         rc = sqlite3_prepare_v2(p->db,
25648           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
25649           "      (1,'run','PRAGMA integrity_check','ok')",
25650           -1, &pStmt, 0);
25651       }
25652       if( rc ){
25653         raw_printf(stderr, "Error querying the selftest table\n");
25654         rc = 1;
25655         sqlite3_finalize(pStmt);
25656         goto meta_command_exit;
25657       }
25658       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
25659         int tno = sqlite3_column_int(pStmt, 0);
25660         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
25661         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
25662         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
25663 
25664         if( zOp==0 ) continue;
25665         if( zSql==0 ) continue;
25666         if( zAns==0 ) continue;
25667         k = 0;
25668         if( bVerbose>0 ){
25669           printf("%d: %s %s\n", tno, zOp, zSql);
25670         }
25671         if( cli_strcmp(zOp,"memo")==0 ){
25672           utf8_printf(p->out, "%s\n", zSql);
25673         }else
25674         if( cli_strcmp(zOp,"run")==0 ){
25675           char *zErrMsg = 0;
25676           str.n = 0;
25677           str.z[0] = 0;
25678           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
25679           nTest++;
25680           if( bVerbose ){
25681             utf8_printf(p->out, "Result: %s\n", str.z);
25682           }
25683           if( rc || zErrMsg ){
25684             nErr++;
25685             rc = 1;
25686             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
25687             sqlite3_free(zErrMsg);
25688           }else if( cli_strcmp(zAns,str.z)!=0 ){
25689             nErr++;
25690             rc = 1;
25691             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
25692             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
25693           }
25694         }else
25695         {
25696           utf8_printf(stderr,
25697             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
25698           rc = 1;
25699           break;
25700         }
25701       } /* End loop over rows of content from SELFTEST */
25702       sqlite3_finalize(pStmt);
25703     } /* End loop over k */
25704     freeText(&str);
25705     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
25706   }else
25707 
25708   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
25709     if( nArg<2 || nArg>3 ){
25710       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
25711       rc = 1;
25712     }
25713     if( nArg>=2 ){
25714       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
25715                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
25716     }
25717     if( nArg>=3 ){
25718       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
25719                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
25720     }
25721   }else
25722 
25723   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
25724     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
25725     int i;                   /* Loop counter */
25726     int bSchema = 0;         /* Also hash the schema */
25727     int bSeparate = 0;       /* Hash each table separately */
25728     int iSize = 224;         /* Hash algorithm to use */
25729     int bDebug = 0;          /* Only show the query that would have run */
25730     sqlite3_stmt *pStmt;     /* For querying tables names */
25731     char *zSql;              /* SQL to be run */
25732     char *zSep;              /* Separator */
25733     ShellText sSql;          /* Complete SQL for the query to run the hash */
25734     ShellText sQuery;        /* Set of queries used to read all content */
25735     open_db(p, 0);
25736     for(i=1; i<nArg; i++){
25737       const char *z = azArg[i];
25738       if( z[0]=='-' ){
25739         z++;
25740         if( z[0]=='-' ) z++;
25741         if( cli_strcmp(z,"schema")==0 ){
25742           bSchema = 1;
25743         }else
25744         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
25745          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
25746         ){
25747           iSize = atoi(&z[5]);
25748         }else
25749         if( cli_strcmp(z,"debug")==0 ){
25750           bDebug = 1;
25751         }else
25752         {
25753           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
25754                       azArg[i], azArg[0]);
25755           showHelp(p->out, azArg[0]);
25756           rc = 1;
25757           goto meta_command_exit;
25758         }
25759       }else if( zLike ){
25760         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
25761         rc = 1;
25762         goto meta_command_exit;
25763       }else{
25764         zLike = z;
25765         bSeparate = 1;
25766         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
25767       }
25768     }
25769     if( bSchema ){
25770       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
25771              " WHERE type='table' AND coalesce(rootpage,0)>1"
25772              " UNION ALL SELECT 'sqlite_schema'"
25773              " ORDER BY 1 collate nocase";
25774     }else{
25775       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
25776              " WHERE type='table' AND coalesce(rootpage,0)>1"
25777              " AND name NOT LIKE 'sqlite_%'"
25778              " ORDER BY 1 collate nocase";
25779     }
25780     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25781     initText(&sQuery);
25782     initText(&sSql);
25783     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
25784     zSep = "VALUES(";
25785     while( SQLITE_ROW==sqlite3_step(pStmt) ){
25786       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
25787       if( zTab==0 ) continue;
25788       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
25789       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
25790         appendText(&sQuery,"SELECT * FROM ", 0);
25791         appendText(&sQuery,zTab,'"');
25792         appendText(&sQuery," NOT INDEXED;", 0);
25793       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
25794         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
25795                            " ORDER BY name;", 0);
25796       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
25797         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
25798                            " ORDER BY name;", 0);
25799       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
25800         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
25801                            " ORDER BY tbl,idx;", 0);
25802       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
25803         appendText(&sQuery, "SELECT * FROM ", 0);
25804         appendText(&sQuery, zTab, 0);
25805         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
25806       }
25807       appendText(&sSql, zSep, 0);
25808       appendText(&sSql, sQuery.z, '\'');
25809       sQuery.n = 0;
25810       appendText(&sSql, ",", 0);
25811       appendText(&sSql, zTab, '\'');
25812       zSep = "),(";
25813     }
25814     sqlite3_finalize(pStmt);
25815     if( bSeparate ){
25816       zSql = sqlite3_mprintf(
25817           "%s))"
25818           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
25819           "   FROM [sha3sum$query]",
25820           sSql.z, iSize);
25821     }else{
25822       zSql = sqlite3_mprintf(
25823           "%s))"
25824           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
25825           "   FROM [sha3sum$query]",
25826           sSql.z, iSize);
25827     }
25828     shell_check_oom(zSql);
25829     freeText(&sQuery);
25830     freeText(&sSql);
25831     if( bDebug ){
25832       utf8_printf(p->out, "%s\n", zSql);
25833     }else{
25834       shell_exec(p, zSql, 0);
25835     }
25836 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
25837     {
25838       int lrc;
25839       char *zRevText = /* Query for reversible to-blob-to-text check */
25840         "SELECT lower(name) as tname FROM sqlite_schema\n"
25841         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
25842         "AND name NOT LIKE 'sqlite_%%'%s\n"
25843         "ORDER BY 1 collate nocase";
25844       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
25845       zRevText = sqlite3_mprintf(
25846           /* lower-case query is first run, producing upper-case query. */
25847           "with tabcols as materialized(\n"
25848           "select tname, cname\n"
25849           "from ("
25850           " select ss.tname as tname, ti.name as cname\n"
25851           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
25852           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
25853           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
25854           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
25855           "FROM '||tname||' WHERE '\n"
25856           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
25857           "|| ' AND typeof('||cname||')=''text'' ',\n"
25858           "' OR ') as query, tname from tabcols group by tname)"
25859           , zRevText);
25860       shell_check_oom(zRevText);
25861       if( bDebug ) utf8_printf(p->out, "%s\n", zRevText);
25862       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
25863       if( lrc!=SQLITE_OK ){
25864         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
25865         ** user does cruel and unnatural things like ".limit expr_depth 0". */
25866         rc = 1;
25867       }else{
25868         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
25869         lrc = SQLITE_ROW==sqlite3_step(pStmt);
25870         if( lrc ){
25871           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
25872           sqlite3_stmt *pCheckStmt;
25873           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
25874           if( bDebug ) utf8_printf(p->out, "%s\n", zGenQuery);
25875           if( lrc!=SQLITE_OK ){
25876             rc = 1;
25877           }else{
25878             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
25879               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
25880               if( countIrreversible>0 ){
25881                 int sz = (int)(countIrreversible + 0.5);
25882                 utf8_printf(stderr,
25883                      "Digest includes %d invalidly encoded text field%s.\n",
25884                             sz, (sz>1)? "s": "");
25885               }
25886             }
25887             sqlite3_finalize(pCheckStmt);
25888           }
25889           sqlite3_finalize(pStmt);
25890         }
25891       }
25892       if( rc ) utf8_printf(stderr, ".sha3sum failed.\n");
25893       sqlite3_free(zRevText);
25894     }
25895 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
25896     sqlite3_free(zSql);
25897   }else
25898 
25899 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
25900   if( c=='s'
25901    && (cli_strncmp(azArg[0], "shell", n)==0
25902        || cli_strncmp(azArg[0],"system",n)==0)
25903   ){
25904     char *zCmd;
25905     int i, x;
25906     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
25907     if( nArg<2 ){
25908       raw_printf(stderr, "Usage: .system COMMAND\n");
25909       rc = 1;
25910       goto meta_command_exit;
25911     }
25912     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
25913     for(i=2; i<nArg && zCmd!=0; i++){
25914       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
25915                              zCmd, azArg[i]);
25916     }
25917     x = zCmd!=0 ? system(zCmd) : 1;
25918     sqlite3_free(zCmd);
25919     if( x ) raw_printf(stderr, "System command returns %d\n", x);
25920   }else
25921 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
25922 
25923   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
25924     static const char *azBool[] = { "off", "on", "trigger", "full"};
25925     const char *zOut;
25926     int i;
25927     if( nArg!=1 ){
25928       raw_printf(stderr, "Usage: .show\n");
25929       rc = 1;
25930       goto meta_command_exit;
25931     }
25932     utf8_printf(p->out, "%12.12s: %s\n","echo",
25933                 azBool[ShellHasFlag(p, SHFLG_Echo)]);
25934     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
25935     utf8_printf(p->out, "%12.12s: %s\n","explain",
25936          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
25937     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
25938     if( p->mode==MODE_Column
25939      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
25940     ){
25941       utf8_printf
25942         (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
25943          modeDescr[p->mode], p->cmOpts.iWrap,
25944          p->cmOpts.bWordWrap ? "on" : "off",
25945          p->cmOpts.bQuote ? "" : "no");
25946     }else{
25947       utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
25948     }
25949     utf8_printf(p->out, "%12.12s: ", "nullvalue");
25950       output_c_string(p->out, p->nullValue);
25951       raw_printf(p->out, "\n");
25952     utf8_printf(p->out,"%12.12s: %s\n","output",
25953             strlen30(p->outfile) ? p->outfile : "stdout");
25954     utf8_printf(p->out,"%12.12s: ", "colseparator");
25955       output_c_string(p->out, p->colSeparator);
25956       raw_printf(p->out, "\n");
25957     utf8_printf(p->out,"%12.12s: ", "rowseparator");
25958       output_c_string(p->out, p->rowSeparator);
25959       raw_printf(p->out, "\n");
25960     switch( p->statsOn ){
25961       case 0:  zOut = "off";     break;
25962       default: zOut = "on";      break;
25963       case 2:  zOut = "stmt";    break;
25964       case 3:  zOut = "vmstep";  break;
25965     }
25966     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
25967     utf8_printf(p->out, "%12.12s: ", "width");
25968     for (i=0;i<p->nWidth;i++) {
25969       raw_printf(p->out, "%d ", p->colWidth[i]);
25970     }
25971     raw_printf(p->out, "\n");
25972     utf8_printf(p->out, "%12.12s: %s\n", "filename",
25973                 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
25974   }else
25975 
25976   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
25977     if( nArg==2 ){
25978       if( cli_strcmp(azArg[1],"stmt")==0 ){
25979         p->statsOn = 2;
25980       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
25981         p->statsOn = 3;
25982       }else{
25983         p->statsOn = (u8)booleanValue(azArg[1]);
25984       }
25985     }else if( nArg==1 ){
25986       display_stats(p->db, p, 0);
25987     }else{
25988       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
25989       rc = 1;
25990     }
25991   }else
25992 
25993   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
25994    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
25995                  || cli_strncmp(azArg[0], "indexes", n)==0) )
25996   ){
25997     sqlite3_stmt *pStmt;
25998     char **azResult;
25999     int nRow, nAlloc;
26000     int ii;
26001     ShellText s;
26002     initText(&s);
26003     open_db(p, 0);
26004     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
26005     if( rc ){
26006       sqlite3_finalize(pStmt);
26007       return shellDatabaseError(p->db);
26008     }
26009 
26010     if( nArg>2 && c=='i' ){
26011       /* It is an historical accident that the .indexes command shows an error
26012       ** when called with the wrong number of arguments whereas the .tables
26013       ** command does not. */
26014       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
26015       rc = 1;
26016       sqlite3_finalize(pStmt);
26017       goto meta_command_exit;
26018     }
26019     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
26020       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
26021       if( zDbName==0 ) continue;
26022       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
26023       if( sqlite3_stricmp(zDbName, "main")==0 ){
26024         appendText(&s, "SELECT name FROM ", 0);
26025       }else{
26026         appendText(&s, "SELECT ", 0);
26027         appendText(&s, zDbName, '\'');
26028         appendText(&s, "||'.'||name FROM ", 0);
26029       }
26030       appendText(&s, zDbName, '"');
26031       appendText(&s, ".sqlite_schema ", 0);
26032       if( c=='t' ){
26033         appendText(&s," WHERE type IN ('table','view')"
26034                       "   AND name NOT LIKE 'sqlite_%'"
26035                       "   AND name LIKE ?1", 0);
26036       }else{
26037         appendText(&s," WHERE type='index'"
26038                       "   AND tbl_name LIKE ?1", 0);
26039       }
26040     }
26041     rc = sqlite3_finalize(pStmt);
26042     if( rc==SQLITE_OK ){
26043       appendText(&s, " ORDER BY 1", 0);
26044       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
26045     }
26046     freeText(&s);
26047     if( rc ) return shellDatabaseError(p->db);
26048 
26049     /* Run the SQL statement prepared by the above block. Store the results
26050     ** as an array of nul-terminated strings in azResult[].  */
26051     nRow = nAlloc = 0;
26052     azResult = 0;
26053     if( nArg>1 ){
26054       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
26055     }else{
26056       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
26057     }
26058     while( sqlite3_step(pStmt)==SQLITE_ROW ){
26059       if( nRow>=nAlloc ){
26060         char **azNew;
26061         int n2 = nAlloc*2 + 10;
26062         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
26063         shell_check_oom(azNew);
26064         nAlloc = n2;
26065         azResult = azNew;
26066       }
26067       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
26068       shell_check_oom(azResult[nRow]);
26069       nRow++;
26070     }
26071     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
26072       rc = shellDatabaseError(p->db);
26073     }
26074 
26075     /* Pretty-print the contents of array azResult[] to the output */
26076     if( rc==0 && nRow>0 ){
26077       int len, maxlen = 0;
26078       int i, j;
26079       int nPrintCol, nPrintRow;
26080       for(i=0; i<nRow; i++){
26081         len = strlen30(azResult[i]);
26082         if( len>maxlen ) maxlen = len;
26083       }
26084       nPrintCol = 80/(maxlen+2);
26085       if( nPrintCol<1 ) nPrintCol = 1;
26086       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
26087       for(i=0; i<nPrintRow; i++){
26088         for(j=i; j<nRow; j+=nPrintRow){
26089           char *zSp = j<nPrintRow ? "" : "  ";
26090           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
26091                       azResult[j] ? azResult[j]:"");
26092         }
26093         raw_printf(p->out, "\n");
26094       }
26095     }
26096 
26097     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
26098     sqlite3_free(azResult);
26099   }else
26100 
26101 #ifndef SQLITE_SHELL_FIDDLE
26102   /* Begin redirecting output to the file "testcase-out.txt" */
26103   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
26104     output_reset(p);
26105     p->out = output_file_open("testcase-out.txt", 0);
26106     if( p->out==0 ){
26107       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
26108     }
26109     if( nArg>=2 ){
26110       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
26111     }else{
26112       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
26113     }
26114   }else
26115 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26116 
26117 #ifndef SQLITE_UNTESTABLE
26118   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
26119     static const struct {
26120        const char *zCtrlName;   /* Name of a test-control option */
26121        int ctrlCode;            /* Integer code for that option */
26122        int unSafe;              /* Not valid for --safe mode */
26123        const char *zUsage;      /* Usage notes */
26124     } aCtrl[] = {
26125     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
26126     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
26127   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
26128   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
26129     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
26130     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
26131   /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
26132     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
26133     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
26134     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
26135     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
26136     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
26137 #ifdef YYCOVERAGE
26138     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
26139 #endif
26140     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
26141     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
26142     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
26143     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
26144     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
26145     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
26146     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
26147     };
26148     int testctrl = -1;
26149     int iCtrl = -1;
26150     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
26151     int isOk = 0;
26152     int i, n2;
26153     const char *zCmd = 0;
26154 
26155     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
26156       utf8_printf(stderr, ".%s unavailable without --unsafe-testing\n",
26157                   "testctrl");
26158       rc = 1;
26159       goto meta_command_exit;
26160     }
26161     open_db(p, 0);
26162     zCmd = nArg>=2 ? azArg[1] : "help";
26163 
26164     /* The argument can optionally begin with "-" or "--" */
26165     if( zCmd[0]=='-' && zCmd[1] ){
26166       zCmd++;
26167       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
26168     }
26169 
26170     /* --help lists all test-controls */
26171     if( cli_strcmp(zCmd,"help")==0 ){
26172       utf8_printf(p->out, "Available test-controls:\n");
26173       for(i=0; i<ArraySize(aCtrl); i++){
26174         utf8_printf(p->out, "  .testctrl %s %s\n",
26175                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
26176       }
26177       rc = 1;
26178       goto meta_command_exit;
26179     }
26180 
26181     /* convert testctrl text option to value. allow any unique prefix
26182     ** of the option name, or a numerical value. */
26183     n2 = strlen30(zCmd);
26184     for(i=0; i<ArraySize(aCtrl); i++){
26185       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
26186         if( testctrl<0 ){
26187           testctrl = aCtrl[i].ctrlCode;
26188           iCtrl = i;
26189         }else{
26190           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
26191                               "Use \".testctrl --help\" for help\n", zCmd);
26192           rc = 1;
26193           goto meta_command_exit;
26194         }
26195       }
26196     }
26197     if( testctrl<0 ){
26198       utf8_printf(stderr,"Error: unknown test-control: %s\n"
26199                          "Use \".testctrl --help\" for help\n", zCmd);
26200     }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
26201       utf8_printf(stderr,
26202          "line %d: \".testctrl %s\" may not be used in safe mode\n",
26203          p->lineno, aCtrl[iCtrl].zCtrlName);
26204       exit(1);
26205     }else{
26206       switch(testctrl){
26207 
26208         /* sqlite3_test_control(int, db, int) */
26209         case SQLITE_TESTCTRL_OPTIMIZATIONS:
26210           if( nArg==3 ){
26211             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
26212             rc2 = sqlite3_test_control(testctrl, p->db, opt);
26213             isOk = 3;
26214           }
26215           break;
26216 
26217         /* sqlite3_test_control(int) */
26218         case SQLITE_TESTCTRL_PRNG_SAVE:
26219         case SQLITE_TESTCTRL_PRNG_RESTORE:
26220         case SQLITE_TESTCTRL_BYTEORDER:
26221           if( nArg==2 ){
26222             rc2 = sqlite3_test_control(testctrl);
26223             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
26224           }
26225           break;
26226 
26227         /* sqlite3_test_control(int, uint) */
26228         case SQLITE_TESTCTRL_PENDING_BYTE:
26229           if( nArg==3 ){
26230             unsigned int opt = (unsigned int)integerValue(azArg[2]);
26231             rc2 = sqlite3_test_control(testctrl, opt);
26232             isOk = 3;
26233           }
26234           break;
26235 
26236         /* sqlite3_test_control(int, int, sqlite3*) */
26237         case SQLITE_TESTCTRL_PRNG_SEED:
26238           if( nArg==3 || nArg==4 ){
26239             int ii = (int)integerValue(azArg[2]);
26240             sqlite3 *db;
26241             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
26242               sqlite3_randomness(sizeof(ii),&ii);
26243               printf("-- random seed: %d\n", ii);
26244             }
26245             if( nArg==3 ){
26246               db = 0;
26247             }else{
26248               db = p->db;
26249               /* Make sure the schema has been loaded */
26250               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
26251             }
26252             rc2 = sqlite3_test_control(testctrl, ii, db);
26253             isOk = 3;
26254           }
26255           break;
26256 
26257         /* sqlite3_test_control(int, int) */
26258         case SQLITE_TESTCTRL_ASSERT:
26259         case SQLITE_TESTCTRL_ALWAYS:
26260           if( nArg==3 ){
26261             int opt = booleanValue(azArg[2]);
26262             rc2 = sqlite3_test_control(testctrl, opt);
26263             isOk = 1;
26264           }
26265           break;
26266 
26267         /* sqlite3_test_control(int, int) */
26268         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
26269         case SQLITE_TESTCTRL_NEVER_CORRUPT:
26270           if( nArg==3 ){
26271             int opt = booleanValue(azArg[2]);
26272             rc2 = sqlite3_test_control(testctrl, opt);
26273             isOk = 3;
26274           }
26275           break;
26276 
26277         /* sqlite3_test_control(sqlite3*) */
26278         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
26279           rc2 = sqlite3_test_control(testctrl, p->db);
26280           isOk = 3;
26281           break;
26282 
26283         case SQLITE_TESTCTRL_IMPOSTER:
26284           if( nArg==5 ){
26285             rc2 = sqlite3_test_control(testctrl, p->db,
26286                           azArg[2],
26287                           integerValue(azArg[3]),
26288                           integerValue(azArg[4]));
26289             isOk = 3;
26290           }
26291           break;
26292 
26293         case SQLITE_TESTCTRL_SEEK_COUNT: {
26294           u64 x = 0;
26295           rc2 = sqlite3_test_control(testctrl, p->db, &x);
26296           utf8_printf(p->out, "%llu\n", x);
26297           isOk = 3;
26298           break;
26299         }
26300 
26301 #ifdef YYCOVERAGE
26302         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
26303           if( nArg==2 ){
26304             sqlite3_test_control(testctrl, p->out);
26305             isOk = 3;
26306           }
26307           break;
26308         }
26309 #endif
26310 #ifdef SQLITE_DEBUG
26311         case SQLITE_TESTCTRL_TUNE: {
26312           if( nArg==4 ){
26313             int id = (int)integerValue(azArg[2]);
26314             int val = (int)integerValue(azArg[3]);
26315             sqlite3_test_control(testctrl, id, &val);
26316             isOk = 3;
26317           }else if( nArg==3 ){
26318             int id = (int)integerValue(azArg[2]);
26319             sqlite3_test_control(testctrl, -id, &rc2);
26320             isOk = 1;
26321           }else if( nArg==2 ){
26322             int id = 1;
26323             while(1){
26324               int val = 0;
26325               rc2 = sqlite3_test_control(testctrl, -id, &val);
26326               if( rc2!=SQLITE_OK ) break;
26327               if( id>1 ) utf8_printf(p->out, "  ");
26328               utf8_printf(p->out, "%d: %d", id, val);
26329               id++;
26330             }
26331             if( id>1 ) utf8_printf(p->out, "\n");
26332             isOk = 3;
26333           }
26334           break;
26335         }
26336 #endif
26337         case SQLITE_TESTCTRL_SORTER_MMAP:
26338           if( nArg==3 ){
26339             int opt = (unsigned int)integerValue(azArg[2]);
26340             rc2 = sqlite3_test_control(testctrl, p->db, opt);
26341             isOk = 3;
26342           }
26343           break;
26344       }
26345     }
26346     if( isOk==0 && iCtrl>=0 ){
26347       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
26348       rc = 1;
26349     }else if( isOk==1 ){
26350       raw_printf(p->out, "%d\n", rc2);
26351     }else if( isOk==2 ){
26352       raw_printf(p->out, "0x%08x\n", rc2);
26353     }
26354   }else
26355 #endif /* !defined(SQLITE_UNTESTABLE) */
26356 
26357   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
26358     open_db(p, 0);
26359     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
26360   }else
26361 
26362   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
26363     if( nArg==2 ){
26364       enableTimer = booleanValue(azArg[1]);
26365       if( enableTimer && !HAS_TIMER ){
26366         raw_printf(stderr, "Error: timer not available on this system.\n");
26367         enableTimer = 0;
26368       }
26369     }else{
26370       raw_printf(stderr, "Usage: .timer on|off\n");
26371       rc = 1;
26372     }
26373   }else
26374 
26375 #ifndef SQLITE_OMIT_TRACE
26376   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
26377     int mType = 0;
26378     int jj;
26379     open_db(p, 0);
26380     for(jj=1; jj<nArg; jj++){
26381       const char *z = azArg[jj];
26382       if( z[0]=='-' ){
26383         if( optionMatch(z, "expanded") ){
26384           p->eTraceType = SHELL_TRACE_EXPANDED;
26385         }
26386 #ifdef SQLITE_ENABLE_NORMALIZE
26387         else if( optionMatch(z, "normalized") ){
26388           p->eTraceType = SHELL_TRACE_NORMALIZED;
26389         }
26390 #endif
26391         else if( optionMatch(z, "plain") ){
26392           p->eTraceType = SHELL_TRACE_PLAIN;
26393         }
26394         else if( optionMatch(z, "profile") ){
26395           mType |= SQLITE_TRACE_PROFILE;
26396         }
26397         else if( optionMatch(z, "row") ){
26398           mType |= SQLITE_TRACE_ROW;
26399         }
26400         else if( optionMatch(z, "stmt") ){
26401           mType |= SQLITE_TRACE_STMT;
26402         }
26403         else if( optionMatch(z, "close") ){
26404           mType |= SQLITE_TRACE_CLOSE;
26405         }
26406         else {
26407           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
26408           rc = 1;
26409           goto meta_command_exit;
26410         }
26411       }else{
26412         output_file_close(p->traceOut);
26413         p->traceOut = output_file_open(z, 0);
26414       }
26415     }
26416     if( p->traceOut==0 ){
26417       sqlite3_trace_v2(p->db, 0, 0, 0);
26418     }else{
26419       if( mType==0 ) mType = SQLITE_TRACE_STMT;
26420       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
26421     }
26422   }else
26423 #endif /* !defined(SQLITE_OMIT_TRACE) */
26424 
26425 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
26426   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
26427     int ii;
26428     int lenOpt;
26429     char *zOpt;
26430     if( nArg<2 ){
26431       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
26432       rc = 1;
26433       goto meta_command_exit;
26434     }
26435     open_db(p, 0);
26436     zOpt = azArg[1];
26437     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
26438     lenOpt = (int)strlen(zOpt);
26439     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
26440       assert( azArg[nArg]==0 );
26441       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
26442     }else{
26443       for(ii=1; ii<nArg; ii++){
26444         sqlite3_create_module(p->db, azArg[ii], 0, 0);
26445       }
26446     }
26447   }else
26448 #endif
26449 
26450 #if SQLITE_USER_AUTHENTICATION
26451   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
26452     if( nArg<2 ){
26453       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
26454       rc = 1;
26455       goto meta_command_exit;
26456     }
26457     open_db(p, 0);
26458     if( cli_strcmp(azArg[1],"login")==0 ){
26459       if( nArg!=4 ){
26460         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
26461         rc = 1;
26462         goto meta_command_exit;
26463       }
26464       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
26465                                      strlen30(azArg[3]));
26466       if( rc ){
26467         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
26468         rc = 1;
26469       }
26470     }else if( cli_strcmp(azArg[1],"add")==0 ){
26471       if( nArg!=5 ){
26472         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
26473         rc = 1;
26474         goto meta_command_exit;
26475       }
26476       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
26477                             booleanValue(azArg[4]));
26478       if( rc ){
26479         raw_printf(stderr, "User-Add failed: %d\n", rc);
26480         rc = 1;
26481       }
26482     }else if( cli_strcmp(azArg[1],"edit")==0 ){
26483       if( nArg!=5 ){
26484         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
26485         rc = 1;
26486         goto meta_command_exit;
26487       }
26488       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
26489                               booleanValue(azArg[4]));
26490       if( rc ){
26491         raw_printf(stderr, "User-Edit failed: %d\n", rc);
26492         rc = 1;
26493       }
26494     }else if( cli_strcmp(azArg[1],"delete")==0 ){
26495       if( nArg!=3 ){
26496         raw_printf(stderr, "Usage: .user delete USER\n");
26497         rc = 1;
26498         goto meta_command_exit;
26499       }
26500       rc = sqlite3_user_delete(p->db, azArg[2]);
26501       if( rc ){
26502         raw_printf(stderr, "User-Delete failed: %d\n", rc);
26503         rc = 1;
26504       }
26505     }else{
26506       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
26507       rc = 1;
26508       goto meta_command_exit;
26509     }
26510   }else
26511 #endif /* SQLITE_USER_AUTHENTICATION */
26512 
26513   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
26514     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
26515         sqlite3_libversion(), sqlite3_sourceid());
26516 #if SQLITE_HAVE_ZLIB
26517     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
26518 #endif
26519 #define CTIMEOPT_VAL_(opt) #opt
26520 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
26521 #if defined(__clang__) && defined(__clang_major__)
26522     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
26523                     CTIMEOPT_VAL(__clang_minor__) "."
26524                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
26525 #elif defined(_MSC_VER)
26526     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
26527 #elif defined(__GNUC__) && defined(__VERSION__)
26528     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
26529 #endif
26530   }else
26531 
26532   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
26533     const char *zDbName = nArg==2 ? azArg[1] : "main";
26534     sqlite3_vfs *pVfs = 0;
26535     if( p->db ){
26536       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
26537       if( pVfs ){
26538         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
26539         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
26540         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
26541         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
26542       }
26543     }
26544   }else
26545 
26546   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
26547     sqlite3_vfs *pVfs;
26548     sqlite3_vfs *pCurrent = 0;
26549     if( p->db ){
26550       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
26551     }
26552     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
26553       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
26554            pVfs==pCurrent ? "  <--- CURRENT" : "");
26555       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
26556       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
26557       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
26558       if( pVfs->pNext ){
26559         raw_printf(p->out, "-----------------------------------\n");
26560       }
26561     }
26562   }else
26563 
26564   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
26565     const char *zDbName = nArg==2 ? azArg[1] : "main";
26566     char *zVfsName = 0;
26567     if( p->db ){
26568       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
26569       if( zVfsName ){
26570         utf8_printf(p->out, "%s\n", zVfsName);
26571         sqlite3_free(zVfsName);
26572       }
26573     }
26574   }else
26575 
26576   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
26577     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26578     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
26579   }else
26580 
26581   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
26582     int j;
26583     assert( nArg<=ArraySize(azArg) );
26584     p->nWidth = nArg-1;
26585     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
26586     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
26587     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
26588     for(j=1; j<nArg; j++){
26589       p->colWidth[j-1] = (int)integerValue(azArg[j]);
26590     }
26591   }else
26592 
26593   {
26594     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
26595       " \"%s\". Enter \".help\" for help\n", azArg[0]);
26596     rc = 1;
26597   }
26598 
26599 meta_command_exit:
26600   if( p->outCount ){
26601     p->outCount--;
26602     if( p->outCount==0 ) output_reset(p);
26603   }
26604   p->bSafeMode = p->bSafeModePersist;
26605   return rc;
26606 }
26607 
26608 /* Line scan result and intermediate states (supporting scan resumption)
26609 */
26610 #ifndef CHAR_BIT
26611 # define CHAR_BIT 8
26612 #endif
26613 typedef enum {
26614   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
26615   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
26616   QSS_Start = 0
26617 } QuickScanState;
26618 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
26619 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
26620 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
26621 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
26622 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
26623 
26624 /*
26625 ** Scan line for classification to guide shell's handling.
26626 ** The scan is resumable for subsequent lines when prior
26627 ** return values are passed as the 2nd argument.
26628 */
26629 static QuickScanState quickscan(char *zLine, QuickScanState qss,
26630                                 SCAN_TRACKER_REFTYPE pst){
26631   char cin;
26632   char cWait = (char)qss; /* intentional narrowing loss */
26633   if( cWait==0 ){
26634   PlainScan:
26635     assert( cWait==0 );
26636     while( (cin = *zLine++)!=0 ){
26637       if( IsSpace(cin) )
26638         continue;
26639       switch (cin){
26640       case '-':
26641         if( *zLine!='-' )
26642           break;
26643         while((cin = *++zLine)!=0 )
26644           if( cin=='\n')
26645             goto PlainScan;
26646         return qss;
26647       case ';':
26648         qss |= QSS_EndingSemi;
26649         continue;
26650       case '/':
26651         if( *zLine=='*' ){
26652           ++zLine;
26653           cWait = '*';
26654           CONTINUE_PROMPT_AWAITS(pst, "/*");
26655           qss = QSS_SETV(qss, cWait);
26656           goto TermScan;
26657         }
26658         break;
26659       case '[':
26660         cin = ']';
26661         deliberate_fall_through;
26662       case '`': case '\'': case '"':
26663         cWait = cin;
26664         qss = QSS_HasDark | cWait;
26665         CONTINUE_PROMPT_AWAITC(pst, cin);
26666         goto TermScan;
26667       case '(':
26668         CONTINUE_PAREN_INCR(pst, 1);
26669         break;
26670       case ')':
26671         CONTINUE_PAREN_INCR(pst, -1);
26672         break;
26673       default:
26674         break;
26675       }
26676       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
26677     }
26678   }else{
26679   TermScan:
26680     while( (cin = *zLine++)!=0 ){
26681       if( cin==cWait ){
26682         switch( cWait ){
26683         case '*':
26684           if( *zLine != '/' )
26685             continue;
26686           ++zLine;
26687           cWait = 0;
26688           CONTINUE_PROMPT_AWAITC(pst, 0);
26689           qss = QSS_SETV(qss, 0);
26690           goto PlainScan;
26691         case '`': case '\'': case '"':
26692           if(*zLine==cWait){
26693             /* Swallow doubled end-delimiter.*/
26694             ++zLine;
26695             continue;
26696           }
26697           deliberate_fall_through;
26698         case ']':
26699           cWait = 0;
26700           CONTINUE_PROMPT_AWAITC(pst, 0);
26701           qss = QSS_SETV(qss, 0);
26702           goto PlainScan;
26703         default: assert(0);
26704         }
26705       }
26706     }
26707   }
26708   return qss;
26709 }
26710 
26711 /*
26712 ** Return TRUE if the line typed in is an SQL command terminator other
26713 ** than a semi-colon.  The SQL Server style "go" command is understood
26714 ** as is the Oracle "/".
26715 */
26716 static int line_is_command_terminator(char *zLine){
26717   while( IsSpace(zLine[0]) ){ zLine++; };
26718   if( zLine[0]=='/' )
26719     zLine += 1; /* Oracle */
26720   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
26721     zLine += 2; /* SQL Server */
26722   else
26723     return 0;
26724   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
26725 }
26726 
26727 /*
26728 ** The CLI needs a working sqlite3_complete() to work properly.  So error
26729 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
26730 */
26731 #ifdef SQLITE_OMIT_COMPLETE
26732 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
26733 #endif
26734 
26735 /*
26736 ** Return true if zSql is a complete SQL statement.  Return false if it
26737 ** ends in the middle of a string literal or C-style comment.
26738 */
26739 static int line_is_complete(char *zSql, int nSql){
26740   int rc;
26741   if( zSql==0 ) return 1;
26742   zSql[nSql] = ';';
26743   zSql[nSql+1] = 0;
26744   rc = sqlite3_complete(zSql);
26745   zSql[nSql] = 0;
26746   return rc;
26747 }
26748 
26749 /*
26750 ** Run a single line of SQL.  Return the number of errors.
26751 */
26752 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
26753   int rc;
26754   char *zErrMsg = 0;
26755 
26756   open_db(p, 0);
26757   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
26758   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
26759   BEGIN_TIMER;
26760   rc = shell_exec(p, zSql, &zErrMsg);
26761   END_TIMER;
26762   if( rc || zErrMsg ){
26763     char zPrefix[100];
26764     const char *zErrorTail;
26765     const char *zErrorType;
26766     if( zErrMsg==0 ){
26767       zErrorType = "Error";
26768       zErrorTail = sqlite3_errmsg(p->db);
26769     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
26770       zErrorType = "Parse error";
26771       zErrorTail = &zErrMsg[12];
26772     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
26773       zErrorType = "Runtime error";
26774       zErrorTail = &zErrMsg[10];
26775     }else{
26776       zErrorType = "Error";
26777       zErrorTail = zErrMsg;
26778     }
26779     if( in!=0 || !stdin_is_interactive ){
26780       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
26781                        "%s near line %d:", zErrorType, startline);
26782     }else{
26783       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
26784     }
26785     utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
26786     sqlite3_free(zErrMsg);
26787     zErrMsg = 0;
26788     return 1;
26789   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
26790     char zLineBuf[2000];
26791     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
26792             "changes: %lld   total_changes: %lld",
26793             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
26794     raw_printf(p->out, "%s\n", zLineBuf);
26795   }
26796   return 0;
26797 }
26798 
26799 static void echo_group_input(ShellState *p, const char *zDo){
26800   if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
26801 }
26802 
26803 #ifdef SQLITE_SHELL_FIDDLE
26804 /*
26805 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
26806 ** impl because we need the global shellState and cannot access it from that
26807 ** function without moving lots of code around (creating a larger/messier diff).
26808 */
26809 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
26810   /* Parse the next line from shellState.wasm.zInput. */
26811   const char *zBegin = shellState.wasm.zPos;
26812   const char *z = zBegin;
26813   char *zLine = 0;
26814   i64 nZ = 0;
26815 
26816   UNUSED_PARAMETER(in);
26817   UNUSED_PARAMETER(isContinuation);
26818   if(!z || !*z){
26819     return 0;
26820   }
26821   while(*z && isspace(*z)) ++z;
26822   zBegin = z;
26823   for(; *z && '\n'!=*z; ++nZ, ++z){}
26824   if(nZ>0 && '\r'==zBegin[nZ-1]){
26825     --nZ;
26826   }
26827   shellState.wasm.zPos = z;
26828   zLine = realloc(zPrior, nZ+1);
26829   shell_check_oom(zLine);
26830   memcpy(zLine, zBegin, nZ);
26831   zLine[nZ] = 0;
26832   return zLine;
26833 }
26834 #endif /* SQLITE_SHELL_FIDDLE */
26835 
26836 /*
26837 ** Read input from *in and process it.  If *in==0 then input
26838 ** is interactive - the user is typing it it.  Otherwise, input
26839 ** is coming from a file or device.  A prompt is issued and history
26840 ** is saved only if input is interactive.  An interrupt signal will
26841 ** cause this routine to exit immediately, unless input is interactive.
26842 **
26843 ** Return the number of errors.
26844 */
26845 static int process_input(ShellState *p){
26846   char *zLine = 0;          /* A single input line */
26847   char *zSql = 0;           /* Accumulated SQL text */
26848   i64 nLine;                /* Length of current line */
26849   i64 nSql = 0;             /* Bytes of zSql[] used */
26850   i64 nAlloc = 0;           /* Allocated zSql[] space */
26851   int rc;                   /* Error code */
26852   int errCnt = 0;           /* Number of errors seen */
26853   i64 startline = 0;        /* Line number for start of current input */
26854   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
26855 
26856   if( p->inputNesting==MAX_INPUT_NESTING ){
26857     /* This will be more informative in a later version. */
26858     utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
26859                 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
26860     return 1;
26861   }
26862   ++p->inputNesting;
26863   p->lineno = 0;
26864   CONTINUE_PROMPT_RESET;
26865   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
26866     fflush(p->out);
26867     zLine = one_input_line(p->in, zLine, nSql>0);
26868     if( zLine==0 ){
26869       /* End of input */
26870       if( p->in==0 && stdin_is_interactive ) printf("\n");
26871       break;
26872     }
26873     if( seenInterrupt ){
26874       if( p->in!=0 ) break;
26875       seenInterrupt = 0;
26876     }
26877     p->lineno++;
26878     if( QSS_INPLAIN(qss)
26879         && line_is_command_terminator(zLine)
26880         && line_is_complete(zSql, nSql) ){
26881       memcpy(zLine,";",2);
26882     }
26883     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
26884     if( QSS_PLAINWHITE(qss) && nSql==0 ){
26885       /* Just swallow single-line whitespace */
26886       echo_group_input(p, zLine);
26887       qss = QSS_Start;
26888       continue;
26889     }
26890     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
26891       CONTINUE_PROMPT_RESET;
26892       echo_group_input(p, zLine);
26893       if( zLine[0]=='.' ){
26894         rc = do_meta_command(zLine, p);
26895         if( rc==2 ){ /* exit requested */
26896           break;
26897         }else if( rc ){
26898           errCnt++;
26899         }
26900       }
26901       qss = QSS_Start;
26902       continue;
26903     }
26904     /* No single-line dispositions remain; accumulate line(s). */
26905     nLine = strlen(zLine);
26906     if( nSql+nLine+2>=nAlloc ){
26907       /* Grow buffer by half-again increments when big. */
26908       nAlloc = nSql+(nSql>>1)+nLine+100;
26909       zSql = realloc(zSql, nAlloc);
26910       shell_check_oom(zSql);
26911     }
26912     if( nSql==0 ){
26913       i64 i;
26914       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
26915       assert( nAlloc>0 && zSql!=0 );
26916       memcpy(zSql, zLine+i, nLine+1-i);
26917       startline = p->lineno;
26918       nSql = nLine-i;
26919     }else{
26920       zSql[nSql++] = '\n';
26921       memcpy(zSql+nSql, zLine, nLine+1);
26922       nSql += nLine;
26923     }
26924     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
26925       echo_group_input(p, zSql);
26926       errCnt += runOneSqlLine(p, zSql, p->in, startline);
26927       CONTINUE_PROMPT_RESET;
26928       nSql = 0;
26929       if( p->outCount ){
26930         output_reset(p);
26931         p->outCount = 0;
26932       }else{
26933         clearTempFile(p);
26934       }
26935       p->bSafeMode = p->bSafeModePersist;
26936       qss = QSS_Start;
26937     }else if( nSql && QSS_PLAINWHITE(qss) ){
26938       echo_group_input(p, zSql);
26939       nSql = 0;
26940       qss = QSS_Start;
26941     }
26942   }
26943   if( nSql ){
26944     /* This may be incomplete. Let the SQL parser deal with that. */
26945     echo_group_input(p, zSql);
26946     errCnt += runOneSqlLine(p, zSql, p->in, startline);
26947     CONTINUE_PROMPT_RESET;
26948   }
26949   free(zSql);
26950   free(zLine);
26951   --p->inputNesting;
26952   return errCnt>0;
26953 }
26954 
26955 /*
26956 ** Return a pathname which is the user's home directory.  A
26957 ** 0 return indicates an error of some kind.
26958 */
26959 static char *find_home_dir(int clearFlag){
26960   static char *home_dir = NULL;
26961   if( clearFlag ){
26962     free(home_dir);
26963     home_dir = 0;
26964     return 0;
26965   }
26966   if( home_dir ) return home_dir;
26967 
26968 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
26969      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
26970   {
26971     struct passwd *pwent;
26972     uid_t uid = getuid();
26973     if( (pwent=getpwuid(uid)) != NULL) {
26974       home_dir = pwent->pw_dir;
26975     }
26976   }
26977 #endif
26978 
26979 #if defined(_WIN32_WCE)
26980   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
26981    */
26982   home_dir = "/";
26983 #else
26984 
26985 #if defined(_WIN32) || defined(WIN32)
26986   if (!home_dir) {
26987     home_dir = getenv("USERPROFILE");
26988   }
26989 #endif
26990 
26991   if (!home_dir) {
26992     home_dir = getenv("HOME");
26993   }
26994 
26995 #if defined(_WIN32) || defined(WIN32)
26996   if (!home_dir) {
26997     char *zDrive, *zPath;
26998     int n;
26999     zDrive = getenv("HOMEDRIVE");
27000     zPath = getenv("HOMEPATH");
27001     if( zDrive && zPath ){
27002       n = strlen30(zDrive) + strlen30(zPath) + 1;
27003       home_dir = malloc( n );
27004       if( home_dir==0 ) return 0;
27005       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
27006       return home_dir;
27007     }
27008     home_dir = "c:\\";
27009   }
27010 #endif
27011 
27012 #endif /* !_WIN32_WCE */
27013 
27014   if( home_dir ){
27015     i64 n = strlen(home_dir) + 1;
27016     char *z = malloc( n );
27017     if( z ) memcpy(z, home_dir, n);
27018     home_dir = z;
27019   }
27020 
27021   return home_dir;
27022 }
27023 
27024 /*
27025 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
27026 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
27027 ** the path to it, else return 0. The result is cached for
27028 ** subsequent calls.
27029 */
27030 static const char *find_xdg_config(void){
27031 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
27032      || defined(__RTP__) || defined(_WRS_KERNEL)
27033   return 0;
27034 #else
27035   static int alreadyTried = 0;
27036   static char *zConfig = 0;
27037   const char *zXdgHome;
27038 
27039   if( alreadyTried!=0 ){
27040     return zConfig;
27041   }
27042   alreadyTried = 1;
27043   zXdgHome = getenv("XDG_CONFIG_HOME");
27044   if( zXdgHome==0 ){
27045     return 0;
27046   }
27047   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
27048   shell_check_oom(zConfig);
27049   if( access(zConfig,0)!=0 ){
27050     sqlite3_free(zConfig);
27051     zConfig = 0;
27052   }
27053   return zConfig;
27054 #endif
27055 }
27056 
27057 /*
27058 ** Read input from the file given by sqliterc_override.  Or if that
27059 ** parameter is NULL, take input from the first of find_xdg_config()
27060 ** or ~/.sqliterc which is found.
27061 **
27062 ** Returns the number of errors.
27063 */
27064 static void process_sqliterc(
27065   ShellState *p,                  /* Configuration data */
27066   const char *sqliterc_override   /* Name of config file. NULL to use default */
27067 ){
27068   char *home_dir = NULL;
27069   const char *sqliterc = sqliterc_override;
27070   char *zBuf = 0;
27071   FILE *inSaved = p->in;
27072   int savedLineno = p->lineno;
27073 
27074   if( sqliterc == NULL ){
27075     sqliterc = find_xdg_config();
27076   }
27077   if( sqliterc == NULL ){
27078     home_dir = find_home_dir(0);
27079     if( home_dir==0 ){
27080       raw_printf(stderr, "-- warning: cannot find home directory;"
27081                       " cannot read ~/.sqliterc\n");
27082       return;
27083     }
27084     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
27085     shell_check_oom(zBuf);
27086     sqliterc = zBuf;
27087   }
27088   p->in = fopen(sqliterc,"rb");
27089   if( p->in ){
27090     if( stdin_is_interactive ){
27091       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
27092     }
27093     if( process_input(p) && bail_on_error ) exit(1);
27094     fclose(p->in);
27095   }else if( sqliterc_override!=0 ){
27096     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
27097     if( bail_on_error ) exit(1);
27098   }
27099   p->in = inSaved;
27100   p->lineno = savedLineno;
27101   sqlite3_free(zBuf);
27102 }
27103 
27104 /*
27105 ** Show available command line options
27106 */
27107 static const char zOptions[] =
27108   "   --                   treat no subsequent arguments as options\n"
27109 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27110   "   -A ARGS...           run \".archive ARGS\" and exit\n"
27111 #endif
27112   "   -append              append the database to the end of the file\n"
27113   "   -ascii               set output mode to 'ascii'\n"
27114   "   -bail                stop after hitting an error\n"
27115   "   -batch               force batch I/O\n"
27116   "   -box                 set output mode to 'box'\n"
27117   "   -column              set output mode to 'column'\n"
27118   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
27119   "   -csv                 set output mode to 'csv'\n"
27120 #if !defined(SQLITE_OMIT_DESERIALIZE)
27121   "   -deserialize         open the database using sqlite3_deserialize()\n"
27122 #endif
27123   "   -echo                print inputs before execution\n"
27124   "   -init FILENAME       read/process named file\n"
27125   "   -[no]header          turn headers on or off\n"
27126 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
27127   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
27128 #endif
27129   "   -help                show this message\n"
27130   "   -html                set output mode to HTML\n"
27131   "   -interactive         force interactive I/O\n"
27132   "   -json                set output mode to 'json'\n"
27133   "   -line                set output mode to 'line'\n"
27134   "   -list                set output mode to 'list'\n"
27135   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
27136   "   -markdown            set output mode to 'markdown'\n"
27137 #if !defined(SQLITE_OMIT_DESERIALIZE)
27138   "   -maxsize N           maximum size for a --deserialize database\n"
27139 #endif
27140   "   -memtrace            trace all memory allocations and deallocations\n"
27141   "   -mmap N              default mmap size set to N\n"
27142 #ifdef SQLITE_ENABLE_MULTIPLEX
27143   "   -multiplex           enable the multiplexor VFS\n"
27144 #endif
27145   "   -newline SEP         set output row separator. Default: '\\n'\n"
27146   "   -nofollow            refuse to open symbolic links to database files\n"
27147   "   -nonce STRING        set the safe-mode escape nonce\n"
27148   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
27149   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
27150   "   -quote               set output mode to 'quote'\n"
27151   "   -readonly            open the database read-only\n"
27152   "   -safe                enable safe-mode\n"
27153   "   -separator SEP       set output column separator. Default: '|'\n"
27154 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27155   "   -sorterref SIZE      sorter references threshold size\n"
27156 #endif
27157   "   -stats               print memory stats before each finalize\n"
27158   "   -table               set output mode to 'table'\n"
27159   "   -tabs                set output mode to 'tabs'\n"
27160   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
27161 #if SHELL_WIN_UTF8_OPT
27162   "   -utf8                setup interactive console code page for UTF-8\n"
27163 #endif
27164   "   -version             show SQLite version\n"
27165   "   -vfs NAME            use NAME as the default VFS\n"
27166 #ifdef SQLITE_ENABLE_VFSTRACE
27167   "   -vfstrace            enable tracing of all VFS calls\n"
27168 #endif
27169 #ifdef SQLITE_HAVE_ZLIB
27170   "   -zip                 open the file as a ZIP Archive\n"
27171 #endif
27172 ;
27173 static void usage(int showDetail){
27174   utf8_printf(stderr,
27175       "Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
27176       "FILENAME is the name of an SQLite database. A new database is created\n"
27177       "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
27178   if( showDetail ){
27179     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
27180   }else{
27181     raw_printf(stderr, "Use the -help option for additional information\n");
27182   }
27183   exit(1);
27184 }
27185 
27186 /*
27187 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
27188 ** error message if it is initialized.
27189 */
27190 static void verify_uninitialized(void){
27191   if( sqlite3_config(-1)==SQLITE_MISUSE ){
27192     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
27193                         " initialization.\n");
27194   }
27195 }
27196 
27197 /*
27198 ** Initialize the state information in data
27199 */
27200 static void main_init(ShellState *data) {
27201   memset(data, 0, sizeof(*data));
27202   data->normalMode = data->cMode = data->mode = MODE_List;
27203   data->autoExplain = 1;
27204   data->pAuxDb = &data->aAuxDb[0];
27205   memcpy(data->colSeparator,SEP_Column, 2);
27206   memcpy(data->rowSeparator,SEP_Row, 2);
27207   data->showHeader = 0;
27208   data->shellFlgs = SHFLG_Lookaside;
27209   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
27210 #if !defined(SQLITE_SHELL_FIDDLE)
27211   verify_uninitialized();
27212 #endif
27213   sqlite3_config(SQLITE_CONFIG_URI, 1);
27214   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
27215   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
27216   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
27217 }
27218 
27219 /*
27220 ** Output text to the console in a font that attracts extra attention.
27221 */
27222 #ifdef _WIN32
27223 static void printBold(const char *zText){
27224 #if !SQLITE_OS_WINRT
27225   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
27226   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
27227   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
27228   SetConsoleTextAttribute(out,
27229          FOREGROUND_RED|FOREGROUND_INTENSITY
27230   );
27231 #endif
27232   printf("%s", zText);
27233 #if !SQLITE_OS_WINRT
27234   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
27235 #endif
27236 }
27237 #else
27238 static void printBold(const char *zText){
27239   printf("\033[1m%s\033[0m", zText);
27240 }
27241 #endif
27242 
27243 /*
27244 ** Get the argument to an --option.  Throw an error and die if no argument
27245 ** is available.
27246 */
27247 static char *cmdline_option_value(int argc, char **argv, int i){
27248   if( i==argc ){
27249     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
27250             argv[0], argv[argc-1]);
27251     exit(1);
27252   }
27253   return argv[i];
27254 }
27255 
27256 static void sayAbnormalExit(void){
27257   if( seenInterrupt ) fprintf(stderr, "Program interrupted.\n");
27258 }
27259 
27260 #ifndef SQLITE_SHELL_IS_UTF8
27261 #  if (defined(_WIN32) || defined(WIN32)) \
27262    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
27263 #    define SQLITE_SHELL_IS_UTF8          (0)
27264 #  else
27265 #    define SQLITE_SHELL_IS_UTF8          (1)
27266 #  endif
27267 #endif
27268 
27269 #ifdef SQLITE_SHELL_FIDDLE
27270 #  define main fiddle_main
27271 #endif
27272 
27273 #if SQLITE_SHELL_IS_UTF8
27274 int SQLITE_CDECL main(int argc, char **argv){
27275 #else
27276 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
27277   char **argv;
27278 #endif
27279 #ifdef SQLITE_DEBUG
27280   sqlite3_int64 mem_main_enter = 0;
27281 #endif
27282   char *zErrMsg = 0;
27283 #ifdef SQLITE_SHELL_FIDDLE
27284 #  define data shellState
27285 #else
27286   ShellState data;
27287 #endif
27288   const char *zInitFile = 0;
27289   int i;
27290   int rc = 0;
27291   int warnInmemoryDb = 0;
27292   int readStdin = 1;
27293   int nCmd = 0;
27294   int nOptsEnd = argc;
27295   char **azCmd = 0;
27296   const char *zVfs = 0;           /* Value of -vfs command-line option */
27297 #if !SQLITE_SHELL_IS_UTF8
27298   char **argvToFree = 0;
27299   int argcToFree = 0;
27300 #endif
27301   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
27302 
27303 #ifdef SQLITE_SHELL_FIDDLE
27304   stdin_is_interactive = 0;
27305   stdout_is_console = 1;
27306   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
27307 #else
27308   stdin_is_interactive = isatty(0);
27309   stdout_is_console = isatty(1);
27310 #endif
27311 #if SHELL_WIN_UTF8_OPT
27312   atexit(console_restore); /* Needs revision for CLI as library call */
27313 #endif
27314   atexit(sayAbnormalExit);
27315 #ifdef SQLITE_DEBUG
27316   mem_main_enter = sqlite3_memory_used();
27317 #endif
27318 #if !defined(_WIN32_WCE)
27319   if( getenv("SQLITE_DEBUG_BREAK") ){
27320     if( isatty(0) && isatty(2) ){
27321       fprintf(stderr,
27322           "attach debugger to process %d and press any key to continue.\n",
27323           GETPID());
27324       fgetc(stdin);
27325     }else{
27326 #if defined(_WIN32) || defined(WIN32)
27327 #if SQLITE_OS_WINRT
27328       __debugbreak();
27329 #else
27330       DebugBreak();
27331 #endif
27332 #elif defined(SIGTRAP)
27333       raise(SIGTRAP);
27334 #endif
27335     }
27336   }
27337 #endif
27338   /* Register a valid signal handler early, before much else is done. */
27339 #ifdef SIGINT
27340   signal(SIGINT, interrupt_handler);
27341 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
27342   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
27343     fprintf(stderr, "No ^C handler.\n");
27344   }
27345 #endif
27346 
27347 #if USE_SYSTEM_SQLITE+0!=1
27348   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
27349     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
27350             sqlite3_sourceid(), SQLITE_SOURCE_ID);
27351     exit(1);
27352   }
27353 #endif
27354   main_init(&data);
27355 
27356   /* On Windows, we must translate command-line arguments into UTF-8.
27357   ** The SQLite memory allocator subsystem has to be enabled in order to
27358   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
27359   ** subsequent sqlite3_config() calls will work.  So copy all results into
27360   ** memory that does not come from the SQLite memory allocator.
27361   */
27362 #if !SQLITE_SHELL_IS_UTF8
27363   sqlite3_initialize();
27364   argvToFree = malloc(sizeof(argv[0])*argc*2);
27365   shell_check_oom(argvToFree);
27366   argcToFree = argc;
27367   argv = argvToFree + argc;
27368   for(i=0; i<argc; i++){
27369     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
27370     i64 n;
27371     shell_check_oom(z);
27372     n = strlen(z);
27373     argv[i] = malloc( n+1 );
27374     shell_check_oom(argv[i]);
27375     memcpy(argv[i], z, n+1);
27376     argvToFree[i] = argv[i];
27377     sqlite3_free(z);
27378   }
27379   sqlite3_shutdown();
27380 #endif
27381 
27382   assert( argc>=1 && argv && argv[0] );
27383   Argv0 = argv[0];
27384 
27385 #ifdef SQLITE_SHELL_DBNAME_PROC
27386   {
27387     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
27388     ** of a C-function that will provide the name of the database file.  Use
27389     ** this compile-time option to embed this shell program in larger
27390     ** applications. */
27391     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
27392     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
27393     warnInmemoryDb = 0;
27394   }
27395 #endif
27396 
27397   /* Do an initial pass through the command-line argument to locate
27398   ** the name of the database file, the name of the initialization file,
27399   ** the size of the alternative malloc heap,
27400   ** and the first command to execute.
27401   */
27402 #ifndef SQLITE_SHELL_FIDDLE
27403   verify_uninitialized();
27404 #endif
27405   for(i=1; i<argc; i++){
27406     char *z;
27407     z = argv[i];
27408     if( z[0]!='-' || i>nOptsEnd ){
27409       if( data.aAuxDb->zDbFilename==0 ){
27410         data.aAuxDb->zDbFilename = z;
27411       }else{
27412         /* Excesss arguments are interpreted as SQL (or dot-commands) and
27413         ** mean that nothing is read from stdin */
27414         readStdin = 0;
27415         nCmd++;
27416         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
27417         shell_check_oom(azCmd);
27418         azCmd[nCmd-1] = z;
27419       }
27420       continue;
27421     }
27422     if( z[1]=='-' ) z++;
27423     if( cli_strcmp(z, "-")==0 ){
27424       nOptsEnd = i;
27425       continue;
27426     }else if( cli_strcmp(z,"-separator")==0
27427      || cli_strcmp(z,"-nullvalue")==0
27428      || cli_strcmp(z,"-newline")==0
27429      || cli_strcmp(z,"-cmd")==0
27430     ){
27431       (void)cmdline_option_value(argc, argv, ++i);
27432     }else if( cli_strcmp(z,"-init")==0 ){
27433       zInitFile = cmdline_option_value(argc, argv, ++i);
27434     }else if( cli_strcmp(z,"-batch")==0 ){
27435       /* Need to check for batch mode here to so we can avoid printing
27436       ** informational messages (like from process_sqliterc) before
27437       ** we do the actual processing of arguments later in a second pass.
27438       */
27439       stdin_is_interactive = 0;
27440     }else if( cli_strcmp(z,"-heap")==0 ){
27441 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
27442       const char *zSize;
27443       sqlite3_int64 szHeap;
27444 
27445       zSize = cmdline_option_value(argc, argv, ++i);
27446       szHeap = integerValue(zSize);
27447       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
27448       verify_uninitialized();
27449       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
27450 #else
27451       (void)cmdline_option_value(argc, argv, ++i);
27452 #endif
27453     }else if( cli_strcmp(z,"-pagecache")==0 ){
27454       sqlite3_int64 n, sz;
27455       sz = integerValue(cmdline_option_value(argc,argv,++i));
27456       if( sz>70000 ) sz = 70000;
27457       if( sz<0 ) sz = 0;
27458       n = integerValue(cmdline_option_value(argc,argv,++i));
27459       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
27460         n = 0xffffffffffffLL/sz;
27461       }
27462       verify_uninitialized();
27463       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
27464                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
27465       data.shellFlgs |= SHFLG_Pagecache;
27466     }else if( cli_strcmp(z,"-lookaside")==0 ){
27467       int n, sz;
27468       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
27469       if( sz<0 ) sz = 0;
27470       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
27471       if( n<0 ) n = 0;
27472       verify_uninitialized();
27473       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
27474       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
27475     }else if( cli_strcmp(z,"-threadsafe")==0 ){
27476       int n;
27477       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
27478       verify_uninitialized();
27479       switch( n ){
27480          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
27481          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
27482          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
27483       }
27484 #ifdef SQLITE_ENABLE_VFSTRACE
27485     }else if( cli_strcmp(z,"-vfstrace")==0 ){
27486       extern int vfstrace_register(
27487          const char *zTraceName,
27488          const char *zOldVfsName,
27489          int (*xOut)(const char*,void*),
27490          void *pOutArg,
27491          int makeDefault
27492       );
27493       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
27494 #endif
27495 #ifdef SQLITE_ENABLE_MULTIPLEX
27496     }else if( cli_strcmp(z,"-multiplex")==0 ){
27497       extern int sqlite3_multiple_initialize(const char*,int);
27498       sqlite3_multiplex_initialize(0, 1);
27499 #endif
27500     }else if( cli_strcmp(z,"-mmap")==0 ){
27501       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
27502       verify_uninitialized();
27503       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
27504 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
27505     }else if( cli_strcmp(z,"-sorterref")==0 ){
27506       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
27507       verify_uninitialized();
27508       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
27509 #endif
27510     }else if( cli_strcmp(z,"-vfs")==0 ){
27511       zVfs = cmdline_option_value(argc, argv, ++i);
27512 #ifdef SQLITE_HAVE_ZLIB
27513     }else if( cli_strcmp(z,"-zip")==0 ){
27514       data.openMode = SHELL_OPEN_ZIPFILE;
27515 #endif
27516     }else if( cli_strcmp(z,"-append")==0 ){
27517       data.openMode = SHELL_OPEN_APPENDVFS;
27518 #ifndef SQLITE_OMIT_DESERIALIZE
27519     }else if( cli_strcmp(z,"-deserialize")==0 ){
27520       data.openMode = SHELL_OPEN_DESERIALIZE;
27521     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
27522       data.szMax = integerValue(argv[++i]);
27523 #endif
27524     }else if( cli_strcmp(z,"-readonly")==0 ){
27525       data.openMode = SHELL_OPEN_READONLY;
27526     }else if( cli_strcmp(z,"-nofollow")==0 ){
27527       data.openFlags = SQLITE_OPEN_NOFOLLOW;
27528 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27529     }else if( cli_strncmp(z, "-A",2)==0 ){
27530       /* All remaining command-line arguments are passed to the ".archive"
27531       ** command, so ignore them */
27532       break;
27533 #endif
27534     }else if( cli_strcmp(z, "-memtrace")==0 ){
27535       sqlite3MemTraceActivate(stderr);
27536     }else if( cli_strcmp(z,"-bail")==0 ){
27537       bail_on_error = 1;
27538     }else if( cli_strcmp(z,"-nonce")==0 ){
27539       free(data.zNonce);
27540       data.zNonce = strdup(argv[++i]);
27541     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
27542       ShellSetFlag(&data,SHFLG_TestingMode);
27543     }else if( cli_strcmp(z,"-safe")==0 ){
27544       /* no-op - catch this on the second pass */
27545     }
27546   }
27547 #ifndef SQLITE_SHELL_FIDDLE
27548   verify_uninitialized();
27549 #endif
27550 
27551 
27552 #ifdef SQLITE_SHELL_INIT_PROC
27553   {
27554     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
27555     ** of a C-function that will perform initialization actions on SQLite that
27556     ** occur just before or after sqlite3_initialize(). Use this compile-time
27557     ** option to embed this shell program in larger applications. */
27558     extern void SQLITE_SHELL_INIT_PROC(void);
27559     SQLITE_SHELL_INIT_PROC();
27560   }
27561 #else
27562   /* All the sqlite3_config() calls have now been made. So it is safe
27563   ** to call sqlite3_initialize() and process any command line -vfs option. */
27564   sqlite3_initialize();
27565 #endif
27566 
27567   if( zVfs ){
27568     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
27569     if( pVfs ){
27570       sqlite3_vfs_register(pVfs, 1);
27571     }else{
27572       utf8_printf(stderr, "no such VFS: \"%s\"\n", zVfs);
27573       exit(1);
27574     }
27575   }
27576 
27577   if( data.pAuxDb->zDbFilename==0 ){
27578 #ifndef SQLITE_OMIT_MEMORYDB
27579     data.pAuxDb->zDbFilename = ":memory:";
27580     warnInmemoryDb = argc==1;
27581 #else
27582     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
27583     return 1;
27584 #endif
27585   }
27586   data.out = stdout;
27587 #ifndef SQLITE_SHELL_FIDDLE
27588   sqlite3_appendvfs_init(0,0,0);
27589 #endif
27590 
27591   /* Go ahead and open the database file if it already exists.  If the
27592   ** file does not exist, delay opening it.  This prevents empty database
27593   ** files from being created if a user mistypes the database name argument
27594   ** to the sqlite command-line tool.
27595   */
27596   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
27597     open_db(&data, 0);
27598   }
27599 
27600   /* Process the initialization file if there is one.  If no -init option
27601   ** is given on the command line, look for a file named ~/.sqliterc and
27602   ** try to process it.
27603   */
27604   process_sqliterc(&data,zInitFile);
27605 
27606   /* Make a second pass through the command-line argument and set
27607   ** options.  This second pass is delayed until after the initialization
27608   ** file is processed so that the command-line arguments will override
27609   ** settings in the initialization file.
27610   */
27611   for(i=1; i<argc; i++){
27612     char *z = argv[i];
27613     if( z[0]!='-' || i>=nOptsEnd ) continue;
27614     if( z[1]=='-' ){ z++; }
27615     if( cli_strcmp(z,"-init")==0 ){
27616       i++;
27617     }else if( cli_strcmp(z,"-html")==0 ){
27618       data.mode = MODE_Html;
27619     }else if( cli_strcmp(z,"-list")==0 ){
27620       data.mode = MODE_List;
27621     }else if( cli_strcmp(z,"-quote")==0 ){
27622       data.mode = MODE_Quote;
27623       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
27624       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
27625     }else if( cli_strcmp(z,"-line")==0 ){
27626       data.mode = MODE_Line;
27627     }else if( cli_strcmp(z,"-column")==0 ){
27628       data.mode = MODE_Column;
27629     }else if( cli_strcmp(z,"-json")==0 ){
27630       data.mode = MODE_Json;
27631     }else if( cli_strcmp(z,"-markdown")==0 ){
27632       data.mode = MODE_Markdown;
27633     }else if( cli_strcmp(z,"-table")==0 ){
27634       data.mode = MODE_Table;
27635     }else if( cli_strcmp(z,"-box")==0 ){
27636       data.mode = MODE_Box;
27637     }else if( cli_strcmp(z,"-csv")==0 ){
27638       data.mode = MODE_Csv;
27639       memcpy(data.colSeparator,",",2);
27640 #ifdef SQLITE_HAVE_ZLIB
27641     }else if( cli_strcmp(z,"-zip")==0 ){
27642       data.openMode = SHELL_OPEN_ZIPFILE;
27643 #endif
27644     }else if( cli_strcmp(z,"-append")==0 ){
27645       data.openMode = SHELL_OPEN_APPENDVFS;
27646 #ifndef SQLITE_OMIT_DESERIALIZE
27647     }else if( cli_strcmp(z,"-deserialize")==0 ){
27648       data.openMode = SHELL_OPEN_DESERIALIZE;
27649     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
27650       data.szMax = integerValue(argv[++i]);
27651 #endif
27652     }else if( cli_strcmp(z,"-readonly")==0 ){
27653       data.openMode = SHELL_OPEN_READONLY;
27654     }else if( cli_strcmp(z,"-nofollow")==0 ){
27655       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
27656     }else if( cli_strcmp(z,"-ascii")==0 ){
27657       data.mode = MODE_Ascii;
27658       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
27659       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
27660     }else if( cli_strcmp(z,"-tabs")==0 ){
27661       data.mode = MODE_List;
27662       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
27663       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
27664     }else if( cli_strcmp(z,"-separator")==0 ){
27665       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
27666                        "%s",cmdline_option_value(argc,argv,++i));
27667     }else if( cli_strcmp(z,"-newline")==0 ){
27668       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
27669                        "%s",cmdline_option_value(argc,argv,++i));
27670     }else if( cli_strcmp(z,"-nullvalue")==0 ){
27671       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
27672                        "%s",cmdline_option_value(argc,argv,++i));
27673     }else if( cli_strcmp(z,"-header")==0 ){
27674       data.showHeader = 1;
27675       ShellSetFlag(&data, SHFLG_HeaderSet);
27676      }else if( cli_strcmp(z,"-noheader")==0 ){
27677       data.showHeader = 0;
27678       ShellSetFlag(&data, SHFLG_HeaderSet);
27679     }else if( cli_strcmp(z,"-echo")==0 ){
27680       ShellSetFlag(&data, SHFLG_Echo);
27681     }else if( cli_strcmp(z,"-eqp")==0 ){
27682       data.autoEQP = AUTOEQP_on;
27683     }else if( cli_strcmp(z,"-eqpfull")==0 ){
27684       data.autoEQP = AUTOEQP_full;
27685     }else if( cli_strcmp(z,"-stats")==0 ){
27686       data.statsOn = 1;
27687     }else if( cli_strcmp(z,"-scanstats")==0 ){
27688       data.scanstatsOn = 1;
27689     }else if( cli_strcmp(z,"-backslash")==0 ){
27690       /* Undocumented command-line option: -backslash
27691       ** Causes C-style backslash escapes to be evaluated in SQL statements
27692       ** prior to sending the SQL into SQLite.  Useful for injecting
27693       ** crazy bytes in the middle of SQL statements for testing and debugging.
27694       */
27695       ShellSetFlag(&data, SHFLG_Backslash);
27696     }else if( cli_strcmp(z,"-bail")==0 ){
27697       /* No-op.  The bail_on_error flag should already be set. */
27698     }else if( cli_strcmp(z,"-version")==0 ){
27699       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
27700       return 0;
27701     }else if( cli_strcmp(z,"-interactive")==0 ){
27702       stdin_is_interactive = 1;
27703     }else if( cli_strcmp(z,"-batch")==0 ){
27704       stdin_is_interactive = 0;
27705     }else if( cli_strcmp(z,"-utf8")==0 ){
27706 #if SHELL_WIN_UTF8_OPT
27707       console_utf8 = 1;
27708 #endif /* SHELL_WIN_UTF8_OPT */
27709     }else if( cli_strcmp(z,"-heap")==0 ){
27710       i++;
27711     }else if( cli_strcmp(z,"-pagecache")==0 ){
27712       i+=2;
27713     }else if( cli_strcmp(z,"-lookaside")==0 ){
27714       i+=2;
27715     }else if( cli_strcmp(z,"-threadsafe")==0 ){
27716       i+=2;
27717     }else if( cli_strcmp(z,"-nonce")==0 ){
27718       i += 2;
27719     }else if( cli_strcmp(z,"-mmap")==0 ){
27720       i++;
27721     }else if( cli_strcmp(z,"-memtrace")==0 ){
27722       i++;
27723 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27724     }else if( cli_strcmp(z,"-sorterref")==0 ){
27725       i++;
27726 #endif
27727     }else if( cli_strcmp(z,"-vfs")==0 ){
27728       i++;
27729 #ifdef SQLITE_ENABLE_VFSTRACE
27730     }else if( cli_strcmp(z,"-vfstrace")==0 ){
27731       i++;
27732 #endif
27733 #ifdef SQLITE_ENABLE_MULTIPLEX
27734     }else if( cli_strcmp(z,"-multiplex")==0 ){
27735       i++;
27736 #endif
27737     }else if( cli_strcmp(z,"-help")==0 ){
27738       usage(1);
27739     }else if( cli_strcmp(z,"-cmd")==0 ){
27740       /* Run commands that follow -cmd first and separately from commands
27741       ** that simply appear on the command-line.  This seems goofy.  It would
27742       ** be better if all commands ran in the order that they appear.  But
27743       ** we retain the goofy behavior for historical compatibility. */
27744       if( i==argc-1 ) break;
27745       z = cmdline_option_value(argc,argv,++i);
27746       if( z[0]=='.' ){
27747         rc = do_meta_command(z, &data);
27748         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
27749       }else{
27750         open_db(&data, 0);
27751         rc = shell_exec(&data, z, &zErrMsg);
27752         if( zErrMsg!=0 ){
27753           utf8_printf(stderr,"Error: %s\n", zErrMsg);
27754           if( bail_on_error ) return rc!=0 ? rc : 1;
27755         }else if( rc!=0 ){
27756           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
27757           if( bail_on_error ) return rc;
27758         }
27759       }
27760 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27761     }else if( cli_strncmp(z, "-A", 2)==0 ){
27762       if( nCmd>0 ){
27763         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
27764                             " with \"%s\"\n", z);
27765         return 1;
27766       }
27767       open_db(&data, OPEN_DB_ZIPFILE);
27768       if( z[2] ){
27769         argv[i] = &z[2];
27770         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
27771       }else{
27772         arDotCommand(&data, 1, argv+i, argc-i);
27773       }
27774       readStdin = 0;
27775       break;
27776 #endif
27777     }else if( cli_strcmp(z,"-safe")==0 ){
27778       data.bSafeMode = data.bSafeModePersist = 1;
27779     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
27780       /* Acted upon in first pass. */
27781     }else{
27782       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
27783       raw_printf(stderr,"Use -help for a list of options.\n");
27784       return 1;
27785     }
27786     data.cMode = data.mode;
27787   }
27788 #if SHELL_WIN_UTF8_OPT
27789   if( console_utf8 && stdin_is_interactive ){
27790     console_prepare();
27791   }else{
27792     setBinaryMode(stdin, 0);
27793     console_utf8 = 0;
27794   }
27795 #endif
27796 
27797   if( !readStdin ){
27798     /* Run all arguments that do not begin with '-' as if they were separate
27799     ** command-line inputs, except for the argToSkip argument which contains
27800     ** the database filename.
27801     */
27802     for(i=0; i<nCmd; i++){
27803       if( azCmd[i][0]=='.' ){
27804         rc = do_meta_command(azCmd[i], &data);
27805         if( rc ){
27806           free(azCmd);
27807           return rc==2 ? 0 : rc;
27808         }
27809       }else{
27810         open_db(&data, 0);
27811         echo_group_input(&data, azCmd[i]);
27812         rc = shell_exec(&data, azCmd[i], &zErrMsg);
27813         if( zErrMsg || rc ){
27814           if( zErrMsg!=0 ){
27815             utf8_printf(stderr,"Error: %s\n", zErrMsg);
27816           }else{
27817             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
27818           }
27819           sqlite3_free(zErrMsg);
27820           free(azCmd);
27821           return rc!=0 ? rc : 1;
27822         }
27823       }
27824     }
27825   }else{
27826     /* Run commands received from standard input
27827     */
27828     if( stdin_is_interactive ){
27829       char *zHome;
27830       char *zHistory;
27831       int nHistory;
27832       printf(
27833         "SQLite version %s %.19s\n" /*extra-version-info*/
27834         "Enter \".help\" for usage hints.\n",
27835         sqlite3_libversion(), sqlite3_sourceid()
27836       );
27837       if( warnInmemoryDb ){
27838         printf("Connected to a ");
27839         printBold("transient in-memory database");
27840         printf(".\nUse \".open FILENAME\" to reopen on a "
27841                "persistent database.\n");
27842       }
27843       zHistory = getenv("SQLITE_HISTORY");
27844       if( zHistory ){
27845         zHistory = strdup(zHistory);
27846       }else if( (zHome = find_home_dir(0))!=0 ){
27847         nHistory = strlen30(zHome) + 20;
27848         if( (zHistory = malloc(nHistory))!=0 ){
27849           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
27850         }
27851       }
27852       if( zHistory ){ shell_read_history(zHistory); }
27853 #if HAVE_READLINE || HAVE_EDITLINE
27854       rl_attempted_completion_function = readline_completion;
27855 #elif HAVE_LINENOISE
27856       linenoiseSetCompletionCallback(linenoise_completion);
27857 #endif
27858       data.in = 0;
27859       rc = process_input(&data);
27860       if( zHistory ){
27861         shell_stifle_history(2000);
27862         shell_write_history(zHistory);
27863         free(zHistory);
27864       }
27865     }else{
27866       data.in = stdin;
27867       rc = process_input(&data);
27868     }
27869   }
27870 #ifndef SQLITE_SHELL_FIDDLE
27871   /* In WASM mode we have to leave the db state in place so that
27872   ** client code can "push" SQL into it after this call returns. */
27873   free(azCmd);
27874   set_table_name(&data, 0);
27875   if( data.db ){
27876     session_close_all(&data, -1);
27877     close_db(data.db);
27878   }
27879   for(i=0; i<ArraySize(data.aAuxDb); i++){
27880     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
27881     if( data.aAuxDb[i].db ){
27882       session_close_all(&data, i);
27883       close_db(data.aAuxDb[i].db);
27884     }
27885   }
27886   find_home_dir(1);
27887   output_reset(&data);
27888   data.doXdgOpen = 0;
27889   clearTempFile(&data);
27890 #if !SQLITE_SHELL_IS_UTF8
27891   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
27892   free(argvToFree);
27893 #endif
27894   free(data.colWidth);
27895   free(data.zNonce);
27896   /* Clear the global data structure so that valgrind will detect memory
27897   ** leaks */
27898   memset(&data, 0, sizeof(data));
27899 #ifdef SQLITE_DEBUG
27900   if( sqlite3_memory_used()>mem_main_enter ){
27901     utf8_printf(stderr, "Memory leaked: %u bytes\n",
27902                 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
27903   }
27904 #endif
27905 #endif /* !SQLITE_SHELL_FIDDLE */
27906   return rc;
27907 }
27908 
27909 
27910 #ifdef SQLITE_SHELL_FIDDLE
27911 /* Only for emcc experimentation purposes. */
27912 int fiddle_experiment(int a,int b){
27913   return a + b;
27914 }
27915 
27916 /*
27917 ** Returns a pointer to the current DB handle.
27918 */
27919 sqlite3 * fiddle_db_handle(){
27920   return globalDb;
27921 }
27922 
27923 /*
27924 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
27925 ** "main" is assumed. Returns 0 if no db with the given name is
27926 ** open.
27927 */
27928 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
27929   sqlite3_vfs * pVfs = 0;
27930   if(globalDb){
27931     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
27932                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
27933   }
27934   return pVfs;
27935 }
27936 
27937 /* Only for emcc experimentation purposes. */
27938 sqlite3 * fiddle_db_arg(sqlite3 *arg){
27939     printf("fiddle_db_arg(%p)\n", (const void*)arg);
27940     return arg;
27941 }
27942 
27943 /*
27944 ** Intended to be called via a SharedWorker() while a separate
27945 ** SharedWorker() (which manages the wasm module) is performing work
27946 ** which should be interrupted. Unfortunately, SharedWorker is not
27947 ** portable enough to make real use of.
27948 */
27949 void fiddle_interrupt(void){
27950   if( globalDb ) sqlite3_interrupt(globalDb);
27951 }
27952 
27953 /*
27954 ** Returns the filename of the given db name, assuming "main" if
27955 ** zDbName is NULL. Returns NULL if globalDb is not opened.
27956 */
27957 const char * fiddle_db_filename(const char * zDbName){
27958     return globalDb
27959       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
27960       : NULL;
27961 }
27962 
27963 /*
27964 ** Completely wipes out the contents of the currently-opened database
27965 ** but leaves its storage intact for reuse.
27966 */
27967 void fiddle_reset_db(void){
27968   if( globalDb ){
27969     int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
27970     if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
27971     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
27972   }
27973 }
27974 
27975 /*
27976 ** Uses the current database's VFS xRead to stream the db file's
27977 ** contents out to the given callback. The callback gets a single
27978 ** chunk of size n (its 2nd argument) on each call and must return 0
27979 ** on success, non-0 on error. This function returns 0 on success,
27980 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
27981 ** code from the callback. Note that this is not thread-friendly: it
27982 ** expects that it will be the only thread reading the db file and
27983 ** takes no measures to ensure that is the case.
27984 */
27985 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
27986   sqlite3_int64 nSize = 0;
27987   sqlite3_int64 nPos = 0;
27988   sqlite3_file * pFile = 0;
27989   unsigned char buf[1024 * 8];
27990   int nBuf = (int)sizeof(buf);
27991   int rc = shellState.db
27992     ? sqlite3_file_control(shellState.db, "main",
27993                            SQLITE_FCNTL_FILE_POINTER, &pFile)
27994     : SQLITE_NOTFOUND;
27995   if( rc ) return rc;
27996   rc = pFile->pMethods->xFileSize(pFile, &nSize);
27997   if( rc ) return rc;
27998   if(nSize % nBuf){
27999     /* DB size is not an even multiple of the buffer size. Reduce
28000     ** buffer size so that we do not unduly inflate the db size when
28001     ** exporting. */
28002     if(0 == nSize % 4096) nBuf = 4096;
28003     else if(0 == nSize % 2048) nBuf = 2048;
28004     else if(0 == nSize % 1024) nBuf = 1024;
28005     else nBuf = 512;
28006   }
28007   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
28008     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
28009     if(SQLITE_IOERR_SHORT_READ == rc){
28010       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
28011     }
28012     if( 0==rc ) rc = xCallback(buf, nBuf);
28013   }
28014   return rc;
28015 }
28016 
28017 /*
28018 ** Trivial exportable function for emscripten. It processes zSql as if
28019 ** it were input to the sqlite3 shell and redirects all output to the
28020 ** wasm binding. fiddle_main() must have been called before this
28021 ** is called, or results are undefined.
28022 */
28023 void fiddle_exec(const char * zSql){
28024   if(zSql && *zSql){
28025     if('.'==*zSql) puts(zSql);
28026     shellState.wasm.zInput = zSql;
28027     shellState.wasm.zPos = zSql;
28028     process_input(&shellState);
28029     shellState.wasm.zInput = shellState.wasm.zPos = 0;
28030   }
28031 }
28032 #endif /* SQLITE_SHELL_FIDDLE */
28033