xref: /freebsd/contrib/sqlite3/shell.c (revision d411c1d6)
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 typedef unsigned int u32;
38 typedef unsigned short int u16;
39 
40 /*
41 ** Optionally #include a user-defined header, whereby compilation options
42 ** may be set prior to where they take effect, but after platform setup.
43 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
44 ** file. Note that this macro has a like effect on sqlite3.c compilation.
45 */
46 # define SHELL_STRINGIFY_(f) #f
47 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
48 #ifdef SQLITE_CUSTOM_INCLUDE
49 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
50 #endif
51 
52 /*
53 ** Determine if we are dealing with WinRT, which provides only a subset of
54 ** the full Win32 API.
55 */
56 #if !defined(SQLITE_OS_WINRT)
57 # define SQLITE_OS_WINRT 0
58 #endif
59 
60 /*
61 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
62 ** somewhat for use as a WASM module in a web browser. This flag
63 ** should only be used when building the "fiddle" web application, as
64 ** the browser-mode build has much different user input requirements
65 ** and this build mode rewires the user input subsystem to account for
66 ** that.
67 */
68 
69 /*
70 ** Warning pragmas copied from msvc.h in the core.
71 */
72 #if defined(_MSC_VER)
73 #pragma warning(disable : 4054)
74 #pragma warning(disable : 4055)
75 #pragma warning(disable : 4100)
76 #pragma warning(disable : 4127)
77 #pragma warning(disable : 4130)
78 #pragma warning(disable : 4152)
79 #pragma warning(disable : 4189)
80 #pragma warning(disable : 4206)
81 #pragma warning(disable : 4210)
82 #pragma warning(disable : 4232)
83 #pragma warning(disable : 4244)
84 #pragma warning(disable : 4305)
85 #pragma warning(disable : 4306)
86 #pragma warning(disable : 4702)
87 #pragma warning(disable : 4706)
88 #endif /* defined(_MSC_VER) */
89 
90 /*
91 ** No support for loadable extensions in VxWorks.
92 */
93 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
94 # define SQLITE_OMIT_LOAD_EXTENSION 1
95 #endif
96 
97 /*
98 ** Enable large-file support for fopen() and friends on unix.
99 */
100 #ifndef SQLITE_DISABLE_LFS
101 # define _LARGE_FILE       1
102 # ifndef _FILE_OFFSET_BITS
103 #   define _FILE_OFFSET_BITS 64
104 # endif
105 # define _LARGEFILE_SOURCE 1
106 #endif
107 
108 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
109 /*
110 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
111 ** to expose strdup().
112 */
113 # define _POSIX_SOURCE
114 #endif
115 
116 #include <stdlib.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include <assert.h>
120 #include "sqlite3.h"
121 typedef sqlite3_int64 i64;
122 typedef sqlite3_uint64 u64;
123 typedef unsigned char u8;
124 #if SQLITE_USER_AUTHENTICATION
125 # include "sqlite3userauth.h"
126 #endif
127 #include <ctype.h>
128 #include <stdarg.h>
129 
130 #if !defined(_WIN32) && !defined(WIN32)
131 # include <signal.h>
132 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
133 #  include <pwd.h>
134 # endif
135 #endif
136 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
137 # include <unistd.h>
138 # include <dirent.h>
139 # define GETPID getpid
140 # if defined(__MINGW32__)
141 #  define DIRENT dirent
142 #  ifndef S_ISLNK
143 #   define S_ISLNK(mode) (0)
144 #  endif
145 # endif
146 #else
147 # define GETPID (int)GetCurrentProcessId
148 #endif
149 #include <sys/types.h>
150 #include <sys/stat.h>
151 
152 #if HAVE_READLINE
153 # include <readline/readline.h>
154 # include <readline/history.h>
155 #endif
156 
157 #if HAVE_EDITLINE
158 # include <editline/readline.h>
159 #endif
160 
161 #if HAVE_EDITLINE || HAVE_READLINE
162 
163 # define shell_add_history(X) add_history(X)
164 # define shell_read_history(X) read_history(X)
165 # define shell_write_history(X) write_history(X)
166 # define shell_stifle_history(X) stifle_history(X)
167 # define shell_readline(X) readline(X)
168 
169 #elif HAVE_LINENOISE
170 
171 # include "linenoise.h"
172 # define shell_add_history(X) linenoiseHistoryAdd(X)
173 # define shell_read_history(X) linenoiseHistoryLoad(X)
174 # define shell_write_history(X) linenoiseHistorySave(X)
175 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
176 # define shell_readline(X) linenoise(X)
177 
178 #else
179 
180 # define shell_read_history(X)
181 # define shell_write_history(X)
182 # define shell_stifle_history(X)
183 
184 # define SHELL_USE_LOCAL_GETLINE 1
185 #endif
186 
187 #ifndef deliberate_fall_through
188 /* Quiet some compilers about some of our intentional code. */
189 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
190 #  define deliberate_fall_through __attribute__((fallthrough));
191 # else
192 #  define deliberate_fall_through
193 # endif
194 #endif
195 
196 #if defined(_WIN32) || defined(WIN32)
197 # if SQLITE_OS_WINRT
198 #  define SQLITE_OMIT_POPEN 1
199 # else
200 #  include <io.h>
201 #  include <fcntl.h>
202 #  define isatty(h) _isatty(h)
203 #  ifndef access
204 #   define access(f,m) _access((f),(m))
205 #  endif
206 #  ifndef unlink
207 #   define unlink _unlink
208 #  endif
209 #  ifndef strdup
210 #   define strdup _strdup
211 #  endif
212 #  undef popen
213 #  define popen _popen
214 #  undef pclose
215 #  define pclose _pclose
216 # endif
217 #else
218  /* Make sure isatty() has a prototype. */
219  extern int isatty(int);
220 
221 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
222   /* popen and pclose are not C89 functions and so are
223   ** sometimes omitted from the <stdio.h> header */
224    extern FILE *popen(const char*,const char*);
225    extern int pclose(FILE*);
226 # else
227 #  define SQLITE_OMIT_POPEN 1
228 # endif
229 #endif
230 
231 #if defined(_WIN32_WCE)
232 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
233  * thus we always assume that we have a console. That can be
234  * overridden with the -batch command line option.
235  */
236 #define isatty(x) 1
237 #endif
238 
239 /* ctype macros that work with signed characters */
240 #define IsSpace(X)  isspace((unsigned char)X)
241 #define IsDigit(X)  isdigit((unsigned char)X)
242 #define ToLower(X)  (char)tolower((unsigned char)X)
243 
244 #if defined(_WIN32) || defined(WIN32)
245 #if SQLITE_OS_WINRT
246 #include <intrin.h>
247 #endif
248 #include <windows.h>
249 
250 /* string conversion routines only needed on Win32 */
251 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
252 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
253 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
254 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
255 #endif
256 
257 /* On Windows, we normally run with output mode of TEXT so that \n characters
258 ** are automatically translated into \r\n.  However, this behavior needs
259 ** to be disabled in some cases (ex: when generating CSV output and when
260 ** rendering quoted strings that contain \n characters).  The following
261 ** routines take care of that.
262 */
263 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
264 static void setBinaryMode(FILE *file, int isOutput){
265   if( isOutput ) fflush(file);
266   _setmode(_fileno(file), _O_BINARY);
267 }
268 static void setTextMode(FILE *file, int isOutput){
269   if( isOutput ) fflush(file);
270   _setmode(_fileno(file), _O_TEXT);
271 }
272 #else
273 # define setBinaryMode(X,Y)
274 # define setTextMode(X,Y)
275 #endif
276 
277 /* True if the timer is enabled */
278 static int enableTimer = 0;
279 
280 /* A version of strcmp() that works with NULL values */
281 static int cli_strcmp(const char *a, const char *b){
282   if( a==0 ) a = "";
283   if( b==0 ) b = "";
284   return strcmp(a,b);
285 }
286 static int cli_strncmp(const char *a, const char *b, size_t n){
287   if( a==0 ) a = "";
288   if( b==0 ) b = "";
289   return strncmp(a,b,n);
290 }
291 
292 /* Return the current wall-clock time */
293 static sqlite3_int64 timeOfDay(void){
294   static sqlite3_vfs *clockVfs = 0;
295   sqlite3_int64 t;
296   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
297   if( clockVfs==0 ) return 0;  /* Never actually happens */
298   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
299     clockVfs->xCurrentTimeInt64(clockVfs, &t);
300   }else{
301     double r;
302     clockVfs->xCurrentTime(clockVfs, &r);
303     t = (sqlite3_int64)(r*86400000.0);
304   }
305   return t;
306 }
307 
308 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
309 #include <sys/time.h>
310 #include <sys/resource.h>
311 
312 /* VxWorks does not support getrusage() as far as we can determine */
313 #if defined(_WRS_KERNEL) || defined(__RTP__)
314 struct rusage {
315   struct timeval ru_utime; /* user CPU time used */
316   struct timeval ru_stime; /* system CPU time used */
317 };
318 #define getrusage(A,B) memset(B,0,sizeof(*B))
319 #endif
320 
321 /* Saved resource information for the beginning of an operation */
322 static struct rusage sBegin;  /* CPU time at start */
323 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
324 
325 /*
326 ** Begin timing an operation
327 */
328 static void beginTimer(void){
329   if( enableTimer ){
330     getrusage(RUSAGE_SELF, &sBegin);
331     iBegin = timeOfDay();
332   }
333 }
334 
335 /* Return the difference of two time_structs in seconds */
336 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
337   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
338          (double)(pEnd->tv_sec - pStart->tv_sec);
339 }
340 
341 /*
342 ** Print the timing results.
343 */
344 static void endTimer(void){
345   if( enableTimer ){
346     sqlite3_int64 iEnd = timeOfDay();
347     struct rusage sEnd;
348     getrusage(RUSAGE_SELF, &sEnd);
349     printf("Run Time: real %.3f user %f sys %f\n",
350        (iEnd - iBegin)*0.001,
351        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
352        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
353   }
354 }
355 
356 #define BEGIN_TIMER beginTimer()
357 #define END_TIMER endTimer()
358 #define HAS_TIMER 1
359 
360 #elif (defined(_WIN32) || defined(WIN32))
361 
362 /* Saved resource information for the beginning of an operation */
363 static HANDLE hProcess;
364 static FILETIME ftKernelBegin;
365 static FILETIME ftUserBegin;
366 static sqlite3_int64 ftWallBegin;
367 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
368                                     LPFILETIME, LPFILETIME);
369 static GETPROCTIMES getProcessTimesAddr = NULL;
370 
371 /*
372 ** Check to see if we have timer support.  Return 1 if necessary
373 ** support found (or found previously).
374 */
375 static int hasTimer(void){
376   if( getProcessTimesAddr ){
377     return 1;
378   } else {
379 #if !SQLITE_OS_WINRT
380     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
381     ** versions. See if the version we are running on has it, and if it
382     ** does, save off a pointer to it and the current process handle.
383     */
384     hProcess = GetCurrentProcess();
385     if( hProcess ){
386       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
387       if( NULL != hinstLib ){
388         getProcessTimesAddr =
389             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
390         if( NULL != getProcessTimesAddr ){
391           return 1;
392         }
393         FreeLibrary(hinstLib);
394       }
395     }
396 #endif
397   }
398   return 0;
399 }
400 
401 /*
402 ** Begin timing an operation
403 */
404 static void beginTimer(void){
405   if( enableTimer && getProcessTimesAddr ){
406     FILETIME ftCreation, ftExit;
407     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
408                         &ftKernelBegin,&ftUserBegin);
409     ftWallBegin = timeOfDay();
410   }
411 }
412 
413 /* Return the difference of two FILETIME structs in seconds */
414 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
415   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
416   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
417   return (double) ((i64End - i64Start) / 10000000.0);
418 }
419 
420 /*
421 ** Print the timing results.
422 */
423 static void endTimer(void){
424   if( enableTimer && getProcessTimesAddr){
425     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
426     sqlite3_int64 ftWallEnd = timeOfDay();
427     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
428     printf("Run Time: real %.3f user %f sys %f\n",
429        (ftWallEnd - ftWallBegin)*0.001,
430        timeDiff(&ftUserBegin, &ftUserEnd),
431        timeDiff(&ftKernelBegin, &ftKernelEnd));
432   }
433 }
434 
435 #define BEGIN_TIMER beginTimer()
436 #define END_TIMER endTimer()
437 #define HAS_TIMER hasTimer()
438 
439 #else
440 #define BEGIN_TIMER
441 #define END_TIMER
442 #define HAS_TIMER 0
443 #endif
444 
445 /*
446 ** Used to prevent warnings about unused parameters
447 */
448 #define UNUSED_PARAMETER(x) (void)(x)
449 
450 /*
451 ** Number of elements in an array
452 */
453 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
454 
455 /*
456 ** If the following flag is set, then command execution stops
457 ** at an error if we are not interactive.
458 */
459 static int bail_on_error = 0;
460 
461 /*
462 ** Threat stdin as an interactive input if the following variable
463 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
464 */
465 static int stdin_is_interactive = 1;
466 
467 /*
468 ** On Windows systems we have to know if standard output is a console
469 ** in order to translate UTF-8 into MBCS.  The following variable is
470 ** true if translation is required.
471 */
472 static int stdout_is_console = 1;
473 
474 /*
475 ** The following is the open SQLite database.  We make a pointer
476 ** to this database a static variable so that it can be accessed
477 ** by the SIGINT handler to interrupt database processing.
478 */
479 static sqlite3 *globalDb = 0;
480 
481 /*
482 ** True if an interrupt (Control-C) has been received.
483 */
484 static volatile int seenInterrupt = 0;
485 
486 /*
487 ** This is the name of our program. It is set in main(), used
488 ** in a number of other places, mostly for error messages.
489 */
490 static char *Argv0;
491 
492 /*
493 ** Prompt strings. Initialized in main. Settable with
494 **   .prompt main continue
495 */
496 #define PROMPT_LEN_MAX 20
497 /* First line prompt.   default: "sqlite> " */
498 static char mainPrompt[PROMPT_LEN_MAX];
499 /* Continuation prompt. default: "   ...> " */
500 static char continuePrompt[PROMPT_LEN_MAX];
501 
502 /* This is variant of the standard-library strncpy() routine with the
503 ** one change that the destination string is always zero-terminated, even
504 ** if there is no zero-terminator in the first n-1 characters of the source
505 ** string.
506 */
507 static char *shell_strncpy(char *dest, const char *src, size_t n){
508   size_t i;
509   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
510   dest[i] = 0;
511   return dest;
512 }
513 
514 /*
515 ** Optionally disable dynamic continuation prompt.
516 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
517 ** or open parentheses level if non-zero, or continuation prompt as set.
518 ** This facility interacts with the scanner and process_input() where the
519 ** below 5 macros are used.
520 */
521 #ifdef SQLITE_OMIT_DYNAPROMPT
522 # define CONTINUATION_PROMPT continuePrompt
523 # define CONTINUE_PROMPT_RESET
524 # define CONTINUE_PROMPT_AWAITS(p,s)
525 # define CONTINUE_PROMPT_AWAITC(p,c)
526 # define CONTINUE_PAREN_INCR(p,n)
527 # define CONTINUE_PROMPT_PSTATE 0
528 typedef void *t_NoDynaPrompt;
529 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
530 #else
531 # define CONTINUATION_PROMPT dynamicContinuePrompt()
532 # define CONTINUE_PROMPT_RESET \
533   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
534 # define CONTINUE_PROMPT_AWAITS(p,s) \
535   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
536 # define CONTINUE_PROMPT_AWAITC(p,c) \
537   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
538 # define CONTINUE_PAREN_INCR(p,n) \
539   if(p && stdin_is_interactive) (trackParenLevel(p,n))
540 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
541 typedef struct DynaPrompt *t_DynaPromptRef;
542 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
543 
544 static struct DynaPrompt {
545   char dynamicPrompt[PROMPT_LEN_MAX];
546   char acAwait[2];
547   int inParenLevel;
548   char *zScannerAwaits;
549 } dynPrompt = { {0}, {0}, 0, 0 };
550 
551 /* Record parenthesis nesting level change, or force level to 0. */
552 static void trackParenLevel(struct DynaPrompt *p, int ni){
553   p->inParenLevel += ni;
554   if( ni==0 ) p->inParenLevel = 0;
555   p->zScannerAwaits = 0;
556 }
557 
558 /* Record that a lexeme is opened, or closed with args==0. */
559 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
560   if( s!=0 || c==0 ){
561     p->zScannerAwaits = s;
562     p->acAwait[0] = 0;
563   }else{
564     p->acAwait[0] = c;
565     p->zScannerAwaits = p->acAwait;
566   }
567 }
568 
569 /* Upon demand, derive the continuation prompt to display. */
570 static char *dynamicContinuePrompt(void){
571   if( continuePrompt[0]==0
572       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
573     return continuePrompt;
574   }else{
575     if( dynPrompt.zScannerAwaits ){
576       size_t ncp = strlen(continuePrompt);
577       size_t ndp = strlen(dynPrompt.zScannerAwaits);
578       if( ndp > ncp-3 ) return continuePrompt;
579       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
580       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
581       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
582               PROMPT_LEN_MAX-4);
583     }else{
584       if( dynPrompt.inParenLevel>9 ){
585         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
586       }else if( dynPrompt.inParenLevel<0 ){
587         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
588       }else{
589         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
590         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
591       }
592       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, PROMPT_LEN_MAX-4);
593     }
594   }
595   return dynPrompt.dynamicPrompt;
596 }
597 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
598 
599 /*
600 ** Render output like fprintf().  Except, if the output is going to the
601 ** console and if this is running on a Windows machine, translate the
602 ** output from UTF-8 into MBCS.
603 */
604 #if defined(_WIN32) || defined(WIN32)
605 void utf8_printf(FILE *out, const char *zFormat, ...){
606   va_list ap;
607   va_start(ap, zFormat);
608   if( stdout_is_console && (out==stdout || out==stderr) ){
609     char *z1 = sqlite3_vmprintf(zFormat, ap);
610     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
611     sqlite3_free(z1);
612     fputs(z2, out);
613     sqlite3_free(z2);
614   }else{
615     vfprintf(out, zFormat, ap);
616   }
617   va_end(ap);
618 }
619 #elif !defined(utf8_printf)
620 # define utf8_printf fprintf
621 #endif
622 
623 /*
624 ** Render output like fprintf().  This should not be used on anything that
625 ** includes string formatting (e.g. "%s").
626 */
627 #if !defined(raw_printf)
628 # define raw_printf fprintf
629 #endif
630 
631 /* Indicate out-of-memory and exit. */
632 static void shell_out_of_memory(void){
633   raw_printf(stderr,"Error: out of memory\n");
634   exit(1);
635 }
636 
637 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
638 ** out-of-memory error.
639 */
640 static void shell_check_oom(void *p){
641   if( p==0 ) shell_out_of_memory();
642 }
643 
644 /*
645 ** Write I/O traces to the following stream.
646 */
647 #ifdef SQLITE_ENABLE_IOTRACE
648 static FILE *iotrace = 0;
649 #endif
650 
651 /*
652 ** This routine works like printf in that its first argument is a
653 ** format string and subsequent arguments are values to be substituted
654 ** in place of % fields.  The result of formatting this string
655 ** is written to iotrace.
656 */
657 #ifdef SQLITE_ENABLE_IOTRACE
658 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
659   va_list ap;
660   char *z;
661   if( iotrace==0 ) return;
662   va_start(ap, zFormat);
663   z = sqlite3_vmprintf(zFormat, ap);
664   va_end(ap);
665   utf8_printf(iotrace, "%s", z);
666   sqlite3_free(z);
667 }
668 #endif
669 
670 /*
671 ** Output string zUtf to stream pOut as w characters.  If w is negative,
672 ** then right-justify the text.  W is the width in UTF-8 characters, not
673 ** in bytes.  This is different from the %*.*s specification in printf
674 ** since with %*.*s the width is measured in bytes, not characters.
675 */
676 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
677   int i;
678   int n;
679   int aw = w<0 ? -w : w;
680   if( zUtf==0 ) zUtf = "";
681   for(i=n=0; zUtf[i]; i++){
682     if( (zUtf[i]&0xc0)!=0x80 ){
683       n++;
684       if( n==aw ){
685         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
686         break;
687       }
688     }
689   }
690   if( n>=aw ){
691     utf8_printf(pOut, "%.*s", i, zUtf);
692   }else if( w<0 ){
693     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
694   }else{
695     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
696   }
697 }
698 
699 
700 /*
701 ** Determines if a string is a number of not.
702 */
703 static int isNumber(const char *z, int *realnum){
704   if( *z=='-' || *z=='+' ) z++;
705   if( !IsDigit(*z) ){
706     return 0;
707   }
708   z++;
709   if( realnum ) *realnum = 0;
710   while( IsDigit(*z) ){ z++; }
711   if( *z=='.' ){
712     z++;
713     if( !IsDigit(*z) ) return 0;
714     while( IsDigit(*z) ){ z++; }
715     if( realnum ) *realnum = 1;
716   }
717   if( *z=='e' || *z=='E' ){
718     z++;
719     if( *z=='+' || *z=='-' ) z++;
720     if( !IsDigit(*z) ) return 0;
721     while( IsDigit(*z) ){ z++; }
722     if( realnum ) *realnum = 1;
723   }
724   return *z==0;
725 }
726 
727 /*
728 ** Compute a string length that is limited to what can be stored in
729 ** lower 30 bits of a 32-bit signed integer.
730 */
731 static int strlen30(const char *z){
732   const char *z2 = z;
733   while( *z2 ){ z2++; }
734   return 0x3fffffff & (int)(z2 - z);
735 }
736 
737 /*
738 ** Return the length of a string in characters.  Multibyte UTF8 characters
739 ** count as a single character.
740 */
741 static int strlenChar(const char *z){
742   int n = 0;
743   while( *z ){
744     if( (0xc0&*(z++))!=0x80 ) n++;
745   }
746   return n;
747 }
748 
749 /*
750 ** Return open FILE * if zFile exists, can be opened for read
751 ** and is an ordinary file or a character stream source.
752 ** Otherwise return 0.
753 */
754 static FILE * openChrSource(const char *zFile){
755 #ifdef _WIN32
756   struct _stat x = {0};
757 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
758   /* On Windows, open first, then check the stream nature. This order
759   ** is necessary because _stat() and sibs, when checking a named pipe,
760   ** effectively break the pipe as its supplier sees it. */
761   FILE *rv = fopen(zFile, "rb");
762   if( rv==0 ) return 0;
763   if( _fstat(_fileno(rv), &x) != 0
764       || !STAT_CHR_SRC(x.st_mode)){
765     fclose(rv);
766     rv = 0;
767   }
768   return rv;
769 #else
770   struct stat x = {0};
771   int rc = stat(zFile, &x);
772 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
773   if( rc!=0 ) return 0;
774   if( STAT_CHR_SRC(x.st_mode) ){
775     return fopen(zFile, "rb");
776   }else{
777     return 0;
778   }
779 #endif
780 #undef STAT_CHR_SRC
781 }
782 
783 /*
784 ** This routine reads a line of text from FILE in, stores
785 ** the text in memory obtained from malloc() and returns a pointer
786 ** to the text.  NULL is returned at end of file, or if malloc()
787 ** fails.
788 **
789 ** If zLine is not NULL then it is a malloced buffer returned from
790 ** a previous call to this routine that may be reused.
791 */
792 static char *local_getline(char *zLine, FILE *in){
793   int nLine = zLine==0 ? 0 : 100;
794   int n = 0;
795 
796   while( 1 ){
797     if( n+100>nLine ){
798       nLine = nLine*2 + 100;
799       zLine = realloc(zLine, nLine);
800       shell_check_oom(zLine);
801     }
802     if( fgets(&zLine[n], nLine - n, in)==0 ){
803       if( n==0 ){
804         free(zLine);
805         return 0;
806       }
807       zLine[n] = 0;
808       break;
809     }
810     while( zLine[n] ) n++;
811     if( n>0 && zLine[n-1]=='\n' ){
812       n--;
813       if( n>0 && zLine[n-1]=='\r' ) n--;
814       zLine[n] = 0;
815       break;
816     }
817   }
818 #if defined(_WIN32) || defined(WIN32)
819   /* For interactive input on Windows systems, translate the
820   ** multi-byte characterset characters into UTF-8. */
821   if( stdin_is_interactive && in==stdin ){
822     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
823     if( zTrans ){
824       i64 nTrans = strlen(zTrans)+1;
825       if( nTrans>nLine ){
826         zLine = realloc(zLine, nTrans);
827         shell_check_oom(zLine);
828       }
829       memcpy(zLine, zTrans, nTrans);
830       sqlite3_free(zTrans);
831     }
832   }
833 #endif /* defined(_WIN32) || defined(WIN32) */
834   return zLine;
835 }
836 
837 /*
838 ** Retrieve a single line of input text.
839 **
840 ** If in==0 then read from standard input and prompt before each line.
841 ** If isContinuation is true, then a continuation prompt is appropriate.
842 ** If isContinuation is zero, then the main prompt should be used.
843 **
844 ** If zPrior is not NULL then it is a buffer from a prior call to this
845 ** routine that can be reused.
846 **
847 ** The result is stored in space obtained from malloc() and must either
848 ** be freed by the caller or else passed back into this routine via the
849 ** zPrior argument for reuse.
850 */
851 #ifndef SQLITE_SHELL_FIDDLE
852 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
853   char *zPrompt;
854   char *zResult;
855   if( in!=0 ){
856     zResult = local_getline(zPrior, in);
857   }else{
858     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
859 #if SHELL_USE_LOCAL_GETLINE
860     printf("%s", zPrompt);
861     fflush(stdout);
862     zResult = local_getline(zPrior, stdin);
863 #else
864     free(zPrior);
865     zResult = shell_readline(zPrompt);
866     if( zResult && *zResult ) shell_add_history(zResult);
867 #endif
868   }
869   return zResult;
870 }
871 #endif /* !SQLITE_SHELL_FIDDLE */
872 
873 /*
874 ** Return the value of a hexadecimal digit.  Return -1 if the input
875 ** is not a hex digit.
876 */
877 static int hexDigitValue(char c){
878   if( c>='0' && c<='9' ) return c - '0';
879   if( c>='a' && c<='f' ) return c - 'a' + 10;
880   if( c>='A' && c<='F' ) return c - 'A' + 10;
881   return -1;
882 }
883 
884 /*
885 ** Interpret zArg as an integer value, possibly with suffixes.
886 */
887 static sqlite3_int64 integerValue(const char *zArg){
888   sqlite3_int64 v = 0;
889   static const struct { char *zSuffix; int iMult; } aMult[] = {
890     { "KiB", 1024 },
891     { "MiB", 1024*1024 },
892     { "GiB", 1024*1024*1024 },
893     { "KB",  1000 },
894     { "MB",  1000000 },
895     { "GB",  1000000000 },
896     { "K",   1000 },
897     { "M",   1000000 },
898     { "G",   1000000000 },
899   };
900   int i;
901   int isNeg = 0;
902   if( zArg[0]=='-' ){
903     isNeg = 1;
904     zArg++;
905   }else if( zArg[0]=='+' ){
906     zArg++;
907   }
908   if( zArg[0]=='0' && zArg[1]=='x' ){
909     int x;
910     zArg += 2;
911     while( (x = hexDigitValue(zArg[0]))>=0 ){
912       v = (v<<4) + x;
913       zArg++;
914     }
915   }else{
916     while( IsDigit(zArg[0]) ){
917       v = v*10 + zArg[0] - '0';
918       zArg++;
919     }
920   }
921   for(i=0; i<ArraySize(aMult); i++){
922     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
923       v *= aMult[i].iMult;
924       break;
925     }
926   }
927   return isNeg? -v : v;
928 }
929 
930 /*
931 ** A variable length string to which one can append text.
932 */
933 typedef struct ShellText ShellText;
934 struct ShellText {
935   char *z;
936   int n;
937   int nAlloc;
938 };
939 
940 /*
941 ** Initialize and destroy a ShellText object
942 */
943 static void initText(ShellText *p){
944   memset(p, 0, sizeof(*p));
945 }
946 static void freeText(ShellText *p){
947   free(p->z);
948   initText(p);
949 }
950 
951 /* zIn is either a pointer to a NULL-terminated string in memory obtained
952 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
953 ** added to zIn, and the result returned in memory obtained from malloc().
954 ** zIn, if it was not NULL, is freed.
955 **
956 ** If the third argument, quote, is not '\0', then it is used as a
957 ** quote character for zAppend.
958 */
959 static void appendText(ShellText *p, const char *zAppend, char quote){
960   i64 len;
961   i64 i;
962   i64 nAppend = strlen30(zAppend);
963 
964   len = nAppend+p->n+1;
965   if( quote ){
966     len += 2;
967     for(i=0; i<nAppend; i++){
968       if( zAppend[i]==quote ) len++;
969     }
970   }
971 
972   if( p->z==0 || p->n+len>=p->nAlloc ){
973     p->nAlloc = p->nAlloc*2 + len + 20;
974     p->z = realloc(p->z, p->nAlloc);
975     shell_check_oom(p->z);
976   }
977 
978   if( quote ){
979     char *zCsr = p->z+p->n;
980     *zCsr++ = quote;
981     for(i=0; i<nAppend; i++){
982       *zCsr++ = zAppend[i];
983       if( zAppend[i]==quote ) *zCsr++ = quote;
984     }
985     *zCsr++ = quote;
986     p->n = (int)(zCsr - p->z);
987     *zCsr = '\0';
988   }else{
989     memcpy(p->z+p->n, zAppend, nAppend);
990     p->n += nAppend;
991     p->z[p->n] = '\0';
992   }
993 }
994 
995 /*
996 ** Attempt to determine if identifier zName needs to be quoted, either
997 ** because it contains non-alphanumeric characters, or because it is an
998 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
999 ** that quoting is required.
1000 **
1001 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1002 */
1003 static char quoteChar(const char *zName){
1004   int i;
1005   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1006   for(i=0; zName[i]; i++){
1007     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1008   }
1009   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1010 }
1011 
1012 /*
1013 ** Construct a fake object name and column list to describe the structure
1014 ** of the view, virtual table, or table valued function zSchema.zName.
1015 */
1016 static char *shellFakeSchema(
1017   sqlite3 *db,            /* The database connection containing the vtab */
1018   const char *zSchema,    /* Schema of the database holding the vtab */
1019   const char *zName       /* The name of the virtual table */
1020 ){
1021   sqlite3_stmt *pStmt = 0;
1022   char *zSql;
1023   ShellText s;
1024   char cQuote;
1025   char *zDiv = "(";
1026   int nRow = 0;
1027 
1028   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1029                          zSchema ? zSchema : "main", zName);
1030   shell_check_oom(zSql);
1031   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1032   sqlite3_free(zSql);
1033   initText(&s);
1034   if( zSchema ){
1035     cQuote = quoteChar(zSchema);
1036     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1037     appendText(&s, zSchema, cQuote);
1038     appendText(&s, ".", 0);
1039   }
1040   cQuote = quoteChar(zName);
1041   appendText(&s, zName, cQuote);
1042   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1043     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1044     nRow++;
1045     appendText(&s, zDiv, 0);
1046     zDiv = ",";
1047     if( zCol==0 ) zCol = "";
1048     cQuote = quoteChar(zCol);
1049     appendText(&s, zCol, cQuote);
1050   }
1051   appendText(&s, ")", 0);
1052   sqlite3_finalize(pStmt);
1053   if( nRow==0 ){
1054     freeText(&s);
1055     s.z = 0;
1056   }
1057   return s.z;
1058 }
1059 
1060 /*
1061 ** SQL function:  shell_module_schema(X)
1062 **
1063 ** Return a fake schema for the table-valued function or eponymous virtual
1064 ** table X.
1065 */
1066 static void shellModuleSchema(
1067   sqlite3_context *pCtx,
1068   int nVal,
1069   sqlite3_value **apVal
1070 ){
1071   const char *zName;
1072   char *zFake;
1073   UNUSED_PARAMETER(nVal);
1074   zName = (const char*)sqlite3_value_text(apVal[0]);
1075   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1076   if( zFake ){
1077     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1078                         -1, sqlite3_free);
1079     free(zFake);
1080   }
1081 }
1082 
1083 /*
1084 ** SQL function:  shell_add_schema(S,X)
1085 **
1086 ** Add the schema name X to the CREATE statement in S and return the result.
1087 ** Examples:
1088 **
1089 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
1090 **
1091 ** Also works on
1092 **
1093 **    CREATE INDEX
1094 **    CREATE UNIQUE INDEX
1095 **    CREATE VIEW
1096 **    CREATE TRIGGER
1097 **    CREATE VIRTUAL TABLE
1098 **
1099 ** This UDF is used by the .schema command to insert the schema name of
1100 ** attached databases into the middle of the sqlite_schema.sql field.
1101 */
1102 static void shellAddSchemaName(
1103   sqlite3_context *pCtx,
1104   int nVal,
1105   sqlite3_value **apVal
1106 ){
1107   static const char *aPrefix[] = {
1108      "TABLE",
1109      "INDEX",
1110      "UNIQUE INDEX",
1111      "VIEW",
1112      "TRIGGER",
1113      "VIRTUAL TABLE"
1114   };
1115   int i = 0;
1116   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1117   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1118   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1119   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1120   UNUSED_PARAMETER(nVal);
1121   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1122     for(i=0; i<ArraySize(aPrefix); i++){
1123       int n = strlen30(aPrefix[i]);
1124       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1125         char *z = 0;
1126         char *zFake = 0;
1127         if( zSchema ){
1128           char cQuote = quoteChar(zSchema);
1129           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1130             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1131           }else{
1132             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1133           }
1134         }
1135         if( zName
1136          && aPrefix[i][0]=='V'
1137          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1138         ){
1139           if( z==0 ){
1140             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1141           }else{
1142             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1143           }
1144           free(zFake);
1145         }
1146         if( z ){
1147           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1148           return;
1149         }
1150       }
1151     }
1152   }
1153   sqlite3_result_value(pCtx, apVal[0]);
1154 }
1155 
1156 /*
1157 ** The source code for several run-time loadable extensions is inserted
1158 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1159 ** code, we need to override some macros to make the included program code
1160 ** work here in the middle of this regular program.
1161 */
1162 #define SQLITE_EXTENSION_INIT1
1163 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1164 
1165 #if defined(_WIN32) && defined(_MSC_VER)
1166 /************************* Begin test_windirent.h ******************/
1167 /*
1168 ** 2015 November 30
1169 **
1170 ** The author disclaims copyright to this source code.  In place of
1171 ** a legal notice, here is a blessing:
1172 **
1173 **    May you do good and not evil.
1174 **    May you find forgiveness for yourself and forgive others.
1175 **    May you share freely, never taking more than you give.
1176 **
1177 *************************************************************************
1178 ** This file contains declarations for most of the opendir() family of
1179 ** POSIX functions on Win32 using the MSVCRT.
1180 */
1181 
1182 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1183 #define SQLITE_WINDIRENT_H
1184 
1185 /*
1186 ** We need several data types from the Windows SDK header.
1187 */
1188 
1189 #ifndef WIN32_LEAN_AND_MEAN
1190 #define WIN32_LEAN_AND_MEAN
1191 #endif
1192 
1193 #include "windows.h"
1194 
1195 /*
1196 ** We need several support functions from the SQLite core.
1197 */
1198 
1199 /* #include "sqlite3.h" */
1200 
1201 /*
1202 ** We need several things from the ANSI and MSVCRT headers.
1203 */
1204 
1205 #include <stdio.h>
1206 #include <stdlib.h>
1207 #include <errno.h>
1208 #include <io.h>
1209 #include <limits.h>
1210 #include <sys/types.h>
1211 #include <sys/stat.h>
1212 
1213 /*
1214 ** We may need several defines that should have been in "sys/stat.h".
1215 */
1216 
1217 #ifndef S_ISREG
1218 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1219 #endif
1220 
1221 #ifndef S_ISDIR
1222 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1223 #endif
1224 
1225 #ifndef S_ISLNK
1226 #define S_ISLNK(mode) (0)
1227 #endif
1228 
1229 /*
1230 ** We may need to provide the "mode_t" type.
1231 */
1232 
1233 #ifndef MODE_T_DEFINED
1234   #define MODE_T_DEFINED
1235   typedef unsigned short mode_t;
1236 #endif
1237 
1238 /*
1239 ** We may need to provide the "ino_t" type.
1240 */
1241 
1242 #ifndef INO_T_DEFINED
1243   #define INO_T_DEFINED
1244   typedef unsigned short ino_t;
1245 #endif
1246 
1247 /*
1248 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1249 */
1250 
1251 #ifndef NAME_MAX
1252 #  ifdef FILENAME_MAX
1253 #    define NAME_MAX (FILENAME_MAX)
1254 #  else
1255 #    define NAME_MAX (260)
1256 #  endif
1257 #endif
1258 
1259 /*
1260 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1261 */
1262 
1263 #ifndef NULL_INTPTR_T
1264 #  define NULL_INTPTR_T ((intptr_t)(0))
1265 #endif
1266 
1267 #ifndef BAD_INTPTR_T
1268 #  define BAD_INTPTR_T ((intptr_t)(-1))
1269 #endif
1270 
1271 /*
1272 ** We need to provide the necessary structures and related types.
1273 */
1274 
1275 #ifndef DIRENT_DEFINED
1276 #define DIRENT_DEFINED
1277 typedef struct DIRENT DIRENT;
1278 typedef DIRENT *LPDIRENT;
1279 struct DIRENT {
1280   ino_t d_ino;               /* Sequence number, do not use. */
1281   unsigned d_attributes;     /* Win32 file attributes. */
1282   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1283 };
1284 #endif
1285 
1286 #ifndef DIR_DEFINED
1287 #define DIR_DEFINED
1288 typedef struct DIR DIR;
1289 typedef DIR *LPDIR;
1290 struct DIR {
1291   intptr_t d_handle; /* Value returned by "_findfirst". */
1292   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1293   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1294 };
1295 #endif
1296 
1297 /*
1298 ** Provide a macro, for use by the implementation, to determine if a
1299 ** particular directory entry should be skipped over when searching for
1300 ** the next directory entry that should be returned by the readdir() or
1301 ** readdir_r() functions.
1302 */
1303 
1304 #ifndef is_filtered
1305 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1306 #endif
1307 
1308 /*
1309 ** Provide the function prototype for the POSIX compatiable getenv()
1310 ** function.  This function is not thread-safe.
1311 */
1312 
1313 extern const char *windirent_getenv(const char *name);
1314 
1315 /*
1316 ** Finally, we can provide the function prototypes for the opendir(),
1317 ** readdir(), readdir_r(), and closedir() POSIX functions.
1318 */
1319 
1320 extern LPDIR opendir(const char *dirname);
1321 extern LPDIRENT readdir(LPDIR dirp);
1322 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1323 extern INT closedir(LPDIR dirp);
1324 
1325 #endif /* defined(WIN32) && defined(_MSC_VER) */
1326 
1327 /************************* End test_windirent.h ********************/
1328 /************************* Begin test_windirent.c ******************/
1329 /*
1330 ** 2015 November 30
1331 **
1332 ** The author disclaims copyright to this source code.  In place of
1333 ** a legal notice, here is a blessing:
1334 **
1335 **    May you do good and not evil.
1336 **    May you find forgiveness for yourself and forgive others.
1337 **    May you share freely, never taking more than you give.
1338 **
1339 *************************************************************************
1340 ** This file contains code to implement most of the opendir() family of
1341 ** POSIX functions on Win32 using the MSVCRT.
1342 */
1343 
1344 #if defined(_WIN32) && defined(_MSC_VER)
1345 /* #include "test_windirent.h" */
1346 
1347 /*
1348 ** Implementation of the POSIX getenv() function using the Win32 API.
1349 ** This function is not thread-safe.
1350 */
1351 const char *windirent_getenv(
1352   const char *name
1353 ){
1354   static char value[32768]; /* Maximum length, per MSDN */
1355   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1356   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1357 
1358   memset(value, 0, sizeof(value));
1359   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1360   if( dwRet==0 || dwRet>dwSize ){
1361     /*
1362     ** The function call to GetEnvironmentVariableA() failed -OR-
1363     ** the buffer is not large enough.  Either way, return NULL.
1364     */
1365     return 0;
1366   }else{
1367     /*
1368     ** The function call to GetEnvironmentVariableA() succeeded
1369     ** -AND- the buffer contains the entire value.
1370     */
1371     return value;
1372   }
1373 }
1374 
1375 /*
1376 ** Implementation of the POSIX opendir() function using the MSVCRT.
1377 */
1378 LPDIR opendir(
1379   const char *dirname
1380 ){
1381   struct _finddata_t data;
1382   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1383   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1384 
1385   if( dirp==NULL ) return NULL;
1386   memset(dirp, 0, sizeof(DIR));
1387 
1388   /* TODO: Remove this if Unix-style root paths are not used. */
1389   if( sqlite3_stricmp(dirname, "/")==0 ){
1390     dirname = windirent_getenv("SystemDrive");
1391   }
1392 
1393   memset(&data, 0, sizeof(struct _finddata_t));
1394   _snprintf(data.name, namesize, "%s\\*", dirname);
1395   dirp->d_handle = _findfirst(data.name, &data);
1396 
1397   if( dirp->d_handle==BAD_INTPTR_T ){
1398     closedir(dirp);
1399     return NULL;
1400   }
1401 
1402   /* TODO: Remove this block to allow hidden and/or system files. */
1403   if( is_filtered(data) ){
1404 next:
1405 
1406     memset(&data, 0, sizeof(struct _finddata_t));
1407     if( _findnext(dirp->d_handle, &data)==-1 ){
1408       closedir(dirp);
1409       return NULL;
1410     }
1411 
1412     /* TODO: Remove this block to allow hidden and/or system files. */
1413     if( is_filtered(data) ) goto next;
1414   }
1415 
1416   dirp->d_first.d_attributes = data.attrib;
1417   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1418   dirp->d_first.d_name[NAME_MAX] = '\0';
1419 
1420   return dirp;
1421 }
1422 
1423 /*
1424 ** Implementation of the POSIX readdir() function using the MSVCRT.
1425 */
1426 LPDIRENT readdir(
1427   LPDIR dirp
1428 ){
1429   struct _finddata_t data;
1430 
1431   if( dirp==NULL ) return NULL;
1432 
1433   if( dirp->d_first.d_ino==0 ){
1434     dirp->d_first.d_ino++;
1435     dirp->d_next.d_ino++;
1436 
1437     return &dirp->d_first;
1438   }
1439 
1440 next:
1441 
1442   memset(&data, 0, sizeof(struct _finddata_t));
1443   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1444 
1445   /* TODO: Remove this block to allow hidden and/or system files. */
1446   if( is_filtered(data) ) goto next;
1447 
1448   dirp->d_next.d_ino++;
1449   dirp->d_next.d_attributes = data.attrib;
1450   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1451   dirp->d_next.d_name[NAME_MAX] = '\0';
1452 
1453   return &dirp->d_next;
1454 }
1455 
1456 /*
1457 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1458 */
1459 INT readdir_r(
1460   LPDIR dirp,
1461   LPDIRENT entry,
1462   LPDIRENT *result
1463 ){
1464   struct _finddata_t data;
1465 
1466   if( dirp==NULL ) return EBADF;
1467 
1468   if( dirp->d_first.d_ino==0 ){
1469     dirp->d_first.d_ino++;
1470     dirp->d_next.d_ino++;
1471 
1472     entry->d_ino = dirp->d_first.d_ino;
1473     entry->d_attributes = dirp->d_first.d_attributes;
1474     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1475     entry->d_name[NAME_MAX] = '\0';
1476 
1477     *result = entry;
1478     return 0;
1479   }
1480 
1481 next:
1482 
1483   memset(&data, 0, sizeof(struct _finddata_t));
1484   if( _findnext(dirp->d_handle, &data)==-1 ){
1485     *result = NULL;
1486     return ENOENT;
1487   }
1488 
1489   /* TODO: Remove this block to allow hidden and/or system files. */
1490   if( is_filtered(data) ) goto next;
1491 
1492   entry->d_ino = (ino_t)-1; /* not available */
1493   entry->d_attributes = data.attrib;
1494   strncpy(entry->d_name, data.name, NAME_MAX);
1495   entry->d_name[NAME_MAX] = '\0';
1496 
1497   *result = entry;
1498   return 0;
1499 }
1500 
1501 /*
1502 ** Implementation of the POSIX closedir() function using the MSVCRT.
1503 */
1504 INT closedir(
1505   LPDIR dirp
1506 ){
1507   INT result = 0;
1508 
1509   if( dirp==NULL ) return EINVAL;
1510 
1511   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1512     result = _findclose(dirp->d_handle);
1513   }
1514 
1515   sqlite3_free(dirp);
1516   return result;
1517 }
1518 
1519 #endif /* defined(WIN32) && defined(_MSC_VER) */
1520 
1521 /************************* End test_windirent.c ********************/
1522 #define dirent DIRENT
1523 #endif
1524 /************************* Begin ../ext/misc/memtrace.c ******************/
1525 /*
1526 ** 2019-01-21
1527 **
1528 ** The author disclaims copyright to this source code.  In place of
1529 ** a legal notice, here is a blessing:
1530 **
1531 **    May you do good and not evil.
1532 **    May you find forgiveness for yourself and forgive others.
1533 **    May you share freely, never taking more than you give.
1534 **
1535 *************************************************************************
1536 **
1537 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
1538 ** mechanism to add a tracing layer on top of SQLite.  If this extension
1539 ** is registered prior to sqlite3_initialize(), it will cause all memory
1540 ** allocation activities to be logged on standard output, or to some other
1541 ** FILE specified by the initializer.
1542 **
1543 ** This file needs to be compiled into the application that uses it.
1544 **
1545 ** This extension is used to implement the --memtrace option of the
1546 ** command-line shell.
1547 */
1548 #include <assert.h>
1549 #include <string.h>
1550 #include <stdio.h>
1551 
1552 /* The original memory allocation routines */
1553 static sqlite3_mem_methods memtraceBase;
1554 static FILE *memtraceOut;
1555 
1556 /* Methods that trace memory allocations */
1557 static void *memtraceMalloc(int n){
1558   if( memtraceOut ){
1559     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
1560             memtraceBase.xRoundup(n));
1561   }
1562   return memtraceBase.xMalloc(n);
1563 }
1564 static void memtraceFree(void *p){
1565   if( p==0 ) return;
1566   if( memtraceOut ){
1567     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
1568   }
1569   memtraceBase.xFree(p);
1570 }
1571 static void *memtraceRealloc(void *p, int n){
1572   if( p==0 ) return memtraceMalloc(n);
1573   if( n==0 ){
1574     memtraceFree(p);
1575     return 0;
1576   }
1577   if( memtraceOut ){
1578     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
1579             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
1580   }
1581   return memtraceBase.xRealloc(p, n);
1582 }
1583 static int memtraceSize(void *p){
1584   return memtraceBase.xSize(p);
1585 }
1586 static int memtraceRoundup(int n){
1587   return memtraceBase.xRoundup(n);
1588 }
1589 static int memtraceInit(void *p){
1590   return memtraceBase.xInit(p);
1591 }
1592 static void memtraceShutdown(void *p){
1593   memtraceBase.xShutdown(p);
1594 }
1595 
1596 /* The substitute memory allocator */
1597 static sqlite3_mem_methods ersaztMethods = {
1598   memtraceMalloc,
1599   memtraceFree,
1600   memtraceRealloc,
1601   memtraceSize,
1602   memtraceRoundup,
1603   memtraceInit,
1604   memtraceShutdown,
1605   0
1606 };
1607 
1608 /* Begin tracing memory allocations to out. */
1609 int sqlite3MemTraceActivate(FILE *out){
1610   int rc = SQLITE_OK;
1611   if( memtraceBase.xMalloc==0 ){
1612     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
1613     if( rc==SQLITE_OK ){
1614       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
1615     }
1616   }
1617   memtraceOut = out;
1618   return rc;
1619 }
1620 
1621 /* Deactivate memory tracing */
1622 int sqlite3MemTraceDeactivate(void){
1623   int rc = SQLITE_OK;
1624   if( memtraceBase.xMalloc!=0 ){
1625     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
1626     if( rc==SQLITE_OK ){
1627       memset(&memtraceBase, 0, sizeof(memtraceBase));
1628     }
1629   }
1630   memtraceOut = 0;
1631   return rc;
1632 }
1633 
1634 /************************* End ../ext/misc/memtrace.c ********************/
1635 /************************* Begin ../ext/misc/shathree.c ******************/
1636 /*
1637 ** 2017-03-08
1638 **
1639 ** The author disclaims copyright to this source code.  In place of
1640 ** a legal notice, here is a blessing:
1641 **
1642 **    May you do good and not evil.
1643 **    May you find forgiveness for yourself and forgive others.
1644 **    May you share freely, never taking more than you give.
1645 **
1646 ******************************************************************************
1647 **
1648 ** This SQLite extension implements functions that compute SHA3 hashes.
1649 ** Two SQL functions are implemented:
1650 **
1651 **     sha3(X,SIZE)
1652 **     sha3_query(Y,SIZE)
1653 **
1654 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1655 ** X is NULL.
1656 **
1657 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
1658 ** and returns a hash of their results.
1659 **
1660 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
1661 ** is used.  If SIZE is included it must be one of the integers 224, 256,
1662 ** 384, or 512, to determine SHA3 hash variant that is computed.
1663 */
1664 /* #include "sqlite3ext.h" */
1665 SQLITE_EXTENSION_INIT1
1666 #include <assert.h>
1667 #include <string.h>
1668 #include <stdarg.h>
1669 
1670 #ifndef SQLITE_AMALGAMATION
1671 /* typedef sqlite3_uint64 u64; */
1672 #endif /* SQLITE_AMALGAMATION */
1673 
1674 /******************************************************************************
1675 ** The Hash Engine
1676 */
1677 /*
1678 ** Macros to determine whether the machine is big or little endian,
1679 ** and whether or not that determination is run-time or compile-time.
1680 **
1681 ** For best performance, an attempt is made to guess at the byte-order
1682 ** using C-preprocessor macros.  If that is unsuccessful, or if
1683 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1684 ** at run-time.
1685 */
1686 #ifndef SHA3_BYTEORDER
1687 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
1688      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
1689      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
1690      defined(__arm__)
1691 #   define SHA3_BYTEORDER    1234
1692 # elif defined(sparc)    || defined(__ppc__)
1693 #   define SHA3_BYTEORDER    4321
1694 # else
1695 #   define SHA3_BYTEORDER 0
1696 # endif
1697 #endif
1698 
1699 
1700 /*
1701 ** State structure for a SHA3 hash in progress
1702 */
1703 typedef struct SHA3Context SHA3Context;
1704 struct SHA3Context {
1705   union {
1706     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
1707     unsigned char x[1600];    /* ... or 1600 bytes */
1708   } u;
1709   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
1710   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
1711   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
1712 };
1713 
1714 /*
1715 ** A single step of the Keccak mixing function for a 1600-bit state
1716 */
1717 static void KeccakF1600Step(SHA3Context *p){
1718   int i;
1719   u64 b0, b1, b2, b3, b4;
1720   u64 c0, c1, c2, c3, c4;
1721   u64 d0, d1, d2, d3, d4;
1722   static const u64 RC[] = {
1723     0x0000000000000001ULL,  0x0000000000008082ULL,
1724     0x800000000000808aULL,  0x8000000080008000ULL,
1725     0x000000000000808bULL,  0x0000000080000001ULL,
1726     0x8000000080008081ULL,  0x8000000000008009ULL,
1727     0x000000000000008aULL,  0x0000000000000088ULL,
1728     0x0000000080008009ULL,  0x000000008000000aULL,
1729     0x000000008000808bULL,  0x800000000000008bULL,
1730     0x8000000000008089ULL,  0x8000000000008003ULL,
1731     0x8000000000008002ULL,  0x8000000000000080ULL,
1732     0x000000000000800aULL,  0x800000008000000aULL,
1733     0x8000000080008081ULL,  0x8000000000008080ULL,
1734     0x0000000080000001ULL,  0x8000000080008008ULL
1735   };
1736 # define a00 (p->u.s[0])
1737 # define a01 (p->u.s[1])
1738 # define a02 (p->u.s[2])
1739 # define a03 (p->u.s[3])
1740 # define a04 (p->u.s[4])
1741 # define a10 (p->u.s[5])
1742 # define a11 (p->u.s[6])
1743 # define a12 (p->u.s[7])
1744 # define a13 (p->u.s[8])
1745 # define a14 (p->u.s[9])
1746 # define a20 (p->u.s[10])
1747 # define a21 (p->u.s[11])
1748 # define a22 (p->u.s[12])
1749 # define a23 (p->u.s[13])
1750 # define a24 (p->u.s[14])
1751 # define a30 (p->u.s[15])
1752 # define a31 (p->u.s[16])
1753 # define a32 (p->u.s[17])
1754 # define a33 (p->u.s[18])
1755 # define a34 (p->u.s[19])
1756 # define a40 (p->u.s[20])
1757 # define a41 (p->u.s[21])
1758 # define a42 (p->u.s[22])
1759 # define a43 (p->u.s[23])
1760 # define a44 (p->u.s[24])
1761 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1762 
1763   for(i=0; i<24; i+=4){
1764     c0 = a00^a10^a20^a30^a40;
1765     c1 = a01^a11^a21^a31^a41;
1766     c2 = a02^a12^a22^a32^a42;
1767     c3 = a03^a13^a23^a33^a43;
1768     c4 = a04^a14^a24^a34^a44;
1769     d0 = c4^ROL64(c1, 1);
1770     d1 = c0^ROL64(c2, 1);
1771     d2 = c1^ROL64(c3, 1);
1772     d3 = c2^ROL64(c4, 1);
1773     d4 = c3^ROL64(c0, 1);
1774 
1775     b0 = (a00^d0);
1776     b1 = ROL64((a11^d1), 44);
1777     b2 = ROL64((a22^d2), 43);
1778     b3 = ROL64((a33^d3), 21);
1779     b4 = ROL64((a44^d4), 14);
1780     a00 =   b0 ^((~b1)&  b2 );
1781     a00 ^= RC[i];
1782     a11 =   b1 ^((~b2)&  b3 );
1783     a22 =   b2 ^((~b3)&  b4 );
1784     a33 =   b3 ^((~b4)&  b0 );
1785     a44 =   b4 ^((~b0)&  b1 );
1786 
1787     b2 = ROL64((a20^d0), 3);
1788     b3 = ROL64((a31^d1), 45);
1789     b4 = ROL64((a42^d2), 61);
1790     b0 = ROL64((a03^d3), 28);
1791     b1 = ROL64((a14^d4), 20);
1792     a20 =   b0 ^((~b1)&  b2 );
1793     a31 =   b1 ^((~b2)&  b3 );
1794     a42 =   b2 ^((~b3)&  b4 );
1795     a03 =   b3 ^((~b4)&  b0 );
1796     a14 =   b4 ^((~b0)&  b1 );
1797 
1798     b4 = ROL64((a40^d0), 18);
1799     b0 = ROL64((a01^d1), 1);
1800     b1 = ROL64((a12^d2), 6);
1801     b2 = ROL64((a23^d3), 25);
1802     b3 = ROL64((a34^d4), 8);
1803     a40 =   b0 ^((~b1)&  b2 );
1804     a01 =   b1 ^((~b2)&  b3 );
1805     a12 =   b2 ^((~b3)&  b4 );
1806     a23 =   b3 ^((~b4)&  b0 );
1807     a34 =   b4 ^((~b0)&  b1 );
1808 
1809     b1 = ROL64((a10^d0), 36);
1810     b2 = ROL64((a21^d1), 10);
1811     b3 = ROL64((a32^d2), 15);
1812     b4 = ROL64((a43^d3), 56);
1813     b0 = ROL64((a04^d4), 27);
1814     a10 =   b0 ^((~b1)&  b2 );
1815     a21 =   b1 ^((~b2)&  b3 );
1816     a32 =   b2 ^((~b3)&  b4 );
1817     a43 =   b3 ^((~b4)&  b0 );
1818     a04 =   b4 ^((~b0)&  b1 );
1819 
1820     b3 = ROL64((a30^d0), 41);
1821     b4 = ROL64((a41^d1), 2);
1822     b0 = ROL64((a02^d2), 62);
1823     b1 = ROL64((a13^d3), 55);
1824     b2 = ROL64((a24^d4), 39);
1825     a30 =   b0 ^((~b1)&  b2 );
1826     a41 =   b1 ^((~b2)&  b3 );
1827     a02 =   b2 ^((~b3)&  b4 );
1828     a13 =   b3 ^((~b4)&  b0 );
1829     a24 =   b4 ^((~b0)&  b1 );
1830 
1831     c0 = a00^a20^a40^a10^a30;
1832     c1 = a11^a31^a01^a21^a41;
1833     c2 = a22^a42^a12^a32^a02;
1834     c3 = a33^a03^a23^a43^a13;
1835     c4 = a44^a14^a34^a04^a24;
1836     d0 = c4^ROL64(c1, 1);
1837     d1 = c0^ROL64(c2, 1);
1838     d2 = c1^ROL64(c3, 1);
1839     d3 = c2^ROL64(c4, 1);
1840     d4 = c3^ROL64(c0, 1);
1841 
1842     b0 = (a00^d0);
1843     b1 = ROL64((a31^d1), 44);
1844     b2 = ROL64((a12^d2), 43);
1845     b3 = ROL64((a43^d3), 21);
1846     b4 = ROL64((a24^d4), 14);
1847     a00 =   b0 ^((~b1)&  b2 );
1848     a00 ^= RC[i+1];
1849     a31 =   b1 ^((~b2)&  b3 );
1850     a12 =   b2 ^((~b3)&  b4 );
1851     a43 =   b3 ^((~b4)&  b0 );
1852     a24 =   b4 ^((~b0)&  b1 );
1853 
1854     b2 = ROL64((a40^d0), 3);
1855     b3 = ROL64((a21^d1), 45);
1856     b4 = ROL64((a02^d2), 61);
1857     b0 = ROL64((a33^d3), 28);
1858     b1 = ROL64((a14^d4), 20);
1859     a40 =   b0 ^((~b1)&  b2 );
1860     a21 =   b1 ^((~b2)&  b3 );
1861     a02 =   b2 ^((~b3)&  b4 );
1862     a33 =   b3 ^((~b4)&  b0 );
1863     a14 =   b4 ^((~b0)&  b1 );
1864 
1865     b4 = ROL64((a30^d0), 18);
1866     b0 = ROL64((a11^d1), 1);
1867     b1 = ROL64((a42^d2), 6);
1868     b2 = ROL64((a23^d3), 25);
1869     b3 = ROL64((a04^d4), 8);
1870     a30 =   b0 ^((~b1)&  b2 );
1871     a11 =   b1 ^((~b2)&  b3 );
1872     a42 =   b2 ^((~b3)&  b4 );
1873     a23 =   b3 ^((~b4)&  b0 );
1874     a04 =   b4 ^((~b0)&  b1 );
1875 
1876     b1 = ROL64((a20^d0), 36);
1877     b2 = ROL64((a01^d1), 10);
1878     b3 = ROL64((a32^d2), 15);
1879     b4 = ROL64((a13^d3), 56);
1880     b0 = ROL64((a44^d4), 27);
1881     a20 =   b0 ^((~b1)&  b2 );
1882     a01 =   b1 ^((~b2)&  b3 );
1883     a32 =   b2 ^((~b3)&  b4 );
1884     a13 =   b3 ^((~b4)&  b0 );
1885     a44 =   b4 ^((~b0)&  b1 );
1886 
1887     b3 = ROL64((a10^d0), 41);
1888     b4 = ROL64((a41^d1), 2);
1889     b0 = ROL64((a22^d2), 62);
1890     b1 = ROL64((a03^d3), 55);
1891     b2 = ROL64((a34^d4), 39);
1892     a10 =   b0 ^((~b1)&  b2 );
1893     a41 =   b1 ^((~b2)&  b3 );
1894     a22 =   b2 ^((~b3)&  b4 );
1895     a03 =   b3 ^((~b4)&  b0 );
1896     a34 =   b4 ^((~b0)&  b1 );
1897 
1898     c0 = a00^a40^a30^a20^a10;
1899     c1 = a31^a21^a11^a01^a41;
1900     c2 = a12^a02^a42^a32^a22;
1901     c3 = a43^a33^a23^a13^a03;
1902     c4 = a24^a14^a04^a44^a34;
1903     d0 = c4^ROL64(c1, 1);
1904     d1 = c0^ROL64(c2, 1);
1905     d2 = c1^ROL64(c3, 1);
1906     d3 = c2^ROL64(c4, 1);
1907     d4 = c3^ROL64(c0, 1);
1908 
1909     b0 = (a00^d0);
1910     b1 = ROL64((a21^d1), 44);
1911     b2 = ROL64((a42^d2), 43);
1912     b3 = ROL64((a13^d3), 21);
1913     b4 = ROL64((a34^d4), 14);
1914     a00 =   b0 ^((~b1)&  b2 );
1915     a00 ^= RC[i+2];
1916     a21 =   b1 ^((~b2)&  b3 );
1917     a42 =   b2 ^((~b3)&  b4 );
1918     a13 =   b3 ^((~b4)&  b0 );
1919     a34 =   b4 ^((~b0)&  b1 );
1920 
1921     b2 = ROL64((a30^d0), 3);
1922     b3 = ROL64((a01^d1), 45);
1923     b4 = ROL64((a22^d2), 61);
1924     b0 = ROL64((a43^d3), 28);
1925     b1 = ROL64((a14^d4), 20);
1926     a30 =   b0 ^((~b1)&  b2 );
1927     a01 =   b1 ^((~b2)&  b3 );
1928     a22 =   b2 ^((~b3)&  b4 );
1929     a43 =   b3 ^((~b4)&  b0 );
1930     a14 =   b4 ^((~b0)&  b1 );
1931 
1932     b4 = ROL64((a10^d0), 18);
1933     b0 = ROL64((a31^d1), 1);
1934     b1 = ROL64((a02^d2), 6);
1935     b2 = ROL64((a23^d3), 25);
1936     b3 = ROL64((a44^d4), 8);
1937     a10 =   b0 ^((~b1)&  b2 );
1938     a31 =   b1 ^((~b2)&  b3 );
1939     a02 =   b2 ^((~b3)&  b4 );
1940     a23 =   b3 ^((~b4)&  b0 );
1941     a44 =   b4 ^((~b0)&  b1 );
1942 
1943     b1 = ROL64((a40^d0), 36);
1944     b2 = ROL64((a11^d1), 10);
1945     b3 = ROL64((a32^d2), 15);
1946     b4 = ROL64((a03^d3), 56);
1947     b0 = ROL64((a24^d4), 27);
1948     a40 =   b0 ^((~b1)&  b2 );
1949     a11 =   b1 ^((~b2)&  b3 );
1950     a32 =   b2 ^((~b3)&  b4 );
1951     a03 =   b3 ^((~b4)&  b0 );
1952     a24 =   b4 ^((~b0)&  b1 );
1953 
1954     b3 = ROL64((a20^d0), 41);
1955     b4 = ROL64((a41^d1), 2);
1956     b0 = ROL64((a12^d2), 62);
1957     b1 = ROL64((a33^d3), 55);
1958     b2 = ROL64((a04^d4), 39);
1959     a20 =   b0 ^((~b1)&  b2 );
1960     a41 =   b1 ^((~b2)&  b3 );
1961     a12 =   b2 ^((~b3)&  b4 );
1962     a33 =   b3 ^((~b4)&  b0 );
1963     a04 =   b4 ^((~b0)&  b1 );
1964 
1965     c0 = a00^a30^a10^a40^a20;
1966     c1 = a21^a01^a31^a11^a41;
1967     c2 = a42^a22^a02^a32^a12;
1968     c3 = a13^a43^a23^a03^a33;
1969     c4 = a34^a14^a44^a24^a04;
1970     d0 = c4^ROL64(c1, 1);
1971     d1 = c0^ROL64(c2, 1);
1972     d2 = c1^ROL64(c3, 1);
1973     d3 = c2^ROL64(c4, 1);
1974     d4 = c3^ROL64(c0, 1);
1975 
1976     b0 = (a00^d0);
1977     b1 = ROL64((a01^d1), 44);
1978     b2 = ROL64((a02^d2), 43);
1979     b3 = ROL64((a03^d3), 21);
1980     b4 = ROL64((a04^d4), 14);
1981     a00 =   b0 ^((~b1)&  b2 );
1982     a00 ^= RC[i+3];
1983     a01 =   b1 ^((~b2)&  b3 );
1984     a02 =   b2 ^((~b3)&  b4 );
1985     a03 =   b3 ^((~b4)&  b0 );
1986     a04 =   b4 ^((~b0)&  b1 );
1987 
1988     b2 = ROL64((a10^d0), 3);
1989     b3 = ROL64((a11^d1), 45);
1990     b4 = ROL64((a12^d2), 61);
1991     b0 = ROL64((a13^d3), 28);
1992     b1 = ROL64((a14^d4), 20);
1993     a10 =   b0 ^((~b1)&  b2 );
1994     a11 =   b1 ^((~b2)&  b3 );
1995     a12 =   b2 ^((~b3)&  b4 );
1996     a13 =   b3 ^((~b4)&  b0 );
1997     a14 =   b4 ^((~b0)&  b1 );
1998 
1999     b4 = ROL64((a20^d0), 18);
2000     b0 = ROL64((a21^d1), 1);
2001     b1 = ROL64((a22^d2), 6);
2002     b2 = ROL64((a23^d3), 25);
2003     b3 = ROL64((a24^d4), 8);
2004     a20 =   b0 ^((~b1)&  b2 );
2005     a21 =   b1 ^((~b2)&  b3 );
2006     a22 =   b2 ^((~b3)&  b4 );
2007     a23 =   b3 ^((~b4)&  b0 );
2008     a24 =   b4 ^((~b0)&  b1 );
2009 
2010     b1 = ROL64((a30^d0), 36);
2011     b2 = ROL64((a31^d1), 10);
2012     b3 = ROL64((a32^d2), 15);
2013     b4 = ROL64((a33^d3), 56);
2014     b0 = ROL64((a34^d4), 27);
2015     a30 =   b0 ^((~b1)&  b2 );
2016     a31 =   b1 ^((~b2)&  b3 );
2017     a32 =   b2 ^((~b3)&  b4 );
2018     a33 =   b3 ^((~b4)&  b0 );
2019     a34 =   b4 ^((~b0)&  b1 );
2020 
2021     b3 = ROL64((a40^d0), 41);
2022     b4 = ROL64((a41^d1), 2);
2023     b0 = ROL64((a42^d2), 62);
2024     b1 = ROL64((a43^d3), 55);
2025     b2 = ROL64((a44^d4), 39);
2026     a40 =   b0 ^((~b1)&  b2 );
2027     a41 =   b1 ^((~b2)&  b3 );
2028     a42 =   b2 ^((~b3)&  b4 );
2029     a43 =   b3 ^((~b4)&  b0 );
2030     a44 =   b4 ^((~b0)&  b1 );
2031   }
2032 }
2033 
2034 /*
2035 ** Initialize a new hash.  iSize determines the size of the hash
2036 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
2037 ** can be zero to use the default hash size of 256 bits.
2038 */
2039 static void SHA3Init(SHA3Context *p, int iSize){
2040   memset(p, 0, sizeof(*p));
2041   if( iSize>=128 && iSize<=512 ){
2042     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
2043   }else{
2044     p->nRate = (1600 - 2*256)/8;
2045   }
2046 #if SHA3_BYTEORDER==1234
2047   /* Known to be little-endian at compile-time. No-op */
2048 #elif SHA3_BYTEORDER==4321
2049   p->ixMask = 7;  /* Big-endian */
2050 #else
2051   {
2052     static unsigned int one = 1;
2053     if( 1==*(unsigned char*)&one ){
2054       /* Little endian.  No byte swapping. */
2055       p->ixMask = 0;
2056     }else{
2057       /* Big endian.  Byte swap. */
2058       p->ixMask = 7;
2059     }
2060   }
2061 #endif
2062 }
2063 
2064 /*
2065 ** Make consecutive calls to the SHA3Update function to add new content
2066 ** to the hash
2067 */
2068 static void SHA3Update(
2069   SHA3Context *p,
2070   const unsigned char *aData,
2071   unsigned int nData
2072 ){
2073   unsigned int i = 0;
2074   if( aData==0 ) return;
2075 #if SHA3_BYTEORDER==1234
2076   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
2077     for(; i+7<nData; i+=8){
2078       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
2079       p->nLoaded += 8;
2080       if( p->nLoaded>=p->nRate ){
2081         KeccakF1600Step(p);
2082         p->nLoaded = 0;
2083       }
2084     }
2085   }
2086 #endif
2087   for(; i<nData; i++){
2088 #if SHA3_BYTEORDER==1234
2089     p->u.x[p->nLoaded] ^= aData[i];
2090 #elif SHA3_BYTEORDER==4321
2091     p->u.x[p->nLoaded^0x07] ^= aData[i];
2092 #else
2093     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
2094 #endif
2095     p->nLoaded++;
2096     if( p->nLoaded==p->nRate ){
2097       KeccakF1600Step(p);
2098       p->nLoaded = 0;
2099     }
2100   }
2101 }
2102 
2103 /*
2104 ** After all content has been added, invoke SHA3Final() to compute
2105 ** the final hash.  The function returns a pointer to the binary
2106 ** hash value.
2107 */
2108 static unsigned char *SHA3Final(SHA3Context *p){
2109   unsigned int i;
2110   if( p->nLoaded==p->nRate-1 ){
2111     const unsigned char c1 = 0x86;
2112     SHA3Update(p, &c1, 1);
2113   }else{
2114     const unsigned char c2 = 0x06;
2115     const unsigned char c3 = 0x80;
2116     SHA3Update(p, &c2, 1);
2117     p->nLoaded = p->nRate - 1;
2118     SHA3Update(p, &c3, 1);
2119   }
2120   for(i=0; i<p->nRate; i++){
2121     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
2122   }
2123   return &p->u.x[p->nRate];
2124 }
2125 /* End of the hashing logic
2126 *****************************************************************************/
2127 
2128 /*
2129 ** Implementation of the sha3(X,SIZE) function.
2130 **
2131 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
2132 ** size is 256.  If X is a BLOB, it is hashed as is.
2133 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2134 ** and the string is hashed without the trailing 0x00 terminator.  The hash
2135 ** of a NULL value is NULL.
2136 */
2137 static void sha3Func(
2138   sqlite3_context *context,
2139   int argc,
2140   sqlite3_value **argv
2141 ){
2142   SHA3Context cx;
2143   int eType = sqlite3_value_type(argv[0]);
2144   int nByte = sqlite3_value_bytes(argv[0]);
2145   int iSize;
2146   if( argc==1 ){
2147     iSize = 256;
2148   }else{
2149     iSize = sqlite3_value_int(argv[1]);
2150     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2151       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2152                                     "384 512", -1);
2153       return;
2154     }
2155   }
2156   if( eType==SQLITE_NULL ) return;
2157   SHA3Init(&cx, iSize);
2158   if( eType==SQLITE_BLOB ){
2159     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
2160   }else{
2161     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
2162   }
2163   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2164 }
2165 
2166 /* Compute a string using sqlite3_vsnprintf() with a maximum length
2167 ** of 50 bytes and add it to the hash.
2168 */
2169 static void sha3_step_vformat(
2170   SHA3Context *p,                 /* Add content to this context */
2171   const char *zFormat,
2172   ...
2173 ){
2174   va_list ap;
2175   int n;
2176   char zBuf[50];
2177   va_start(ap, zFormat);
2178   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
2179   va_end(ap);
2180   n = (int)strlen(zBuf);
2181   SHA3Update(p, (unsigned char*)zBuf, n);
2182 }
2183 
2184 /*
2185 ** Implementation of the sha3_query(SQL,SIZE) function.
2186 **
2187 ** This function compiles and runs the SQL statement(s) given in the
2188 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
2189 ** size is 256.
2190 **
2191 ** The format of the byte stream that is hashed is summarized as follows:
2192 **
2193 **       S<n>:<sql>
2194 **       R
2195 **       N
2196 **       I<int>
2197 **       F<ieee-float>
2198 **       B<size>:<bytes>
2199 **       T<size>:<text>
2200 **
2201 ** <sql> is the original SQL text for each statement run and <n> is
2202 ** the size of that text.  The SQL text is UTF-8.  A single R character
2203 ** occurs before the start of each row.  N means a NULL value.
2204 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
2205 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
2206 ** B means blobs of <size> bytes.  T means text rendered as <size>
2207 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
2208 ** text integers.
2209 **
2210 ** For each SQL statement in the X input, there is one S segment.  Each
2211 ** S segment is followed by zero or more R segments, one for each row in the
2212 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
2213 ** one for each column in the result set.  Segments are concatentated directly
2214 ** with no delimiters of any kind.
2215 */
2216 static void sha3QueryFunc(
2217   sqlite3_context *context,
2218   int argc,
2219   sqlite3_value **argv
2220 ){
2221   sqlite3 *db = sqlite3_context_db_handle(context);
2222   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
2223   sqlite3_stmt *pStmt = 0;
2224   int nCol;                   /* Number of columns in the result set */
2225   int i;                      /* Loop counter */
2226   int rc;
2227   int n;
2228   const char *z;
2229   SHA3Context cx;
2230   int iSize;
2231 
2232   if( argc==1 ){
2233     iSize = 256;
2234   }else{
2235     iSize = sqlite3_value_int(argv[1]);
2236     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2237       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2238                                     "384 512", -1);
2239       return;
2240     }
2241   }
2242   if( zSql==0 ) return;
2243   SHA3Init(&cx, iSize);
2244   while( zSql[0] ){
2245     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2246     if( rc ){
2247       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2248                                    zSql, sqlite3_errmsg(db));
2249       sqlite3_finalize(pStmt);
2250       sqlite3_result_error(context, zMsg, -1);
2251       sqlite3_free(zMsg);
2252       return;
2253     }
2254     if( !sqlite3_stmt_readonly(pStmt) ){
2255       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2256       sqlite3_finalize(pStmt);
2257       sqlite3_result_error(context, zMsg, -1);
2258       sqlite3_free(zMsg);
2259       return;
2260     }
2261     nCol = sqlite3_column_count(pStmt);
2262     z = sqlite3_sql(pStmt);
2263     if( z ){
2264       n = (int)strlen(z);
2265       sha3_step_vformat(&cx,"S%d:",n);
2266       SHA3Update(&cx,(unsigned char*)z,n);
2267     }
2268 
2269     /* Compute a hash over the result of the query */
2270     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2271       SHA3Update(&cx,(const unsigned char*)"R",1);
2272       for(i=0; i<nCol; i++){
2273         switch( sqlite3_column_type(pStmt,i) ){
2274           case SQLITE_NULL: {
2275             SHA3Update(&cx, (const unsigned char*)"N",1);
2276             break;
2277           }
2278           case SQLITE_INTEGER: {
2279             sqlite3_uint64 u;
2280             int j;
2281             unsigned char x[9];
2282             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2283             memcpy(&u, &v, 8);
2284             for(j=8; j>=1; j--){
2285               x[j] = u & 0xff;
2286               u >>= 8;
2287             }
2288             x[0] = 'I';
2289             SHA3Update(&cx, x, 9);
2290             break;
2291           }
2292           case SQLITE_FLOAT: {
2293             sqlite3_uint64 u;
2294             int j;
2295             unsigned char x[9];
2296             double r = sqlite3_column_double(pStmt,i);
2297             memcpy(&u, &r, 8);
2298             for(j=8; j>=1; j--){
2299               x[j] = u & 0xff;
2300               u >>= 8;
2301             }
2302             x[0] = 'F';
2303             SHA3Update(&cx,x,9);
2304             break;
2305           }
2306           case SQLITE_TEXT: {
2307             int n2 = sqlite3_column_bytes(pStmt, i);
2308             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2309             sha3_step_vformat(&cx,"T%d:",n2);
2310             SHA3Update(&cx, z2, n2);
2311             break;
2312           }
2313           case SQLITE_BLOB: {
2314             int n2 = sqlite3_column_bytes(pStmt, i);
2315             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2316             sha3_step_vformat(&cx,"B%d:",n2);
2317             SHA3Update(&cx, z2, n2);
2318             break;
2319           }
2320         }
2321       }
2322     }
2323     sqlite3_finalize(pStmt);
2324   }
2325   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2326 }
2327 
2328 
2329 #ifdef _WIN32
2330 
2331 #endif
2332 int sqlite3_shathree_init(
2333   sqlite3 *db,
2334   char **pzErrMsg,
2335   const sqlite3_api_routines *pApi
2336 ){
2337   int rc = SQLITE_OK;
2338   SQLITE_EXTENSION_INIT2(pApi);
2339   (void)pzErrMsg;  /* Unused parameter */
2340   rc = sqlite3_create_function(db, "sha3", 1,
2341                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2342                       0, sha3Func, 0, 0);
2343   if( rc==SQLITE_OK ){
2344     rc = sqlite3_create_function(db, "sha3", 2,
2345                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2346                       0, sha3Func, 0, 0);
2347   }
2348   if( rc==SQLITE_OK ){
2349     rc = sqlite3_create_function(db, "sha3_query", 1,
2350                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2351                       0, sha3QueryFunc, 0, 0);
2352   }
2353   if( rc==SQLITE_OK ){
2354     rc = sqlite3_create_function(db, "sha3_query", 2,
2355                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2356                       0, sha3QueryFunc, 0, 0);
2357   }
2358   return rc;
2359 }
2360 
2361 /************************* End ../ext/misc/shathree.c ********************/
2362 /************************* Begin ../ext/misc/uint.c ******************/
2363 /*
2364 ** 2020-04-14
2365 **
2366 ** The author disclaims copyright to this source code.  In place of
2367 ** a legal notice, here is a blessing:
2368 **
2369 **    May you do good and not evil.
2370 **    May you find forgiveness for yourself and forgive others.
2371 **    May you share freely, never taking more than you give.
2372 **
2373 ******************************************************************************
2374 **
2375 ** This SQLite extension implements the UINT collating sequence.
2376 **
2377 ** UINT works like BINARY for text, except that embedded strings
2378 ** of digits compare in numeric order.
2379 **
2380 **     *   Leading zeros are handled properly, in the sense that
2381 **         they do not mess of the maginitude comparison of embedded
2382 **         strings of digits.  "x00123y" is equal to "x123y".
2383 **
2384 **     *   Only unsigned integers are recognized.  Plus and minus
2385 **         signs are ignored.  Decimal points and exponential notation
2386 **         are ignored.
2387 **
2388 **     *   Embedded integers can be of arbitrary length.  Comparison
2389 **         is *not* limited integers that can be expressed as a
2390 **         64-bit machine integer.
2391 */
2392 /* #include "sqlite3ext.h" */
2393 SQLITE_EXTENSION_INIT1
2394 #include <assert.h>
2395 #include <string.h>
2396 #include <ctype.h>
2397 
2398 /*
2399 ** Compare text in lexicographic order, except strings of digits
2400 ** compare in numeric order.
2401 */
2402 static int uintCollFunc(
2403   void *notUsed,
2404   int nKey1, const void *pKey1,
2405   int nKey2, const void *pKey2
2406 ){
2407   const unsigned char *zA = (const unsigned char*)pKey1;
2408   const unsigned char *zB = (const unsigned char*)pKey2;
2409   int i=0, j=0, x;
2410   (void)notUsed;
2411   while( i<nKey1 && j<nKey2 ){
2412     x = zA[i] - zB[j];
2413     if( isdigit(zA[i]) ){
2414       int k;
2415       if( !isdigit(zB[j]) ) return x;
2416       while( i<nKey1 && zA[i]=='0' ){ i++; }
2417       while( j<nKey2 && zB[j]=='0' ){ j++; }
2418       k = 0;
2419       while( i+k<nKey1 && isdigit(zA[i+k])
2420              && j+k<nKey2 && isdigit(zB[j+k]) ){
2421         k++;
2422       }
2423       if( i+k<nKey1 && isdigit(zA[i+k]) ){
2424         return +1;
2425       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
2426         return -1;
2427       }else{
2428         x = memcmp(zA+i, zB+j, k);
2429         if( x ) return x;
2430         i += k;
2431         j += k;
2432       }
2433     }else if( x ){
2434       return x;
2435     }else{
2436       i++;
2437       j++;
2438     }
2439   }
2440   return (nKey1 - i) - (nKey2 - j);
2441 }
2442 
2443 #ifdef _WIN32
2444 
2445 #endif
2446 int sqlite3_uint_init(
2447   sqlite3 *db,
2448   char **pzErrMsg,
2449   const sqlite3_api_routines *pApi
2450 ){
2451   SQLITE_EXTENSION_INIT2(pApi);
2452   (void)pzErrMsg;  /* Unused parameter */
2453   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
2454 }
2455 
2456 /************************* End ../ext/misc/uint.c ********************/
2457 /************************* Begin ../ext/misc/decimal.c ******************/
2458 /*
2459 ** 2020-06-22
2460 **
2461 ** The author disclaims copyright to this source code.  In place of
2462 ** a legal notice, here is a blessing:
2463 **
2464 **    May you do good and not evil.
2465 **    May you find forgiveness for yourself and forgive others.
2466 **    May you share freely, never taking more than you give.
2467 **
2468 ******************************************************************************
2469 **
2470 ** Routines to implement arbitrary-precision decimal math.
2471 **
2472 ** The focus here is on simplicity and correctness, not performance.
2473 */
2474 /* #include "sqlite3ext.h" */
2475 SQLITE_EXTENSION_INIT1
2476 #include <assert.h>
2477 #include <string.h>
2478 #include <ctype.h>
2479 #include <stdlib.h>
2480 
2481 /* Mark a function parameter as unused, to suppress nuisance compiler
2482 ** warnings. */
2483 #ifndef UNUSED_PARAMETER
2484 # define UNUSED_PARAMETER(X)  (void)(X)
2485 #endif
2486 
2487 
2488 /* A decimal object */
2489 typedef struct Decimal Decimal;
2490 struct Decimal {
2491   char sign;        /* 0 for positive, 1 for negative */
2492   char oom;         /* True if an OOM is encountered */
2493   char isNull;      /* True if holds a NULL rather than a number */
2494   char isInit;      /* True upon initialization */
2495   int nDigit;       /* Total number of digits */
2496   int nFrac;        /* Number of digits to the right of the decimal point */
2497   signed char *a;   /* Array of digits.  Most significant first. */
2498 };
2499 
2500 /*
2501 ** Release memory held by a Decimal, but do not free the object itself.
2502 */
2503 static void decimal_clear(Decimal *p){
2504   sqlite3_free(p->a);
2505 }
2506 
2507 /*
2508 ** Destroy a Decimal object
2509 */
2510 static void decimal_free(Decimal *p){
2511   if( p ){
2512     decimal_clear(p);
2513     sqlite3_free(p);
2514   }
2515 }
2516 
2517 /*
2518 ** Allocate a new Decimal object.  Initialize it to the number given
2519 ** by the input string.
2520 */
2521 static Decimal *decimal_new(
2522   sqlite3_context *pCtx,
2523   sqlite3_value *pIn,
2524   int nAlt,
2525   const unsigned char *zAlt
2526 ){
2527   Decimal *p;
2528   int n, i;
2529   const unsigned char *zIn;
2530   int iExp = 0;
2531   p = sqlite3_malloc( sizeof(*p) );
2532   if( p==0 ) goto new_no_mem;
2533   p->sign = 0;
2534   p->oom = 0;
2535   p->isInit = 1;
2536   p->isNull = 0;
2537   p->nDigit = 0;
2538   p->nFrac = 0;
2539   if( zAlt ){
2540     n = nAlt,
2541     zIn = zAlt;
2542   }else{
2543     if( sqlite3_value_type(pIn)==SQLITE_NULL ){
2544       p->a = 0;
2545       p->isNull = 1;
2546       return p;
2547     }
2548     n = sqlite3_value_bytes(pIn);
2549     zIn = sqlite3_value_text(pIn);
2550   }
2551   p->a = sqlite3_malloc64( n+1 );
2552   if( p->a==0 ) goto new_no_mem;
2553   for(i=0; isspace(zIn[i]); i++){}
2554   if( zIn[i]=='-' ){
2555     p->sign = 1;
2556     i++;
2557   }else if( zIn[i]=='+' ){
2558     i++;
2559   }
2560   while( i<n && zIn[i]=='0' ) i++;
2561   while( i<n ){
2562     char c = zIn[i];
2563     if( c>='0' && c<='9' ){
2564       p->a[p->nDigit++] = c - '0';
2565     }else if( c=='.' ){
2566       p->nFrac = p->nDigit + 1;
2567     }else if( c=='e' || c=='E' ){
2568       int j = i+1;
2569       int neg = 0;
2570       if( j>=n ) break;
2571       if( zIn[j]=='-' ){
2572         neg = 1;
2573         j++;
2574       }else if( zIn[j]=='+' ){
2575         j++;
2576       }
2577       while( j<n && iExp<1000000 ){
2578         if( zIn[j]>='0' && zIn[j]<='9' ){
2579           iExp = iExp*10 + zIn[j] - '0';
2580         }
2581         j++;
2582       }
2583       if( neg ) iExp = -iExp;
2584       break;
2585     }
2586     i++;
2587   }
2588   if( p->nFrac ){
2589     p->nFrac = p->nDigit - (p->nFrac - 1);
2590   }
2591   if( iExp>0 ){
2592     if( p->nFrac>0 ){
2593       if( iExp<=p->nFrac ){
2594         p->nFrac -= iExp;
2595         iExp = 0;
2596       }else{
2597         iExp -= p->nFrac;
2598         p->nFrac = 0;
2599       }
2600     }
2601     if( iExp>0 ){
2602       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2603       if( p->a==0 ) goto new_no_mem;
2604       memset(p->a+p->nDigit, 0, iExp);
2605       p->nDigit += iExp;
2606     }
2607   }else if( iExp<0 ){
2608     int nExtra;
2609     iExp = -iExp;
2610     nExtra = p->nDigit - p->nFrac - 1;
2611     if( nExtra ){
2612       if( nExtra>=iExp ){
2613         p->nFrac += iExp;
2614         iExp  = 0;
2615       }else{
2616         iExp -= nExtra;
2617         p->nFrac = p->nDigit - 1;
2618       }
2619     }
2620     if( iExp>0 ){
2621       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
2622       if( p->a==0 ) goto new_no_mem;
2623       memmove(p->a+iExp, p->a, p->nDigit);
2624       memset(p->a, 0, iExp);
2625       p->nDigit += iExp;
2626       p->nFrac += iExp;
2627     }
2628   }
2629   return p;
2630 
2631 new_no_mem:
2632   if( pCtx ) sqlite3_result_error_nomem(pCtx);
2633   sqlite3_free(p);
2634   return 0;
2635 }
2636 
2637 /*
2638 ** Make the given Decimal the result.
2639 */
2640 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
2641   char *z;
2642   int i, j;
2643   int n;
2644   if( p==0 || p->oom ){
2645     sqlite3_result_error_nomem(pCtx);
2646     return;
2647   }
2648   if( p->isNull ){
2649     sqlite3_result_null(pCtx);
2650     return;
2651   }
2652   z = sqlite3_malloc( p->nDigit+4 );
2653   if( z==0 ){
2654     sqlite3_result_error_nomem(pCtx);
2655     return;
2656   }
2657   i = 0;
2658   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
2659     p->sign = 0;
2660   }
2661   if( p->sign ){
2662     z[0] = '-';
2663     i = 1;
2664   }
2665   n = p->nDigit - p->nFrac;
2666   if( n<=0 ){
2667     z[i++] = '0';
2668   }
2669   j = 0;
2670   while( n>1 && p->a[j]==0 ){
2671     j++;
2672     n--;
2673   }
2674   while( n>0  ){
2675     z[i++] = p->a[j] + '0';
2676     j++;
2677     n--;
2678   }
2679   if( p->nFrac ){
2680     z[i++] = '.';
2681     do{
2682       z[i++] = p->a[j] + '0';
2683       j++;
2684     }while( j<p->nDigit );
2685   }
2686   z[i] = 0;
2687   sqlite3_result_text(pCtx, z, i, sqlite3_free);
2688 }
2689 
2690 /*
2691 ** SQL Function:   decimal(X)
2692 **
2693 ** Convert input X into decimal and then back into text
2694 */
2695 static void decimalFunc(
2696   sqlite3_context *context,
2697   int argc,
2698   sqlite3_value **argv
2699 ){
2700   Decimal *p = decimal_new(context, argv[0], 0, 0);
2701   UNUSED_PARAMETER(argc);
2702   decimal_result(context, p);
2703   decimal_free(p);
2704 }
2705 
2706 /*
2707 ** Compare to Decimal objects.  Return negative, 0, or positive if the
2708 ** first object is less than, equal to, or greater than the second.
2709 **
2710 ** Preconditions for this routine:
2711 **
2712 **    pA!=0
2713 **    pA->isNull==0
2714 **    pB!=0
2715 **    pB->isNull==0
2716 */
2717 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
2718   int nASig, nBSig, rc, n;
2719   if( pA->sign!=pB->sign ){
2720     return pA->sign ? -1 : +1;
2721   }
2722   if( pA->sign ){
2723     const Decimal *pTemp = pA;
2724     pA = pB;
2725     pB = pTemp;
2726   }
2727   nASig = pA->nDigit - pA->nFrac;
2728   nBSig = pB->nDigit - pB->nFrac;
2729   if( nASig!=nBSig ){
2730     return nASig - nBSig;
2731   }
2732   n = pA->nDigit;
2733   if( n>pB->nDigit ) n = pB->nDigit;
2734   rc = memcmp(pA->a, pB->a, n);
2735   if( rc==0 ){
2736     rc = pA->nDigit - pB->nDigit;
2737   }
2738   return rc;
2739 }
2740 
2741 /*
2742 ** SQL Function:   decimal_cmp(X, Y)
2743 **
2744 ** Return negative, zero, or positive if X is less then, equal to, or
2745 ** greater than Y.
2746 */
2747 static void decimalCmpFunc(
2748   sqlite3_context *context,
2749   int argc,
2750   sqlite3_value **argv
2751 ){
2752   Decimal *pA = 0, *pB = 0;
2753   int rc;
2754 
2755   UNUSED_PARAMETER(argc);
2756   pA = decimal_new(context, argv[0], 0, 0);
2757   if( pA==0 || pA->isNull ) goto cmp_done;
2758   pB = decimal_new(context, argv[1], 0, 0);
2759   if( pB==0 || pB->isNull ) goto cmp_done;
2760   rc = decimal_cmp(pA, pB);
2761   if( rc<0 ) rc = -1;
2762   else if( rc>0 ) rc = +1;
2763   sqlite3_result_int(context, rc);
2764 cmp_done:
2765   decimal_free(pA);
2766   decimal_free(pB);
2767 }
2768 
2769 /*
2770 ** Expand the Decimal so that it has a least nDigit digits and nFrac
2771 ** digits to the right of the decimal point.
2772 */
2773 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
2774   int nAddSig;
2775   int nAddFrac;
2776   if( p==0 ) return;
2777   nAddFrac = nFrac - p->nFrac;
2778   nAddSig = (nDigit - p->nDigit) - nAddFrac;
2779   if( nAddFrac==0 && nAddSig==0 ) return;
2780   p->a = sqlite3_realloc64(p->a, nDigit+1);
2781   if( p->a==0 ){
2782     p->oom = 1;
2783     return;
2784   }
2785   if( nAddSig ){
2786     memmove(p->a+nAddSig, p->a, p->nDigit);
2787     memset(p->a, 0, nAddSig);
2788     p->nDigit += nAddSig;
2789   }
2790   if( nAddFrac ){
2791     memset(p->a+p->nDigit, 0, nAddFrac);
2792     p->nDigit += nAddFrac;
2793     p->nFrac += nAddFrac;
2794   }
2795 }
2796 
2797 /*
2798 ** Add the value pB into pA.
2799 **
2800 ** Both pA and pB might become denormalized by this routine.
2801 */
2802 static void decimal_add(Decimal *pA, Decimal *pB){
2803   int nSig, nFrac, nDigit;
2804   int i, rc;
2805   if( pA==0 ){
2806     return;
2807   }
2808   if( pA->oom || pB==0 || pB->oom ){
2809     pA->oom = 1;
2810     return;
2811   }
2812   if( pA->isNull || pB->isNull ){
2813     pA->isNull = 1;
2814     return;
2815   }
2816   nSig = pA->nDigit - pA->nFrac;
2817   if( nSig && pA->a[0]==0 ) nSig--;
2818   if( nSig<pB->nDigit-pB->nFrac ){
2819     nSig = pB->nDigit - pB->nFrac;
2820   }
2821   nFrac = pA->nFrac;
2822   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
2823   nDigit = nSig + nFrac + 1;
2824   decimal_expand(pA, nDigit, nFrac);
2825   decimal_expand(pB, nDigit, nFrac);
2826   if( pA->oom || pB->oom ){
2827     pA->oom = 1;
2828   }else{
2829     if( pA->sign==pB->sign ){
2830       int carry = 0;
2831       for(i=nDigit-1; i>=0; i--){
2832         int x = pA->a[i] + pB->a[i] + carry;
2833         if( x>=10 ){
2834           carry = 1;
2835           pA->a[i] = x - 10;
2836         }else{
2837           carry = 0;
2838           pA->a[i] = x;
2839         }
2840       }
2841     }else{
2842       signed char *aA, *aB;
2843       int borrow = 0;
2844       rc = memcmp(pA->a, pB->a, nDigit);
2845       if( rc<0 ){
2846         aA = pB->a;
2847         aB = pA->a;
2848         pA->sign = !pA->sign;
2849       }else{
2850         aA = pA->a;
2851         aB = pB->a;
2852       }
2853       for(i=nDigit-1; i>=0; i--){
2854         int x = aA[i] - aB[i] - borrow;
2855         if( x<0 ){
2856           pA->a[i] = x+10;
2857           borrow = 1;
2858         }else{
2859           pA->a[i] = x;
2860           borrow = 0;
2861         }
2862       }
2863     }
2864   }
2865 }
2866 
2867 /*
2868 ** Compare text in decimal order.
2869 */
2870 static int decimalCollFunc(
2871   void *notUsed,
2872   int nKey1, const void *pKey1,
2873   int nKey2, const void *pKey2
2874 ){
2875   const unsigned char *zA = (const unsigned char*)pKey1;
2876   const unsigned char *zB = (const unsigned char*)pKey2;
2877   Decimal *pA = decimal_new(0, 0, nKey1, zA);
2878   Decimal *pB = decimal_new(0, 0, nKey2, zB);
2879   int rc;
2880   UNUSED_PARAMETER(notUsed);
2881   if( pA==0 || pB==0 ){
2882     rc = 0;
2883   }else{
2884     rc = decimal_cmp(pA, pB);
2885   }
2886   decimal_free(pA);
2887   decimal_free(pB);
2888   return rc;
2889 }
2890 
2891 
2892 /*
2893 ** SQL Function:   decimal_add(X, Y)
2894 **                 decimal_sub(X, Y)
2895 **
2896 ** Return the sum or difference of X and Y.
2897 */
2898 static void decimalAddFunc(
2899   sqlite3_context *context,
2900   int argc,
2901   sqlite3_value **argv
2902 ){
2903   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2904   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2905   UNUSED_PARAMETER(argc);
2906   decimal_add(pA, pB);
2907   decimal_result(context, pA);
2908   decimal_free(pA);
2909   decimal_free(pB);
2910 }
2911 static void decimalSubFunc(
2912   sqlite3_context *context,
2913   int argc,
2914   sqlite3_value **argv
2915 ){
2916   Decimal *pA = decimal_new(context, argv[0], 0, 0);
2917   Decimal *pB = decimal_new(context, argv[1], 0, 0);
2918   UNUSED_PARAMETER(argc);
2919   if( pB ){
2920     pB->sign = !pB->sign;
2921     decimal_add(pA, pB);
2922     decimal_result(context, pA);
2923   }
2924   decimal_free(pA);
2925   decimal_free(pB);
2926 }
2927 
2928 /* Aggregate funcion:   decimal_sum(X)
2929 **
2930 ** Works like sum() except that it uses decimal arithmetic for unlimited
2931 ** precision.
2932 */
2933 static void decimalSumStep(
2934   sqlite3_context *context,
2935   int argc,
2936   sqlite3_value **argv
2937 ){
2938   Decimal *p;
2939   Decimal *pArg;
2940   UNUSED_PARAMETER(argc);
2941   p = sqlite3_aggregate_context(context, sizeof(*p));
2942   if( p==0 ) return;
2943   if( !p->isInit ){
2944     p->isInit = 1;
2945     p->a = sqlite3_malloc(2);
2946     if( p->a==0 ){
2947       p->oom = 1;
2948     }else{
2949       p->a[0] = 0;
2950     }
2951     p->nDigit = 1;
2952     p->nFrac = 0;
2953   }
2954   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2955   pArg = decimal_new(context, argv[0], 0, 0);
2956   decimal_add(p, pArg);
2957   decimal_free(pArg);
2958 }
2959 static void decimalSumInverse(
2960   sqlite3_context *context,
2961   int argc,
2962   sqlite3_value **argv
2963 ){
2964   Decimal *p;
2965   Decimal *pArg;
2966   UNUSED_PARAMETER(argc);
2967   p = sqlite3_aggregate_context(context, sizeof(*p));
2968   if( p==0 ) return;
2969   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2970   pArg = decimal_new(context, argv[0], 0, 0);
2971   if( pArg ) pArg->sign = !pArg->sign;
2972   decimal_add(p, pArg);
2973   decimal_free(pArg);
2974 }
2975 static void decimalSumValue(sqlite3_context *context){
2976   Decimal *p = sqlite3_aggregate_context(context, 0);
2977   if( p==0 ) return;
2978   decimal_result(context, p);
2979 }
2980 static void decimalSumFinalize(sqlite3_context *context){
2981   Decimal *p = sqlite3_aggregate_context(context, 0);
2982   if( p==0 ) return;
2983   decimal_result(context, p);
2984   decimal_clear(p);
2985 }
2986 
2987 /*
2988 ** SQL Function:   decimal_mul(X, Y)
2989 **
2990 ** Return the product of X and Y.
2991 **
2992 ** All significant digits after the decimal point are retained.
2993 ** Trailing zeros after the decimal point are omitted as long as
2994 ** the number of digits after the decimal point is no less than
2995 ** either the number of digits in either input.
2996 */
2997 static void decimalMulFunc(
2998   sqlite3_context *context,
2999   int argc,
3000   sqlite3_value **argv
3001 ){
3002   Decimal *pA = decimal_new(context, argv[0], 0, 0);
3003   Decimal *pB = decimal_new(context, argv[1], 0, 0);
3004   signed char *acc = 0;
3005   int i, j, k;
3006   int minFrac;
3007   UNUSED_PARAMETER(argc);
3008   if( pA==0 || pA->oom || pA->isNull
3009    || pB==0 || pB->oom || pB->isNull
3010   ){
3011     goto mul_end;
3012   }
3013   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
3014   if( acc==0 ){
3015     sqlite3_result_error_nomem(context);
3016     goto mul_end;
3017   }
3018   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
3019   minFrac = pA->nFrac;
3020   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
3021   for(i=pA->nDigit-1; i>=0; i--){
3022     signed char f = pA->a[i];
3023     int carry = 0, x;
3024     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
3025       x = acc[k] + f*pB->a[j] + carry;
3026       acc[k] = x%10;
3027       carry = x/10;
3028     }
3029     x = acc[k] + carry;
3030     acc[k] = x%10;
3031     acc[k-1] += x/10;
3032   }
3033   sqlite3_free(pA->a);
3034   pA->a = acc;
3035   acc = 0;
3036   pA->nDigit += pB->nDigit + 2;
3037   pA->nFrac += pB->nFrac;
3038   pA->sign ^= pB->sign;
3039   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
3040     pA->nFrac--;
3041     pA->nDigit--;
3042   }
3043   decimal_result(context, pA);
3044 
3045 mul_end:
3046   sqlite3_free(acc);
3047   decimal_free(pA);
3048   decimal_free(pB);
3049 }
3050 
3051 #ifdef _WIN32
3052 
3053 #endif
3054 int sqlite3_decimal_init(
3055   sqlite3 *db,
3056   char **pzErrMsg,
3057   const sqlite3_api_routines *pApi
3058 ){
3059   int rc = SQLITE_OK;
3060   static const struct {
3061     const char *zFuncName;
3062     int nArg;
3063     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3064   } aFunc[] = {
3065     { "decimal",       1,   decimalFunc        },
3066     { "decimal_cmp",   2,   decimalCmpFunc     },
3067     { "decimal_add",   2,   decimalAddFunc     },
3068     { "decimal_sub",   2,   decimalSubFunc     },
3069     { "decimal_mul",   2,   decimalMulFunc     },
3070   };
3071   unsigned int i;
3072   (void)pzErrMsg;  /* Unused parameter */
3073 
3074   SQLITE_EXTENSION_INIT2(pApi);
3075 
3076   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
3077     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
3078                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
3079                    0, aFunc[i].xFunc, 0, 0);
3080   }
3081   if( rc==SQLITE_OK ){
3082     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
3083                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
3084                    decimalSumStep, decimalSumFinalize,
3085                    decimalSumValue, decimalSumInverse, 0);
3086   }
3087   if( rc==SQLITE_OK ){
3088     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
3089                                   0, decimalCollFunc);
3090   }
3091   return rc;
3092 }
3093 
3094 /************************* End ../ext/misc/decimal.c ********************/
3095 #undef sqlite3_base_init
3096 #define sqlite3_base_init sqlite3_base64_init
3097 /************************* Begin ../ext/misc/base64.c ******************/
3098 /*
3099 ** 2022-11-18
3100 **
3101 ** The author disclaims copyright to this source code.  In place of
3102 ** a legal notice, here is a blessing:
3103 **
3104 **    May you do good and not evil.
3105 **    May you find forgiveness for yourself and forgive others.
3106 **    May you share freely, never taking more than you give.
3107 **
3108 *************************************************************************
3109 **
3110 ** This is a SQLite extension for converting in either direction
3111 ** between a (binary) blob and base64 text. Base64 can transit a
3112 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3113 ** written as TCL brace-enclosed literals or SQL string literals,
3114 ** and can be used unmodified in XML-like documents.
3115 **
3116 ** This is an independent implementation of conversions specified in
3117 ** RFC 4648, done on the above date by the author (Larry Brasfield)
3118 ** who thereby has the right to put this into the public domain.
3119 **
3120 ** The conversions meet RFC 4648 requirements, provided that this
3121 ** C source specifies that line-feeds are included in the encoded
3122 ** data to limit visible line lengths to 72 characters and to
3123 ** terminate any encoded blob having non-zero length.
3124 **
3125 ** Length limitations are not imposed except that the runtime
3126 ** SQLite string or blob length limits are respected. Otherwise,
3127 ** any length binary sequence can be represented and recovered.
3128 ** Generated base64 sequences, with their line-feeds included,
3129 ** can be concatenated; the result converted back to binary will
3130 ** be the concatenation of the represented binary sequences.
3131 **
3132 ** This SQLite3 extension creates a function, base64(x), which
3133 ** either: converts text x containing base64 to a returned blob;
3134 ** or converts a blob x to returned text containing base64. An
3135 ** error will be thrown for other input argument types.
3136 **
3137 ** This code relies on UTF-8 encoding only with respect to the
3138 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
3139 ** It will fail miserably if somehow made to try to convert EBCDIC.
3140 ** Because it is table-driven, it could be enhanced to handle that,
3141 ** but the world and SQLite have moved on from that anachronism.
3142 **
3143 ** To build the extension:
3144 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3145 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
3146 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
3147 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
3148 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
3149 */
3150 
3151 #include <assert.h>
3152 
3153 /* #include "sqlite3ext.h" */
3154 
3155 #ifndef deliberate_fall_through
3156 /* Quiet some compilers about some of our intentional code. */
3157 # if GCC_VERSION>=7000000
3158 #  define deliberate_fall_through __attribute__((fallthrough));
3159 # else
3160 #  define deliberate_fall_through
3161 # endif
3162 #endif
3163 
3164 SQLITE_EXTENSION_INIT1;
3165 
3166 #define PC 0x80 /* pad character */
3167 #define WS 0x81 /* whitespace */
3168 #define ND 0x82 /* Not above or digit-value */
3169 #define PAD_CHAR '='
3170 
3171 #ifndef U8_TYPEDEF
3172 /* typedef unsigned char u8; */
3173 #define U8_TYPEDEF
3174 #endif
3175 
3176 static const u8 b64DigitValues[128] = {
3177   /*                             HT LF VT  FF CR       */
3178     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
3179   /*                                                US */
3180     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
3181   /*sp                                  +            / */
3182     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
3183   /* 0  1            5            9            =       */
3184     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
3185   /*    A                                            O */
3186     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
3187   /* P                               Z                 */
3188     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
3189   /*    a                                            o */
3190     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
3191   /* p                               z                 */
3192     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
3193 };
3194 
3195 static const char b64Numerals[64+1]
3196 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3197 
3198 #define BX_DV_PROTO(c) \
3199   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
3200 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
3201 #define IS_BX_WS(bdp) ((bdp)==WS)
3202 #define IS_BX_PAD(bdp) ((bdp)==PC)
3203 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
3204 /* Width of base64 lines. Should be an integer multiple of 4. */
3205 #define B64_DARK_MAX 72
3206 
3207 /* Encode a byte buffer into base64 text with linefeeds appended to limit
3208 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
3209 */
3210 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
3211   int nCol = 0;
3212   while( nbIn >= 3 ){
3213     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
3214     pOut[0] = BX_NUMERAL(pIn[0]>>2);
3215     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
3216     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
3217     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
3218     pOut += 4;
3219     nbIn -= 3;
3220     pIn += 3;
3221     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
3222       *pOut++ = '\n';
3223       nCol = 0;
3224     }
3225   }
3226   if( nbIn > 0 ){
3227     signed char nco = nbIn+1;
3228     int nbe;
3229     unsigned long qv = *pIn++;
3230     for( nbe=1; nbe<3; ++nbe ){
3231       qv <<= 8;
3232       if( nbe<nbIn ) qv |= *pIn++;
3233     }
3234     for( nbe=3; nbe>=0; --nbe ){
3235       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
3236       qv >>= 6;
3237       pOut[nbe] = ce;
3238     }
3239     pOut += 4;
3240     *pOut++ = '\n';
3241   }
3242   *pOut = 0;
3243   return pOut;
3244 }
3245 
3246 /* Skip over text which is not base64 numeral(s). */
3247 static char * skipNonB64( char *s ){
3248   char c;
3249   while( (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
3250   return s;
3251 }
3252 
3253 /* Decode base64 text into a byte buffer. */
3254 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
3255   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3256   while( ncIn>0 && *pIn!=PAD_CHAR ){
3257     static signed char nboi[] = { 0, 0, 1, 2, 3 };
3258     char *pUse = skipNonB64(pIn);
3259     unsigned long qv = 0L;
3260     int nti, nbo, nac;
3261     ncIn -= (pUse - pIn);
3262     pIn = pUse;
3263     nti = (ncIn>4)? 4 : ncIn;
3264     ncIn -= nti;
3265     nbo = nboi[nti];
3266     if( nbo==0 ) break;
3267     for( nac=0; nac<4; ++nac ){
3268       char c = (nac<nti)? *pIn++ : b64Numerals[0];
3269       u8 bdp = BX_DV_PROTO(c);
3270       switch( bdp ){
3271       case ND:
3272         /*  Treat dark non-digits as pad, but they terminate decode too. */
3273         ncIn = 0;
3274         deliberate_fall_through;
3275       case WS:
3276         /* Treat whitespace as pad and terminate this group.*/
3277         nti = nac;
3278         deliberate_fall_through;
3279       case PC:
3280         bdp = 0;
3281         --nbo;
3282         deliberate_fall_through;
3283       default: /* bdp is the digit value. */
3284         qv = qv<<6 | bdp;
3285         break;
3286       }
3287     }
3288     switch( nbo ){
3289     case 3:
3290       pOut[2] = (qv) & 0xff;
3291     case 2:
3292       pOut[1] = (qv>>8) & 0xff;
3293     case 1:
3294       pOut[0] = (qv>>16) & 0xff;
3295     }
3296     pOut += nbo;
3297   }
3298   return pOut;
3299 }
3300 
3301 /* This function does the work for the SQLite base64(x) UDF. */
3302 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
3303   int nb, nc, nv = sqlite3_value_bytes(av[0]);
3304   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
3305                             SQLITE_LIMIT_LENGTH, -1);
3306   char *cBuf;
3307   u8 *bBuf;
3308   assert(na==1);
3309   switch( sqlite3_value_type(av[0]) ){
3310   case SQLITE_BLOB:
3311     nb = nv;
3312     nc = 4*(nv+2/3); /* quads needed */
3313     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
3314     if( nvMax < nc ){
3315       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
3316       return;
3317     }
3318     cBuf = sqlite3_malloc(nc);
3319     if( !cBuf ) goto memFail;
3320     bBuf = (u8*)sqlite3_value_blob(av[0]);
3321     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
3322     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
3323     break;
3324   case SQLITE_TEXT:
3325     nc = nv;
3326     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
3327     if( nvMax < nb ){
3328       sqlite3_result_error(context, "blob from base64 may be too big", -1);
3329       return;
3330     }else if( nb<1 ){
3331       nb = 1;
3332     }
3333     bBuf = sqlite3_malloc(nb);
3334     if( !bBuf ) goto memFail;
3335     cBuf = (char *)sqlite3_value_text(av[0]);
3336     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
3337     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
3338     break;
3339   default:
3340     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
3341     return;
3342   }
3343   return;
3344  memFail:
3345   sqlite3_result_error(context, "base64 OOM", -1);
3346 }
3347 
3348 /*
3349 ** Establish linkage to running SQLite library.
3350 */
3351 #ifndef SQLITE_SHELL_EXTFUNCS
3352 #ifdef _WIN32
3353 
3354 #endif
3355 int sqlite3_base_init
3356 #else
3357 static int sqlite3_base64_init
3358 #endif
3359 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
3360   SQLITE_EXTENSION_INIT2(pApi);
3361   (void)pzErr;
3362   return sqlite3_create_function
3363     (db, "base64", 1,
3364      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
3365      0, base64, 0, 0);
3366 }
3367 
3368 /*
3369 ** Define some macros to allow this extension to be built into the shell
3370 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
3371 ** allows shell.c, as distributed, to have this extension built in.
3372 */
3373 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
3374 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
3375 
3376 /************************* End ../ext/misc/base64.c ********************/
3377 #undef sqlite3_base_init
3378 #define sqlite3_base_init sqlite3_base85_init
3379 #define OMIT_BASE85_CHECKER
3380 /************************* Begin ../ext/misc/base85.c ******************/
3381 /*
3382 ** 2022-11-16
3383 **
3384 ** The author disclaims copyright to this source code.  In place of
3385 ** a legal notice, here is a blessing:
3386 **
3387 **    May you do good and not evil.
3388 **    May you find forgiveness for yourself and forgive others.
3389 **    May you share freely, never taking more than you give.
3390 **
3391 *************************************************************************
3392 **
3393 ** This is a utility for converting binary to base85 or vice-versa.
3394 ** It can be built as a standalone program or an SQLite3 extension.
3395 **
3396 ** Much like base64 representations, base85 can be sent through a
3397 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3398 ** written as TCL brace-enclosed literals or SQL string literals.
3399 ** It is not suited for unmodified use in XML-like documents.
3400 **
3401 ** The encoding used resembles Ascii85, but was devised by the author
3402 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
3403 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
3404 ** Further, this is an independent implementation of a base85 system.
3405 ** Hence, the author has rightfully put this into the public domain.
3406 **
3407 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
3408 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
3409 ** in code order representing digit values 0 to 84 (base 10.)
3410 **
3411 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
3412 ** are represented as 5-digit base85 numbers with MS to LS digit
3413 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
3414 ** still big-endian but 8-24 bit values. (Using big-endian yields
3415 ** the simplest transition to byte groups smaller than 4 bytes.
3416 ** These byte groups can also be considered base-256 numbers.)
3417 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
3418 ** No pad characters are used; Encoded base85 numeral sequence
3419 ** (aka "group") length maps 1-to-1 to the decoded binary length.
3420 **
3421 ** Any character not in the base85 numeral set delimits groups.
3422 ** When base85 is streamed or stored in containers of indefinite
3423 ** size, newline is used to separate it into sub-sequences of no
3424 ** more than 80 digits so that fgets() can be used to read it.
3425 **
3426 ** Length limitations are not imposed except that the runtime
3427 ** SQLite string or blob length limits are respected. Otherwise,
3428 ** any length binary sequence can be represented and recovered.
3429 ** Base85 sequences can be concatenated by separating them with
3430 ** a non-base85 character; the conversion to binary will then
3431 ** be the concatenation of the represented binary sequences.
3432 
3433 ** The standalone program either converts base85 on stdin to create
3434 ** a binary file or converts a binary file to base85 on stdout.
3435 ** Read or make it blurt its help for invocation details.
3436 **
3437 ** The SQLite3 extension creates a function, base85(x), which will
3438 ** either convert text base85 to a blob or a blob to text base85
3439 ** and return the result (or throw an error for other types.)
3440 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
3441 ** function, is_base85(t), which returns 1 iff the text t contains
3442 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
3443 **
3444 ** To build the extension:
3445 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3446 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
3447 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
3448 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
3449 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
3450 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
3451 **
3452 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
3453 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
3454 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
3455 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
3456 */
3457 
3458 #include <stdio.h>
3459 #include <memory.h>
3460 #include <string.h>
3461 #include <assert.h>
3462 #ifndef OMIT_BASE85_CHECKER
3463 # include <ctype.h>
3464 #endif
3465 
3466 #ifndef BASE85_STANDALONE
3467 
3468 /* # include "sqlite3ext.h" */
3469 
3470 SQLITE_EXTENSION_INIT1;
3471 
3472 #else
3473 
3474 # ifdef _WIN32
3475 #  include <io.h>
3476 #  include <fcntl.h>
3477 # else
3478 #  define setmode(fd,m)
3479 # endif
3480 
3481 static char *zHelp =
3482   "Usage: base85 <dirFlag> <binFile>\n"
3483   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
3484   "   content to be converted to/from base85 on stdout/stdin.\n"
3485   " <binFile> names a binary file to be rendered or created.\n"
3486   "   Or, the name '-' refers to the stdin or stdout stream.\n"
3487   ;
3488 
3489 static void sayHelp(){
3490   printf("%s", zHelp);
3491 }
3492 #endif
3493 
3494 #ifndef U8_TYPEDEF
3495 /* typedef unsigned char u8; */
3496 #define U8_TYPEDEF
3497 #endif
3498 
3499 /* Classify c according to interval within USASCII set w.r.t. base85
3500  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
3501  */
3502 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
3503 
3504 /* Provide digitValue to b85Numeral offset as a function of above class. */
3505 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
3506 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
3507 
3508 /* Say whether c is a base85 numeral. */
3509 #define IS_B85( c ) (B85_CLASS(c) & 1)
3510 
3511 #if 0 /* Not used, */
3512 static u8 base85DigitValue( char c ){
3513   u8 dv = (u8)(c - '#');
3514   if( dv>87 ) return 0xff;
3515   return (dv > 3)? dv-3 : dv;
3516 }
3517 #endif
3518 
3519 /* Width of base64 lines. Should be an integer multiple of 5. */
3520 #define B85_DARK_MAX 80
3521 
3522 
3523 static char * skipNonB85( char *s ){
3524   char c;
3525   while( (c = *s) && !IS_B85(c) ) ++s;
3526   return s;
3527 }
3528 
3529 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
3530  * Do not use the macro form with argument expression having a side-effect.*/
3531 #if 0
3532 static char base85Numeral( u8 b ){
3533   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
3534 }
3535 #else
3536 # define base85Numeral( dn )\
3537   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
3538 #endif
3539 
3540 static char *putcs(char *pc, char *s){
3541   char c;
3542   while( (c = *s++)!=0 ) *pc++ = c;
3543   return pc;
3544 }
3545 
3546 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
3547 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
3548 ** or to terminate the last group (to aid concatenation.)
3549 */
3550 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
3551   int nCol = 0;
3552   while( nbIn >= 4 ){
3553     int nco = 5;
3554     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
3555                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
3556     while( nco > 0 ){
3557       unsigned nqv = (unsigned)(qbv/85UL);
3558       unsigned char dv = qbv - 85UL*nqv;
3559       qbv = nqv;
3560       pOut[--nco] = base85Numeral(dv);
3561     }
3562     nbIn -= 4;
3563     pIn += 4;
3564     pOut += 5;
3565     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
3566       pOut = putcs(pOut, pSep);
3567       nCol = 0;
3568     }
3569   }
3570   if( nbIn > 0 ){
3571     int nco = nbIn + 1;
3572     unsigned long qv = *pIn++;
3573     int nbe = 1;
3574     while( nbe++ < nbIn ){
3575       qv = (qv<<8) | *pIn++;
3576     }
3577     nCol += nco;
3578     while( nco > 0 ){
3579       u8 dv = (u8)(qv % 85);
3580       qv /= 85;
3581       pOut[--nco] = base85Numeral(dv);
3582     }
3583     pOut += (nbIn+1);
3584   }
3585   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
3586   *pOut = 0;
3587   return pOut;
3588 }
3589 
3590 /* Decode base85 text into a byte buffer. */
3591 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
3592   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3593   while( ncIn>0 ){
3594     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
3595     char *pUse = skipNonB85(pIn);
3596     unsigned long qv = 0L;
3597     int nti, nbo;
3598     ncIn -= (pUse - pIn);
3599     pIn = pUse;
3600     nti = (ncIn>5)? 5 : ncIn;
3601     nbo = nboi[nti];
3602     if( nbo==0 ) break;
3603     while( nti>0 ){
3604       char c = *pIn++;
3605       u8 cdo = B85_DNOS(c);
3606       --ncIn;
3607       if( cdo==0 ) break;
3608       qv = 85 * qv + (c - cdo);
3609       --nti;
3610     }
3611     nbo -= nti; /* Adjust for early (non-digit) end of group. */
3612     switch( nbo ){
3613     case 4:
3614       *pOut++ = (qv >> 24)&0xff;
3615     case 3:
3616       *pOut++ = (qv >> 16)&0xff;
3617     case 2:
3618       *pOut++ = (qv >> 8)&0xff;
3619     case 1:
3620       *pOut++ = qv&0xff;
3621     case 0:
3622       break;
3623     }
3624   }
3625   return pOut;
3626 }
3627 
3628 #ifndef OMIT_BASE85_CHECKER
3629 /* Say whether input char sequence is all (base85 and/or whitespace).*/
3630 static int allBase85( char *p, int len ){
3631   char c;
3632   while( len-- > 0 && (c = *p++) != 0 ){
3633     if( !IS_B85(c) && !isspace(c) ) return 0;
3634   }
3635   return 1;
3636 }
3637 #endif
3638 
3639 #ifndef BASE85_STANDALONE
3640 
3641 # ifndef OMIT_BASE85_CHECKER
3642 /* This function does the work for the SQLite is_base85(t) UDF. */
3643 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
3644   assert(na==1);
3645   switch( sqlite3_value_type(av[0]) ){
3646   case SQLITE_TEXT:
3647     {
3648       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
3649                           sqlite3_value_bytes(av[0]) );
3650       sqlite3_result_int(context, rv);
3651     }
3652     break;
3653   case SQLITE_NULL:
3654     sqlite3_result_null(context);
3655     break;
3656   default:
3657     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
3658     return;
3659   }
3660 }
3661 # endif
3662 
3663 /* This function does the work for the SQLite base85(x) UDF. */
3664 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
3665   int nb, nc, nv = sqlite3_value_bytes(av[0]);
3666   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
3667                             SQLITE_LIMIT_LENGTH, -1);
3668   char *cBuf;
3669   u8 *bBuf;
3670   assert(na==1);
3671   switch( sqlite3_value_type(av[0]) ){
3672   case SQLITE_BLOB:
3673     nb = nv;
3674     /*    ulongs    tail   newlines  tailenc+nul*/
3675     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
3676     if( nvMax < nc ){
3677       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
3678       return;
3679     }
3680     cBuf = sqlite3_malloc(nc);
3681     if( !cBuf ) goto memFail;
3682     bBuf = (u8*)sqlite3_value_blob(av[0]);
3683     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
3684     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
3685     break;
3686   case SQLITE_TEXT:
3687     nc = nv;
3688     nb = 4*(nv/5) + nv%5; /* may overestimate */
3689     if( nvMax < nb ){
3690       sqlite3_result_error(context, "blob from base85 may be too big", -1);
3691       return;
3692     }else if( nb<1 ){
3693       nb = 1;
3694     }
3695     bBuf = sqlite3_malloc(nb);
3696     if( !bBuf ) goto memFail;
3697     cBuf = (char *)sqlite3_value_text(av[0]);
3698     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
3699     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
3700     break;
3701   default:
3702     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
3703     return;
3704   }
3705   return;
3706  memFail:
3707   sqlite3_result_error(context, "base85 OOM", -1);
3708 }
3709 
3710 /*
3711 ** Establish linkage to running SQLite library.
3712 */
3713 #ifndef SQLITE_SHELL_EXTFUNCS
3714 #ifdef _WIN32
3715 
3716 #endif
3717 int sqlite3_base_init
3718 #else
3719 static int sqlite3_base85_init
3720 #endif
3721 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
3722   SQLITE_EXTENSION_INIT2(pApi);
3723   (void)pzErr;
3724 # ifndef OMIT_BASE85_CHECKER
3725   {
3726     int rc = sqlite3_create_function
3727       (db, "is_base85", 1,
3728        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
3729        0, is_base85, 0, 0);
3730     if( rc!=SQLITE_OK ) return rc;
3731   }
3732 # endif
3733   return sqlite3_create_function
3734     (db, "base85", 1,
3735      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
3736      0, base85, 0, 0);
3737 }
3738 
3739 /*
3740 ** Define some macros to allow this extension to be built into the shell
3741 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
3742 ** allows shell.c, as distributed, to have this extension built in.
3743 */
3744 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
3745 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
3746 
3747 #else /* standalone program */
3748 
3749 int main(int na, char *av[]){
3750   int cin;
3751   int rc = 0;
3752   u8 bBuf[4*(B85_DARK_MAX/5)];
3753   char cBuf[5*(sizeof(bBuf)/4)+2];
3754   size_t nio;
3755 # ifndef OMIT_BASE85_CHECKER
3756   int b85Clean = 1;
3757 # endif
3758   char rw;
3759   FILE *fb = 0, *foc = 0;
3760   char fmode[3] = "xb";
3761   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
3762     sayHelp();
3763     return 0;
3764   }
3765   fmode[0] = rw;
3766   if( av[2][0]=='-' && av[2][1]==0 ){
3767     switch( rw ){
3768     case 'r':
3769       fb = stdin;
3770       setmode(fileno(stdin), O_BINARY);
3771       break;
3772     case 'w':
3773       fb = stdout;
3774       setmode(fileno(stdout), O_BINARY);
3775       break;
3776     }
3777   }else{
3778     fb = fopen(av[2], fmode);
3779     foc = fb;
3780   }
3781   if( !fb ){
3782     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
3783     rc = 1;
3784   }else{
3785     switch( rw ){
3786     case 'r':
3787       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
3788         toBase85( bBuf, (int)nio, cBuf, 0 );
3789         fprintf(stdout, "%s\n", cBuf);
3790       }
3791       break;
3792     case 'w':
3793       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
3794         int nc = strlen(cBuf);
3795         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
3796         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
3797 # ifndef OMIT_BASE85_CHECKER
3798         b85Clean &= allBase85( cBuf, nc );
3799 # endif
3800       }
3801       break;
3802     default:
3803       sayHelp();
3804       rc = 1;
3805     }
3806     if( foc ) fclose(foc);
3807   }
3808 # ifndef OMIT_BASE85_CHECKER
3809   if( !b85Clean ){
3810     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
3811   }
3812 # endif
3813   return rc;
3814 }
3815 
3816 #endif
3817 
3818 /************************* End ../ext/misc/base85.c ********************/
3819 /************************* Begin ../ext/misc/ieee754.c ******************/
3820 /*
3821 ** 2013-04-17
3822 **
3823 ** The author disclaims copyright to this source code.  In place of
3824 ** a legal notice, here is a blessing:
3825 **
3826 **    May you do good and not evil.
3827 **    May you find forgiveness for yourself and forgive others.
3828 **    May you share freely, never taking more than you give.
3829 **
3830 ******************************************************************************
3831 **
3832 ** This SQLite extension implements functions for the exact display
3833 ** and input of IEEE754 Binary64 floating-point numbers.
3834 **
3835 **   ieee754(X)
3836 **   ieee754(Y,Z)
3837 **
3838 ** In the first form, the value X should be a floating-point number.
3839 ** The function will return a string of the form 'ieee754(Y,Z)' where
3840 ** Y and Z are integers such that X==Y*pow(2,Z).
3841 **
3842 ** In the second form, Y and Z are integers which are the mantissa and
3843 ** base-2 exponent of a new floating point number.  The function returns
3844 ** a floating-point value equal to Y*pow(2,Z).
3845 **
3846 ** Examples:
3847 **
3848 **     ieee754(2.0)             ->     'ieee754(2,0)'
3849 **     ieee754(45.25)           ->     'ieee754(181,-2)'
3850 **     ieee754(2, 0)            ->     2.0
3851 **     ieee754(181, -2)         ->     45.25
3852 **
3853 ** Two additional functions break apart the one-argument ieee754()
3854 ** result into separate integer values:
3855 **
3856 **     ieee754_mantissa(45.25)  ->     181
3857 **     ieee754_exponent(45.25)  ->     -2
3858 **
3859 ** These functions convert binary64 numbers into blobs and back again.
3860 **
3861 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
3862 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
3863 **
3864 ** In all single-argument functions, if the argument is an 8-byte blob
3865 ** then that blob is interpreted as a big-endian binary64 value.
3866 **
3867 **
3868 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
3869 ** -----------------------------------------------
3870 **
3871 ** This extension in combination with the separate 'decimal' extension
3872 ** can be used to compute the exact decimal representation of binary64
3873 ** values.  To begin, first compute a table of exponent values:
3874 **
3875 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
3876 **    WITH RECURSIVE c(x,v) AS (
3877 **      VALUES(0,'1')
3878 **      UNION ALL
3879 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
3880 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
3881 **    WITH RECURSIVE c(x,v) AS (
3882 **      VALUES(-1,'0.5')
3883 **      UNION ALL
3884 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
3885 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
3886 **
3887 ** Then, to compute the exact decimal representation of a floating
3888 ** point value (the value 47.49 is used in the example) do:
3889 **
3890 **    WITH c(n) AS (VALUES(47.49))
3891 **          ---------------^^^^^---- Replace with whatever you want
3892 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
3893 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
3894 **
3895 ** Here is a query to show various boundry values for the binary64
3896 ** number format:
3897 **
3898 **    WITH c(name,bin) AS (VALUES
3899 **       ('minimum positive value',        x'0000000000000001'),
3900 **       ('maximum subnormal value',       x'000fffffffffffff'),
3901 **       ('mininum positive nornal value', x'0010000000000000'),
3902 **       ('maximum value',                 x'7fefffffffffffff'))
3903 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
3904 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
3905 **
3906 */
3907 /* #include "sqlite3ext.h" */
3908 SQLITE_EXTENSION_INIT1
3909 #include <assert.h>
3910 #include <string.h>
3911 
3912 /* Mark a function parameter as unused, to suppress nuisance compiler
3913 ** warnings. */
3914 #ifndef UNUSED_PARAMETER
3915 # define UNUSED_PARAMETER(X)  (void)(X)
3916 #endif
3917 
3918 /*
3919 ** Implementation of the ieee754() function
3920 */
3921 static void ieee754func(
3922   sqlite3_context *context,
3923   int argc,
3924   sqlite3_value **argv
3925 ){
3926   if( argc==1 ){
3927     sqlite3_int64 m, a;
3928     double r;
3929     int e;
3930     int isNeg;
3931     char zResult[100];
3932     assert( sizeof(m)==sizeof(r) );
3933     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
3934      && sqlite3_value_bytes(argv[0])==sizeof(r)
3935     ){
3936       const unsigned char *x = sqlite3_value_blob(argv[0]);
3937       unsigned int i;
3938       sqlite3_uint64 v = 0;
3939       for(i=0; i<sizeof(r); i++){
3940         v = (v<<8) | x[i];
3941       }
3942       memcpy(&r, &v, sizeof(r));
3943     }else{
3944       r = sqlite3_value_double(argv[0]);
3945     }
3946     if( r<0.0 ){
3947       isNeg = 1;
3948       r = -r;
3949     }else{
3950       isNeg = 0;
3951     }
3952     memcpy(&a,&r,sizeof(a));
3953     if( a==0 ){
3954       e = 0;
3955       m = 0;
3956     }else{
3957       e = a>>52;
3958       m = a & ((((sqlite3_int64)1)<<52)-1);
3959       if( e==0 ){
3960         m <<= 1;
3961       }else{
3962         m |= ((sqlite3_int64)1)<<52;
3963       }
3964       while( e<1075 && m>0 && (m&1)==0 ){
3965         m >>= 1;
3966         e++;
3967       }
3968       if( isNeg ) m = -m;
3969     }
3970     switch( *(int*)sqlite3_user_data(context) ){
3971       case 0:
3972         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
3973                          m, e-1075);
3974         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
3975         break;
3976       case 1:
3977         sqlite3_result_int64(context, m);
3978         break;
3979       case 2:
3980         sqlite3_result_int(context, e-1075);
3981         break;
3982     }
3983   }else{
3984     sqlite3_int64 m, e, a;
3985     double r;
3986     int isNeg = 0;
3987     m = sqlite3_value_int64(argv[0]);
3988     e = sqlite3_value_int64(argv[1]);
3989 
3990     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
3991     if( e>10000 ){
3992       e = 10000;
3993     }else if( e<-10000 ){
3994       e = -10000;
3995     }
3996 
3997     if( m<0 ){
3998       isNeg = 1;
3999       m = -m;
4000       if( m<0 ) return;
4001     }else if( m==0 && e>-1000 && e<1000 ){
4002       sqlite3_result_double(context, 0.0);
4003       return;
4004     }
4005     while( (m>>32)&0xffe00000 ){
4006       m >>= 1;
4007       e++;
4008     }
4009     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
4010       m <<= 1;
4011       e--;
4012     }
4013     e += 1075;
4014     if( e<=0 ){
4015       /* Subnormal */
4016       if( 1-e >= 64 ){
4017         m = 0;
4018       }else{
4019         m >>= 1-e;
4020       }
4021       e = 0;
4022     }else if( e>0x7ff ){
4023       e = 0x7ff;
4024     }
4025     a = m & ((((sqlite3_int64)1)<<52)-1);
4026     a |= e<<52;
4027     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
4028     memcpy(&r, &a, sizeof(r));
4029     sqlite3_result_double(context, r);
4030   }
4031 }
4032 
4033 /*
4034 ** Functions to convert between blobs and floats.
4035 */
4036 static void ieee754func_from_blob(
4037   sqlite3_context *context,
4038   int argc,
4039   sqlite3_value **argv
4040 ){
4041   UNUSED_PARAMETER(argc);
4042   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
4043    && sqlite3_value_bytes(argv[0])==sizeof(double)
4044   ){
4045     double r;
4046     const unsigned char *x = sqlite3_value_blob(argv[0]);
4047     unsigned int i;
4048     sqlite3_uint64 v = 0;
4049     for(i=0; i<sizeof(r); i++){
4050       v = (v<<8) | x[i];
4051     }
4052     memcpy(&r, &v, sizeof(r));
4053     sqlite3_result_double(context, r);
4054   }
4055 }
4056 static void ieee754func_to_blob(
4057   sqlite3_context *context,
4058   int argc,
4059   sqlite3_value **argv
4060 ){
4061   UNUSED_PARAMETER(argc);
4062   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
4063    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
4064   ){
4065     double r = sqlite3_value_double(argv[0]);
4066     sqlite3_uint64 v;
4067     unsigned char a[sizeof(r)];
4068     unsigned int i;
4069     memcpy(&v, &r, sizeof(r));
4070     for(i=1; i<=sizeof(r); i++){
4071       a[sizeof(r)-i] = v&0xff;
4072       v >>= 8;
4073     }
4074     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
4075   }
4076 }
4077 
4078 
4079 #ifdef _WIN32
4080 
4081 #endif
4082 int sqlite3_ieee_init(
4083   sqlite3 *db,
4084   char **pzErrMsg,
4085   const sqlite3_api_routines *pApi
4086 ){
4087   static const struct {
4088     char *zFName;
4089     int nArg;
4090     int iAux;
4091     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4092   } aFunc[] = {
4093     { "ieee754",           1,   0, ieee754func },
4094     { "ieee754",           2,   0, ieee754func },
4095     { "ieee754_mantissa",  1,   1, ieee754func },
4096     { "ieee754_exponent",  1,   2, ieee754func },
4097     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
4098     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
4099 
4100   };
4101   unsigned int i;
4102   int rc = SQLITE_OK;
4103   SQLITE_EXTENSION_INIT2(pApi);
4104   (void)pzErrMsg;  /* Unused parameter */
4105   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
4106     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
4107                                SQLITE_UTF8|SQLITE_INNOCUOUS,
4108                                (void*)&aFunc[i].iAux,
4109                                aFunc[i].xFunc, 0, 0);
4110   }
4111   return rc;
4112 }
4113 
4114 /************************* End ../ext/misc/ieee754.c ********************/
4115 /************************* Begin ../ext/misc/series.c ******************/
4116 /*
4117 ** 2015-08-18
4118 **
4119 ** The author disclaims copyright to this source code.  In place of
4120 ** a legal notice, here is a blessing:
4121 **
4122 **    May you do good and not evil.
4123 **    May you find forgiveness for yourself and forgive others.
4124 **    May you share freely, never taking more than you give.
4125 **
4126 *************************************************************************
4127 **
4128 ** This file demonstrates how to create a table-valued-function using
4129 ** a virtual table.  This demo implements the generate_series() function
4130 ** which gives similar results to the eponymous function in PostgreSQL.
4131 ** Examples:
4132 **
4133 **      SELECT * FROM generate_series(0,100,5);
4134 **
4135 ** The query above returns integers from 0 through 100 counting by steps
4136 ** of 5.
4137 **
4138 **      SELECT * FROM generate_series(0,100);
4139 **
4140 ** Integers from 0 through 100 with a step size of 1.
4141 **
4142 **      SELECT * FROM generate_series(20) LIMIT 10;
4143 **
4144 ** Integers 20 through 29.
4145 **
4146 ** HOW IT WORKS
4147 **
4148 ** The generate_series "function" is really a virtual table with the
4149 ** following schema:
4150 **
4151 **     CREATE TABLE generate_series(
4152 **       value,
4153 **       start HIDDEN,
4154 **       stop HIDDEN,
4155 **       step HIDDEN
4156 **     );
4157 **
4158 ** Function arguments in queries against this virtual table are translated
4159 ** into equality constraints against successive hidden columns.  In other
4160 ** words, the following pairs of queries are equivalent to each other:
4161 **
4162 **    SELECT * FROM generate_series(0,100,5);
4163 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
4164 **
4165 **    SELECT * FROM generate_series(0,100);
4166 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
4167 **
4168 **    SELECT * FROM generate_series(20) LIMIT 10;
4169 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
4170 **
4171 ** The generate_series virtual table implementation leaves the xCreate method
4172 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
4173 ** TABLE command with "generate_series" as the USING argument.  Instead, there
4174 ** is a single generate_series virtual table that is always available without
4175 ** having to be created first.
4176 **
4177 ** The xBestIndex method looks for equality constraints against the hidden
4178 ** start, stop, and step columns, and if present, it uses those constraints
4179 ** to bound the sequence of generated values.  If the equality constraints
4180 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
4181 ** xBestIndex returns a small cost when both start and stop are available,
4182 ** and a very large cost if either start or stop are unavailable.  This
4183 ** encourages the query planner to order joins such that the bounds of the
4184 ** series are well-defined.
4185 */
4186 /* #include "sqlite3ext.h" */
4187 SQLITE_EXTENSION_INIT1
4188 #include <assert.h>
4189 #include <string.h>
4190 
4191 #ifndef SQLITE_OMIT_VIRTUALTABLE
4192 
4193 
4194 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
4195 ** serve as the underlying representation of a cursor that scans
4196 ** over rows of the result
4197 */
4198 typedef struct series_cursor series_cursor;
4199 struct series_cursor {
4200   sqlite3_vtab_cursor base;  /* Base class - must be first */
4201   int isDesc;                /* True to count down rather than up */
4202   sqlite3_int64 iRowid;      /* The rowid */
4203   sqlite3_int64 iValue;      /* Current value ("value") */
4204   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
4205   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
4206   sqlite3_int64 iStep;       /* Increment ("step") */
4207 };
4208 
4209 /*
4210 ** The seriesConnect() method is invoked to create a new
4211 ** series_vtab that describes the generate_series virtual table.
4212 **
4213 ** Think of this routine as the constructor for series_vtab objects.
4214 **
4215 ** All this routine needs to do is:
4216 **
4217 **    (1) Allocate the series_vtab object and initialize all fields.
4218 **
4219 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
4220 **        result set of queries against generate_series will look like.
4221 */
4222 static int seriesConnect(
4223   sqlite3 *db,
4224   void *pUnused,
4225   int argcUnused, const char *const*argvUnused,
4226   sqlite3_vtab **ppVtab,
4227   char **pzErrUnused
4228 ){
4229   sqlite3_vtab *pNew;
4230   int rc;
4231 
4232 /* Column numbers */
4233 #define SERIES_COLUMN_VALUE 0
4234 #define SERIES_COLUMN_START 1
4235 #define SERIES_COLUMN_STOP  2
4236 #define SERIES_COLUMN_STEP  3
4237 
4238   (void)pUnused;
4239   (void)argcUnused;
4240   (void)argvUnused;
4241   (void)pzErrUnused;
4242   rc = sqlite3_declare_vtab(db,
4243      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
4244   if( rc==SQLITE_OK ){
4245     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
4246     if( pNew==0 ) return SQLITE_NOMEM;
4247     memset(pNew, 0, sizeof(*pNew));
4248     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
4249   }
4250   return rc;
4251 }
4252 
4253 /*
4254 ** This method is the destructor for series_cursor objects.
4255 */
4256 static int seriesDisconnect(sqlite3_vtab *pVtab){
4257   sqlite3_free(pVtab);
4258   return SQLITE_OK;
4259 }
4260 
4261 /*
4262 ** Constructor for a new series_cursor object.
4263 */
4264 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
4265   series_cursor *pCur;
4266   (void)pUnused;
4267   pCur = sqlite3_malloc( sizeof(*pCur) );
4268   if( pCur==0 ) return SQLITE_NOMEM;
4269   memset(pCur, 0, sizeof(*pCur));
4270   *ppCursor = &pCur->base;
4271   return SQLITE_OK;
4272 }
4273 
4274 /*
4275 ** Destructor for a series_cursor.
4276 */
4277 static int seriesClose(sqlite3_vtab_cursor *cur){
4278   sqlite3_free(cur);
4279   return SQLITE_OK;
4280 }
4281 
4282 
4283 /*
4284 ** Advance a series_cursor to its next row of output.
4285 */
4286 static int seriesNext(sqlite3_vtab_cursor *cur){
4287   series_cursor *pCur = (series_cursor*)cur;
4288   if( pCur->isDesc ){
4289     pCur->iValue -= pCur->iStep;
4290   }else{
4291     pCur->iValue += pCur->iStep;
4292   }
4293   pCur->iRowid++;
4294   return SQLITE_OK;
4295 }
4296 
4297 /*
4298 ** Return values of columns for the row at which the series_cursor
4299 ** is currently pointing.
4300 */
4301 static int seriesColumn(
4302   sqlite3_vtab_cursor *cur,   /* The cursor */
4303   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
4304   int i                       /* Which column to return */
4305 ){
4306   series_cursor *pCur = (series_cursor*)cur;
4307   sqlite3_int64 x = 0;
4308   switch( i ){
4309     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
4310     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
4311     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
4312     default:                   x = pCur->iValue;  break;
4313   }
4314   sqlite3_result_int64(ctx, x);
4315   return SQLITE_OK;
4316 }
4317 
4318 /*
4319 ** Return the rowid for the current row. In this implementation, the
4320 ** first row returned is assigned rowid value 1, and each subsequent
4321 ** row a value 1 more than that of the previous.
4322 */
4323 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
4324   series_cursor *pCur = (series_cursor*)cur;
4325   *pRowid = pCur->iRowid;
4326   return SQLITE_OK;
4327 }
4328 
4329 /*
4330 ** Return TRUE if the cursor has been moved off of the last
4331 ** row of output.
4332 */
4333 static int seriesEof(sqlite3_vtab_cursor *cur){
4334   series_cursor *pCur = (series_cursor*)cur;
4335   if( pCur->isDesc ){
4336     return pCur->iValue < pCur->mnValue;
4337   }else{
4338     return pCur->iValue > pCur->mxValue;
4339   }
4340 }
4341 
4342 /* True to cause run-time checking of the start=, stop=, and/or step=
4343 ** parameters.  The only reason to do this is for testing the
4344 ** constraint checking logic for virtual tables in the SQLite core.
4345 */
4346 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
4347 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
4348 #endif
4349 
4350 /*
4351 ** This method is called to "rewind" the series_cursor object back
4352 ** to the first row of output.  This method is always called at least
4353 ** once prior to any call to seriesColumn() or seriesRowid() or
4354 ** seriesEof().
4355 **
4356 ** The query plan selected by seriesBestIndex is passed in the idxNum
4357 ** parameter.  (idxStr is not used in this implementation.)  idxNum
4358 ** is a bitmask showing which constraints are available:
4359 **
4360 **    1:    start=VALUE
4361 **    2:    stop=VALUE
4362 **    4:    step=VALUE
4363 **
4364 ** Also, if bit 8 is set, that means that the series should be output
4365 ** in descending order rather than in ascending order.  If bit 16 is
4366 ** set, then output must appear in ascending order.
4367 **
4368 ** This routine should initialize the cursor and position it so that it
4369 ** is pointing at the first row, or pointing off the end of the table
4370 ** (so that seriesEof() will return true) if the table is empty.
4371 */
4372 static int seriesFilter(
4373   sqlite3_vtab_cursor *pVtabCursor,
4374   int idxNum, const char *idxStrUnused,
4375   int argc, sqlite3_value **argv
4376 ){
4377   series_cursor *pCur = (series_cursor *)pVtabCursor;
4378   int i = 0;
4379   (void)idxStrUnused;
4380   if( idxNum & 1 ){
4381     pCur->mnValue = sqlite3_value_int64(argv[i++]);
4382   }else{
4383     pCur->mnValue = 0;
4384   }
4385   if( idxNum & 2 ){
4386     pCur->mxValue = sqlite3_value_int64(argv[i++]);
4387   }else{
4388     pCur->mxValue = 0xffffffff;
4389   }
4390   if( idxNum & 4 ){
4391     pCur->iStep = sqlite3_value_int64(argv[i++]);
4392     if( pCur->iStep==0 ){
4393       pCur->iStep = 1;
4394     }else if( pCur->iStep<0 ){
4395       pCur->iStep = -pCur->iStep;
4396       if( (idxNum & 16)==0 ) idxNum |= 8;
4397     }
4398   }else{
4399     pCur->iStep = 1;
4400   }
4401   for(i=0; i<argc; i++){
4402     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
4403       /* If any of the constraints have a NULL value, then return no rows.
4404       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
4405       pCur->mnValue = 1;
4406       pCur->mxValue = 0;
4407       break;
4408     }
4409   }
4410   if( idxNum & 8 ){
4411     pCur->isDesc = 1;
4412     pCur->iValue = pCur->mxValue;
4413     if( pCur->iStep>0 ){
4414       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
4415     }
4416   }else{
4417     pCur->isDesc = 0;
4418     pCur->iValue = pCur->mnValue;
4419   }
4420   pCur->iRowid = 1;
4421   return SQLITE_OK;
4422 }
4423 
4424 /*
4425 ** SQLite will invoke this method one or more times while planning a query
4426 ** that uses the generate_series virtual table.  This routine needs to create
4427 ** a query plan for each invocation and compute an estimated cost for that
4428 ** plan.
4429 **
4430 ** In this implementation idxNum is used to represent the
4431 ** query plan.  idxStr is unused.
4432 **
4433 ** The query plan is represented by bits in idxNum:
4434 **
4435 **  (1)  start = $value  -- constraint exists
4436 **  (2)  stop = $value   -- constraint exists
4437 **  (4)  step = $value   -- constraint exists
4438 **  (8)  output in descending order
4439 */
4440 static int seriesBestIndex(
4441   sqlite3_vtab *pVTab,
4442   sqlite3_index_info *pIdxInfo
4443 ){
4444   int i, j;              /* Loop over constraints */
4445   int idxNum = 0;        /* The query plan bitmask */
4446   int bStartSeen = 0;    /* EQ constraint seen on the START column */
4447   int unusableMask = 0;  /* Mask of unusable constraints */
4448   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
4449   int aIdx[3];           /* Constraints on start, stop, and step */
4450   const struct sqlite3_index_constraint *pConstraint;
4451 
4452   /* This implementation assumes that the start, stop, and step columns
4453   ** are the last three columns in the virtual table. */
4454   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
4455   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
4456 
4457   aIdx[0] = aIdx[1] = aIdx[2] = -1;
4458   pConstraint = pIdxInfo->aConstraint;
4459   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
4460     int iCol;    /* 0 for start, 1 for stop, 2 for step */
4461     int iMask;   /* bitmask for those column */
4462     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
4463     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
4464     assert( iCol>=0 && iCol<=2 );
4465     iMask = 1 << iCol;
4466     if( iCol==0 ) bStartSeen = 1;
4467     if( pConstraint->usable==0 ){
4468       unusableMask |=  iMask;
4469       continue;
4470     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
4471       idxNum |= iMask;
4472       aIdx[iCol] = i;
4473     }
4474   }
4475   for(i=0; i<3; i++){
4476     if( (j = aIdx[i])>=0 ){
4477       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
4478       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
4479     }
4480   }
4481   /* The current generate_column() implementation requires at least one
4482   ** argument (the START value).  Legacy versions assumed START=0 if the
4483   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
4484   ** to obtain the legacy behavior */
4485 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
4486   if( !bStartSeen ){
4487     sqlite3_free(pVTab->zErrMsg);
4488     pVTab->zErrMsg = sqlite3_mprintf(
4489         "first argument to \"generate_series()\" missing or unusable");
4490     return SQLITE_ERROR;
4491   }
4492 #endif
4493   if( (unusableMask & ~idxNum)!=0 ){
4494     /* The start, stop, and step columns are inputs.  Therefore if there
4495     ** are unusable constraints on any of start, stop, or step then
4496     ** this plan is unusable */
4497     return SQLITE_CONSTRAINT;
4498   }
4499   if( (idxNum & 3)==3 ){
4500     /* Both start= and stop= boundaries are available.  This is the
4501     ** the preferred case */
4502     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
4503     pIdxInfo->estimatedRows = 1000;
4504     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
4505       if( pIdxInfo->aOrderBy[0].desc ){
4506         idxNum |= 8;
4507       }else{
4508         idxNum |= 16;
4509       }
4510       pIdxInfo->orderByConsumed = 1;
4511     }
4512   }else{
4513     /* If either boundary is missing, we have to generate a huge span
4514     ** of numbers.  Make this case very expensive so that the query
4515     ** planner will work hard to avoid it. */
4516     pIdxInfo->estimatedRows = 2147483647;
4517   }
4518   pIdxInfo->idxNum = idxNum;
4519   return SQLITE_OK;
4520 }
4521 
4522 /*
4523 ** This following structure defines all the methods for the
4524 ** generate_series virtual table.
4525 */
4526 static sqlite3_module seriesModule = {
4527   0,                         /* iVersion */
4528   0,                         /* xCreate */
4529   seriesConnect,             /* xConnect */
4530   seriesBestIndex,           /* xBestIndex */
4531   seriesDisconnect,          /* xDisconnect */
4532   0,                         /* xDestroy */
4533   seriesOpen,                /* xOpen - open a cursor */
4534   seriesClose,               /* xClose - close a cursor */
4535   seriesFilter,              /* xFilter - configure scan constraints */
4536   seriesNext,                /* xNext - advance a cursor */
4537   seriesEof,                 /* xEof - check for end of scan */
4538   seriesColumn,              /* xColumn - read data */
4539   seriesRowid,               /* xRowid - read data */
4540   0,                         /* xUpdate */
4541   0,                         /* xBegin */
4542   0,                         /* xSync */
4543   0,                         /* xCommit */
4544   0,                         /* xRollback */
4545   0,                         /* xFindMethod */
4546   0,                         /* xRename */
4547   0,                         /* xSavepoint */
4548   0,                         /* xRelease */
4549   0,                         /* xRollbackTo */
4550   0                          /* xShadowName */
4551 };
4552 
4553 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4554 
4555 #ifdef _WIN32
4556 
4557 #endif
4558 int sqlite3_series_init(
4559   sqlite3 *db,
4560   char **pzErrMsg,
4561   const sqlite3_api_routines *pApi
4562 ){
4563   int rc = SQLITE_OK;
4564   SQLITE_EXTENSION_INIT2(pApi);
4565 #ifndef SQLITE_OMIT_VIRTUALTABLE
4566   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
4567     *pzErrMsg = sqlite3_mprintf(
4568         "generate_series() requires SQLite 3.8.12 or later");
4569     return SQLITE_ERROR;
4570   }
4571   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
4572 #endif
4573   return rc;
4574 }
4575 
4576 /************************* End ../ext/misc/series.c ********************/
4577 /************************* Begin ../ext/misc/regexp.c ******************/
4578 /*
4579 ** 2012-11-13
4580 **
4581 ** The author disclaims copyright to this source code.  In place of
4582 ** a legal notice, here is a blessing:
4583 **
4584 **    May you do good and not evil.
4585 **    May you find forgiveness for yourself and forgive others.
4586 **    May you share freely, never taking more than you give.
4587 **
4588 ******************************************************************************
4589 **
4590 ** The code in this file implements a compact but reasonably
4591 ** efficient regular-expression matcher for posix extended regular
4592 ** expressions against UTF8 text.
4593 **
4594 ** This file is an SQLite extension.  It registers a single function
4595 ** named "regexp(A,B)" where A is the regular expression and B is the
4596 ** string to be matched.  By registering this function, SQLite will also
4597 ** then implement the "B regexp A" operator.  Note that with the function
4598 ** the regular expression comes first, but with the operator it comes
4599 ** second.
4600 **
4601 **  The following regular expression syntax is supported:
4602 **
4603 **     X*      zero or more occurrences of X
4604 **     X+      one or more occurrences of X
4605 **     X?      zero or one occurrences of X
4606 **     X{p,q}  between p and q occurrences of X
4607 **     (X)     match X
4608 **     X|Y     X or Y
4609 **     ^X      X occurring at the beginning of the string
4610 **     X$      X occurring at the end of the string
4611 **     .       Match any single character
4612 **     \c      Character c where c is one of \{}()[]|*+?.
4613 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
4614 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
4615 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
4616 **     [abc]   Any single character from the set abc
4617 **     [^abc]  Any single character not in the set abc
4618 **     [a-z]   Any single character in the range a-z
4619 **     [^a-z]  Any single character not in the range a-z
4620 **     \b      Word boundary
4621 **     \w      Word character.  [A-Za-z0-9_]
4622 **     \W      Non-word character
4623 **     \d      Digit
4624 **     \D      Non-digit
4625 **     \s      Whitespace character
4626 **     \S      Non-whitespace character
4627 **
4628 ** A nondeterministic finite automaton (NFA) is used for matching, so the
4629 ** performance is bounded by O(N*M) where N is the size of the regular
4630 ** expression and M is the size of the input string.  The matcher never
4631 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
4632 ** to p copies of X following by q-p copies of X? and that the size of the
4633 ** regular expression in the O(N*M) performance bound is computed after
4634 ** this expansion.
4635 */
4636 #include <string.h>
4637 #include <stdlib.h>
4638 /* #include "sqlite3ext.h" */
4639 SQLITE_EXTENSION_INIT1
4640 
4641 /*
4642 ** The following #defines change the names of some functions implemented in
4643 ** this file to prevent name collisions with C-library functions of the
4644 ** same name.
4645 */
4646 #define re_match   sqlite3re_match
4647 #define re_compile sqlite3re_compile
4648 #define re_free    sqlite3re_free
4649 
4650 /* The end-of-input character */
4651 #define RE_EOF            0    /* End of input */
4652 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
4653 
4654 /* The NFA is implemented as sequence of opcodes taken from the following
4655 ** set.  Each opcode has a single integer argument.
4656 */
4657 #define RE_OP_MATCH       1    /* Match the one character in the argument */
4658 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
4659 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
4660 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
4661 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
4662 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
4663 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
4664 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
4665 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
4666 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
4667 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
4668 #define RE_OP_NOTWORD    12    /* Not a perl word character */
4669 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
4670 #define RE_OP_NOTDIGIT   14    /* Not a digit */
4671 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
4672 #define RE_OP_NOTSPACE   16    /* Not a digit */
4673 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
4674 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
4675 
4676 #if defined(SQLITE_DEBUG)
4677 /* Opcode names used for symbolic debugging */
4678 static const char *ReOpName[] = {
4679   "EOF",
4680   "MATCH",
4681   "ANY",
4682   "ANYSTAR",
4683   "FORK",
4684   "GOTO",
4685   "ACCEPT",
4686   "CC_INC",
4687   "CC_EXC",
4688   "CC_VALUE",
4689   "CC_RANGE",
4690   "WORD",
4691   "NOTWORD",
4692   "DIGIT",
4693   "NOTDIGIT",
4694   "SPACE",
4695   "NOTSPACE",
4696   "BOUNDARY",
4697   "ATSTART",
4698 };
4699 #endif /* SQLITE_DEBUG */
4700 
4701 
4702 /* Each opcode is a "state" in the NFA */
4703 typedef unsigned short ReStateNumber;
4704 
4705 /* Because this is an NFA and not a DFA, multiple states can be active at
4706 ** once.  An instance of the following object records all active states in
4707 ** the NFA.  The implementation is optimized for the common case where the
4708 ** number of actives states is small.
4709 */
4710 typedef struct ReStateSet {
4711   unsigned nState;            /* Number of current states */
4712   ReStateNumber *aState;      /* Current states */
4713 } ReStateSet;
4714 
4715 /* An input string read one character at a time.
4716 */
4717 typedef struct ReInput ReInput;
4718 struct ReInput {
4719   const unsigned char *z;  /* All text */
4720   int i;                   /* Next byte to read */
4721   int mx;                  /* EOF when i>=mx */
4722 };
4723 
4724 /* A compiled NFA (or an NFA that is in the process of being compiled) is
4725 ** an instance of the following object.
4726 */
4727 typedef struct ReCompiled ReCompiled;
4728 struct ReCompiled {
4729   ReInput sIn;                /* Regular expression text */
4730   const char *zErr;           /* Error message to return */
4731   char *aOp;                  /* Operators for the virtual machine */
4732   int *aArg;                  /* Arguments to each operator */
4733   unsigned (*xNextChar)(ReInput*);  /* Next character function */
4734   unsigned char zInit[12];    /* Initial text to match */
4735   int nInit;                  /* Number of bytes in zInit */
4736   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
4737   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
4738 };
4739 
4740 /* Add a state to the given state set if it is not already there */
4741 static void re_add_state(ReStateSet *pSet, int newState){
4742   unsigned i;
4743   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
4744   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
4745 }
4746 
4747 /* Extract the next unicode character from *pzIn and return it.  Advance
4748 ** *pzIn to the first byte past the end of the character returned.  To
4749 ** be clear:  this routine converts utf8 to unicode.  This routine is
4750 ** optimized for the common case where the next character is a single byte.
4751 */
4752 static unsigned re_next_char(ReInput *p){
4753   unsigned c;
4754   if( p->i>=p->mx ) return 0;
4755   c = p->z[p->i++];
4756   if( c>=0x80 ){
4757     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
4758       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
4759       if( c<0x80 ) c = 0xfffd;
4760     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
4761            && (p->z[p->i+1]&0xc0)==0x80 ){
4762       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
4763       p->i += 2;
4764       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
4765     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
4766            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
4767       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
4768                        | (p->z[p->i+2]&0x3f);
4769       p->i += 3;
4770       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
4771     }else{
4772       c = 0xfffd;
4773     }
4774   }
4775   return c;
4776 }
4777 static unsigned re_next_char_nocase(ReInput *p){
4778   unsigned c = re_next_char(p);
4779   if( c>='A' && c<='Z' ) c += 'a' - 'A';
4780   return c;
4781 }
4782 
4783 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
4784 static int re_word_char(int c){
4785   return (c>='0' && c<='9') || (c>='a' && c<='z')
4786       || (c>='A' && c<='Z') || c=='_';
4787 }
4788 
4789 /* Return true if c is a "digit" character:  [0-9] */
4790 static int re_digit_char(int c){
4791   return (c>='0' && c<='9');
4792 }
4793 
4794 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
4795 static int re_space_char(int c){
4796   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
4797 }
4798 
4799 /* Run a compiled regular expression on the zero-terminated input
4800 ** string zIn[].  Return true on a match and false if there is no match.
4801 */
4802 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
4803   ReStateSet aStateSet[2], *pThis, *pNext;
4804   ReStateNumber aSpace[100];
4805   ReStateNumber *pToFree;
4806   unsigned int i = 0;
4807   unsigned int iSwap = 0;
4808   int c = RE_START;
4809   int cPrev = 0;
4810   int rc = 0;
4811   ReInput in;
4812 
4813   in.z = zIn;
4814   in.i = 0;
4815   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
4816 
4817   /* Look for the initial prefix match, if there is one. */
4818   if( pRe->nInit ){
4819     unsigned char x = pRe->zInit[0];
4820     while( in.i+pRe->nInit<=in.mx
4821      && (zIn[in.i]!=x ||
4822          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
4823     ){
4824       in.i++;
4825     }
4826     if( in.i+pRe->nInit>in.mx ) return 0;
4827     c = RE_START-1;
4828   }
4829 
4830   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
4831     pToFree = 0;
4832     aStateSet[0].aState = aSpace;
4833   }else{
4834     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
4835     if( pToFree==0 ) return -1;
4836     aStateSet[0].aState = pToFree;
4837   }
4838   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
4839   pNext = &aStateSet[1];
4840   pNext->nState = 0;
4841   re_add_state(pNext, 0);
4842   while( c!=RE_EOF && pNext->nState>0 ){
4843     cPrev = c;
4844     c = pRe->xNextChar(&in);
4845     pThis = pNext;
4846     pNext = &aStateSet[iSwap];
4847     iSwap = 1 - iSwap;
4848     pNext->nState = 0;
4849     for(i=0; i<pThis->nState; i++){
4850       int x = pThis->aState[i];
4851       switch( pRe->aOp[x] ){
4852         case RE_OP_MATCH: {
4853           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
4854           break;
4855         }
4856         case RE_OP_ATSTART: {
4857           if( cPrev==RE_START ) re_add_state(pThis, x+1);
4858           break;
4859         }
4860         case RE_OP_ANY: {
4861           if( c!=0 ) re_add_state(pNext, x+1);
4862           break;
4863         }
4864         case RE_OP_WORD: {
4865           if( re_word_char(c) ) re_add_state(pNext, x+1);
4866           break;
4867         }
4868         case RE_OP_NOTWORD: {
4869           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
4870           break;
4871         }
4872         case RE_OP_DIGIT: {
4873           if( re_digit_char(c) ) re_add_state(pNext, x+1);
4874           break;
4875         }
4876         case RE_OP_NOTDIGIT: {
4877           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
4878           break;
4879         }
4880         case RE_OP_SPACE: {
4881           if( re_space_char(c) ) re_add_state(pNext, x+1);
4882           break;
4883         }
4884         case RE_OP_NOTSPACE: {
4885           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
4886           break;
4887         }
4888         case RE_OP_BOUNDARY: {
4889           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
4890           break;
4891         }
4892         case RE_OP_ANYSTAR: {
4893           re_add_state(pNext, x);
4894           re_add_state(pThis, x+1);
4895           break;
4896         }
4897         case RE_OP_FORK: {
4898           re_add_state(pThis, x+pRe->aArg[x]);
4899           re_add_state(pThis, x+1);
4900           break;
4901         }
4902         case RE_OP_GOTO: {
4903           re_add_state(pThis, x+pRe->aArg[x]);
4904           break;
4905         }
4906         case RE_OP_ACCEPT: {
4907           rc = 1;
4908           goto re_match_end;
4909         }
4910         case RE_OP_CC_EXC: {
4911           if( c==0 ) break;
4912           /* fall-through */ goto re_op_cc_inc;
4913         }
4914         case RE_OP_CC_INC: re_op_cc_inc: {
4915           int j = 1;
4916           int n = pRe->aArg[x];
4917           int hit = 0;
4918           for(j=1; j>0 && j<n; j++){
4919             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
4920               if( pRe->aArg[x+j]==c ){
4921                 hit = 1;
4922                 j = -1;
4923               }
4924             }else{
4925               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
4926                 hit = 1;
4927                 j = -1;
4928               }else{
4929                 j++;
4930               }
4931             }
4932           }
4933           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
4934           if( hit ) re_add_state(pNext, x+n);
4935           break;
4936         }
4937       }
4938     }
4939   }
4940   for(i=0; i<pNext->nState; i++){
4941     int x = pNext->aState[i];
4942     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
4943     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
4944   }
4945 re_match_end:
4946   sqlite3_free(pToFree);
4947   return rc;
4948 }
4949 
4950 /* Resize the opcode and argument arrays for an RE under construction.
4951 */
4952 static int re_resize(ReCompiled *p, int N){
4953   char *aOp;
4954   int *aArg;
4955   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
4956   if( aOp==0 ) return 1;
4957   p->aOp = aOp;
4958   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
4959   if( aArg==0 ) return 1;
4960   p->aArg = aArg;
4961   p->nAlloc = N;
4962   return 0;
4963 }
4964 
4965 /* Insert a new opcode and argument into an RE under construction.  The
4966 ** insertion point is just prior to existing opcode iBefore.
4967 */
4968 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
4969   int i;
4970   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
4971   for(i=p->nState; i>iBefore; i--){
4972     p->aOp[i] = p->aOp[i-1];
4973     p->aArg[i] = p->aArg[i-1];
4974   }
4975   p->nState++;
4976   p->aOp[iBefore] = (char)op;
4977   p->aArg[iBefore] = arg;
4978   return iBefore;
4979 }
4980 
4981 /* Append a new opcode and argument to the end of the RE under construction.
4982 */
4983 static int re_append(ReCompiled *p, int op, int arg){
4984   return re_insert(p, p->nState, op, arg);
4985 }
4986 
4987 /* Make a copy of N opcodes starting at iStart onto the end of the RE
4988 ** under construction.
4989 */
4990 static void re_copy(ReCompiled *p, int iStart, int N){
4991   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
4992   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
4993   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
4994   p->nState += N;
4995 }
4996 
4997 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
4998 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
4999 ** c is not a hex digit *pV is unchanged.
5000 */
5001 static int re_hex(int c, int *pV){
5002   if( c>='0' && c<='9' ){
5003     c -= '0';
5004   }else if( c>='a' && c<='f' ){
5005     c -= 'a' - 10;
5006   }else if( c>='A' && c<='F' ){
5007     c -= 'A' - 10;
5008   }else{
5009     return 0;
5010   }
5011   *pV = (*pV)*16 + (c & 0xff);
5012   return 1;
5013 }
5014 
5015 /* A backslash character has been seen, read the next character and
5016 ** return its interpretation.
5017 */
5018 static unsigned re_esc_char(ReCompiled *p){
5019   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
5020   static const char zTrans[] = "\a\f\n\r\t\v";
5021   int i, v = 0;
5022   char c;
5023   if( p->sIn.i>=p->sIn.mx ) return 0;
5024   c = p->sIn.z[p->sIn.i];
5025   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
5026     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5027     if( re_hex(zIn[1],&v)
5028      && re_hex(zIn[2],&v)
5029      && re_hex(zIn[3],&v)
5030      && re_hex(zIn[4],&v)
5031     ){
5032       p->sIn.i += 5;
5033       return v;
5034     }
5035   }
5036   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
5037     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5038     if( re_hex(zIn[1],&v)
5039      && re_hex(zIn[2],&v)
5040     ){
5041       p->sIn.i += 3;
5042       return v;
5043     }
5044   }
5045   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
5046   if( zEsc[i] ){
5047     if( i<6 ) c = zTrans[i];
5048     p->sIn.i++;
5049   }else{
5050     p->zErr = "unknown \\ escape";
5051   }
5052   return c;
5053 }
5054 
5055 /* Forward declaration */
5056 static const char *re_subcompile_string(ReCompiled*);
5057 
5058 /* Peek at the next byte of input */
5059 static unsigned char rePeek(ReCompiled *p){
5060   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
5061 }
5062 
5063 /* Compile RE text into a sequence of opcodes.  Continue up to the
5064 ** first unmatched ")" character, then return.  If an error is found,
5065 ** return a pointer to the error message string.
5066 */
5067 static const char *re_subcompile_re(ReCompiled *p){
5068   const char *zErr;
5069   int iStart, iEnd, iGoto;
5070   iStart = p->nState;
5071   zErr = re_subcompile_string(p);
5072   if( zErr ) return zErr;
5073   while( rePeek(p)=='|' ){
5074     iEnd = p->nState;
5075     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
5076     iGoto = re_append(p, RE_OP_GOTO, 0);
5077     p->sIn.i++;
5078     zErr = re_subcompile_string(p);
5079     if( zErr ) return zErr;
5080     p->aArg[iGoto] = p->nState - iGoto;
5081   }
5082   return 0;
5083 }
5084 
5085 /* Compile an element of regular expression text (anything that can be
5086 ** an operand to the "|" operator).  Return NULL on success or a pointer
5087 ** to the error message if there is a problem.
5088 */
5089 static const char *re_subcompile_string(ReCompiled *p){
5090   int iPrev = -1;
5091   int iStart;
5092   unsigned c;
5093   const char *zErr;
5094   while( (c = p->xNextChar(&p->sIn))!=0 ){
5095     iStart = p->nState;
5096     switch( c ){
5097       case '|':
5098       case ')': {
5099         p->sIn.i--;
5100         return 0;
5101       }
5102       case '(': {
5103         zErr = re_subcompile_re(p);
5104         if( zErr ) return zErr;
5105         if( rePeek(p)!=')' ) return "unmatched '('";
5106         p->sIn.i++;
5107         break;
5108       }
5109       case '.': {
5110         if( rePeek(p)=='*' ){
5111           re_append(p, RE_OP_ANYSTAR, 0);
5112           p->sIn.i++;
5113         }else{
5114           re_append(p, RE_OP_ANY, 0);
5115         }
5116         break;
5117       }
5118       case '*': {
5119         if( iPrev<0 ) return "'*' without operand";
5120         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
5121         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
5122         break;
5123       }
5124       case '+': {
5125         if( iPrev<0 ) return "'+' without operand";
5126         re_append(p, RE_OP_FORK, iPrev - p->nState);
5127         break;
5128       }
5129       case '?': {
5130         if( iPrev<0 ) return "'?' without operand";
5131         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
5132         break;
5133       }
5134       case '$': {
5135         re_append(p, RE_OP_MATCH, RE_EOF);
5136         break;
5137       }
5138       case '^': {
5139         re_append(p, RE_OP_ATSTART, 0);
5140         break;
5141       }
5142       case '{': {
5143         int m = 0, n = 0;
5144         int sz, j;
5145         if( iPrev<0 ) return "'{m,n}' without operand";
5146         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
5147         n = m;
5148         if( c==',' ){
5149           p->sIn.i++;
5150           n = 0;
5151           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
5152         }
5153         if( c!='}' ) return "unmatched '{'";
5154         if( n>0 && n<m ) return "n less than m in '{m,n}'";
5155         p->sIn.i++;
5156         sz = p->nState - iPrev;
5157         if( m==0 ){
5158           if( n==0 ) return "both m and n are zero in '{m,n}'";
5159           re_insert(p, iPrev, RE_OP_FORK, sz+1);
5160           iPrev++;
5161           n--;
5162         }else{
5163           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
5164         }
5165         for(j=m; j<n; j++){
5166           re_append(p, RE_OP_FORK, sz+1);
5167           re_copy(p, iPrev, sz);
5168         }
5169         if( n==0 && m>0 ){
5170           re_append(p, RE_OP_FORK, -sz);
5171         }
5172         break;
5173       }
5174       case '[': {
5175         int iFirst = p->nState;
5176         if( rePeek(p)=='^' ){
5177           re_append(p, RE_OP_CC_EXC, 0);
5178           p->sIn.i++;
5179         }else{
5180           re_append(p, RE_OP_CC_INC, 0);
5181         }
5182         while( (c = p->xNextChar(&p->sIn))!=0 ){
5183           if( c=='[' && rePeek(p)==':' ){
5184             return "POSIX character classes not supported";
5185           }
5186           if( c=='\\' ) c = re_esc_char(p);
5187           if( rePeek(p)=='-' ){
5188             re_append(p, RE_OP_CC_RANGE, c);
5189             p->sIn.i++;
5190             c = p->xNextChar(&p->sIn);
5191             if( c=='\\' ) c = re_esc_char(p);
5192             re_append(p, RE_OP_CC_RANGE, c);
5193           }else{
5194             re_append(p, RE_OP_CC_VALUE, c);
5195           }
5196           if( rePeek(p)==']' ){ p->sIn.i++; break; }
5197         }
5198         if( c==0 ) return "unclosed '['";
5199         p->aArg[iFirst] = p->nState - iFirst;
5200         break;
5201       }
5202       case '\\': {
5203         int specialOp = 0;
5204         switch( rePeek(p) ){
5205           case 'b': specialOp = RE_OP_BOUNDARY;   break;
5206           case 'd': specialOp = RE_OP_DIGIT;      break;
5207           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
5208           case 's': specialOp = RE_OP_SPACE;      break;
5209           case 'S': specialOp = RE_OP_NOTSPACE;   break;
5210           case 'w': specialOp = RE_OP_WORD;       break;
5211           case 'W': specialOp = RE_OP_NOTWORD;    break;
5212         }
5213         if( specialOp ){
5214           p->sIn.i++;
5215           re_append(p, specialOp, 0);
5216         }else{
5217           c = re_esc_char(p);
5218           re_append(p, RE_OP_MATCH, c);
5219         }
5220         break;
5221       }
5222       default: {
5223         re_append(p, RE_OP_MATCH, c);
5224         break;
5225       }
5226     }
5227     iPrev = iStart;
5228   }
5229   return 0;
5230 }
5231 
5232 /* Free and reclaim all the memory used by a previously compiled
5233 ** regular expression.  Applications should invoke this routine once
5234 ** for every call to re_compile() to avoid memory leaks.
5235 */
5236 static void re_free(ReCompiled *pRe){
5237   if( pRe ){
5238     sqlite3_free(pRe->aOp);
5239     sqlite3_free(pRe->aArg);
5240     sqlite3_free(pRe);
5241   }
5242 }
5243 
5244 /*
5245 ** Compile a textual regular expression in zIn[] into a compiled regular
5246 ** expression suitable for us by re_match() and return a pointer to the
5247 ** compiled regular expression in *ppRe.  Return NULL on success or an
5248 ** error message if something goes wrong.
5249 */
5250 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
5251   ReCompiled *pRe;
5252   const char *zErr;
5253   int i, j;
5254 
5255   *ppRe = 0;
5256   pRe = sqlite3_malloc( sizeof(*pRe) );
5257   if( pRe==0 ){
5258     return "out of memory";
5259   }
5260   memset(pRe, 0, sizeof(*pRe));
5261   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
5262   if( re_resize(pRe, 30) ){
5263     re_free(pRe);
5264     return "out of memory";
5265   }
5266   if( zIn[0]=='^' ){
5267     zIn++;
5268   }else{
5269     re_append(pRe, RE_OP_ANYSTAR, 0);
5270   }
5271   pRe->sIn.z = (unsigned char*)zIn;
5272   pRe->sIn.i = 0;
5273   pRe->sIn.mx = (int)strlen(zIn);
5274   zErr = re_subcompile_re(pRe);
5275   if( zErr ){
5276     re_free(pRe);
5277     return zErr;
5278   }
5279   if( pRe->sIn.i>=pRe->sIn.mx ){
5280     re_append(pRe, RE_OP_ACCEPT, 0);
5281     *ppRe = pRe;
5282   }else{
5283     re_free(pRe);
5284     return "unrecognized character";
5285   }
5286 
5287   /* The following is a performance optimization.  If the regex begins with
5288   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
5289   ** one or more matching characters, enter those matching characters into
5290   ** zInit[].  The re_match() routine can then search ahead in the input
5291   ** string looking for the initial match without having to run the whole
5292   ** regex engine over the string.  Do not worry about trying to match
5293   ** unicode characters beyond plane 0 - those are very rare and this is
5294   ** just an optimization. */
5295   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
5296     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
5297       unsigned x = pRe->aArg[i];
5298       if( x<=0x7f ){
5299         pRe->zInit[j++] = (unsigned char)x;
5300       }else if( x<=0x7ff ){
5301         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
5302         pRe->zInit[j++] = 0x80 | (x&0x3f);
5303       }else if( x<=0xffff ){
5304         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
5305         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
5306         pRe->zInit[j++] = 0x80 | (x&0x3f);
5307       }else{
5308         break;
5309       }
5310     }
5311     if( j>0 && pRe->zInit[j-1]==0 ) j--;
5312     pRe->nInit = j;
5313   }
5314   return pRe->zErr;
5315 }
5316 
5317 /*
5318 ** Implementation of the regexp() SQL function.  This function implements
5319 ** the build-in REGEXP operator.  The first argument to the function is the
5320 ** pattern and the second argument is the string.  So, the SQL statements:
5321 **
5322 **       A REGEXP B
5323 **
5324 ** is implemented as regexp(B,A).
5325 */
5326 static void re_sql_func(
5327   sqlite3_context *context,
5328   int argc,
5329   sqlite3_value **argv
5330 ){
5331   ReCompiled *pRe;          /* Compiled regular expression */
5332   const char *zPattern;     /* The regular expression */
5333   const unsigned char *zStr;/* String being searched */
5334   const char *zErr;         /* Compile error message */
5335   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
5336 
5337   (void)argc;  /* Unused */
5338   pRe = sqlite3_get_auxdata(context, 0);
5339   if( pRe==0 ){
5340     zPattern = (const char*)sqlite3_value_text(argv[0]);
5341     if( zPattern==0 ) return;
5342     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
5343     if( zErr ){
5344       re_free(pRe);
5345       sqlite3_result_error(context, zErr, -1);
5346       return;
5347     }
5348     if( pRe==0 ){
5349       sqlite3_result_error_nomem(context);
5350       return;
5351     }
5352     setAux = 1;
5353   }
5354   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
5355   if( zStr!=0 ){
5356     sqlite3_result_int(context, re_match(pRe, zStr, -1));
5357   }
5358   if( setAux ){
5359     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
5360   }
5361 }
5362 
5363 #if defined(SQLITE_DEBUG)
5364 /*
5365 ** This function is used for testing and debugging only.  It is only available
5366 ** if the SQLITE_DEBUG compile-time option is used.
5367 **
5368 ** Compile a regular expression and then convert the compiled expression into
5369 ** text and return that text.
5370 */
5371 static void re_bytecode_func(
5372   sqlite3_context *context,
5373   int argc,
5374   sqlite3_value **argv
5375 ){
5376   const char *zPattern;
5377   const char *zErr;
5378   ReCompiled *pRe;
5379   sqlite3_str *pStr;
5380   int i;
5381   int n;
5382   char *z;
5383   (void)argc;
5384 
5385   zPattern = (const char*)sqlite3_value_text(argv[0]);
5386   if( zPattern==0 ) return;
5387   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
5388   if( zErr ){
5389     re_free(pRe);
5390     sqlite3_result_error(context, zErr, -1);
5391     return;
5392   }
5393   if( pRe==0 ){
5394     sqlite3_result_error_nomem(context);
5395     return;
5396   }
5397   pStr = sqlite3_str_new(0);
5398   if( pStr==0 ) goto re_bytecode_func_err;
5399   if( pRe->nInit>0 ){
5400     sqlite3_str_appendf(pStr, "INIT     ");
5401     for(i=0; i<pRe->nInit; i++){
5402       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
5403     }
5404     sqlite3_str_appendf(pStr, "\n");
5405   }
5406   for(i=0; (unsigned)i<pRe->nState; i++){
5407     sqlite3_str_appendf(pStr, "%-8s %4d\n",
5408          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
5409   }
5410   n = sqlite3_str_length(pStr);
5411   z = sqlite3_str_finish(pStr);
5412   if( n==0 ){
5413     sqlite3_free(z);
5414   }else{
5415     sqlite3_result_text(context, z, n-1, sqlite3_free);
5416   }
5417 
5418 re_bytecode_func_err:
5419   re_free(pRe);
5420 }
5421 
5422 #endif /* SQLITE_DEBUG */
5423 
5424 
5425 /*
5426 ** Invoke this routine to register the regexp() function with the
5427 ** SQLite database connection.
5428 */
5429 #ifdef _WIN32
5430 
5431 #endif
5432 int sqlite3_regexp_init(
5433   sqlite3 *db,
5434   char **pzErrMsg,
5435   const sqlite3_api_routines *pApi
5436 ){
5437   int rc = SQLITE_OK;
5438   SQLITE_EXTENSION_INIT2(pApi);
5439   (void)pzErrMsg;  /* Unused */
5440   rc = sqlite3_create_function(db, "regexp", 2,
5441                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5442                             0, re_sql_func, 0, 0);
5443   if( rc==SQLITE_OK ){
5444     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
5445     ** of regexp(PATTERN,STRING). */
5446     rc = sqlite3_create_function(db, "regexpi", 2,
5447                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5448                             (void*)db, re_sql_func, 0, 0);
5449 #if defined(SQLITE_DEBUG)
5450     if( rc==SQLITE_OK ){
5451       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
5452                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
5453                             0, re_bytecode_func, 0, 0);
5454     }
5455 #endif /* SQLITE_DEBUG */
5456   }
5457   return rc;
5458 }
5459 
5460 /************************* End ../ext/misc/regexp.c ********************/
5461 #ifndef SQLITE_SHELL_FIDDLE
5462 /************************* Begin ../ext/misc/fileio.c ******************/
5463 /*
5464 ** 2014-06-13
5465 **
5466 ** The author disclaims copyright to this source code.  In place of
5467 ** a legal notice, here is a blessing:
5468 **
5469 **    May you do good and not evil.
5470 **    May you find forgiveness for yourself and forgive others.
5471 **    May you share freely, never taking more than you give.
5472 **
5473 ******************************************************************************
5474 **
5475 ** This SQLite extension implements SQL functions readfile() and
5476 ** writefile(), and eponymous virtual type "fsdir".
5477 **
5478 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
5479 **
5480 **   If neither of the optional arguments is present, then this UDF
5481 **   function writes blob DATA to file FILE. If successful, the number
5482 **   of bytes written is returned. If an error occurs, NULL is returned.
5483 **
5484 **   If the first option argument - MODE - is present, then it must
5485 **   be passed an integer value that corresponds to a POSIX mode
5486 **   value (file type + permissions, as returned in the stat.st_mode
5487 **   field by the stat() system call). Three types of files may
5488 **   be written/created:
5489 **
5490 **     regular files:  (mode & 0170000)==0100000
5491 **     symbolic links: (mode & 0170000)==0120000
5492 **     directories:    (mode & 0170000)==0040000
5493 **
5494 **   For a directory, the DATA is ignored. For a symbolic link, it is
5495 **   interpreted as text and used as the target of the link. For a
5496 **   regular file, it is interpreted as a blob and written into the
5497 **   named file. Regardless of the type of file, its permissions are
5498 **   set to (mode & 0777) before returning.
5499 **
5500 **   If the optional MTIME argument is present, then it is interpreted
5501 **   as an integer - the number of seconds since the unix epoch. The
5502 **   modification-time of the target file is set to this value before
5503 **   returning.
5504 **
5505 **   If three or more arguments are passed to this function and an
5506 **   error is encountered, an exception is raised.
5507 **
5508 ** READFILE(FILE):
5509 **
5510 **   Read and return the contents of file FILE (type blob) from disk.
5511 **
5512 ** FSDIR:
5513 **
5514 **   Used as follows:
5515 **
5516 **     SELECT * FROM fsdir($path [, $dir]);
5517 **
5518 **   Parameter $path is an absolute or relative pathname. If the file that it
5519 **   refers to does not exist, it is an error. If the path refers to a regular
5520 **   file or symbolic link, it returns a single row. Or, if the path refers
5521 **   to a directory, it returns one row for the directory, and one row for each
5522 **   file within the hierarchy rooted at $path.
5523 **
5524 **   Each row has the following columns:
5525 **
5526 **     name:  Path to file or directory (text value).
5527 **     mode:  Value of stat.st_mode for directory entry (an integer).
5528 **     mtime: Value of stat.st_mtime for directory entry (an integer).
5529 **     data:  For a regular file, a blob containing the file data. For a
5530 **            symlink, a text value containing the text of the link. For a
5531 **            directory, NULL.
5532 **
5533 **   If a non-NULL value is specified for the optional $dir parameter and
5534 **   $path is a relative path, then $path is interpreted relative to $dir.
5535 **   And the paths returned in the "name" column of the table are also
5536 **   relative to directory $dir.
5537 **
5538 ** Notes on building this extension for Windows:
5539 **   Unless linked statically with the SQLite library, a preprocessor
5540 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
5541 **   DLL form of this extension for WIN32. See its use below for details.
5542 */
5543 /* #include "sqlite3ext.h" */
5544 SQLITE_EXTENSION_INIT1
5545 #include <stdio.h>
5546 #include <string.h>
5547 #include <assert.h>
5548 
5549 #include <sys/types.h>
5550 #include <sys/stat.h>
5551 #include <fcntl.h>
5552 #if !defined(_WIN32) && !defined(WIN32)
5553 #  include <unistd.h>
5554 #  include <dirent.h>
5555 #  include <utime.h>
5556 #  include <sys/time.h>
5557 #else
5558 #  include "windows.h"
5559 #  include <io.h>
5560 #  include <direct.h>
5561 /* #  include "test_windirent.h" */
5562 #  define dirent DIRENT
5563 #  ifndef chmod
5564 #    define chmod _chmod
5565 #  endif
5566 #  ifndef stat
5567 #    define stat _stat
5568 #  endif
5569 #  define mkdir(path,mode) _mkdir(path)
5570 #  define lstat(path,buf) stat(path,buf)
5571 #endif
5572 #include <time.h>
5573 #include <errno.h>
5574 
5575 
5576 /*
5577 ** Structure of the fsdir() table-valued function
5578 */
5579                  /*    0    1    2     3    4           5             */
5580 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
5581 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
5582 #define FSDIR_COLUMN_MODE     1     /* Access mode */
5583 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
5584 #define FSDIR_COLUMN_DATA     3     /* File content */
5585 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
5586 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
5587 
5588 
5589 /*
5590 ** Set the result stored by context ctx to a blob containing the
5591 ** contents of file zName.  Or, leave the result unchanged (NULL)
5592 ** if the file does not exist or is unreadable.
5593 **
5594 ** If the file exceeds the SQLite blob size limit, through an
5595 ** SQLITE_TOOBIG error.
5596 **
5597 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
5598 ** off of disk.
5599 */
5600 static void readFileContents(sqlite3_context *ctx, const char *zName){
5601   FILE *in;
5602   sqlite3_int64 nIn;
5603   void *pBuf;
5604   sqlite3 *db;
5605   int mxBlob;
5606 
5607   in = fopen(zName, "rb");
5608   if( in==0 ){
5609     /* File does not exist or is unreadable. Leave the result set to NULL. */
5610     return;
5611   }
5612   fseek(in, 0, SEEK_END);
5613   nIn = ftell(in);
5614   rewind(in);
5615   db = sqlite3_context_db_handle(ctx);
5616   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
5617   if( nIn>mxBlob ){
5618     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
5619     fclose(in);
5620     return;
5621   }
5622   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
5623   if( pBuf==0 ){
5624     sqlite3_result_error_nomem(ctx);
5625     fclose(in);
5626     return;
5627   }
5628   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
5629     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
5630   }else{
5631     sqlite3_result_error_code(ctx, SQLITE_IOERR);
5632     sqlite3_free(pBuf);
5633   }
5634   fclose(in);
5635 }
5636 
5637 /*
5638 ** Implementation of the "readfile(X)" SQL function.  The entire content
5639 ** of the file named X is read and returned as a BLOB.  NULL is returned
5640 ** if the file does not exist or is unreadable.
5641 */
5642 static void readfileFunc(
5643   sqlite3_context *context,
5644   int argc,
5645   sqlite3_value **argv
5646 ){
5647   const char *zName;
5648   (void)(argc);  /* Unused parameter */
5649   zName = (const char*)sqlite3_value_text(argv[0]);
5650   if( zName==0 ) return;
5651   readFileContents(context, zName);
5652 }
5653 
5654 /*
5655 ** Set the error message contained in context ctx to the results of
5656 ** vprintf(zFmt, ...).
5657 */
5658 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
5659   char *zMsg = 0;
5660   va_list ap;
5661   va_start(ap, zFmt);
5662   zMsg = sqlite3_vmprintf(zFmt, ap);
5663   sqlite3_result_error(ctx, zMsg, -1);
5664   sqlite3_free(zMsg);
5665   va_end(ap);
5666 }
5667 
5668 #if defined(_WIN32)
5669 /*
5670 ** This function is designed to convert a Win32 FILETIME structure into the
5671 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
5672 */
5673 static sqlite3_uint64 fileTimeToUnixTime(
5674   LPFILETIME pFileTime
5675 ){
5676   SYSTEMTIME epochSystemTime;
5677   ULARGE_INTEGER epochIntervals;
5678   FILETIME epochFileTime;
5679   ULARGE_INTEGER fileIntervals;
5680 
5681   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
5682   epochSystemTime.wYear = 1970;
5683   epochSystemTime.wMonth = 1;
5684   epochSystemTime.wDay = 1;
5685   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
5686   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
5687   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
5688 
5689   fileIntervals.LowPart = pFileTime->dwLowDateTime;
5690   fileIntervals.HighPart = pFileTime->dwHighDateTime;
5691 
5692   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
5693 }
5694 
5695 
5696 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
5697 #  /* To allow a standalone DLL, use this next replacement function: */
5698 #  undef sqlite3_win32_utf8_to_unicode
5699 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
5700 #
5701 LPWSTR utf8_to_utf16(const char *z){
5702   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
5703   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
5704   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
5705     return rv;
5706   sqlite3_free(rv);
5707   return 0;
5708 }
5709 #endif
5710 
5711 /*
5712 ** This function attempts to normalize the time values found in the stat()
5713 ** buffer to UTC.  This is necessary on Win32, where the runtime library
5714 ** appears to return these values as local times.
5715 */
5716 static void statTimesToUtc(
5717   const char *zPath,
5718   struct stat *pStatBuf
5719 ){
5720   HANDLE hFindFile;
5721   WIN32_FIND_DATAW fd;
5722   LPWSTR zUnicodeName;
5723   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
5724   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
5725   if( zUnicodeName ){
5726     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
5727     hFindFile = FindFirstFileW(zUnicodeName, &fd);
5728     if( hFindFile!=NULL ){
5729       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
5730       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
5731       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
5732       FindClose(hFindFile);
5733     }
5734     sqlite3_free(zUnicodeName);
5735   }
5736 }
5737 #endif
5738 
5739 /*
5740 ** This function is used in place of stat().  On Windows, special handling
5741 ** is required in order for the included time to be returned as UTC.  On all
5742 ** other systems, this function simply calls stat().
5743 */
5744 static int fileStat(
5745   const char *zPath,
5746   struct stat *pStatBuf
5747 ){
5748 #if defined(_WIN32)
5749   int rc = stat(zPath, pStatBuf);
5750   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
5751   return rc;
5752 #else
5753   return stat(zPath, pStatBuf);
5754 #endif
5755 }
5756 
5757 /*
5758 ** This function is used in place of lstat().  On Windows, special handling
5759 ** is required in order for the included time to be returned as UTC.  On all
5760 ** other systems, this function simply calls lstat().
5761 */
5762 static int fileLinkStat(
5763   const char *zPath,
5764   struct stat *pStatBuf
5765 ){
5766 #if defined(_WIN32)
5767   int rc = lstat(zPath, pStatBuf);
5768   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
5769   return rc;
5770 #else
5771   return lstat(zPath, pStatBuf);
5772 #endif
5773 }
5774 
5775 /*
5776 ** Argument zFile is the name of a file that will be created and/or written
5777 ** by SQL function writefile(). This function ensures that the directory
5778 ** zFile will be written to exists, creating it if required. The permissions
5779 ** for any path components created by this function are set in accordance
5780 ** with the current umask.
5781 **
5782 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
5783 ** SQLITE_OK is returned if the directory is successfully created, or
5784 ** SQLITE_ERROR otherwise.
5785 */
5786 static int makeDirectory(
5787   const char *zFile
5788 ){
5789   char *zCopy = sqlite3_mprintf("%s", zFile);
5790   int rc = SQLITE_OK;
5791 
5792   if( zCopy==0 ){
5793     rc = SQLITE_NOMEM;
5794   }else{
5795     int nCopy = (int)strlen(zCopy);
5796     int i = 1;
5797 
5798     while( rc==SQLITE_OK ){
5799       struct stat sStat;
5800       int rc2;
5801 
5802       for(; zCopy[i]!='/' && i<nCopy; i++);
5803       if( i==nCopy ) break;
5804       zCopy[i] = '\0';
5805 
5806       rc2 = fileStat(zCopy, &sStat);
5807       if( rc2!=0 ){
5808         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
5809       }else{
5810         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
5811       }
5812       zCopy[i] = '/';
5813       i++;
5814     }
5815 
5816     sqlite3_free(zCopy);
5817   }
5818 
5819   return rc;
5820 }
5821 
5822 /*
5823 ** This function does the work for the writefile() UDF. Refer to
5824 ** header comments at the top of this file for details.
5825 */
5826 static int writeFile(
5827   sqlite3_context *pCtx,          /* Context to return bytes written in */
5828   const char *zFile,              /* File to write */
5829   sqlite3_value *pData,           /* Data to write */
5830   mode_t mode,                    /* MODE parameter passed to writefile() */
5831   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
5832 ){
5833   if( zFile==0 ) return 1;
5834 #if !defined(_WIN32) && !defined(WIN32)
5835   if( S_ISLNK(mode) ){
5836     const char *zTo = (const char*)sqlite3_value_text(pData);
5837     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
5838   }else
5839 #endif
5840   {
5841     if( S_ISDIR(mode) ){
5842       if( mkdir(zFile, mode) ){
5843         /* The mkdir() call to create the directory failed. This might not
5844         ** be an error though - if there is already a directory at the same
5845         ** path and either the permissions already match or can be changed
5846         ** to do so using chmod(), it is not an error.  */
5847         struct stat sStat;
5848         if( errno!=EEXIST
5849          || 0!=fileStat(zFile, &sStat)
5850          || !S_ISDIR(sStat.st_mode)
5851          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
5852         ){
5853           return 1;
5854         }
5855       }
5856     }else{
5857       sqlite3_int64 nWrite = 0;
5858       const char *z;
5859       int rc = 0;
5860       FILE *out = fopen(zFile, "wb");
5861       if( out==0 ) return 1;
5862       z = (const char*)sqlite3_value_blob(pData);
5863       if( z ){
5864         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
5865         nWrite = sqlite3_value_bytes(pData);
5866         if( nWrite!=n ){
5867           rc = 1;
5868         }
5869       }
5870       fclose(out);
5871       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
5872         rc = 1;
5873       }
5874       if( rc ) return 2;
5875       sqlite3_result_int64(pCtx, nWrite);
5876     }
5877   }
5878 
5879   if( mtime>=0 ){
5880 #if defined(_WIN32)
5881 #if !SQLITE_OS_WINRT
5882     /* Windows */
5883     FILETIME lastAccess;
5884     FILETIME lastWrite;
5885     SYSTEMTIME currentTime;
5886     LONGLONG intervals;
5887     HANDLE hFile;
5888     LPWSTR zUnicodeName;
5889     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
5890 
5891     GetSystemTime(&currentTime);
5892     SystemTimeToFileTime(&currentTime, &lastAccess);
5893     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
5894     lastWrite.dwLowDateTime = (DWORD)intervals;
5895     lastWrite.dwHighDateTime = intervals >> 32;
5896     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
5897     if( zUnicodeName==0 ){
5898       return 1;
5899     }
5900     hFile = CreateFileW(
5901       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
5902       FILE_FLAG_BACKUP_SEMANTICS, NULL
5903     );
5904     sqlite3_free(zUnicodeName);
5905     if( hFile!=INVALID_HANDLE_VALUE ){
5906       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
5907       CloseHandle(hFile);
5908       return !bResult;
5909     }else{
5910       return 1;
5911     }
5912 #endif
5913 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
5914     /* Recent unix */
5915     struct timespec times[2];
5916     times[0].tv_nsec = times[1].tv_nsec = 0;
5917     times[0].tv_sec = time(0);
5918     times[1].tv_sec = mtime;
5919     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
5920       return 1;
5921     }
5922 #else
5923     /* Legacy unix */
5924     struct timeval times[2];
5925     times[0].tv_usec = times[1].tv_usec = 0;
5926     times[0].tv_sec = time(0);
5927     times[1].tv_sec = mtime;
5928     if( utimes(zFile, times) ){
5929       return 1;
5930     }
5931 #endif
5932   }
5933 
5934   return 0;
5935 }
5936 
5937 /*
5938 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
5939 ** Refer to header comments at the top of this file for details.
5940 */
5941 static void writefileFunc(
5942   sqlite3_context *context,
5943   int argc,
5944   sqlite3_value **argv
5945 ){
5946   const char *zFile;
5947   mode_t mode = 0;
5948   int res;
5949   sqlite3_int64 mtime = -1;
5950 
5951   if( argc<2 || argc>4 ){
5952     sqlite3_result_error(context,
5953         "wrong number of arguments to function writefile()", -1
5954     );
5955     return;
5956   }
5957 
5958   zFile = (const char*)sqlite3_value_text(argv[0]);
5959   if( zFile==0 ) return;
5960   if( argc>=3 ){
5961     mode = (mode_t)sqlite3_value_int(argv[2]);
5962   }
5963   if( argc==4 ){
5964     mtime = sqlite3_value_int64(argv[3]);
5965   }
5966 
5967   res = writeFile(context, zFile, argv[1], mode, mtime);
5968   if( res==1 && errno==ENOENT ){
5969     if( makeDirectory(zFile)==SQLITE_OK ){
5970       res = writeFile(context, zFile, argv[1], mode, mtime);
5971     }
5972   }
5973 
5974   if( argc>2 && res!=0 ){
5975     if( S_ISLNK(mode) ){
5976       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
5977     }else if( S_ISDIR(mode) ){
5978       ctxErrorMsg(context, "failed to create directory: %s", zFile);
5979     }else{
5980       ctxErrorMsg(context, "failed to write file: %s", zFile);
5981     }
5982   }
5983 }
5984 
5985 /*
5986 ** SQL function:   lsmode(MODE)
5987 **
5988 ** Given a numberic st_mode from stat(), convert it into a human-readable
5989 ** text string in the style of "ls -l".
5990 */
5991 static void lsModeFunc(
5992   sqlite3_context *context,
5993   int argc,
5994   sqlite3_value **argv
5995 ){
5996   int i;
5997   int iMode = sqlite3_value_int(argv[0]);
5998   char z[16];
5999   (void)argc;
6000   if( S_ISLNK(iMode) ){
6001     z[0] = 'l';
6002   }else if( S_ISREG(iMode) ){
6003     z[0] = '-';
6004   }else if( S_ISDIR(iMode) ){
6005     z[0] = 'd';
6006   }else{
6007     z[0] = '?';
6008   }
6009   for(i=0; i<3; i++){
6010     int m = (iMode >> ((2-i)*3));
6011     char *a = &z[1 + i*3];
6012     a[0] = (m & 0x4) ? 'r' : '-';
6013     a[1] = (m & 0x2) ? 'w' : '-';
6014     a[2] = (m & 0x1) ? 'x' : '-';
6015   }
6016   z[10] = '\0';
6017   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
6018 }
6019 
6020 #ifndef SQLITE_OMIT_VIRTUALTABLE
6021 
6022 /*
6023 ** Cursor type for recursively iterating through a directory structure.
6024 */
6025 typedef struct fsdir_cursor fsdir_cursor;
6026 typedef struct FsdirLevel FsdirLevel;
6027 
6028 struct FsdirLevel {
6029   DIR *pDir;                 /* From opendir() */
6030   char *zDir;                /* Name of directory (nul-terminated) */
6031 };
6032 
6033 struct fsdir_cursor {
6034   sqlite3_vtab_cursor base;  /* Base class - must be first */
6035 
6036   int nLvl;                  /* Number of entries in aLvl[] array */
6037   int iLvl;                  /* Index of current entry */
6038   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
6039 
6040   const char *zBase;
6041   int nBase;
6042 
6043   struct stat sStat;         /* Current lstat() results */
6044   char *zPath;               /* Path to current entry */
6045   sqlite3_int64 iRowid;      /* Current rowid */
6046 };
6047 
6048 typedef struct fsdir_tab fsdir_tab;
6049 struct fsdir_tab {
6050   sqlite3_vtab base;         /* Base class - must be first */
6051 };
6052 
6053 /*
6054 ** Construct a new fsdir virtual table object.
6055 */
6056 static int fsdirConnect(
6057   sqlite3 *db,
6058   void *pAux,
6059   int argc, const char *const*argv,
6060   sqlite3_vtab **ppVtab,
6061   char **pzErr
6062 ){
6063   fsdir_tab *pNew = 0;
6064   int rc;
6065   (void)pAux;
6066   (void)argc;
6067   (void)argv;
6068   (void)pzErr;
6069   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
6070   if( rc==SQLITE_OK ){
6071     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
6072     if( pNew==0 ) return SQLITE_NOMEM;
6073     memset(pNew, 0, sizeof(*pNew));
6074     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
6075   }
6076   *ppVtab = (sqlite3_vtab*)pNew;
6077   return rc;
6078 }
6079 
6080 /*
6081 ** This method is the destructor for fsdir vtab objects.
6082 */
6083 static int fsdirDisconnect(sqlite3_vtab *pVtab){
6084   sqlite3_free(pVtab);
6085   return SQLITE_OK;
6086 }
6087 
6088 /*
6089 ** Constructor for a new fsdir_cursor object.
6090 */
6091 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6092   fsdir_cursor *pCur;
6093   (void)p;
6094   pCur = sqlite3_malloc( sizeof(*pCur) );
6095   if( pCur==0 ) return SQLITE_NOMEM;
6096   memset(pCur, 0, sizeof(*pCur));
6097   pCur->iLvl = -1;
6098   *ppCursor = &pCur->base;
6099   return SQLITE_OK;
6100 }
6101 
6102 /*
6103 ** Reset a cursor back to the state it was in when first returned
6104 ** by fsdirOpen().
6105 */
6106 static void fsdirResetCursor(fsdir_cursor *pCur){
6107   int i;
6108   for(i=0; i<=pCur->iLvl; i++){
6109     FsdirLevel *pLvl = &pCur->aLvl[i];
6110     if( pLvl->pDir ) closedir(pLvl->pDir);
6111     sqlite3_free(pLvl->zDir);
6112   }
6113   sqlite3_free(pCur->zPath);
6114   sqlite3_free(pCur->aLvl);
6115   pCur->aLvl = 0;
6116   pCur->zPath = 0;
6117   pCur->zBase = 0;
6118   pCur->nBase = 0;
6119   pCur->nLvl = 0;
6120   pCur->iLvl = -1;
6121   pCur->iRowid = 1;
6122 }
6123 
6124 /*
6125 ** Destructor for an fsdir_cursor.
6126 */
6127 static int fsdirClose(sqlite3_vtab_cursor *cur){
6128   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6129 
6130   fsdirResetCursor(pCur);
6131   sqlite3_free(pCur);
6132   return SQLITE_OK;
6133 }
6134 
6135 /*
6136 ** Set the error message for the virtual table associated with cursor
6137 ** pCur to the results of vprintf(zFmt, ...).
6138 */
6139 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
6140   va_list ap;
6141   va_start(ap, zFmt);
6142   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
6143   va_end(ap);
6144 }
6145 
6146 
6147 /*
6148 ** Advance an fsdir_cursor to its next row of output.
6149 */
6150 static int fsdirNext(sqlite3_vtab_cursor *cur){
6151   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6152   mode_t m = pCur->sStat.st_mode;
6153 
6154   pCur->iRowid++;
6155   if( S_ISDIR(m) ){
6156     /* Descend into this directory */
6157     int iNew = pCur->iLvl + 1;
6158     FsdirLevel *pLvl;
6159     if( iNew>=pCur->nLvl ){
6160       int nNew = iNew+1;
6161       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
6162       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
6163       if( aNew==0 ) return SQLITE_NOMEM;
6164       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
6165       pCur->aLvl = aNew;
6166       pCur->nLvl = nNew;
6167     }
6168     pCur->iLvl = iNew;
6169     pLvl = &pCur->aLvl[iNew];
6170 
6171     pLvl->zDir = pCur->zPath;
6172     pCur->zPath = 0;
6173     pLvl->pDir = opendir(pLvl->zDir);
6174     if( pLvl->pDir==0 ){
6175       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
6176       return SQLITE_ERROR;
6177     }
6178   }
6179 
6180   while( pCur->iLvl>=0 ){
6181     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
6182     struct dirent *pEntry = readdir(pLvl->pDir);
6183     if( pEntry ){
6184       if( pEntry->d_name[0]=='.' ){
6185        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
6186        if( pEntry->d_name[1]=='\0' ) continue;
6187       }
6188       sqlite3_free(pCur->zPath);
6189       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
6190       if( pCur->zPath==0 ) return SQLITE_NOMEM;
6191       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
6192         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
6193         return SQLITE_ERROR;
6194       }
6195       return SQLITE_OK;
6196     }
6197     closedir(pLvl->pDir);
6198     sqlite3_free(pLvl->zDir);
6199     pLvl->pDir = 0;
6200     pLvl->zDir = 0;
6201     pCur->iLvl--;
6202   }
6203 
6204   /* EOF */
6205   sqlite3_free(pCur->zPath);
6206   pCur->zPath = 0;
6207   return SQLITE_OK;
6208 }
6209 
6210 /*
6211 ** Return values of columns for the row at which the series_cursor
6212 ** is currently pointing.
6213 */
6214 static int fsdirColumn(
6215   sqlite3_vtab_cursor *cur,   /* The cursor */
6216   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6217   int i                       /* Which column to return */
6218 ){
6219   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6220   switch( i ){
6221     case FSDIR_COLUMN_NAME: {
6222       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
6223       break;
6224     }
6225 
6226     case FSDIR_COLUMN_MODE:
6227       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
6228       break;
6229 
6230     case FSDIR_COLUMN_MTIME:
6231       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
6232       break;
6233 
6234     case FSDIR_COLUMN_DATA: {
6235       mode_t m = pCur->sStat.st_mode;
6236       if( S_ISDIR(m) ){
6237         sqlite3_result_null(ctx);
6238 #if !defined(_WIN32) && !defined(WIN32)
6239       }else if( S_ISLNK(m) ){
6240         char aStatic[64];
6241         char *aBuf = aStatic;
6242         sqlite3_int64 nBuf = 64;
6243         int n;
6244 
6245         while( 1 ){
6246           n = readlink(pCur->zPath, aBuf, nBuf);
6247           if( n<nBuf ) break;
6248           if( aBuf!=aStatic ) sqlite3_free(aBuf);
6249           nBuf = nBuf*2;
6250           aBuf = sqlite3_malloc64(nBuf);
6251           if( aBuf==0 ){
6252             sqlite3_result_error_nomem(ctx);
6253             return SQLITE_NOMEM;
6254           }
6255         }
6256 
6257         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
6258         if( aBuf!=aStatic ) sqlite3_free(aBuf);
6259 #endif
6260       }else{
6261         readFileContents(ctx, pCur->zPath);
6262       }
6263     }
6264     case FSDIR_COLUMN_PATH:
6265     default: {
6266       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
6267       ** always return their values as NULL */
6268       break;
6269     }
6270   }
6271   return SQLITE_OK;
6272 }
6273 
6274 /*
6275 ** Return the rowid for the current row. In this implementation, the
6276 ** first row returned is assigned rowid value 1, and each subsequent
6277 ** row a value 1 more than that of the previous.
6278 */
6279 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
6280   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6281   *pRowid = pCur->iRowid;
6282   return SQLITE_OK;
6283 }
6284 
6285 /*
6286 ** Return TRUE if the cursor has been moved off of the last
6287 ** row of output.
6288 */
6289 static int fsdirEof(sqlite3_vtab_cursor *cur){
6290   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6291   return (pCur->zPath==0);
6292 }
6293 
6294 /*
6295 ** xFilter callback.
6296 **
6297 ** idxNum==1   PATH parameter only
6298 ** idxNum==2   Both PATH and DIR supplied
6299 */
6300 static int fsdirFilter(
6301   sqlite3_vtab_cursor *cur,
6302   int idxNum, const char *idxStr,
6303   int argc, sqlite3_value **argv
6304 ){
6305   const char *zDir = 0;
6306   fsdir_cursor *pCur = (fsdir_cursor*)cur;
6307   (void)idxStr;
6308   fsdirResetCursor(pCur);
6309 
6310   if( idxNum==0 ){
6311     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
6312     return SQLITE_ERROR;
6313   }
6314 
6315   assert( argc==idxNum && (argc==1 || argc==2) );
6316   zDir = (const char*)sqlite3_value_text(argv[0]);
6317   if( zDir==0 ){
6318     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
6319     return SQLITE_ERROR;
6320   }
6321   if( argc==2 ){
6322     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
6323   }
6324   if( pCur->zBase ){
6325     pCur->nBase = (int)strlen(pCur->zBase)+1;
6326     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
6327   }else{
6328     pCur->zPath = sqlite3_mprintf("%s", zDir);
6329   }
6330 
6331   if( pCur->zPath==0 ){
6332     return SQLITE_NOMEM;
6333   }
6334   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
6335     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
6336     return SQLITE_ERROR;
6337   }
6338 
6339   return SQLITE_OK;
6340 }
6341 
6342 /*
6343 ** SQLite will invoke this method one or more times while planning a query
6344 ** that uses the generate_series virtual table.  This routine needs to create
6345 ** a query plan for each invocation and compute an estimated cost for that
6346 ** plan.
6347 **
6348 ** In this implementation idxNum is used to represent the
6349 ** query plan.  idxStr is unused.
6350 **
6351 ** The query plan is represented by values of idxNum:
6352 **
6353 **  (1)  The path value is supplied by argv[0]
6354 **  (2)  Path is in argv[0] and dir is in argv[1]
6355 */
6356 static int fsdirBestIndex(
6357   sqlite3_vtab *tab,
6358   sqlite3_index_info *pIdxInfo
6359 ){
6360   int i;                 /* Loop over constraints */
6361   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
6362   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
6363   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
6364   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
6365   const struct sqlite3_index_constraint *pConstraint;
6366 
6367   (void)tab;
6368   pConstraint = pIdxInfo->aConstraint;
6369   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6370     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
6371     switch( pConstraint->iColumn ){
6372       case FSDIR_COLUMN_PATH: {
6373         if( pConstraint->usable ){
6374           idxPath = i;
6375           seenPath = 0;
6376         }else if( idxPath<0 ){
6377           seenPath = 1;
6378         }
6379         break;
6380       }
6381       case FSDIR_COLUMN_DIR: {
6382         if( pConstraint->usable ){
6383           idxDir = i;
6384           seenDir = 0;
6385         }else if( idxDir<0 ){
6386           seenDir = 1;
6387         }
6388         break;
6389       }
6390     }
6391   }
6392   if( seenPath || seenDir ){
6393     /* If input parameters are unusable, disallow this plan */
6394     return SQLITE_CONSTRAINT;
6395   }
6396 
6397   if( idxPath<0 ){
6398     pIdxInfo->idxNum = 0;
6399     /* The pIdxInfo->estimatedCost should have been initialized to a huge
6400     ** number.  Leave it unchanged. */
6401     pIdxInfo->estimatedRows = 0x7fffffff;
6402   }else{
6403     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
6404     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
6405     if( idxDir>=0 ){
6406       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
6407       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
6408       pIdxInfo->idxNum = 2;
6409       pIdxInfo->estimatedCost = 10.0;
6410     }else{
6411       pIdxInfo->idxNum = 1;
6412       pIdxInfo->estimatedCost = 100.0;
6413     }
6414   }
6415 
6416   return SQLITE_OK;
6417 }
6418 
6419 /*
6420 ** Register the "fsdir" virtual table.
6421 */
6422 static int fsdirRegister(sqlite3 *db){
6423   static sqlite3_module fsdirModule = {
6424     0,                         /* iVersion */
6425     0,                         /* xCreate */
6426     fsdirConnect,              /* xConnect */
6427     fsdirBestIndex,            /* xBestIndex */
6428     fsdirDisconnect,           /* xDisconnect */
6429     0,                         /* xDestroy */
6430     fsdirOpen,                 /* xOpen - open a cursor */
6431     fsdirClose,                /* xClose - close a cursor */
6432     fsdirFilter,               /* xFilter - configure scan constraints */
6433     fsdirNext,                 /* xNext - advance a cursor */
6434     fsdirEof,                  /* xEof - check for end of scan */
6435     fsdirColumn,               /* xColumn - read data */
6436     fsdirRowid,                /* xRowid - read data */
6437     0,                         /* xUpdate */
6438     0,                         /* xBegin */
6439     0,                         /* xSync */
6440     0,                         /* xCommit */
6441     0,                         /* xRollback */
6442     0,                         /* xFindMethod */
6443     0,                         /* xRename */
6444     0,                         /* xSavepoint */
6445     0,                         /* xRelease */
6446     0,                         /* xRollbackTo */
6447     0,                         /* xShadowName */
6448   };
6449 
6450   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
6451   return rc;
6452 }
6453 #else         /* SQLITE_OMIT_VIRTUALTABLE */
6454 # define fsdirRegister(x) SQLITE_OK
6455 #endif
6456 
6457 #ifdef _WIN32
6458 
6459 #endif
6460 int sqlite3_fileio_init(
6461   sqlite3 *db,
6462   char **pzErrMsg,
6463   const sqlite3_api_routines *pApi
6464 ){
6465   int rc = SQLITE_OK;
6466   SQLITE_EXTENSION_INIT2(pApi);
6467   (void)pzErrMsg;  /* Unused parameter */
6468   rc = sqlite3_create_function(db, "readfile", 1,
6469                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
6470                                readfileFunc, 0, 0);
6471   if( rc==SQLITE_OK ){
6472     rc = sqlite3_create_function(db, "writefile", -1,
6473                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
6474                                  writefileFunc, 0, 0);
6475   }
6476   if( rc==SQLITE_OK ){
6477     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
6478                                  lsModeFunc, 0, 0);
6479   }
6480   if( rc==SQLITE_OK ){
6481     rc = fsdirRegister(db);
6482   }
6483   return rc;
6484 }
6485 
6486 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
6487 /* To allow a standalone DLL, make test_windirent.c use the same
6488  * redefined SQLite API calls as the above extension code does.
6489  * Just pull in this .c to accomplish this. As a beneficial side
6490  * effect, this extension becomes a single translation unit. */
6491 #  include "test_windirent.c"
6492 #endif
6493 
6494 /************************* End ../ext/misc/fileio.c ********************/
6495 /************************* Begin ../ext/misc/completion.c ******************/
6496 /*
6497 ** 2017-07-10
6498 **
6499 ** The author disclaims copyright to this source code.  In place of
6500 ** a legal notice, here is a blessing:
6501 **
6502 **    May you do good and not evil.
6503 **    May you find forgiveness for yourself and forgive others.
6504 **    May you share freely, never taking more than you give.
6505 **
6506 *************************************************************************
6507 **
6508 ** This file implements an eponymous virtual table that returns suggested
6509 ** completions for a partial SQL input.
6510 **
6511 ** Suggested usage:
6512 **
6513 **     SELECT DISTINCT candidate COLLATE nocase
6514 **       FROM completion($prefix,$wholeline)
6515 **      ORDER BY 1;
6516 **
6517 ** The two query parameters are optional.  $prefix is the text of the
6518 ** current word being typed and that is to be completed.  $wholeline is
6519 ** the complete input line, used for context.
6520 **
6521 ** The raw completion() table might return the same candidate multiple
6522 ** times, for example if the same column name is used to two or more
6523 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
6524 ** the DISTINCT and ORDER BY are recommended.
6525 **
6526 ** This virtual table operates at the speed of human typing, and so there
6527 ** is no attempt to make it fast.  Even a slow implementation will be much
6528 ** faster than any human can type.
6529 **
6530 */
6531 /* #include "sqlite3ext.h" */
6532 SQLITE_EXTENSION_INIT1
6533 #include <assert.h>
6534 #include <string.h>
6535 #include <ctype.h>
6536 
6537 #ifndef SQLITE_OMIT_VIRTUALTABLE
6538 
6539 /* completion_vtab is a subclass of sqlite3_vtab which will
6540 ** serve as the underlying representation of a completion virtual table
6541 */
6542 typedef struct completion_vtab completion_vtab;
6543 struct completion_vtab {
6544   sqlite3_vtab base;  /* Base class - must be first */
6545   sqlite3 *db;        /* Database connection for this completion vtab */
6546 };
6547 
6548 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
6549 ** serve as the underlying representation of a cursor that scans
6550 ** over rows of the result
6551 */
6552 typedef struct completion_cursor completion_cursor;
6553 struct completion_cursor {
6554   sqlite3_vtab_cursor base;  /* Base class - must be first */
6555   sqlite3 *db;               /* Database connection for this cursor */
6556   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
6557   char *zPrefix;             /* The prefix for the word we want to complete */
6558   char *zLine;               /* The whole that we want to complete */
6559   const char *zCurrentRow;   /* Current output row */
6560   int szRow;                 /* Length of the zCurrentRow string */
6561   sqlite3_stmt *pStmt;       /* Current statement */
6562   sqlite3_int64 iRowid;      /* The rowid */
6563   int ePhase;                /* Current phase */
6564   int j;                     /* inter-phase counter */
6565 };
6566 
6567 /* Values for ePhase:
6568 */
6569 #define COMPLETION_FIRST_PHASE   1
6570 #define COMPLETION_KEYWORDS      1
6571 #define COMPLETION_PRAGMAS       2
6572 #define COMPLETION_FUNCTIONS     3
6573 #define COMPLETION_COLLATIONS    4
6574 #define COMPLETION_INDEXES       5
6575 #define COMPLETION_TRIGGERS      6
6576 #define COMPLETION_DATABASES     7
6577 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
6578 #define COMPLETION_COLUMNS       9
6579 #define COMPLETION_MODULES       10
6580 #define COMPLETION_EOF           11
6581 
6582 /*
6583 ** The completionConnect() method is invoked to create a new
6584 ** completion_vtab that describes the completion virtual table.
6585 **
6586 ** Think of this routine as the constructor for completion_vtab objects.
6587 **
6588 ** All this routine needs to do is:
6589 **
6590 **    (1) Allocate the completion_vtab object and initialize all fields.
6591 **
6592 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
6593 **        result set of queries against completion will look like.
6594 */
6595 static int completionConnect(
6596   sqlite3 *db,
6597   void *pAux,
6598   int argc, const char *const*argv,
6599   sqlite3_vtab **ppVtab,
6600   char **pzErr
6601 ){
6602   completion_vtab *pNew;
6603   int rc;
6604 
6605   (void)(pAux);    /* Unused parameter */
6606   (void)(argc);    /* Unused parameter */
6607   (void)(argv);    /* Unused parameter */
6608   (void)(pzErr);   /* Unused parameter */
6609 
6610 /* Column numbers */
6611 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
6612 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
6613 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
6614 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
6615 
6616   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
6617   rc = sqlite3_declare_vtab(db,
6618       "CREATE TABLE x("
6619       "  candidate TEXT,"
6620       "  prefix TEXT HIDDEN,"
6621       "  wholeline TEXT HIDDEN,"
6622       "  phase INT HIDDEN"        /* Used for debugging only */
6623       ")");
6624   if( rc==SQLITE_OK ){
6625     pNew = sqlite3_malloc( sizeof(*pNew) );
6626     *ppVtab = (sqlite3_vtab*)pNew;
6627     if( pNew==0 ) return SQLITE_NOMEM;
6628     memset(pNew, 0, sizeof(*pNew));
6629     pNew->db = db;
6630   }
6631   return rc;
6632 }
6633 
6634 /*
6635 ** This method is the destructor for completion_cursor objects.
6636 */
6637 static int completionDisconnect(sqlite3_vtab *pVtab){
6638   sqlite3_free(pVtab);
6639   return SQLITE_OK;
6640 }
6641 
6642 /*
6643 ** Constructor for a new completion_cursor object.
6644 */
6645 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6646   completion_cursor *pCur;
6647   pCur = sqlite3_malloc( sizeof(*pCur) );
6648   if( pCur==0 ) return SQLITE_NOMEM;
6649   memset(pCur, 0, sizeof(*pCur));
6650   pCur->db = ((completion_vtab*)p)->db;
6651   *ppCursor = &pCur->base;
6652   return SQLITE_OK;
6653 }
6654 
6655 /*
6656 ** Reset the completion_cursor.
6657 */
6658 static void completionCursorReset(completion_cursor *pCur){
6659   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
6660   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
6661   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
6662   pCur->j = 0;
6663 }
6664 
6665 /*
6666 ** Destructor for a completion_cursor.
6667 */
6668 static int completionClose(sqlite3_vtab_cursor *cur){
6669   completionCursorReset((completion_cursor*)cur);
6670   sqlite3_free(cur);
6671   return SQLITE_OK;
6672 }
6673 
6674 /*
6675 ** Advance a completion_cursor to its next row of output.
6676 **
6677 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
6678 ** record the current state of the scan.  This routine sets ->zCurrentRow
6679 ** to the current row of output and then returns.  If no more rows remain,
6680 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
6681 ** table that has reached the end of its scan.
6682 **
6683 ** The current implementation just lists potential identifiers and
6684 ** keywords and filters them by zPrefix.  Future enhancements should
6685 ** take zLine into account to try to restrict the set of identifiers and
6686 ** keywords based on what would be legal at the current point of input.
6687 */
6688 static int completionNext(sqlite3_vtab_cursor *cur){
6689   completion_cursor *pCur = (completion_cursor*)cur;
6690   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
6691   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
6692   pCur->iRowid++;
6693   while( pCur->ePhase!=COMPLETION_EOF ){
6694     switch( pCur->ePhase ){
6695       case COMPLETION_KEYWORDS: {
6696         if( pCur->j >= sqlite3_keyword_count() ){
6697           pCur->zCurrentRow = 0;
6698           pCur->ePhase = COMPLETION_DATABASES;
6699         }else{
6700           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
6701         }
6702         iCol = -1;
6703         break;
6704       }
6705       case COMPLETION_DATABASES: {
6706         if( pCur->pStmt==0 ){
6707           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
6708                              &pCur->pStmt, 0);
6709         }
6710         iCol = 1;
6711         eNextPhase = COMPLETION_TABLES;
6712         break;
6713       }
6714       case COMPLETION_TABLES: {
6715         if( pCur->pStmt==0 ){
6716           sqlite3_stmt *pS2;
6717           char *zSql = 0;
6718           const char *zSep = "";
6719           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
6720           while( sqlite3_step(pS2)==SQLITE_ROW ){
6721             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
6722             zSql = sqlite3_mprintf(
6723                "%z%s"
6724                "SELECT name FROM \"%w\".sqlite_schema",
6725                zSql, zSep, zDb
6726             );
6727             if( zSql==0 ) return SQLITE_NOMEM;
6728             zSep = " UNION ";
6729           }
6730           sqlite3_finalize(pS2);
6731           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
6732           sqlite3_free(zSql);
6733         }
6734         iCol = 0;
6735         eNextPhase = COMPLETION_COLUMNS;
6736         break;
6737       }
6738       case COMPLETION_COLUMNS: {
6739         if( pCur->pStmt==0 ){
6740           sqlite3_stmt *pS2;
6741           char *zSql = 0;
6742           const char *zSep = "";
6743           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
6744           while( sqlite3_step(pS2)==SQLITE_ROW ){
6745             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
6746             zSql = sqlite3_mprintf(
6747                "%z%s"
6748                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
6749                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
6750                " WHERE sm.type='table'",
6751                zSql, zSep, zDb, zDb
6752             );
6753             if( zSql==0 ) return SQLITE_NOMEM;
6754             zSep = " UNION ";
6755           }
6756           sqlite3_finalize(pS2);
6757           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
6758           sqlite3_free(zSql);
6759         }
6760         iCol = 0;
6761         eNextPhase = COMPLETION_EOF;
6762         break;
6763       }
6764     }
6765     if( iCol<0 ){
6766       /* This case is when the phase presets zCurrentRow */
6767       if( pCur->zCurrentRow==0 ) continue;
6768     }else{
6769       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
6770         /* Extract the next row of content */
6771         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
6772         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
6773       }else{
6774         /* When all rows are finished, advance to the next phase */
6775         sqlite3_finalize(pCur->pStmt);
6776         pCur->pStmt = 0;
6777         pCur->ePhase = eNextPhase;
6778         continue;
6779       }
6780     }
6781     if( pCur->nPrefix==0 ) break;
6782     if( pCur->nPrefix<=pCur->szRow
6783      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
6784     ){
6785       break;
6786     }
6787   }
6788 
6789   return SQLITE_OK;
6790 }
6791 
6792 /*
6793 ** Return values of columns for the row at which the completion_cursor
6794 ** is currently pointing.
6795 */
6796 static int completionColumn(
6797   sqlite3_vtab_cursor *cur,   /* The cursor */
6798   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
6799   int i                       /* Which column to return */
6800 ){
6801   completion_cursor *pCur = (completion_cursor*)cur;
6802   switch( i ){
6803     case COMPLETION_COLUMN_CANDIDATE: {
6804       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
6805       break;
6806     }
6807     case COMPLETION_COLUMN_PREFIX: {
6808       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
6809       break;
6810     }
6811     case COMPLETION_COLUMN_WHOLELINE: {
6812       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
6813       break;
6814     }
6815     case COMPLETION_COLUMN_PHASE: {
6816       sqlite3_result_int(ctx, pCur->ePhase);
6817       break;
6818     }
6819   }
6820   return SQLITE_OK;
6821 }
6822 
6823 /*
6824 ** Return the rowid for the current row.  In this implementation, the
6825 ** rowid is the same as the output value.
6826 */
6827 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
6828   completion_cursor *pCur = (completion_cursor*)cur;
6829   *pRowid = pCur->iRowid;
6830   return SQLITE_OK;
6831 }
6832 
6833 /*
6834 ** Return TRUE if the cursor has been moved off of the last
6835 ** row of output.
6836 */
6837 static int completionEof(sqlite3_vtab_cursor *cur){
6838   completion_cursor *pCur = (completion_cursor*)cur;
6839   return pCur->ePhase >= COMPLETION_EOF;
6840 }
6841 
6842 /*
6843 ** This method is called to "rewind" the completion_cursor object back
6844 ** to the first row of output.  This method is always called at least
6845 ** once prior to any call to completionColumn() or completionRowid() or
6846 ** completionEof().
6847 */
6848 static int completionFilter(
6849   sqlite3_vtab_cursor *pVtabCursor,
6850   int idxNum, const char *idxStr,
6851   int argc, sqlite3_value **argv
6852 ){
6853   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
6854   int iArg = 0;
6855   (void)(idxStr);   /* Unused parameter */
6856   (void)(argc);     /* Unused parameter */
6857   completionCursorReset(pCur);
6858   if( idxNum & 1 ){
6859     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
6860     if( pCur->nPrefix>0 ){
6861       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
6862       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
6863     }
6864     iArg = 1;
6865   }
6866   if( idxNum & 2 ){
6867     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
6868     if( pCur->nLine>0 ){
6869       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
6870       if( pCur->zLine==0 ) return SQLITE_NOMEM;
6871     }
6872   }
6873   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
6874     int i = pCur->nLine;
6875     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
6876       i--;
6877     }
6878     pCur->nPrefix = pCur->nLine - i;
6879     if( pCur->nPrefix>0 ){
6880       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
6881       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
6882     }
6883   }
6884   pCur->iRowid = 0;
6885   pCur->ePhase = COMPLETION_FIRST_PHASE;
6886   return completionNext(pVtabCursor);
6887 }
6888 
6889 /*
6890 ** SQLite will invoke this method one or more times while planning a query
6891 ** that uses the completion virtual table.  This routine needs to create
6892 ** a query plan for each invocation and compute an estimated cost for that
6893 ** plan.
6894 **
6895 ** There are two hidden parameters that act as arguments to the table-valued
6896 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
6897 ** is available and bit 1 is set if "wholeline" is available.
6898 */
6899 static int completionBestIndex(
6900   sqlite3_vtab *tab,
6901   sqlite3_index_info *pIdxInfo
6902 ){
6903   int i;                 /* Loop over constraints */
6904   int idxNum = 0;        /* The query plan bitmask */
6905   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
6906   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
6907   int nArg = 0;          /* Number of arguments that completeFilter() expects */
6908   const struct sqlite3_index_constraint *pConstraint;
6909 
6910   (void)(tab);    /* Unused parameter */
6911   pConstraint = pIdxInfo->aConstraint;
6912   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6913     if( pConstraint->usable==0 ) continue;
6914     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
6915     switch( pConstraint->iColumn ){
6916       case COMPLETION_COLUMN_PREFIX:
6917         prefixIdx = i;
6918         idxNum |= 1;
6919         break;
6920       case COMPLETION_COLUMN_WHOLELINE:
6921         wholelineIdx = i;
6922         idxNum |= 2;
6923         break;
6924     }
6925   }
6926   if( prefixIdx>=0 ){
6927     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
6928     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
6929   }
6930   if( wholelineIdx>=0 ){
6931     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
6932     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
6933   }
6934   pIdxInfo->idxNum = idxNum;
6935   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
6936   pIdxInfo->estimatedRows = 500 - 100*nArg;
6937   return SQLITE_OK;
6938 }
6939 
6940 /*
6941 ** This following structure defines all the methods for the
6942 ** completion virtual table.
6943 */
6944 static sqlite3_module completionModule = {
6945   0,                         /* iVersion */
6946   0,                         /* xCreate */
6947   completionConnect,         /* xConnect */
6948   completionBestIndex,       /* xBestIndex */
6949   completionDisconnect,      /* xDisconnect */
6950   0,                         /* xDestroy */
6951   completionOpen,            /* xOpen - open a cursor */
6952   completionClose,           /* xClose - close a cursor */
6953   completionFilter,          /* xFilter - configure scan constraints */
6954   completionNext,            /* xNext - advance a cursor */
6955   completionEof,             /* xEof - check for end of scan */
6956   completionColumn,          /* xColumn - read data */
6957   completionRowid,           /* xRowid - read data */
6958   0,                         /* xUpdate */
6959   0,                         /* xBegin */
6960   0,                         /* xSync */
6961   0,                         /* xCommit */
6962   0,                         /* xRollback */
6963   0,                         /* xFindMethod */
6964   0,                         /* xRename */
6965   0,                         /* xSavepoint */
6966   0,                         /* xRelease */
6967   0,                         /* xRollbackTo */
6968   0                          /* xShadowName */
6969 };
6970 
6971 #endif /* SQLITE_OMIT_VIRTUALTABLE */
6972 
6973 int sqlite3CompletionVtabInit(sqlite3 *db){
6974   int rc = SQLITE_OK;
6975 #ifndef SQLITE_OMIT_VIRTUALTABLE
6976   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
6977 #endif
6978   return rc;
6979 }
6980 
6981 #ifdef _WIN32
6982 
6983 #endif
6984 int sqlite3_completion_init(
6985   sqlite3 *db,
6986   char **pzErrMsg,
6987   const sqlite3_api_routines *pApi
6988 ){
6989   int rc = SQLITE_OK;
6990   SQLITE_EXTENSION_INIT2(pApi);
6991   (void)(pzErrMsg);  /* Unused parameter */
6992 #ifndef SQLITE_OMIT_VIRTUALTABLE
6993   rc = sqlite3CompletionVtabInit(db);
6994 #endif
6995   return rc;
6996 }
6997 
6998 /************************* End ../ext/misc/completion.c ********************/
6999 /************************* Begin ../ext/misc/appendvfs.c ******************/
7000 /*
7001 ** 2017-10-20
7002 **
7003 ** The author disclaims copyright to this source code.  In place of
7004 ** a legal notice, here is a blessing:
7005 **
7006 **    May you do good and not evil.
7007 **    May you find forgiveness for yourself and forgive others.
7008 **    May you share freely, never taking more than you give.
7009 **
7010 ******************************************************************************
7011 **
7012 ** This file implements a VFS shim that allows an SQLite database to be
7013 ** appended onto the end of some other file, such as an executable.
7014 **
7015 ** A special record must appear at the end of the file that identifies the
7016 ** file as an appended database and provides the offset to the first page
7017 ** of the exposed content. (Or, it is the length of the content prefix.)
7018 ** For best performance page 1 should be located at a disk page boundary,
7019 ** though that is not required.
7020 **
7021 ** When opening a database using this VFS, the connection might treat
7022 ** the file as an ordinary SQLite database, or it might treat it as a
7023 ** database appended onto some other file.  The decision is made by
7024 ** applying the following rules in order:
7025 **
7026 **  (1)  An empty file is an ordinary database.
7027 **
7028 **  (2)  If the file ends with the appendvfs trailer string
7029 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
7030 **
7031 **  (3)  If the file begins with the standard SQLite prefix string
7032 **       "SQLite format 3", that file is an ordinary database.
7033 **
7034 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
7035 **       set, then a new database is appended to the already existing file.
7036 **
7037 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
7038 **
7039 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
7040 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
7041 ** This VFS will not read or write past the 1GiB mark.  This restriction
7042 ** might be lifted in future versions.  For now, if you need a larger
7043 ** database, then keep it in a separate file.
7044 **
7045 ** If the file being opened is a plain database (not an appended one), then
7046 ** this shim is a pass-through into the default underlying VFS. (rule 3)
7047 **/
7048 /* #include "sqlite3ext.h" */
7049 SQLITE_EXTENSION_INIT1
7050 #include <string.h>
7051 #include <assert.h>
7052 
7053 /* The append mark at the end of the database is:
7054 **
7055 **     Start-Of-SQLite3-NNNNNNNN
7056 **     123456789 123456789 12345
7057 **
7058 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
7059 ** the offset to page 1, and also the length of the prefix content.
7060 */
7061 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
7062 #define APND_MARK_PREFIX_SZ  17
7063 #define APND_MARK_FOS_SZ      8
7064 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
7065 
7066 /*
7067 ** Maximum size of the combined prefix + database + append-mark.  This
7068 ** must be less than 0x40000000 to avoid locking issues on Windows.
7069 */
7070 #define APND_MAX_SIZE  (0x40000000)
7071 
7072 /*
7073 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
7074 */
7075 #ifndef APND_ROUNDUP
7076 #define APND_ROUNDUP 4096
7077 #endif
7078 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
7079 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
7080 
7081 /*
7082 ** Forward declaration of objects used by this utility
7083 */
7084 typedef struct sqlite3_vfs ApndVfs;
7085 typedef struct ApndFile ApndFile;
7086 
7087 /* Access to a lower-level VFS that (might) implement dynamic loading,
7088 ** access to randomness, etc.
7089 */
7090 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
7091 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
7092 
7093 /* An open appendvfs file
7094 **
7095 ** An instance of this structure describes the appended database file.
7096 ** A separate sqlite3_file object is always appended. The appended
7097 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
7098 ** the entire file, including the prefix, the database, and the
7099 ** append-mark.
7100 **
7101 ** The structure of an AppendVFS database is like this:
7102 **
7103 **   +-------------+---------+----------+-------------+
7104 **   | prefix-file | padding | database | append-mark |
7105 **   +-------------+---------+----------+-------------+
7106 **                           ^          ^
7107 **                           |          |
7108 **                         iPgOne      iMark
7109 **
7110 **
7111 ** "prefix file" -  file onto which the database has been appended.
7112 ** "padding"     -  zero or more bytes inserted so that "database"
7113 **                  starts on an APND_ROUNDUP boundary
7114 ** "database"    -  The SQLite database file
7115 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
7116 **                  the offset from the start of prefix-file to the start
7117 **                  of "database".
7118 **
7119 ** The size of the database is iMark - iPgOne.
7120 **
7121 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
7122 ** of iPgOne stored as a big-ending 64-bit integer.
7123 **
7124 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
7125 ** Or, iMark is -1 to indicate that it has not yet been written.
7126 */
7127 struct ApndFile {
7128   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
7129   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
7130   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
7131   /* Always followed by another sqlite3_file that describes the whole file */
7132 };
7133 
7134 /*
7135 ** Methods for ApndFile
7136 */
7137 static int apndClose(sqlite3_file*);
7138 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
7139 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
7140 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
7141 static int apndSync(sqlite3_file*, int flags);
7142 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
7143 static int apndLock(sqlite3_file*, int);
7144 static int apndUnlock(sqlite3_file*, int);
7145 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
7146 static int apndFileControl(sqlite3_file*, int op, void *pArg);
7147 static int apndSectorSize(sqlite3_file*);
7148 static int apndDeviceCharacteristics(sqlite3_file*);
7149 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
7150 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
7151 static void apndShmBarrier(sqlite3_file*);
7152 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
7153 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
7154 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
7155 
7156 /*
7157 ** Methods for ApndVfs
7158 */
7159 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
7160 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
7161 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
7162 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
7163 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
7164 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
7165 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
7166 static void apndDlClose(sqlite3_vfs*, void*);
7167 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
7168 static int apndSleep(sqlite3_vfs*, int microseconds);
7169 static int apndCurrentTime(sqlite3_vfs*, double*);
7170 static int apndGetLastError(sqlite3_vfs*, int, char *);
7171 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
7172 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
7173 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
7174 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
7175 
7176 static sqlite3_vfs apnd_vfs = {
7177   3,                            /* iVersion (set when registered) */
7178   0,                            /* szOsFile (set when registered) */
7179   1024,                         /* mxPathname */
7180   0,                            /* pNext */
7181   "apndvfs",                    /* zName */
7182   0,                            /* pAppData (set when registered) */
7183   apndOpen,                     /* xOpen */
7184   apndDelete,                   /* xDelete */
7185   apndAccess,                   /* xAccess */
7186   apndFullPathname,             /* xFullPathname */
7187   apndDlOpen,                   /* xDlOpen */
7188   apndDlError,                  /* xDlError */
7189   apndDlSym,                    /* xDlSym */
7190   apndDlClose,                  /* xDlClose */
7191   apndRandomness,               /* xRandomness */
7192   apndSleep,                    /* xSleep */
7193   apndCurrentTime,              /* xCurrentTime */
7194   apndGetLastError,             /* xGetLastError */
7195   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
7196   apndSetSystemCall,            /* xSetSystemCall */
7197   apndGetSystemCall,            /* xGetSystemCall */
7198   apndNextSystemCall            /* xNextSystemCall */
7199 };
7200 
7201 static const sqlite3_io_methods apnd_io_methods = {
7202   3,                              /* iVersion */
7203   apndClose,                      /* xClose */
7204   apndRead,                       /* xRead */
7205   apndWrite,                      /* xWrite */
7206   apndTruncate,                   /* xTruncate */
7207   apndSync,                       /* xSync */
7208   apndFileSize,                   /* xFileSize */
7209   apndLock,                       /* xLock */
7210   apndUnlock,                     /* xUnlock */
7211   apndCheckReservedLock,          /* xCheckReservedLock */
7212   apndFileControl,                /* xFileControl */
7213   apndSectorSize,                 /* xSectorSize */
7214   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
7215   apndShmMap,                     /* xShmMap */
7216   apndShmLock,                    /* xShmLock */
7217   apndShmBarrier,                 /* xShmBarrier */
7218   apndShmUnmap,                   /* xShmUnmap */
7219   apndFetch,                      /* xFetch */
7220   apndUnfetch                     /* xUnfetch */
7221 };
7222 
7223 /*
7224 ** Close an apnd-file.
7225 */
7226 static int apndClose(sqlite3_file *pFile){
7227   pFile = ORIGFILE(pFile);
7228   return pFile->pMethods->xClose(pFile);
7229 }
7230 
7231 /*
7232 ** Read data from an apnd-file.
7233 */
7234 static int apndRead(
7235   sqlite3_file *pFile,
7236   void *zBuf,
7237   int iAmt,
7238   sqlite_int64 iOfst
7239 ){
7240   ApndFile *paf = (ApndFile *)pFile;
7241   pFile = ORIGFILE(pFile);
7242   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
7243 }
7244 
7245 /*
7246 ** Add the append-mark onto what should become the end of the file.
7247 *  If and only if this succeeds, internal ApndFile.iMark is updated.
7248 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
7249 */
7250 static int apndWriteMark(
7251   ApndFile *paf,
7252   sqlite3_file *pFile,
7253   sqlite_int64 iWriteEnd
7254 ){
7255   sqlite_int64 iPgOne = paf->iPgOne;
7256   unsigned char a[APND_MARK_SIZE];
7257   int i = APND_MARK_FOS_SZ;
7258   int rc;
7259   assert(pFile == ORIGFILE(paf));
7260   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
7261   while( --i >= 0 ){
7262     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
7263     iPgOne >>= 8;
7264   }
7265   iWriteEnd += paf->iPgOne;
7266   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
7267                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
7268     paf->iMark = iWriteEnd;
7269   }
7270   return rc;
7271 }
7272 
7273 /*
7274 ** Write data to an apnd-file.
7275 */
7276 static int apndWrite(
7277   sqlite3_file *pFile,
7278   const void *zBuf,
7279   int iAmt,
7280   sqlite_int64 iOfst
7281 ){
7282   ApndFile *paf = (ApndFile *)pFile;
7283   sqlite_int64 iWriteEnd = iOfst + iAmt;
7284   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
7285   pFile = ORIGFILE(pFile);
7286   /* If append-mark is absent or will be overwritten, write it. */
7287   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
7288     int rc = apndWriteMark(paf, pFile, iWriteEnd);
7289     if( SQLITE_OK!=rc ) return rc;
7290   }
7291   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
7292 }
7293 
7294 /*
7295 ** Truncate an apnd-file.
7296 */
7297 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
7298   ApndFile *paf = (ApndFile *)pFile;
7299   pFile = ORIGFILE(pFile);
7300   /* The append mark goes out first so truncate failure does not lose it. */
7301   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
7302   /* Truncate underlying file just past append mark */
7303   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
7304 }
7305 
7306 /*
7307 ** Sync an apnd-file.
7308 */
7309 static int apndSync(sqlite3_file *pFile, int flags){
7310   pFile = ORIGFILE(pFile);
7311   return pFile->pMethods->xSync(pFile, flags);
7312 }
7313 
7314 /*
7315 ** Return the current file-size of an apnd-file.
7316 ** If the append mark is not yet there, the file-size is 0.
7317 */
7318 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
7319   ApndFile *paf = (ApndFile *)pFile;
7320   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
7321   return SQLITE_OK;
7322 }
7323 
7324 /*
7325 ** Lock an apnd-file.
7326 */
7327 static int apndLock(sqlite3_file *pFile, int eLock){
7328   pFile = ORIGFILE(pFile);
7329   return pFile->pMethods->xLock(pFile, eLock);
7330 }
7331 
7332 /*
7333 ** Unlock an apnd-file.
7334 */
7335 static int apndUnlock(sqlite3_file *pFile, int eLock){
7336   pFile = ORIGFILE(pFile);
7337   return pFile->pMethods->xUnlock(pFile, eLock);
7338 }
7339 
7340 /*
7341 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
7342 */
7343 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
7344   pFile = ORIGFILE(pFile);
7345   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
7346 }
7347 
7348 /*
7349 ** File control method. For custom operations on an apnd-file.
7350 */
7351 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
7352   ApndFile *paf = (ApndFile *)pFile;
7353   int rc;
7354   pFile = ORIGFILE(pFile);
7355   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
7356   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
7357   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
7358     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
7359   }
7360   return rc;
7361 }
7362 
7363 /*
7364 ** Return the sector-size in bytes for an apnd-file.
7365 */
7366 static int apndSectorSize(sqlite3_file *pFile){
7367   pFile = ORIGFILE(pFile);
7368   return pFile->pMethods->xSectorSize(pFile);
7369 }
7370 
7371 /*
7372 ** Return the device characteristic flags supported by an apnd-file.
7373 */
7374 static int apndDeviceCharacteristics(sqlite3_file *pFile){
7375   pFile = ORIGFILE(pFile);
7376   return pFile->pMethods->xDeviceCharacteristics(pFile);
7377 }
7378 
7379 /* Create a shared memory file mapping */
7380 static int apndShmMap(
7381   sqlite3_file *pFile,
7382   int iPg,
7383   int pgsz,
7384   int bExtend,
7385   void volatile **pp
7386 ){
7387   pFile = ORIGFILE(pFile);
7388   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
7389 }
7390 
7391 /* Perform locking on a shared-memory segment */
7392 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
7393   pFile = ORIGFILE(pFile);
7394   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
7395 }
7396 
7397 /* Memory barrier operation on shared memory */
7398 static void apndShmBarrier(sqlite3_file *pFile){
7399   pFile = ORIGFILE(pFile);
7400   pFile->pMethods->xShmBarrier(pFile);
7401 }
7402 
7403 /* Unmap a shared memory segment */
7404 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
7405   pFile = ORIGFILE(pFile);
7406   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
7407 }
7408 
7409 /* Fetch a page of a memory-mapped file */
7410 static int apndFetch(
7411   sqlite3_file *pFile,
7412   sqlite3_int64 iOfst,
7413   int iAmt,
7414   void **pp
7415 ){
7416   ApndFile *p = (ApndFile *)pFile;
7417   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
7418     return SQLITE_IOERR; /* Cannot read what is not yet there. */
7419   }
7420   pFile = ORIGFILE(pFile);
7421   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
7422 }
7423 
7424 /* Release a memory-mapped page */
7425 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
7426   ApndFile *p = (ApndFile *)pFile;
7427   pFile = ORIGFILE(pFile);
7428   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
7429 }
7430 
7431 /*
7432 ** Try to read the append-mark off the end of a file.  Return the
7433 ** start of the appended database if the append-mark is present.
7434 ** If there is no valid append-mark, return -1;
7435 **
7436 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
7437 ** indicates that the appended database contains at least one page.  The
7438 ** start-of-database value must be a multiple of 512.
7439 */
7440 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
7441   int rc, i;
7442   sqlite3_int64 iMark;
7443   int msbs = 8 * (APND_MARK_FOS_SZ-1);
7444   unsigned char a[APND_MARK_SIZE];
7445 
7446   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
7447   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
7448   if( rc ) return -1;
7449   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
7450   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
7451   for(i=1; i<8; i++){
7452     msbs -= 8;
7453     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
7454   }
7455   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
7456   if( iMark & 0x1ff ) return -1;
7457   return iMark;
7458 }
7459 
7460 static const char apvfsSqliteHdr[] = "SQLite format 3";
7461 /*
7462 ** Check to see if the file is an appendvfs SQLite database file.
7463 ** Return true iff it is such. Parameter sz is the file's size.
7464 */
7465 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
7466   int rc;
7467   char zHdr[16];
7468   sqlite3_int64 iMark = apndReadMark(sz, pFile);
7469   if( iMark>=0 ){
7470     /* If file has the correct end-marker, the expected odd size, and the
7471     ** SQLite DB type marker where the end-marker puts it, then it
7472     ** is an appendvfs database.
7473     */
7474     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
7475     if( SQLITE_OK==rc
7476      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
7477      && (sz & 0x1ff) == APND_MARK_SIZE
7478      && sz>=512+APND_MARK_SIZE
7479     ){
7480       return 1; /* It's an appendvfs database */
7481     }
7482   }
7483   return 0;
7484 }
7485 
7486 /*
7487 ** Check to see if the file is an ordinary SQLite database file.
7488 ** Return true iff so. Parameter sz is the file's size.
7489 */
7490 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
7491   char zHdr[16];
7492   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
7493    || (sz & 0x1ff) != 0
7494    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
7495    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
7496   ){
7497     return 0;
7498   }else{
7499     return 1;
7500   }
7501 }
7502 
7503 /*
7504 ** Open an apnd file handle.
7505 */
7506 static int apndOpen(
7507   sqlite3_vfs *pApndVfs,
7508   const char *zName,
7509   sqlite3_file *pFile,
7510   int flags,
7511   int *pOutFlags
7512 ){
7513   ApndFile *pApndFile = (ApndFile*)pFile;
7514   sqlite3_file *pBaseFile = ORIGFILE(pFile);
7515   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
7516   int rc;
7517   sqlite3_int64 sz = 0;
7518   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
7519     /* The appendvfs is not to be used for transient or temporary databases.
7520     ** Just use the base VFS open to initialize the given file object and
7521     ** open the underlying file. (Appendvfs is then unused for this file.)
7522     */
7523     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
7524   }
7525   memset(pApndFile, 0, sizeof(ApndFile));
7526   pFile->pMethods = &apnd_io_methods;
7527   pApndFile->iMark = -1;    /* Append mark not yet written */
7528 
7529   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
7530   if( rc==SQLITE_OK ){
7531     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
7532     if( rc ){
7533       pBaseFile->pMethods->xClose(pBaseFile);
7534     }
7535   }
7536   if( rc ){
7537     pFile->pMethods = 0;
7538     return rc;
7539   }
7540   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
7541     /* The file being opened appears to be just an ordinary DB. Copy
7542     ** the base dispatch-table so this instance mimics the base VFS.
7543     */
7544     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
7545     return SQLITE_OK;
7546   }
7547   pApndFile->iPgOne = apndReadMark(sz, pFile);
7548   if( pApndFile->iPgOne>=0 ){
7549     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
7550     return SQLITE_OK;
7551   }
7552   if( (flags & SQLITE_OPEN_CREATE)==0 ){
7553     pBaseFile->pMethods->xClose(pBaseFile);
7554     rc = SQLITE_CANTOPEN;
7555     pFile->pMethods = 0;
7556   }else{
7557     /* Round newly added appendvfs location to #define'd page boundary.
7558     ** Note that nothing has yet been written to the underlying file.
7559     ** The append mark will be written along with first content write.
7560     ** Until then, paf->iMark value indicates it is not yet written.
7561     */
7562     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
7563   }
7564   return rc;
7565 }
7566 
7567 /*
7568 ** Delete an apnd file.
7569 ** For an appendvfs, this could mean delete the appendvfs portion,
7570 ** leaving the appendee as it was before it gained an appendvfs.
7571 ** For now, this code deletes the underlying file too.
7572 */
7573 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
7574   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
7575 }
7576 
7577 /*
7578 ** All other VFS methods are pass-thrus.
7579 */
7580 static int apndAccess(
7581   sqlite3_vfs *pVfs,
7582   const char *zPath,
7583   int flags,
7584   int *pResOut
7585 ){
7586   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
7587 }
7588 static int apndFullPathname(
7589   sqlite3_vfs *pVfs,
7590   const char *zPath,
7591   int nOut,
7592   char *zOut
7593 ){
7594   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
7595 }
7596 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
7597   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
7598 }
7599 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
7600   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
7601 }
7602 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
7603   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
7604 }
7605 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
7606   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
7607 }
7608 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
7609   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
7610 }
7611 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
7612   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
7613 }
7614 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
7615   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
7616 }
7617 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
7618   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
7619 }
7620 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
7621   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
7622 }
7623 static int apndSetSystemCall(
7624   sqlite3_vfs *pVfs,
7625   const char *zName,
7626   sqlite3_syscall_ptr pCall
7627 ){
7628   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
7629 }
7630 static sqlite3_syscall_ptr apndGetSystemCall(
7631   sqlite3_vfs *pVfs,
7632   const char *zName
7633 ){
7634   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
7635 }
7636 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
7637   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
7638 }
7639 
7640 
7641 #ifdef _WIN32
7642 
7643 #endif
7644 /*
7645 ** This routine is called when the extension is loaded.
7646 ** Register the new VFS.
7647 */
7648 int sqlite3_appendvfs_init(
7649   sqlite3 *db,
7650   char **pzErrMsg,
7651   const sqlite3_api_routines *pApi
7652 ){
7653   int rc = SQLITE_OK;
7654   sqlite3_vfs *pOrig;
7655   SQLITE_EXTENSION_INIT2(pApi);
7656   (void)pzErrMsg;
7657   (void)db;
7658   pOrig = sqlite3_vfs_find(0);
7659   if( pOrig==0 ) return SQLITE_ERROR;
7660   apnd_vfs.iVersion = pOrig->iVersion;
7661   apnd_vfs.pAppData = pOrig;
7662   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
7663   rc = sqlite3_vfs_register(&apnd_vfs, 0);
7664 #ifdef APPENDVFS_TEST
7665   if( rc==SQLITE_OK ){
7666     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
7667   }
7668 #endif
7669   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
7670   return rc;
7671 }
7672 
7673 /************************* End ../ext/misc/appendvfs.c ********************/
7674 #endif
7675 #ifdef SQLITE_HAVE_ZLIB
7676 /************************* Begin ../ext/misc/zipfile.c ******************/
7677 /*
7678 ** 2017-12-26
7679 **
7680 ** The author disclaims copyright to this source code.  In place of
7681 ** a legal notice, here is a blessing:
7682 **
7683 **    May you do good and not evil.
7684 **    May you find forgiveness for yourself and forgive others.
7685 **    May you share freely, never taking more than you give.
7686 **
7687 ******************************************************************************
7688 **
7689 ** This file implements a virtual table for reading and writing ZIP archive
7690 ** files.
7691 **
7692 ** Usage example:
7693 **
7694 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
7695 **
7696 ** Current limitations:
7697 **
7698 **    *  No support for encryption
7699 **    *  No support for ZIP archives spanning multiple files
7700 **    *  No support for zip64 extensions
7701 **    *  Only the "inflate/deflate" (zlib) compression method is supported
7702 */
7703 /* #include "sqlite3ext.h" */
7704 SQLITE_EXTENSION_INIT1
7705 #include <stdio.h>
7706 #include <string.h>
7707 #include <assert.h>
7708 
7709 #include <zlib.h>
7710 
7711 #ifndef SQLITE_OMIT_VIRTUALTABLE
7712 
7713 #ifndef SQLITE_AMALGAMATION
7714 
7715 #ifndef UINT32_TYPE
7716 # ifdef HAVE_UINT32_T
7717 #  define UINT32_TYPE uint32_t
7718 # else
7719 #  define UINT32_TYPE unsigned int
7720 # endif
7721 #endif
7722 #ifndef UINT16_TYPE
7723 # ifdef HAVE_UINT16_T
7724 #  define UINT16_TYPE uint16_t
7725 # else
7726 #  define UINT16_TYPE unsigned short int
7727 # endif
7728 #endif
7729 /* typedef sqlite3_int64 i64; */
7730 /* typedef unsigned char u8; */
7731 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
7732 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
7733 #define MIN(a,b) ((a)<(b) ? (a) : (b))
7734 
7735 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
7736 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
7737 #endif
7738 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
7739 # define ALWAYS(X)      (1)
7740 # define NEVER(X)       (0)
7741 #elif !defined(NDEBUG)
7742 # define ALWAYS(X)      ((X)?1:(assert(0),0))
7743 # define NEVER(X)       ((X)?(assert(0),1):0)
7744 #else
7745 # define ALWAYS(X)      (X)
7746 # define NEVER(X)       (X)
7747 #endif
7748 
7749 #endif   /* SQLITE_AMALGAMATION */
7750 
7751 /*
7752 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
7753 **
7754 ** In some ways it would be better to obtain these values from system
7755 ** header files. But, the dependency is undesirable and (a) these
7756 ** have been stable for decades, (b) the values are part of POSIX and
7757 ** are also made explicit in [man stat], and (c) are part of the
7758 ** file format for zip archives.
7759 */
7760 #ifndef S_IFDIR
7761 # define S_IFDIR 0040000
7762 #endif
7763 #ifndef S_IFREG
7764 # define S_IFREG 0100000
7765 #endif
7766 #ifndef S_IFLNK
7767 # define S_IFLNK 0120000
7768 #endif
7769 
7770 static const char ZIPFILE_SCHEMA[] =
7771   "CREATE TABLE y("
7772     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
7773     "mode,"              /* 1: POSIX mode for file */
7774     "mtime,"             /* 2: Last modification time (secs since 1970)*/
7775     "sz,"                /* 3: Size of object */
7776     "rawdata,"           /* 4: Raw data */
7777     "data,"              /* 5: Uncompressed data */
7778     "method,"            /* 6: Compression method (integer) */
7779     "z HIDDEN"           /* 7: Name of zip file */
7780   ") WITHOUT ROWID;";
7781 
7782 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
7783 #define ZIPFILE_BUFFER_SIZE (64*1024)
7784 
7785 
7786 /*
7787 ** Magic numbers used to read and write zip files.
7788 **
7789 ** ZIPFILE_NEWENTRY_MADEBY:
7790 **   Use this value for the "version-made-by" field in new zip file
7791 **   entries. The upper byte indicates "unix", and the lower byte
7792 **   indicates that the zip file matches pkzip specification 3.0.
7793 **   This is what info-zip seems to do.
7794 **
7795 ** ZIPFILE_NEWENTRY_REQUIRED:
7796 **   Value for "version-required-to-extract" field of new entries.
7797 **   Version 2.0 is required to support folders and deflate compression.
7798 **
7799 ** ZIPFILE_NEWENTRY_FLAGS:
7800 **   Value for "general-purpose-bit-flags" field of new entries. Bit
7801 **   11 means "utf-8 filename and comment".
7802 **
7803 ** ZIPFILE_SIGNATURE_CDS:
7804 **   First 4 bytes of a valid CDS record.
7805 **
7806 ** ZIPFILE_SIGNATURE_LFH:
7807 **   First 4 bytes of a valid LFH record.
7808 **
7809 ** ZIPFILE_SIGNATURE_EOCD
7810 **   First 4 bytes of a valid EOCD record.
7811 */
7812 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
7813 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
7814 #define ZIPFILE_NEWENTRY_REQUIRED 20
7815 #define ZIPFILE_NEWENTRY_FLAGS    0x800
7816 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
7817 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
7818 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
7819 
7820 /*
7821 ** The sizes of the fixed-size part of each of the three main data
7822 ** structures in a zip archive.
7823 */
7824 #define ZIPFILE_LFH_FIXED_SZ      30
7825 #define ZIPFILE_EOCD_FIXED_SZ     22
7826 #define ZIPFILE_CDS_FIXED_SZ      46
7827 
7828 /*
7829 *** 4.3.16  End of central directory record:
7830 ***
7831 ***   end of central dir signature    4 bytes  (0x06054b50)
7832 ***   number of this disk             2 bytes
7833 ***   number of the disk with the
7834 ***   start of the central directory  2 bytes
7835 ***   total number of entries in the
7836 ***   central directory on this disk  2 bytes
7837 ***   total number of entries in
7838 ***   the central directory           2 bytes
7839 ***   size of the central directory   4 bytes
7840 ***   offset of start of central
7841 ***   directory with respect to
7842 ***   the starting disk number        4 bytes
7843 ***   .ZIP file comment length        2 bytes
7844 ***   .ZIP file comment       (variable size)
7845 */
7846 typedef struct ZipfileEOCD ZipfileEOCD;
7847 struct ZipfileEOCD {
7848   u16 iDisk;
7849   u16 iFirstDisk;
7850   u16 nEntry;
7851   u16 nEntryTotal;
7852   u32 nSize;
7853   u32 iOffset;
7854 };
7855 
7856 /*
7857 *** 4.3.12  Central directory structure:
7858 ***
7859 *** ...
7860 ***
7861 ***   central file header signature   4 bytes  (0x02014b50)
7862 ***   version made by                 2 bytes
7863 ***   version needed to extract       2 bytes
7864 ***   general purpose bit flag        2 bytes
7865 ***   compression method              2 bytes
7866 ***   last mod file time              2 bytes
7867 ***   last mod file date              2 bytes
7868 ***   crc-32                          4 bytes
7869 ***   compressed size                 4 bytes
7870 ***   uncompressed size               4 bytes
7871 ***   file name length                2 bytes
7872 ***   extra field length              2 bytes
7873 ***   file comment length             2 bytes
7874 ***   disk number start               2 bytes
7875 ***   internal file attributes        2 bytes
7876 ***   external file attributes        4 bytes
7877 ***   relative offset of local header 4 bytes
7878 */
7879 typedef struct ZipfileCDS ZipfileCDS;
7880 struct ZipfileCDS {
7881   u16 iVersionMadeBy;
7882   u16 iVersionExtract;
7883   u16 flags;
7884   u16 iCompression;
7885   u16 mTime;
7886   u16 mDate;
7887   u32 crc32;
7888   u32 szCompressed;
7889   u32 szUncompressed;
7890   u16 nFile;
7891   u16 nExtra;
7892   u16 nComment;
7893   u16 iDiskStart;
7894   u16 iInternalAttr;
7895   u32 iExternalAttr;
7896   u32 iOffset;
7897   char *zFile;                    /* Filename (sqlite3_malloc()) */
7898 };
7899 
7900 /*
7901 *** 4.3.7  Local file header:
7902 ***
7903 ***   local file header signature     4 bytes  (0x04034b50)
7904 ***   version needed to extract       2 bytes
7905 ***   general purpose bit flag        2 bytes
7906 ***   compression method              2 bytes
7907 ***   last mod file time              2 bytes
7908 ***   last mod file date              2 bytes
7909 ***   crc-32                          4 bytes
7910 ***   compressed size                 4 bytes
7911 ***   uncompressed size               4 bytes
7912 ***   file name length                2 bytes
7913 ***   extra field length              2 bytes
7914 ***
7915 */
7916 typedef struct ZipfileLFH ZipfileLFH;
7917 struct ZipfileLFH {
7918   u16 iVersionExtract;
7919   u16 flags;
7920   u16 iCompression;
7921   u16 mTime;
7922   u16 mDate;
7923   u32 crc32;
7924   u32 szCompressed;
7925   u32 szUncompressed;
7926   u16 nFile;
7927   u16 nExtra;
7928 };
7929 
7930 typedef struct ZipfileEntry ZipfileEntry;
7931 struct ZipfileEntry {
7932   ZipfileCDS cds;            /* Parsed CDS record */
7933   u32 mUnixTime;             /* Modification time, in UNIX format */
7934   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
7935   i64 iDataOff;              /* Offset to data in file (if aData==0) */
7936   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
7937   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
7938 };
7939 
7940 /*
7941 ** Cursor type for zipfile tables.
7942 */
7943 typedef struct ZipfileCsr ZipfileCsr;
7944 struct ZipfileCsr {
7945   sqlite3_vtab_cursor base;  /* Base class - must be first */
7946   i64 iId;                   /* Cursor ID */
7947   u8 bEof;                   /* True when at EOF */
7948   u8 bNoop;                  /* If next xNext() call is no-op */
7949 
7950   /* Used outside of write transactions */
7951   FILE *pFile;               /* Zip file */
7952   i64 iNextOff;              /* Offset of next record in central directory */
7953   ZipfileEOCD eocd;          /* Parse of central directory record */
7954 
7955   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
7956   ZipfileEntry *pCurrent;    /* Current entry */
7957   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
7958 };
7959 
7960 typedef struct ZipfileTab ZipfileTab;
7961 struct ZipfileTab {
7962   sqlite3_vtab base;         /* Base class - must be first */
7963   char *zFile;               /* Zip file this table accesses (may be NULL) */
7964   sqlite3 *db;               /* Host database connection */
7965   u8 *aBuffer;               /* Temporary buffer used for various tasks */
7966 
7967   ZipfileCsr *pCsrList;      /* List of cursors */
7968   i64 iNextCsrid;
7969 
7970   /* The following are used by write transactions only */
7971   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
7972   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
7973   FILE *pWriteFd;            /* File handle open on zip archive */
7974   i64 szCurrent;             /* Current size of zip archive */
7975   i64 szOrig;                /* Size of archive at start of transaction */
7976 };
7977 
7978 /*
7979 ** Set the error message contained in context ctx to the results of
7980 ** vprintf(zFmt, ...).
7981 */
7982 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7983   char *zMsg = 0;
7984   va_list ap;
7985   va_start(ap, zFmt);
7986   zMsg = sqlite3_vmprintf(zFmt, ap);
7987   sqlite3_result_error(ctx, zMsg, -1);
7988   sqlite3_free(zMsg);
7989   va_end(ap);
7990 }
7991 
7992 /*
7993 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
7994 ** is not quoted, do nothing.
7995 */
7996 static void zipfileDequote(char *zIn){
7997   char q = zIn[0];
7998   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
7999     int iIn = 1;
8000     int iOut = 0;
8001     if( q=='[' ) q = ']';
8002     while( ALWAYS(zIn[iIn]) ){
8003       char c = zIn[iIn++];
8004       if( c==q && zIn[iIn++]!=q ) break;
8005       zIn[iOut++] = c;
8006     }
8007     zIn[iOut] = '\0';
8008   }
8009 }
8010 
8011 /*
8012 ** Construct a new ZipfileTab virtual table object.
8013 **
8014 **   argv[0]   -> module name  ("zipfile")
8015 **   argv[1]   -> database name
8016 **   argv[2]   -> table name
8017 **   argv[...] -> "column name" and other module argument fields.
8018 */
8019 static int zipfileConnect(
8020   sqlite3 *db,
8021   void *pAux,
8022   int argc, const char *const*argv,
8023   sqlite3_vtab **ppVtab,
8024   char **pzErr
8025 ){
8026   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
8027   int nFile = 0;
8028   const char *zFile = 0;
8029   ZipfileTab *pNew = 0;
8030   int rc;
8031   (void)pAux;
8032 
8033   /* If the table name is not "zipfile", require that the argument be
8034   ** specified. This stops zipfile tables from being created as:
8035   **
8036   **   CREATE VIRTUAL TABLE zzz USING zipfile();
8037   **
8038   ** It does not prevent:
8039   **
8040   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
8041   */
8042   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
8043   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
8044     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
8045     return SQLITE_ERROR;
8046   }
8047 
8048   if( argc>3 ){
8049     zFile = argv[3];
8050     nFile = (int)strlen(zFile)+1;
8051   }
8052 
8053   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
8054   if( rc==SQLITE_OK ){
8055     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
8056     if( pNew==0 ) return SQLITE_NOMEM;
8057     memset(pNew, 0, nByte+nFile);
8058     pNew->db = db;
8059     pNew->aBuffer = (u8*)&pNew[1];
8060     if( zFile ){
8061       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
8062       memcpy(pNew->zFile, zFile, nFile);
8063       zipfileDequote(pNew->zFile);
8064     }
8065   }
8066   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
8067   *ppVtab = (sqlite3_vtab*)pNew;
8068   return rc;
8069 }
8070 
8071 /*
8072 ** Free the ZipfileEntry structure indicated by the only argument.
8073 */
8074 static void zipfileEntryFree(ZipfileEntry *p){
8075   if( p ){
8076     sqlite3_free(p->cds.zFile);
8077     sqlite3_free(p);
8078   }
8079 }
8080 
8081 /*
8082 ** Release resources that should be freed at the end of a write
8083 ** transaction.
8084 */
8085 static void zipfileCleanupTransaction(ZipfileTab *pTab){
8086   ZipfileEntry *pEntry;
8087   ZipfileEntry *pNext;
8088 
8089   if( pTab->pWriteFd ){
8090     fclose(pTab->pWriteFd);
8091     pTab->pWriteFd = 0;
8092   }
8093   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
8094     pNext = pEntry->pNext;
8095     zipfileEntryFree(pEntry);
8096   }
8097   pTab->pFirstEntry = 0;
8098   pTab->pLastEntry = 0;
8099   pTab->szCurrent = 0;
8100   pTab->szOrig = 0;
8101 }
8102 
8103 /*
8104 ** This method is the destructor for zipfile vtab objects.
8105 */
8106 static int zipfileDisconnect(sqlite3_vtab *pVtab){
8107   zipfileCleanupTransaction((ZipfileTab*)pVtab);
8108   sqlite3_free(pVtab);
8109   return SQLITE_OK;
8110 }
8111 
8112 /*
8113 ** Constructor for a new ZipfileCsr object.
8114 */
8115 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
8116   ZipfileTab *pTab = (ZipfileTab*)p;
8117   ZipfileCsr *pCsr;
8118   pCsr = sqlite3_malloc(sizeof(*pCsr));
8119   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
8120   if( pCsr==0 ){
8121     return SQLITE_NOMEM;
8122   }
8123   memset(pCsr, 0, sizeof(*pCsr));
8124   pCsr->iId = ++pTab->iNextCsrid;
8125   pCsr->pCsrNext = pTab->pCsrList;
8126   pTab->pCsrList = pCsr;
8127   return SQLITE_OK;
8128 }
8129 
8130 /*
8131 ** Reset a cursor back to the state it was in when first returned
8132 ** by zipfileOpen().
8133 */
8134 static void zipfileResetCursor(ZipfileCsr *pCsr){
8135   ZipfileEntry *p;
8136   ZipfileEntry *pNext;
8137 
8138   pCsr->bEof = 0;
8139   if( pCsr->pFile ){
8140     fclose(pCsr->pFile);
8141     pCsr->pFile = 0;
8142     zipfileEntryFree(pCsr->pCurrent);
8143     pCsr->pCurrent = 0;
8144   }
8145 
8146   for(p=pCsr->pFreeEntry; p; p=pNext){
8147     pNext = p->pNext;
8148     zipfileEntryFree(p);
8149   }
8150 }
8151 
8152 /*
8153 ** Destructor for an ZipfileCsr.
8154 */
8155 static int zipfileClose(sqlite3_vtab_cursor *cur){
8156   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8157   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
8158   ZipfileCsr **pp;
8159   zipfileResetCursor(pCsr);
8160 
8161   /* Remove this cursor from the ZipfileTab.pCsrList list. */
8162   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
8163   *pp = pCsr->pCsrNext;
8164 
8165   sqlite3_free(pCsr);
8166   return SQLITE_OK;
8167 }
8168 
8169 /*
8170 ** Set the error message for the virtual table associated with cursor
8171 ** pCsr to the results of vprintf(zFmt, ...).
8172 */
8173 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
8174   va_list ap;
8175   va_start(ap, zFmt);
8176   sqlite3_free(pTab->base.zErrMsg);
8177   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
8178   va_end(ap);
8179 }
8180 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
8181   va_list ap;
8182   va_start(ap, zFmt);
8183   sqlite3_free(pCsr->base.pVtab->zErrMsg);
8184   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
8185   va_end(ap);
8186 }
8187 
8188 /*
8189 ** Read nRead bytes of data from offset iOff of file pFile into buffer
8190 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
8191 ** otherwise.
8192 **
8193 ** If an error does occur, output variable (*pzErrmsg) may be set to point
8194 ** to an English language error message. It is the responsibility of the
8195 ** caller to eventually free this buffer using
8196 ** sqlite3_free().
8197 */
8198 static int zipfileReadData(
8199   FILE *pFile,                    /* Read from this file */
8200   u8 *aRead,                      /* Read into this buffer */
8201   int nRead,                      /* Number of bytes to read */
8202   i64 iOff,                       /* Offset to read from */
8203   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
8204 ){
8205   size_t n;
8206   fseek(pFile, (long)iOff, SEEK_SET);
8207   n = fread(aRead, 1, nRead, pFile);
8208   if( (int)n!=nRead ){
8209     *pzErrmsg = sqlite3_mprintf("error in fread()");
8210     return SQLITE_ERROR;
8211   }
8212   return SQLITE_OK;
8213 }
8214 
8215 static int zipfileAppendData(
8216   ZipfileTab *pTab,
8217   const u8 *aWrite,
8218   int nWrite
8219 ){
8220   if( nWrite>0 ){
8221     size_t n = nWrite;
8222     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
8223     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
8224     if( (int)n!=nWrite ){
8225       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
8226       return SQLITE_ERROR;
8227     }
8228     pTab->szCurrent += nWrite;
8229   }
8230   return SQLITE_OK;
8231 }
8232 
8233 /*
8234 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
8235 */
8236 static u16 zipfileGetU16(const u8 *aBuf){
8237   return (aBuf[1] << 8) + aBuf[0];
8238 }
8239 
8240 /*
8241 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
8242 */
8243 static u32 zipfileGetU32(const u8 *aBuf){
8244   if( aBuf==0 ) return 0;
8245   return ((u32)(aBuf[3]) << 24)
8246        + ((u32)(aBuf[2]) << 16)
8247        + ((u32)(aBuf[1]) <<  8)
8248        + ((u32)(aBuf[0]) <<  0);
8249 }
8250 
8251 /*
8252 ** Write a 16-bit little endiate integer into buffer aBuf.
8253 */
8254 static void zipfilePutU16(u8 *aBuf, u16 val){
8255   aBuf[0] = val & 0xFF;
8256   aBuf[1] = (val>>8) & 0xFF;
8257 }
8258 
8259 /*
8260 ** Write a 32-bit little endiate integer into buffer aBuf.
8261 */
8262 static void zipfilePutU32(u8 *aBuf, u32 val){
8263   aBuf[0] = val & 0xFF;
8264   aBuf[1] = (val>>8) & 0xFF;
8265   aBuf[2] = (val>>16) & 0xFF;
8266   aBuf[3] = (val>>24) & 0xFF;
8267 }
8268 
8269 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
8270 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
8271 
8272 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
8273 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
8274 
8275 /*
8276 ** Magic numbers used to read CDS records.
8277 */
8278 #define ZIPFILE_CDS_NFILE_OFF        28
8279 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
8280 
8281 /*
8282 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
8283 ** if the record is not well-formed, or SQLITE_OK otherwise.
8284 */
8285 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
8286   u8 *aRead = aBuf;
8287   u32 sig = zipfileRead32(aRead);
8288   int rc = SQLITE_OK;
8289   if( sig!=ZIPFILE_SIGNATURE_CDS ){
8290     rc = SQLITE_ERROR;
8291   }else{
8292     pCDS->iVersionMadeBy = zipfileRead16(aRead);
8293     pCDS->iVersionExtract = zipfileRead16(aRead);
8294     pCDS->flags = zipfileRead16(aRead);
8295     pCDS->iCompression = zipfileRead16(aRead);
8296     pCDS->mTime = zipfileRead16(aRead);
8297     pCDS->mDate = zipfileRead16(aRead);
8298     pCDS->crc32 = zipfileRead32(aRead);
8299     pCDS->szCompressed = zipfileRead32(aRead);
8300     pCDS->szUncompressed = zipfileRead32(aRead);
8301     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
8302     pCDS->nFile = zipfileRead16(aRead);
8303     pCDS->nExtra = zipfileRead16(aRead);
8304     pCDS->nComment = zipfileRead16(aRead);
8305     pCDS->iDiskStart = zipfileRead16(aRead);
8306     pCDS->iInternalAttr = zipfileRead16(aRead);
8307     pCDS->iExternalAttr = zipfileRead32(aRead);
8308     pCDS->iOffset = zipfileRead32(aRead);
8309     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
8310   }
8311 
8312   return rc;
8313 }
8314 
8315 /*
8316 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
8317 ** if the record is not well-formed, or SQLITE_OK otherwise.
8318 */
8319 static int zipfileReadLFH(
8320   u8 *aBuffer,
8321   ZipfileLFH *pLFH
8322 ){
8323   u8 *aRead = aBuffer;
8324   int rc = SQLITE_OK;
8325 
8326   u32 sig = zipfileRead32(aRead);
8327   if( sig!=ZIPFILE_SIGNATURE_LFH ){
8328     rc = SQLITE_ERROR;
8329   }else{
8330     pLFH->iVersionExtract = zipfileRead16(aRead);
8331     pLFH->flags = zipfileRead16(aRead);
8332     pLFH->iCompression = zipfileRead16(aRead);
8333     pLFH->mTime = zipfileRead16(aRead);
8334     pLFH->mDate = zipfileRead16(aRead);
8335     pLFH->crc32 = zipfileRead32(aRead);
8336     pLFH->szCompressed = zipfileRead32(aRead);
8337     pLFH->szUncompressed = zipfileRead32(aRead);
8338     pLFH->nFile = zipfileRead16(aRead);
8339     pLFH->nExtra = zipfileRead16(aRead);
8340   }
8341   return rc;
8342 }
8343 
8344 
8345 /*
8346 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
8347 ** Scan through this buffer to find an "extra-timestamp" field. If one
8348 ** exists, extract the 32-bit modification-timestamp from it and store
8349 ** the value in output parameter *pmTime.
8350 **
8351 ** Zero is returned if no extra-timestamp record could be found (and so
8352 ** *pmTime is left unchanged), or non-zero otherwise.
8353 **
8354 ** The general format of an extra field is:
8355 **
8356 **   Header ID    2 bytes
8357 **   Data Size    2 bytes
8358 **   Data         N bytes
8359 */
8360 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
8361   int ret = 0;
8362   u8 *p = aExtra;
8363   u8 *pEnd = &aExtra[nExtra];
8364 
8365   while( p<pEnd ){
8366     u16 id = zipfileRead16(p);
8367     u16 nByte = zipfileRead16(p);
8368 
8369     switch( id ){
8370       case ZIPFILE_EXTRA_TIMESTAMP: {
8371         u8 b = p[0];
8372         if( b & 0x01 ){     /* 0x01 -> modtime is present */
8373           *pmTime = zipfileGetU32(&p[1]);
8374           ret = 1;
8375         }
8376         break;
8377       }
8378     }
8379 
8380     p += nByte;
8381   }
8382   return ret;
8383 }
8384 
8385 /*
8386 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
8387 ** fields of the CDS structure passed as the only argument to a 32-bit
8388 ** UNIX seconds-since-the-epoch timestamp. Return the result.
8389 **
8390 ** "Standard" MS-DOS time format:
8391 **
8392 **   File modification time:
8393 **     Bits 00-04: seconds divided by 2
8394 **     Bits 05-10: minute
8395 **     Bits 11-15: hour
8396 **   File modification date:
8397 **     Bits 00-04: day
8398 **     Bits 05-08: month (1-12)
8399 **     Bits 09-15: years from 1980
8400 **
8401 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
8402 */
8403 static u32 zipfileMtime(ZipfileCDS *pCDS){
8404   int Y,M,D,X1,X2,A,B,sec,min,hr;
8405   i64 JDsec;
8406   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
8407   M = ((pCDS->mDate >> 5) & 0x0F);
8408   D = (pCDS->mDate & 0x1F);
8409   sec = (pCDS->mTime & 0x1F)*2;
8410   min = (pCDS->mTime >> 5) & 0x3F;
8411   hr = (pCDS->mTime >> 11) & 0x1F;
8412   if( M<=2 ){
8413     Y--;
8414     M += 12;
8415   }
8416   X1 = 36525*(Y+4716)/100;
8417   X2 = 306001*(M+1)/10000;
8418   A = Y/100;
8419   B = 2 - A + (A/4);
8420   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
8421   return (u32)(JDsec - (i64)24405875*(i64)8640);
8422 }
8423 
8424 /*
8425 ** The opposite of zipfileMtime(). This function populates the mTime and
8426 ** mDate fields of the CDS structure passed as the first argument according
8427 ** to the UNIX timestamp value passed as the second.
8428 */
8429 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
8430   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
8431   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
8432 
8433   int A, B, C, D, E;
8434   int yr, mon, day;
8435   int hr, min, sec;
8436 
8437   A = (int)((JD - 1867216.25)/36524.25);
8438   A = (int)(JD + 1 + A - (A/4));
8439   B = A + 1524;
8440   C = (int)((B - 122.1)/365.25);
8441   D = (36525*(C&32767))/100;
8442   E = (int)((B-D)/30.6001);
8443 
8444   day = B - D - (int)(30.6001*E);
8445   mon = (E<14 ? E-1 : E-13);
8446   yr = mon>2 ? C-4716 : C-4715;
8447 
8448   hr = (mUnixTime % (24*60*60)) / (60*60);
8449   min = (mUnixTime % (60*60)) / 60;
8450   sec = (mUnixTime % 60);
8451 
8452   if( yr>=1980 ){
8453     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
8454     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
8455   }else{
8456     pCds->mDate = pCds->mTime = 0;
8457   }
8458 
8459   assert( mUnixTime<315507600
8460        || mUnixTime==zipfileMtime(pCds)
8461        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
8462        /* || (mUnixTime % 2) */
8463   );
8464 }
8465 
8466 /*
8467 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
8468 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
8469 ** then pFile is a file-handle open on a zip file. In either case, this
8470 ** function creates a ZipfileEntry object based on the zip archive entry
8471 ** for which the CDS record is at offset iOff.
8472 **
8473 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
8474 ** the new object. Otherwise, an SQLite error code is returned and the
8475 ** final value of (*ppEntry) undefined.
8476 */
8477 static int zipfileGetEntry(
8478   ZipfileTab *pTab,               /* Store any error message here */
8479   const u8 *aBlob,                /* Pointer to in-memory file image */
8480   int nBlob,                      /* Size of aBlob[] in bytes */
8481   FILE *pFile,                    /* If aBlob==0, read from this file */
8482   i64 iOff,                       /* Offset of CDS record */
8483   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
8484 ){
8485   u8 *aRead;
8486   char **pzErr = &pTab->base.zErrMsg;
8487   int rc = SQLITE_OK;
8488   (void)nBlob;
8489 
8490   if( aBlob==0 ){
8491     aRead = pTab->aBuffer;
8492     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
8493   }else{
8494     aRead = (u8*)&aBlob[iOff];
8495   }
8496 
8497   if( rc==SQLITE_OK ){
8498     sqlite3_int64 nAlloc;
8499     ZipfileEntry *pNew;
8500 
8501     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
8502     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
8503     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
8504 
8505     nAlloc = sizeof(ZipfileEntry) + nExtra;
8506     if( aBlob ){
8507       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
8508     }
8509 
8510     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
8511     if( pNew==0 ){
8512       rc = SQLITE_NOMEM;
8513     }else{
8514       memset(pNew, 0, sizeof(ZipfileEntry));
8515       rc = zipfileReadCDS(aRead, &pNew->cds);
8516       if( rc!=SQLITE_OK ){
8517         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
8518       }else if( aBlob==0 ){
8519         rc = zipfileReadData(
8520             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
8521         );
8522       }else{
8523         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
8524       }
8525     }
8526 
8527     if( rc==SQLITE_OK ){
8528       u32 *pt = &pNew->mUnixTime;
8529       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
8530       pNew->aExtra = (u8*)&pNew[1];
8531       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
8532       if( pNew->cds.zFile==0 ){
8533         rc = SQLITE_NOMEM;
8534       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
8535         pNew->mUnixTime = zipfileMtime(&pNew->cds);
8536       }
8537     }
8538 
8539     if( rc==SQLITE_OK ){
8540       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
8541       ZipfileLFH lfh;
8542       if( pFile ){
8543         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
8544       }else{
8545         aRead = (u8*)&aBlob[pNew->cds.iOffset];
8546       }
8547 
8548       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
8549       if( rc==SQLITE_OK ){
8550         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
8551         pNew->iDataOff += lfh.nFile + lfh.nExtra;
8552         if( aBlob && pNew->cds.szCompressed ){
8553           pNew->aData = &pNew->aExtra[nExtra];
8554           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
8555         }
8556       }else{
8557         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
8558             (int)pNew->cds.iOffset
8559         );
8560       }
8561     }
8562 
8563     if( rc!=SQLITE_OK ){
8564       zipfileEntryFree(pNew);
8565     }else{
8566       *ppEntry = pNew;
8567     }
8568   }
8569 
8570   return rc;
8571 }
8572 
8573 /*
8574 ** Advance an ZipfileCsr to its next row of output.
8575 */
8576 static int zipfileNext(sqlite3_vtab_cursor *cur){
8577   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8578   int rc = SQLITE_OK;
8579 
8580   if( pCsr->pFile ){
8581     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
8582     zipfileEntryFree(pCsr->pCurrent);
8583     pCsr->pCurrent = 0;
8584     if( pCsr->iNextOff>=iEof ){
8585       pCsr->bEof = 1;
8586     }else{
8587       ZipfileEntry *p = 0;
8588       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
8589       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
8590       if( rc==SQLITE_OK ){
8591         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
8592         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
8593       }
8594       pCsr->pCurrent = p;
8595     }
8596   }else{
8597     if( !pCsr->bNoop ){
8598       pCsr->pCurrent = pCsr->pCurrent->pNext;
8599     }
8600     if( pCsr->pCurrent==0 ){
8601       pCsr->bEof = 1;
8602     }
8603   }
8604 
8605   pCsr->bNoop = 0;
8606   return rc;
8607 }
8608 
8609 static void zipfileFree(void *p) {
8610   sqlite3_free(p);
8611 }
8612 
8613 /*
8614 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
8615 ** size is nOut bytes. This function uncompresses the data and sets the
8616 ** return value in context pCtx to the result (a blob).
8617 **
8618 ** If an error occurs, an error code is left in pCtx instead.
8619 */
8620 static void zipfileInflate(
8621   sqlite3_context *pCtx,          /* Store result here */
8622   const u8 *aIn,                  /* Compressed data */
8623   int nIn,                        /* Size of buffer aIn[] in bytes */
8624   int nOut                        /* Expected output size */
8625 ){
8626   u8 *aRes = sqlite3_malloc(nOut);
8627   if( aRes==0 ){
8628     sqlite3_result_error_nomem(pCtx);
8629   }else{
8630     int err;
8631     z_stream str;
8632     memset(&str, 0, sizeof(str));
8633 
8634     str.next_in = (Byte*)aIn;
8635     str.avail_in = nIn;
8636     str.next_out = (Byte*)aRes;
8637     str.avail_out = nOut;
8638 
8639     err = inflateInit2(&str, -15);
8640     if( err!=Z_OK ){
8641       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
8642     }else{
8643       err = inflate(&str, Z_NO_FLUSH);
8644       if( err!=Z_STREAM_END ){
8645         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
8646       }else{
8647         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
8648         aRes = 0;
8649       }
8650     }
8651     sqlite3_free(aRes);
8652     inflateEnd(&str);
8653   }
8654 }
8655 
8656 /*
8657 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
8658 ** compresses it and sets (*ppOut) to point to a buffer containing the
8659 ** compressed data. The caller is responsible for eventually calling
8660 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
8661 ** is set to the size of buffer (*ppOut) in bytes.
8662 **
8663 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
8664 ** code is returned and an error message left in virtual-table handle
8665 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
8666 ** case.
8667 */
8668 static int zipfileDeflate(
8669   const u8 *aIn, int nIn,         /* Input */
8670   u8 **ppOut, int *pnOut,         /* Output */
8671   char **pzErr                    /* OUT: Error message */
8672 ){
8673   int rc = SQLITE_OK;
8674   sqlite3_int64 nAlloc;
8675   z_stream str;
8676   u8 *aOut;
8677 
8678   memset(&str, 0, sizeof(str));
8679   str.next_in = (Bytef*)aIn;
8680   str.avail_in = nIn;
8681   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
8682 
8683   nAlloc = deflateBound(&str, nIn);
8684   aOut = (u8*)sqlite3_malloc64(nAlloc);
8685   if( aOut==0 ){
8686     rc = SQLITE_NOMEM;
8687   }else{
8688     int res;
8689     str.next_out = aOut;
8690     str.avail_out = nAlloc;
8691     res = deflate(&str, Z_FINISH);
8692     if( res==Z_STREAM_END ){
8693       *ppOut = aOut;
8694       *pnOut = (int)str.total_out;
8695     }else{
8696       sqlite3_free(aOut);
8697       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
8698       rc = SQLITE_ERROR;
8699     }
8700     deflateEnd(&str);
8701   }
8702 
8703   return rc;
8704 }
8705 
8706 
8707 /*
8708 ** Return values of columns for the row at which the series_cursor
8709 ** is currently pointing.
8710 */
8711 static int zipfileColumn(
8712   sqlite3_vtab_cursor *cur,   /* The cursor */
8713   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8714   int i                       /* Which column to return */
8715 ){
8716   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8717   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
8718   int rc = SQLITE_OK;
8719   switch( i ){
8720     case 0:   /* name */
8721       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
8722       break;
8723     case 1:   /* mode */
8724       /* TODO: Whether or not the following is correct surely depends on
8725       ** the platform on which the archive was created.  */
8726       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
8727       break;
8728     case 2: { /* mtime */
8729       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
8730       break;
8731     }
8732     case 3: { /* sz */
8733       if( sqlite3_vtab_nochange(ctx)==0 ){
8734         sqlite3_result_int64(ctx, pCDS->szUncompressed);
8735       }
8736       break;
8737     }
8738     case 4:   /* rawdata */
8739       if( sqlite3_vtab_nochange(ctx) ) break;
8740     case 5: { /* data */
8741       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
8742         int sz = pCDS->szCompressed;
8743         int szFinal = pCDS->szUncompressed;
8744         if( szFinal>0 ){
8745           u8 *aBuf;
8746           u8 *aFree = 0;
8747           if( pCsr->pCurrent->aData ){
8748             aBuf = pCsr->pCurrent->aData;
8749           }else{
8750             aBuf = aFree = sqlite3_malloc64(sz);
8751             if( aBuf==0 ){
8752               rc = SQLITE_NOMEM;
8753             }else{
8754               FILE *pFile = pCsr->pFile;
8755               if( pFile==0 ){
8756                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
8757               }
8758               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
8759                   &pCsr->base.pVtab->zErrMsg
8760               );
8761             }
8762           }
8763           if( rc==SQLITE_OK ){
8764             if( i==5 && pCDS->iCompression ){
8765               zipfileInflate(ctx, aBuf, sz, szFinal);
8766             }else{
8767               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
8768             }
8769           }
8770           sqlite3_free(aFree);
8771         }else{
8772           /* Figure out if this is a directory or a zero-sized file. Consider
8773           ** it to be a directory either if the mode suggests so, or if
8774           ** the final character in the name is '/'.  */
8775           u32 mode = pCDS->iExternalAttr >> 16;
8776           if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
8777             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
8778           }
8779         }
8780       }
8781       break;
8782     }
8783     case 6:   /* method */
8784       sqlite3_result_int(ctx, pCDS->iCompression);
8785       break;
8786     default:  /* z */
8787       assert( i==7 );
8788       sqlite3_result_int64(ctx, pCsr->iId);
8789       break;
8790   }
8791 
8792   return rc;
8793 }
8794 
8795 /*
8796 ** Return TRUE if the cursor is at EOF.
8797 */
8798 static int zipfileEof(sqlite3_vtab_cursor *cur){
8799   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8800   return pCsr->bEof;
8801 }
8802 
8803 /*
8804 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
8805 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
8806 ** is guaranteed to be a file-handle open on a zip file.
8807 **
8808 ** This function attempts to locate the EOCD record within the zip archive
8809 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
8810 ** returned if successful. Otherwise, an SQLite error code is returned and
8811 ** an English language error message may be left in virtual-table pTab.
8812 */
8813 static int zipfileReadEOCD(
8814   ZipfileTab *pTab,               /* Return errors here */
8815   const u8 *aBlob,                /* Pointer to in-memory file image */
8816   int nBlob,                      /* Size of aBlob[] in bytes */
8817   FILE *pFile,                    /* Read from this file if aBlob==0 */
8818   ZipfileEOCD *pEOCD              /* Object to populate */
8819 ){
8820   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
8821   int nRead;                      /* Bytes to read from file */
8822   int rc = SQLITE_OK;
8823 
8824   memset(pEOCD, 0, sizeof(ZipfileEOCD));
8825   if( aBlob==0 ){
8826     i64 iOff;                     /* Offset to read from */
8827     i64 szFile;                   /* Total size of file in bytes */
8828     fseek(pFile, 0, SEEK_END);
8829     szFile = (i64)ftell(pFile);
8830     if( szFile==0 ){
8831       return SQLITE_OK;
8832     }
8833     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
8834     iOff = szFile - nRead;
8835     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
8836   }else{
8837     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
8838     aRead = (u8*)&aBlob[nBlob-nRead];
8839   }
8840 
8841   if( rc==SQLITE_OK ){
8842     int i;
8843 
8844     /* Scan backwards looking for the signature bytes */
8845     for(i=nRead-20; i>=0; i--){
8846       if( aRead[i]==0x50 && aRead[i+1]==0x4b
8847        && aRead[i+2]==0x05 && aRead[i+3]==0x06
8848       ){
8849         break;
8850       }
8851     }
8852     if( i<0 ){
8853       pTab->base.zErrMsg = sqlite3_mprintf(
8854           "cannot find end of central directory record"
8855       );
8856       return SQLITE_ERROR;
8857     }
8858 
8859     aRead += i+4;
8860     pEOCD->iDisk = zipfileRead16(aRead);
8861     pEOCD->iFirstDisk = zipfileRead16(aRead);
8862     pEOCD->nEntry = zipfileRead16(aRead);
8863     pEOCD->nEntryTotal = zipfileRead16(aRead);
8864     pEOCD->nSize = zipfileRead32(aRead);
8865     pEOCD->iOffset = zipfileRead32(aRead);
8866   }
8867 
8868   return rc;
8869 }
8870 
8871 /*
8872 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
8873 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
8874 ** to the end of the list. Otherwise, it is added to the list immediately
8875 ** before pBefore (which is guaranteed to be a part of said list).
8876 */
8877 static void zipfileAddEntry(
8878   ZipfileTab *pTab,
8879   ZipfileEntry *pBefore,
8880   ZipfileEntry *pNew
8881 ){
8882   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
8883   assert( pNew->pNext==0 );
8884   if( pBefore==0 ){
8885     if( pTab->pFirstEntry==0 ){
8886       pTab->pFirstEntry = pTab->pLastEntry = pNew;
8887     }else{
8888       assert( pTab->pLastEntry->pNext==0 );
8889       pTab->pLastEntry->pNext = pNew;
8890       pTab->pLastEntry = pNew;
8891     }
8892   }else{
8893     ZipfileEntry **pp;
8894     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
8895     pNew->pNext = pBefore;
8896     *pp = pNew;
8897   }
8898 }
8899 
8900 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
8901   ZipfileEOCD eocd;
8902   int rc;
8903   int i;
8904   i64 iOff;
8905 
8906   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
8907   iOff = eocd.iOffset;
8908   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
8909     ZipfileEntry *pNew = 0;
8910     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
8911 
8912     if( rc==SQLITE_OK ){
8913       zipfileAddEntry(pTab, 0, pNew);
8914       iOff += ZIPFILE_CDS_FIXED_SZ;
8915       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
8916     }
8917   }
8918   return rc;
8919 }
8920 
8921 /*
8922 ** xFilter callback.
8923 */
8924 static int zipfileFilter(
8925   sqlite3_vtab_cursor *cur,
8926   int idxNum, const char *idxStr,
8927   int argc, sqlite3_value **argv
8928 ){
8929   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
8930   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
8931   const char *zFile = 0;          /* Zip file to scan */
8932   int rc = SQLITE_OK;             /* Return Code */
8933   int bInMemory = 0;              /* True for an in-memory zipfile */
8934 
8935   (void)idxStr;
8936   (void)argc;
8937 
8938   zipfileResetCursor(pCsr);
8939 
8940   if( pTab->zFile ){
8941     zFile = pTab->zFile;
8942   }else if( idxNum==0 ){
8943     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
8944     return SQLITE_ERROR;
8945   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
8946     static const u8 aEmptyBlob = 0;
8947     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
8948     int nBlob = sqlite3_value_bytes(argv[0]);
8949     assert( pTab->pFirstEntry==0 );
8950     if( aBlob==0 ){
8951       aBlob = &aEmptyBlob;
8952       nBlob = 0;
8953     }
8954     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
8955     pCsr->pFreeEntry = pTab->pFirstEntry;
8956     pTab->pFirstEntry = pTab->pLastEntry = 0;
8957     if( rc!=SQLITE_OK ) return rc;
8958     bInMemory = 1;
8959   }else{
8960     zFile = (const char*)sqlite3_value_text(argv[0]);
8961   }
8962 
8963   if( 0==pTab->pWriteFd && 0==bInMemory ){
8964     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
8965     if( pCsr->pFile==0 ){
8966       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
8967       rc = SQLITE_ERROR;
8968     }else{
8969       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
8970       if( rc==SQLITE_OK ){
8971         if( pCsr->eocd.nEntry==0 ){
8972           pCsr->bEof = 1;
8973         }else{
8974           pCsr->iNextOff = pCsr->eocd.iOffset;
8975           rc = zipfileNext(cur);
8976         }
8977       }
8978     }
8979   }else{
8980     pCsr->bNoop = 1;
8981     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
8982     rc = zipfileNext(cur);
8983   }
8984 
8985   return rc;
8986 }
8987 
8988 /*
8989 ** xBestIndex callback.
8990 */
8991 static int zipfileBestIndex(
8992   sqlite3_vtab *tab,
8993   sqlite3_index_info *pIdxInfo
8994 ){
8995   int i;
8996   int idx = -1;
8997   int unusable = 0;
8998   (void)tab;
8999 
9000   for(i=0; i<pIdxInfo->nConstraint; i++){
9001     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
9002     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
9003     if( pCons->usable==0 ){
9004       unusable = 1;
9005     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9006       idx = i;
9007     }
9008   }
9009   pIdxInfo->estimatedCost = 1000.0;
9010   if( idx>=0 ){
9011     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
9012     pIdxInfo->aConstraintUsage[idx].omit = 1;
9013     pIdxInfo->idxNum = 1;
9014   }else if( unusable ){
9015     return SQLITE_CONSTRAINT;
9016   }
9017   return SQLITE_OK;
9018 }
9019 
9020 static ZipfileEntry *zipfileNewEntry(const char *zPath){
9021   ZipfileEntry *pNew;
9022   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
9023   if( pNew ){
9024     memset(pNew, 0, sizeof(ZipfileEntry));
9025     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
9026     if( pNew->cds.zFile==0 ){
9027       sqlite3_free(pNew);
9028       pNew = 0;
9029     }
9030   }
9031   return pNew;
9032 }
9033 
9034 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
9035   ZipfileCDS *pCds = &pEntry->cds;
9036   u8 *a = aBuf;
9037 
9038   pCds->nExtra = 9;
9039 
9040   /* Write the LFH itself */
9041   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
9042   zipfileWrite16(a, pCds->iVersionExtract);
9043   zipfileWrite16(a, pCds->flags);
9044   zipfileWrite16(a, pCds->iCompression);
9045   zipfileWrite16(a, pCds->mTime);
9046   zipfileWrite16(a, pCds->mDate);
9047   zipfileWrite32(a, pCds->crc32);
9048   zipfileWrite32(a, pCds->szCompressed);
9049   zipfileWrite32(a, pCds->szUncompressed);
9050   zipfileWrite16(a, (u16)pCds->nFile);
9051   zipfileWrite16(a, pCds->nExtra);
9052   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
9053 
9054   /* Add the file name */
9055   memcpy(a, pCds->zFile, (int)pCds->nFile);
9056   a += (int)pCds->nFile;
9057 
9058   /* The "extra" data */
9059   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9060   zipfileWrite16(a, 5);
9061   *a++ = 0x01;
9062   zipfileWrite32(a, pEntry->mUnixTime);
9063 
9064   return a-aBuf;
9065 }
9066 
9067 static int zipfileAppendEntry(
9068   ZipfileTab *pTab,
9069   ZipfileEntry *pEntry,
9070   const u8 *pData,
9071   int nData
9072 ){
9073   u8 *aBuf = pTab->aBuffer;
9074   int nBuf;
9075   int rc;
9076 
9077   nBuf = zipfileSerializeLFH(pEntry, aBuf);
9078   rc = zipfileAppendData(pTab, aBuf, nBuf);
9079   if( rc==SQLITE_OK ){
9080     pEntry->iDataOff = pTab->szCurrent;
9081     rc = zipfileAppendData(pTab, pData, nData);
9082   }
9083 
9084   return rc;
9085 }
9086 
9087 static int zipfileGetMode(
9088   sqlite3_value *pVal,
9089   int bIsDir,                     /* If true, default to directory */
9090   u32 *pMode,                     /* OUT: Mode value */
9091   char **pzErr                    /* OUT: Error message */
9092 ){
9093   const char *z = (const char*)sqlite3_value_text(pVal);
9094   u32 mode = 0;
9095   if( z==0 ){
9096     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
9097   }else if( z[0]>='0' && z[0]<='9' ){
9098     mode = (unsigned int)sqlite3_value_int(pVal);
9099   }else{
9100     const char zTemplate[11] = "-rwxrwxrwx";
9101     int i;
9102     if( strlen(z)!=10 ) goto parse_error;
9103     switch( z[0] ){
9104       case '-': mode |= S_IFREG; break;
9105       case 'd': mode |= S_IFDIR; break;
9106       case 'l': mode |= S_IFLNK; break;
9107       default: goto parse_error;
9108     }
9109     for(i=1; i<10; i++){
9110       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
9111       else if( z[i]!='-' ) goto parse_error;
9112     }
9113   }
9114   if( ((mode & S_IFDIR)==0)==bIsDir ){
9115     /* The "mode" attribute is a directory, but data has been specified.
9116     ** Or vice-versa - no data but "mode" is a file or symlink.  */
9117     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
9118     return SQLITE_CONSTRAINT;
9119   }
9120   *pMode = mode;
9121   return SQLITE_OK;
9122 
9123  parse_error:
9124   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
9125   return SQLITE_ERROR;
9126 }
9127 
9128 /*
9129 ** Both (const char*) arguments point to nul-terminated strings. Argument
9130 ** nB is the value of strlen(zB). This function returns 0 if the strings are
9131 ** identical, ignoring any trailing '/' character in either path.  */
9132 static int zipfileComparePath(const char *zA, const char *zB, int nB){
9133   int nA = (int)strlen(zA);
9134   if( nA>0 && zA[nA-1]=='/' ) nA--;
9135   if( nB>0 && zB[nB-1]=='/' ) nB--;
9136   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
9137   return 1;
9138 }
9139 
9140 static int zipfileBegin(sqlite3_vtab *pVtab){
9141   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9142   int rc = SQLITE_OK;
9143 
9144   assert( pTab->pWriteFd==0 );
9145   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
9146     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
9147     return SQLITE_ERROR;
9148   }
9149 
9150   /* Open a write fd on the file. Also load the entire central directory
9151   ** structure into memory. During the transaction any new file data is
9152   ** appended to the archive file, but the central directory is accumulated
9153   ** in main-memory until the transaction is committed.  */
9154   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
9155   if( pTab->pWriteFd==0 ){
9156     pTab->base.zErrMsg = sqlite3_mprintf(
9157         "zipfile: failed to open file %s for writing", pTab->zFile
9158         );
9159     rc = SQLITE_ERROR;
9160   }else{
9161     fseek(pTab->pWriteFd, 0, SEEK_END);
9162     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
9163     rc = zipfileLoadDirectory(pTab, 0, 0);
9164   }
9165 
9166   if( rc!=SQLITE_OK ){
9167     zipfileCleanupTransaction(pTab);
9168   }
9169 
9170   return rc;
9171 }
9172 
9173 /*
9174 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
9175 ** time(2)).
9176 */
9177 static u32 zipfileTime(void){
9178   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
9179   u32 ret;
9180   if( pVfs==0 ) return 0;
9181   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
9182     i64 ms;
9183     pVfs->xCurrentTimeInt64(pVfs, &ms);
9184     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
9185   }else{
9186     double day;
9187     pVfs->xCurrentTime(pVfs, &day);
9188     ret = (u32)((day - 2440587.5) * 86400);
9189   }
9190   return ret;
9191 }
9192 
9193 /*
9194 ** Return a 32-bit timestamp in UNIX epoch format.
9195 **
9196 ** If the value passed as the only argument is either NULL or an SQL NULL,
9197 ** return the current time. Otherwise, return the value stored in (*pVal)
9198 ** cast to a 32-bit unsigned integer.
9199 */
9200 static u32 zipfileGetTime(sqlite3_value *pVal){
9201   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
9202     return zipfileTime();
9203   }
9204   return (u32)sqlite3_value_int64(pVal);
9205 }
9206 
9207 /*
9208 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
9209 ** linked list.  Remove it from the list and free the object.
9210 */
9211 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
9212   if( pOld ){
9213     ZipfileEntry **pp;
9214     for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
9215     *pp = (*pp)->pNext;
9216     zipfileEntryFree(pOld);
9217   }
9218 }
9219 
9220 /*
9221 ** xUpdate method.
9222 */
9223 static int zipfileUpdate(
9224   sqlite3_vtab *pVtab,
9225   int nVal,
9226   sqlite3_value **apVal,
9227   sqlite_int64 *pRowid
9228 ){
9229   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9230   int rc = SQLITE_OK;             /* Return Code */
9231   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
9232 
9233   u32 mode = 0;                   /* Mode for new entry */
9234   u32 mTime = 0;                  /* Modification time for new entry */
9235   i64 sz = 0;                     /* Uncompressed size */
9236   const char *zPath = 0;          /* Path for new entry */
9237   int nPath = 0;                  /* strlen(zPath) */
9238   const u8 *pData = 0;            /* Pointer to buffer containing content */
9239   int nData = 0;                  /* Size of pData buffer in bytes */
9240   int iMethod = 0;                /* Compression method for new entry */
9241   u8 *pFree = 0;                  /* Free this */
9242   char *zFree = 0;                /* Also free this */
9243   ZipfileEntry *pOld = 0;
9244   ZipfileEntry *pOld2 = 0;
9245   int bUpdate = 0;                /* True for an update that modifies "name" */
9246   int bIsDir = 0;
9247   u32 iCrc32 = 0;
9248 
9249   (void)pRowid;
9250 
9251   if( pTab->pWriteFd==0 ){
9252     rc = zipfileBegin(pVtab);
9253     if( rc!=SQLITE_OK ) return rc;
9254   }
9255 
9256   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
9257   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
9258     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
9259     int nDelete = (int)strlen(zDelete);
9260     if( nVal>1 ){
9261       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
9262       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
9263         bUpdate = 1;
9264       }
9265     }
9266     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
9267       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
9268         break;
9269       }
9270       assert( pOld->pNext );
9271     }
9272   }
9273 
9274   if( nVal>1 ){
9275     /* Check that "sz" and "rawdata" are both NULL: */
9276     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
9277       zipfileTableErr(pTab, "sz must be NULL");
9278       rc = SQLITE_CONSTRAINT;
9279     }
9280     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
9281       zipfileTableErr(pTab, "rawdata must be NULL");
9282       rc = SQLITE_CONSTRAINT;
9283     }
9284 
9285     if( rc==SQLITE_OK ){
9286       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
9287         /* data=NULL. A directory */
9288         bIsDir = 1;
9289       }else{
9290         /* Value specified for "data", and possibly "method". This must be
9291         ** a regular file or a symlink. */
9292         const u8 *aIn = sqlite3_value_blob(apVal[7]);
9293         int nIn = sqlite3_value_bytes(apVal[7]);
9294         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
9295 
9296         iMethod = sqlite3_value_int(apVal[8]);
9297         sz = nIn;
9298         pData = aIn;
9299         nData = nIn;
9300         if( iMethod!=0 && iMethod!=8 ){
9301           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
9302           rc = SQLITE_CONSTRAINT;
9303         }else{
9304           if( bAuto || iMethod ){
9305             int nCmp;
9306             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
9307             if( rc==SQLITE_OK ){
9308               if( iMethod || nCmp<nIn ){
9309                 iMethod = 8;
9310                 pData = pFree;
9311                 nData = nCmp;
9312               }
9313             }
9314           }
9315           iCrc32 = crc32(0, aIn, nIn);
9316         }
9317       }
9318     }
9319 
9320     if( rc==SQLITE_OK ){
9321       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
9322     }
9323 
9324     if( rc==SQLITE_OK ){
9325       zPath = (const char*)sqlite3_value_text(apVal[2]);
9326       if( zPath==0 ) zPath = "";
9327       nPath = (int)strlen(zPath);
9328       mTime = zipfileGetTime(apVal[4]);
9329     }
9330 
9331     if( rc==SQLITE_OK && bIsDir ){
9332       /* For a directory, check that the last character in the path is a
9333       ** '/'. This appears to be required for compatibility with info-zip
9334       ** (the unzip command on unix). It does not create directories
9335       ** otherwise.  */
9336       if( nPath<=0 || zPath[nPath-1]!='/' ){
9337         zFree = sqlite3_mprintf("%s/", zPath);
9338         zPath = (const char*)zFree;
9339         if( zFree==0 ){
9340           rc = SQLITE_NOMEM;
9341           nPath = 0;
9342         }else{
9343           nPath = (int)strlen(zPath);
9344         }
9345       }
9346     }
9347 
9348     /* Check that we're not inserting a duplicate entry -OR- updating an
9349     ** entry with a path, thereby making it into a duplicate. */
9350     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
9351       ZipfileEntry *p;
9352       for(p=pTab->pFirstEntry; p; p=p->pNext){
9353         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
9354           switch( sqlite3_vtab_on_conflict(pTab->db) ){
9355             case SQLITE_IGNORE: {
9356               goto zipfile_update_done;
9357             }
9358             case SQLITE_REPLACE: {
9359               pOld2 = p;
9360               break;
9361             }
9362             default: {
9363               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
9364               rc = SQLITE_CONSTRAINT;
9365               break;
9366             }
9367           }
9368           break;
9369         }
9370       }
9371     }
9372 
9373     if( rc==SQLITE_OK ){
9374       /* Create the new CDS record. */
9375       pNew = zipfileNewEntry(zPath);
9376       if( pNew==0 ){
9377         rc = SQLITE_NOMEM;
9378       }else{
9379         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
9380         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
9381         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
9382         pNew->cds.iCompression = (u16)iMethod;
9383         zipfileMtimeToDos(&pNew->cds, mTime);
9384         pNew->cds.crc32 = iCrc32;
9385         pNew->cds.szCompressed = nData;
9386         pNew->cds.szUncompressed = (u32)sz;
9387         pNew->cds.iExternalAttr = (mode<<16);
9388         pNew->cds.iOffset = (u32)pTab->szCurrent;
9389         pNew->cds.nFile = (u16)nPath;
9390         pNew->mUnixTime = (u32)mTime;
9391         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
9392         zipfileAddEntry(pTab, pOld, pNew);
9393       }
9394     }
9395   }
9396 
9397   if( rc==SQLITE_OK && (pOld || pOld2) ){
9398     ZipfileCsr *pCsr;
9399     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
9400       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
9401         pCsr->pCurrent = pCsr->pCurrent->pNext;
9402         pCsr->bNoop = 1;
9403       }
9404     }
9405 
9406     zipfileRemoveEntryFromList(pTab, pOld);
9407     zipfileRemoveEntryFromList(pTab, pOld2);
9408   }
9409 
9410 zipfile_update_done:
9411   sqlite3_free(pFree);
9412   sqlite3_free(zFree);
9413   return rc;
9414 }
9415 
9416 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
9417   u8 *a = aBuf;
9418   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
9419   zipfileWrite16(a, p->iDisk);
9420   zipfileWrite16(a, p->iFirstDisk);
9421   zipfileWrite16(a, p->nEntry);
9422   zipfileWrite16(a, p->nEntryTotal);
9423   zipfileWrite32(a, p->nSize);
9424   zipfileWrite32(a, p->iOffset);
9425   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
9426 
9427   return a-aBuf;
9428 }
9429 
9430 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
9431   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
9432   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
9433   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
9434 }
9435 
9436 /*
9437 ** Serialize the CDS structure into buffer aBuf[]. Return the number
9438 ** of bytes written.
9439 */
9440 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
9441   u8 *a = aBuf;
9442   ZipfileCDS *pCDS = &pEntry->cds;
9443 
9444   if( pEntry->aExtra==0 ){
9445     pCDS->nExtra = 9;
9446   }
9447 
9448   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
9449   zipfileWrite16(a, pCDS->iVersionMadeBy);
9450   zipfileWrite16(a, pCDS->iVersionExtract);
9451   zipfileWrite16(a, pCDS->flags);
9452   zipfileWrite16(a, pCDS->iCompression);
9453   zipfileWrite16(a, pCDS->mTime);
9454   zipfileWrite16(a, pCDS->mDate);
9455   zipfileWrite32(a, pCDS->crc32);
9456   zipfileWrite32(a, pCDS->szCompressed);
9457   zipfileWrite32(a, pCDS->szUncompressed);
9458   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9459   zipfileWrite16(a, pCDS->nFile);
9460   zipfileWrite16(a, pCDS->nExtra);
9461   zipfileWrite16(a, pCDS->nComment);
9462   zipfileWrite16(a, pCDS->iDiskStart);
9463   zipfileWrite16(a, pCDS->iInternalAttr);
9464   zipfileWrite32(a, pCDS->iExternalAttr);
9465   zipfileWrite32(a, pCDS->iOffset);
9466 
9467   memcpy(a, pCDS->zFile, pCDS->nFile);
9468   a += pCDS->nFile;
9469 
9470   if( pEntry->aExtra ){
9471     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
9472     memcpy(a, pEntry->aExtra, n);
9473     a += n;
9474   }else{
9475     assert( pCDS->nExtra==9 );
9476     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9477     zipfileWrite16(a, 5);
9478     *a++ = 0x01;
9479     zipfileWrite32(a, pEntry->mUnixTime);
9480   }
9481 
9482   return a-aBuf;
9483 }
9484 
9485 static int zipfileCommit(sqlite3_vtab *pVtab){
9486   ZipfileTab *pTab = (ZipfileTab*)pVtab;
9487   int rc = SQLITE_OK;
9488   if( pTab->pWriteFd ){
9489     i64 iOffset = pTab->szCurrent;
9490     ZipfileEntry *p;
9491     ZipfileEOCD eocd;
9492     int nEntry = 0;
9493 
9494     /* Write out all entries */
9495     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
9496       int n = zipfileSerializeCDS(p, pTab->aBuffer);
9497       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
9498       nEntry++;
9499     }
9500 
9501     /* Write out the EOCD record */
9502     eocd.iDisk = 0;
9503     eocd.iFirstDisk = 0;
9504     eocd.nEntry = (u16)nEntry;
9505     eocd.nEntryTotal = (u16)nEntry;
9506     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
9507     eocd.iOffset = (u32)iOffset;
9508     rc = zipfileAppendEOCD(pTab, &eocd);
9509 
9510     zipfileCleanupTransaction(pTab);
9511   }
9512   return rc;
9513 }
9514 
9515 static int zipfileRollback(sqlite3_vtab *pVtab){
9516   return zipfileCommit(pVtab);
9517 }
9518 
9519 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
9520   ZipfileCsr *pCsr;
9521   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
9522     if( iId==pCsr->iId ) break;
9523   }
9524   return pCsr;
9525 }
9526 
9527 static void zipfileFunctionCds(
9528   sqlite3_context *context,
9529   int argc,
9530   sqlite3_value **argv
9531 ){
9532   ZipfileCsr *pCsr;
9533   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
9534   assert( argc>0 );
9535 
9536   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
9537   if( pCsr ){
9538     ZipfileCDS *p = &pCsr->pCurrent->cds;
9539     char *zRes = sqlite3_mprintf("{"
9540         "\"version-made-by\" : %u, "
9541         "\"version-to-extract\" : %u, "
9542         "\"flags\" : %u, "
9543         "\"compression\" : %u, "
9544         "\"time\" : %u, "
9545         "\"date\" : %u, "
9546         "\"crc32\" : %u, "
9547         "\"compressed-size\" : %u, "
9548         "\"uncompressed-size\" : %u, "
9549         "\"file-name-length\" : %u, "
9550         "\"extra-field-length\" : %u, "
9551         "\"file-comment-length\" : %u, "
9552         "\"disk-number-start\" : %u, "
9553         "\"internal-attr\" : %u, "
9554         "\"external-attr\" : %u, "
9555         "\"offset\" : %u }",
9556         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
9557         (u32)p->flags, (u32)p->iCompression,
9558         (u32)p->mTime, (u32)p->mDate,
9559         (u32)p->crc32, (u32)p->szCompressed,
9560         (u32)p->szUncompressed, (u32)p->nFile,
9561         (u32)p->nExtra, (u32)p->nComment,
9562         (u32)p->iDiskStart, (u32)p->iInternalAttr,
9563         (u32)p->iExternalAttr, (u32)p->iOffset
9564     );
9565 
9566     if( zRes==0 ){
9567       sqlite3_result_error_nomem(context);
9568     }else{
9569       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
9570       sqlite3_free(zRes);
9571     }
9572   }
9573 }
9574 
9575 /*
9576 ** xFindFunction method.
9577 */
9578 static int zipfileFindFunction(
9579   sqlite3_vtab *pVtab,            /* Virtual table handle */
9580   int nArg,                       /* Number of SQL function arguments */
9581   const char *zName,              /* Name of SQL function */
9582   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
9583   void **ppArg                    /* OUT: User data for *pxFunc */
9584 ){
9585   (void)nArg;
9586   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
9587     *pxFunc = zipfileFunctionCds;
9588     *ppArg = (void*)pVtab;
9589     return 1;
9590   }
9591   return 0;
9592 }
9593 
9594 typedef struct ZipfileBuffer ZipfileBuffer;
9595 struct ZipfileBuffer {
9596   u8 *a;                          /* Pointer to buffer */
9597   int n;                          /* Size of buffer in bytes */
9598   int nAlloc;                     /* Byte allocated at a[] */
9599 };
9600 
9601 typedef struct ZipfileCtx ZipfileCtx;
9602 struct ZipfileCtx {
9603   int nEntry;
9604   ZipfileBuffer body;
9605   ZipfileBuffer cds;
9606 };
9607 
9608 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
9609   if( pBuf->n+nByte>pBuf->nAlloc ){
9610     u8 *aNew;
9611     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
9612     int nReq = pBuf->n + nByte;
9613 
9614     while( nNew<nReq ) nNew = nNew*2;
9615     aNew = sqlite3_realloc64(pBuf->a, nNew);
9616     if( aNew==0 ) return SQLITE_NOMEM;
9617     pBuf->a = aNew;
9618     pBuf->nAlloc = (int)nNew;
9619   }
9620   return SQLITE_OK;
9621 }
9622 
9623 /*
9624 ** xStep() callback for the zipfile() aggregate. This can be called in
9625 ** any of the following ways:
9626 **
9627 **   SELECT zipfile(name,data) ...
9628 **   SELECT zipfile(name,mode,mtime,data) ...
9629 **   SELECT zipfile(name,mode,mtime,data,method) ...
9630 */
9631 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
9632   ZipfileCtx *p;                  /* Aggregate function context */
9633   ZipfileEntry e;                 /* New entry to add to zip archive */
9634 
9635   sqlite3_value *pName = 0;
9636   sqlite3_value *pMode = 0;
9637   sqlite3_value *pMtime = 0;
9638   sqlite3_value *pData = 0;
9639   sqlite3_value *pMethod = 0;
9640 
9641   int bIsDir = 0;
9642   u32 mode;
9643   int rc = SQLITE_OK;
9644   char *zErr = 0;
9645 
9646   int iMethod = -1;               /* Compression method to use (0 or 8) */
9647 
9648   const u8 *aData = 0;            /* Possibly compressed data for new entry */
9649   int nData = 0;                  /* Size of aData[] in bytes */
9650   int szUncompressed = 0;         /* Size of data before compression */
9651   u8 *aFree = 0;                  /* Free this before returning */
9652   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
9653 
9654   char *zName = 0;                /* Path (name) of new entry */
9655   int nName = 0;                  /* Size of zName in bytes */
9656   char *zFree = 0;                /* Free this before returning */
9657   int nByte;
9658 
9659   memset(&e, 0, sizeof(e));
9660   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
9661   if( p==0 ) return;
9662 
9663   /* Martial the arguments into stack variables */
9664   if( nVal!=2 && nVal!=4 && nVal!=5 ){
9665     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
9666     rc = SQLITE_ERROR;
9667     goto zipfile_step_out;
9668   }
9669   pName = apVal[0];
9670   if( nVal==2 ){
9671     pData = apVal[1];
9672   }else{
9673     pMode = apVal[1];
9674     pMtime = apVal[2];
9675     pData = apVal[3];
9676     if( nVal==5 ){
9677       pMethod = apVal[4];
9678     }
9679   }
9680 
9681   /* Check that the 'name' parameter looks ok. */
9682   zName = (char*)sqlite3_value_text(pName);
9683   nName = sqlite3_value_bytes(pName);
9684   if( zName==0 ){
9685     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
9686     rc = SQLITE_ERROR;
9687     goto zipfile_step_out;
9688   }
9689 
9690   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
9691   ** deflate compression) or NULL (choose automatically).  */
9692   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
9693     iMethod = (int)sqlite3_value_int64(pMethod);
9694     if( iMethod!=0 && iMethod!=8 ){
9695       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
9696       rc = SQLITE_ERROR;
9697       goto zipfile_step_out;
9698     }
9699   }
9700 
9701   /* Now inspect the data. If this is NULL, then the new entry must be a
9702   ** directory.  Otherwise, figure out whether or not the data should
9703   ** be deflated or simply stored in the zip archive. */
9704   if( sqlite3_value_type(pData)==SQLITE_NULL ){
9705     bIsDir = 1;
9706     iMethod = 0;
9707   }else{
9708     aData = sqlite3_value_blob(pData);
9709     szUncompressed = nData = sqlite3_value_bytes(pData);
9710     iCrc32 = crc32(0, aData, nData);
9711     if( iMethod<0 || iMethod==8 ){
9712       int nOut = 0;
9713       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
9714       if( rc!=SQLITE_OK ){
9715         goto zipfile_step_out;
9716       }
9717       if( iMethod==8 || nOut<nData ){
9718         aData = aFree;
9719         nData = nOut;
9720         iMethod = 8;
9721       }else{
9722         iMethod = 0;
9723       }
9724     }
9725   }
9726 
9727   /* Decode the "mode" argument. */
9728   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
9729   if( rc ) goto zipfile_step_out;
9730 
9731   /* Decode the "mtime" argument. */
9732   e.mUnixTime = zipfileGetTime(pMtime);
9733 
9734   /* If this is a directory entry, ensure that there is exactly one '/'
9735   ** at the end of the path. Or, if this is not a directory and the path
9736   ** ends in '/' it is an error. */
9737   if( bIsDir==0 ){
9738     if( nName>0 && zName[nName-1]=='/' ){
9739       zErr = sqlite3_mprintf("non-directory name must not end with /");
9740       rc = SQLITE_ERROR;
9741       goto zipfile_step_out;
9742     }
9743   }else{
9744     if( nName==0 || zName[nName-1]!='/' ){
9745       zName = zFree = sqlite3_mprintf("%s/", zName);
9746       if( zName==0 ){
9747         rc = SQLITE_NOMEM;
9748         goto zipfile_step_out;
9749       }
9750       nName = (int)strlen(zName);
9751     }else{
9752       while( nName>1 && zName[nName-2]=='/' ) nName--;
9753     }
9754   }
9755 
9756   /* Assemble the ZipfileEntry object for the new zip archive entry */
9757   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
9758   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
9759   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
9760   e.cds.iCompression = (u16)iMethod;
9761   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
9762   e.cds.crc32 = iCrc32;
9763   e.cds.szCompressed = nData;
9764   e.cds.szUncompressed = szUncompressed;
9765   e.cds.iExternalAttr = (mode<<16);
9766   e.cds.iOffset = p->body.n;
9767   e.cds.nFile = (u16)nName;
9768   e.cds.zFile = zName;
9769 
9770   /* Append the LFH to the body of the new archive */
9771   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
9772   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
9773   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
9774 
9775   /* Append the data to the body of the new archive */
9776   if( nData>0 ){
9777     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
9778     memcpy(&p->body.a[p->body.n], aData, nData);
9779     p->body.n += nData;
9780   }
9781 
9782   /* Append the CDS record to the directory of the new archive */
9783   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
9784   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
9785   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
9786 
9787   /* Increment the count of entries in the archive */
9788   p->nEntry++;
9789 
9790  zipfile_step_out:
9791   sqlite3_free(aFree);
9792   sqlite3_free(zFree);
9793   if( rc ){
9794     if( zErr ){
9795       sqlite3_result_error(pCtx, zErr, -1);
9796     }else{
9797       sqlite3_result_error_code(pCtx, rc);
9798     }
9799   }
9800   sqlite3_free(zErr);
9801 }
9802 
9803 /*
9804 ** xFinalize() callback for zipfile aggregate function.
9805 */
9806 static void zipfileFinal(sqlite3_context *pCtx){
9807   ZipfileCtx *p;
9808   ZipfileEOCD eocd;
9809   sqlite3_int64 nZip;
9810   u8 *aZip;
9811 
9812   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
9813   if( p==0 ) return;
9814   if( p->nEntry>0 ){
9815     memset(&eocd, 0, sizeof(eocd));
9816     eocd.nEntry = (u16)p->nEntry;
9817     eocd.nEntryTotal = (u16)p->nEntry;
9818     eocd.nSize = p->cds.n;
9819     eocd.iOffset = p->body.n;
9820 
9821     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
9822     aZip = (u8*)sqlite3_malloc64(nZip);
9823     if( aZip==0 ){
9824       sqlite3_result_error_nomem(pCtx);
9825     }else{
9826       memcpy(aZip, p->body.a, p->body.n);
9827       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
9828       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
9829       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
9830     }
9831   }
9832 
9833   sqlite3_free(p->body.a);
9834   sqlite3_free(p->cds.a);
9835 }
9836 
9837 
9838 /*
9839 ** Register the "zipfile" virtual table.
9840 */
9841 static int zipfileRegister(sqlite3 *db){
9842   static sqlite3_module zipfileModule = {
9843     1,                         /* iVersion */
9844     zipfileConnect,            /* xCreate */
9845     zipfileConnect,            /* xConnect */
9846     zipfileBestIndex,          /* xBestIndex */
9847     zipfileDisconnect,         /* xDisconnect */
9848     zipfileDisconnect,         /* xDestroy */
9849     zipfileOpen,               /* xOpen - open a cursor */
9850     zipfileClose,              /* xClose - close a cursor */
9851     zipfileFilter,             /* xFilter - configure scan constraints */
9852     zipfileNext,               /* xNext - advance a cursor */
9853     zipfileEof,                /* xEof - check for end of scan */
9854     zipfileColumn,             /* xColumn - read data */
9855     0,                         /* xRowid - read data */
9856     zipfileUpdate,             /* xUpdate */
9857     zipfileBegin,              /* xBegin */
9858     0,                         /* xSync */
9859     zipfileCommit,             /* xCommit */
9860     zipfileRollback,           /* xRollback */
9861     zipfileFindFunction,       /* xFindMethod */
9862     0,                         /* xRename */
9863     0,                         /* xSavepoint */
9864     0,                         /* xRelease */
9865     0,                         /* xRollback */
9866     0                          /* xShadowName */
9867   };
9868 
9869   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
9870   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
9871   if( rc==SQLITE_OK ){
9872     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
9873         zipfileStep, zipfileFinal
9874     );
9875   }
9876   assert( sizeof(i64)==8 );
9877   assert( sizeof(u32)==4 );
9878   assert( sizeof(u16)==2 );
9879   assert( sizeof(u8)==1 );
9880   return rc;
9881 }
9882 #else         /* SQLITE_OMIT_VIRTUALTABLE */
9883 # define zipfileRegister(x) SQLITE_OK
9884 #endif
9885 
9886 #ifdef _WIN32
9887 
9888 #endif
9889 int sqlite3_zipfile_init(
9890   sqlite3 *db,
9891   char **pzErrMsg,
9892   const sqlite3_api_routines *pApi
9893 ){
9894   SQLITE_EXTENSION_INIT2(pApi);
9895   (void)pzErrMsg;  /* Unused parameter */
9896   return zipfileRegister(db);
9897 }
9898 
9899 /************************* End ../ext/misc/zipfile.c ********************/
9900 /************************* Begin ../ext/misc/sqlar.c ******************/
9901 /*
9902 ** 2017-12-17
9903 **
9904 ** The author disclaims copyright to this source code.  In place of
9905 ** a legal notice, here is a blessing:
9906 **
9907 **    May you do good and not evil.
9908 **    May you find forgiveness for yourself and forgive others.
9909 **    May you share freely, never taking more than you give.
9910 **
9911 ******************************************************************************
9912 **
9913 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
9914 ** for working with sqlar archives and used by the shell tool's built-in
9915 ** sqlar support.
9916 */
9917 /* #include "sqlite3ext.h" */
9918 SQLITE_EXTENSION_INIT1
9919 #include <zlib.h>
9920 #include <assert.h>
9921 
9922 /*
9923 ** Implementation of the "sqlar_compress(X)" SQL function.
9924 **
9925 ** If the type of X is SQLITE_BLOB, and compressing that blob using
9926 ** zlib utility function compress() yields a smaller blob, return the
9927 ** compressed blob. Otherwise, return a copy of X.
9928 **
9929 ** SQLar uses the "zlib format" for compressed content.  The zlib format
9930 ** contains a two-byte identification header and a four-byte checksum at
9931 ** the end.  This is different from ZIP which uses the raw deflate format.
9932 **
9933 ** Future enhancements to SQLar might add support for new compression formats.
9934 ** If so, those new formats will be identified by alternative headers in the
9935 ** compressed data.
9936 */
9937 static void sqlarCompressFunc(
9938   sqlite3_context *context,
9939   int argc,
9940   sqlite3_value **argv
9941 ){
9942   assert( argc==1 );
9943   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
9944     const Bytef *pData = sqlite3_value_blob(argv[0]);
9945     uLong nData = sqlite3_value_bytes(argv[0]);
9946     uLongf nOut = compressBound(nData);
9947     Bytef *pOut;
9948 
9949     pOut = (Bytef*)sqlite3_malloc(nOut);
9950     if( pOut==0 ){
9951       sqlite3_result_error_nomem(context);
9952       return;
9953     }else{
9954       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
9955         sqlite3_result_error(context, "error in compress()", -1);
9956       }else if( nOut<nData ){
9957         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
9958       }else{
9959         sqlite3_result_value(context, argv[0]);
9960       }
9961       sqlite3_free(pOut);
9962     }
9963   }else{
9964     sqlite3_result_value(context, argv[0]);
9965   }
9966 }
9967 
9968 /*
9969 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
9970 **
9971 ** Parameter SZ is interpreted as an integer. If it is less than or
9972 ** equal to zero, then this function returns a copy of X. Or, if
9973 ** SZ is equal to the size of X when interpreted as a blob, also
9974 ** return a copy of X. Otherwise, decompress blob X using zlib
9975 ** utility function uncompress() and return the results (another
9976 ** blob).
9977 */
9978 static void sqlarUncompressFunc(
9979   sqlite3_context *context,
9980   int argc,
9981   sqlite3_value **argv
9982 ){
9983   uLong nData;
9984   uLongf sz;
9985 
9986   assert( argc==2 );
9987   sz = sqlite3_value_int(argv[1]);
9988 
9989   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
9990     sqlite3_result_value(context, argv[0]);
9991   }else{
9992     const Bytef *pData= sqlite3_value_blob(argv[0]);
9993     Bytef *pOut = sqlite3_malloc(sz);
9994     if( pOut==0 ){
9995       sqlite3_result_error_nomem(context);
9996     }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
9997       sqlite3_result_error(context, "error in uncompress()", -1);
9998     }else{
9999       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
10000     }
10001     sqlite3_free(pOut);
10002   }
10003 }
10004 
10005 #ifdef _WIN32
10006 
10007 #endif
10008 int sqlite3_sqlar_init(
10009   sqlite3 *db,
10010   char **pzErrMsg,
10011   const sqlite3_api_routines *pApi
10012 ){
10013   int rc = SQLITE_OK;
10014   SQLITE_EXTENSION_INIT2(pApi);
10015   (void)pzErrMsg;  /* Unused parameter */
10016   rc = sqlite3_create_function(db, "sqlar_compress", 1,
10017                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10018                                sqlarCompressFunc, 0, 0);
10019   if( rc==SQLITE_OK ){
10020     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
10021                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10022                                  sqlarUncompressFunc, 0, 0);
10023   }
10024   return rc;
10025 }
10026 
10027 /************************* End ../ext/misc/sqlar.c ********************/
10028 #endif
10029 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
10030 /*
10031 ** 2017 April 07
10032 **
10033 ** The author disclaims copyright to this source code.  In place of
10034 ** a legal notice, here is a blessing:
10035 **
10036 **    May you do good and not evil.
10037 **    May you find forgiveness for yourself and forgive others.
10038 **    May you share freely, never taking more than you give.
10039 **
10040 *************************************************************************
10041 */
10042 #if !defined(SQLITEEXPERT_H)
10043 #define SQLITEEXPERT_H 1
10044 /* #include "sqlite3.h" */
10045 
10046 typedef struct sqlite3expert sqlite3expert;
10047 
10048 /*
10049 ** Create a new sqlite3expert object.
10050 **
10051 ** If successful, a pointer to the new object is returned and (*pzErr) set
10052 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
10053 ** an English-language error message. In this case it is the responsibility
10054 ** of the caller to eventually free the error message buffer using
10055 ** sqlite3_free().
10056 */
10057 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
10058 
10059 /*
10060 ** Configure an sqlite3expert object.
10061 **
10062 ** EXPERT_CONFIG_SAMPLE:
10063 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
10064 **   each candidate index. This involves scanning and sorting the entire
10065 **   contents of each user database table once for each candidate index
10066 **   associated with the table. For large databases, this can be
10067 **   prohibitively slow. This option allows the sqlite3expert object to
10068 **   be configured so that sqlite_stat1 data is instead generated based on a
10069 **   subset of each table, or so that no sqlite_stat1 data is used at all.
10070 **
10071 **   A single integer argument is passed to this option. If the value is less
10072 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
10073 **   the analysis - indexes are recommended based on the database schema only.
10074 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
10075 **   generated for each candidate index (this is the default). Finally, if the
10076 **   value falls between 0 and 100, then it represents the percentage of user
10077 **   table rows that should be considered when generating sqlite_stat1 data.
10078 **
10079 **   Examples:
10080 **
10081 **     // Do not generate any sqlite_stat1 data
10082 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
10083 **
10084 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
10085 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
10086 */
10087 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
10088 
10089 #define EXPERT_CONFIG_SAMPLE 1    /* int */
10090 
10091 /*
10092 ** Specify zero or more SQL statements to be included in the analysis.
10093 **
10094 ** Buffer zSql must contain zero or more complete SQL statements. This
10095 ** function parses all statements contained in the buffer and adds them
10096 ** to the internal list of statements to analyze. If successful, SQLITE_OK
10097 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
10098 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
10099 ** may be set to point to an English language error message. In this case
10100 ** the caller is responsible for eventually freeing the error message buffer
10101 ** using sqlite3_free().
10102 **
10103 ** If an error does occur while processing one of the statements in the
10104 ** buffer passed as the second argument, none of the statements in the
10105 ** buffer are added to the analysis.
10106 **
10107 ** This function must be called before sqlite3_expert_analyze(). If a call
10108 ** to this function is made on an sqlite3expert object that has already
10109 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
10110 ** immediately and no statements are added to the analysis.
10111 */
10112 int sqlite3_expert_sql(
10113   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
10114   const char *zSql,               /* SQL statement(s) to add */
10115   char **pzErr                    /* OUT: Error message (if any) */
10116 );
10117 
10118 
10119 /*
10120 ** This function is called after the sqlite3expert object has been configured
10121 ** with all SQL statements using sqlite3_expert_sql() to actually perform
10122 ** the analysis. Once this function has been called, it is not possible to
10123 ** add further SQL statements to the analysis.
10124 **
10125 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
10126 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
10127 ** point to a buffer containing an English language error message. In this
10128 ** case it is the responsibility of the caller to eventually free the buffer
10129 ** using sqlite3_free().
10130 **
10131 ** If an error does occur within this function, the sqlite3expert object
10132 ** is no longer useful for any purpose. At that point it is no longer
10133 ** possible to add further SQL statements to the object or to re-attempt
10134 ** the analysis. The sqlite3expert object must still be freed using a call
10135 ** sqlite3_expert_destroy().
10136 */
10137 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
10138 
10139 /*
10140 ** Return the total number of statements loaded using sqlite3_expert_sql().
10141 ** The total number of SQL statements may be different from the total number
10142 ** to calls to sqlite3_expert_sql().
10143 */
10144 int sqlite3_expert_count(sqlite3expert*);
10145 
10146 /*
10147 ** Return a component of the report.
10148 **
10149 ** This function is called after sqlite3_expert_analyze() to extract the
10150 ** results of the analysis. Each call to this function returns either a
10151 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
10152 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
10153 ** #define constants defined below.
10154 **
10155 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
10156 ** information relating to a specific SQL statement. In these cases that
10157 ** SQL statement is identified by the value passed as the second argument.
10158 ** SQL statements are numbered from 0 in the order in which they are parsed.
10159 ** If an out-of-range value (less than zero or equal to or greater than the
10160 ** value returned by sqlite3_expert_count()) is passed as the second argument
10161 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
10162 **
10163 ** EXPERT_REPORT_SQL:
10164 **   Return the text of SQL statement iStmt.
10165 **
10166 ** EXPERT_REPORT_INDEXES:
10167 **   Return a buffer containing the CREATE INDEX statements for all recommended
10168 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
10169 **   is returned.
10170 **
10171 ** EXPERT_REPORT_PLAN:
10172 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
10173 **   iStmt after the proposed indexes have been added to the database schema.
10174 **
10175 ** EXPERT_REPORT_CANDIDATES:
10176 **   Return a pointer to a buffer containing the CREATE INDEX statements
10177 **   for all indexes that were tested (for all SQL statements). The iStmt
10178 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
10179 */
10180 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
10181 
10182 /*
10183 ** Values for the third argument passed to sqlite3_expert_report().
10184 */
10185 #define EXPERT_REPORT_SQL        1
10186 #define EXPERT_REPORT_INDEXES    2
10187 #define EXPERT_REPORT_PLAN       3
10188 #define EXPERT_REPORT_CANDIDATES 4
10189 
10190 /*
10191 ** Free an (sqlite3expert*) handle and all associated resources. There
10192 ** should be one call to this function for each successful call to
10193 ** sqlite3-expert_new().
10194 */
10195 void sqlite3_expert_destroy(sqlite3expert*);
10196 
10197 #endif  /* !defined(SQLITEEXPERT_H) */
10198 
10199 /************************* End ../ext/expert/sqlite3expert.h ********************/
10200 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
10201 /*
10202 ** 2017 April 09
10203 **
10204 ** The author disclaims copyright to this source code.  In place of
10205 ** a legal notice, here is a blessing:
10206 **
10207 **    May you do good and not evil.
10208 **    May you find forgiveness for yourself and forgive others.
10209 **    May you share freely, never taking more than you give.
10210 **
10211 *************************************************************************
10212 */
10213 /* #include "sqlite3expert.h" */
10214 #include <assert.h>
10215 #include <string.h>
10216 #include <stdio.h>
10217 
10218 #if !defined(SQLITE_AMALGAMATION)
10219 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
10220 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
10221 #endif
10222 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
10223 # define ALWAYS(X)      (1)
10224 # define NEVER(X)       (0)
10225 #elif !defined(NDEBUG)
10226 # define ALWAYS(X)      ((X)?1:(assert(0),0))
10227 # define NEVER(X)       ((X)?(assert(0),1):0)
10228 #else
10229 # define ALWAYS(X)      (X)
10230 # define NEVER(X)       (X)
10231 #endif
10232 #endif /* !defined(SQLITE_AMALGAMATION) */
10233 
10234 
10235 #ifndef SQLITE_OMIT_VIRTUALTABLE
10236 
10237 /* typedef sqlite3_int64 i64; */
10238 /* typedef sqlite3_uint64 u64; */
10239 
10240 typedef struct IdxColumn IdxColumn;
10241 typedef struct IdxConstraint IdxConstraint;
10242 typedef struct IdxScan IdxScan;
10243 typedef struct IdxStatement IdxStatement;
10244 typedef struct IdxTable IdxTable;
10245 typedef struct IdxWrite IdxWrite;
10246 
10247 #define STRLEN  (int)strlen
10248 
10249 /*
10250 ** A temp table name that we assume no user database will actually use.
10251 ** If this assumption proves incorrect triggers on the table with the
10252 ** conflicting name will be ignored.
10253 */
10254 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
10255 
10256 /*
10257 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
10258 ** any other type of single-ended range constraint on a column).
10259 **
10260 ** pLink:
10261 **   Used to temporarily link IdxConstraint objects into lists while
10262 **   creating candidate indexes.
10263 */
10264 struct IdxConstraint {
10265   char *zColl;                    /* Collation sequence */
10266   int bRange;                     /* True for range, false for eq */
10267   int iCol;                       /* Constrained table column */
10268   int bFlag;                      /* Used by idxFindCompatible() */
10269   int bDesc;                      /* True if ORDER BY <expr> DESC */
10270   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
10271   IdxConstraint *pLink;           /* See above */
10272 };
10273 
10274 /*
10275 ** A single scan of a single table.
10276 */
10277 struct IdxScan {
10278   IdxTable *pTab;                 /* Associated table object */
10279   int iDb;                        /* Database containing table zTable */
10280   i64 covering;                   /* Mask of columns required for cov. index */
10281   IdxConstraint *pOrder;          /* ORDER BY columns */
10282   IdxConstraint *pEq;             /* List of == constraints */
10283   IdxConstraint *pRange;          /* List of < constraints */
10284   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
10285 };
10286 
10287 /*
10288 ** Information regarding a single database table. Extracted from
10289 ** "PRAGMA table_info" by function idxGetTableInfo().
10290 */
10291 struct IdxColumn {
10292   char *zName;
10293   char *zColl;
10294   int iPk;
10295 };
10296 struct IdxTable {
10297   int nCol;
10298   char *zName;                    /* Table name */
10299   IdxColumn *aCol;
10300   IdxTable *pNext;                /* Next table in linked list of all tables */
10301 };
10302 
10303 /*
10304 ** An object of the following type is created for each unique table/write-op
10305 ** seen. The objects are stored in a singly-linked list beginning at
10306 ** sqlite3expert.pWrite.
10307 */
10308 struct IdxWrite {
10309   IdxTable *pTab;
10310   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
10311   IdxWrite *pNext;
10312 };
10313 
10314 /*
10315 ** Each statement being analyzed is represented by an instance of this
10316 ** structure.
10317 */
10318 struct IdxStatement {
10319   int iId;                        /* Statement number */
10320   char *zSql;                     /* SQL statement */
10321   char *zIdx;                     /* Indexes */
10322   char *zEQP;                     /* Plan */
10323   IdxStatement *pNext;
10324 };
10325 
10326 
10327 /*
10328 ** A hash table for storing strings. With space for a payload string
10329 ** with each entry. Methods are:
10330 **
10331 **   idxHashInit()
10332 **   idxHashClear()
10333 **   idxHashAdd()
10334 **   idxHashSearch()
10335 */
10336 #define IDX_HASH_SIZE 1023
10337 typedef struct IdxHashEntry IdxHashEntry;
10338 typedef struct IdxHash IdxHash;
10339 struct IdxHashEntry {
10340   char *zKey;                     /* nul-terminated key */
10341   char *zVal;                     /* nul-terminated value string */
10342   char *zVal2;                    /* nul-terminated value string 2 */
10343   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
10344   IdxHashEntry *pNext;            /* Next entry in hash */
10345 };
10346 struct IdxHash {
10347   IdxHashEntry *pFirst;
10348   IdxHashEntry *aHash[IDX_HASH_SIZE];
10349 };
10350 
10351 /*
10352 ** sqlite3expert object.
10353 */
10354 struct sqlite3expert {
10355   int iSample;                    /* Percentage of tables to sample for stat1 */
10356   sqlite3 *db;                    /* User database */
10357   sqlite3 *dbm;                   /* In-memory db for this analysis */
10358   sqlite3 *dbv;                   /* Vtab schema for this analysis */
10359   IdxTable *pTable;               /* List of all IdxTable objects */
10360   IdxScan *pScan;                 /* List of scan objects */
10361   IdxWrite *pWrite;               /* List of write objects */
10362   IdxStatement *pStatement;       /* List of IdxStatement objects */
10363   int bRun;                       /* True once analysis has run */
10364   char **pzErrmsg;
10365   int rc;                         /* Error code from whereinfo hook */
10366   IdxHash hIdx;                   /* Hash containing all candidate indexes */
10367   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
10368 };
10369 
10370 
10371 /*
10372 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
10373 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
10374 */
10375 static void *idxMalloc(int *pRc, int nByte){
10376   void *pRet;
10377   assert( *pRc==SQLITE_OK );
10378   assert( nByte>0 );
10379   pRet = sqlite3_malloc(nByte);
10380   if( pRet ){
10381     memset(pRet, 0, nByte);
10382   }else{
10383     *pRc = SQLITE_NOMEM;
10384   }
10385   return pRet;
10386 }
10387 
10388 /*
10389 ** Initialize an IdxHash hash table.
10390 */
10391 static void idxHashInit(IdxHash *pHash){
10392   memset(pHash, 0, sizeof(IdxHash));
10393 }
10394 
10395 /*
10396 ** Reset an IdxHash hash table.
10397 */
10398 static void idxHashClear(IdxHash *pHash){
10399   int i;
10400   for(i=0; i<IDX_HASH_SIZE; i++){
10401     IdxHashEntry *pEntry;
10402     IdxHashEntry *pNext;
10403     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
10404       pNext = pEntry->pHashNext;
10405       sqlite3_free(pEntry->zVal2);
10406       sqlite3_free(pEntry);
10407     }
10408   }
10409   memset(pHash, 0, sizeof(IdxHash));
10410 }
10411 
10412 /*
10413 ** Return the index of the hash bucket that the string specified by the
10414 ** arguments to this function belongs.
10415 */
10416 static int idxHashString(const char *z, int n){
10417   unsigned int ret = 0;
10418   int i;
10419   for(i=0; i<n; i++){
10420     ret += (ret<<3) + (unsigned char)(z[i]);
10421   }
10422   return (int)(ret % IDX_HASH_SIZE);
10423 }
10424 
10425 /*
10426 ** If zKey is already present in the hash table, return non-zero and do
10427 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
10428 ** the hash table passed as the second argument.
10429 */
10430 static int idxHashAdd(
10431   int *pRc,
10432   IdxHash *pHash,
10433   const char *zKey,
10434   const char *zVal
10435 ){
10436   int nKey = STRLEN(zKey);
10437   int iHash = idxHashString(zKey, nKey);
10438   int nVal = (zVal ? STRLEN(zVal) : 0);
10439   IdxHashEntry *pEntry;
10440   assert( iHash>=0 );
10441   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
10442     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
10443       return 1;
10444     }
10445   }
10446   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
10447   if( pEntry ){
10448     pEntry->zKey = (char*)&pEntry[1];
10449     memcpy(pEntry->zKey, zKey, nKey);
10450     if( zVal ){
10451       pEntry->zVal = &pEntry->zKey[nKey+1];
10452       memcpy(pEntry->zVal, zVal, nVal);
10453     }
10454     pEntry->pHashNext = pHash->aHash[iHash];
10455     pHash->aHash[iHash] = pEntry;
10456 
10457     pEntry->pNext = pHash->pFirst;
10458     pHash->pFirst = pEntry;
10459   }
10460   return 0;
10461 }
10462 
10463 /*
10464 ** If zKey/nKey is present in the hash table, return a pointer to the
10465 ** hash-entry object.
10466 */
10467 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
10468   int iHash;
10469   IdxHashEntry *pEntry;
10470   if( nKey<0 ) nKey = STRLEN(zKey);
10471   iHash = idxHashString(zKey, nKey);
10472   assert( iHash>=0 );
10473   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
10474     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
10475       return pEntry;
10476     }
10477   }
10478   return 0;
10479 }
10480 
10481 /*
10482 ** If the hash table contains an entry with a key equal to the string
10483 ** passed as the final two arguments to this function, return a pointer
10484 ** to the payload string. Otherwise, if zKey/nKey is not present in the
10485 ** hash table, return NULL.
10486 */
10487 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
10488   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
10489   if( pEntry ) return pEntry->zVal;
10490   return 0;
10491 }
10492 
10493 /*
10494 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
10495 ** variable to point to a copy of nul-terminated string zColl.
10496 */
10497 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
10498   IdxConstraint *pNew;
10499   int nColl = STRLEN(zColl);
10500 
10501   assert( *pRc==SQLITE_OK );
10502   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
10503   if( pNew ){
10504     pNew->zColl = (char*)&pNew[1];
10505     memcpy(pNew->zColl, zColl, nColl+1);
10506   }
10507   return pNew;
10508 }
10509 
10510 /*
10511 ** An error associated with database handle db has just occurred. Pass
10512 ** the error message to callback function xOut.
10513 */
10514 static void idxDatabaseError(
10515   sqlite3 *db,                    /* Database handle */
10516   char **pzErrmsg                 /* Write error here */
10517 ){
10518   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
10519 }
10520 
10521 /*
10522 ** Prepare an SQL statement.
10523 */
10524 static int idxPrepareStmt(
10525   sqlite3 *db,                    /* Database handle to compile against */
10526   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
10527   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
10528   const char *zSql                /* SQL statement to compile */
10529 ){
10530   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
10531   if( rc!=SQLITE_OK ){
10532     *ppStmt = 0;
10533     idxDatabaseError(db, pzErrmsg);
10534   }
10535   return rc;
10536 }
10537 
10538 /*
10539 ** Prepare an SQL statement using the results of a printf() formatting.
10540 */
10541 static int idxPrintfPrepareStmt(
10542   sqlite3 *db,                    /* Database handle to compile against */
10543   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
10544   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
10545   const char *zFmt,               /* printf() format of SQL statement */
10546   ...                             /* Trailing printf() arguments */
10547 ){
10548   va_list ap;
10549   int rc;
10550   char *zSql;
10551   va_start(ap, zFmt);
10552   zSql = sqlite3_vmprintf(zFmt, ap);
10553   if( zSql==0 ){
10554     rc = SQLITE_NOMEM;
10555   }else{
10556     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
10557     sqlite3_free(zSql);
10558   }
10559   va_end(ap);
10560   return rc;
10561 }
10562 
10563 
10564 /*************************************************************************
10565 ** Beginning of virtual table implementation.
10566 */
10567 typedef struct ExpertVtab ExpertVtab;
10568 struct ExpertVtab {
10569   sqlite3_vtab base;
10570   IdxTable *pTab;
10571   sqlite3expert *pExpert;
10572 };
10573 
10574 typedef struct ExpertCsr ExpertCsr;
10575 struct ExpertCsr {
10576   sqlite3_vtab_cursor base;
10577   sqlite3_stmt *pData;
10578 };
10579 
10580 static char *expertDequote(const char *zIn){
10581   int n = STRLEN(zIn);
10582   char *zRet = sqlite3_malloc(n);
10583 
10584   assert( zIn[0]=='\'' );
10585   assert( zIn[n-1]=='\'' );
10586 
10587   if( zRet ){
10588     int iOut = 0;
10589     int iIn = 0;
10590     for(iIn=1; iIn<(n-1); iIn++){
10591       if( zIn[iIn]=='\'' ){
10592         assert( zIn[iIn+1]=='\'' );
10593         iIn++;
10594       }
10595       zRet[iOut++] = zIn[iIn];
10596     }
10597     zRet[iOut] = '\0';
10598   }
10599 
10600   return zRet;
10601 }
10602 
10603 /*
10604 ** This function is the implementation of both the xConnect and xCreate
10605 ** methods of the r-tree virtual table.
10606 **
10607 **   argv[0]   -> module name
10608 **   argv[1]   -> database name
10609 **   argv[2]   -> table name
10610 **   argv[...] -> column names...
10611 */
10612 static int expertConnect(
10613   sqlite3 *db,
10614   void *pAux,
10615   int argc, const char *const*argv,
10616   sqlite3_vtab **ppVtab,
10617   char **pzErr
10618 ){
10619   sqlite3expert *pExpert = (sqlite3expert*)pAux;
10620   ExpertVtab *p = 0;
10621   int rc;
10622 
10623   if( argc!=4 ){
10624     *pzErr = sqlite3_mprintf("internal error!");
10625     rc = SQLITE_ERROR;
10626   }else{
10627     char *zCreateTable = expertDequote(argv[3]);
10628     if( zCreateTable ){
10629       rc = sqlite3_declare_vtab(db, zCreateTable);
10630       if( rc==SQLITE_OK ){
10631         p = idxMalloc(&rc, sizeof(ExpertVtab));
10632       }
10633       if( rc==SQLITE_OK ){
10634         p->pExpert = pExpert;
10635         p->pTab = pExpert->pTable;
10636         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
10637       }
10638       sqlite3_free(zCreateTable);
10639     }else{
10640       rc = SQLITE_NOMEM;
10641     }
10642   }
10643 
10644   *ppVtab = (sqlite3_vtab*)p;
10645   return rc;
10646 }
10647 
10648 static int expertDisconnect(sqlite3_vtab *pVtab){
10649   ExpertVtab *p = (ExpertVtab*)pVtab;
10650   sqlite3_free(p);
10651   return SQLITE_OK;
10652 }
10653 
10654 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
10655   ExpertVtab *p = (ExpertVtab*)pVtab;
10656   int rc = SQLITE_OK;
10657   int n = 0;
10658   IdxScan *pScan;
10659   const int opmask =
10660     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
10661     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
10662     SQLITE_INDEX_CONSTRAINT_LE;
10663 
10664   pScan = idxMalloc(&rc, sizeof(IdxScan));
10665   if( pScan ){
10666     int i;
10667 
10668     /* Link the new scan object into the list */
10669     pScan->pTab = p->pTab;
10670     pScan->pNextScan = p->pExpert->pScan;
10671     p->pExpert->pScan = pScan;
10672 
10673     /* Add the constraints to the IdxScan object */
10674     for(i=0; i<pIdxInfo->nConstraint; i++){
10675       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10676       if( pCons->usable
10677        && pCons->iColumn>=0
10678        && p->pTab->aCol[pCons->iColumn].iPk==0
10679        && (pCons->op & opmask)
10680       ){
10681         IdxConstraint *pNew;
10682         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
10683         pNew = idxNewConstraint(&rc, zColl);
10684         if( pNew ){
10685           pNew->iCol = pCons->iColumn;
10686           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10687             pNew->pNext = pScan->pEq;
10688             pScan->pEq = pNew;
10689           }else{
10690             pNew->bRange = 1;
10691             pNew->pNext = pScan->pRange;
10692             pScan->pRange = pNew;
10693           }
10694         }
10695         n++;
10696         pIdxInfo->aConstraintUsage[i].argvIndex = n;
10697       }
10698     }
10699 
10700     /* Add the ORDER BY to the IdxScan object */
10701     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
10702       int iCol = pIdxInfo->aOrderBy[i].iColumn;
10703       if( iCol>=0 ){
10704         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
10705         if( pNew ){
10706           pNew->iCol = iCol;
10707           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
10708           pNew->pNext = pScan->pOrder;
10709           pNew->pLink = pScan->pOrder;
10710           pScan->pOrder = pNew;
10711           n++;
10712         }
10713       }
10714     }
10715   }
10716 
10717   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
10718   return rc;
10719 }
10720 
10721 static int expertUpdate(
10722   sqlite3_vtab *pVtab,
10723   int nData,
10724   sqlite3_value **azData,
10725   sqlite_int64 *pRowid
10726 ){
10727   (void)pVtab;
10728   (void)nData;
10729   (void)azData;
10730   (void)pRowid;
10731   return SQLITE_OK;
10732 }
10733 
10734 /*
10735 ** Virtual table module xOpen method.
10736 */
10737 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
10738   int rc = SQLITE_OK;
10739   ExpertCsr *pCsr;
10740   (void)pVTab;
10741   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
10742   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
10743   return rc;
10744 }
10745 
10746 /*
10747 ** Virtual table module xClose method.
10748 */
10749 static int expertClose(sqlite3_vtab_cursor *cur){
10750   ExpertCsr *pCsr = (ExpertCsr*)cur;
10751   sqlite3_finalize(pCsr->pData);
10752   sqlite3_free(pCsr);
10753   return SQLITE_OK;
10754 }
10755 
10756 /*
10757 ** Virtual table module xEof method.
10758 **
10759 ** Return non-zero if the cursor does not currently point to a valid
10760 ** record (i.e if the scan has finished), or zero otherwise.
10761 */
10762 static int expertEof(sqlite3_vtab_cursor *cur){
10763   ExpertCsr *pCsr = (ExpertCsr*)cur;
10764   return pCsr->pData==0;
10765 }
10766 
10767 /*
10768 ** Virtual table module xNext method.
10769 */
10770 static int expertNext(sqlite3_vtab_cursor *cur){
10771   ExpertCsr *pCsr = (ExpertCsr*)cur;
10772   int rc = SQLITE_OK;
10773 
10774   assert( pCsr->pData );
10775   rc = sqlite3_step(pCsr->pData);
10776   if( rc!=SQLITE_ROW ){
10777     rc = sqlite3_finalize(pCsr->pData);
10778     pCsr->pData = 0;
10779   }else{
10780     rc = SQLITE_OK;
10781   }
10782 
10783   return rc;
10784 }
10785 
10786 /*
10787 ** Virtual table module xRowid method.
10788 */
10789 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
10790   (void)cur;
10791   *pRowid = 0;
10792   return SQLITE_OK;
10793 }
10794 
10795 /*
10796 ** Virtual table module xColumn method.
10797 */
10798 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
10799   ExpertCsr *pCsr = (ExpertCsr*)cur;
10800   sqlite3_value *pVal;
10801   pVal = sqlite3_column_value(pCsr->pData, i);
10802   if( pVal ){
10803     sqlite3_result_value(ctx, pVal);
10804   }
10805   return SQLITE_OK;
10806 }
10807 
10808 /*
10809 ** Virtual table module xFilter method.
10810 */
10811 static int expertFilter(
10812   sqlite3_vtab_cursor *cur,
10813   int idxNum, const char *idxStr,
10814   int argc, sqlite3_value **argv
10815 ){
10816   ExpertCsr *pCsr = (ExpertCsr*)cur;
10817   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
10818   sqlite3expert *pExpert = pVtab->pExpert;
10819   int rc;
10820 
10821   (void)idxNum;
10822   (void)idxStr;
10823   (void)argc;
10824   (void)argv;
10825   rc = sqlite3_finalize(pCsr->pData);
10826   pCsr->pData = 0;
10827   if( rc==SQLITE_OK ){
10828     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
10829         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
10830     );
10831   }
10832 
10833   if( rc==SQLITE_OK ){
10834     rc = expertNext(cur);
10835   }
10836   return rc;
10837 }
10838 
10839 static int idxRegisterVtab(sqlite3expert *p){
10840   static sqlite3_module expertModule = {
10841     2,                            /* iVersion */
10842     expertConnect,                /* xCreate - create a table */
10843     expertConnect,                /* xConnect - connect to an existing table */
10844     expertBestIndex,              /* xBestIndex - Determine search strategy */
10845     expertDisconnect,             /* xDisconnect - Disconnect from a table */
10846     expertDisconnect,             /* xDestroy - Drop a table */
10847     expertOpen,                   /* xOpen - open a cursor */
10848     expertClose,                  /* xClose - close a cursor */
10849     expertFilter,                 /* xFilter - configure scan constraints */
10850     expertNext,                   /* xNext - advance a cursor */
10851     expertEof,                    /* xEof */
10852     expertColumn,                 /* xColumn - read data */
10853     expertRowid,                  /* xRowid - read data */
10854     expertUpdate,                 /* xUpdate - write data */
10855     0,                            /* xBegin - begin transaction */
10856     0,                            /* xSync - sync transaction */
10857     0,                            /* xCommit - commit transaction */
10858     0,                            /* xRollback - rollback transaction */
10859     0,                            /* xFindFunction - function overloading */
10860     0,                            /* xRename - rename the table */
10861     0,                            /* xSavepoint */
10862     0,                            /* xRelease */
10863     0,                            /* xRollbackTo */
10864     0,                            /* xShadowName */
10865   };
10866 
10867   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
10868 }
10869 /*
10870 ** End of virtual table implementation.
10871 *************************************************************************/
10872 /*
10873 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
10874 ** is called, set it to the return value of sqlite3_finalize() before
10875 ** returning. Otherwise, discard the sqlite3_finalize() return value.
10876 */
10877 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
10878   int rc = sqlite3_finalize(pStmt);
10879   if( *pRc==SQLITE_OK ) *pRc = rc;
10880 }
10881 
10882 /*
10883 ** Attempt to allocate an IdxTable structure corresponding to table zTab
10884 ** in the main database of connection db. If successful, set (*ppOut) to
10885 ** point to the new object and return SQLITE_OK. Otherwise, return an
10886 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
10887 ** set to point to an error string.
10888 **
10889 ** It is the responsibility of the caller to eventually free either the
10890 ** IdxTable object or error message using sqlite3_free().
10891 */
10892 static int idxGetTableInfo(
10893   sqlite3 *db,                    /* Database connection to read details from */
10894   const char *zTab,               /* Table name */
10895   IdxTable **ppOut,               /* OUT: New object (if successful) */
10896   char **pzErrmsg                 /* OUT: Error message (if not) */
10897 ){
10898   sqlite3_stmt *p1 = 0;
10899   int nCol = 0;
10900   int nTab;
10901   int nByte;
10902   IdxTable *pNew = 0;
10903   int rc, rc2;
10904   char *pCsr = 0;
10905   int nPk = 0;
10906 
10907   *ppOut = 0;
10908   if( zTab==0 ) return SQLITE_ERROR;
10909   nTab = STRLEN(zTab);
10910   nByte = sizeof(IdxTable) + nTab + 1;
10911   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
10912   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
10913     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
10914     const char *zColSeq = 0;
10915     if( zCol==0 ){
10916       rc = SQLITE_ERROR;
10917       break;
10918     }
10919     nByte += 1 + STRLEN(zCol);
10920     rc = sqlite3_table_column_metadata(
10921         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
10922     );
10923     if( zColSeq==0 ) zColSeq = "binary";
10924     nByte += 1 + STRLEN(zColSeq);
10925     nCol++;
10926     nPk += (sqlite3_column_int(p1, 5)>0);
10927   }
10928   rc2 = sqlite3_reset(p1);
10929   if( rc==SQLITE_OK ) rc = rc2;
10930 
10931   nByte += sizeof(IdxColumn) * nCol;
10932   if( rc==SQLITE_OK ){
10933     pNew = idxMalloc(&rc, nByte);
10934   }
10935   if( rc==SQLITE_OK ){
10936     pNew->aCol = (IdxColumn*)&pNew[1];
10937     pNew->nCol = nCol;
10938     pCsr = (char*)&pNew->aCol[nCol];
10939   }
10940 
10941   nCol = 0;
10942   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
10943     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
10944     const char *zColSeq = 0;
10945     int nCopy;
10946     if( zCol==0 ) continue;
10947     nCopy = STRLEN(zCol) + 1;
10948     pNew->aCol[nCol].zName = pCsr;
10949     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
10950     memcpy(pCsr, zCol, nCopy);
10951     pCsr += nCopy;
10952 
10953     rc = sqlite3_table_column_metadata(
10954         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
10955     );
10956     if( rc==SQLITE_OK ){
10957       if( zColSeq==0 ) zColSeq = "binary";
10958       nCopy = STRLEN(zColSeq) + 1;
10959       pNew->aCol[nCol].zColl = pCsr;
10960       memcpy(pCsr, zColSeq, nCopy);
10961       pCsr += nCopy;
10962     }
10963 
10964     nCol++;
10965   }
10966   idxFinalize(&rc, p1);
10967 
10968   if( rc!=SQLITE_OK ){
10969     sqlite3_free(pNew);
10970     pNew = 0;
10971   }else if( ALWAYS(pNew!=0) ){
10972     pNew->zName = pCsr;
10973     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
10974   }
10975 
10976   *ppOut = pNew;
10977   return rc;
10978 }
10979 
10980 /*
10981 ** This function is a no-op if *pRc is set to anything other than
10982 ** SQLITE_OK when it is called.
10983 **
10984 ** If *pRc is initially set to SQLITE_OK, then the text specified by
10985 ** the printf() style arguments is appended to zIn and the result returned
10986 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
10987 ** zIn before returning.
10988 */
10989 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
10990   va_list ap;
10991   char *zAppend = 0;
10992   char *zRet = 0;
10993   int nIn = zIn ? STRLEN(zIn) : 0;
10994   int nAppend = 0;
10995   va_start(ap, zFmt);
10996   if( *pRc==SQLITE_OK ){
10997     zAppend = sqlite3_vmprintf(zFmt, ap);
10998     if( zAppend ){
10999       nAppend = STRLEN(zAppend);
11000       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
11001     }
11002     if( zAppend && zRet ){
11003       if( nIn ) memcpy(zRet, zIn, nIn);
11004       memcpy(&zRet[nIn], zAppend, nAppend+1);
11005     }else{
11006       sqlite3_free(zRet);
11007       zRet = 0;
11008       *pRc = SQLITE_NOMEM;
11009     }
11010     sqlite3_free(zAppend);
11011     sqlite3_free(zIn);
11012   }
11013   va_end(ap);
11014   return zRet;
11015 }
11016 
11017 /*
11018 ** Return true if zId must be quoted in order to use it as an SQL
11019 ** identifier, or false otherwise.
11020 */
11021 static int idxIdentifierRequiresQuotes(const char *zId){
11022   int i;
11023   int nId = STRLEN(zId);
11024 
11025   if( sqlite3_keyword_check(zId, nId) ) return 1;
11026 
11027   for(i=0; zId[i]; i++){
11028     if( !(zId[i]=='_')
11029      && !(zId[i]>='0' && zId[i]<='9')
11030      && !(zId[i]>='a' && zId[i]<='z')
11031      && !(zId[i]>='A' && zId[i]<='Z')
11032     ){
11033       return 1;
11034     }
11035   }
11036   return 0;
11037 }
11038 
11039 /*
11040 ** This function appends an index column definition suitable for constraint
11041 ** pCons to the string passed as zIn and returns the result.
11042 */
11043 static char *idxAppendColDefn(
11044   int *pRc,                       /* IN/OUT: Error code */
11045   char *zIn,                      /* Column defn accumulated so far */
11046   IdxTable *pTab,                 /* Table index will be created on */
11047   IdxConstraint *pCons
11048 ){
11049   char *zRet = zIn;
11050   IdxColumn *p = &pTab->aCol[pCons->iCol];
11051   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
11052 
11053   if( idxIdentifierRequiresQuotes(p->zName) ){
11054     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
11055   }else{
11056     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
11057   }
11058 
11059   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
11060     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
11061       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
11062     }else{
11063       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
11064     }
11065   }
11066 
11067   if( pCons->bDesc ){
11068     zRet = idxAppendText(pRc, zRet, " DESC");
11069   }
11070   return zRet;
11071 }
11072 
11073 /*
11074 ** Search database dbm for an index compatible with the one idxCreateFromCons()
11075 ** would create from arguments pScan, pEq and pTail. If no error occurs and
11076 ** such an index is found, return non-zero. Or, if no such index is found,
11077 ** return zero.
11078 **
11079 ** If an error occurs, set *pRc to an SQLite error code and return zero.
11080 */
11081 static int idxFindCompatible(
11082   int *pRc,                       /* OUT: Error code */
11083   sqlite3* dbm,                   /* Database to search */
11084   IdxScan *pScan,                 /* Scan for table to search for index on */
11085   IdxConstraint *pEq,             /* List of == constraints */
11086   IdxConstraint *pTail            /* List of range constraints */
11087 ){
11088   const char *zTbl = pScan->pTab->zName;
11089   sqlite3_stmt *pIdxList = 0;
11090   IdxConstraint *pIter;
11091   int nEq = 0;                    /* Number of elements in pEq */
11092   int rc;
11093 
11094   /* Count the elements in list pEq */
11095   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
11096 
11097   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
11098   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
11099     int bMatch = 1;
11100     IdxConstraint *pT = pTail;
11101     sqlite3_stmt *pInfo = 0;
11102     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
11103     if( zIdx==0 ) continue;
11104 
11105     /* Zero the IdxConstraint.bFlag values in the pEq list */
11106     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
11107 
11108     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
11109     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
11110       int iIdx = sqlite3_column_int(pInfo, 0);
11111       int iCol = sqlite3_column_int(pInfo, 1);
11112       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
11113 
11114       if( iIdx<nEq ){
11115         for(pIter=pEq; pIter; pIter=pIter->pLink){
11116           if( pIter->bFlag ) continue;
11117           if( pIter->iCol!=iCol ) continue;
11118           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
11119           pIter->bFlag = 1;
11120           break;
11121         }
11122         if( pIter==0 ){
11123           bMatch = 0;
11124           break;
11125         }
11126       }else{
11127         if( pT ){
11128           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
11129             bMatch = 0;
11130             break;
11131           }
11132           pT = pT->pLink;
11133         }
11134       }
11135     }
11136     idxFinalize(&rc, pInfo);
11137 
11138     if( rc==SQLITE_OK && bMatch ){
11139       sqlite3_finalize(pIdxList);
11140       return 1;
11141     }
11142   }
11143   idxFinalize(&rc, pIdxList);
11144 
11145   *pRc = rc;
11146   return 0;
11147 }
11148 
11149 /* Callback for sqlite3_exec() with query with leading count(*) column.
11150  * The first argument is expected to be an int*, referent to be incremented
11151  * if that leading column is not exactly '0'.
11152  */
11153 static int countNonzeros(void* pCount, int nc,
11154                          char* azResults[], char* azColumns[]){
11155   (void)azColumns;  /* Suppress unused parameter warning */
11156   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
11157     *((int *)pCount) += 1;
11158   }
11159   return 0;
11160 }
11161 
11162 static int idxCreateFromCons(
11163   sqlite3expert *p,
11164   IdxScan *pScan,
11165   IdxConstraint *pEq,
11166   IdxConstraint *pTail
11167 ){
11168   sqlite3 *dbm = p->dbm;
11169   int rc = SQLITE_OK;
11170   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
11171     IdxTable *pTab = pScan->pTab;
11172     char *zCols = 0;
11173     char *zIdx = 0;
11174     IdxConstraint *pCons;
11175     unsigned int h = 0;
11176     const char *zFmt;
11177 
11178     for(pCons=pEq; pCons; pCons=pCons->pLink){
11179       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
11180     }
11181     for(pCons=pTail; pCons; pCons=pCons->pLink){
11182       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
11183     }
11184 
11185     if( rc==SQLITE_OK ){
11186       /* Hash the list of columns to come up with a name for the index */
11187       const char *zTable = pScan->pTab->zName;
11188       int quoteTable = idxIdentifierRequiresQuotes(zTable);
11189       char *zName = 0;          /* Index name */
11190       int collisions = 0;
11191       do{
11192         int i;
11193         char *zFind;
11194         for(i=0; zCols[i]; i++){
11195           h += ((h<<3) + zCols[i]);
11196         }
11197         sqlite3_free(zName);
11198         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
11199         if( zName==0 ) break;
11200         /* Is is unique among table, view and index names? */
11201         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
11202           " AND type in ('index','table','view')";
11203         zFind = sqlite3_mprintf(zFmt, zName);
11204         i = 0;
11205         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
11206         assert(rc==SQLITE_OK);
11207         sqlite3_free(zFind);
11208         if( i==0 ){
11209           collisions = 0;
11210           break;
11211         }
11212         ++collisions;
11213       }while( collisions<50 && zName!=0 );
11214       if( collisions ){
11215         /* This return means "Gave up trying to find a unique index name." */
11216         rc = SQLITE_BUSY_TIMEOUT;
11217       }else if( zName==0 ){
11218         rc = SQLITE_NOMEM;
11219       }else{
11220         if( quoteTable ){
11221           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
11222         }else{
11223           zFmt = "CREATE INDEX %s ON %s(%s)";
11224         }
11225         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
11226         if( !zIdx ){
11227           rc = SQLITE_NOMEM;
11228         }else{
11229           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
11230           if( rc!=SQLITE_OK ){
11231             rc = SQLITE_BUSY_TIMEOUT;
11232           }else{
11233             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
11234           }
11235         }
11236         sqlite3_free(zName);
11237         sqlite3_free(zIdx);
11238       }
11239     }
11240 
11241     sqlite3_free(zCols);
11242   }
11243   return rc;
11244 }
11245 
11246 /*
11247 ** Return true if list pList (linked by IdxConstraint.pLink) contains
11248 ** a constraint compatible with *p. Otherwise return false.
11249 */
11250 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
11251   IdxConstraint *pCmp;
11252   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
11253     if( p->iCol==pCmp->iCol ) return 1;
11254   }
11255   return 0;
11256 }
11257 
11258 static int idxCreateFromWhere(
11259   sqlite3expert *p,
11260   IdxScan *pScan,                 /* Create indexes for this scan */
11261   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
11262 ){
11263   IdxConstraint *p1 = 0;
11264   IdxConstraint *pCon;
11265   int rc;
11266 
11267   /* Gather up all the == constraints. */
11268   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
11269     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
11270       pCon->pLink = p1;
11271       p1 = pCon;
11272     }
11273   }
11274 
11275   /* Create an index using the == constraints collected above. And the
11276   ** range constraint/ORDER BY terms passed in by the caller, if any. */
11277   rc = idxCreateFromCons(p, pScan, p1, pTail);
11278 
11279   /* If no range/ORDER BY passed by the caller, create a version of the
11280   ** index for each range constraint.  */
11281   if( pTail==0 ){
11282     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
11283       assert( pCon->pLink==0 );
11284       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
11285         rc = idxCreateFromCons(p, pScan, p1, pCon);
11286       }
11287     }
11288   }
11289 
11290   return rc;
11291 }
11292 
11293 /*
11294 ** Create candidate indexes in database [dbm] based on the data in
11295 ** linked-list pScan.
11296 */
11297 static int idxCreateCandidates(sqlite3expert *p){
11298   int rc = SQLITE_OK;
11299   IdxScan *pIter;
11300 
11301   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
11302     rc = idxCreateFromWhere(p, pIter, 0);
11303     if( rc==SQLITE_OK && pIter->pOrder ){
11304       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
11305     }
11306   }
11307 
11308   return rc;
11309 }
11310 
11311 /*
11312 ** Free all elements of the linked list starting at pConstraint.
11313 */
11314 static void idxConstraintFree(IdxConstraint *pConstraint){
11315   IdxConstraint *pNext;
11316   IdxConstraint *p;
11317 
11318   for(p=pConstraint; p; p=pNext){
11319     pNext = p->pNext;
11320     sqlite3_free(p);
11321   }
11322 }
11323 
11324 /*
11325 ** Free all elements of the linked list starting from pScan up until pLast
11326 ** (pLast is not freed).
11327 */
11328 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
11329   IdxScan *p;
11330   IdxScan *pNext;
11331   for(p=pScan; p!=pLast; p=pNext){
11332     pNext = p->pNextScan;
11333     idxConstraintFree(p->pOrder);
11334     idxConstraintFree(p->pEq);
11335     idxConstraintFree(p->pRange);
11336     sqlite3_free(p);
11337   }
11338 }
11339 
11340 /*
11341 ** Free all elements of the linked list starting from pStatement up
11342 ** until pLast (pLast is not freed).
11343 */
11344 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
11345   IdxStatement *p;
11346   IdxStatement *pNext;
11347   for(p=pStatement; p!=pLast; p=pNext){
11348     pNext = p->pNext;
11349     sqlite3_free(p->zEQP);
11350     sqlite3_free(p->zIdx);
11351     sqlite3_free(p);
11352   }
11353 }
11354 
11355 /*
11356 ** Free the linked list of IdxTable objects starting at pTab.
11357 */
11358 static void idxTableFree(IdxTable *pTab){
11359   IdxTable *pIter;
11360   IdxTable *pNext;
11361   for(pIter=pTab; pIter; pIter=pNext){
11362     pNext = pIter->pNext;
11363     sqlite3_free(pIter);
11364   }
11365 }
11366 
11367 /*
11368 ** Free the linked list of IdxWrite objects starting at pTab.
11369 */
11370 static void idxWriteFree(IdxWrite *pTab){
11371   IdxWrite *pIter;
11372   IdxWrite *pNext;
11373   for(pIter=pTab; pIter; pIter=pNext){
11374     pNext = pIter->pNext;
11375     sqlite3_free(pIter);
11376   }
11377 }
11378 
11379 
11380 
11381 /*
11382 ** This function is called after candidate indexes have been created. It
11383 ** runs all the queries to see which indexes they prefer, and populates
11384 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
11385 */
11386 static int idxFindIndexes(
11387   sqlite3expert *p,
11388   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
11389 ){
11390   IdxStatement *pStmt;
11391   sqlite3 *dbm = p->dbm;
11392   int rc = SQLITE_OK;
11393 
11394   IdxHash hIdx;
11395   idxHashInit(&hIdx);
11396 
11397   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
11398     IdxHashEntry *pEntry;
11399     sqlite3_stmt *pExplain = 0;
11400     idxHashClear(&hIdx);
11401     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
11402         "EXPLAIN QUERY PLAN %s", pStmt->zSql
11403     );
11404     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
11405       /* int iId = sqlite3_column_int(pExplain, 0); */
11406       /* int iParent = sqlite3_column_int(pExplain, 1); */
11407       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
11408       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
11409       int nDetail;
11410       int i;
11411 
11412       if( !zDetail ) continue;
11413       nDetail = STRLEN(zDetail);
11414 
11415       for(i=0; i<nDetail; i++){
11416         const char *zIdx = 0;
11417         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
11418           zIdx = &zDetail[i+13];
11419         }else if( i+22<nDetail
11420             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
11421         ){
11422           zIdx = &zDetail[i+22];
11423         }
11424         if( zIdx ){
11425           const char *zSql;
11426           int nIdx = 0;
11427           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
11428             nIdx++;
11429           }
11430           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
11431           if( zSql ){
11432             idxHashAdd(&rc, &hIdx, zSql, 0);
11433             if( rc ) goto find_indexes_out;
11434           }
11435           break;
11436         }
11437       }
11438 
11439       if( zDetail[0]!='-' ){
11440         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
11441       }
11442     }
11443 
11444     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
11445       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
11446     }
11447 
11448     idxFinalize(&rc, pExplain);
11449   }
11450 
11451  find_indexes_out:
11452   idxHashClear(&hIdx);
11453   return rc;
11454 }
11455 
11456 static int idxAuthCallback(
11457   void *pCtx,
11458   int eOp,
11459   const char *z3,
11460   const char *z4,
11461   const char *zDb,
11462   const char *zTrigger
11463 ){
11464   int rc = SQLITE_OK;
11465   (void)z4;
11466   (void)zTrigger;
11467   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
11468     if( sqlite3_stricmp(zDb, "main")==0 ){
11469       sqlite3expert *p = (sqlite3expert*)pCtx;
11470       IdxTable *pTab;
11471       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
11472         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
11473       }
11474       if( pTab ){
11475         IdxWrite *pWrite;
11476         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
11477           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
11478         }
11479         if( pWrite==0 ){
11480           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
11481           if( rc==SQLITE_OK ){
11482             pWrite->pTab = pTab;
11483             pWrite->eOp = eOp;
11484             pWrite->pNext = p->pWrite;
11485             p->pWrite = pWrite;
11486           }
11487         }
11488       }
11489     }
11490   }
11491   return rc;
11492 }
11493 
11494 static int idxProcessOneTrigger(
11495   sqlite3expert *p,
11496   IdxWrite *pWrite,
11497   char **pzErr
11498 ){
11499   static const char *zInt = UNIQUE_TABLE_NAME;
11500   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
11501   IdxTable *pTab = pWrite->pTab;
11502   const char *zTab = pTab->zName;
11503   const char *zSql =
11504     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
11505     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
11506     "ORDER BY type;";
11507   sqlite3_stmt *pSelect = 0;
11508   int rc = SQLITE_OK;
11509   char *zWrite = 0;
11510 
11511   /* Create the table and its triggers in the temp schema */
11512   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
11513   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
11514     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
11515     if( zCreate==0 ) continue;
11516     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
11517   }
11518   idxFinalize(&rc, pSelect);
11519 
11520   /* Rename the table in the temp schema to zInt */
11521   if( rc==SQLITE_OK ){
11522     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
11523     if( z==0 ){
11524       rc = SQLITE_NOMEM;
11525     }else{
11526       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
11527       sqlite3_free(z);
11528     }
11529   }
11530 
11531   switch( pWrite->eOp ){
11532     case SQLITE_INSERT: {
11533       int i;
11534       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
11535       for(i=0; i<pTab->nCol; i++){
11536         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
11537       }
11538       zWrite = idxAppendText(&rc, zWrite, ")");
11539       break;
11540     }
11541     case SQLITE_UPDATE: {
11542       int i;
11543       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
11544       for(i=0; i<pTab->nCol; i++){
11545         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
11546             pTab->aCol[i].zName
11547         );
11548       }
11549       break;
11550     }
11551     default: {
11552       assert( pWrite->eOp==SQLITE_DELETE );
11553       if( rc==SQLITE_OK ){
11554         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
11555         if( zWrite==0 ) rc = SQLITE_NOMEM;
11556       }
11557     }
11558   }
11559 
11560   if( rc==SQLITE_OK ){
11561     sqlite3_stmt *pX = 0;
11562     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
11563     idxFinalize(&rc, pX);
11564     if( rc!=SQLITE_OK ){
11565       idxDatabaseError(p->dbv, pzErr);
11566     }
11567   }
11568   sqlite3_free(zWrite);
11569 
11570   if( rc==SQLITE_OK ){
11571     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
11572   }
11573 
11574   return rc;
11575 }
11576 
11577 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
11578   int rc = SQLITE_OK;
11579   IdxWrite *pEnd = 0;
11580   IdxWrite *pFirst = p->pWrite;
11581 
11582   while( rc==SQLITE_OK && pFirst!=pEnd ){
11583     IdxWrite *pIter;
11584     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
11585       rc = idxProcessOneTrigger(p, pIter, pzErr);
11586     }
11587     pEnd = pFirst;
11588     pFirst = p->pWrite;
11589   }
11590 
11591   return rc;
11592 }
11593 
11594 
11595 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
11596   int rc = idxRegisterVtab(p);
11597   sqlite3_stmt *pSchema = 0;
11598 
11599   /* For each table in the main db schema:
11600   **
11601   **   1) Add an entry to the p->pTable list, and
11602   **   2) Create the equivalent virtual table in dbv.
11603   */
11604   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
11605       "SELECT type, name, sql, 1 FROM sqlite_schema "
11606       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
11607       " UNION ALL "
11608       "SELECT type, name, sql, 2 FROM sqlite_schema "
11609       "WHERE type = 'trigger'"
11610       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
11611       "ORDER BY 4, 1"
11612   );
11613   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
11614     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
11615     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
11616     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
11617 
11618     if( zType==0 || zName==0 ) continue;
11619     if( zType[0]=='v' || zType[1]=='r' ){
11620       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
11621     }else{
11622       IdxTable *pTab;
11623       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
11624       if( rc==SQLITE_OK ){
11625         int i;
11626         char *zInner = 0;
11627         char *zOuter = 0;
11628         pTab->pNext = p->pTable;
11629         p->pTable = pTab;
11630 
11631         /* The statement the vtab will pass to sqlite3_declare_vtab() */
11632         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
11633         for(i=0; i<pTab->nCol; i++){
11634           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
11635               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
11636           );
11637         }
11638         zInner = idxAppendText(&rc, zInner, ")");
11639 
11640         /* The CVT statement to create the vtab */
11641         zOuter = idxAppendText(&rc, 0,
11642             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
11643         );
11644         if( rc==SQLITE_OK ){
11645           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
11646         }
11647         sqlite3_free(zInner);
11648         sqlite3_free(zOuter);
11649       }
11650     }
11651   }
11652   idxFinalize(&rc, pSchema);
11653   return rc;
11654 }
11655 
11656 struct IdxSampleCtx {
11657   int iTarget;
11658   double target;                  /* Target nRet/nRow value */
11659   double nRow;                    /* Number of rows seen */
11660   double nRet;                    /* Number of rows returned */
11661 };
11662 
11663 static void idxSampleFunc(
11664   sqlite3_context *pCtx,
11665   int argc,
11666   sqlite3_value **argv
11667 ){
11668   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
11669   int bRet;
11670 
11671   (void)argv;
11672   assert( argc==0 );
11673   if( p->nRow==0.0 ){
11674     bRet = 1;
11675   }else{
11676     bRet = (p->nRet / p->nRow) <= p->target;
11677     if( bRet==0 ){
11678       unsigned short rnd;
11679       sqlite3_randomness(2, (void*)&rnd);
11680       bRet = ((int)rnd % 100) <= p->iTarget;
11681     }
11682   }
11683 
11684   sqlite3_result_int(pCtx, bRet);
11685   p->nRow += 1.0;
11686   p->nRet += (double)bRet;
11687 }
11688 
11689 struct IdxRemCtx {
11690   int nSlot;
11691   struct IdxRemSlot {
11692     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
11693     i64 iVal;                     /* SQLITE_INTEGER value */
11694     double rVal;                  /* SQLITE_FLOAT value */
11695     int nByte;                    /* Bytes of space allocated at z */
11696     int n;                        /* Size of buffer z */
11697     char *z;                      /* SQLITE_TEXT/BLOB value */
11698   } aSlot[1];
11699 };
11700 
11701 /*
11702 ** Implementation of scalar function rem().
11703 */
11704 static void idxRemFunc(
11705   sqlite3_context *pCtx,
11706   int argc,
11707   sqlite3_value **argv
11708 ){
11709   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
11710   struct IdxRemSlot *pSlot;
11711   int iSlot;
11712   assert( argc==2 );
11713 
11714   iSlot = sqlite3_value_int(argv[0]);
11715   assert( iSlot<=p->nSlot );
11716   pSlot = &p->aSlot[iSlot];
11717 
11718   switch( pSlot->eType ){
11719     case SQLITE_NULL:
11720       /* no-op */
11721       break;
11722 
11723     case SQLITE_INTEGER:
11724       sqlite3_result_int64(pCtx, pSlot->iVal);
11725       break;
11726 
11727     case SQLITE_FLOAT:
11728       sqlite3_result_double(pCtx, pSlot->rVal);
11729       break;
11730 
11731     case SQLITE_BLOB:
11732       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
11733       break;
11734 
11735     case SQLITE_TEXT:
11736       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
11737       break;
11738   }
11739 
11740   pSlot->eType = sqlite3_value_type(argv[1]);
11741   switch( pSlot->eType ){
11742     case SQLITE_NULL:
11743       /* no-op */
11744       break;
11745 
11746     case SQLITE_INTEGER:
11747       pSlot->iVal = sqlite3_value_int64(argv[1]);
11748       break;
11749 
11750     case SQLITE_FLOAT:
11751       pSlot->rVal = sqlite3_value_double(argv[1]);
11752       break;
11753 
11754     case SQLITE_BLOB:
11755     case SQLITE_TEXT: {
11756       int nByte = sqlite3_value_bytes(argv[1]);
11757       const void *pData = 0;
11758       if( nByte>pSlot->nByte ){
11759         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
11760         if( zNew==0 ){
11761           sqlite3_result_error_nomem(pCtx);
11762           return;
11763         }
11764         pSlot->nByte = nByte*2;
11765         pSlot->z = zNew;
11766       }
11767       pSlot->n = nByte;
11768       if( pSlot->eType==SQLITE_BLOB ){
11769         pData = sqlite3_value_blob(argv[1]);
11770         if( pData ) memcpy(pSlot->z, pData, nByte);
11771       }else{
11772         pData = sqlite3_value_text(argv[1]);
11773         memcpy(pSlot->z, pData, nByte);
11774       }
11775       break;
11776     }
11777   }
11778 }
11779 
11780 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
11781   int rc = SQLITE_OK;
11782   const char *zMax =
11783     "SELECT max(i.seqno) FROM "
11784     "  sqlite_schema AS s, "
11785     "  pragma_index_list(s.name) AS l, "
11786     "  pragma_index_info(l.name) AS i "
11787     "WHERE s.type = 'table'";
11788   sqlite3_stmt *pMax = 0;
11789 
11790   *pnMax = 0;
11791   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
11792   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
11793     *pnMax = sqlite3_column_int(pMax, 0) + 1;
11794   }
11795   idxFinalize(&rc, pMax);
11796 
11797   return rc;
11798 }
11799 
11800 static int idxPopulateOneStat1(
11801   sqlite3expert *p,
11802   sqlite3_stmt *pIndexXInfo,
11803   sqlite3_stmt *pWriteStat,
11804   const char *zTab,
11805   const char *zIdx,
11806   char **pzErr
11807 ){
11808   char *zCols = 0;
11809   char *zOrder = 0;
11810   char *zQuery = 0;
11811   int nCol = 0;
11812   int i;
11813   sqlite3_stmt *pQuery = 0;
11814   int *aStat = 0;
11815   int rc = SQLITE_OK;
11816 
11817   assert( p->iSample>0 );
11818 
11819   /* Formulate the query text */
11820   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
11821   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
11822     const char *zComma = zCols==0 ? "" : ", ";
11823     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
11824     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
11825     zCols = idxAppendText(&rc, zCols,
11826         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
11827     );
11828     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
11829   }
11830   sqlite3_reset(pIndexXInfo);
11831   if( rc==SQLITE_OK ){
11832     if( p->iSample==100 ){
11833       zQuery = sqlite3_mprintf(
11834           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
11835       );
11836     }else{
11837       zQuery = sqlite3_mprintf(
11838           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
11839       );
11840     }
11841   }
11842   sqlite3_free(zCols);
11843   sqlite3_free(zOrder);
11844 
11845   /* Formulate the query text */
11846   if( rc==SQLITE_OK ){
11847     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
11848     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
11849   }
11850   sqlite3_free(zQuery);
11851 
11852   if( rc==SQLITE_OK ){
11853     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
11854   }
11855   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
11856     IdxHashEntry *pEntry;
11857     char *zStat = 0;
11858     for(i=0; i<=nCol; i++) aStat[i] = 1;
11859     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
11860       aStat[0]++;
11861       for(i=0; i<nCol; i++){
11862         if( sqlite3_column_int(pQuery, i)==0 ) break;
11863       }
11864       for(/*no-op*/; i<nCol; i++){
11865         aStat[i+1]++;
11866       }
11867     }
11868 
11869     if( rc==SQLITE_OK ){
11870       int s0 = aStat[0];
11871       zStat = sqlite3_mprintf("%d", s0);
11872       if( zStat==0 ) rc = SQLITE_NOMEM;
11873       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
11874         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
11875       }
11876     }
11877 
11878     if( rc==SQLITE_OK ){
11879       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
11880       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
11881       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
11882       sqlite3_step(pWriteStat);
11883       rc = sqlite3_reset(pWriteStat);
11884     }
11885 
11886     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
11887     if( pEntry ){
11888       assert( pEntry->zVal2==0 );
11889       pEntry->zVal2 = zStat;
11890     }else{
11891       sqlite3_free(zStat);
11892     }
11893   }
11894   sqlite3_free(aStat);
11895   idxFinalize(&rc, pQuery);
11896 
11897   return rc;
11898 }
11899 
11900 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
11901   int rc;
11902   char *zSql;
11903 
11904   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
11905   if( rc!=SQLITE_OK ) return rc;
11906 
11907   zSql = sqlite3_mprintf(
11908       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
11909   );
11910   if( zSql==0 ) return SQLITE_NOMEM;
11911   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
11912   sqlite3_free(zSql);
11913 
11914   return rc;
11915 }
11916 
11917 /*
11918 ** This function is called as part of sqlite3_expert_analyze(). Candidate
11919 ** indexes have already been created in database sqlite3expert.dbm, this
11920 ** function populates sqlite_stat1 table in the same database.
11921 **
11922 ** The stat1 data is generated by querying the
11923 */
11924 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
11925   int rc = SQLITE_OK;
11926   int nMax =0;
11927   struct IdxRemCtx *pCtx = 0;
11928   struct IdxSampleCtx samplectx;
11929   int i;
11930   i64 iPrev = -100000;
11931   sqlite3_stmt *pAllIndex = 0;
11932   sqlite3_stmt *pIndexXInfo = 0;
11933   sqlite3_stmt *pWrite = 0;
11934 
11935   const char *zAllIndex =
11936     "SELECT s.rowid, s.name, l.name FROM "
11937     "  sqlite_schema AS s, "
11938     "  pragma_index_list(s.name) AS l "
11939     "WHERE s.type = 'table'";
11940   const char *zIndexXInfo =
11941     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
11942   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
11943 
11944   /* If iSample==0, no sqlite_stat1 data is required. */
11945   if( p->iSample==0 ) return SQLITE_OK;
11946 
11947   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
11948   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
11949 
11950   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
11951 
11952   if( rc==SQLITE_OK ){
11953     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
11954     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
11955   }
11956 
11957   if( rc==SQLITE_OK ){
11958     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
11959     rc = sqlite3_create_function(
11960         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
11961     );
11962   }
11963   if( rc==SQLITE_OK ){
11964     rc = sqlite3_create_function(
11965         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
11966     );
11967   }
11968 
11969   if( rc==SQLITE_OK ){
11970     pCtx->nSlot = nMax+1;
11971     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
11972   }
11973   if( rc==SQLITE_OK ){
11974     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
11975   }
11976   if( rc==SQLITE_OK ){
11977     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
11978   }
11979 
11980   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
11981     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
11982     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
11983     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
11984     if( zTab==0 || zIdx==0 ) continue;
11985     if( p->iSample<100 && iPrev!=iRowid ){
11986       samplectx.target = (double)p->iSample / 100.0;
11987       samplectx.iTarget = p->iSample;
11988       samplectx.nRow = 0.0;
11989       samplectx.nRet = 0.0;
11990       rc = idxBuildSampleTable(p, zTab);
11991       if( rc!=SQLITE_OK ) break;
11992     }
11993     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
11994     iPrev = iRowid;
11995   }
11996   if( rc==SQLITE_OK && p->iSample<100 ){
11997     rc = sqlite3_exec(p->dbv,
11998         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
11999     );
12000   }
12001 
12002   idxFinalize(&rc, pAllIndex);
12003   idxFinalize(&rc, pIndexXInfo);
12004   idxFinalize(&rc, pWrite);
12005 
12006   if( pCtx ){
12007     for(i=0; i<pCtx->nSlot; i++){
12008       sqlite3_free(pCtx->aSlot[i].z);
12009     }
12010     sqlite3_free(pCtx);
12011   }
12012 
12013   if( rc==SQLITE_OK ){
12014     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
12015   }
12016 
12017   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
12018   return rc;
12019 }
12020 
12021 /*
12022 ** Allocate a new sqlite3expert object.
12023 */
12024 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
12025   int rc = SQLITE_OK;
12026   sqlite3expert *pNew;
12027 
12028   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
12029 
12030   /* Open two in-memory databases to work with. The "vtab database" (dbv)
12031   ** will contain a virtual table corresponding to each real table in
12032   ** the user database schema, and a copy of each view. It is used to
12033   ** collect information regarding the WHERE, ORDER BY and other clauses
12034   ** of the user's query.
12035   */
12036   if( rc==SQLITE_OK ){
12037     pNew->db = db;
12038     pNew->iSample = 100;
12039     rc = sqlite3_open(":memory:", &pNew->dbv);
12040   }
12041   if( rc==SQLITE_OK ){
12042     rc = sqlite3_open(":memory:", &pNew->dbm);
12043     if( rc==SQLITE_OK ){
12044       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
12045     }
12046   }
12047 
12048 
12049   /* Copy the entire schema of database [db] into [dbm]. */
12050   if( rc==SQLITE_OK ){
12051     sqlite3_stmt *pSql = 0;
12052     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
12053         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
12054         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
12055     );
12056     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12057       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
12058       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
12059     }
12060     idxFinalize(&rc, pSql);
12061   }
12062 
12063   /* Create the vtab schema */
12064   if( rc==SQLITE_OK ){
12065     rc = idxCreateVtabSchema(pNew, pzErrmsg);
12066   }
12067 
12068   /* Register the auth callback with dbv */
12069   if( rc==SQLITE_OK ){
12070     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
12071   }
12072 
12073   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
12074   ** return the new sqlite3expert handle.  */
12075   if( rc!=SQLITE_OK ){
12076     sqlite3_expert_destroy(pNew);
12077     pNew = 0;
12078   }
12079   return pNew;
12080 }
12081 
12082 /*
12083 ** Configure an sqlite3expert object.
12084 */
12085 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
12086   int rc = SQLITE_OK;
12087   va_list ap;
12088   va_start(ap, op);
12089   switch( op ){
12090     case EXPERT_CONFIG_SAMPLE: {
12091       int iVal = va_arg(ap, int);
12092       if( iVal<0 ) iVal = 0;
12093       if( iVal>100 ) iVal = 100;
12094       p->iSample = iVal;
12095       break;
12096     }
12097     default:
12098       rc = SQLITE_NOTFOUND;
12099       break;
12100   }
12101 
12102   va_end(ap);
12103   return rc;
12104 }
12105 
12106 /*
12107 ** Add an SQL statement to the analysis.
12108 */
12109 int sqlite3_expert_sql(
12110   sqlite3expert *p,               /* From sqlite3_expert_new() */
12111   const char *zSql,               /* SQL statement to add */
12112   char **pzErr                    /* OUT: Error message (if any) */
12113 ){
12114   IdxScan *pScanOrig = p->pScan;
12115   IdxStatement *pStmtOrig = p->pStatement;
12116   int rc = SQLITE_OK;
12117   const char *zStmt = zSql;
12118 
12119   if( p->bRun ) return SQLITE_MISUSE;
12120 
12121   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
12122     sqlite3_stmt *pStmt = 0;
12123     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
12124     if( rc==SQLITE_OK ){
12125       if( pStmt ){
12126         IdxStatement *pNew;
12127         const char *z = sqlite3_sql(pStmt);
12128         int n = STRLEN(z);
12129         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
12130         if( rc==SQLITE_OK ){
12131           pNew->zSql = (char*)&pNew[1];
12132           memcpy(pNew->zSql, z, n+1);
12133           pNew->pNext = p->pStatement;
12134           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
12135           p->pStatement = pNew;
12136         }
12137         sqlite3_finalize(pStmt);
12138       }
12139     }else{
12140       idxDatabaseError(p->dbv, pzErr);
12141     }
12142   }
12143 
12144   if( rc!=SQLITE_OK ){
12145     idxScanFree(p->pScan, pScanOrig);
12146     idxStatementFree(p->pStatement, pStmtOrig);
12147     p->pScan = pScanOrig;
12148     p->pStatement = pStmtOrig;
12149   }
12150 
12151   return rc;
12152 }
12153 
12154 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
12155   int rc;
12156   IdxHashEntry *pEntry;
12157 
12158   /* Do trigger processing to collect any extra IdxScan structures */
12159   rc = idxProcessTriggers(p, pzErr);
12160 
12161   /* Create candidate indexes within the in-memory database file */
12162   if( rc==SQLITE_OK ){
12163     rc = idxCreateCandidates(p);
12164   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
12165     if( pzErr )
12166       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
12167     return rc;
12168   }
12169 
12170   /* Generate the stat1 data */
12171   if( rc==SQLITE_OK ){
12172     rc = idxPopulateStat1(p, pzErr);
12173   }
12174 
12175   /* Formulate the EXPERT_REPORT_CANDIDATES text */
12176   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
12177     p->zCandidates = idxAppendText(&rc, p->zCandidates,
12178         "%s;%s%s\n", pEntry->zVal,
12179         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
12180     );
12181   }
12182 
12183   /* Figure out which of the candidate indexes are preferred by the query
12184   ** planner and report the results to the user.  */
12185   if( rc==SQLITE_OK ){
12186     rc = idxFindIndexes(p, pzErr);
12187   }
12188 
12189   if( rc==SQLITE_OK ){
12190     p->bRun = 1;
12191   }
12192   return rc;
12193 }
12194 
12195 /*
12196 ** Return the total number of statements that have been added to this
12197 ** sqlite3expert using sqlite3_expert_sql().
12198 */
12199 int sqlite3_expert_count(sqlite3expert *p){
12200   int nRet = 0;
12201   if( p->pStatement ) nRet = p->pStatement->iId+1;
12202   return nRet;
12203 }
12204 
12205 /*
12206 ** Return a component of the report.
12207 */
12208 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
12209   const char *zRet = 0;
12210   IdxStatement *pStmt;
12211 
12212   if( p->bRun==0 ) return 0;
12213   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
12214   switch( eReport ){
12215     case EXPERT_REPORT_SQL:
12216       if( pStmt ) zRet = pStmt->zSql;
12217       break;
12218     case EXPERT_REPORT_INDEXES:
12219       if( pStmt ) zRet = pStmt->zIdx;
12220       break;
12221     case EXPERT_REPORT_PLAN:
12222       if( pStmt ) zRet = pStmt->zEQP;
12223       break;
12224     case EXPERT_REPORT_CANDIDATES:
12225       zRet = p->zCandidates;
12226       break;
12227   }
12228   return zRet;
12229 }
12230 
12231 /*
12232 ** Free an sqlite3expert object.
12233 */
12234 void sqlite3_expert_destroy(sqlite3expert *p){
12235   if( p ){
12236     sqlite3_close(p->dbm);
12237     sqlite3_close(p->dbv);
12238     idxScanFree(p->pScan, 0);
12239     idxStatementFree(p->pStatement, 0);
12240     idxTableFree(p->pTable);
12241     idxWriteFree(p->pWrite);
12242     idxHashClear(&p->hIdx);
12243     sqlite3_free(p->zCandidates);
12244     sqlite3_free(p);
12245   }
12246 }
12247 
12248 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
12249 
12250 /************************* End ../ext/expert/sqlite3expert.c ********************/
12251 
12252 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
12253 #define SQLITE_SHELL_HAVE_RECOVER 1
12254 #else
12255 #define SQLITE_SHELL_HAVE_RECOVER 0
12256 #endif
12257 #if SQLITE_SHELL_HAVE_RECOVER
12258 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
12259 /*
12260 ** 2022-08-27
12261 **
12262 ** The author disclaims copyright to this source code.  In place of
12263 ** a legal notice, here is a blessing:
12264 **
12265 **    May you do good and not evil.
12266 **    May you find forgiveness for yourself and forgive others.
12267 **    May you share freely, never taking more than you give.
12268 **
12269 *************************************************************************
12270 **
12271 ** This file contains the public interface to the "recover" extension -
12272 ** an SQLite extension designed to recover data from corrupted database
12273 ** files.
12274 */
12275 
12276 /*
12277 ** OVERVIEW:
12278 **
12279 ** To use the API to recover data from a corrupted database, an
12280 ** application:
12281 **
12282 **   1) Creates an sqlite3_recover handle by calling either
12283 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
12284 **
12285 **   2) Configures the new handle using one or more calls to
12286 **      sqlite3_recover_config().
12287 **
12288 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
12289 **      the handle until it returns something other than SQLITE_OK. If it
12290 **      returns SQLITE_DONE, then the recovery operation completed without
12291 **      error. If it returns some other non-SQLITE_OK value, then an error
12292 **      has occurred.
12293 **
12294 **   4) Retrieves any error code and English language error message using the
12295 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
12296 **      respectively.
12297 **
12298 **   5) Destroys the sqlite3_recover handle and frees all resources
12299 **      using sqlite3_recover_finish().
12300 **
12301 ** The application may abandon the recovery operation at any point
12302 ** before it is finished by passing the sqlite3_recover handle to
12303 ** sqlite3_recover_finish(). This is not an error, but the final state
12304 ** of the output database, or the results of running the partial script
12305 ** delivered to the SQL callback, are undefined.
12306 */
12307 
12308 #ifndef _SQLITE_RECOVER_H
12309 #define _SQLITE_RECOVER_H
12310 
12311 /* #include "sqlite3.h" */
12312 
12313 #ifdef __cplusplus
12314 extern "C" {
12315 #endif
12316 
12317 /*
12318 ** An instance of the sqlite3_recover object represents a recovery
12319 ** operation in progress.
12320 **
12321 ** Constructors:
12322 **
12323 **    sqlite3_recover_init()
12324 **    sqlite3_recover_init_sql()
12325 **
12326 ** Destructor:
12327 **
12328 **    sqlite3_recover_finish()
12329 **
12330 ** Methods:
12331 **
12332 **    sqlite3_recover_config()
12333 **    sqlite3_recover_errcode()
12334 **    sqlite3_recover_errmsg()
12335 **    sqlite3_recover_run()
12336 **    sqlite3_recover_step()
12337 */
12338 typedef struct sqlite3_recover sqlite3_recover;
12339 
12340 /*
12341 ** These two APIs attempt to create and return a new sqlite3_recover object.
12342 ** In both cases the first two arguments identify the (possibly
12343 ** corrupt) database to recover data from. The first argument is an open
12344 ** database handle and the second the name of a database attached to that
12345 ** handle (i.e. "main", "temp" or the name of an attached database).
12346 **
12347 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
12348 ** handle, then data is recovered into a new database, identified by
12349 ** string parameter zUri. zUri may be an absolute or relative file path,
12350 ** or may be an SQLite URI. If the identified database file already exists,
12351 ** it is overwritten.
12352 **
12353 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
12354 ** be returned to the user as a series of SQL statements. Executing these
12355 ** SQL statements results in the same database as would have been created
12356 ** had sqlite3_recover_init() been used. For each SQL statement in the
12357 ** output, the callback function passed as the third argument (xSql) is
12358 ** invoked once. The first parameter is a passed a copy of the fourth argument
12359 ** to this function (pCtx) as its first parameter, and a pointer to a
12360 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
12361 ** the second. If the xSql callback returns any value other than SQLITE_OK,
12362 ** then processing is immediately abandoned and the value returned used as
12363 ** the recover handle error code (see below).
12364 **
12365 ** If an out-of-memory error occurs, NULL may be returned instead of
12366 ** a valid handle. In all other cases, it is the responsibility of the
12367 ** application to avoid resource leaks by ensuring that
12368 ** sqlite3_recover_finish() is called on all allocated handles.
12369 */
12370 sqlite3_recover *sqlite3_recover_init(
12371   sqlite3* db,
12372   const char *zDb,
12373   const char *zUri
12374 );
12375 sqlite3_recover *sqlite3_recover_init_sql(
12376   sqlite3* db,
12377   const char *zDb,
12378   int (*xSql)(void*, const char*),
12379   void *pCtx
12380 );
12381 
12382 /*
12383 ** Configure an sqlite3_recover object that has just been created using
12384 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
12385 ** may only be called before the first call to sqlite3_recover_step()
12386 ** or sqlite3_recover_run() on the object.
12387 **
12388 ** The second argument passed to this function must be one of the
12389 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
12390 ** depend on the specific SQLITE_RECOVER_* symbol in use.
12391 **
12392 ** SQLITE_OK is returned if the configuration operation was successful,
12393 ** or an SQLite error code otherwise.
12394 */
12395 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
12396 
12397 /*
12398 ** SQLITE_RECOVER_LOST_AND_FOUND:
12399 **   The pArg argument points to a string buffer containing the name
12400 **   of a "lost-and-found" table in the output database, or NULL. If
12401 **   the argument is non-NULL and the database contains seemingly
12402 **   valid pages that cannot be associated with any table in the
12403 **   recovered part of the schema, data is extracted from these
12404 **   pages to add to the lost-and-found table.
12405 **
12406 ** SQLITE_RECOVER_FREELIST_CORRUPT:
12407 **   The pArg value must actually be a pointer to a value of type
12408 **   int containing value 0 or 1 cast as a (void*). If this option is set
12409 **   (argument is 1) and a lost-and-found table has been configured using
12410 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
12411 **   corrupt and an attempt is made to recover records from pages that
12412 **   appear to be linked into the freelist. Otherwise, pages on the freelist
12413 **   are ignored. Setting this option can recover more data from the
12414 **   database, but often ends up "recovering" deleted records. The default
12415 **   value is 0 (clear).
12416 **
12417 ** SQLITE_RECOVER_ROWIDS:
12418 **   The pArg value must actually be a pointer to a value of type
12419 **   int containing value 0 or 1 cast as a (void*). If this option is set
12420 **   (argument is 1), then an attempt is made to recover rowid values
12421 **   that are not also INTEGER PRIMARY KEY values. If this option is
12422 **   clear, then new rowids are assigned to all recovered rows. The
12423 **   default value is 1 (set).
12424 **
12425 ** SQLITE_RECOVER_SLOWINDEXES:
12426 **   The pArg value must actually be a pointer to a value of type
12427 **   int containing value 0 or 1 cast as a (void*). If this option is clear
12428 **   (argument is 0), then when creating an output database, the recover
12429 **   module creates and populates non-UNIQUE indexes right at the end of the
12430 **   recovery operation - after all recoverable data has been inserted
12431 **   into the new database. This is faster overall, but means that the
12432 **   final call to sqlite3_recover_step() for a recovery operation may
12433 **   be need to create a large number of indexes, which may be very slow.
12434 **
12435 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
12436 **   are created in the output database before it is populated with
12437 **   recovered data. This is slower overall, but avoids the slow call
12438 **   to sqlite3_recover_step() at the end of the recovery operation.
12439 **
12440 **   The default option value is 0.
12441 */
12442 #define SQLITE_RECOVER_LOST_AND_FOUND   1
12443 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
12444 #define SQLITE_RECOVER_ROWIDS           3
12445 #define SQLITE_RECOVER_SLOWINDEXES      4
12446 
12447 /*
12448 ** Perform a unit of work towards the recovery operation. This function
12449 ** must normally be called multiple times to complete database recovery.
12450 **
12451 ** If no error occurs but the recovery operation is not completed, this
12452 ** function returns SQLITE_OK. If recovery has been completed successfully
12453 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
12454 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
12455 ** considered an error if some or all of the data cannot be recovered
12456 ** due to database corruption.
12457 **
12458 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
12459 ** all further such calls on the same recover handle are no-ops that return
12460 ** the same non-SQLITE_OK value.
12461 */
12462 int sqlite3_recover_step(sqlite3_recover*);
12463 
12464 /*
12465 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
12466 ** or an SQLite error code otherwise. Calling this function is the same
12467 ** as executing:
12468 **
12469 **     while( SQLITE_OK==sqlite3_recover_step(p) );
12470 **     return sqlite3_recover_errcode(p);
12471 */
12472 int sqlite3_recover_run(sqlite3_recover*);
12473 
12474 /*
12475 ** If an error has been encountered during a prior call to
12476 ** sqlite3_recover_step(), then this function attempts to return a
12477 ** pointer to a buffer containing an English language explanation of
12478 ** the error. If no error message is available, or if an out-of memory
12479 ** error occurs while attempting to allocate a buffer in which to format
12480 ** the error message, NULL is returned.
12481 **
12482 ** The returned buffer remains valid until the sqlite3_recover handle is
12483 ** destroyed using sqlite3_recover_finish().
12484 */
12485 const char *sqlite3_recover_errmsg(sqlite3_recover*);
12486 
12487 /*
12488 ** If this function is called on an sqlite3_recover handle after
12489 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
12490 */
12491 int sqlite3_recover_errcode(sqlite3_recover*);
12492 
12493 /*
12494 ** Clean up a recovery object created by a call to sqlite3_recover_init().
12495 ** The results of using a recovery object with any API after it has been
12496 ** passed to this function are undefined.
12497 **
12498 ** This function returns the same value as sqlite3_recover_errcode().
12499 */
12500 int sqlite3_recover_finish(sqlite3_recover*);
12501 
12502 
12503 #ifdef __cplusplus
12504 }  /* end of the 'extern "C"' block */
12505 #endif
12506 
12507 #endif /* ifndef _SQLITE_RECOVER_H */
12508 
12509 /************************* End ../ext/recover/sqlite3recover.h ********************/
12510 # ifndef SQLITE_HAVE_SQLITE3R
12511 /************************* Begin ../ext/recover/dbdata.c ******************/
12512 /*
12513 ** 2019-04-17
12514 **
12515 ** The author disclaims copyright to this source code.  In place of
12516 ** a legal notice, here is a blessing:
12517 **
12518 **    May you do good and not evil.
12519 **    May you find forgiveness for yourself and forgive others.
12520 **    May you share freely, never taking more than you give.
12521 **
12522 ******************************************************************************
12523 **
12524 ** This file contains an implementation of two eponymous virtual tables,
12525 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
12526 ** "sqlite_dbpage" eponymous virtual table be available.
12527 **
12528 ** SQLITE_DBDATA:
12529 **   sqlite_dbdata is used to extract data directly from a database b-tree
12530 **   page and its associated overflow pages, bypassing the b-tree layer.
12531 **   The table schema is equivalent to:
12532 **
12533 **     CREATE TABLE sqlite_dbdata(
12534 **       pgno INTEGER,
12535 **       cell INTEGER,
12536 **       field INTEGER,
12537 **       value ANY,
12538 **       schema TEXT HIDDEN
12539 **     );
12540 **
12541 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
12542 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
12543 **   "schema".
12544 **
12545 **   Each page of the database is inspected. If it cannot be interpreted as
12546 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
12547 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
12548 **   table contains one row for each field in the record associated with
12549 **   each cell on the page. For intkey b-trees, the key value is stored in
12550 **   field -1.
12551 **
12552 **   For example, for the database:
12553 **
12554 **     CREATE TABLE t1(a, b);     -- root page is page 2
12555 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
12556 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
12557 **
12558 **   the sqlite_dbdata table contains, as well as from entries related to
12559 **   page 1, content equivalent to:
12560 **
12561 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
12562 **         (2, 0, -1, 5     ),
12563 **         (2, 0,  0, 'v'   ),
12564 **         (2, 0,  1, 'five'),
12565 **         (2, 1, -1, 10    ),
12566 **         (2, 1,  0, 'x'   ),
12567 **         (2, 1,  1, 'ten' );
12568 **
12569 **   If database corruption is encountered, this module does not report an
12570 **   error. Instead, it attempts to extract as much data as possible and
12571 **   ignores the corruption.
12572 **
12573 ** SQLITE_DBPTR:
12574 **   The sqlite_dbptr table has the following schema:
12575 **
12576 **     CREATE TABLE sqlite_dbptr(
12577 **       pgno INTEGER,
12578 **       child INTEGER,
12579 **       schema TEXT HIDDEN
12580 **     );
12581 **
12582 **   It contains one entry for each b-tree pointer between a parent and
12583 **   child page in the database.
12584 */
12585 
12586 #if !defined(SQLITEINT_H)
12587 /* #include "sqlite3ext.h" */
12588 
12589 /* typedef unsigned char u8; */
12590 /* typedef unsigned int u32; */
12591 
12592 #endif
12593 SQLITE_EXTENSION_INIT1
12594 #include <string.h>
12595 #include <assert.h>
12596 
12597 #ifndef SQLITE_OMIT_VIRTUALTABLE
12598 
12599 #define DBDATA_PADDING_BYTES 100
12600 
12601 typedef struct DbdataTable DbdataTable;
12602 typedef struct DbdataCursor DbdataCursor;
12603 
12604 /* Cursor object */
12605 struct DbdataCursor {
12606   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
12607   sqlite3_stmt *pStmt;            /* For fetching database pages */
12608 
12609   int iPgno;                      /* Current page number */
12610   u8 *aPage;                      /* Buffer containing page */
12611   int nPage;                      /* Size of aPage[] in bytes */
12612   int nCell;                      /* Number of cells on aPage[] */
12613   int iCell;                      /* Current cell number */
12614   int bOnePage;                   /* True to stop after one page */
12615   int szDb;
12616   sqlite3_int64 iRowid;
12617 
12618   /* Only for the sqlite_dbdata table */
12619   u8 *pRec;                       /* Buffer containing current record */
12620   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
12621   sqlite3_int64 nHdr;             /* Size of header in bytes */
12622   int iField;                     /* Current field number */
12623   u8 *pHdrPtr;
12624   u8 *pPtr;
12625   u32 enc;                        /* Text encoding */
12626 
12627   sqlite3_int64 iIntkey;          /* Integer key value */
12628 };
12629 
12630 /* Table object */
12631 struct DbdataTable {
12632   sqlite3_vtab base;              /* Base class.  Must be first */
12633   sqlite3 *db;                    /* The database connection */
12634   sqlite3_stmt *pStmt;            /* For fetching database pages */
12635   int bPtr;                       /* True for sqlite3_dbptr table */
12636 };
12637 
12638 /* Column and schema definitions for sqlite_dbdata */
12639 #define DBDATA_COLUMN_PGNO        0
12640 #define DBDATA_COLUMN_CELL        1
12641 #define DBDATA_COLUMN_FIELD       2
12642 #define DBDATA_COLUMN_VALUE       3
12643 #define DBDATA_COLUMN_SCHEMA      4
12644 #define DBDATA_SCHEMA             \
12645       "CREATE TABLE x("           \
12646       "  pgno INTEGER,"           \
12647       "  cell INTEGER,"           \
12648       "  field INTEGER,"          \
12649       "  value ANY,"              \
12650       "  schema TEXT HIDDEN"      \
12651       ")"
12652 
12653 /* Column and schema definitions for sqlite_dbptr */
12654 #define DBPTR_COLUMN_PGNO         0
12655 #define DBPTR_COLUMN_CHILD        1
12656 #define DBPTR_COLUMN_SCHEMA       2
12657 #define DBPTR_SCHEMA              \
12658       "CREATE TABLE x("           \
12659       "  pgno INTEGER,"           \
12660       "  child INTEGER,"          \
12661       "  schema TEXT HIDDEN"      \
12662       ")"
12663 
12664 /*
12665 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
12666 ** table.
12667 */
12668 static int dbdataConnect(
12669   sqlite3 *db,
12670   void *pAux,
12671   int argc, const char *const*argv,
12672   sqlite3_vtab **ppVtab,
12673   char **pzErr
12674 ){
12675   DbdataTable *pTab = 0;
12676   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
12677 
12678   (void)argc;
12679   (void)argv;
12680   (void)pzErr;
12681   if( rc==SQLITE_OK ){
12682     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
12683     if( pTab==0 ){
12684       rc = SQLITE_NOMEM;
12685     }else{
12686       memset(pTab, 0, sizeof(DbdataTable));
12687       pTab->db = db;
12688       pTab->bPtr = (pAux!=0);
12689     }
12690   }
12691 
12692   *ppVtab = (sqlite3_vtab*)pTab;
12693   return rc;
12694 }
12695 
12696 /*
12697 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
12698 */
12699 static int dbdataDisconnect(sqlite3_vtab *pVtab){
12700   DbdataTable *pTab = (DbdataTable*)pVtab;
12701   if( pTab ){
12702     sqlite3_finalize(pTab->pStmt);
12703     sqlite3_free(pVtab);
12704   }
12705   return SQLITE_OK;
12706 }
12707 
12708 /*
12709 ** This function interprets two types of constraints:
12710 **
12711 **       schema=?
12712 **       pgno=?
12713 **
12714 ** If neither are present, idxNum is set to 0. If schema=? is present,
12715 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
12716 ** in idxNum is set.
12717 **
12718 ** If both parameters are present, schema is in position 0 and pgno in
12719 ** position 1.
12720 */
12721 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
12722   DbdataTable *pTab = (DbdataTable*)tab;
12723   int i;
12724   int iSchema = -1;
12725   int iPgno = -1;
12726   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
12727 
12728   for(i=0; i<pIdx->nConstraint; i++){
12729     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
12730     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12731       if( p->iColumn==colSchema ){
12732         if( p->usable==0 ) return SQLITE_CONSTRAINT;
12733         iSchema = i;
12734       }
12735       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
12736         iPgno = i;
12737       }
12738     }
12739   }
12740 
12741   if( iSchema>=0 ){
12742     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
12743     pIdx->aConstraintUsage[iSchema].omit = 1;
12744   }
12745   if( iPgno>=0 ){
12746     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
12747     pIdx->aConstraintUsage[iPgno].omit = 1;
12748     pIdx->estimatedCost = 100;
12749     pIdx->estimatedRows =  50;
12750 
12751     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
12752       int iCol = pIdx->aOrderBy[0].iColumn;
12753       if( pIdx->nOrderBy==1 ){
12754         pIdx->orderByConsumed = (iCol==0 || iCol==1);
12755       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
12756         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
12757       }
12758     }
12759 
12760   }else{
12761     pIdx->estimatedCost = 100000000;
12762     pIdx->estimatedRows = 1000000000;
12763   }
12764   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
12765   return SQLITE_OK;
12766 }
12767 
12768 /*
12769 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
12770 */
12771 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12772   DbdataCursor *pCsr;
12773 
12774   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
12775   if( pCsr==0 ){
12776     return SQLITE_NOMEM;
12777   }else{
12778     memset(pCsr, 0, sizeof(DbdataCursor));
12779     pCsr->base.pVtab = pVTab;
12780   }
12781 
12782   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
12783   return SQLITE_OK;
12784 }
12785 
12786 /*
12787 ** Restore a cursor object to the state it was in when first allocated
12788 ** by dbdataOpen().
12789 */
12790 static void dbdataResetCursor(DbdataCursor *pCsr){
12791   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
12792   if( pTab->pStmt==0 ){
12793     pTab->pStmt = pCsr->pStmt;
12794   }else{
12795     sqlite3_finalize(pCsr->pStmt);
12796   }
12797   pCsr->pStmt = 0;
12798   pCsr->iPgno = 1;
12799   pCsr->iCell = 0;
12800   pCsr->iField = 0;
12801   pCsr->bOnePage = 0;
12802   sqlite3_free(pCsr->aPage);
12803   sqlite3_free(pCsr->pRec);
12804   pCsr->pRec = 0;
12805   pCsr->aPage = 0;
12806 }
12807 
12808 /*
12809 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
12810 */
12811 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
12812   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
12813   dbdataResetCursor(pCsr);
12814   sqlite3_free(pCsr);
12815   return SQLITE_OK;
12816 }
12817 
12818 /*
12819 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
12820 */
12821 static u32 get_uint16(unsigned char *a){
12822   return (a[0]<<8)|a[1];
12823 }
12824 static u32 get_uint32(unsigned char *a){
12825   return ((u32)a[0]<<24)
12826        | ((u32)a[1]<<16)
12827        | ((u32)a[2]<<8)
12828        | ((u32)a[3]);
12829 }
12830 
12831 /*
12832 ** Load page pgno from the database via the sqlite_dbpage virtual table.
12833 ** If successful, set (*ppPage) to point to a buffer containing the page
12834 ** data, (*pnPage) to the size of that buffer in bytes and return
12835 ** SQLITE_OK. In this case it is the responsibility of the caller to
12836 ** eventually free the buffer using sqlite3_free().
12837 **
12838 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
12839 ** return an SQLite error code.
12840 */
12841 static int dbdataLoadPage(
12842   DbdataCursor *pCsr,             /* Cursor object */
12843   u32 pgno,                       /* Page number of page to load */
12844   u8 **ppPage,                    /* OUT: pointer to page buffer */
12845   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
12846 ){
12847   int rc2;
12848   int rc = SQLITE_OK;
12849   sqlite3_stmt *pStmt = pCsr->pStmt;
12850 
12851   *ppPage = 0;
12852   *pnPage = 0;
12853   if( pgno>0 ){
12854     sqlite3_bind_int64(pStmt, 2, pgno);
12855     if( SQLITE_ROW==sqlite3_step(pStmt) ){
12856       int nCopy = sqlite3_column_bytes(pStmt, 0);
12857       if( nCopy>0 ){
12858         u8 *pPage;
12859         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
12860         if( pPage==0 ){
12861           rc = SQLITE_NOMEM;
12862         }else{
12863           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
12864           memcpy(pPage, pCopy, nCopy);
12865           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
12866         }
12867         *ppPage = pPage;
12868         *pnPage = nCopy;
12869       }
12870     }
12871     rc2 = sqlite3_reset(pStmt);
12872     if( rc==SQLITE_OK ) rc = rc2;
12873   }
12874 
12875   return rc;
12876 }
12877 
12878 /*
12879 ** Read a varint.  Put the value in *pVal and return the number of bytes.
12880 */
12881 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
12882   sqlite3_uint64 u = 0;
12883   int i;
12884   for(i=0; i<8; i++){
12885     u = (u<<7) + (z[i]&0x7f);
12886     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
12887   }
12888   u = (u<<8) + (z[i]&0xff);
12889   *pVal = (sqlite3_int64)u;
12890   return 9;
12891 }
12892 
12893 /*
12894 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
12895 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
12896 ** SQLite database except for key values in intkey tables.
12897 */
12898 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
12899   sqlite3_int64 val;
12900   int nRet = dbdataGetVarint(z, &val);
12901   if( val<0 || val>0xFFFFFFFF ) val = 0;
12902   *pVal = val;
12903   return nRet;
12904 }
12905 
12906 /*
12907 ** Return the number of bytes of space used by an SQLite value of type
12908 ** eType.
12909 */
12910 static int dbdataValueBytes(int eType){
12911   switch( eType ){
12912     case 0: case 8: case 9:
12913     case 10: case 11:
12914       return 0;
12915     case 1:
12916       return 1;
12917     case 2:
12918       return 2;
12919     case 3:
12920       return 3;
12921     case 4:
12922       return 4;
12923     case 5:
12924       return 6;
12925     case 6:
12926     case 7:
12927       return 8;
12928     default:
12929       if( eType>0 ){
12930         return ((eType-12) / 2);
12931       }
12932       return 0;
12933   }
12934 }
12935 
12936 /*
12937 ** Load a value of type eType from buffer pData and use it to set the
12938 ** result of context object pCtx.
12939 */
12940 static void dbdataValue(
12941   sqlite3_context *pCtx,
12942   u32 enc,
12943   int eType,
12944   u8 *pData,
12945   sqlite3_int64 nData
12946 ){
12947   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
12948     switch( eType ){
12949       case 0:
12950       case 10:
12951       case 11:
12952         sqlite3_result_null(pCtx);
12953         break;
12954 
12955       case 8:
12956         sqlite3_result_int(pCtx, 0);
12957         break;
12958       case 9:
12959         sqlite3_result_int(pCtx, 1);
12960         break;
12961 
12962       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
12963         sqlite3_uint64 v = (signed char)pData[0];
12964         pData++;
12965         switch( eType ){
12966           case 7:
12967           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
12968           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
12969           case 4:  v = (v<<8) + pData[0];  pData++;
12970           case 3:  v = (v<<8) + pData[0];  pData++;
12971           case 2:  v = (v<<8) + pData[0];  pData++;
12972         }
12973 
12974         if( eType==7 ){
12975           double r;
12976           memcpy(&r, &v, sizeof(r));
12977           sqlite3_result_double(pCtx, r);
12978         }else{
12979           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
12980         }
12981         break;
12982       }
12983 
12984       default: {
12985         int n = ((eType-12) / 2);
12986         if( eType % 2 ){
12987           switch( enc ){
12988 #ifndef SQLITE_OMIT_UTF16
12989             case SQLITE_UTF16BE:
12990               sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
12991               break;
12992             case SQLITE_UTF16LE:
12993               sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
12994               break;
12995 #endif
12996             default:
12997               sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
12998               break;
12999           }
13000         }else{
13001           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
13002         }
13003       }
13004     }
13005   }
13006 }
13007 
13008 /*
13009 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
13010 */
13011 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
13012   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13013   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13014 
13015   pCsr->iRowid++;
13016   while( 1 ){
13017     int rc;
13018     int iOff = (pCsr->iPgno==1 ? 100 : 0);
13019     int bNextPage = 0;
13020 
13021     if( pCsr->aPage==0 ){
13022       while( 1 ){
13023         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
13024         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
13025         if( rc!=SQLITE_OK ) return rc;
13026         if( pCsr->aPage && pCsr->nPage>=256 ) break;
13027         sqlite3_free(pCsr->aPage);
13028         pCsr->aPage = 0;
13029         if( pCsr->bOnePage ) return SQLITE_OK;
13030         pCsr->iPgno++;
13031       }
13032 
13033       assert( iOff+3+2<=pCsr->nPage );
13034       pCsr->iCell = pTab->bPtr ? -2 : 0;
13035       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
13036     }
13037 
13038     if( pTab->bPtr ){
13039       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
13040         pCsr->iCell = pCsr->nCell;
13041       }
13042       pCsr->iCell++;
13043       if( pCsr->iCell>=pCsr->nCell ){
13044         sqlite3_free(pCsr->aPage);
13045         pCsr->aPage = 0;
13046         if( pCsr->bOnePage ) return SQLITE_OK;
13047         pCsr->iPgno++;
13048       }else{
13049         return SQLITE_OK;
13050       }
13051     }else{
13052       /* If there is no record loaded, load it now. */
13053       if( pCsr->pRec==0 ){
13054         int bHasRowid = 0;
13055         int nPointer = 0;
13056         sqlite3_int64 nPayload = 0;
13057         sqlite3_int64 nHdr = 0;
13058         int iHdr;
13059         int U, X;
13060         int nLocal;
13061 
13062         switch( pCsr->aPage[iOff] ){
13063           case 0x02:
13064             nPointer = 4;
13065             break;
13066           case 0x0a:
13067             break;
13068           case 0x0d:
13069             bHasRowid = 1;
13070             break;
13071           default:
13072             /* This is not a b-tree page with records on it. Continue. */
13073             pCsr->iCell = pCsr->nCell;
13074             break;
13075         }
13076 
13077         if( pCsr->iCell>=pCsr->nCell ){
13078           bNextPage = 1;
13079         }else{
13080 
13081           iOff += 8 + nPointer + pCsr->iCell*2;
13082           if( iOff>pCsr->nPage ){
13083             bNextPage = 1;
13084           }else{
13085             iOff = get_uint16(&pCsr->aPage[iOff]);
13086           }
13087 
13088           /* For an interior node cell, skip past the child-page number */
13089           iOff += nPointer;
13090 
13091           /* Load the "byte of payload including overflow" field */
13092           if( bNextPage || iOff>pCsr->nPage ){
13093             bNextPage = 1;
13094           }else{
13095             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
13096           }
13097 
13098           /* If this is a leaf intkey cell, load the rowid */
13099           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
13100             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
13101           }
13102 
13103           /* Figure out how much data to read from the local page */
13104           U = pCsr->nPage;
13105           if( bHasRowid ){
13106             X = U-35;
13107           }else{
13108             X = ((U-12)*64/255)-23;
13109           }
13110           if( nPayload<=X ){
13111             nLocal = nPayload;
13112           }else{
13113             int M, K;
13114             M = ((U-12)*32/255)-23;
13115             K = M+((nPayload-M)%(U-4));
13116             if( K<=X ){
13117               nLocal = K;
13118             }else{
13119               nLocal = M;
13120             }
13121           }
13122 
13123           if( bNextPage || nLocal+iOff>pCsr->nPage ){
13124             bNextPage = 1;
13125           }else{
13126 
13127             /* Allocate space for payload. And a bit more to catch small buffer
13128             ** overruns caused by attempting to read a varint or similar from
13129             ** near the end of a corrupt record.  */
13130             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
13131             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
13132             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
13133             pCsr->nRec = nPayload;
13134 
13135             /* Load the nLocal bytes of payload */
13136             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
13137             iOff += nLocal;
13138 
13139             /* Load content from overflow pages */
13140             if( nPayload>nLocal ){
13141               sqlite3_int64 nRem = nPayload - nLocal;
13142               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
13143               while( nRem>0 ){
13144                 u8 *aOvfl = 0;
13145                 int nOvfl = 0;
13146                 int nCopy;
13147                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
13148                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
13149                 if( rc!=SQLITE_OK ) return rc;
13150                 if( aOvfl==0 ) break;
13151 
13152                 nCopy = U-4;
13153                 if( nCopy>nRem ) nCopy = nRem;
13154                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
13155                 nRem -= nCopy;
13156 
13157                 pgnoOvfl = get_uint32(aOvfl);
13158                 sqlite3_free(aOvfl);
13159               }
13160             }
13161 
13162             iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
13163             if( nHdr>nPayload ) nHdr = 0;
13164             pCsr->nHdr = nHdr;
13165             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
13166             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
13167             pCsr->iField = (bHasRowid ? -1 : 0);
13168           }
13169         }
13170       }else{
13171         pCsr->iField++;
13172         if( pCsr->iField>0 ){
13173           sqlite3_int64 iType;
13174           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
13175             bNextPage = 1;
13176           }else{
13177             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
13178             pCsr->pPtr += dbdataValueBytes(iType);
13179           }
13180         }
13181       }
13182 
13183       if( bNextPage ){
13184         sqlite3_free(pCsr->aPage);
13185         sqlite3_free(pCsr->pRec);
13186         pCsr->aPage = 0;
13187         pCsr->pRec = 0;
13188         if( pCsr->bOnePage ) return SQLITE_OK;
13189         pCsr->iPgno++;
13190       }else{
13191         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
13192           return SQLITE_OK;
13193         }
13194 
13195         /* Advance to the next cell. The next iteration of the loop will load
13196         ** the record and so on. */
13197         sqlite3_free(pCsr->pRec);
13198         pCsr->pRec = 0;
13199         pCsr->iCell++;
13200       }
13201     }
13202   }
13203 
13204   assert( !"can't get here" );
13205   return SQLITE_OK;
13206 }
13207 
13208 /*
13209 ** Return true if the cursor is at EOF.
13210 */
13211 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
13212   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13213   return pCsr->aPage==0;
13214 }
13215 
13216 /*
13217 ** Return true if nul-terminated string zSchema ends in "()". Or false
13218 ** otherwise.
13219 */
13220 static int dbdataIsFunction(const char *zSchema){
13221   size_t n = strlen(zSchema);
13222   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
13223     return (int)n-2;
13224   }
13225   return 0;
13226 }
13227 
13228 /*
13229 ** Determine the size in pages of database zSchema (where zSchema is
13230 ** "main", "temp" or the name of an attached database) and set
13231 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
13232 ** an SQLite error code.
13233 */
13234 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
13235   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
13236   char *zSql = 0;
13237   int rc, rc2;
13238   int nFunc = 0;
13239   sqlite3_stmt *pStmt = 0;
13240 
13241   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
13242     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
13243   }else{
13244     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
13245   }
13246   if( zSql==0 ) return SQLITE_NOMEM;
13247 
13248   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
13249   sqlite3_free(zSql);
13250   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
13251     pCsr->szDb = sqlite3_column_int(pStmt, 0);
13252   }
13253   rc2 = sqlite3_finalize(pStmt);
13254   if( rc==SQLITE_OK ) rc = rc2;
13255   return rc;
13256 }
13257 
13258 /*
13259 ** Attempt to figure out the encoding of the database by retrieving page 1
13260 ** and inspecting the header field. If successful, set the pCsr->enc variable
13261 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
13262 */
13263 static int dbdataGetEncoding(DbdataCursor *pCsr){
13264   int rc = SQLITE_OK;
13265   int nPg1 = 0;
13266   u8 *aPg1 = 0;
13267   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
13268   if( rc==SQLITE_OK && nPg1>=(56+4) ){
13269     pCsr->enc = get_uint32(&aPg1[56]);
13270   }
13271   sqlite3_free(aPg1);
13272   return rc;
13273 }
13274 
13275 
13276 /*
13277 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
13278 */
13279 static int dbdataFilter(
13280   sqlite3_vtab_cursor *pCursor,
13281   int idxNum, const char *idxStr,
13282   int argc, sqlite3_value **argv
13283 ){
13284   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13285   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13286   int rc = SQLITE_OK;
13287   const char *zSchema = "main";
13288   (void)idxStr;
13289   (void)argc;
13290 
13291   dbdataResetCursor(pCsr);
13292   assert( pCsr->iPgno==1 );
13293   if( idxNum & 0x01 ){
13294     zSchema = (const char*)sqlite3_value_text(argv[0]);
13295     if( zSchema==0 ) zSchema = "";
13296   }
13297   if( idxNum & 0x02 ){
13298     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
13299     pCsr->bOnePage = 1;
13300   }else{
13301     rc = dbdataDbsize(pCsr, zSchema);
13302   }
13303 
13304   if( rc==SQLITE_OK ){
13305     int nFunc = 0;
13306     if( pTab->pStmt ){
13307       pCsr->pStmt = pTab->pStmt;
13308       pTab->pStmt = 0;
13309     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
13310       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
13311       if( zSql==0 ){
13312         rc = SQLITE_NOMEM;
13313       }else{
13314         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
13315         sqlite3_free(zSql);
13316       }
13317     }else{
13318       rc = sqlite3_prepare_v2(pTab->db,
13319           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
13320           &pCsr->pStmt, 0
13321       );
13322     }
13323   }
13324   if( rc==SQLITE_OK ){
13325     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
13326   }else{
13327     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
13328   }
13329 
13330   /* Try to determine the encoding of the db by inspecting the header
13331   ** field on page 1. */
13332   if( rc==SQLITE_OK ){
13333     rc = dbdataGetEncoding(pCsr);
13334   }
13335 
13336   if( rc==SQLITE_OK ){
13337     rc = dbdataNext(pCursor);
13338   }
13339   return rc;
13340 }
13341 
13342 /*
13343 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
13344 */
13345 static int dbdataColumn(
13346   sqlite3_vtab_cursor *pCursor,
13347   sqlite3_context *ctx,
13348   int i
13349 ){
13350   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13351   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
13352   if( pTab->bPtr ){
13353     switch( i ){
13354       case DBPTR_COLUMN_PGNO:
13355         sqlite3_result_int64(ctx, pCsr->iPgno);
13356         break;
13357       case DBPTR_COLUMN_CHILD: {
13358         int iOff = pCsr->iPgno==1 ? 100 : 0;
13359         if( pCsr->iCell<0 ){
13360           iOff += 8;
13361         }else{
13362           iOff += 12 + pCsr->iCell*2;
13363           if( iOff>pCsr->nPage ) return SQLITE_OK;
13364           iOff = get_uint16(&pCsr->aPage[iOff]);
13365         }
13366         if( iOff<=pCsr->nPage ){
13367           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
13368         }
13369         break;
13370       }
13371     }
13372   }else{
13373     switch( i ){
13374       case DBDATA_COLUMN_PGNO:
13375         sqlite3_result_int64(ctx, pCsr->iPgno);
13376         break;
13377       case DBDATA_COLUMN_CELL:
13378         sqlite3_result_int(ctx, pCsr->iCell);
13379         break;
13380       case DBDATA_COLUMN_FIELD:
13381         sqlite3_result_int(ctx, pCsr->iField);
13382         break;
13383       case DBDATA_COLUMN_VALUE: {
13384         if( pCsr->iField<0 ){
13385           sqlite3_result_int64(ctx, pCsr->iIntkey);
13386         }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
13387           sqlite3_int64 iType;
13388           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
13389           dbdataValue(
13390               ctx, pCsr->enc, iType, pCsr->pPtr,
13391               &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
13392           );
13393         }
13394         break;
13395       }
13396     }
13397   }
13398   return SQLITE_OK;
13399 }
13400 
13401 /*
13402 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
13403 */
13404 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
13405   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13406   *pRowid = pCsr->iRowid;
13407   return SQLITE_OK;
13408 }
13409 
13410 
13411 /*
13412 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
13413 */
13414 static int sqlite3DbdataRegister(sqlite3 *db){
13415   static sqlite3_module dbdata_module = {
13416     0,                            /* iVersion */
13417     0,                            /* xCreate */
13418     dbdataConnect,                /* xConnect */
13419     dbdataBestIndex,              /* xBestIndex */
13420     dbdataDisconnect,             /* xDisconnect */
13421     0,                            /* xDestroy */
13422     dbdataOpen,                   /* xOpen - open a cursor */
13423     dbdataClose,                  /* xClose - close a cursor */
13424     dbdataFilter,                 /* xFilter - configure scan constraints */
13425     dbdataNext,                   /* xNext - advance a cursor */
13426     dbdataEof,                    /* xEof - check for end of scan */
13427     dbdataColumn,                 /* xColumn - read data */
13428     dbdataRowid,                  /* xRowid - read data */
13429     0,                            /* xUpdate */
13430     0,                            /* xBegin */
13431     0,                            /* xSync */
13432     0,                            /* xCommit */
13433     0,                            /* xRollback */
13434     0,                            /* xFindMethod */
13435     0,                            /* xRename */
13436     0,                            /* xSavepoint */
13437     0,                            /* xRelease */
13438     0,                            /* xRollbackTo */
13439     0                             /* xShadowName */
13440   };
13441 
13442   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
13443   if( rc==SQLITE_OK ){
13444     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
13445   }
13446   return rc;
13447 }
13448 
13449 #ifdef _WIN32
13450 
13451 #endif
13452 int sqlite3_dbdata_init(
13453   sqlite3 *db,
13454   char **pzErrMsg,
13455   const sqlite3_api_routines *pApi
13456 ){
13457   SQLITE_EXTENSION_INIT2(pApi);
13458   (void)pzErrMsg;
13459   return sqlite3DbdataRegister(db);
13460 }
13461 
13462 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13463 
13464 /************************* End ../ext/recover/dbdata.c ********************/
13465 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
13466 /*
13467 ** 2022-08-27
13468 **
13469 ** The author disclaims copyright to this source code.  In place of
13470 ** a legal notice, here is a blessing:
13471 **
13472 **    May you do good and not evil.
13473 **    May you find forgiveness for yourself and forgive others.
13474 **    May you share freely, never taking more than you give.
13475 **
13476 *************************************************************************
13477 **
13478 */
13479 
13480 
13481 /* #include "sqlite3recover.h" */
13482 #include <assert.h>
13483 #include <string.h>
13484 
13485 #ifndef SQLITE_OMIT_VIRTUALTABLE
13486 
13487 /*
13488 ** Declaration for public API function in file dbdata.c. This may be called
13489 ** with NULL as the final two arguments to register the sqlite_dbptr and
13490 ** sqlite_dbdata virtual tables with a database handle.
13491 */
13492 #ifdef _WIN32
13493 
13494 #endif
13495 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
13496 
13497 /* typedef unsigned int u32; */
13498 /* typedef unsigned char u8; */
13499 /* typedef sqlite3_int64 i64; */
13500 
13501 typedef struct RecoverTable RecoverTable;
13502 typedef struct RecoverColumn RecoverColumn;
13503 
13504 /*
13505 ** When recovering rows of data that can be associated with table
13506 ** definitions recovered from the sqlite_schema table, each table is
13507 ** represented by an instance of the following object.
13508 **
13509 ** iRoot:
13510 **   The root page in the original database. Not necessarily (and usually
13511 **   not) the same in the recovered database.
13512 **
13513 ** zTab:
13514 **   Name of the table.
13515 **
13516 ** nCol/aCol[]:
13517 **   aCol[] is an array of nCol columns. In the order in which they appear
13518 **   in the table.
13519 **
13520 ** bIntkey:
13521 **   Set to true for intkey tables, false for WITHOUT ROWID.
13522 **
13523 ** iRowidBind:
13524 **   Each column in the aCol[] array has associated with it the index of
13525 **   the bind parameter its values will be bound to in the INSERT statement
13526 **   used to construct the output database. If the table does has a rowid
13527 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
13528 **   index of the bind paramater to which the rowid value should be bound.
13529 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
13530 **   KEY column, then the rowid value should be bound to the index associated
13531 **   with the column.
13532 **
13533 ** pNext:
13534 **   All RecoverTable objects used by the recovery operation are allocated
13535 **   and populated as part of creating the recovered database schema in
13536 **   the output database, before any non-schema data are recovered. They
13537 **   are then stored in a singly-linked list linked by this variable beginning
13538 **   at sqlite3_recover.pTblList.
13539 */
13540 struct RecoverTable {
13541   u32 iRoot;                      /* Root page in original database */
13542   char *zTab;                     /* Name of table */
13543   int nCol;                       /* Number of columns in table */
13544   RecoverColumn *aCol;            /* Array of columns */
13545   int bIntkey;                    /* True for intkey, false for without rowid */
13546   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
13547   RecoverTable *pNext;
13548 };
13549 
13550 /*
13551 ** Each database column is represented by an instance of the following object
13552 ** stored in the RecoverTable.aCol[] array of the associated table.
13553 **
13554 ** iField:
13555 **   The index of the associated field within database records. Or -1 if
13556 **   there is no associated field (e.g. for virtual generated columns).
13557 **
13558 ** iBind:
13559 **   The bind index of the INSERT statement to bind this columns values
13560 **   to. Or 0 if there is no such index (iff (iField<0)).
13561 **
13562 ** bIPK:
13563 **   True if this is the INTEGER PRIMARY KEY column.
13564 **
13565 ** zCol:
13566 **   Name of column.
13567 **
13568 ** eHidden:
13569 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
13570 */
13571 struct RecoverColumn {
13572   int iField;                     /* Field in record on disk */
13573   int iBind;                      /* Binding to use in INSERT */
13574   int bIPK;                       /* True for IPK column */
13575   char *zCol;
13576   int eHidden;
13577 };
13578 
13579 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
13580 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
13581 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
13582 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
13583 
13584 /*
13585 ** Bitmap object used to track pages in the input database. Allocated
13586 ** and manipulated only by the following functions:
13587 **
13588 **     recoverBitmapAlloc()
13589 **     recoverBitmapFree()
13590 **     recoverBitmapSet()
13591 **     recoverBitmapQuery()
13592 **
13593 ** nPg:
13594 **   Largest page number that may be stored in the bitmap. The range
13595 **   of valid keys is 1 to nPg, inclusive.
13596 **
13597 ** aElem[]:
13598 **   Array large enough to contain a bit for each key. For key value
13599 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
13600 **   In other words, the following is true if bit iKey is set, or
13601 **   false if it is clear:
13602 **
13603 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
13604 */
13605 typedef struct RecoverBitmap RecoverBitmap;
13606 struct RecoverBitmap {
13607   i64 nPg;                        /* Size of bitmap */
13608   u32 aElem[1];                   /* Array of 32-bit bitmasks */
13609 };
13610 
13611 /*
13612 ** State variables (part of the sqlite3_recover structure) used while
13613 ** recovering data for tables identified in the recovered schema (state
13614 ** RECOVER_STATE_WRITING).
13615 */
13616 typedef struct RecoverStateW1 RecoverStateW1;
13617 struct RecoverStateW1 {
13618   sqlite3_stmt *pTbls;
13619   sqlite3_stmt *pSel;
13620   sqlite3_stmt *pInsert;
13621   int nInsert;
13622 
13623   RecoverTable *pTab;             /* Table currently being written */
13624   int nMax;                       /* Max column count in any schema table */
13625   sqlite3_value **apVal;          /* Array of nMax values */
13626   int nVal;                       /* Number of valid entries in apVal[] */
13627   int bHaveRowid;
13628   i64 iRowid;
13629   i64 iPrevPage;
13630   int iPrevCell;
13631 };
13632 
13633 /*
13634 ** State variables (part of the sqlite3_recover structure) used while
13635 ** recovering data destined for the lost and found table (states
13636 ** RECOVER_STATE_LOSTANDFOUND[123]).
13637 */
13638 typedef struct RecoverStateLAF RecoverStateLAF;
13639 struct RecoverStateLAF {
13640   RecoverBitmap *pUsed;
13641   i64 nPg;                        /* Size of db in pages */
13642   sqlite3_stmt *pAllAndParent;
13643   sqlite3_stmt *pMapInsert;
13644   sqlite3_stmt *pMaxField;
13645   sqlite3_stmt *pUsedPages;
13646   sqlite3_stmt *pFindRoot;
13647   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
13648   sqlite3_stmt *pAllPage;
13649   sqlite3_stmt *pPageData;
13650   sqlite3_value **apVal;
13651   int nMaxField;
13652 };
13653 
13654 /*
13655 ** Main recover handle structure.
13656 */
13657 struct sqlite3_recover {
13658   /* Copies of sqlite3_recover_init[_sql]() parameters */
13659   sqlite3 *dbIn;                  /* Input database */
13660   char *zDb;                      /* Name of input db ("main" etc.) */
13661   char *zUri;                     /* URI for output database */
13662   void *pSqlCtx;                  /* SQL callback context */
13663   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
13664 
13665   /* Values configured by sqlite3_recover_config() */
13666   char *zStateDb;                 /* State database to use (or NULL) */
13667   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
13668   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
13669   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
13670   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
13671 
13672   int pgsz;
13673   int detected_pgsz;
13674   int nReserve;
13675   u8 *pPage1Disk;
13676   u8 *pPage1Cache;
13677 
13678   /* Error code and error message */
13679   int errCode;                    /* For sqlite3_recover_errcode() */
13680   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
13681 
13682   int eState;
13683   int bCloseTransaction;
13684 
13685   /* Variables used with eState==RECOVER_STATE_WRITING */
13686   RecoverStateW1 w1;
13687 
13688   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
13689   RecoverStateLAF laf;
13690 
13691   /* Fields used within sqlite3_recover_run() */
13692   sqlite3 *dbOut;                 /* Output database */
13693   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
13694   RecoverTable *pTblList;         /* List of tables recovered from schema */
13695 };
13696 
13697 /*
13698 ** The various states in which an sqlite3_recover object may exist:
13699 **
13700 **   RECOVER_STATE_INIT:
13701 **    The object is initially created in this state. sqlite3_recover_step()
13702 **    has yet to be called. This is the only state in which it is permitted
13703 **    to call sqlite3_recover_config().
13704 **
13705 **   RECOVER_STATE_WRITING:
13706 **
13707 **   RECOVER_STATE_LOSTANDFOUND1:
13708 **    State to populate the bitmap of pages used by other tables or the
13709 **    database freelist.
13710 **
13711 **   RECOVER_STATE_LOSTANDFOUND2:
13712 **    Populate the recovery.map table - used to figure out a "root" page
13713 **    for each lost page from in the database from which records are
13714 **    extracted.
13715 **
13716 **   RECOVER_STATE_LOSTANDFOUND3:
13717 **    Populate the lost-and-found table itself.
13718 */
13719 #define RECOVER_STATE_INIT           0
13720 #define RECOVER_STATE_WRITING        1
13721 #define RECOVER_STATE_LOSTANDFOUND1  2
13722 #define RECOVER_STATE_LOSTANDFOUND2  3
13723 #define RECOVER_STATE_LOSTANDFOUND3  4
13724 #define RECOVER_STATE_SCHEMA2        5
13725 #define RECOVER_STATE_DONE           6
13726 
13727 
13728 /*
13729 ** Global variables used by this extension.
13730 */
13731 typedef struct RecoverGlobal RecoverGlobal;
13732 struct RecoverGlobal {
13733   const sqlite3_io_methods *pMethods;
13734   sqlite3_recover *p;
13735 };
13736 static RecoverGlobal recover_g;
13737 
13738 /*
13739 ** Use this static SQLite mutex to protect the globals during the
13740 ** first call to sqlite3_recover_step().
13741 */
13742 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
13743 
13744 
13745 /*
13746 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
13747 */
13748 #define RECOVER_ROWID_DEFAULT 1
13749 
13750 /*
13751 ** Mutex handling:
13752 **
13753 **    recoverEnterMutex()       -   Enter the recovery mutex
13754 **    recoverLeaveMutex()       -   Leave the recovery mutex
13755 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
13756 */
13757 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
13758 # define recoverEnterMutex()
13759 # define recoverLeaveMutex()
13760 #else
13761 static void recoverEnterMutex(void){
13762   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
13763 }
13764 static void recoverLeaveMutex(void){
13765   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
13766 }
13767 #endif
13768 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
13769 static void recoverAssertMutexHeld(void){
13770   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
13771 }
13772 #else
13773 # define recoverAssertMutexHeld()
13774 #endif
13775 
13776 
13777 /*
13778 ** Like strlen(). But handles NULL pointer arguments.
13779 */
13780 static int recoverStrlen(const char *zStr){
13781   if( zStr==0 ) return 0;
13782   return (int)(strlen(zStr)&0x7fffffff);
13783 }
13784 
13785 /*
13786 ** This function is a no-op if the recover handle passed as the first
13787 ** argument already contains an error (if p->errCode!=SQLITE_OK).
13788 **
13789 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
13790 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
13791 ** if an OOM error occurs, NULL is returned and the handle error code
13792 ** (p->errCode) set to SQLITE_NOMEM.
13793 */
13794 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
13795   void *pRet = 0;
13796   assert( nByte>0 );
13797   if( p->errCode==SQLITE_OK ){
13798     pRet = sqlite3_malloc64(nByte);
13799     if( pRet ){
13800       memset(pRet, 0, nByte);
13801     }else{
13802       p->errCode = SQLITE_NOMEM;
13803     }
13804   }
13805   return pRet;
13806 }
13807 
13808 /*
13809 ** Set the error code and error message for the recover handle passed as
13810 ** the first argument. The error code is set to the value of parameter
13811 ** errCode.
13812 **
13813 ** Parameter zFmt must be a printf() style formatting string. The handle
13814 ** error message is set to the result of using any trailing arguments for
13815 ** parameter substitutions in the formatting string.
13816 **
13817 ** For example:
13818 **
13819 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
13820 */
13821 static int recoverError(
13822   sqlite3_recover *p,
13823   int errCode,
13824   const char *zFmt, ...
13825 ){
13826   char *z = 0;
13827   va_list ap;
13828   va_start(ap, zFmt);
13829   if( zFmt ){
13830     z = sqlite3_vmprintf(zFmt, ap);
13831     va_end(ap);
13832   }
13833   sqlite3_free(p->zErrMsg);
13834   p->zErrMsg = z;
13835   p->errCode = errCode;
13836   return errCode;
13837 }
13838 
13839 
13840 /*
13841 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
13842 ** In this case it returns NULL.
13843 **
13844 ** Otherwise, an attempt is made to allocate and return a bitmap object
13845 ** large enough to store a bit for all page numbers between 1 and nPg,
13846 ** inclusive. The bitmap is initially zeroed.
13847 */
13848 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
13849   int nElem = (nPg+1+31) / 32;
13850   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
13851   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
13852 
13853   if( pRet ){
13854     pRet->nPg = nPg;
13855   }
13856   return pRet;
13857 }
13858 
13859 /*
13860 ** Free a bitmap object allocated by recoverBitmapAlloc().
13861 */
13862 static void recoverBitmapFree(RecoverBitmap *pMap){
13863   sqlite3_free(pMap);
13864 }
13865 
13866 /*
13867 ** Set the bit associated with page iPg in bitvec pMap.
13868 */
13869 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
13870   if( iPg<=pMap->nPg ){
13871     int iElem = (iPg / 32);
13872     int iBit = (iPg % 32);
13873     pMap->aElem[iElem] |= (((u32)1) << iBit);
13874   }
13875 }
13876 
13877 /*
13878 ** Query bitmap object pMap for the state of the bit associated with page
13879 ** iPg. Return 1 if it is set, or 0 otherwise.
13880 */
13881 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
13882   int ret = 1;
13883   if( iPg<=pMap->nPg && iPg>0 ){
13884     int iElem = (iPg / 32);
13885     int iBit = (iPg % 32);
13886     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
13887   }
13888   return ret;
13889 }
13890 
13891 /*
13892 ** Set the recover handle error to the error code and message returned by
13893 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
13894 ** handle db.
13895 */
13896 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
13897   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
13898 }
13899 
13900 /*
13901 ** This function is a no-op if recover handle p already contains an error
13902 ** (if p->errCode!=SQLITE_OK).
13903 **
13904 ** Otherwise, it attempts to prepare the SQL statement in zSql against
13905 ** database handle db. If successful, the statement handle is returned.
13906 ** Or, if an error occurs, NULL is returned and an error left in the
13907 ** recover handle.
13908 */
13909 static sqlite3_stmt *recoverPrepare(
13910   sqlite3_recover *p,
13911   sqlite3 *db,
13912   const char *zSql
13913 ){
13914   sqlite3_stmt *pStmt = 0;
13915   if( p->errCode==SQLITE_OK ){
13916     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
13917       recoverDbError(p, db);
13918     }
13919   }
13920   return pStmt;
13921 }
13922 
13923 /*
13924 ** This function is a no-op if recover handle p already contains an error
13925 ** (if p->errCode!=SQLITE_OK).
13926 **
13927 ** Otherwise, argument zFmt is used as a printf() style format string,
13928 ** along with any trailing arguments, to create an SQL statement. This
13929 ** SQL statement is prepared against database handle db and, if successful,
13930 ** the statment handle returned. Or, if an error occurs - either during
13931 ** the printf() formatting or when preparing the resulting SQL - an
13932 ** error code and message are left in the recover handle.
13933 */
13934 static sqlite3_stmt *recoverPreparePrintf(
13935   sqlite3_recover *p,
13936   sqlite3 *db,
13937   const char *zFmt, ...
13938 ){
13939   sqlite3_stmt *pStmt = 0;
13940   if( p->errCode==SQLITE_OK ){
13941     va_list ap;
13942     char *z;
13943     va_start(ap, zFmt);
13944     z = sqlite3_vmprintf(zFmt, ap);
13945     va_end(ap);
13946     if( z==0 ){
13947       p->errCode = SQLITE_NOMEM;
13948     }else{
13949       pStmt = recoverPrepare(p, db, z);
13950       sqlite3_free(z);
13951     }
13952   }
13953   return pStmt;
13954 }
13955 
13956 /*
13957 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
13958 ** indicates that an error occurred, and there is not already an error
13959 ** in the recover handle passed as the first argument, set the error
13960 ** code and error message appropriately.
13961 **
13962 ** This function returns a copy of the statement handle pointer passed
13963 ** as the second argument.
13964 */
13965 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
13966   int rc = sqlite3_reset(pStmt);
13967   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
13968     recoverDbError(p, sqlite3_db_handle(pStmt));
13969   }
13970   return pStmt;
13971 }
13972 
13973 /*
13974 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
13975 ** indicates that an error occurred, and there is not already an error
13976 ** in the recover handle passed as the first argument, set the error
13977 ** code and error message appropriately.
13978 */
13979 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
13980   sqlite3 *db = sqlite3_db_handle(pStmt);
13981   int rc = sqlite3_finalize(pStmt);
13982   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
13983     recoverDbError(p, db);
13984   }
13985 }
13986 
13987 /*
13988 ** This function is a no-op if recover handle p already contains an error
13989 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
13990 ** case.
13991 **
13992 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
13993 ** Or, if an error occurs, leave an error code and message in the recover
13994 ** handle and return a copy of the error code.
13995 */
13996 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
13997   if( p->errCode==SQLITE_OK ){
13998     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
13999     if( rc ){
14000       recoverDbError(p, db);
14001     }
14002   }
14003   return p->errCode;
14004 }
14005 
14006 /*
14007 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
14008 ** error in the recover handle passed as the first argument if an error
14009 ** (e.g. an OOM) occurs.
14010 */
14011 static void recoverBindValue(
14012   sqlite3_recover *p,
14013   sqlite3_stmt *pStmt,
14014   int iBind,
14015   sqlite3_value *pVal
14016 ){
14017   if( p->errCode==SQLITE_OK ){
14018     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
14019     if( rc ) recoverError(p, rc, 0);
14020   }
14021 }
14022 
14023 /*
14024 ** This function is a no-op if recover handle p already contains an error
14025 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
14026 **
14027 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
14028 ** formatting string and the result of using the trailing arguments for
14029 ** parameter substitution with it written into a buffer obtained from
14030 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
14031 ** It is the responsibility of the caller to eventually free the buffer
14032 ** using sqlite3_free().
14033 **
14034 ** Or, if an error occurs, an error code and message is left in the recover
14035 ** handle and NULL returned.
14036 */
14037 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
14038   va_list ap;
14039   char *z;
14040   va_start(ap, zFmt);
14041   z = sqlite3_vmprintf(zFmt, ap);
14042   va_end(ap);
14043   if( p->errCode==SQLITE_OK ){
14044     if( z==0 ) p->errCode = SQLITE_NOMEM;
14045   }else{
14046     sqlite3_free(z);
14047     z = 0;
14048   }
14049   return z;
14050 }
14051 
14052 /*
14053 ** This function is a no-op if recover handle p already contains an error
14054 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
14055 **
14056 ** Otherwise, execute "PRAGMA page_count" against the input database. If
14057 ** successful, return the integer result. Or, if an error occurs, leave an
14058 ** error code and error message in the sqlite3_recover handle and return
14059 ** zero.
14060 */
14061 static i64 recoverPageCount(sqlite3_recover *p){
14062   i64 nPg = 0;
14063   if( p->errCode==SQLITE_OK ){
14064     sqlite3_stmt *pStmt = 0;
14065     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
14066     if( pStmt ){
14067       sqlite3_step(pStmt);
14068       nPg = sqlite3_column_int64(pStmt, 0);
14069     }
14070     recoverFinalize(p, pStmt);
14071   }
14072   return nPg;
14073 }
14074 
14075 /*
14076 ** Implementation of SQL scalar function "read_i32". The first argument to
14077 ** this function must be a blob. The second a non-negative integer. This
14078 ** function reads and returns a 32-bit big-endian integer from byte
14079 ** offset (4*<arg2>) of the blob.
14080 **
14081 **     SELECT read_i32(<blob>, <idx>)
14082 */
14083 static void recoverReadI32(
14084   sqlite3_context *context,
14085   int argc,
14086   sqlite3_value **argv
14087 ){
14088   const unsigned char *pBlob;
14089   int nBlob;
14090   int iInt;
14091 
14092   assert( argc==2 );
14093   nBlob = sqlite3_value_bytes(argv[0]);
14094   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
14095   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
14096 
14097   if( (iInt+1)*4<=nBlob ){
14098     const unsigned char *a = &pBlob[iInt*4];
14099     i64 iVal = ((i64)a[0]<<24)
14100              + ((i64)a[1]<<16)
14101              + ((i64)a[2]<< 8)
14102              + ((i64)a[3]<< 0);
14103     sqlite3_result_int64(context, iVal);
14104   }
14105 }
14106 
14107 /*
14108 ** Implementation of SQL scalar function "page_is_used". This function
14109 ** is used as part of the procedure for locating orphan rows for the
14110 ** lost-and-found table, and it depends on those routines having populated
14111 ** the sqlite3_recover.laf.pUsed variable.
14112 **
14113 ** The only argument to this function is a page-number. It returns true
14114 ** if the page has already been used somehow during data recovery, or false
14115 ** otherwise.
14116 **
14117 **     SELECT page_is_used(<pgno>);
14118 */
14119 static void recoverPageIsUsed(
14120   sqlite3_context *pCtx,
14121   int nArg,
14122   sqlite3_value **apArg
14123 ){
14124   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
14125   i64 pgno = sqlite3_value_int64(apArg[0]);
14126   assert( nArg==1 );
14127   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
14128 }
14129 
14130 /*
14131 ** The implementation of a user-defined SQL function invoked by the
14132 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
14133 ** of the database being recovered.
14134 **
14135 ** This function always takes a single integer argument. If the argument
14136 ** is zero, then the value returned is the number of pages in the db being
14137 ** recovered. If the argument is greater than zero, it is a page number.
14138 ** The value returned in this case is an SQL blob containing the data for
14139 ** the identified page of the db being recovered. e.g.
14140 **
14141 **     SELECT getpage(0);       -- return number of pages in db
14142 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
14143 */
14144 static void recoverGetPage(
14145   sqlite3_context *pCtx,
14146   int nArg,
14147   sqlite3_value **apArg
14148 ){
14149   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
14150   i64 pgno = sqlite3_value_int64(apArg[0]);
14151   sqlite3_stmt *pStmt = 0;
14152 
14153   assert( nArg==1 );
14154   if( pgno==0 ){
14155     i64 nPg = recoverPageCount(p);
14156     sqlite3_result_int64(pCtx, nPg);
14157     return;
14158   }else{
14159     if( p->pGetPage==0 ){
14160       pStmt = p->pGetPage = recoverPreparePrintf(
14161           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
14162       );
14163     }else if( p->errCode==SQLITE_OK ){
14164       pStmt = p->pGetPage;
14165     }
14166 
14167     if( pStmt ){
14168       sqlite3_bind_int64(pStmt, 1, pgno);
14169       if( SQLITE_ROW==sqlite3_step(pStmt) ){
14170         const u8 *aPg;
14171         int nPg;
14172         assert( p->errCode==SQLITE_OK );
14173         aPg = sqlite3_column_blob(pStmt, 0);
14174         nPg = sqlite3_column_bytes(pStmt, 0);
14175         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
14176           aPg = p->pPage1Disk;
14177         }
14178         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
14179       }
14180       recoverReset(p, pStmt);
14181     }
14182   }
14183 
14184   if( p->errCode ){
14185     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
14186     sqlite3_result_error_code(pCtx, p->errCode);
14187   }
14188 }
14189 
14190 /*
14191 ** Find a string that is not found anywhere in z[].  Return a pointer
14192 ** to that string.
14193 **
14194 ** Try to use zA and zB first.  If both of those are already found in z[]
14195 ** then make up some string and store it in the buffer zBuf.
14196 */
14197 static const char *recoverUnusedString(
14198   const char *z,                    /* Result must not appear anywhere in z */
14199   const char *zA, const char *zB,   /* Try these first */
14200   char *zBuf                        /* Space to store a generated string */
14201 ){
14202   unsigned i = 0;
14203   if( strstr(z, zA)==0 ) return zA;
14204   if( strstr(z, zB)==0 ) return zB;
14205   do{
14206     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
14207   }while( strstr(z,zBuf)!=0 );
14208   return zBuf;
14209 }
14210 
14211 /*
14212 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
14213 ** this function is the output of built-in function quote(). If the first
14214 ** character of the input is "'", indicating that the value passed to quote()
14215 ** was a text value, then this function searches the input for "\n" and "\r"
14216 ** characters and adds a wrapper similar to the following:
14217 **
14218 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
14219 **
14220 ** Or, if the first character of the input is not "'", then a copy of the input
14221 ** is returned.
14222 */
14223 static void recoverEscapeCrnl(
14224   sqlite3_context *context,
14225   int argc,
14226   sqlite3_value **argv
14227 ){
14228   const char *zText = (const char*)sqlite3_value_text(argv[0]);
14229   (void)argc;
14230   if( zText && zText[0]=='\'' ){
14231     int nText = sqlite3_value_bytes(argv[0]);
14232     int i;
14233     char zBuf1[20];
14234     char zBuf2[20];
14235     const char *zNL = 0;
14236     const char *zCR = 0;
14237     int nCR = 0;
14238     int nNL = 0;
14239 
14240     for(i=0; zText[i]; i++){
14241       if( zNL==0 && zText[i]=='\n' ){
14242         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
14243         nNL = (int)strlen(zNL);
14244       }
14245       if( zCR==0 && zText[i]=='\r' ){
14246         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
14247         nCR = (int)strlen(zCR);
14248       }
14249     }
14250 
14251     if( zNL || zCR ){
14252       int iOut = 0;
14253       i64 nMax = (nNL > nCR) ? nNL : nCR;
14254       i64 nAlloc = nMax * nText + (nMax+64)*2;
14255       char *zOut = (char*)sqlite3_malloc64(nAlloc);
14256       if( zOut==0 ){
14257         sqlite3_result_error_nomem(context);
14258         return;
14259       }
14260 
14261       if( zNL && zCR ){
14262         memcpy(&zOut[iOut], "replace(replace(", 16);
14263         iOut += 16;
14264       }else{
14265         memcpy(&zOut[iOut], "replace(", 8);
14266         iOut += 8;
14267       }
14268       for(i=0; zText[i]; i++){
14269         if( zText[i]=='\n' ){
14270           memcpy(&zOut[iOut], zNL, nNL);
14271           iOut += nNL;
14272         }else if( zText[i]=='\r' ){
14273           memcpy(&zOut[iOut], zCR, nCR);
14274           iOut += nCR;
14275         }else{
14276           zOut[iOut] = zText[i];
14277           iOut++;
14278         }
14279       }
14280 
14281       if( zNL ){
14282         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14283         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
14284         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
14285       }
14286       if( zCR ){
14287         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
14288         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
14289         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
14290       }
14291 
14292       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
14293       sqlite3_free(zOut);
14294       return;
14295     }
14296   }
14297 
14298   sqlite3_result_value(context, argv[0]);
14299 }
14300 
14301 /*
14302 ** This function is a no-op if recover handle p already contains an error
14303 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
14304 ** this case.
14305 **
14306 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
14307 ** parts of the database schema that can be extracted from the input database.
14308 **
14309 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
14310 ** and error message are left in the recover handle and a copy of the
14311 ** error code returned. It is not considered an error if part of all of
14312 ** the database schema cannot be recovered due to corruption.
14313 */
14314 static int recoverCacheSchema(sqlite3_recover *p){
14315   return recoverExec(p, p->dbOut,
14316     "WITH RECURSIVE pages(p) AS ("
14317     "  SELECT 1"
14318     "    UNION"
14319     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
14320     ")"
14321     "INSERT INTO recovery.schema SELECT"
14322     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
14323     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
14324     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
14325     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
14326     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
14327     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
14328     "  SELECT p FROM pages"
14329     ") GROUP BY pgno, cell"
14330   );
14331 }
14332 
14333 /*
14334 ** If this recover handle is not in SQL callback mode (i.e. was not created
14335 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
14336 ** this function is a no-op. Otherwise, issue a callback with SQL statement
14337 ** zSql as the parameter.
14338 **
14339 ** If the callback returns non-zero, set the recover handle error code to
14340 ** the value returned (so that the caller will abandon processing).
14341 */
14342 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
14343   if( p->errCode==SQLITE_OK && p->xSql ){
14344     int res = p->xSql(p->pSqlCtx, zSql);
14345     if( res ){
14346       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
14347     }
14348   }
14349 }
14350 
14351 /*
14352 ** Transfer the following settings from the input database to the output
14353 ** database:
14354 **
14355 **   + page-size,
14356 **   + auto-vacuum settings,
14357 **   + database encoding,
14358 **   + user-version (PRAGMA user_version), and
14359 **   + application-id (PRAGMA application_id), and
14360 */
14361 static void recoverTransferSettings(sqlite3_recover *p){
14362   const char *aPragma[] = {
14363     "encoding",
14364     "page_size",
14365     "auto_vacuum",
14366     "user_version",
14367     "application_id"
14368   };
14369   int ii;
14370 
14371   /* Truncate the output database to 0 pages in size. This is done by
14372   ** opening a new, empty, temp db, then using the backup API to clobber
14373   ** any existing output db with a copy of it. */
14374   if( p->errCode==SQLITE_OK ){
14375     sqlite3 *db2 = 0;
14376     int rc = sqlite3_open("", &db2);
14377     if( rc!=SQLITE_OK ){
14378       recoverDbError(p, db2);
14379       return;
14380     }
14381 
14382     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
14383       const char *zPrag = aPragma[ii];
14384       sqlite3_stmt *p1 = 0;
14385       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
14386       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
14387         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
14388         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
14389         recoverSqlCallback(p, z2);
14390         recoverExec(p, db2, z2);
14391         sqlite3_free(z2);
14392         if( zArg==0 ){
14393           recoverError(p, SQLITE_NOMEM, 0);
14394         }
14395       }
14396       recoverFinalize(p, p1);
14397     }
14398     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
14399 
14400     if( p->errCode==SQLITE_OK ){
14401       sqlite3 *db = p->dbOut;
14402       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
14403       if( pBackup ){
14404         sqlite3_backup_step(pBackup, -1);
14405         p->errCode = sqlite3_backup_finish(pBackup);
14406       }else{
14407         recoverDbError(p, db);
14408       }
14409     }
14410 
14411     sqlite3_close(db2);
14412   }
14413 }
14414 
14415 /*
14416 ** This function is a no-op if recover handle p already contains an error
14417 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
14418 ** this case.
14419 **
14420 ** Otherwise, an attempt is made to open the output database, attach
14421 ** and create the schema of the temporary database used to store
14422 ** intermediate data, and to register all required user functions and
14423 ** virtual table modules with the output handle.
14424 **
14425 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
14426 ** and error message are left in the recover handle and a copy of the
14427 ** error code returned.
14428 */
14429 static int recoverOpenOutput(sqlite3_recover *p){
14430   struct Func {
14431     const char *zName;
14432     int nArg;
14433     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
14434   } aFunc[] = {
14435     { "getpage", 1, recoverGetPage },
14436     { "page_is_used", 1, recoverPageIsUsed },
14437     { "read_i32", 2, recoverReadI32 },
14438     { "escape_crnl", 1, recoverEscapeCrnl },
14439   };
14440 
14441   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
14442   sqlite3 *db = 0;                /* New database handle */
14443   int ii;                         /* For iterating through aFunc[] */
14444 
14445   assert( p->dbOut==0 );
14446 
14447   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
14448     recoverDbError(p, db);
14449   }
14450 
14451   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
14452   ** These two are registered with the output database handle - this
14453   ** module depends on the input handle supporting the sqlite_dbpage
14454   ** virtual table only.  */
14455   if( p->errCode==SQLITE_OK ){
14456     p->errCode = sqlite3_dbdata_init(db, 0, 0);
14457   }
14458 
14459   /* Register the custom user-functions with the output handle. */
14460   for(ii=0;
14461       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
14462       ii++){
14463     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
14464         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
14465     );
14466   }
14467 
14468   p->dbOut = db;
14469   return p->errCode;
14470 }
14471 
14472 /*
14473 ** Attach the auxiliary database 'recovery' to the output database handle.
14474 ** This temporary database is used during the recovery process and then
14475 ** discarded.
14476 */
14477 static void recoverOpenRecovery(sqlite3_recover *p){
14478   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
14479   recoverExec(p, p->dbOut, zSql);
14480   recoverExec(p, p->dbOut,
14481       "PRAGMA writable_schema = 1;"
14482       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
14483       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
14484   );
14485   sqlite3_free(zSql);
14486 }
14487 
14488 
14489 /*
14490 ** This function is a no-op if recover handle p already contains an error
14491 ** (if p->errCode!=SQLITE_OK).
14492 **
14493 ** Otherwise, argument zName must be the name of a table that has just been
14494 ** created in the output database. This function queries the output db
14495 ** for the schema of said table, and creates a RecoverTable object to
14496 ** store the schema in memory. The new RecoverTable object is linked into
14497 ** the list at sqlite3_recover.pTblList.
14498 **
14499 ** Parameter iRoot must be the root page of table zName in the INPUT
14500 ** database.
14501 */
14502 static void recoverAddTable(
14503   sqlite3_recover *p,
14504   const char *zName,              /* Name of table created in output db */
14505   i64 iRoot                       /* Root page of same table in INPUT db */
14506 ){
14507   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
14508       "PRAGMA table_xinfo(%Q)", zName
14509   );
14510 
14511   if( pStmt ){
14512     int iPk = -1;
14513     int iBind = 1;
14514     RecoverTable *pNew = 0;
14515     int nCol = 0;
14516     int nName = recoverStrlen(zName);
14517     int nByte = 0;
14518     while( sqlite3_step(pStmt)==SQLITE_ROW ){
14519       nCol++;
14520       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
14521     }
14522     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
14523     recoverReset(p, pStmt);
14524 
14525     pNew = recoverMalloc(p, nByte);
14526     if( pNew ){
14527       int i = 0;
14528       int iField = 0;
14529       char *csr = 0;
14530       pNew->aCol = (RecoverColumn*)&pNew[1];
14531       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
14532       pNew->nCol = nCol;
14533       pNew->iRoot = iRoot;
14534       memcpy(csr, zName, nName);
14535       csr += nName+1;
14536 
14537       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
14538         int iPKF = sqlite3_column_int(pStmt, 5);
14539         int n = sqlite3_column_bytes(pStmt, 1);
14540         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
14541         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
14542         int eHidden = sqlite3_column_int(pStmt, 6);
14543 
14544         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
14545         if( iPKF>1 ) iPk = -2;
14546         pNew->aCol[i].zCol = csr;
14547         pNew->aCol[i].eHidden = eHidden;
14548         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
14549           pNew->aCol[i].iField = -1;
14550         }else{
14551           pNew->aCol[i].iField = iField++;
14552         }
14553         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
14554          && eHidden!=RECOVER_EHIDDEN_STORED
14555         ){
14556           pNew->aCol[i].iBind = iBind++;
14557         }
14558         memcpy(csr, z, n);
14559         csr += (n+1);
14560       }
14561 
14562       pNew->pNext = p->pTblList;
14563       p->pTblList = pNew;
14564       pNew->bIntkey = 1;
14565     }
14566 
14567     recoverFinalize(p, pStmt);
14568 
14569     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
14570     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
14571       int iField = sqlite3_column_int(pStmt, 0);
14572       int iCol = sqlite3_column_int(pStmt, 1);
14573 
14574       assert( iField<pNew->nCol && iCol<pNew->nCol );
14575       pNew->aCol[iCol].iField = iField;
14576 
14577       pNew->bIntkey = 0;
14578       iPk = -2;
14579     }
14580     recoverFinalize(p, pStmt);
14581 
14582     if( p->errCode==SQLITE_OK ){
14583       if( iPk>=0 ){
14584         pNew->aCol[iPk].bIPK = 1;
14585       }else if( pNew->bIntkey ){
14586         pNew->iRowidBind = iBind++;
14587       }
14588     }
14589   }
14590 }
14591 
14592 /*
14593 ** This function is called after recoverCacheSchema() has cached those parts
14594 ** of the input database schema that could be recovered in temporary table
14595 ** "recovery.schema". This function creates in the output database copies
14596 ** of all parts of that schema that must be created before the tables can
14597 ** be populated. Specifically, this means:
14598 **
14599 **     * all tables that are not VIRTUAL, and
14600 **     * UNIQUE indexes.
14601 **
14602 ** If the recovery handle uses SQL callbacks, then callbacks containing
14603 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
14604 **
14605 ** Additionally, records are added to the sqlite_schema table of the
14606 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
14607 ** records are written directly to sqlite_schema, not actually executed.
14608 ** If the handle is in SQL callback mode, then callbacks are invoked
14609 ** with equivalent SQL statements.
14610 */
14611 static int recoverWriteSchema1(sqlite3_recover *p){
14612   sqlite3_stmt *pSelect = 0;
14613   sqlite3_stmt *pTblname = 0;
14614 
14615   pSelect = recoverPrepare(p, p->dbOut,
14616       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
14617       "  SELECT rootpage, name, sql, "
14618       "    type='table', "
14619       "    sql LIKE 'create virtual%',"
14620       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
14621       "  FROM recovery.schema"
14622       ")"
14623       "SELECT rootpage, tbl, isVirtual, name, sql"
14624       " FROM dbschema "
14625       "  WHERE tbl OR isIndex"
14626       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
14627   );
14628 
14629   pTblname = recoverPrepare(p, p->dbOut,
14630       "SELECT name FROM sqlite_schema "
14631       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
14632   );
14633 
14634   if( pSelect ){
14635     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
14636     while( sqlite3_step(pSelect)==SQLITE_ROW ){
14637       i64 iRoot = sqlite3_column_int64(pSelect, 0);
14638       int bTable = sqlite3_column_int(pSelect, 1);
14639       int bVirtual = sqlite3_column_int(pSelect, 2);
14640       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
14641       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
14642       char *zFree = 0;
14643       int rc = SQLITE_OK;
14644 
14645       if( bVirtual ){
14646         zSql = (const char*)(zFree = recoverMPrintf(p,
14647             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
14648             zName, zName, zSql
14649         ));
14650       }
14651       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
14652       if( rc==SQLITE_OK ){
14653         recoverSqlCallback(p, zSql);
14654         if( bTable && !bVirtual ){
14655           if( SQLITE_ROW==sqlite3_step(pTblname) ){
14656             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
14657             recoverAddTable(p, zTbl, iRoot);
14658           }
14659           recoverReset(p, pTblname);
14660         }
14661       }else if( rc!=SQLITE_ERROR ){
14662         recoverDbError(p, p->dbOut);
14663       }
14664       sqlite3_free(zFree);
14665     }
14666   }
14667   recoverFinalize(p, pSelect);
14668   recoverFinalize(p, pTblname);
14669 
14670   return p->errCode;
14671 }
14672 
14673 /*
14674 ** This function is called after the output database has been populated. It
14675 ** adds all recovered schema elements that were not created in the output
14676 ** database by recoverWriteSchema1() - everything except for tables and
14677 ** UNIQUE indexes. Specifically:
14678 **
14679 **     * views,
14680 **     * triggers,
14681 **     * non-UNIQUE indexes.
14682 **
14683 ** If the recover handle is in SQL callback mode, then equivalent callbacks
14684 ** are issued to create the schema elements.
14685 */
14686 static int recoverWriteSchema2(sqlite3_recover *p){
14687   sqlite3_stmt *pSelect = 0;
14688 
14689   pSelect = recoverPrepare(p, p->dbOut,
14690       p->bSlowIndexes ?
14691       "SELECT rootpage, sql FROM recovery.schema "
14692       "  WHERE type!='table' AND type!='index'"
14693       :
14694       "SELECT rootpage, sql FROM recovery.schema "
14695       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
14696   );
14697 
14698   if( pSelect ){
14699     while( sqlite3_step(pSelect)==SQLITE_ROW ){
14700       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
14701       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
14702       if( rc==SQLITE_OK ){
14703         recoverSqlCallback(p, zSql);
14704       }else if( rc!=SQLITE_ERROR ){
14705         recoverDbError(p, p->dbOut);
14706       }
14707     }
14708   }
14709   recoverFinalize(p, pSelect);
14710 
14711   return p->errCode;
14712 }
14713 
14714 /*
14715 ** This function is a no-op if recover handle p already contains an error
14716 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
14717 **
14718 ** Otherwise, if the recover handle is configured to create an output
14719 ** database (was created by sqlite3_recover_init()), then this function
14720 ** prepares and returns an SQL statement to INSERT a new record into table
14721 ** pTab, assuming the first nField fields of a record extracted from disk
14722 ** are valid.
14723 **
14724 ** For example, if table pTab is:
14725 **
14726 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
14727 **
14728 ** And nField is 4, then the SQL statement prepared and returned is:
14729 **
14730 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
14731 **
14732 ** In this case even though 4 values were extracted from the input db,
14733 ** only 3 are written to the output, as the generated STORED column
14734 ** cannot be written.
14735 **
14736 ** If the recover handle is in SQL callback mode, then the SQL statement
14737 ** prepared is such that evaluating it returns a single row containing
14738 ** a single text value - itself an SQL statement similar to the above,
14739 ** except with SQL literals in place of the variables. For example:
14740 **
14741 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
14742 **          || quote(?1) || ', '
14743 **          || quote(?2) || ', '
14744 **          || quote(?3) || ')';
14745 **
14746 ** In either case, it is the responsibility of the caller to eventually
14747 ** free the statement handle using sqlite3_finalize().
14748 */
14749 static sqlite3_stmt *recoverInsertStmt(
14750   sqlite3_recover *p,
14751   RecoverTable *pTab,
14752   int nField
14753 ){
14754   sqlite3_stmt *pRet = 0;
14755   const char *zSep = "";
14756   const char *zSqlSep = "";
14757   char *zSql = 0;
14758   char *zFinal = 0;
14759   char *zBind = 0;
14760   int ii;
14761   int bSql = p->xSql ? 1 : 0;
14762 
14763   if( nField<=0 ) return 0;
14764 
14765   assert( nField<=pTab->nCol );
14766 
14767   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
14768 
14769   if( pTab->iRowidBind ){
14770     assert( pTab->bIntkey );
14771     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
14772     if( bSql ){
14773       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
14774     }else{
14775       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
14776     }
14777     zSqlSep = "||', '||";
14778     zSep = ", ";
14779   }
14780 
14781   for(ii=0; ii<nField; ii++){
14782     int eHidden = pTab->aCol[ii].eHidden;
14783     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
14784      && eHidden!=RECOVER_EHIDDEN_STORED
14785     ){
14786       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
14787       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
14788 
14789       if( bSql ){
14790         zBind = recoverMPrintf(p,
14791             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
14792         );
14793         zSqlSep = "||', '||";
14794       }else{
14795         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
14796       }
14797       zSep = ", ";
14798     }
14799   }
14800 
14801   if( bSql ){
14802     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
14803         zSql, zBind
14804     );
14805   }else{
14806     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
14807   }
14808 
14809   pRet = recoverPrepare(p, p->dbOut, zFinal);
14810   sqlite3_free(zSql);
14811   sqlite3_free(zBind);
14812   sqlite3_free(zFinal);
14813 
14814   return pRet;
14815 }
14816 
14817 
14818 /*
14819 ** Search the list of RecoverTable objects at p->pTblList for one that
14820 ** has root page iRoot in the input database. If such an object is found,
14821 ** return a pointer to it. Otherwise, return NULL.
14822 */
14823 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
14824   RecoverTable *pRet = 0;
14825   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
14826   return pRet;
14827 }
14828 
14829 /*
14830 ** This function attempts to create a lost and found table within the
14831 ** output db. If successful, it returns a pointer to a buffer containing
14832 ** the name of the new table. It is the responsibility of the caller to
14833 ** eventually free this buffer using sqlite3_free().
14834 **
14835 ** If an error occurs, NULL is returned and an error code and error
14836 ** message left in the recover handle.
14837 */
14838 static char *recoverLostAndFoundCreate(
14839   sqlite3_recover *p,             /* Recover object */
14840   int nField                      /* Number of column fields in new table */
14841 ){
14842   char *zTbl = 0;
14843   sqlite3_stmt *pProbe = 0;
14844   int ii = 0;
14845 
14846   pProbe = recoverPrepare(p, p->dbOut,
14847     "SELECT 1 FROM sqlite_schema WHERE name=?"
14848   );
14849   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
14850     int bFail = 0;
14851     if( ii<0 ){
14852       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
14853     }else{
14854       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
14855     }
14856 
14857     if( p->errCode==SQLITE_OK ){
14858       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
14859       if( SQLITE_ROW==sqlite3_step(pProbe) ){
14860         bFail = 1;
14861       }
14862       recoverReset(p, pProbe);
14863     }
14864 
14865     if( bFail ){
14866       sqlite3_clear_bindings(pProbe);
14867       sqlite3_free(zTbl);
14868       zTbl = 0;
14869     }
14870   }
14871   recoverFinalize(p, pProbe);
14872 
14873   if( zTbl ){
14874     const char *zSep = 0;
14875     char *zField = 0;
14876     char *zSql = 0;
14877 
14878     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
14879     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
14880       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
14881       zSep = ", ";
14882     }
14883 
14884     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
14885     sqlite3_free(zField);
14886 
14887     recoverExec(p, p->dbOut, zSql);
14888     recoverSqlCallback(p, zSql);
14889     sqlite3_free(zSql);
14890   }else if( p->errCode==SQLITE_OK ){
14891     recoverError(
14892         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
14893     );
14894   }
14895 
14896   return zTbl;
14897 }
14898 
14899 /*
14900 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
14901 ** table in the output database. The name of the table is zTab, and it has
14902 ** nField c* fields.
14903 */
14904 static sqlite3_stmt *recoverLostAndFoundInsert(
14905   sqlite3_recover *p,
14906   const char *zTab,
14907   int nField
14908 ){
14909   int nTotal = nField + 4;
14910   int ii;
14911   char *zBind = 0;
14912   sqlite3_stmt *pRet = 0;
14913 
14914   if( p->xSql==0 ){
14915     for(ii=0; ii<nTotal; ii++){
14916       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
14917     }
14918     pRet = recoverPreparePrintf(
14919         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
14920     );
14921   }else{
14922     const char *zSep = "";
14923     for(ii=0; ii<nTotal; ii++){
14924       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
14925       zSep = "|| ', ' ||";
14926     }
14927     pRet = recoverPreparePrintf(
14928         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
14929     );
14930   }
14931 
14932   sqlite3_free(zBind);
14933   return pRet;
14934 }
14935 
14936 /*
14937 ** Input database page iPg contains data that will be written to the
14938 ** lost-and-found table of the output database. This function attempts
14939 ** to identify the root page of the tree that page iPg belonged to.
14940 ** If successful, it sets output variable (*piRoot) to the page number
14941 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
14942 ** an SQLite error code is returned and the final value of *piRoot
14943 ** undefined.
14944 */
14945 static int recoverLostAndFoundFindRoot(
14946   sqlite3_recover *p,
14947   i64 iPg,
14948   i64 *piRoot
14949 ){
14950   RecoverStateLAF *pLaf = &p->laf;
14951 
14952   if( pLaf->pFindRoot==0 ){
14953     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
14954         "WITH RECURSIVE p(pgno) AS ("
14955         "  SELECT ?"
14956         "    UNION"
14957         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
14958         ") "
14959         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
14960         "    AND m.parent IS NULL"
14961     );
14962   }
14963   if( p->errCode==SQLITE_OK ){
14964     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
14965     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
14966       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
14967     }else{
14968       *piRoot = iPg;
14969     }
14970     recoverReset(p, pLaf->pFindRoot);
14971   }
14972   return p->errCode;
14973 }
14974 
14975 /*
14976 ** Recover data from page iPage of the input database and write it to
14977 ** the lost-and-found table in the output database.
14978 */
14979 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
14980   RecoverStateLAF *pLaf = &p->laf;
14981   sqlite3_value **apVal = pLaf->apVal;
14982   sqlite3_stmt *pPageData = pLaf->pPageData;
14983   sqlite3_stmt *pInsert = pLaf->pInsert;
14984 
14985   int nVal = -1;
14986   int iPrevCell = 0;
14987   i64 iRoot = 0;
14988   int bHaveRowid = 0;
14989   i64 iRowid = 0;
14990   int ii = 0;
14991 
14992   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
14993   sqlite3_bind_int64(pPageData, 1, iPage);
14994   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
14995     int iCell = sqlite3_column_int64(pPageData, 0);
14996     int iField = sqlite3_column_int64(pPageData, 1);
14997 
14998     if( iPrevCell!=iCell && nVal>=0 ){
14999       /* Insert the new row */
15000       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
15001       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
15002       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
15003       if( bHaveRowid ){
15004         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
15005       }
15006       for(ii=0; ii<nVal; ii++){
15007         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
15008       }
15009       if( sqlite3_step(pInsert)==SQLITE_ROW ){
15010         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
15011       }
15012       recoverReset(p, pInsert);
15013 
15014       /* Discard the accumulated row data */
15015       for(ii=0; ii<nVal; ii++){
15016         sqlite3_value_free(apVal[ii]);
15017         apVal[ii] = 0;
15018       }
15019       sqlite3_clear_bindings(pInsert);
15020       bHaveRowid = 0;
15021       nVal = -1;
15022     }
15023 
15024     if( iCell<0 ) break;
15025 
15026     if( iField<0 ){
15027       assert( nVal==-1 );
15028       iRowid = sqlite3_column_int64(pPageData, 2);
15029       bHaveRowid = 1;
15030       nVal = 0;
15031     }else if( iField<pLaf->nMaxField ){
15032       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
15033       apVal[iField] = sqlite3_value_dup(pVal);
15034       assert( iField==nVal || (nVal==-1 && iField==0) );
15035       nVal = iField+1;
15036       if( apVal[iField]==0 ){
15037         recoverError(p, SQLITE_NOMEM, 0);
15038       }
15039     }
15040 
15041     iPrevCell = iCell;
15042   }
15043   recoverReset(p, pPageData);
15044 
15045   for(ii=0; ii<nVal; ii++){
15046     sqlite3_value_free(apVal[ii]);
15047     apVal[ii] = 0;
15048   }
15049 }
15050 
15051 /*
15052 ** Perform one step (sqlite3_recover_step()) of work for the connection
15053 ** passed as the only argument, which is guaranteed to be in
15054 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
15055 ** table of the output database is populated with recovered data that can
15056 ** not be assigned to any recovered schema object.
15057 */
15058 static int recoverLostAndFound3Step(sqlite3_recover *p){
15059   RecoverStateLAF *pLaf = &p->laf;
15060   if( p->errCode==SQLITE_OK ){
15061     if( pLaf->pInsert==0 ){
15062       return SQLITE_DONE;
15063     }else{
15064       if( p->errCode==SQLITE_OK ){
15065         int res = sqlite3_step(pLaf->pAllPage);
15066         if( res==SQLITE_ROW ){
15067           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
15068           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
15069             recoverLostAndFoundOnePage(p, iPage);
15070           }
15071         }else{
15072           recoverReset(p, pLaf->pAllPage);
15073           return SQLITE_DONE;
15074         }
15075       }
15076     }
15077   }
15078   return SQLITE_OK;
15079 }
15080 
15081 /*
15082 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
15083 ** state - during which the lost-and-found table of the output database
15084 ** is populated with recovered data that can not be assigned to any
15085 ** recovered schema object.
15086 */
15087 static void recoverLostAndFound3Init(sqlite3_recover *p){
15088   RecoverStateLAF *pLaf = &p->laf;
15089 
15090   if( pLaf->nMaxField>0 ){
15091     char *zTab = 0;               /* Name of lost_and_found table */
15092 
15093     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
15094     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
15095     sqlite3_free(zTab);
15096 
15097     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
15098         "WITH RECURSIVE seq(ii) AS ("
15099         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
15100         ")"
15101         "SELECT ii FROM seq" , p->laf.nPg
15102     );
15103     pLaf->pPageData = recoverPrepare(p, p->dbOut,
15104         "SELECT cell, field, value "
15105         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
15106         "UNION ALL "
15107         "SELECT -1, -1, -1"
15108     );
15109 
15110     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
15111         pLaf->nMaxField*sizeof(sqlite3_value*)
15112     );
15113   }
15114 }
15115 
15116 /*
15117 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
15118 ** tables recovered from the schema of the input database are populated with
15119 ** recovered data.
15120 */
15121 static int recoverWriteDataInit(sqlite3_recover *p){
15122   RecoverStateW1 *p1 = &p->w1;
15123   RecoverTable *pTbl = 0;
15124   int nByte = 0;
15125 
15126   /* Figure out the maximum number of columns for any table in the schema */
15127   assert( p1->nMax==0 );
15128   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
15129     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
15130   }
15131 
15132   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
15133   ** that will be written to the output database in a single row. */
15134   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
15135   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
15136   if( p1->apVal==0 ) return p->errCode;
15137 
15138   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
15139   ** to loop through cells that appear to belong to a single table (pSel). */
15140   p1->pTbls = recoverPrepare(p, p->dbOut,
15141       "SELECT rootpage FROM recovery.schema "
15142       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
15143       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
15144   );
15145   p1->pSel = recoverPrepare(p, p->dbOut,
15146       "WITH RECURSIVE pages(page) AS ("
15147       "  SELECT ?1"
15148       "    UNION"
15149       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
15150       "    WHERE pgno=page"
15151       ") "
15152       "SELECT page, cell, field, value "
15153       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
15154       "UNION ALL "
15155       "SELECT 0, 0, 0, 0"
15156   );
15157 
15158   return p->errCode;
15159 }
15160 
15161 /*
15162 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
15163 ** sqlite3_recover.w1).
15164 */
15165 static void recoverWriteDataCleanup(sqlite3_recover *p){
15166   RecoverStateW1 *p1 = &p->w1;
15167   int ii;
15168   for(ii=0; ii<p1->nVal; ii++){
15169     sqlite3_value_free(p1->apVal[ii]);
15170   }
15171   sqlite3_free(p1->apVal);
15172   recoverFinalize(p, p1->pInsert);
15173   recoverFinalize(p, p1->pTbls);
15174   recoverFinalize(p, p1->pSel);
15175   memset(p1, 0, sizeof(*p1));
15176 }
15177 
15178 /*
15179 ** Perform one step (sqlite3_recover_step()) of work for the connection
15180 ** passed as the only argument, which is guaranteed to be in
15181 ** RECOVER_STATE_WRITING state - during which tables recovered from the
15182 ** schema of the input database are populated with recovered data.
15183 */
15184 static int recoverWriteDataStep(sqlite3_recover *p){
15185   RecoverStateW1 *p1 = &p->w1;
15186   sqlite3_stmt *pSel = p1->pSel;
15187   sqlite3_value **apVal = p1->apVal;
15188 
15189   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
15190     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
15191       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
15192       p1->pTab = recoverFindTable(p, iRoot);
15193 
15194       recoverFinalize(p, p1->pInsert);
15195       p1->pInsert = 0;
15196 
15197       /* If this table is unknown, return early. The caller will invoke this
15198       ** function again and it will move on to the next table.  */
15199       if( p1->pTab==0 ) return p->errCode;
15200 
15201       /* If this is the sqlite_sequence table, delete any rows added by
15202       ** earlier INSERT statements on tables with AUTOINCREMENT primary
15203       ** keys before recovering its contents. The p1->pTbls SELECT statement
15204       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
15205       ** worry about it being modified after it is recovered. */
15206       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
15207         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
15208         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
15209       }
15210 
15211       /* Bind the root page of this table within the original database to
15212       ** SELECT statement p1->pSel. The SELECT statement will then iterate
15213       ** through cells that look like they belong to table pTab.  */
15214       sqlite3_bind_int64(pSel, 1, iRoot);
15215 
15216       p1->nVal = 0;
15217       p1->bHaveRowid = 0;
15218       p1->iPrevPage = -1;
15219       p1->iPrevCell = -1;
15220     }else{
15221       return SQLITE_DONE;
15222     }
15223   }
15224   assert( p->errCode!=SQLITE_OK || p1->pTab );
15225 
15226   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
15227     RecoverTable *pTab = p1->pTab;
15228 
15229     i64 iPage = sqlite3_column_int64(pSel, 0);
15230     int iCell = sqlite3_column_int(pSel, 1);
15231     int iField = sqlite3_column_int(pSel, 2);
15232     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
15233     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
15234 
15235     assert( bNewCell==0 || (iField==-1 || iField==0) );
15236     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
15237 
15238     if( bNewCell ){
15239       int ii = 0;
15240       if( p1->nVal>=0 ){
15241         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
15242           recoverFinalize(p, p1->pInsert);
15243           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
15244           p1->nInsert = p1->nVal;
15245         }
15246         if( p1->nVal>0 ){
15247           sqlite3_stmt *pInsert = p1->pInsert;
15248           for(ii=0; ii<pTab->nCol; ii++){
15249             RecoverColumn *pCol = &pTab->aCol[ii];
15250             int iBind = pCol->iBind;
15251             if( iBind>0 ){
15252               if( pCol->bIPK ){
15253                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
15254               }else if( pCol->iField<p1->nVal ){
15255                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
15256               }
15257             }
15258           }
15259           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
15260             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
15261           }
15262           if( SQLITE_ROW==sqlite3_step(pInsert) ){
15263             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
15264             recoverSqlCallback(p, z);
15265           }
15266           recoverReset(p, pInsert);
15267           assert( p->errCode || pInsert );
15268           if( pInsert ) sqlite3_clear_bindings(pInsert);
15269         }
15270       }
15271 
15272       for(ii=0; ii<p1->nVal; ii++){
15273         sqlite3_value_free(apVal[ii]);
15274         apVal[ii] = 0;
15275       }
15276       p1->nVal = -1;
15277       p1->bHaveRowid = 0;
15278     }
15279 
15280     if( iPage!=0 ){
15281       if( iField<0 ){
15282         p1->iRowid = sqlite3_column_int64(pSel, 3);
15283         assert( p1->nVal==-1 );
15284         p1->nVal = 0;
15285         p1->bHaveRowid = 1;
15286       }else if( iField<pTab->nCol ){
15287         assert( apVal[iField]==0 );
15288         apVal[iField] = sqlite3_value_dup( pVal );
15289         if( apVal[iField]==0 ){
15290           recoverError(p, SQLITE_NOMEM, 0);
15291         }
15292         p1->nVal = iField+1;
15293       }
15294       p1->iPrevCell = iCell;
15295       p1->iPrevPage = iPage;
15296     }
15297   }else{
15298     recoverReset(p, pSel);
15299     p1->pTab = 0;
15300   }
15301 
15302   return p->errCode;
15303 }
15304 
15305 /*
15306 ** Initialize resources required by sqlite3_recover_step() in
15307 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
15308 ** already allocated to a recovered schema element is determined.
15309 */
15310 static void recoverLostAndFound1Init(sqlite3_recover *p){
15311   RecoverStateLAF *pLaf = &p->laf;
15312   sqlite3_stmt *pStmt = 0;
15313 
15314   assert( p->laf.pUsed==0 );
15315   pLaf->nPg = recoverPageCount(p);
15316   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
15317 
15318   /* Prepare a statement to iterate through all pages that are part of any tree
15319   ** in the recoverable part of the input database schema to the bitmap. And,
15320   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
15321   ** freelist.  */
15322   pStmt = recoverPrepare(
15323       p, p->dbOut,
15324       "WITH trunk(pgno) AS ("
15325       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
15326       "    UNION"
15327       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
15328       "),"
15329       "trunkdata(pgno, data) AS ("
15330       "  SELECT pgno, getpage(pgno) FROM trunk"
15331       "),"
15332       "freelist(data, n, freepgno) AS ("
15333       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
15334       "    UNION ALL"
15335       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
15336       "),"
15337       ""
15338       "roots(r) AS ("
15339       "  SELECT 1 UNION ALL"
15340       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
15341       "),"
15342       "used(page) AS ("
15343       "  SELECT r FROM roots"
15344       "    UNION"
15345       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
15346       "    WHERE pgno=page"
15347       ") "
15348       "SELECT page FROM used"
15349       " UNION ALL "
15350       "SELECT freepgno FROM freelist WHERE NOT ?"
15351   );
15352   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
15353   pLaf->pUsedPages = pStmt;
15354 }
15355 
15356 /*
15357 ** Perform one step (sqlite3_recover_step()) of work for the connection
15358 ** passed as the only argument, which is guaranteed to be in
15359 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
15360 ** already allocated to a recovered schema element is determined.
15361 */
15362 static int recoverLostAndFound1Step(sqlite3_recover *p){
15363   RecoverStateLAF *pLaf = &p->laf;
15364   int rc = p->errCode;
15365   if( rc==SQLITE_OK ){
15366     rc = sqlite3_step(pLaf->pUsedPages);
15367     if( rc==SQLITE_ROW ){
15368       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
15369       recoverBitmapSet(pLaf->pUsed, iPg);
15370       rc = SQLITE_OK;
15371     }else{
15372       recoverFinalize(p, pLaf->pUsedPages);
15373       pLaf->pUsedPages = 0;
15374     }
15375   }
15376   return rc;
15377 }
15378 
15379 /*
15380 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
15381 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
15382 ** are sorted into sets that likely belonged to the same database tree.
15383 */
15384 static void recoverLostAndFound2Init(sqlite3_recover *p){
15385   RecoverStateLAF *pLaf = &p->laf;
15386 
15387   assert( p->laf.pAllAndParent==0 );
15388   assert( p->laf.pMapInsert==0 );
15389   assert( p->laf.pMaxField==0 );
15390   assert( p->laf.nMaxField==0 );
15391 
15392   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
15393       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
15394   );
15395   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
15396       "WITH RECURSIVE seq(ii) AS ("
15397       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
15398       ")"
15399       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
15400       " UNION ALL "
15401       "SELECT NULL, ii FROM seq", p->laf.nPg
15402   );
15403   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
15404       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
15405   );
15406 }
15407 
15408 /*
15409 ** Perform one step (sqlite3_recover_step()) of work for the connection
15410 ** passed as the only argument, which is guaranteed to be in
15411 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
15412 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
15413 ** to the same database tree.
15414 */
15415 static int recoverLostAndFound2Step(sqlite3_recover *p){
15416   RecoverStateLAF *pLaf = &p->laf;
15417   if( p->errCode==SQLITE_OK ){
15418     int res = sqlite3_step(pLaf->pAllAndParent);
15419     if( res==SQLITE_ROW ){
15420       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
15421       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
15422         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
15423         sqlite3_bind_value(pLaf->pMapInsert, 2,
15424             sqlite3_column_value(pLaf->pAllAndParent, 0)
15425         );
15426         sqlite3_step(pLaf->pMapInsert);
15427         recoverReset(p, pLaf->pMapInsert);
15428         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
15429         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
15430           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
15431           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
15432         }
15433         recoverReset(p, pLaf->pMaxField);
15434       }
15435     }else{
15436       recoverFinalize(p, pLaf->pAllAndParent);
15437       pLaf->pAllAndParent =0;
15438       return SQLITE_DONE;
15439     }
15440   }
15441   return p->errCode;
15442 }
15443 
15444 /*
15445 ** Free all resources allocated as part of sqlite3_recover_step() calls
15446 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
15447 */
15448 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
15449   recoverBitmapFree(p->laf.pUsed);
15450   p->laf.pUsed = 0;
15451   sqlite3_finalize(p->laf.pUsedPages);
15452   sqlite3_finalize(p->laf.pAllAndParent);
15453   sqlite3_finalize(p->laf.pMapInsert);
15454   sqlite3_finalize(p->laf.pMaxField);
15455   sqlite3_finalize(p->laf.pFindRoot);
15456   sqlite3_finalize(p->laf.pInsert);
15457   sqlite3_finalize(p->laf.pAllPage);
15458   sqlite3_finalize(p->laf.pPageData);
15459   p->laf.pUsedPages = 0;
15460   p->laf.pAllAndParent = 0;
15461   p->laf.pMapInsert = 0;
15462   p->laf.pMaxField = 0;
15463   p->laf.pFindRoot = 0;
15464   p->laf.pInsert = 0;
15465   p->laf.pAllPage = 0;
15466   p->laf.pPageData = 0;
15467   sqlite3_free(p->laf.apVal);
15468   p->laf.apVal = 0;
15469 }
15470 
15471 /*
15472 ** Free all resources allocated as part of sqlite3_recover_step() calls.
15473 */
15474 static void recoverFinalCleanup(sqlite3_recover *p){
15475   RecoverTable *pTab = 0;
15476   RecoverTable *pNext = 0;
15477 
15478   recoverWriteDataCleanup(p);
15479   recoverLostAndFoundCleanup(p);
15480 
15481   for(pTab=p->pTblList; pTab; pTab=pNext){
15482     pNext = pTab->pNext;
15483     sqlite3_free(pTab);
15484   }
15485   p->pTblList = 0;
15486   sqlite3_finalize(p->pGetPage);
15487   p->pGetPage = 0;
15488   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
15489 
15490   {
15491 #ifndef NDEBUG
15492     int res =
15493 #endif
15494        sqlite3_close(p->dbOut);
15495     assert( res==SQLITE_OK );
15496   }
15497   p->dbOut = 0;
15498 }
15499 
15500 /*
15501 ** Decode and return an unsigned 16-bit big-endian integer value from
15502 ** buffer a[].
15503 */
15504 static u32 recoverGetU16(const u8 *a){
15505   return (((u32)a[0])<<8) + ((u32)a[1]);
15506 }
15507 
15508 /*
15509 ** Decode and return an unsigned 32-bit big-endian integer value from
15510 ** buffer a[].
15511 */
15512 static u32 recoverGetU32(const u8 *a){
15513   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
15514 }
15515 
15516 /*
15517 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
15518 ** and return the number of bytes consumed.
15519 */
15520 static int recoverGetVarint(const u8 *a, i64 *pVal){
15521   sqlite3_uint64 u = 0;
15522   int i;
15523   for(i=0; i<8; i++){
15524     u = (u<<7) + (a[i]&0x7f);
15525     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
15526   }
15527   u = (u<<8) + (a[i]&0xff);
15528   *pVal = (sqlite3_int64)u;
15529   return 9;
15530 }
15531 
15532 /*
15533 ** The second argument points to a buffer n bytes in size. If this buffer
15534 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
15535 ** return the page-size in bytes. Otherwise, if the buffer does not
15536 ** appear to contain a well-formed b-tree page, return 0.
15537 */
15538 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
15539   u8 *aUsed = aTmp;
15540   int nFrag = 0;
15541   int nActual = 0;
15542   int iFree = 0;
15543   int nCell = 0;                  /* Number of cells on page */
15544   int iCellOff = 0;               /* Offset of cell array in page */
15545   int iContent = 0;
15546   int eType = 0;
15547   int ii = 0;
15548 
15549   eType = (int)a[0];
15550   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
15551 
15552   iFree = (int)recoverGetU16(&a[1]);
15553   nCell = (int)recoverGetU16(&a[3]);
15554   iContent = (int)recoverGetU16(&a[5]);
15555   if( iContent==0 ) iContent = 65536;
15556   nFrag = (int)a[7];
15557 
15558   if( iContent>n ) return 0;
15559 
15560   memset(aUsed, 0, n);
15561   memset(aUsed, 0xFF, iContent);
15562 
15563   /* Follow the free-list. This is the same format for all b-tree pages. */
15564   if( iFree && iFree<=iContent ) return 0;
15565   while( iFree ){
15566     int iNext = 0;
15567     int nByte = 0;
15568     if( iFree>(n-4) ) return 0;
15569     iNext = recoverGetU16(&a[iFree]);
15570     nByte = recoverGetU16(&a[iFree+2]);
15571     if( iFree+nByte>n ) return 0;
15572     if( iNext && iNext<iFree+nByte ) return 0;
15573     memset(&aUsed[iFree], 0xFF, nByte);
15574     iFree = iNext;
15575   }
15576 
15577   /* Run through the cells */
15578   if( eType==0x02 || eType==0x05 ){
15579     iCellOff = 12;
15580   }else{
15581     iCellOff = 8;
15582   }
15583   if( (iCellOff + 2*nCell)>iContent ) return 0;
15584   for(ii=0; ii<nCell; ii++){
15585     int iByte;
15586     i64 nPayload = 0;
15587     int nByte = 0;
15588     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
15589     if( iOff<iContent || iOff>n ){
15590       return 0;
15591     }
15592     if( eType==0x05 || eType==0x02 ) nByte += 4;
15593     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
15594     if( eType==0x0D ){
15595       i64 dummy = 0;
15596       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
15597     }
15598     if( eType!=0x05 ){
15599       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
15600       int M = ((n-12)*32/255)-23;
15601       int K = M+((nPayload-M)%(n-4));
15602 
15603       if( nPayload<X ){
15604         nByte += nPayload;
15605       }else if( K<=X ){
15606         nByte += K+4;
15607       }else{
15608         nByte += M+4;
15609       }
15610     }
15611 
15612     if( iOff+nByte>n ){
15613       return 0;
15614     }
15615     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
15616       if( aUsed[iByte]!=0 ){
15617         return 0;
15618       }
15619       aUsed[iByte] = 0xFF;
15620     }
15621   }
15622 
15623   nActual = 0;
15624   for(ii=0; ii<n; ii++){
15625     if( aUsed[ii]==0 ) nActual++;
15626   }
15627   return (nActual==nFrag);
15628 }
15629 
15630 
15631 static int recoverVfsClose(sqlite3_file*);
15632 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
15633 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
15634 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
15635 static int recoverVfsSync(sqlite3_file*, int flags);
15636 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
15637 static int recoverVfsLock(sqlite3_file*, int);
15638 static int recoverVfsUnlock(sqlite3_file*, int);
15639 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
15640 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
15641 static int recoverVfsSectorSize(sqlite3_file*);
15642 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
15643 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
15644 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
15645 static void recoverVfsShmBarrier(sqlite3_file*);
15646 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
15647 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
15648 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
15649 
15650 static sqlite3_io_methods recover_methods = {
15651   2, /* iVersion */
15652   recoverVfsClose,
15653   recoverVfsRead,
15654   recoverVfsWrite,
15655   recoverVfsTruncate,
15656   recoverVfsSync,
15657   recoverVfsFileSize,
15658   recoverVfsLock,
15659   recoverVfsUnlock,
15660   recoverVfsCheckReservedLock,
15661   recoverVfsFileControl,
15662   recoverVfsSectorSize,
15663   recoverVfsDeviceCharacteristics,
15664   recoverVfsShmMap,
15665   recoverVfsShmLock,
15666   recoverVfsShmBarrier,
15667   recoverVfsShmUnmap,
15668   recoverVfsFetch,
15669   recoverVfsUnfetch
15670 };
15671 
15672 static int recoverVfsClose(sqlite3_file *pFd){
15673   assert( pFd->pMethods!=&recover_methods );
15674   return pFd->pMethods->xClose(pFd);
15675 }
15676 
15677 /*
15678 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
15679 */
15680 static void recoverPutU16(u8 *a, u32 v){
15681   a[0] = (v>>8) & 0x00FF;
15682   a[1] = (v>>0) & 0x00FF;
15683 }
15684 
15685 /*
15686 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
15687 */
15688 static void recoverPutU32(u8 *a, u32 v){
15689   a[0] = (v>>24) & 0x00FF;
15690   a[1] = (v>>16) & 0x00FF;
15691   a[2] = (v>>8) & 0x00FF;
15692   a[3] = (v>>0) & 0x00FF;
15693 }
15694 
15695 /*
15696 ** Detect the page-size of the database opened by file-handle pFd by
15697 ** searching the first part of the file for a well-formed SQLite b-tree
15698 ** page. If parameter nReserve is non-zero, then as well as searching for
15699 ** a b-tree page with zero reserved bytes, this function searches for one
15700 ** with nReserve reserved bytes at the end of it.
15701 **
15702 ** If successful, set variable p->detected_pgsz to the detected page-size
15703 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
15704 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
15705 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
15706 ** is returned. The final value of p->detected_pgsz is undefined in this
15707 ** case.
15708 */
15709 static int recoverVfsDetectPagesize(
15710   sqlite3_recover *p,             /* Recover handle */
15711   sqlite3_file *pFd,              /* File-handle open on input database */
15712   u32 nReserve,                   /* Possible nReserve value */
15713   i64 nSz                         /* Size of database file in bytes */
15714 ){
15715   int rc = SQLITE_OK;
15716   const int nMin = 512;
15717   const int nMax = 65536;
15718   const int nMaxBlk = 4;
15719   u32 pgsz = 0;
15720   int iBlk = 0;
15721   u8 *aPg = 0;
15722   u8 *aTmp = 0;
15723   int nBlk = 0;
15724 
15725   aPg = (u8*)sqlite3_malloc(2*nMax);
15726   if( aPg==0 ) return SQLITE_NOMEM;
15727   aTmp = &aPg[nMax];
15728 
15729   nBlk = (nSz+nMax-1)/nMax;
15730   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
15731 
15732   do {
15733     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
15734       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
15735       memset(aPg, 0, nMax);
15736       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
15737       if( rc==SQLITE_OK ){
15738         int pgsz2;
15739         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
15740           int iOff;
15741           for(iOff=0; iOff<nMax; iOff+=pgsz2){
15742             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
15743               pgsz = pgsz2;
15744               break;
15745             }
15746           }
15747         }
15748       }
15749     }
15750     if( pgsz>(u32)p->detected_pgsz ){
15751       p->detected_pgsz = pgsz;
15752       p->nReserve = nReserve;
15753     }
15754     if( nReserve==0 ) break;
15755     nReserve = 0;
15756   }while( 1 );
15757 
15758   p->detected_pgsz = pgsz;
15759   sqlite3_free(aPg);
15760   return rc;
15761 }
15762 
15763 /*
15764 ** The xRead() method of the wrapper VFS. This is used to intercept calls
15765 ** to read page 1 of the input database.
15766 */
15767 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
15768   int rc = SQLITE_OK;
15769   if( pFd->pMethods==&recover_methods ){
15770     pFd->pMethods = recover_g.pMethods;
15771     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
15772     if( nByte==16 ){
15773       sqlite3_randomness(16, aBuf);
15774     }else
15775     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
15776       /* Ensure that the database has a valid header file. The only fields
15777       ** that really matter to recovery are:
15778       **
15779       **   + Database page size (16-bits at offset 16)
15780       **   + Size of db in pages (32-bits at offset 28)
15781       **   + Database encoding (32-bits at offset 56)
15782       **
15783       ** Also preserved are:
15784       **
15785       **   + first freelist page (32-bits at offset 32)
15786       **   + size of freelist (32-bits at offset 36)
15787       **   + the wal-mode flags (16-bits at offset 18)
15788       **
15789       ** We also try to preserve the auto-vacuum, incr-value, user-version
15790       ** and application-id fields - all 32 bit quantities at offsets
15791       ** 52, 60, 64 and 68. All other fields are set to known good values.
15792       **
15793       ** Byte offset 105 should also contain the page-size as a 16-bit
15794       ** integer.
15795       */
15796       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
15797       u8 aHdr[108] = {
15798         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
15799         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
15800         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
15801         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
15802         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
15803         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
15804         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
15805         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
15806         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
15807         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
15808         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
15809         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
15810         0x00, 0x2e, 0x5b, 0x30,
15811 
15812         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
15813       };
15814       u8 *a = (u8*)aBuf;
15815 
15816       u32 pgsz = recoverGetU16(&a[16]);
15817       u32 nReserve = a[20];
15818       u32 enc = recoverGetU32(&a[56]);
15819       u32 dbsz = 0;
15820       i64 dbFileSize = 0;
15821       int ii;
15822       sqlite3_recover *p = recover_g.p;
15823 
15824       if( pgsz==0x01 ) pgsz = 65536;
15825       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
15826 
15827       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
15828         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
15829       }
15830       if( p->detected_pgsz ){
15831         pgsz = p->detected_pgsz;
15832         nReserve = p->nReserve;
15833       }
15834 
15835       if( pgsz ){
15836         dbsz = dbFileSize / pgsz;
15837       }
15838       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
15839         enc = SQLITE_UTF8;
15840       }
15841 
15842       sqlite3_free(p->pPage1Cache);
15843       p->pPage1Cache = 0;
15844       p->pPage1Disk = 0;
15845 
15846       p->pgsz = nByte;
15847       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
15848       if( p->pPage1Cache ){
15849         p->pPage1Disk = &p->pPage1Cache[nByte];
15850         memcpy(p->pPage1Disk, aBuf, nByte);
15851         aHdr[18] = a[18];
15852         aHdr[19] = a[19];
15853         recoverPutU32(&aHdr[28], dbsz);
15854         recoverPutU32(&aHdr[56], enc);
15855         recoverPutU16(&aHdr[105], pgsz-nReserve);
15856         if( pgsz==65536 ) pgsz = 1;
15857         recoverPutU16(&aHdr[16], pgsz);
15858         aHdr[20] = nReserve;
15859         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
15860           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
15861         }
15862         memcpy(aBuf, aHdr, sizeof(aHdr));
15863         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
15864 
15865         memcpy(p->pPage1Cache, aBuf, nByte);
15866       }else{
15867         rc = p->errCode;
15868       }
15869 
15870     }
15871     pFd->pMethods = &recover_methods;
15872   }else{
15873     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
15874   }
15875   return rc;
15876 }
15877 
15878 /*
15879 ** Used to make sqlite3_io_methods wrapper methods less verbose.
15880 */
15881 #define RECOVER_VFS_WRAPPER(code)                         \
15882   int rc = SQLITE_OK;                                     \
15883   if( pFd->pMethods==&recover_methods ){                  \
15884     pFd->pMethods = recover_g.pMethods;                   \
15885     rc = code;                                            \
15886     pFd->pMethods = &recover_methods;                     \
15887   }else{                                                  \
15888     rc = code;                                            \
15889   }                                                       \
15890   return rc;
15891 
15892 /*
15893 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
15894 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
15895 ** method on the lower level VFS, then reinstall the wrapper before returning.
15896 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
15897 */
15898 static int recoverVfsWrite(
15899   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
15900 ){
15901   RECOVER_VFS_WRAPPER (
15902       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
15903   );
15904 }
15905 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
15906   RECOVER_VFS_WRAPPER (
15907       pFd->pMethods->xTruncate(pFd, size)
15908   );
15909 }
15910 static int recoverVfsSync(sqlite3_file *pFd, int flags){
15911   RECOVER_VFS_WRAPPER (
15912       pFd->pMethods->xSync(pFd, flags)
15913   );
15914 }
15915 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
15916   RECOVER_VFS_WRAPPER (
15917       pFd->pMethods->xFileSize(pFd, pSize)
15918   );
15919 }
15920 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
15921   RECOVER_VFS_WRAPPER (
15922       pFd->pMethods->xLock(pFd, eLock)
15923   );
15924 }
15925 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
15926   RECOVER_VFS_WRAPPER (
15927       pFd->pMethods->xUnlock(pFd, eLock)
15928   );
15929 }
15930 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
15931   RECOVER_VFS_WRAPPER (
15932       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
15933   );
15934 }
15935 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
15936   RECOVER_VFS_WRAPPER (
15937     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
15938   );
15939 }
15940 static int recoverVfsSectorSize(sqlite3_file *pFd){
15941   RECOVER_VFS_WRAPPER (
15942       pFd->pMethods->xSectorSize(pFd)
15943   );
15944 }
15945 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
15946   RECOVER_VFS_WRAPPER (
15947       pFd->pMethods->xDeviceCharacteristics(pFd)
15948   );
15949 }
15950 static int recoverVfsShmMap(
15951   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
15952 ){
15953   RECOVER_VFS_WRAPPER (
15954       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
15955   );
15956 }
15957 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
15958   RECOVER_VFS_WRAPPER (
15959       pFd->pMethods->xShmLock(pFd, offset, n, flags)
15960   );
15961 }
15962 static void recoverVfsShmBarrier(sqlite3_file *pFd){
15963   if( pFd->pMethods==&recover_methods ){
15964     pFd->pMethods = recover_g.pMethods;
15965     pFd->pMethods->xShmBarrier(pFd);
15966     pFd->pMethods = &recover_methods;
15967   }else{
15968     pFd->pMethods->xShmBarrier(pFd);
15969   }
15970 }
15971 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
15972   RECOVER_VFS_WRAPPER (
15973       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
15974   );
15975 }
15976 
15977 static int recoverVfsFetch(
15978   sqlite3_file *pFd,
15979   sqlite3_int64 iOff,
15980   int iAmt,
15981   void **pp
15982 ){
15983   (void)pFd;
15984   (void)iOff;
15985   (void)iAmt;
15986   *pp = 0;
15987   return SQLITE_OK;
15988 }
15989 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
15990   (void)pFd;
15991   (void)iOff;
15992   (void)p;
15993   return SQLITE_OK;
15994 }
15995 
15996 /*
15997 ** Install the VFS wrapper around the file-descriptor open on the input
15998 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
15999 ** when this function is called.
16000 */
16001 static void recoverInstallWrapper(sqlite3_recover *p){
16002   sqlite3_file *pFd = 0;
16003   assert( recover_g.pMethods==0 );
16004   recoverAssertMutexHeld();
16005   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
16006   assert( pFd==0 || pFd->pMethods!=&recover_methods );
16007   if( pFd && pFd->pMethods ){
16008     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
16009     recover_g.pMethods = pFd->pMethods;
16010     recover_g.p = p;
16011     recover_methods.iVersion = iVersion;
16012     pFd->pMethods = &recover_methods;
16013   }
16014 }
16015 
16016 /*
16017 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
16018 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
16019 ** held when this function is called.
16020 */
16021 static void recoverUninstallWrapper(sqlite3_recover *p){
16022   sqlite3_file *pFd = 0;
16023   recoverAssertMutexHeld();
16024   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
16025   if( pFd && pFd->pMethods ){
16026     pFd->pMethods = recover_g.pMethods;
16027     recover_g.pMethods = 0;
16028     recover_g.p = 0;
16029   }
16030 }
16031 
16032 /*
16033 ** This function does the work of a single sqlite3_recover_step() call. It
16034 ** is guaranteed that the handle is not in an error state when this
16035 ** function is called.
16036 */
16037 static void recoverStep(sqlite3_recover *p){
16038   assert( p && p->errCode==SQLITE_OK );
16039   switch( p->eState ){
16040     case RECOVER_STATE_INIT:
16041       /* This is the very first call to sqlite3_recover_step() on this object.
16042       */
16043       recoverSqlCallback(p, "BEGIN");
16044       recoverSqlCallback(p, "PRAGMA writable_schema = on");
16045 
16046       recoverEnterMutex();
16047       recoverInstallWrapper(p);
16048 
16049       /* Open the output database. And register required virtual tables and
16050       ** user functions with the new handle. */
16051       recoverOpenOutput(p);
16052 
16053       /* Open transactions on both the input and output databases. */
16054       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
16055       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
16056       recoverExec(p, p->dbIn, "BEGIN");
16057       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
16058       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
16059       recoverTransferSettings(p);
16060       recoverOpenRecovery(p);
16061       recoverCacheSchema(p);
16062 
16063       recoverUninstallWrapper(p);
16064       recoverLeaveMutex();
16065 
16066       recoverExec(p, p->dbOut, "BEGIN");
16067 
16068       recoverWriteSchema1(p);
16069       p->eState = RECOVER_STATE_WRITING;
16070       break;
16071 
16072     case RECOVER_STATE_WRITING: {
16073       if( p->w1.pTbls==0 ){
16074         recoverWriteDataInit(p);
16075       }
16076       if( SQLITE_DONE==recoverWriteDataStep(p) ){
16077         recoverWriteDataCleanup(p);
16078         if( p->zLostAndFound ){
16079           p->eState = RECOVER_STATE_LOSTANDFOUND1;
16080         }else{
16081           p->eState = RECOVER_STATE_SCHEMA2;
16082         }
16083       }
16084       break;
16085     }
16086 
16087     case RECOVER_STATE_LOSTANDFOUND1: {
16088       if( p->laf.pUsed==0 ){
16089         recoverLostAndFound1Init(p);
16090       }
16091       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
16092         p->eState = RECOVER_STATE_LOSTANDFOUND2;
16093       }
16094       break;
16095     }
16096     case RECOVER_STATE_LOSTANDFOUND2: {
16097       if( p->laf.pAllAndParent==0 ){
16098         recoverLostAndFound2Init(p);
16099       }
16100       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
16101         p->eState = RECOVER_STATE_LOSTANDFOUND3;
16102       }
16103       break;
16104     }
16105 
16106     case RECOVER_STATE_LOSTANDFOUND3: {
16107       if( p->laf.pInsert==0 ){
16108         recoverLostAndFound3Init(p);
16109       }
16110       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
16111         p->eState = RECOVER_STATE_SCHEMA2;
16112       }
16113       break;
16114     }
16115 
16116     case RECOVER_STATE_SCHEMA2: {
16117       int rc = SQLITE_OK;
16118 
16119       recoverWriteSchema2(p);
16120       p->eState = RECOVER_STATE_DONE;
16121 
16122       /* If no error has occurred, commit the write transaction on the output
16123       ** database. Regardless of whether or not an error has occurred, make
16124       ** an attempt to end the read transaction on the input database.  */
16125       recoverExec(p, p->dbOut, "COMMIT");
16126       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
16127       if( p->errCode==SQLITE_OK ) p->errCode = rc;
16128 
16129       recoverSqlCallback(p, "PRAGMA writable_schema = off");
16130       recoverSqlCallback(p, "COMMIT");
16131       p->eState = RECOVER_STATE_DONE;
16132       recoverFinalCleanup(p);
16133       break;
16134     };
16135 
16136     case RECOVER_STATE_DONE: {
16137       /* no-op */
16138       break;
16139     };
16140   }
16141 }
16142 
16143 
16144 /*
16145 ** This is a worker function that does the heavy lifting for both init
16146 ** functions:
16147 **
16148 **     sqlite3_recover_init()
16149 **     sqlite3_recover_init_sql()
16150 **
16151 ** All this function does is allocate space for the recover handle and
16152 ** take copies of the input parameters. All the real work is done within
16153 ** sqlite3_recover_run().
16154 */
16155 sqlite3_recover *recoverInit(
16156   sqlite3* db,
16157   const char *zDb,
16158   const char *zUri,               /* Output URI for _recover_init() */
16159   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
16160   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
16161 ){
16162   sqlite3_recover *pRet = 0;
16163   int nDb = 0;
16164   int nUri = 0;
16165   int nByte = 0;
16166 
16167   if( zDb==0 ){ zDb = "main"; }
16168 
16169   nDb = recoverStrlen(zDb);
16170   nUri = recoverStrlen(zUri);
16171 
16172   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
16173   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
16174   if( pRet ){
16175     memset(pRet, 0, nByte);
16176     pRet->dbIn = db;
16177     pRet->zDb = (char*)&pRet[1];
16178     pRet->zUri = &pRet->zDb[nDb+1];
16179     memcpy(pRet->zDb, zDb, nDb);
16180     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
16181     pRet->xSql = xSql;
16182     pRet->pSqlCtx = pSqlCtx;
16183     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
16184   }
16185 
16186   return pRet;
16187 }
16188 
16189 /*
16190 ** Initialize a recovery handle that creates a new database containing
16191 ** the recovered data.
16192 */
16193 sqlite3_recover *sqlite3_recover_init(
16194   sqlite3* db,
16195   const char *zDb,
16196   const char *zUri
16197 ){
16198   return recoverInit(db, zDb, zUri, 0, 0);
16199 }
16200 
16201 /*
16202 ** Initialize a recovery handle that returns recovered data in the
16203 ** form of SQL statements via a callback.
16204 */
16205 sqlite3_recover *sqlite3_recover_init_sql(
16206   sqlite3* db,
16207   const char *zDb,
16208   int (*xSql)(void*, const char*),
16209   void *pSqlCtx
16210 ){
16211   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
16212 }
16213 
16214 /*
16215 ** Return the handle error message, if any.
16216 */
16217 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
16218   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
16219 }
16220 
16221 /*
16222 ** Return the handle error code.
16223 */
16224 int sqlite3_recover_errcode(sqlite3_recover *p){
16225   return p ? p->errCode : SQLITE_NOMEM;
16226 }
16227 
16228 /*
16229 ** Configure the handle.
16230 */
16231 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
16232   int rc = SQLITE_OK;
16233   if( p==0 ){
16234     rc = SQLITE_NOMEM;
16235   }else if( p->eState!=RECOVER_STATE_INIT ){
16236     rc = SQLITE_MISUSE;
16237   }else{
16238     switch( op ){
16239       case 789:
16240         /* This undocumented magic configuration option is used to set the
16241         ** name of the auxiliary database that is ATTACH-ed to the database
16242         ** connection and used to hold state information during the
16243         ** recovery process.  This option is for debugging use only and
16244         ** is subject to change or removal at any time. */
16245         sqlite3_free(p->zStateDb);
16246         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
16247         break;
16248 
16249       case SQLITE_RECOVER_LOST_AND_FOUND: {
16250         const char *zArg = (const char*)pArg;
16251         sqlite3_free(p->zLostAndFound);
16252         if( zArg ){
16253           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
16254         }else{
16255           p->zLostAndFound = 0;
16256         }
16257         break;
16258       }
16259 
16260       case SQLITE_RECOVER_FREELIST_CORRUPT:
16261         p->bFreelistCorrupt = *(int*)pArg;
16262         break;
16263 
16264       case SQLITE_RECOVER_ROWIDS:
16265         p->bRecoverRowid = *(int*)pArg;
16266         break;
16267 
16268       case SQLITE_RECOVER_SLOWINDEXES:
16269         p->bSlowIndexes = *(int*)pArg;
16270         break;
16271 
16272       default:
16273         rc = SQLITE_NOTFOUND;
16274         break;
16275     }
16276   }
16277 
16278   return rc;
16279 }
16280 
16281 /*
16282 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
16283 ** no error has occurred but database recovery is not finished, SQLITE_DONE
16284 ** if database recovery has been successfully completed, or an SQLite
16285 ** error code if an error has occurred.
16286 */
16287 int sqlite3_recover_step(sqlite3_recover *p){
16288   if( p==0 ) return SQLITE_NOMEM;
16289   if( p->errCode==SQLITE_OK ) recoverStep(p);
16290   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
16291     return SQLITE_DONE;
16292   }
16293   return p->errCode;
16294 }
16295 
16296 /*
16297 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
16298 ** else an SQLite error code.
16299 */
16300 int sqlite3_recover_run(sqlite3_recover *p){
16301   while( SQLITE_OK==sqlite3_recover_step(p) );
16302   return sqlite3_recover_errcode(p);
16303 }
16304 
16305 
16306 /*
16307 ** Free all resources associated with the recover handle passed as the only
16308 ** argument. The results of using a handle with any sqlite3_recover_**
16309 ** API function after it has been passed to this function are undefined.
16310 **
16311 ** A copy of the value returned by the first call made to sqlite3_recover_run()
16312 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
16313 ** not been called on this handle.
16314 */
16315 int sqlite3_recover_finish(sqlite3_recover *p){
16316   int rc;
16317   if( p==0 ){
16318     rc = SQLITE_NOMEM;
16319   }else{
16320     recoverFinalCleanup(p);
16321     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
16322       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
16323       if( p->errCode==SQLITE_OK ) p->errCode = rc;
16324     }
16325     rc = p->errCode;
16326     sqlite3_free(p->zErrMsg);
16327     sqlite3_free(p->zStateDb);
16328     sqlite3_free(p->zLostAndFound);
16329     sqlite3_free(p->pPage1Cache);
16330     sqlite3_free(p);
16331   }
16332   return rc;
16333 }
16334 
16335 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
16336 
16337 /************************* End ../ext/recover/sqlite3recover.c ********************/
16338 # endif
16339 #endif
16340 #ifdef SQLITE_SHELL_EXTSRC
16341 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
16342 #endif
16343 
16344 #if defined(SQLITE_ENABLE_SESSION)
16345 /*
16346 ** State information for a single open session
16347 */
16348 typedef struct OpenSession OpenSession;
16349 struct OpenSession {
16350   char *zName;             /* Symbolic name for this session */
16351   int nFilter;             /* Number of xFilter rejection GLOB patterns */
16352   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
16353   sqlite3_session *p;      /* The open session */
16354 };
16355 #endif
16356 
16357 typedef struct ExpertInfo ExpertInfo;
16358 struct ExpertInfo {
16359   sqlite3expert *pExpert;
16360   int bVerbose;
16361 };
16362 
16363 /* A single line in the EQP output */
16364 typedef struct EQPGraphRow EQPGraphRow;
16365 struct EQPGraphRow {
16366   int iEqpId;           /* ID for this row */
16367   int iParentId;        /* ID of the parent row */
16368   EQPGraphRow *pNext;   /* Next row in sequence */
16369   char zText[1];        /* Text to display for this row */
16370 };
16371 
16372 /* All EQP output is collected into an instance of the following */
16373 typedef struct EQPGraph EQPGraph;
16374 struct EQPGraph {
16375   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
16376   EQPGraphRow *pLast;   /* Last element of the pRow list */
16377   char zPrefix[100];    /* Graph prefix */
16378 };
16379 
16380 /* Parameters affecting columnar mode result display (defaulting together) */
16381 typedef struct ColModeOpts {
16382   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
16383   u8 bQuote;            /* Quote results for .mode box and table */
16384   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
16385 } ColModeOpts;
16386 #define ColModeOpts_default { 60, 0, 0 }
16387 #define ColModeOpts_default_qbox { 60, 1, 0 }
16388 
16389 /*
16390 ** State information about the database connection is contained in an
16391 ** instance of the following structure.
16392 */
16393 typedef struct ShellState ShellState;
16394 struct ShellState {
16395   sqlite3 *db;           /* The database */
16396   u8 autoExplain;        /* Automatically turn on .explain mode */
16397   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
16398   u8 autoEQPtest;        /* autoEQP is in test mode */
16399   u8 autoEQPtrace;       /* autoEQP is in trace mode */
16400   u8 scanstatsOn;        /* True to display scan stats before each finalize */
16401   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
16402   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
16403   u8 nEqpLevel;          /* Depth of the EQP output graph */
16404   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
16405   u8 bSafeMode;          /* True to prohibit unsafe operations */
16406   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
16407   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
16408   unsigned statsOn;      /* True to display memory stats before each finalize */
16409   unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
16410   int inputNesting;      /* Track nesting level of .read and other redirects */
16411   int outCount;          /* Revert to stdout when reaching zero */
16412   int cnt;               /* Number of records displayed so far */
16413   int lineno;            /* Line number of last line read from in */
16414   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
16415   FILE *in;              /* Read commands from this stream */
16416   FILE *out;             /* Write results here */
16417   FILE *traceOut;        /* Output for sqlite3_trace() */
16418   int nErr;              /* Number of errors seen */
16419   int mode;              /* An output mode setting */
16420   int modePrior;         /* Saved mode */
16421   int cMode;             /* temporary output mode for the current query */
16422   int normalMode;        /* Output mode before ".explain on" */
16423   int writableSchema;    /* True if PRAGMA writable_schema=ON */
16424   int showHeader;        /* True to show column names in List or Column mode */
16425   int nCheck;            /* Number of ".check" commands run */
16426   unsigned nProgress;    /* Number of progress callbacks encountered */
16427   unsigned mxProgress;   /* Maximum progress callbacks before failing */
16428   unsigned flgProgress;  /* Flags for the progress callback */
16429   unsigned shellFlgs;    /* Various flags */
16430   unsigned priorShFlgs;  /* Saved copy of flags */
16431   sqlite3_int64 szMax;   /* --maxsize argument to .open */
16432   char *zDestTable;      /* Name of destination table when MODE_Insert */
16433   char *zTempFile;       /* Temporary file that might need deleting */
16434   char zTestcase[30];    /* Name of current test case */
16435   char colSeparator[20]; /* Column separator character for several modes */
16436   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
16437   char colSepPrior[20];  /* Saved column separator */
16438   char rowSepPrior[20];  /* Saved row separator */
16439   int *colWidth;         /* Requested width of each column in columnar modes */
16440   int *actualWidth;      /* Actual width of each column */
16441   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
16442   char nullValue[20];    /* The text to print when a NULL comes back from
16443                          ** the database */
16444   char outfile[FILENAME_MAX]; /* Filename for *out */
16445   sqlite3_stmt *pStmt;   /* Current statement if any. */
16446   FILE *pLog;            /* Write log output here */
16447   struct AuxDb {         /* Storage space for auxiliary database connections */
16448     sqlite3 *db;               /* Connection pointer */
16449     const char *zDbFilename;   /* Filename used to open the connection */
16450     char *zFreeOnClose;        /* Free this memory allocation on close */
16451 #if defined(SQLITE_ENABLE_SESSION)
16452     int nSession;              /* Number of active sessions */
16453     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
16454 #endif
16455   } aAuxDb[5],           /* Array of all database connections */
16456     *pAuxDb;             /* Currently active database connection */
16457   int *aiIndent;         /* Array of indents used in MODE_Explain */
16458   int nIndent;           /* Size of array aiIndent[] */
16459   int iIndent;           /* Index of current op in aiIndent[] */
16460   char *zNonce;          /* Nonce for temporary safe-mode excapes */
16461   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
16462   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
16463 #ifdef SQLITE_SHELL_FIDDLE
16464   struct {
16465     const char * zInput; /* Input string from wasm/JS proxy */
16466     const char * zPos;   /* Cursor pos into zInput */
16467     const char * zDefaultDbName; /* Default name for db file */
16468   } wasm;
16469 #endif
16470 };
16471 
16472 #ifdef SQLITE_SHELL_FIDDLE
16473 static ShellState shellState;
16474 #endif
16475 
16476 
16477 /* Allowed values for ShellState.autoEQP
16478 */
16479 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
16480 #define AUTOEQP_on       1           /* Automatic EQP is on */
16481 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
16482 #define AUTOEQP_full     3           /* Show full EXPLAIN */
16483 
16484 /* Allowed values for ShellState.openMode
16485 */
16486 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
16487 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
16488 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
16489 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
16490 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
16491 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
16492 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
16493 
16494 /* Allowed values for ShellState.eTraceType
16495 */
16496 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
16497 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
16498 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
16499 
16500 /* Bits in the ShellState.flgProgress variable */
16501 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
16502 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
16503                                    ** callback limit is reached, and for each
16504                                    ** top-level SQL statement */
16505 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
16506 
16507 /*
16508 ** These are the allowed shellFlgs values
16509 */
16510 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
16511 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
16512 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
16513 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
16514 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
16515 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
16516 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
16517 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
16518 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
16519 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
16520 
16521 /*
16522 ** Macros for testing and setting shellFlgs
16523 */
16524 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
16525 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
16526 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
16527 
16528 /*
16529 ** These are the allowed modes.
16530 */
16531 #define MODE_Line     0  /* One column per line.  Blank line between records */
16532 #define MODE_Column   1  /* One record per line in neat columns */
16533 #define MODE_List     2  /* One record per line with a separator */
16534 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
16535 #define MODE_Html     4  /* Generate an XHTML table */
16536 #define MODE_Insert   5  /* Generate SQL "insert" statements */
16537 #define MODE_Quote    6  /* Quote values as for SQL */
16538 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
16539 #define MODE_Csv      8  /* Quote strings, numbers are plain */
16540 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
16541 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
16542 #define MODE_Pretty  11  /* Pretty-print schemas */
16543 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
16544 #define MODE_Json    13  /* Output JSON */
16545 #define MODE_Markdown 14 /* Markdown formatting */
16546 #define MODE_Table   15  /* MySQL-style table formatting */
16547 #define MODE_Box     16  /* Unicode box-drawing characters */
16548 #define MODE_Count   17  /* Output only a count of the rows of output */
16549 #define MODE_Off     18  /* No query output shown */
16550 
16551 static const char *modeDescr[] = {
16552   "line",
16553   "column",
16554   "list",
16555   "semi",
16556   "html",
16557   "insert",
16558   "quote",
16559   "tcl",
16560   "csv",
16561   "explain",
16562   "ascii",
16563   "prettyprint",
16564   "eqp",
16565   "json",
16566   "markdown",
16567   "table",
16568   "box",
16569   "count",
16570   "off"
16571 };
16572 
16573 /*
16574 ** These are the column/row/line separators used by the various
16575 ** import/export modes.
16576 */
16577 #define SEP_Column    "|"
16578 #define SEP_Row       "\n"
16579 #define SEP_Tab       "\t"
16580 #define SEP_Space     " "
16581 #define SEP_Comma     ","
16582 #define SEP_CrLf      "\r\n"
16583 #define SEP_Unit      "\x1F"
16584 #define SEP_Record    "\x1E"
16585 
16586 /*
16587 ** Limit input nesting via .read or any other input redirect.
16588 ** It's not too expensive, so a generous allowance can be made.
16589 */
16590 #define MAX_INPUT_NESTING 25
16591 
16592 /*
16593 ** A callback for the sqlite3_log() interface.
16594 */
16595 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
16596   ShellState *p = (ShellState*)pArg;
16597   if( p->pLog==0 ) return;
16598   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
16599   fflush(p->pLog);
16600 }
16601 
16602 /*
16603 ** SQL function:  shell_putsnl(X)
16604 **
16605 ** Write the text X to the screen (or whatever output is being directed)
16606 ** adding a newline at the end, and then return X.
16607 */
16608 static void shellPutsFunc(
16609   sqlite3_context *pCtx,
16610   int nVal,
16611   sqlite3_value **apVal
16612 ){
16613   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
16614   (void)nVal;
16615   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
16616   sqlite3_result_value(pCtx, apVal[0]);
16617 }
16618 
16619 /*
16620 ** If in safe mode, print an error message described by the arguments
16621 ** and exit immediately.
16622 */
16623 static void failIfSafeMode(
16624   ShellState *p,
16625   const char *zErrMsg,
16626   ...
16627 ){
16628   if( p->bSafeMode ){
16629     va_list ap;
16630     char *zMsg;
16631     va_start(ap, zErrMsg);
16632     zMsg = sqlite3_vmprintf(zErrMsg, ap);
16633     va_end(ap);
16634     raw_printf(stderr, "line %d: ", p->lineno);
16635     utf8_printf(stderr, "%s\n", zMsg);
16636     exit(1);
16637   }
16638 }
16639 
16640 /*
16641 ** SQL function:   edit(VALUE)
16642 **                 edit(VALUE,EDITOR)
16643 **
16644 ** These steps:
16645 **
16646 **     (1) Write VALUE into a temporary file.
16647 **     (2) Run program EDITOR on that temporary file.
16648 **     (3) Read the temporary file back and return its content as the result.
16649 **     (4) Delete the temporary file
16650 **
16651 ** If the EDITOR argument is omitted, use the value in the VISUAL
16652 ** environment variable.  If still there is no EDITOR, through an error.
16653 **
16654 ** Also throw an error if the EDITOR program returns a non-zero exit code.
16655 */
16656 #ifndef SQLITE_NOHAVE_SYSTEM
16657 static void editFunc(
16658   sqlite3_context *context,
16659   int argc,
16660   sqlite3_value **argv
16661 ){
16662   const char *zEditor;
16663   char *zTempFile = 0;
16664   sqlite3 *db;
16665   char *zCmd = 0;
16666   int bBin;
16667   int rc;
16668   int hasCRNL = 0;
16669   FILE *f = 0;
16670   sqlite3_int64 sz;
16671   sqlite3_int64 x;
16672   unsigned char *p = 0;
16673 
16674   if( argc==2 ){
16675     zEditor = (const char*)sqlite3_value_text(argv[1]);
16676   }else{
16677     zEditor = getenv("VISUAL");
16678   }
16679   if( zEditor==0 ){
16680     sqlite3_result_error(context, "no editor for edit()", -1);
16681     return;
16682   }
16683   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
16684     sqlite3_result_error(context, "NULL input to edit()", -1);
16685     return;
16686   }
16687   db = sqlite3_context_db_handle(context);
16688   zTempFile = 0;
16689   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
16690   if( zTempFile==0 ){
16691     sqlite3_uint64 r = 0;
16692     sqlite3_randomness(sizeof(r), &r);
16693     zTempFile = sqlite3_mprintf("temp%llx", r);
16694     if( zTempFile==0 ){
16695       sqlite3_result_error_nomem(context);
16696       return;
16697     }
16698   }
16699   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
16700   /* When writing the file to be edited, do \n to \r\n conversions on systems
16701   ** that want \r\n line endings */
16702   f = fopen(zTempFile, bBin ? "wb" : "w");
16703   if( f==0 ){
16704     sqlite3_result_error(context, "edit() cannot open temp file", -1);
16705     goto edit_func_end;
16706   }
16707   sz = sqlite3_value_bytes(argv[0]);
16708   if( bBin ){
16709     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
16710   }else{
16711     const char *z = (const char*)sqlite3_value_text(argv[0]);
16712     /* Remember whether or not the value originally contained \r\n */
16713     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
16714     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
16715   }
16716   fclose(f);
16717   f = 0;
16718   if( x!=sz ){
16719     sqlite3_result_error(context, "edit() could not write the whole file", -1);
16720     goto edit_func_end;
16721   }
16722   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
16723   if( zCmd==0 ){
16724     sqlite3_result_error_nomem(context);
16725     goto edit_func_end;
16726   }
16727   rc = system(zCmd);
16728   sqlite3_free(zCmd);
16729   if( rc ){
16730     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
16731     goto edit_func_end;
16732   }
16733   f = fopen(zTempFile, "rb");
16734   if( f==0 ){
16735     sqlite3_result_error(context,
16736       "edit() cannot reopen temp file after edit", -1);
16737     goto edit_func_end;
16738   }
16739   fseek(f, 0, SEEK_END);
16740   sz = ftell(f);
16741   rewind(f);
16742   p = sqlite3_malloc64( sz+1 );
16743   if( p==0 ){
16744     sqlite3_result_error_nomem(context);
16745     goto edit_func_end;
16746   }
16747   x = fread(p, 1, (size_t)sz, f);
16748   fclose(f);
16749   f = 0;
16750   if( x!=sz ){
16751     sqlite3_result_error(context, "could not read back the whole file", -1);
16752     goto edit_func_end;
16753   }
16754   if( bBin ){
16755     sqlite3_result_blob64(context, p, sz, sqlite3_free);
16756   }else{
16757     sqlite3_int64 i, j;
16758     if( hasCRNL ){
16759       /* If the original contains \r\n then do no conversions back to \n */
16760     }else{
16761       /* If the file did not originally contain \r\n then convert any new
16762       ** \r\n back into \n */
16763       for(i=j=0; i<sz; i++){
16764         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
16765         p[j++] = p[i];
16766       }
16767       sz = j;
16768       p[sz] = 0;
16769     }
16770     sqlite3_result_text64(context, (const char*)p, sz,
16771                           sqlite3_free, SQLITE_UTF8);
16772   }
16773   p = 0;
16774 
16775 edit_func_end:
16776   if( f ) fclose(f);
16777   unlink(zTempFile);
16778   sqlite3_free(zTempFile);
16779   sqlite3_free(p);
16780 }
16781 #endif /* SQLITE_NOHAVE_SYSTEM */
16782 
16783 /*
16784 ** Save or restore the current output mode
16785 */
16786 static void outputModePush(ShellState *p){
16787   p->modePrior = p->mode;
16788   p->priorShFlgs = p->shellFlgs;
16789   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
16790   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
16791 }
16792 static void outputModePop(ShellState *p){
16793   p->mode = p->modePrior;
16794   p->shellFlgs = p->priorShFlgs;
16795   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
16796   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
16797 }
16798 
16799 /*
16800 ** Output the given string as a hex-encoded blob (eg. X'1234' )
16801 */
16802 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
16803   int i;
16804   unsigned char *aBlob = (unsigned char*)pBlob;
16805 
16806   char *zStr = sqlite3_malloc(nBlob*2 + 1);
16807   shell_check_oom(zStr);
16808 
16809   for(i=0; i<nBlob; i++){
16810     static const char aHex[] = {
16811         '0', '1', '2', '3', '4', '5', '6', '7',
16812         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
16813     };
16814     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
16815     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
16816   }
16817   zStr[i*2] = '\0';
16818 
16819   raw_printf(out,"X'%s'", zStr);
16820   sqlite3_free(zStr);
16821 }
16822 
16823 /*
16824 ** Find a string that is not found anywhere in z[].  Return a pointer
16825 ** to that string.
16826 **
16827 ** Try to use zA and zB first.  If both of those are already found in z[]
16828 ** then make up some string and store it in the buffer zBuf.
16829 */
16830 static const char *unused_string(
16831   const char *z,                    /* Result must not appear anywhere in z */
16832   const char *zA, const char *zB,   /* Try these first */
16833   char *zBuf                        /* Space to store a generated string */
16834 ){
16835   unsigned i = 0;
16836   if( strstr(z, zA)==0 ) return zA;
16837   if( strstr(z, zB)==0 ) return zB;
16838   do{
16839     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
16840   }while( strstr(z,zBuf)!=0 );
16841   return zBuf;
16842 }
16843 
16844 /*
16845 ** Output the given string as a quoted string using SQL quoting conventions.
16846 **
16847 ** See also: output_quoted_escaped_string()
16848 */
16849 static void output_quoted_string(FILE *out, const char *z){
16850   int i;
16851   char c;
16852   setBinaryMode(out, 1);
16853   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
16854   if( c==0 ){
16855     utf8_printf(out,"'%s'",z);
16856   }else{
16857     raw_printf(out, "'");
16858     while( *z ){
16859       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
16860       if( c=='\'' ) i++;
16861       if( i ){
16862         utf8_printf(out, "%.*s", i, z);
16863         z += i;
16864       }
16865       if( c=='\'' ){
16866         raw_printf(out, "'");
16867         continue;
16868       }
16869       if( c==0 ){
16870         break;
16871       }
16872       z++;
16873     }
16874     raw_printf(out, "'");
16875   }
16876   setTextMode(out, 1);
16877 }
16878 
16879 /*
16880 ** Output the given string as a quoted string using SQL quoting conventions.
16881 ** Additionallly , escape the "\n" and "\r" characters so that they do not
16882 ** get corrupted by end-of-line translation facilities in some operating
16883 ** systems.
16884 **
16885 ** This is like output_quoted_string() but with the addition of the \r\n
16886 ** escape mechanism.
16887 */
16888 static void output_quoted_escaped_string(FILE *out, const char *z){
16889   int i;
16890   char c;
16891   setBinaryMode(out, 1);
16892   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
16893   if( c==0 ){
16894     utf8_printf(out,"'%s'",z);
16895   }else{
16896     const char *zNL = 0;
16897     const char *zCR = 0;
16898     int nNL = 0;
16899     int nCR = 0;
16900     char zBuf1[20], zBuf2[20];
16901     for(i=0; z[i]; i++){
16902       if( z[i]=='\n' ) nNL++;
16903       if( z[i]=='\r' ) nCR++;
16904     }
16905     if( nNL ){
16906       raw_printf(out, "replace(");
16907       zNL = unused_string(z, "\\n", "\\012", zBuf1);
16908     }
16909     if( nCR ){
16910       raw_printf(out, "replace(");
16911       zCR = unused_string(z, "\\r", "\\015", zBuf2);
16912     }
16913     raw_printf(out, "'");
16914     while( *z ){
16915       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
16916       if( c=='\'' ) i++;
16917       if( i ){
16918         utf8_printf(out, "%.*s", i, z);
16919         z += i;
16920       }
16921       if( c=='\'' ){
16922         raw_printf(out, "'");
16923         continue;
16924       }
16925       if( c==0 ){
16926         break;
16927       }
16928       z++;
16929       if( c=='\n' ){
16930         raw_printf(out, "%s", zNL);
16931         continue;
16932       }
16933       raw_printf(out, "%s", zCR);
16934     }
16935     raw_printf(out, "'");
16936     if( nCR ){
16937       raw_printf(out, ",'%s',char(13))", zCR);
16938     }
16939     if( nNL ){
16940       raw_printf(out, ",'%s',char(10))", zNL);
16941     }
16942   }
16943   setTextMode(out, 1);
16944 }
16945 
16946 /*
16947 ** Output the given string as a quoted according to C or TCL quoting rules.
16948 */
16949 static void output_c_string(FILE *out, const char *z){
16950   unsigned int c;
16951   fputc('"', out);
16952   while( (c = *(z++))!=0 ){
16953     if( c=='\\' ){
16954       fputc(c, out);
16955       fputc(c, out);
16956     }else if( c=='"' ){
16957       fputc('\\', out);
16958       fputc('"', out);
16959     }else if( c=='\t' ){
16960       fputc('\\', out);
16961       fputc('t', out);
16962     }else if( c=='\n' ){
16963       fputc('\\', out);
16964       fputc('n', out);
16965     }else if( c=='\r' ){
16966       fputc('\\', out);
16967       fputc('r', out);
16968     }else if( !isprint(c&0xff) ){
16969       raw_printf(out, "\\%03o", c&0xff);
16970     }else{
16971       fputc(c, out);
16972     }
16973   }
16974   fputc('"', out);
16975 }
16976 
16977 /*
16978 ** Output the given string as a quoted according to JSON quoting rules.
16979 */
16980 static void output_json_string(FILE *out, const char *z, i64 n){
16981   unsigned int c;
16982   if( n<0 ) n = strlen(z);
16983   fputc('"', out);
16984   while( n-- ){
16985     c = *(z++);
16986     if( c=='\\' || c=='"' ){
16987       fputc('\\', out);
16988       fputc(c, out);
16989     }else if( c<=0x1f ){
16990       fputc('\\', out);
16991       if( c=='\b' ){
16992         fputc('b', out);
16993       }else if( c=='\f' ){
16994         fputc('f', out);
16995       }else if( c=='\n' ){
16996         fputc('n', out);
16997       }else if( c=='\r' ){
16998         fputc('r', out);
16999       }else if( c=='\t' ){
17000         fputc('t', out);
17001       }else{
17002          raw_printf(out, "u%04x",c);
17003       }
17004     }else{
17005       fputc(c, out);
17006     }
17007   }
17008   fputc('"', out);
17009 }
17010 
17011 /*
17012 ** Output the given string with characters that are special to
17013 ** HTML escaped.
17014 */
17015 static void output_html_string(FILE *out, const char *z){
17016   int i;
17017   if( z==0 ) z = "";
17018   while( *z ){
17019     for(i=0;   z[i]
17020             && z[i]!='<'
17021             && z[i]!='&'
17022             && z[i]!='>'
17023             && z[i]!='\"'
17024             && z[i]!='\'';
17025         i++){}
17026     if( i>0 ){
17027       utf8_printf(out,"%.*s",i,z);
17028     }
17029     if( z[i]=='<' ){
17030       raw_printf(out,"&lt;");
17031     }else if( z[i]=='&' ){
17032       raw_printf(out,"&amp;");
17033     }else if( z[i]=='>' ){
17034       raw_printf(out,"&gt;");
17035     }else if( z[i]=='\"' ){
17036       raw_printf(out,"&quot;");
17037     }else if( z[i]=='\'' ){
17038       raw_printf(out,"&#39;");
17039     }else{
17040       break;
17041     }
17042     z += i + 1;
17043   }
17044 }
17045 
17046 /*
17047 ** If a field contains any character identified by a 1 in the following
17048 ** array, then the string must be quoted for CSV.
17049 */
17050 static const char needCsvQuote[] = {
17051   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17052   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17053   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
17054   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17055   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17056   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17057   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
17058   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
17059   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17060   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17061   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17062   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17063   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17064   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17065   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17066   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
17067 };
17068 
17069 /*
17070 ** Output a single term of CSV.  Actually, p->colSeparator is used for
17071 ** the separator, which may or may not be a comma.  p->nullValue is
17072 ** the null value.  Strings are quoted if necessary.  The separator
17073 ** is only issued if bSep is true.
17074 */
17075 static void output_csv(ShellState *p, const char *z, int bSep){
17076   FILE *out = p->out;
17077   if( z==0 ){
17078     utf8_printf(out,"%s",p->nullValue);
17079   }else{
17080     unsigned i;
17081     for(i=0; z[i]; i++){
17082       if( needCsvQuote[((unsigned char*)z)[i]] ){
17083         i = 0;
17084         break;
17085       }
17086     }
17087     if( i==0 || strstr(z, p->colSeparator)!=0 ){
17088       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
17089       shell_check_oom(zQuoted);
17090       utf8_printf(out, "%s", zQuoted);
17091       sqlite3_free(zQuoted);
17092     }else{
17093       utf8_printf(out, "%s", z);
17094     }
17095   }
17096   if( bSep ){
17097     utf8_printf(p->out, "%s", p->colSeparator);
17098   }
17099 }
17100 
17101 /*
17102 ** This routine runs when the user presses Ctrl-C
17103 */
17104 static void interrupt_handler(int NotUsed){
17105   UNUSED_PARAMETER(NotUsed);
17106   seenInterrupt++;
17107   if( seenInterrupt>2 ) exit(1);
17108   if( globalDb ) sqlite3_interrupt(globalDb);
17109 }
17110 
17111 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
17112 /*
17113 ** This routine runs for console events (e.g. Ctrl-C) on Win32
17114 */
17115 static BOOL WINAPI ConsoleCtrlHandler(
17116   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
17117 ){
17118   if( dwCtrlType==CTRL_C_EVENT ){
17119     interrupt_handler(0);
17120     return TRUE;
17121   }
17122   return FALSE;
17123 }
17124 #endif
17125 
17126 #ifndef SQLITE_OMIT_AUTHORIZATION
17127 /*
17128 ** This authorizer runs in safe mode.
17129 */
17130 static int safeModeAuth(
17131   void *pClientData,
17132   int op,
17133   const char *zA1,
17134   const char *zA2,
17135   const char *zA3,
17136   const char *zA4
17137 ){
17138   ShellState *p = (ShellState*)pClientData;
17139   static const char *azProhibitedFunctions[] = {
17140     "edit",
17141     "fts3_tokenizer",
17142     "load_extension",
17143     "readfile",
17144     "writefile",
17145     "zipfile",
17146     "zipfile_cds",
17147   };
17148   UNUSED_PARAMETER(zA1);
17149   UNUSED_PARAMETER(zA3);
17150   UNUSED_PARAMETER(zA4);
17151   switch( op ){
17152     case SQLITE_ATTACH: {
17153 #ifndef SQLITE_SHELL_FIDDLE
17154       /* In WASM builds the filesystem is a virtual sandbox, so
17155       ** there's no harm in using ATTACH. */
17156       failIfSafeMode(p, "cannot run ATTACH in safe mode");
17157 #endif
17158       break;
17159     }
17160     case SQLITE_FUNCTION: {
17161       int i;
17162       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
17163         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
17164           failIfSafeMode(p, "cannot use the %s() function in safe mode",
17165                          azProhibitedFunctions[i]);
17166         }
17167       }
17168       break;
17169     }
17170   }
17171   return SQLITE_OK;
17172 }
17173 
17174 /*
17175 ** When the ".auth ON" is set, the following authorizer callback is
17176 ** invoked.  It always returns SQLITE_OK.
17177 */
17178 static int shellAuth(
17179   void *pClientData,
17180   int op,
17181   const char *zA1,
17182   const char *zA2,
17183   const char *zA3,
17184   const char *zA4
17185 ){
17186   ShellState *p = (ShellState*)pClientData;
17187   static const char *azAction[] = { 0,
17188      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
17189      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
17190      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
17191      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
17192      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
17193      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
17194      "PRAGMA",               "READ",                 "SELECT",
17195      "TRANSACTION",          "UPDATE",               "ATTACH",
17196      "DETACH",               "ALTER_TABLE",          "REINDEX",
17197      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
17198      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
17199   };
17200   int i;
17201   const char *az[4];
17202   az[0] = zA1;
17203   az[1] = zA2;
17204   az[2] = zA3;
17205   az[3] = zA4;
17206   utf8_printf(p->out, "authorizer: %s", azAction[op]);
17207   for(i=0; i<4; i++){
17208     raw_printf(p->out, " ");
17209     if( az[i] ){
17210       output_c_string(p->out, az[i]);
17211     }else{
17212       raw_printf(p->out, "NULL");
17213     }
17214   }
17215   raw_printf(p->out, "\n");
17216   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
17217   return SQLITE_OK;
17218 }
17219 #endif
17220 
17221 /*
17222 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
17223 **
17224 ** This routine converts some CREATE TABLE statements for shadow tables
17225 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
17226 **
17227 ** If the schema statement in z[] contains a start-of-comment and if
17228 ** sqlite3_complete() returns false, try to terminate the comment before
17229 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
17230 */
17231 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
17232   char *zToFree = 0;
17233   if( z==0 ) return;
17234   if( zTail==0 ) return;
17235   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
17236     const char *zOrig = z;
17237     static const char *azTerm[] = { "", "*/", "\n" };
17238     int i;
17239     for(i=0; i<ArraySize(azTerm); i++){
17240       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
17241       if( sqlite3_complete(zNew) ){
17242         size_t n = strlen(zNew);
17243         zNew[n-1] = 0;
17244         zToFree = zNew;
17245         z = zNew;
17246         break;
17247       }
17248       sqlite3_free(zNew);
17249     }
17250   }
17251   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
17252     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
17253   }else{
17254     utf8_printf(out, "%s%s", z, zTail);
17255   }
17256   sqlite3_free(zToFree);
17257 }
17258 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
17259   char c = z[n];
17260   z[n] = 0;
17261   printSchemaLine(out, z, zTail);
17262   z[n] = c;
17263 }
17264 
17265 /*
17266 ** Return true if string z[] has nothing but whitespace and comments to the
17267 ** end of the first line.
17268 */
17269 static int wsToEol(const char *z){
17270   int i;
17271   for(i=0; z[i]; i++){
17272     if( z[i]=='\n' ) return 1;
17273     if( IsSpace(z[i]) ) continue;
17274     if( z[i]=='-' && z[i+1]=='-' ) return 1;
17275     return 0;
17276   }
17277   return 1;
17278 }
17279 
17280 /*
17281 ** Add a new entry to the EXPLAIN QUERY PLAN data
17282 */
17283 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
17284   EQPGraphRow *pNew;
17285   i64 nText;
17286   if( zText==0 ) return;
17287   nText = strlen(zText);
17288   if( p->autoEQPtest ){
17289     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
17290   }
17291   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
17292   shell_check_oom(pNew);
17293   pNew->iEqpId = iEqpId;
17294   pNew->iParentId = p2;
17295   memcpy(pNew->zText, zText, nText+1);
17296   pNew->pNext = 0;
17297   if( p->sGraph.pLast ){
17298     p->sGraph.pLast->pNext = pNew;
17299   }else{
17300     p->sGraph.pRow = pNew;
17301   }
17302   p->sGraph.pLast = pNew;
17303 }
17304 
17305 /*
17306 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
17307 ** in p->sGraph.
17308 */
17309 static void eqp_reset(ShellState *p){
17310   EQPGraphRow *pRow, *pNext;
17311   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
17312     pNext = pRow->pNext;
17313     sqlite3_free(pRow);
17314   }
17315   memset(&p->sGraph, 0, sizeof(p->sGraph));
17316 }
17317 
17318 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
17319 ** pOld, or return the first such line if pOld is NULL
17320 */
17321 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
17322   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
17323   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
17324   return pRow;
17325 }
17326 
17327 /* Render a single level of the graph that has iEqpId as its parent.  Called
17328 ** recursively to render sublevels.
17329 */
17330 static void eqp_render_level(ShellState *p, int iEqpId){
17331   EQPGraphRow *pRow, *pNext;
17332   i64 n = strlen(p->sGraph.zPrefix);
17333   char *z;
17334   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
17335     pNext = eqp_next_row(p, iEqpId, pRow);
17336     z = pRow->zText;
17337     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
17338                 pNext ? "|--" : "`--", z);
17339     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
17340       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
17341       eqp_render_level(p, pRow->iEqpId);
17342       p->sGraph.zPrefix[n] = 0;
17343     }
17344   }
17345 }
17346 
17347 /*
17348 ** Display and reset the EXPLAIN QUERY PLAN data
17349 */
17350 static void eqp_render(ShellState *p, i64 nCycle){
17351   EQPGraphRow *pRow = p->sGraph.pRow;
17352   if( pRow ){
17353     if( pRow->zText[0]=='-' ){
17354       if( pRow->pNext==0 ){
17355         eqp_reset(p);
17356         return;
17357       }
17358       utf8_printf(p->out, "%s\n", pRow->zText+3);
17359       p->sGraph.pRow = pRow->pNext;
17360       sqlite3_free(pRow);
17361     }else if( nCycle>0 ){
17362       utf8_printf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
17363     }else{
17364       utf8_printf(p->out, "QUERY PLAN\n");
17365     }
17366     p->sGraph.zPrefix[0] = 0;
17367     eqp_render_level(p, 0);
17368     eqp_reset(p);
17369   }
17370 }
17371 
17372 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
17373 /*
17374 ** Progress handler callback.
17375 */
17376 static int progress_handler(void *pClientData) {
17377   ShellState *p = (ShellState*)pClientData;
17378   p->nProgress++;
17379   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
17380     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
17381     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
17382     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
17383     return 1;
17384   }
17385   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
17386     raw_printf(p->out, "Progress %u\n", p->nProgress);
17387   }
17388   return 0;
17389 }
17390 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
17391 
17392 /*
17393 ** Print N dashes
17394 */
17395 static void print_dashes(FILE *out, int N){
17396   const char zDash[] = "--------------------------------------------------";
17397   const int nDash = sizeof(zDash) - 1;
17398   while( N>nDash ){
17399     fputs(zDash, out);
17400     N -= nDash;
17401   }
17402   raw_printf(out, "%.*s", N, zDash);
17403 }
17404 
17405 /*
17406 ** Print a markdown or table-style row separator using ascii-art
17407 */
17408 static void print_row_separator(
17409   ShellState *p,
17410   int nArg,
17411   const char *zSep
17412 ){
17413   int i;
17414   if( nArg>0 ){
17415     fputs(zSep, p->out);
17416     print_dashes(p->out, p->actualWidth[0]+2);
17417     for(i=1; i<nArg; i++){
17418       fputs(zSep, p->out);
17419       print_dashes(p->out, p->actualWidth[i]+2);
17420     }
17421     fputs(zSep, p->out);
17422   }
17423   fputs("\n", p->out);
17424 }
17425 
17426 /*
17427 ** This is the callback routine that the shell
17428 ** invokes for each row of a query result.
17429 */
17430 static int shell_callback(
17431   void *pArg,
17432   int nArg,        /* Number of result columns */
17433   char **azArg,    /* Text of each result column */
17434   char **azCol,    /* Column names */
17435   int *aiType      /* Column types.  Might be NULL */
17436 ){
17437   int i;
17438   ShellState *p = (ShellState*)pArg;
17439 
17440   if( azArg==0 ) return 0;
17441   switch( p->cMode ){
17442     case MODE_Count:
17443     case MODE_Off: {
17444       break;
17445     }
17446     case MODE_Line: {
17447       int w = 5;
17448       if( azArg==0 ) break;
17449       for(i=0; i<nArg; i++){
17450         int len = strlen30(azCol[i] ? azCol[i] : "");
17451         if( len>w ) w = len;
17452       }
17453       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
17454       for(i=0; i<nArg; i++){
17455         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
17456                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
17457       }
17458       break;
17459     }
17460     case MODE_Explain: {
17461       static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
17462       if( nArg>ArraySize(aExplainWidth) ){
17463         nArg = ArraySize(aExplainWidth);
17464       }
17465       if( p->cnt++==0 ){
17466         for(i=0; i<nArg; i++){
17467           int w = aExplainWidth[i];
17468           utf8_width_print(p->out, w, azCol[i]);
17469           fputs(i==nArg-1 ? "\n" : "  ", p->out);
17470         }
17471         for(i=0; i<nArg; i++){
17472           int w = aExplainWidth[i];
17473           print_dashes(p->out, w);
17474           fputs(i==nArg-1 ? "\n" : "  ", p->out);
17475         }
17476       }
17477       if( azArg==0 ) break;
17478       for(i=0; i<nArg; i++){
17479         int w = aExplainWidth[i];
17480         if( i==nArg-1 ) w = 0;
17481         if( azArg[i] && strlenChar(azArg[i])>w ){
17482           w = strlenChar(azArg[i]);
17483         }
17484         if( i==1 && p->aiIndent && p->pStmt ){
17485           if( p->iIndent<p->nIndent ){
17486             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
17487           }
17488           p->iIndent++;
17489         }
17490         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
17491         fputs(i==nArg-1 ? "\n" : "  ", p->out);
17492       }
17493       break;
17494     }
17495     case MODE_Semi: {   /* .schema and .fullschema output */
17496       printSchemaLine(p->out, azArg[0], ";\n");
17497       break;
17498     }
17499     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
17500       char *z;
17501       int j;
17502       int nParen = 0;
17503       char cEnd = 0;
17504       char c;
17505       int nLine = 0;
17506       assert( nArg==1 );
17507       if( azArg[0]==0 ) break;
17508       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
17509        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
17510       ){
17511         utf8_printf(p->out, "%s;\n", azArg[0]);
17512         break;
17513       }
17514       z = sqlite3_mprintf("%s", azArg[0]);
17515       shell_check_oom(z);
17516       j = 0;
17517       for(i=0; IsSpace(z[i]); i++){}
17518       for(; (c = z[i])!=0; i++){
17519         if( IsSpace(c) ){
17520           if( z[j-1]=='\r' ) z[j-1] = '\n';
17521           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
17522         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
17523           j--;
17524         }
17525         z[j++] = c;
17526       }
17527       while( j>0 && IsSpace(z[j-1]) ){ j--; }
17528       z[j] = 0;
17529       if( strlen30(z)>=79 ){
17530         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
17531           if( c==cEnd ){
17532             cEnd = 0;
17533           }else if( c=='"' || c=='\'' || c=='`' ){
17534             cEnd = c;
17535           }else if( c=='[' ){
17536             cEnd = ']';
17537           }else if( c=='-' && z[i+1]=='-' ){
17538             cEnd = '\n';
17539           }else if( c=='(' ){
17540             nParen++;
17541           }else if( c==')' ){
17542             nParen--;
17543             if( nLine>0 && nParen==0 && j>0 ){
17544               printSchemaLineN(p->out, z, j, "\n");
17545               j = 0;
17546             }
17547           }
17548           z[j++] = c;
17549           if( nParen==1 && cEnd==0
17550            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
17551           ){
17552             if( c=='\n' ) j--;
17553             printSchemaLineN(p->out, z, j, "\n  ");
17554             j = 0;
17555             nLine++;
17556             while( IsSpace(z[i+1]) ){ i++; }
17557           }
17558         }
17559         z[j] = 0;
17560       }
17561       printSchemaLine(p->out, z, ";\n");
17562       sqlite3_free(z);
17563       break;
17564     }
17565     case MODE_List: {
17566       if( p->cnt++==0 && p->showHeader ){
17567         for(i=0; i<nArg; i++){
17568           utf8_printf(p->out,"%s%s",azCol[i],
17569                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
17570         }
17571       }
17572       if( azArg==0 ) break;
17573       for(i=0; i<nArg; i++){
17574         char *z = azArg[i];
17575         if( z==0 ) z = p->nullValue;
17576         utf8_printf(p->out, "%s", z);
17577         if( i<nArg-1 ){
17578           utf8_printf(p->out, "%s", p->colSeparator);
17579         }else{
17580           utf8_printf(p->out, "%s", p->rowSeparator);
17581         }
17582       }
17583       break;
17584     }
17585     case MODE_Html: {
17586       if( p->cnt++==0 && p->showHeader ){
17587         raw_printf(p->out,"<TR>");
17588         for(i=0; i<nArg; i++){
17589           raw_printf(p->out,"<TH>");
17590           output_html_string(p->out, azCol[i]);
17591           raw_printf(p->out,"</TH>\n");
17592         }
17593         raw_printf(p->out,"</TR>\n");
17594       }
17595       if( azArg==0 ) break;
17596       raw_printf(p->out,"<TR>");
17597       for(i=0; i<nArg; i++){
17598         raw_printf(p->out,"<TD>");
17599         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
17600         raw_printf(p->out,"</TD>\n");
17601       }
17602       raw_printf(p->out,"</TR>\n");
17603       break;
17604     }
17605     case MODE_Tcl: {
17606       if( p->cnt++==0 && p->showHeader ){
17607         for(i=0; i<nArg; i++){
17608           output_c_string(p->out,azCol[i] ? azCol[i] : "");
17609           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
17610         }
17611         utf8_printf(p->out, "%s", p->rowSeparator);
17612       }
17613       if( azArg==0 ) break;
17614       for(i=0; i<nArg; i++){
17615         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
17616         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
17617       }
17618       utf8_printf(p->out, "%s", p->rowSeparator);
17619       break;
17620     }
17621     case MODE_Csv: {
17622       setBinaryMode(p->out, 1);
17623       if( p->cnt++==0 && p->showHeader ){
17624         for(i=0; i<nArg; i++){
17625           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
17626         }
17627         utf8_printf(p->out, "%s", p->rowSeparator);
17628       }
17629       if( nArg>0 ){
17630         for(i=0; i<nArg; i++){
17631           output_csv(p, azArg[i], i<nArg-1);
17632         }
17633         utf8_printf(p->out, "%s", p->rowSeparator);
17634       }
17635       setTextMode(p->out, 1);
17636       break;
17637     }
17638     case MODE_Insert: {
17639       if( azArg==0 ) break;
17640       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
17641       if( p->showHeader ){
17642         raw_printf(p->out,"(");
17643         for(i=0; i<nArg; i++){
17644           if( i>0 ) raw_printf(p->out, ",");
17645           if( quoteChar(azCol[i]) ){
17646             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
17647             shell_check_oom(z);
17648             utf8_printf(p->out, "%s", z);
17649             sqlite3_free(z);
17650           }else{
17651             raw_printf(p->out, "%s", azCol[i]);
17652           }
17653         }
17654         raw_printf(p->out,")");
17655       }
17656       p->cnt++;
17657       for(i=0; i<nArg; i++){
17658         raw_printf(p->out, i>0 ? "," : " VALUES(");
17659         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17660           utf8_printf(p->out,"NULL");
17661         }else if( aiType && aiType[i]==SQLITE_TEXT ){
17662           if( ShellHasFlag(p, SHFLG_Newlines) ){
17663             output_quoted_string(p->out, azArg[i]);
17664           }else{
17665             output_quoted_escaped_string(p->out, azArg[i]);
17666           }
17667         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
17668           utf8_printf(p->out,"%s", azArg[i]);
17669         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
17670           char z[50];
17671           double r = sqlite3_column_double(p->pStmt, i);
17672           sqlite3_uint64 ur;
17673           memcpy(&ur,&r,sizeof(r));
17674           if( ur==0x7ff0000000000000LL ){
17675             raw_printf(p->out, "1e999");
17676           }else if( ur==0xfff0000000000000LL ){
17677             raw_printf(p->out, "-1e999");
17678           }else{
17679             sqlite3_int64 ir = (sqlite3_int64)r;
17680             if( r==(double)ir ){
17681               sqlite3_snprintf(50,z,"%lld.0", ir);
17682             }else{
17683               sqlite3_snprintf(50,z,"%!.20g", r);
17684             }
17685             raw_printf(p->out, "%s", z);
17686           }
17687         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
17688           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
17689           int nBlob = sqlite3_column_bytes(p->pStmt, i);
17690           output_hex_blob(p->out, pBlob, nBlob);
17691         }else if( isNumber(azArg[i], 0) ){
17692           utf8_printf(p->out,"%s", azArg[i]);
17693         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
17694           output_quoted_string(p->out, azArg[i]);
17695         }else{
17696           output_quoted_escaped_string(p->out, azArg[i]);
17697         }
17698       }
17699       raw_printf(p->out,");\n");
17700       break;
17701     }
17702     case MODE_Json: {
17703       if( azArg==0 ) break;
17704       if( p->cnt==0 ){
17705         fputs("[{", p->out);
17706       }else{
17707         fputs(",\n{", p->out);
17708       }
17709       p->cnt++;
17710       for(i=0; i<nArg; i++){
17711         output_json_string(p->out, azCol[i], -1);
17712         putc(':', p->out);
17713         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17714           fputs("null",p->out);
17715         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
17716           char z[50];
17717           double r = sqlite3_column_double(p->pStmt, i);
17718           sqlite3_uint64 ur;
17719           memcpy(&ur,&r,sizeof(r));
17720           if( ur==0x7ff0000000000000LL ){
17721             raw_printf(p->out, "1e999");
17722           }else if( ur==0xfff0000000000000LL ){
17723             raw_printf(p->out, "-1e999");
17724           }else{
17725             sqlite3_snprintf(50,z,"%!.20g", r);
17726             raw_printf(p->out, "%s", z);
17727           }
17728         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
17729           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
17730           int nBlob = sqlite3_column_bytes(p->pStmt, i);
17731           output_json_string(p->out, pBlob, nBlob);
17732         }else if( aiType && aiType[i]==SQLITE_TEXT ){
17733           output_json_string(p->out, azArg[i], -1);
17734         }else{
17735           utf8_printf(p->out,"%s", azArg[i]);
17736         }
17737         if( i<nArg-1 ){
17738           putc(',', p->out);
17739         }
17740       }
17741       putc('}', p->out);
17742       break;
17743     }
17744     case MODE_Quote: {
17745       if( azArg==0 ) break;
17746       if( p->cnt==0 && p->showHeader ){
17747         for(i=0; i<nArg; i++){
17748           if( i>0 ) fputs(p->colSeparator, p->out);
17749           output_quoted_string(p->out, azCol[i]);
17750         }
17751         fputs(p->rowSeparator, p->out);
17752       }
17753       p->cnt++;
17754       for(i=0; i<nArg; i++){
17755         if( i>0 ) fputs(p->colSeparator, p->out);
17756         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
17757           utf8_printf(p->out,"NULL");
17758         }else if( aiType && aiType[i]==SQLITE_TEXT ){
17759           output_quoted_string(p->out, azArg[i]);
17760         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
17761           utf8_printf(p->out,"%s", azArg[i]);
17762         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
17763           char z[50];
17764           double r = sqlite3_column_double(p->pStmt, i);
17765           sqlite3_snprintf(50,z,"%!.20g", r);
17766           raw_printf(p->out, "%s", z);
17767         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
17768           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
17769           int nBlob = sqlite3_column_bytes(p->pStmt, i);
17770           output_hex_blob(p->out, pBlob, nBlob);
17771         }else if( isNumber(azArg[i], 0) ){
17772           utf8_printf(p->out,"%s", azArg[i]);
17773         }else{
17774           output_quoted_string(p->out, azArg[i]);
17775         }
17776       }
17777       fputs(p->rowSeparator, p->out);
17778       break;
17779     }
17780     case MODE_Ascii: {
17781       if( p->cnt++==0 && p->showHeader ){
17782         for(i=0; i<nArg; i++){
17783           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
17784           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
17785         }
17786         utf8_printf(p->out, "%s", p->rowSeparator);
17787       }
17788       if( azArg==0 ) break;
17789       for(i=0; i<nArg; i++){
17790         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
17791         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
17792       }
17793       utf8_printf(p->out, "%s", p->rowSeparator);
17794       break;
17795     }
17796     case MODE_EQP: {
17797       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
17798       break;
17799     }
17800   }
17801   return 0;
17802 }
17803 
17804 /*
17805 ** This is the callback routine that the SQLite library
17806 ** invokes for each row of a query result.
17807 */
17808 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
17809   /* since we don't have type info, call the shell_callback with a NULL value */
17810   return shell_callback(pArg, nArg, azArg, azCol, NULL);
17811 }
17812 
17813 /*
17814 ** This is the callback routine from sqlite3_exec() that appends all
17815 ** output onto the end of a ShellText object.
17816 */
17817 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
17818   ShellText *p = (ShellText*)pArg;
17819   int i;
17820   UNUSED_PARAMETER(az);
17821   if( azArg==0 ) return 0;
17822   if( p->n ) appendText(p, "|", 0);
17823   for(i=0; i<nArg; i++){
17824     if( i ) appendText(p, ",", 0);
17825     if( azArg[i] ) appendText(p, azArg[i], 0);
17826   }
17827   return 0;
17828 }
17829 
17830 /*
17831 ** Generate an appropriate SELFTEST table in the main database.
17832 */
17833 static void createSelftestTable(ShellState *p){
17834   char *zErrMsg = 0;
17835   sqlite3_exec(p->db,
17836     "SAVEPOINT selftest_init;\n"
17837     "CREATE TABLE IF NOT EXISTS selftest(\n"
17838     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
17839     "  op TEXT,\n"                   /* Operator:  memo run */
17840     "  cmd TEXT,\n"                  /* Command text */
17841     "  ans TEXT\n"                   /* Desired answer */
17842     ");"
17843     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
17844     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
17845     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
17846     "         'memo','Tests generated by --init');\n"
17847     "INSERT INTO [_shell$self]\n"
17848     "  SELECT 'run',\n"
17849     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
17850                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
17851     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
17852                           "FROM sqlite_schema ORDER BY 2',224));\n"
17853     "INSERT INTO [_shell$self]\n"
17854     "  SELECT 'run',"
17855     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
17856     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
17857     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
17858     "  FROM (\n"
17859     "    SELECT name FROM sqlite_schema\n"
17860     "     WHERE type='table'\n"
17861     "       AND name<>'selftest'\n"
17862     "       AND coalesce(rootpage,0)>0\n"
17863     "  )\n"
17864     " ORDER BY name;\n"
17865     "INSERT INTO [_shell$self]\n"
17866     "  VALUES('run','PRAGMA integrity_check','ok');\n"
17867     "INSERT INTO selftest(tno,op,cmd,ans)"
17868     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
17869     "DROP TABLE [_shell$self];"
17870     ,0,0,&zErrMsg);
17871   if( zErrMsg ){
17872     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
17873     sqlite3_free(zErrMsg);
17874   }
17875   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
17876 }
17877 
17878 
17879 /*
17880 ** Set the destination table field of the ShellState structure to
17881 ** the name of the table given.  Escape any quote characters in the
17882 ** table name.
17883 */
17884 static void set_table_name(ShellState *p, const char *zName){
17885   int i, n;
17886   char cQuote;
17887   char *z;
17888 
17889   if( p->zDestTable ){
17890     free(p->zDestTable);
17891     p->zDestTable = 0;
17892   }
17893   if( zName==0 ) return;
17894   cQuote = quoteChar(zName);
17895   n = strlen30(zName);
17896   if( cQuote ) n += n+2;
17897   z = p->zDestTable = malloc( n+1 );
17898   shell_check_oom(z);
17899   n = 0;
17900   if( cQuote ) z[n++] = cQuote;
17901   for(i=0; zName[i]; i++){
17902     z[n++] = zName[i];
17903     if( zName[i]==cQuote ) z[n++] = cQuote;
17904   }
17905   if( cQuote ) z[n++] = cQuote;
17906   z[n] = 0;
17907 }
17908 
17909 /*
17910 ** Maybe construct two lines of text that point out the position of a
17911 ** syntax error.  Return a pointer to the text, in memory obtained from
17912 ** sqlite3_malloc().  Or, if the most recent error does not involve a
17913 ** specific token that we can point to, return an empty string.
17914 **
17915 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
17916 ** and should be released by the caller invoking sqlite3_free().
17917 */
17918 static char *shell_error_context(const char *zSql, sqlite3 *db){
17919   int iOffset;
17920   size_t len;
17921   char *zCode;
17922   char *zMsg;
17923   int i;
17924   if( db==0
17925    || zSql==0
17926    || (iOffset = sqlite3_error_offset(db))<0
17927    || iOffset>=strlen(zSql)
17928   ){
17929     return sqlite3_mprintf("");
17930   }
17931   while( iOffset>50 ){
17932     iOffset--;
17933     zSql++;
17934     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
17935   }
17936   len = strlen(zSql);
17937   if( len>78 ){
17938     len = 78;
17939     while( (zSql[len]&0xc0)==0x80 ) len--;
17940   }
17941   zCode = sqlite3_mprintf("%.*s", len, zSql);
17942   shell_check_oom(zCode);
17943   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
17944   if( iOffset<25 ){
17945     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
17946   }else{
17947     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
17948   }
17949   return zMsg;
17950 }
17951 
17952 
17953 /*
17954 ** Execute a query statement that will generate SQL output.  Print
17955 ** the result columns, comma-separated, on a line and then add a
17956 ** semicolon terminator to the end of that line.
17957 **
17958 ** If the number of columns is 1 and that column contains text "--"
17959 ** then write the semicolon on a separate line.  That way, if a
17960 ** "--" comment occurs at the end of the statement, the comment
17961 ** won't consume the semicolon terminator.
17962 */
17963 static int run_table_dump_query(
17964   ShellState *p,           /* Query context */
17965   const char *zSelect      /* SELECT statement to extract content */
17966 ){
17967   sqlite3_stmt *pSelect;
17968   int rc;
17969   int nResult;
17970   int i;
17971   const char *z;
17972   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
17973   if( rc!=SQLITE_OK || !pSelect ){
17974     char *zContext = shell_error_context(zSelect, p->db);
17975     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
17976                 sqlite3_errmsg(p->db), zContext);
17977     sqlite3_free(zContext);
17978     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
17979     return rc;
17980   }
17981   rc = sqlite3_step(pSelect);
17982   nResult = sqlite3_column_count(pSelect);
17983   while( rc==SQLITE_ROW ){
17984     z = (const char*)sqlite3_column_text(pSelect, 0);
17985     utf8_printf(p->out, "%s", z);
17986     for(i=1; i<nResult; i++){
17987       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
17988     }
17989     if( z==0 ) z = "";
17990     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
17991     if( z[0] ){
17992       raw_printf(p->out, "\n;\n");
17993     }else{
17994       raw_printf(p->out, ";\n");
17995     }
17996     rc = sqlite3_step(pSelect);
17997   }
17998   rc = sqlite3_finalize(pSelect);
17999   if( rc!=SQLITE_OK ){
18000     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
18001                 sqlite3_errmsg(p->db));
18002     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
18003   }
18004   return rc;
18005 }
18006 
18007 /*
18008 ** Allocate space and save off string indicating current error.
18009 */
18010 static char *save_err_msg(
18011   sqlite3 *db,           /* Database to query */
18012   const char *zPhase,    /* When the error occcurs */
18013   int rc,                /* Error code returned from API */
18014   const char *zSql       /* SQL string, or NULL */
18015 ){
18016   char *zErr;
18017   char *zContext;
18018   sqlite3_str *pStr = sqlite3_str_new(0);
18019   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
18020   if( rc>1 ){
18021     sqlite3_str_appendf(pStr, " (%d)", rc);
18022   }
18023   zContext = shell_error_context(zSql, db);
18024   if( zContext ){
18025     sqlite3_str_appendall(pStr, zContext);
18026     sqlite3_free(zContext);
18027   }
18028   zErr = sqlite3_str_finish(pStr);
18029   shell_check_oom(zErr);
18030   return zErr;
18031 }
18032 
18033 #ifdef __linux__
18034 /*
18035 ** Attempt to display I/O stats on Linux using /proc/PID/io
18036 */
18037 static void displayLinuxIoStats(FILE *out){
18038   FILE *in;
18039   char z[200];
18040   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
18041   in = fopen(z, "rb");
18042   if( in==0 ) return;
18043   while( fgets(z, sizeof(z), in)!=0 ){
18044     static const struct {
18045       const char *zPattern;
18046       const char *zDesc;
18047     } aTrans[] = {
18048       { "rchar: ",                  "Bytes received by read():" },
18049       { "wchar: ",                  "Bytes sent to write():"    },
18050       { "syscr: ",                  "Read() system calls:"      },
18051       { "syscw: ",                  "Write() system calls:"     },
18052       { "read_bytes: ",             "Bytes read from storage:"  },
18053       { "write_bytes: ",            "Bytes written to storage:" },
18054       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
18055     };
18056     int i;
18057     for(i=0; i<ArraySize(aTrans); i++){
18058       int n = strlen30(aTrans[i].zPattern);
18059       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
18060         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
18061         break;
18062       }
18063     }
18064   }
18065   fclose(in);
18066 }
18067 #endif
18068 
18069 /*
18070 ** Display a single line of status using 64-bit values.
18071 */
18072 static void displayStatLine(
18073   ShellState *p,            /* The shell context */
18074   char *zLabel,             /* Label for this one line */
18075   char *zFormat,            /* Format for the result */
18076   int iStatusCtrl,          /* Which status to display */
18077   int bReset                /* True to reset the stats */
18078 ){
18079   sqlite3_int64 iCur = -1;
18080   sqlite3_int64 iHiwtr = -1;
18081   int i, nPercent;
18082   char zLine[200];
18083   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
18084   for(i=0, nPercent=0; zFormat[i]; i++){
18085     if( zFormat[i]=='%' ) nPercent++;
18086   }
18087   if( nPercent>1 ){
18088     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
18089   }else{
18090     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
18091   }
18092   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
18093 }
18094 
18095 /*
18096 ** Display memory stats.
18097 */
18098 static int display_stats(
18099   sqlite3 *db,                /* Database to query */
18100   ShellState *pArg,           /* Pointer to ShellState */
18101   int bReset                  /* True to reset the stats */
18102 ){
18103   int iCur;
18104   int iHiwtr;
18105   FILE *out;
18106   if( pArg==0 || pArg->out==0 ) return 0;
18107   out = pArg->out;
18108 
18109   if( pArg->pStmt && pArg->statsOn==2 ){
18110     int nCol, i, x;
18111     sqlite3_stmt *pStmt = pArg->pStmt;
18112     char z[100];
18113     nCol = sqlite3_column_count(pStmt);
18114     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
18115     for(i=0; i<nCol; i++){
18116       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
18117       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
18118 #ifndef SQLITE_OMIT_DECLTYPE
18119       sqlite3_snprintf(30, z+x, "declared type:");
18120       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
18121 #endif
18122 #ifdef SQLITE_ENABLE_COLUMN_METADATA
18123       sqlite3_snprintf(30, z+x, "database name:");
18124       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
18125       sqlite3_snprintf(30, z+x, "table name:");
18126       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
18127       sqlite3_snprintf(30, z+x, "origin name:");
18128       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
18129 #endif
18130     }
18131   }
18132 
18133   if( pArg->statsOn==3 ){
18134     if( pArg->pStmt ){
18135       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
18136       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
18137     }
18138     return 0;
18139   }
18140 
18141   displayStatLine(pArg, "Memory Used:",
18142      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
18143   displayStatLine(pArg, "Number of Outstanding Allocations:",
18144      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
18145   if( pArg->shellFlgs & SHFLG_Pagecache ){
18146     displayStatLine(pArg, "Number of Pcache Pages Used:",
18147        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
18148   }
18149   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
18150      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
18151   displayStatLine(pArg, "Largest Allocation:",
18152      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
18153   displayStatLine(pArg, "Largest Pcache Allocation:",
18154      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
18155 #ifdef YYTRACKMAXSTACKDEPTH
18156   displayStatLine(pArg, "Deepest Parser Stack:",
18157      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
18158 #endif
18159 
18160   if( db ){
18161     if( pArg->shellFlgs & SHFLG_Lookaside ){
18162       iHiwtr = iCur = -1;
18163       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
18164                         &iCur, &iHiwtr, bReset);
18165       raw_printf(pArg->out,
18166               "Lookaside Slots Used:                %d (max %d)\n",
18167               iCur, iHiwtr);
18168       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
18169                         &iCur, &iHiwtr, bReset);
18170       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
18171               iHiwtr);
18172       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
18173                         &iCur, &iHiwtr, bReset);
18174       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
18175               iHiwtr);
18176       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
18177                         &iCur, &iHiwtr, bReset);
18178       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
18179               iHiwtr);
18180     }
18181     iHiwtr = iCur = -1;
18182     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
18183     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
18184             iCur);
18185     iHiwtr = iCur = -1;
18186     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
18187     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
18188     iHiwtr = iCur = -1;
18189     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
18190     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
18191     iHiwtr = iCur = -1;
18192     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
18193     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
18194     iHiwtr = iCur = -1;
18195     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
18196     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
18197     iHiwtr = iCur = -1;
18198     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
18199     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
18200             iCur);
18201     iHiwtr = iCur = -1;
18202     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
18203     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
18204             iCur);
18205   }
18206 
18207   if( pArg->pStmt ){
18208     int iHit, iMiss;
18209     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
18210                                bReset);
18211     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
18212     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
18213     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
18214     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
18215     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
18216     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
18217                                bReset);
18218     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
18219                                 bReset);
18220     if( iHit || iMiss ){
18221       raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
18222             iHit, iHit+iMiss);
18223     }
18224     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
18225     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
18226     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
18227     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
18228     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
18229     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
18230     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
18231     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
18232   }
18233 
18234 #ifdef __linux__
18235   displayLinuxIoStats(pArg->out);
18236 #endif
18237 
18238   /* Do not remove this machine readable comment: extra-stats-output-here */
18239 
18240   return 0;
18241 }
18242 
18243 
18244 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18245 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
18246   int iPid = 0;
18247   int ret = 1;
18248   sqlite3_stmt_scanstatus_v2(p, iEntry,
18249       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
18250   );
18251   while( iPid!=0 ){
18252     int ii;
18253     for(ii=0; 1; ii++){
18254       int iId;
18255       int res;
18256       res = sqlite3_stmt_scanstatus_v2(p, ii,
18257           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
18258       );
18259       if( res ) break;
18260       if( iId==iPid ){
18261         sqlite3_stmt_scanstatus_v2(p, ii,
18262             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
18263         );
18264       }
18265     }
18266     ret++;
18267   }
18268   return ret;
18269 }
18270 #endif
18271 
18272 /*
18273 ** Display scan stats.
18274 */
18275 static void display_scanstats(
18276   sqlite3 *db,                    /* Database to query */
18277   ShellState *pArg                /* Pointer to ShellState */
18278 ){
18279 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
18280   UNUSED_PARAMETER(db);
18281   UNUSED_PARAMETER(pArg);
18282 #else
18283   static const int f = SQLITE_SCANSTAT_COMPLEX;
18284   sqlite3_stmt *p = pArg->pStmt;
18285   int ii = 0;
18286   i64 nTotal = 0;
18287   int nWidth = 0;
18288   eqp_reset(pArg);
18289 
18290   for(ii=0; 1; ii++){
18291     const char *z = 0;
18292     int n = 0;
18293     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
18294       break;
18295     }
18296     n = strlen(z) + scanStatsHeight(p, ii)*3;
18297     if( n>nWidth ) nWidth = n;
18298   }
18299   nWidth += 4;
18300 
18301   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
18302   for(ii=0; 1; ii++){
18303     i64 nLoop = 0;
18304     i64 nRow = 0;
18305     i64 nCycle = 0;
18306     int iId = 0;
18307     int iPid = 0;
18308     const char *z = 0;
18309     const char *zName = 0;
18310     char *zText = 0;
18311     double rEst = 0.0;
18312 
18313     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
18314       break;
18315     }
18316     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
18317     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
18318     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
18319     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
18320     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
18321     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
18322     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
18323 
18324     zText = sqlite3_mprintf("%s", z);
18325     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
18326       char *z = 0;
18327       if( nCycle>=0 && nTotal>0 ){
18328         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
18329             nCycle, ((nCycle*100)+nTotal/2) / nTotal
18330         );
18331       }
18332       if( nLoop>=0 ){
18333         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
18334       }
18335       if( nRow>=0 ){
18336         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
18337       }
18338 
18339       if( zName && pArg->scanstatsOn>1 ){
18340         double rpl = (double)nRow / (double)nLoop;
18341         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
18342       }
18343 
18344       zText = sqlite3_mprintf(
18345           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
18346       );
18347     }
18348 
18349     eqp_append(pArg, iId, iPid, zText);
18350     sqlite3_free(zText);
18351   }
18352 
18353   eqp_render(pArg, nTotal);
18354 #endif
18355 }
18356 
18357 /*
18358 ** Parameter azArray points to a zero-terminated array of strings. zStr
18359 ** points to a single nul-terminated string. Return non-zero if zStr
18360 ** is equal, according to strcmp(), to any of the strings in the array.
18361 ** Otherwise, return zero.
18362 */
18363 static int str_in_array(const char *zStr, const char **azArray){
18364   int i;
18365   for(i=0; azArray[i]; i++){
18366     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
18367   }
18368   return 0;
18369 }
18370 
18371 /*
18372 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
18373 ** and populate the ShellState.aiIndent[] array with the number of
18374 ** spaces each opcode should be indented before it is output.
18375 **
18376 ** The indenting rules are:
18377 **
18378 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
18379 **       all opcodes that occur between the p2 jump destination and the opcode
18380 **       itself by 2 spaces.
18381 **
18382 **     * Do the previous for "Return" instructions for when P2 is positive.
18383 **       See tag-20220407a in wherecode.c and vdbe.c.
18384 **
18385 **     * For each "Goto", if the jump destination is earlier in the program
18386 **       and ends on one of:
18387 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
18388 **       or if the P1 parameter is one instead of zero,
18389 **       then indent all opcodes between the earlier instruction
18390 **       and "Goto" by 2 spaces.
18391 */
18392 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
18393   const char *zSql;               /* The text of the SQL statement */
18394   const char *z;                  /* Used to check if this is an EXPLAIN */
18395   int *abYield = 0;               /* True if op is an OP_Yield */
18396   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
18397   int iOp;                        /* Index of operation in p->aiIndent[] */
18398 
18399   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
18400                            "Return", 0 };
18401   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
18402                             "Rewind", 0 };
18403   const char *azGoto[] = { "Goto", 0 };
18404 
18405   /* Try to figure out if this is really an EXPLAIN statement. If this
18406   ** cannot be verified, return early.  */
18407   if( sqlite3_column_count(pSql)!=8 ){
18408     p->cMode = p->mode;
18409     return;
18410   }
18411   zSql = sqlite3_sql(pSql);
18412   if( zSql==0 ) return;
18413   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
18414   if( sqlite3_strnicmp(z, "explain", 7) ){
18415     p->cMode = p->mode;
18416     return;
18417   }
18418 
18419   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
18420     int i;
18421     int iAddr = sqlite3_column_int(pSql, 0);
18422     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
18423 
18424     /* Set p2 to the P2 field of the current opcode. Then, assuming that
18425     ** p2 is an instruction address, set variable p2op to the index of that
18426     ** instruction in the aiIndent[] array. p2 and p2op may be different if
18427     ** the current instruction is part of a sub-program generated by an
18428     ** SQL trigger or foreign key.  */
18429     int p2 = sqlite3_column_int(pSql, 3);
18430     int p2op = (p2 + (iOp-iAddr));
18431 
18432     /* Grow the p->aiIndent array as required */
18433     if( iOp>=nAlloc ){
18434       if( iOp==0 ){
18435         /* Do further verfication that this is explain output.  Abort if
18436         ** it is not */
18437         static const char *explainCols[] = {
18438            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
18439         int jj;
18440         for(jj=0; jj<ArraySize(explainCols); jj++){
18441           if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
18442             p->cMode = p->mode;
18443             sqlite3_reset(pSql);
18444             return;
18445           }
18446         }
18447       }
18448       nAlloc += 100;
18449       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
18450       shell_check_oom(p->aiIndent);
18451       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
18452       shell_check_oom(abYield);
18453     }
18454     abYield[iOp] = str_in_array(zOp, azYield);
18455     p->aiIndent[iOp] = 0;
18456     p->nIndent = iOp+1;
18457 
18458     if( str_in_array(zOp, azNext) && p2op>0 ){
18459       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
18460     }
18461     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
18462      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
18463     ){
18464       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
18465     }
18466   }
18467 
18468   p->iIndent = 0;
18469   sqlite3_free(abYield);
18470   sqlite3_reset(pSql);
18471 }
18472 
18473 /*
18474 ** Free the array allocated by explain_data_prepare().
18475 */
18476 static void explain_data_delete(ShellState *p){
18477   sqlite3_free(p->aiIndent);
18478   p->aiIndent = 0;
18479   p->nIndent = 0;
18480   p->iIndent = 0;
18481 }
18482 
18483 /*
18484 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
18485 */
18486 static unsigned int savedSelectTrace;
18487 static unsigned int savedWhereTrace;
18488 static void disable_debug_trace_modes(void){
18489   unsigned int zero = 0;
18490   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
18491   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
18492   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
18493   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
18494 }
18495 static void restore_debug_trace_modes(void){
18496   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
18497   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
18498 }
18499 
18500 /* Create the TEMP table used to store parameter bindings */
18501 static void bind_table_init(ShellState *p){
18502   int wrSchema = 0;
18503   int defensiveMode = 0;
18504   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
18505   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
18506   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
18507   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
18508   sqlite3_exec(p->db,
18509     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
18510     "  key TEXT PRIMARY KEY,\n"
18511     "  value\n"
18512     ") WITHOUT ROWID;",
18513     0, 0, 0);
18514   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
18515   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
18516 }
18517 
18518 /*
18519 ** Bind parameters on a prepared statement.
18520 **
18521 ** Parameter bindings are taken from a TEMP table of the form:
18522 **
18523 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
18524 **    WITHOUT ROWID;
18525 **
18526 ** No bindings occur if this table does not exist.  The name of the table
18527 ** begins with "sqlite_" so that it will not collide with ordinary application
18528 ** tables.  The table must be in the TEMP schema.
18529 */
18530 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
18531   int nVar;
18532   int i;
18533   int rc;
18534   sqlite3_stmt *pQ = 0;
18535 
18536   nVar = sqlite3_bind_parameter_count(pStmt);
18537   if( nVar==0 ) return;  /* Nothing to do */
18538   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
18539                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
18540     return; /* Parameter table does not exist */
18541   }
18542   rc = sqlite3_prepare_v2(pArg->db,
18543           "SELECT value FROM temp.sqlite_parameters"
18544           " WHERE key=?1", -1, &pQ, 0);
18545   if( rc || pQ==0 ) return;
18546   for(i=1; i<=nVar; i++){
18547     char zNum[30];
18548     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
18549     if( zVar==0 ){
18550       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
18551       zVar = zNum;
18552     }
18553     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
18554     if( sqlite3_step(pQ)==SQLITE_ROW ){
18555       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
18556     }else{
18557       sqlite3_bind_null(pStmt, i);
18558     }
18559     sqlite3_reset(pQ);
18560   }
18561   sqlite3_finalize(pQ);
18562 }
18563 
18564 /*
18565 ** UTF8 box-drawing characters.  Imagine box lines like this:
18566 **
18567 **           1
18568 **           |
18569 **       4 --+-- 2
18570 **           |
18571 **           3
18572 **
18573 ** Each box characters has between 2 and 4 of the lines leading from
18574 ** the center.  The characters are here identified by the numbers of
18575 ** their corresponding lines.
18576 */
18577 #define BOX_24   "\342\224\200"  /* U+2500 --- */
18578 #define BOX_13   "\342\224\202"  /* U+2502  |  */
18579 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
18580 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
18581 #define BOX_12   "\342\224\224"  /* U+2514  '- */
18582 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
18583 #define BOX_123  "\342\224\234"  /* U+251c  |- */
18584 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
18585 #define BOX_234  "\342\224\254"  /* U+252c -,- */
18586 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
18587 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
18588 
18589 /* Draw horizontal line N characters long using unicode box
18590 ** characters
18591 */
18592 static void print_box_line(FILE *out, int N){
18593   const char zDash[] =
18594       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
18595       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
18596   const int nDash = sizeof(zDash) - 1;
18597   N *= 3;
18598   while( N>nDash ){
18599     utf8_printf(out, zDash);
18600     N -= nDash;
18601   }
18602   utf8_printf(out, "%.*s", N, zDash);
18603 }
18604 
18605 /*
18606 ** Draw a horizontal separator for a MODE_Box table.
18607 */
18608 static void print_box_row_separator(
18609   ShellState *p,
18610   int nArg,
18611   const char *zSep1,
18612   const char *zSep2,
18613   const char *zSep3
18614 ){
18615   int i;
18616   if( nArg>0 ){
18617     utf8_printf(p->out, "%s", zSep1);
18618     print_box_line(p->out, p->actualWidth[0]+2);
18619     for(i=1; i<nArg; i++){
18620       utf8_printf(p->out, "%s", zSep2);
18621       print_box_line(p->out, p->actualWidth[i]+2);
18622     }
18623     utf8_printf(p->out, "%s", zSep3);
18624   }
18625   fputs("\n", p->out);
18626 }
18627 
18628 /*
18629 ** z[] is a line of text that is to be displayed the .mode box or table or
18630 ** similar tabular formats.  z[] might contain control characters such
18631 ** as \n, \t, \f, or \r.
18632 **
18633 ** Compute characters to display on the first line of z[].  Stop at the
18634 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
18635 ** from malloc()) of that first line, which caller should free sometime.
18636 ** Write anything to display on the next line into *pzTail.  If this is
18637 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
18638 */
18639 static char *translateForDisplayAndDup(
18640   const unsigned char *z,            /* Input text to be transformed */
18641   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
18642   int mxWidth,                       /* Max width.  0 means no limit */
18643   u8 bWordWrap                       /* If true, avoid breaking mid-word */
18644 ){
18645   int i;                 /* Input bytes consumed */
18646   int j;                 /* Output bytes generated */
18647   int k;                 /* Input bytes to be displayed */
18648   int n;                 /* Output column number */
18649   unsigned char *zOut;   /* Output text */
18650 
18651   if( z==0 ){
18652     *pzTail = 0;
18653     return 0;
18654   }
18655   if( mxWidth<0 ) mxWidth = -mxWidth;
18656   if( mxWidth==0 ) mxWidth = 1000000;
18657   i = j = n = 0;
18658   while( n<mxWidth ){
18659     if( z[i]>=' ' ){
18660       n++;
18661       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
18662       continue;
18663     }
18664     if( z[i]=='\t' ){
18665       do{
18666         n++;
18667         j++;
18668       }while( (n&7)!=0 && n<mxWidth );
18669       i++;
18670       continue;
18671     }
18672     break;
18673   }
18674   if( n>=mxWidth && bWordWrap  ){
18675     /* Perhaps try to back up to a better place to break the line */
18676     for(k=i; k>i/2; k--){
18677       if( isspace(z[k-1]) ) break;
18678     }
18679     if( k<=i/2 ){
18680       for(k=i; k>i/2; k--){
18681         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
18682       }
18683     }
18684     if( k<=i/2 ){
18685       k = i;
18686     }else{
18687       i = k;
18688       while( z[i]==' ' ) i++;
18689     }
18690   }else{
18691     k = i;
18692   }
18693   if( n>=mxWidth && z[i]>=' ' ){
18694    *pzTail = &z[i];
18695   }else if( z[i]=='\r' && z[i+1]=='\n' ){
18696     *pzTail = z[i+2] ? &z[i+2] : 0;
18697   }else if( z[i]==0 || z[i+1]==0 ){
18698     *pzTail = 0;
18699   }else{
18700     *pzTail = &z[i+1];
18701   }
18702   zOut = malloc( j+1 );
18703   shell_check_oom(zOut);
18704   i = j = n = 0;
18705   while( i<k ){
18706     if( z[i]>=' ' ){
18707       n++;
18708       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
18709       continue;
18710     }
18711     if( z[i]=='\t' ){
18712       do{
18713         n++;
18714         zOut[j++] = ' ';
18715       }while( (n&7)!=0 && n<mxWidth );
18716       i++;
18717       continue;
18718     }
18719     break;
18720   }
18721   zOut[j] = 0;
18722   return (char*)zOut;
18723 }
18724 
18725 /* Extract the value of the i-th current column for pStmt as an SQL literal
18726 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
18727 ** the caller.
18728 */
18729 static char *quoted_column(sqlite3_stmt *pStmt, int i){
18730   switch( sqlite3_column_type(pStmt, i) ){
18731     case SQLITE_NULL: {
18732       return sqlite3_mprintf("NULL");
18733     }
18734     case SQLITE_INTEGER:
18735     case SQLITE_FLOAT: {
18736       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
18737     }
18738     case SQLITE_TEXT: {
18739       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
18740     }
18741     case SQLITE_BLOB: {
18742       int j;
18743       sqlite3_str *pStr = sqlite3_str_new(0);
18744       const unsigned char *a = sqlite3_column_blob(pStmt,i);
18745       int n = sqlite3_column_bytes(pStmt,i);
18746       sqlite3_str_append(pStr, "x'", 2);
18747       for(j=0; j<n; j++){
18748         sqlite3_str_appendf(pStr, "%02x", a[j]);
18749       }
18750       sqlite3_str_append(pStr, "'", 1);
18751       return sqlite3_str_finish(pStr);
18752     }
18753   }
18754   return 0; /* Not reached */
18755 }
18756 
18757 /*
18758 ** Run a prepared statement and output the result in one of the
18759 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
18760 ** or MODE_Box.
18761 **
18762 ** This is different from ordinary exec_prepared_stmt() in that
18763 ** it has to run the entire query and gather the results into memory
18764 ** first, in order to determine column widths, before providing
18765 ** any output.
18766 */
18767 static void exec_prepared_stmt_columnar(
18768   ShellState *p,                        /* Pointer to ShellState */
18769   sqlite3_stmt *pStmt                   /* Statment to run */
18770 ){
18771   sqlite3_int64 nRow = 0;
18772   int nColumn = 0;
18773   char **azData = 0;
18774   sqlite3_int64 nAlloc = 0;
18775   char *abRowDiv = 0;
18776   const unsigned char *uz;
18777   const char *z;
18778   char **azQuoted = 0;
18779   int rc;
18780   sqlite3_int64 i, nData;
18781   int j, nTotal, w, n;
18782   const char *colSep = 0;
18783   const char *rowSep = 0;
18784   const unsigned char **azNextLine = 0;
18785   int bNextLine = 0;
18786   int bMultiLineRowExists = 0;
18787   int bw = p->cmOpts.bWordWrap;
18788   const char *zEmpty = "";
18789   const char *zShowNull = p->nullValue;
18790 
18791   rc = sqlite3_step(pStmt);
18792   if( rc!=SQLITE_ROW ) return;
18793   nColumn = sqlite3_column_count(pStmt);
18794   nAlloc = nColumn*4;
18795   if( nAlloc<=0 ) nAlloc = 1;
18796   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
18797   shell_check_oom(azData);
18798   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
18799   shell_check_oom((void*)azNextLine);
18800   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
18801   if( p->cmOpts.bQuote ){
18802     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
18803     shell_check_oom(azQuoted);
18804     memset(azQuoted, 0, nColumn*sizeof(char*) );
18805   }
18806   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
18807   shell_check_oom(abRowDiv);
18808   if( nColumn>p->nWidth ){
18809     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
18810     shell_check_oom(p->colWidth);
18811     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
18812     p->nWidth = nColumn;
18813     p->actualWidth = &p->colWidth[nColumn];
18814   }
18815   memset(p->actualWidth, 0, nColumn*sizeof(int));
18816   for(i=0; i<nColumn; i++){
18817     w = p->colWidth[i];
18818     if( w<0 ) w = -w;
18819     p->actualWidth[i] = w;
18820   }
18821   for(i=0; i<nColumn; i++){
18822     const unsigned char *zNotUsed;
18823     int wx = p->colWidth[i];
18824     if( wx==0 ){
18825       wx = p->cmOpts.iWrap;
18826     }
18827     if( wx<0 ) wx = -wx;
18828     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
18829     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
18830   }
18831   do{
18832     int useNextLine = bNextLine;
18833     bNextLine = 0;
18834     if( (nRow+2)*nColumn >= nAlloc ){
18835       nAlloc *= 2;
18836       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
18837       shell_check_oom(azData);
18838       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
18839       shell_check_oom(abRowDiv);
18840     }
18841     abRowDiv[nRow] = 1;
18842     nRow++;
18843     for(i=0; i<nColumn; i++){
18844       int wx = p->colWidth[i];
18845       if( wx==0 ){
18846         wx = p->cmOpts.iWrap;
18847       }
18848       if( wx<0 ) wx = -wx;
18849       if( useNextLine ){
18850         uz = azNextLine[i];
18851         if( uz==0 ) uz = (u8*)zEmpty;
18852       }else if( p->cmOpts.bQuote ){
18853         sqlite3_free(azQuoted[i]);
18854         azQuoted[i] = quoted_column(pStmt,i);
18855         uz = (const unsigned char*)azQuoted[i];
18856       }else{
18857         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
18858         if( uz==0 ) uz = (u8*)zShowNull;
18859       }
18860       azData[nRow*nColumn + i]
18861         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
18862       if( azNextLine[i] ){
18863         bNextLine = 1;
18864         abRowDiv[nRow-1] = 0;
18865         bMultiLineRowExists = 1;
18866       }
18867     }
18868   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
18869   nTotal = nColumn*(nRow+1);
18870   for(i=0; i<nTotal; i++){
18871     z = azData[i];
18872     if( z==0 ) z = (char*)zEmpty;
18873     n = strlenChar(z);
18874     j = i%nColumn;
18875     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
18876   }
18877   if( seenInterrupt ) goto columnar_end;
18878   if( nColumn==0 ) goto columnar_end;
18879   switch( p->cMode ){
18880     case MODE_Column: {
18881       colSep = "  ";
18882       rowSep = "\n";
18883       if( p->showHeader ){
18884         for(i=0; i<nColumn; i++){
18885           w = p->actualWidth[i];
18886           if( p->colWidth[i]<0 ) w = -w;
18887           utf8_width_print(p->out, w, azData[i]);
18888           fputs(i==nColumn-1?"\n":"  ", p->out);
18889         }
18890         for(i=0; i<nColumn; i++){
18891           print_dashes(p->out, p->actualWidth[i]);
18892           fputs(i==nColumn-1?"\n":"  ", p->out);
18893         }
18894       }
18895       break;
18896     }
18897     case MODE_Table: {
18898       colSep = " | ";
18899       rowSep = " |\n";
18900       print_row_separator(p, nColumn, "+");
18901       fputs("| ", p->out);
18902       for(i=0; i<nColumn; i++){
18903         w = p->actualWidth[i];
18904         n = strlenChar(azData[i]);
18905         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
18906         fputs(i==nColumn-1?" |\n":" | ", p->out);
18907       }
18908       print_row_separator(p, nColumn, "+");
18909       break;
18910     }
18911     case MODE_Markdown: {
18912       colSep = " | ";
18913       rowSep = " |\n";
18914       fputs("| ", p->out);
18915       for(i=0; i<nColumn; i++){
18916         w = p->actualWidth[i];
18917         n = strlenChar(azData[i]);
18918         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
18919         fputs(i==nColumn-1?" |\n":" | ", p->out);
18920       }
18921       print_row_separator(p, nColumn, "|");
18922       break;
18923     }
18924     case MODE_Box: {
18925       colSep = " " BOX_13 " ";
18926       rowSep = " " BOX_13 "\n";
18927       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
18928       utf8_printf(p->out, BOX_13 " ");
18929       for(i=0; i<nColumn; i++){
18930         w = p->actualWidth[i];
18931         n = strlenChar(azData[i]);
18932         utf8_printf(p->out, "%*s%s%*s%s",
18933             (w-n)/2, "", azData[i], (w-n+1)/2, "",
18934             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
18935       }
18936       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
18937       break;
18938     }
18939   }
18940   for(i=nColumn, j=0; i<nTotal; i++, j++){
18941     if( j==0 && p->cMode!=MODE_Column ){
18942       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
18943     }
18944     z = azData[i];
18945     if( z==0 ) z = p->nullValue;
18946     w = p->actualWidth[j];
18947     if( p->colWidth[j]<0 ) w = -w;
18948     utf8_width_print(p->out, w, z);
18949     if( j==nColumn-1 ){
18950       utf8_printf(p->out, "%s", rowSep);
18951       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
18952         if( p->cMode==MODE_Table ){
18953           print_row_separator(p, nColumn, "+");
18954         }else if( p->cMode==MODE_Box ){
18955           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
18956         }else if( p->cMode==MODE_Column ){
18957           raw_printf(p->out, "\n");
18958         }
18959       }
18960       j = -1;
18961       if( seenInterrupt ) goto columnar_end;
18962     }else{
18963       utf8_printf(p->out, "%s", colSep);
18964     }
18965   }
18966   if( p->cMode==MODE_Table ){
18967     print_row_separator(p, nColumn, "+");
18968   }else if( p->cMode==MODE_Box ){
18969     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
18970   }
18971 columnar_end:
18972   if( seenInterrupt ){
18973     utf8_printf(p->out, "Interrupt\n");
18974   }
18975   nData = (nRow+1)*nColumn;
18976   for(i=0; i<nData; i++){
18977     z = azData[i];
18978     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
18979   }
18980   sqlite3_free(azData);
18981   sqlite3_free((void*)azNextLine);
18982   sqlite3_free(abRowDiv);
18983   if( azQuoted ){
18984     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
18985     sqlite3_free(azQuoted);
18986   }
18987 }
18988 
18989 /*
18990 ** Run a prepared statement
18991 */
18992 static void exec_prepared_stmt(
18993   ShellState *pArg,                                /* Pointer to ShellState */
18994   sqlite3_stmt *pStmt                              /* Statment to run */
18995 ){
18996   int rc;
18997   sqlite3_uint64 nRow = 0;
18998 
18999   if( pArg->cMode==MODE_Column
19000    || pArg->cMode==MODE_Table
19001    || pArg->cMode==MODE_Box
19002    || pArg->cMode==MODE_Markdown
19003   ){
19004     exec_prepared_stmt_columnar(pArg, pStmt);
19005     return;
19006   }
19007 
19008   /* perform the first step.  this will tell us if we
19009   ** have a result set or not and how wide it is.
19010   */
19011   rc = sqlite3_step(pStmt);
19012   /* if we have a result set... */
19013   if( SQLITE_ROW == rc ){
19014     /* allocate space for col name ptr, value ptr, and type */
19015     int nCol = sqlite3_column_count(pStmt);
19016     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
19017     if( !pData ){
19018       shell_out_of_memory();
19019     }else{
19020       char **azCols = (char **)pData;      /* Names of result columns */
19021       char **azVals = &azCols[nCol];       /* Results */
19022       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
19023       int i, x;
19024       assert(sizeof(int) <= sizeof(char *));
19025       /* save off ptrs to column names */
19026       for(i=0; i<nCol; i++){
19027         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
19028       }
19029       do{
19030         nRow++;
19031         /* extract the data and data types */
19032         for(i=0; i<nCol; i++){
19033           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
19034           if( x==SQLITE_BLOB
19035            && pArg
19036            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
19037           ){
19038             azVals[i] = "";
19039           }else{
19040             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
19041           }
19042           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
19043             rc = SQLITE_NOMEM;
19044             break; /* from for */
19045           }
19046         } /* end for */
19047 
19048         /* if data and types extracted successfully... */
19049         if( SQLITE_ROW == rc ){
19050           /* call the supplied callback with the result row data */
19051           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
19052             rc = SQLITE_ABORT;
19053           }else{
19054             rc = sqlite3_step(pStmt);
19055           }
19056         }
19057       } while( SQLITE_ROW == rc );
19058       sqlite3_free(pData);
19059       if( pArg->cMode==MODE_Json ){
19060         fputs("]\n", pArg->out);
19061       }else if( pArg->cMode==MODE_Count ){
19062         char zBuf[200];
19063         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
19064                          nRow, nRow!=1 ? "s" : "");
19065         printf("%s", zBuf);
19066       }
19067     }
19068   }
19069 }
19070 
19071 #ifndef SQLITE_OMIT_VIRTUALTABLE
19072 /*
19073 ** This function is called to process SQL if the previous shell command
19074 ** was ".expert". It passes the SQL in the second argument directly to
19075 ** the sqlite3expert object.
19076 **
19077 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
19078 ** code. In this case, (*pzErr) may be set to point to a buffer containing
19079 ** an English language error message. It is the responsibility of the
19080 ** caller to eventually free this buffer using sqlite3_free().
19081 */
19082 static int expertHandleSQL(
19083   ShellState *pState,
19084   const char *zSql,
19085   char **pzErr
19086 ){
19087   assert( pState->expert.pExpert );
19088   assert( pzErr==0 || *pzErr==0 );
19089   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
19090 }
19091 
19092 /*
19093 ** This function is called either to silently clean up the object
19094 ** created by the ".expert" command (if bCancel==1), or to generate a
19095 ** report from it and then clean it up (if bCancel==0).
19096 **
19097 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
19098 ** code. In this case, (*pzErr) may be set to point to a buffer containing
19099 ** an English language error message. It is the responsibility of the
19100 ** caller to eventually free this buffer using sqlite3_free().
19101 */
19102 static int expertFinish(
19103   ShellState *pState,
19104   int bCancel,
19105   char **pzErr
19106 ){
19107   int rc = SQLITE_OK;
19108   sqlite3expert *p = pState->expert.pExpert;
19109   assert( p );
19110   assert( bCancel || pzErr==0 || *pzErr==0 );
19111   if( bCancel==0 ){
19112     FILE *out = pState->out;
19113     int bVerbose = pState->expert.bVerbose;
19114 
19115     rc = sqlite3_expert_analyze(p, pzErr);
19116     if( rc==SQLITE_OK ){
19117       int nQuery = sqlite3_expert_count(p);
19118       int i;
19119 
19120       if( bVerbose ){
19121         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
19122         raw_printf(out, "-- Candidates -----------------------------\n");
19123         raw_printf(out, "%s\n", zCand);
19124       }
19125       for(i=0; i<nQuery; i++){
19126         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
19127         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
19128         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
19129         if( zIdx==0 ) zIdx = "(no new indexes)\n";
19130         if( bVerbose ){
19131           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
19132           raw_printf(out, "%s\n\n", zSql);
19133         }
19134         raw_printf(out, "%s\n", zIdx);
19135         raw_printf(out, "%s\n", zEQP);
19136       }
19137     }
19138   }
19139   sqlite3_expert_destroy(p);
19140   pState->expert.pExpert = 0;
19141   return rc;
19142 }
19143 
19144 /*
19145 ** Implementation of ".expert" dot command.
19146 */
19147 static int expertDotCommand(
19148   ShellState *pState,             /* Current shell tool state */
19149   char **azArg,                   /* Array of arguments passed to dot command */
19150   int nArg                        /* Number of entries in azArg[] */
19151 ){
19152   int rc = SQLITE_OK;
19153   char *zErr = 0;
19154   int i;
19155   int iSample = 0;
19156 
19157   assert( pState->expert.pExpert==0 );
19158   memset(&pState->expert, 0, sizeof(ExpertInfo));
19159 
19160   for(i=1; rc==SQLITE_OK && i<nArg; i++){
19161     char *z = azArg[i];
19162     int n;
19163     if( z[0]=='-' && z[1]=='-' ) z++;
19164     n = strlen30(z);
19165     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
19166       pState->expert.bVerbose = 1;
19167     }
19168     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
19169       if( i==(nArg-1) ){
19170         raw_printf(stderr, "option requires an argument: %s\n", z);
19171         rc = SQLITE_ERROR;
19172       }else{
19173         iSample = (int)integerValue(azArg[++i]);
19174         if( iSample<0 || iSample>100 ){
19175           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
19176           rc = SQLITE_ERROR;
19177         }
19178       }
19179     }
19180     else{
19181       raw_printf(stderr, "unknown option: %s\n", z);
19182       rc = SQLITE_ERROR;
19183     }
19184   }
19185 
19186   if( rc==SQLITE_OK ){
19187     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
19188     if( pState->expert.pExpert==0 ){
19189       raw_printf(stderr, "sqlite3_expert_new: %s\n",
19190                  zErr ? zErr : "out of memory");
19191       rc = SQLITE_ERROR;
19192     }else{
19193       sqlite3_expert_config(
19194           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
19195       );
19196     }
19197   }
19198   sqlite3_free(zErr);
19199 
19200   return rc;
19201 }
19202 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
19203 
19204 /*
19205 ** Execute a statement or set of statements.  Print
19206 ** any result rows/columns depending on the current mode
19207 ** set via the supplied callback.
19208 **
19209 ** This is very similar to SQLite's built-in sqlite3_exec()
19210 ** function except it takes a slightly different callback
19211 ** and callback data argument.
19212 */
19213 static int shell_exec(
19214   ShellState *pArg,                         /* Pointer to ShellState */
19215   const char *zSql,                         /* SQL to be evaluated */
19216   char **pzErrMsg                           /* Error msg written here */
19217 ){
19218   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
19219   int rc = SQLITE_OK;             /* Return Code */
19220   int rc2;
19221   const char *zLeftover;          /* Tail of unprocessed SQL */
19222   sqlite3 *db = pArg->db;
19223 
19224   if( pzErrMsg ){
19225     *pzErrMsg = NULL;
19226   }
19227 
19228 #ifndef SQLITE_OMIT_VIRTUALTABLE
19229   if( pArg->expert.pExpert ){
19230     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
19231     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
19232   }
19233 #endif
19234 
19235   while( zSql[0] && (SQLITE_OK == rc) ){
19236     static const char *zStmtSql;
19237     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
19238     if( SQLITE_OK != rc ){
19239       if( pzErrMsg ){
19240         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
19241       }
19242     }else{
19243       if( !pStmt ){
19244         /* this happens for a comment or white-space */
19245         zSql = zLeftover;
19246         while( IsSpace(zSql[0]) ) zSql++;
19247         continue;
19248       }
19249       zStmtSql = sqlite3_sql(pStmt);
19250       if( zStmtSql==0 ) zStmtSql = "";
19251       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
19252 
19253       /* save off the prepared statment handle and reset row count */
19254       if( pArg ){
19255         pArg->pStmt = pStmt;
19256         pArg->cnt = 0;
19257       }
19258 
19259       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
19260       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
19261         sqlite3_stmt *pExplain;
19262         char *zEQP;
19263         int triggerEQP = 0;
19264         disable_debug_trace_modes();
19265         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
19266         if( pArg->autoEQP>=AUTOEQP_trigger ){
19267           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
19268         }
19269         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
19270         shell_check_oom(zEQP);
19271         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
19272         if( rc==SQLITE_OK ){
19273           while( sqlite3_step(pExplain)==SQLITE_ROW ){
19274             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
19275             int iEqpId = sqlite3_column_int(pExplain, 0);
19276             int iParentId = sqlite3_column_int(pExplain, 1);
19277             if( zEQPLine==0 ) zEQPLine = "";
19278             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
19279             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
19280           }
19281           eqp_render(pArg, 0);
19282         }
19283         sqlite3_finalize(pExplain);
19284         sqlite3_free(zEQP);
19285         if( pArg->autoEQP>=AUTOEQP_full ){
19286           /* Also do an EXPLAIN for ".eqp full" mode */
19287           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
19288           shell_check_oom(zEQP);
19289           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
19290           if( rc==SQLITE_OK ){
19291             pArg->cMode = MODE_Explain;
19292             explain_data_prepare(pArg, pExplain);
19293             exec_prepared_stmt(pArg, pExplain);
19294             explain_data_delete(pArg);
19295           }
19296           sqlite3_finalize(pExplain);
19297           sqlite3_free(zEQP);
19298         }
19299         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
19300           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
19301           /* Reprepare pStmt before reactiving trace modes */
19302           sqlite3_finalize(pStmt);
19303           sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
19304           if( pArg ) pArg->pStmt = pStmt;
19305         }
19306         restore_debug_trace_modes();
19307       }
19308 
19309       if( pArg ){
19310         pArg->cMode = pArg->mode;
19311         if( pArg->autoExplain ){
19312           if( sqlite3_stmt_isexplain(pStmt)==1 ){
19313             pArg->cMode = MODE_Explain;
19314           }
19315           if( sqlite3_stmt_isexplain(pStmt)==2 ){
19316             pArg->cMode = MODE_EQP;
19317           }
19318         }
19319 
19320         /* If the shell is currently in ".explain" mode, gather the extra
19321         ** data required to add indents to the output.*/
19322         if( pArg->cMode==MODE_Explain ){
19323           explain_data_prepare(pArg, pStmt);
19324         }
19325       }
19326 
19327       bind_prepared_stmt(pArg, pStmt);
19328       exec_prepared_stmt(pArg, pStmt);
19329       explain_data_delete(pArg);
19330       eqp_render(pArg, 0);
19331 
19332       /* print usage stats if stats on */
19333       if( pArg && pArg->statsOn ){
19334         display_stats(db, pArg, 0);
19335       }
19336 
19337       /* print loop-counters if required */
19338       if( pArg && pArg->scanstatsOn ){
19339         display_scanstats(db, pArg);
19340       }
19341 
19342       /* Finalize the statement just executed. If this fails, save a
19343       ** copy of the error message. Otherwise, set zSql to point to the
19344       ** next statement to execute. */
19345       rc2 = sqlite3_finalize(pStmt);
19346       if( rc!=SQLITE_NOMEM ) rc = rc2;
19347       if( rc==SQLITE_OK ){
19348         zSql = zLeftover;
19349         while( IsSpace(zSql[0]) ) zSql++;
19350       }else if( pzErrMsg ){
19351         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
19352       }
19353 
19354       /* clear saved stmt handle */
19355       if( pArg ){
19356         pArg->pStmt = NULL;
19357       }
19358     }
19359   } /* end while */
19360 
19361   return rc;
19362 }
19363 
19364 /*
19365 ** Release memory previously allocated by tableColumnList().
19366 */
19367 static void freeColumnList(char **azCol){
19368   int i;
19369   for(i=1; azCol[i]; i++){
19370     sqlite3_free(azCol[i]);
19371   }
19372   /* azCol[0] is a static string */
19373   sqlite3_free(azCol);
19374 }
19375 
19376 /*
19377 ** Return a list of pointers to strings which are the names of all
19378 ** columns in table zTab.   The memory to hold the names is dynamically
19379 ** allocated and must be released by the caller using a subsequent call
19380 ** to freeColumnList().
19381 **
19382 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
19383 ** value that needs to be preserved, then azCol[0] is filled in with the
19384 ** name of the rowid column.
19385 **
19386 ** The first regular column in the table is azCol[1].  The list is terminated
19387 ** by an entry with azCol[i]==0.
19388 */
19389 static char **tableColumnList(ShellState *p, const char *zTab){
19390   char **azCol = 0;
19391   sqlite3_stmt *pStmt;
19392   char *zSql;
19393   int nCol = 0;
19394   int nAlloc = 0;
19395   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
19396   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
19397   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
19398   int rc;
19399 
19400   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
19401   shell_check_oom(zSql);
19402   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19403   sqlite3_free(zSql);
19404   if( rc ) return 0;
19405   while( sqlite3_step(pStmt)==SQLITE_ROW ){
19406     if( nCol>=nAlloc-2 ){
19407       nAlloc = nAlloc*2 + nCol + 10;
19408       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
19409       shell_check_oom(azCol);
19410     }
19411     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
19412     shell_check_oom(azCol[nCol]);
19413     if( sqlite3_column_int(pStmt, 5) ){
19414       nPK++;
19415       if( nPK==1
19416        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
19417                           "INTEGER")==0
19418       ){
19419         isIPK = 1;
19420       }else{
19421         isIPK = 0;
19422       }
19423     }
19424   }
19425   sqlite3_finalize(pStmt);
19426   if( azCol==0 ) return 0;
19427   azCol[0] = 0;
19428   azCol[nCol+1] = 0;
19429 
19430   /* The decision of whether or not a rowid really needs to be preserved
19431   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
19432   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
19433   ** rowids on tables where the rowid is inaccessible because there are other
19434   ** columns in the table named "rowid", "_rowid_", and "oid".
19435   */
19436   if( preserveRowid && isIPK ){
19437     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
19438     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
19439     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
19440     ** ROWID aliases.  To distinguish these cases, check to see if
19441     ** there is a "pk" entry in "PRAGMA index_list".  There will be
19442     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
19443     */
19444     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
19445                            " WHERE origin='pk'", zTab);
19446     shell_check_oom(zSql);
19447     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
19448     sqlite3_free(zSql);
19449     if( rc ){
19450       freeColumnList(azCol);
19451       return 0;
19452     }
19453     rc = sqlite3_step(pStmt);
19454     sqlite3_finalize(pStmt);
19455     preserveRowid = rc==SQLITE_ROW;
19456   }
19457   if( preserveRowid ){
19458     /* Only preserve the rowid if we can find a name to use for the
19459     ** rowid */
19460     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
19461     int i, j;
19462     for(j=0; j<3; j++){
19463       for(i=1; i<=nCol; i++){
19464         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
19465       }
19466       if( i>nCol ){
19467         /* At this point, we know that azRowid[j] is not the name of any
19468         ** ordinary column in the table.  Verify that azRowid[j] is a valid
19469         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
19470         ** tables will fail this last check */
19471         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
19472         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
19473         break;
19474       }
19475     }
19476   }
19477   return azCol;
19478 }
19479 
19480 /*
19481 ** Toggle the reverse_unordered_selects setting.
19482 */
19483 static void toggleSelectOrder(sqlite3 *db){
19484   sqlite3_stmt *pStmt = 0;
19485   int iSetting = 0;
19486   char zStmt[100];
19487   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
19488   if( sqlite3_step(pStmt)==SQLITE_ROW ){
19489     iSetting = sqlite3_column_int(pStmt, 0);
19490   }
19491   sqlite3_finalize(pStmt);
19492   sqlite3_snprintf(sizeof(zStmt), zStmt,
19493        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
19494   sqlite3_exec(db, zStmt, 0, 0, 0);
19495 }
19496 
19497 /*
19498 ** This is a different callback routine used for dumping the database.
19499 ** Each row received by this callback consists of a table name,
19500 ** the table type ("index" or "table") and SQL to create the table.
19501 ** This routine should print text sufficient to recreate the table.
19502 */
19503 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
19504   int rc;
19505   const char *zTable;
19506   const char *zType;
19507   const char *zSql;
19508   ShellState *p = (ShellState *)pArg;
19509   int dataOnly;
19510   int noSys;
19511 
19512   UNUSED_PARAMETER(azNotUsed);
19513   if( nArg!=3 || azArg==0 ) return 0;
19514   zTable = azArg[0];
19515   zType = azArg[1];
19516   zSql = azArg[2];
19517   if( zTable==0 ) return 0;
19518   if( zType==0 ) return 0;
19519   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
19520   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
19521 
19522   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
19523     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
19524   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
19525     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
19526   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
19527     return 0;
19528   }else if( dataOnly ){
19529     /* no-op */
19530   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
19531     char *zIns;
19532     if( !p->writableSchema ){
19533       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
19534       p->writableSchema = 1;
19535     }
19536     zIns = sqlite3_mprintf(
19537        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
19538        "VALUES('table','%q','%q',0,'%q');",
19539        zTable, zTable, zSql);
19540     shell_check_oom(zIns);
19541     utf8_printf(p->out, "%s\n", zIns);
19542     sqlite3_free(zIns);
19543     return 0;
19544   }else{
19545     printSchemaLine(p->out, zSql, ";\n");
19546   }
19547 
19548   if( cli_strcmp(zType, "table")==0 ){
19549     ShellText sSelect;
19550     ShellText sTable;
19551     char **azCol;
19552     int i;
19553     char *savedDestTable;
19554     int savedMode;
19555 
19556     azCol = tableColumnList(p, zTable);
19557     if( azCol==0 ){
19558       p->nErr++;
19559       return 0;
19560     }
19561 
19562     /* Always quote the table name, even if it appears to be pure ascii,
19563     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
19564     initText(&sTable);
19565     appendText(&sTable, zTable, quoteChar(zTable));
19566     /* If preserving the rowid, add a column list after the table name.
19567     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
19568     ** instead of the usual "INSERT INTO tab VALUES(...)".
19569     */
19570     if( azCol[0] ){
19571       appendText(&sTable, "(", 0);
19572       appendText(&sTable, azCol[0], 0);
19573       for(i=1; azCol[i]; i++){
19574         appendText(&sTable, ",", 0);
19575         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
19576       }
19577       appendText(&sTable, ")", 0);
19578     }
19579 
19580     /* Build an appropriate SELECT statement */
19581     initText(&sSelect);
19582     appendText(&sSelect, "SELECT ", 0);
19583     if( azCol[0] ){
19584       appendText(&sSelect, azCol[0], 0);
19585       appendText(&sSelect, ",", 0);
19586     }
19587     for(i=1; azCol[i]; i++){
19588       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
19589       if( azCol[i+1] ){
19590         appendText(&sSelect, ",", 0);
19591       }
19592     }
19593     freeColumnList(azCol);
19594     appendText(&sSelect, " FROM ", 0);
19595     appendText(&sSelect, zTable, quoteChar(zTable));
19596 
19597     savedDestTable = p->zDestTable;
19598     savedMode = p->mode;
19599     p->zDestTable = sTable.z;
19600     p->mode = p->cMode = MODE_Insert;
19601     rc = shell_exec(p, sSelect.z, 0);
19602     if( (rc&0xff)==SQLITE_CORRUPT ){
19603       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
19604       toggleSelectOrder(p->db);
19605       shell_exec(p, sSelect.z, 0);
19606       toggleSelectOrder(p->db);
19607     }
19608     p->zDestTable = savedDestTable;
19609     p->mode = savedMode;
19610     freeText(&sTable);
19611     freeText(&sSelect);
19612     if( rc ) p->nErr++;
19613   }
19614   return 0;
19615 }
19616 
19617 /*
19618 ** Run zQuery.  Use dump_callback() as the callback routine so that
19619 ** the contents of the query are output as SQL statements.
19620 **
19621 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
19622 ** "ORDER BY rowid DESC" to the end.
19623 */
19624 static int run_schema_dump_query(
19625   ShellState *p,
19626   const char *zQuery
19627 ){
19628   int rc;
19629   char *zErr = 0;
19630   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
19631   if( rc==SQLITE_CORRUPT ){
19632     char *zQ2;
19633     int len = strlen30(zQuery);
19634     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
19635     if( zErr ){
19636       utf8_printf(p->out, "/****** %s ******/\n", zErr);
19637       sqlite3_free(zErr);
19638       zErr = 0;
19639     }
19640     zQ2 = malloc( len+100 );
19641     if( zQ2==0 ) return rc;
19642     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
19643     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
19644     if( rc ){
19645       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
19646     }else{
19647       rc = SQLITE_CORRUPT;
19648     }
19649     sqlite3_free(zErr);
19650     free(zQ2);
19651   }
19652   return rc;
19653 }
19654 
19655 /*
19656 ** Text of help messages.
19657 **
19658 ** The help text for each individual command begins with a line that starts
19659 ** with ".".  Subsequent lines are supplemental information.
19660 **
19661 ** There must be two or more spaces between the end of the command and the
19662 ** start of the description of what that command does.
19663 */
19664 static const char *(azHelp[]) = {
19665 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
19666   && !defined(SQLITE_SHELL_FIDDLE)
19667   ".archive ...             Manage SQL archives",
19668   "   Each command must have exactly one of the following options:",
19669   "     -c, --create               Create a new archive",
19670   "     -u, --update               Add or update files with changed mtime",
19671   "     -i, --insert               Like -u but always add even if unchanged",
19672   "     -r, --remove               Remove files from archive",
19673   "     -t, --list                 List contents of archive",
19674   "     -x, --extract              Extract files from archive",
19675   "   Optional arguments:",
19676   "     -v, --verbose              Print each filename as it is processed",
19677   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
19678   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
19679   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
19680   "     -g, --glob                 Use glob matching for names in archive",
19681   "     -n, --dryrun               Show the SQL that would have occurred",
19682   "   Examples:",
19683   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
19684   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
19685   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
19686   "   See also:",
19687   "      http://sqlite.org/cli.html#sqlite_archive_support",
19688 #endif
19689 #ifndef SQLITE_OMIT_AUTHORIZATION
19690   ".auth ON|OFF             Show authorizer callbacks",
19691 #endif
19692 #ifndef SQLITE_SHELL_FIDDLE
19693   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
19694   "   Options:",
19695   "       --append            Use the appendvfs",
19696   "       --async             Write to FILE without journal and fsync()",
19697 #endif
19698   ".bail on|off             Stop after hitting an error.  Default OFF",
19699   ".binary on|off           Turn binary output on or off.  Default OFF",
19700 #ifndef SQLITE_SHELL_FIDDLE
19701   ".cd DIRECTORY            Change the working directory to DIRECTORY",
19702 #endif
19703   ".changes on|off          Show number of rows changed by SQL",
19704 #ifndef SQLITE_SHELL_FIDDLE
19705   ".check GLOB              Fail if output since .testcase does not match",
19706   ".clone NEWDB             Clone data into NEWDB from the existing database",
19707 #endif
19708   ".connection [close] [#]  Open or close an auxiliary database connection",
19709   ".databases               List names and files of attached databases",
19710   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
19711 #if SQLITE_SHELL_HAVE_RECOVER
19712   ".dbinfo ?DB?             Show status information about the database",
19713 #endif
19714   ".dump ?OBJECTS?          Render database content as SQL",
19715   "   Options:",
19716   "     --data-only            Output only INSERT statements",
19717   "     --newlines             Allow unescaped newline characters in output",
19718   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
19719   "     --preserve-rowids      Include ROWID values in the output",
19720   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
19721   "   Additional LIKE patterns can be given in subsequent arguments",
19722   ".echo on|off             Turn command echo on or off",
19723   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
19724   "   Other Modes:",
19725 #ifdef SQLITE_DEBUG
19726   "      test                  Show raw EXPLAIN QUERY PLAN output",
19727   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
19728 #endif
19729   "      trigger               Like \"full\" but also show trigger bytecode",
19730 #ifndef SQLITE_SHELL_FIDDLE
19731   ".excel                   Display the output of next command in spreadsheet",
19732   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
19733 #endif
19734 #ifndef SQLITE_SHELL_FIDDLE
19735   ".exit ?CODE?             Exit this program with return-code CODE",
19736 #endif
19737   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
19738   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
19739   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
19740   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
19741   "   --help                  Show CMD details",
19742   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
19743   ".headers on|off          Turn display of headers on or off",
19744   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
19745 #ifndef SQLITE_SHELL_FIDDLE
19746   ".import FILE TABLE       Import data from FILE into TABLE",
19747   "   Options:",
19748   "     --ascii               Use \\037 and \\036 as column and row separators",
19749   "     --csv                 Use , and \\n as column and row separators",
19750   "     --skip N              Skip the first N rows of input",
19751   "     --schema S            Target table to be S.TABLE",
19752   "     -v                    \"Verbose\" - increase auxiliary output",
19753   "   Notes:",
19754   "     *  If TABLE does not exist, it is created.  The first row of input",
19755   "        determines the column names.",
19756   "     *  If neither --csv or --ascii are used, the input mode is derived",
19757   "        from the \".mode\" output mode",
19758   "     *  If FILE begins with \"|\" then it is a command that generates the",
19759   "        input text.",
19760 #endif
19761 #ifndef SQLITE_OMIT_TEST_CONTROL
19762   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
19763 #endif
19764   ".indexes ?TABLE?         Show names of indexes",
19765   "                           If TABLE is specified, only show indexes for",
19766   "                           tables matching TABLE using the LIKE operator.",
19767 #ifdef SQLITE_ENABLE_IOTRACE
19768   ".iotrace FILE            Enable I/O diagnostic logging to FILE",
19769 #endif
19770   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
19771   ".lint OPTIONS            Report potential schema issues.",
19772   "     Options:",
19773   "        fkey-indexes     Find missing foreign key indexes",
19774 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
19775   ".load FILE ?ENTRY?       Load an extension library",
19776 #endif
19777 #ifndef SQLITE_SHELL_FIDDLE
19778   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
19779 #endif
19780   ".mode MODE ?OPTIONS?     Set output mode",
19781   "   MODE is one of:",
19782   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
19783   "     box         Tables using unicode box-drawing characters",
19784   "     csv         Comma-separated values",
19785   "     column      Output in columns.  (See .width)",
19786   "     html        HTML <table> code",
19787   "     insert      SQL insert statements for TABLE",
19788   "     json        Results in a JSON array",
19789   "     line        One value per line",
19790   "     list        Values delimited by \"|\"",
19791   "     markdown    Markdown table format",
19792   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
19793   "     quote       Escape answers as for SQL",
19794   "     table       ASCII-art table",
19795   "     tabs        Tab-separated values",
19796   "     tcl         TCL list elements",
19797   "   OPTIONS: (for columnar modes or insert mode):",
19798   "     --wrap N       Wrap output lines to no longer than N characters",
19799   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
19800   "     --ww           Shorthand for \"--wordwrap 1\"",
19801   "     --quote        Quote output text as SQL literals",
19802   "     --noquote      Do not quote output text",
19803   "     TABLE          The name of SQL table used for \"insert\" mode",
19804 #ifndef SQLITE_SHELL_FIDDLE
19805   ".nonce STRING            Suspend safe mode for one command if nonce matches",
19806 #endif
19807   ".nullvalue STRING        Use STRING in place of NULL values",
19808 #ifndef SQLITE_SHELL_FIDDLE
19809   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
19810   "     If FILE begins with '|' then open as a pipe",
19811   "       --bom  Put a UTF8 byte-order mark at the beginning",
19812   "       -e     Send output to the system text editor",
19813   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
19814   /* Note that .open is (partially) available in WASM builds but is
19815   ** currently only intended to be used by the fiddle tool, not
19816   ** end users, so is "undocumented." */
19817   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
19818   "     Options:",
19819   "        --append        Use appendvfs to append database to the end of FILE",
19820 #endif
19821 #ifndef SQLITE_OMIT_DESERIALIZE
19822   "        --deserialize   Load into memory using sqlite3_deserialize()",
19823   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
19824   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
19825 #endif
19826   "        --new           Initialize FILE to an empty database",
19827   "        --nofollow      Do not follow symbolic links",
19828   "        --readonly      Open FILE readonly",
19829   "        --zip           FILE is a ZIP archive",
19830 #ifndef SQLITE_SHELL_FIDDLE
19831   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
19832   "   If FILE begins with '|' then open it as a pipe.",
19833   "   Options:",
19834   "     --bom                 Prefix output with a UTF8 byte-order mark",
19835   "     -e                    Send output to the system text editor",
19836   "     -x                    Send output as CSV to a spreadsheet",
19837 #endif
19838   ".parameter CMD ...       Manage SQL parameter bindings",
19839   "   clear                   Erase all bindings",
19840   "   init                    Initialize the TEMP table that holds bindings",
19841   "   list                    List the current parameter bindings",
19842   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
19843   "                           PARAMETER should start with one of: $ : @ ?",
19844   "   unset PARAMETER         Remove PARAMETER from the binding table",
19845   ".print STRING...         Print literal STRING",
19846 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
19847   ".progress N              Invoke progress handler after every N opcodes",
19848   "   --limit N                 Interrupt after N progress callbacks",
19849   "   --once                    Do no more than one progress interrupt",
19850   "   --quiet|-q                No output except at interrupts",
19851   "   --reset                   Reset the count for each input and interrupt",
19852 #endif
19853   ".prompt MAIN CONTINUE    Replace the standard prompts",
19854 #ifndef SQLITE_SHELL_FIDDLE
19855   ".quit                    Stop interpreting input stream, exit if primary.",
19856   ".read FILE               Read input from FILE or command output",
19857   "    If FILE begins with \"|\", it is a command that generates the input.",
19858 #endif
19859 #if SQLITE_SHELL_HAVE_RECOVER
19860   ".recover                 Recover as much data as possible from corrupt db.",
19861   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
19862   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
19863   "   --no-rowids              Do not attempt to recover rowid values",
19864   "                            that are not also INTEGER PRIMARY KEYs",
19865 #endif
19866 #ifndef SQLITE_SHELL_FIDDLE
19867   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
19868   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
19869 #endif
19870   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
19871   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
19872   "   Options:",
19873   "      --indent             Try to pretty-print the schema",
19874   "      --nosys              Omit objects whose names start with \"sqlite_\"",
19875   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
19876   "    Options:",
19877   "       --init               Create a new SELFTEST table",
19878   "       -v                   Verbose output",
19879   ".separator COL ?ROW?     Change the column and row separators",
19880 #if defined(SQLITE_ENABLE_SESSION)
19881   ".session ?NAME? CMD ...  Create or control sessions",
19882   "   Subcommands:",
19883   "     attach TABLE             Attach TABLE",
19884   "     changeset FILE           Write a changeset into FILE",
19885   "     close                    Close one session",
19886   "     enable ?BOOLEAN?         Set or query the enable bit",
19887   "     filter GLOB...           Reject tables matching GLOBs",
19888   "     indirect ?BOOLEAN?       Mark or query the indirect status",
19889   "     isempty                  Query whether the session is empty",
19890   "     list                     List currently open session names",
19891   "     open DB NAME             Open a new session on DB",
19892   "     patchset FILE            Write a patchset into FILE",
19893   "   If ?NAME? is omitted, the first defined session is used.",
19894 #endif
19895   ".sha3sum ...             Compute a SHA3 hash of database content",
19896   "    Options:",
19897   "      --schema              Also hash the sqlite_schema table",
19898   "      --sha3-224            Use the sha3-224 algorithm",
19899   "      --sha3-256            Use the sha3-256 algorithm (default)",
19900   "      --sha3-384            Use the sha3-384 algorithm",
19901   "      --sha3-512            Use the sha3-512 algorithm",
19902   "    Any other argument is a LIKE pattern for tables to hash",
19903 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
19904   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
19905 #endif
19906   ".show                    Show the current values for various settings",
19907   ".stats ?ARG?             Show stats or turn stats on or off",
19908   "   off                      Turn off automatic stat display",
19909   "   on                       Turn on automatic stat display",
19910   "   stmt                     Show statement stats",
19911   "   vmstep                   Show the virtual machine step count only",
19912 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
19913   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
19914 #endif
19915   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
19916 #ifndef SQLITE_SHELL_FIDDLE
19917   ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
19918 #endif
19919   ".testctrl CMD ...        Run various sqlite3_test_control() operations",
19920   "                           Run \".testctrl\" with no arguments for details",
19921   ".timeout MS              Try opening locked tables for MS milliseconds",
19922   ".timer on|off            Turn SQL timer on or off",
19923 #ifndef SQLITE_OMIT_TRACE
19924   ".trace ?OPTIONS?         Output each SQL statement as it is run",
19925   "    FILE                    Send output to FILE",
19926   "    stdout                  Send output to stdout",
19927   "    stderr                  Send output to stderr",
19928   "    off                     Disable tracing",
19929   "    --expanded              Expand query parameters",
19930 #ifdef SQLITE_ENABLE_NORMALIZE
19931   "    --normalized            Normal the SQL statements",
19932 #endif
19933   "    --plain                 Show SQL as it is input",
19934   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
19935   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
19936   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
19937   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
19938 #endif /* SQLITE_OMIT_TRACE */
19939 #ifdef SQLITE_DEBUG
19940   ".unmodule NAME ...       Unregister virtual table modules",
19941   "    --allexcept             Unregister everything except those named",
19942 #endif
19943   ".version                 Show source, library and compiler versions",
19944   ".vfsinfo ?AUX?           Information about the top-level VFS",
19945   ".vfslist                 List all available VFSes",
19946   ".vfsname ?AUX?           Print the name of the VFS stack",
19947   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
19948   "     Negative values right-justify",
19949 };
19950 
19951 /*
19952 ** Output help text.
19953 **
19954 ** zPattern describes the set of commands for which help text is provided.
19955 ** If zPattern is NULL, then show all commands, but only give a one-line
19956 ** description of each.
19957 **
19958 ** Return the number of matches.
19959 */
19960 static int showHelp(FILE *out, const char *zPattern){
19961   int i = 0;
19962   int j = 0;
19963   int n = 0;
19964   char *zPat;
19965   if( zPattern==0
19966    || zPattern[0]=='0'
19967    || cli_strcmp(zPattern,"-a")==0
19968    || cli_strcmp(zPattern,"-all")==0
19969    || cli_strcmp(zPattern,"--all")==0
19970   ){
19971     /* Show all commands, but only one line per command */
19972     if( zPattern==0 ) zPattern = "";
19973     for(i=0; i<ArraySize(azHelp); i++){
19974       if( azHelp[i][0]=='.' || zPattern[0] ){
19975         utf8_printf(out, "%s\n", azHelp[i]);
19976         n++;
19977       }
19978     }
19979   }else{
19980     /* Look for commands that for which zPattern is an exact prefix */
19981     zPat = sqlite3_mprintf(".%s*", zPattern);
19982     shell_check_oom(zPat);
19983     for(i=0; i<ArraySize(azHelp); i++){
19984       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
19985         utf8_printf(out, "%s\n", azHelp[i]);
19986         j = i+1;
19987         n++;
19988       }
19989     }
19990     sqlite3_free(zPat);
19991     if( n ){
19992       if( n==1 ){
19993         /* when zPattern is a prefix of exactly one command, then include the
19994         ** details of that command, which should begin at offset j */
19995         while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
19996           utf8_printf(out, "%s\n", azHelp[j]);
19997           j++;
19998         }
19999       }
20000       return n;
20001     }
20002     /* Look for commands that contain zPattern anywhere.  Show the complete
20003     ** text of all commands that match. */
20004     zPat = sqlite3_mprintf("%%%s%%", zPattern);
20005     shell_check_oom(zPat);
20006     for(i=0; i<ArraySize(azHelp); i++){
20007       if( azHelp[i][0]=='.' ) j = i;
20008       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
20009         utf8_printf(out, "%s\n", azHelp[j]);
20010         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
20011           j++;
20012           utf8_printf(out, "%s\n", azHelp[j]);
20013         }
20014         i = j;
20015         n++;
20016       }
20017     }
20018     sqlite3_free(zPat);
20019   }
20020   return n;
20021 }
20022 
20023 /* Forward reference */
20024 static int process_input(ShellState *p);
20025 
20026 /*
20027 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
20028 ** and return a pointer to the buffer. The caller is responsible for freeing
20029 ** the memory.
20030 **
20031 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
20032 ** read.
20033 **
20034 ** For convenience, a nul-terminator byte is always appended to the data read
20035 ** from the file before the buffer is returned. This byte is not included in
20036 ** the final value of (*pnByte), if applicable.
20037 **
20038 ** NULL is returned if any error is encountered. The final value of *pnByte
20039 ** is undefined in this case.
20040 */
20041 static char *readFile(const char *zName, int *pnByte){
20042   FILE *in = fopen(zName, "rb");
20043   long nIn;
20044   size_t nRead;
20045   char *pBuf;
20046   if( in==0 ) return 0;
20047   fseek(in, 0, SEEK_END);
20048   nIn = ftell(in);
20049   rewind(in);
20050   pBuf = sqlite3_malloc64( nIn+1 );
20051   if( pBuf==0 ){ fclose(in); return 0; }
20052   nRead = fread(pBuf, nIn, 1, in);
20053   fclose(in);
20054   if( nRead!=1 ){
20055     sqlite3_free(pBuf);
20056     return 0;
20057   }
20058   pBuf[nIn] = 0;
20059   if( pnByte ) *pnByte = nIn;
20060   return pBuf;
20061 }
20062 
20063 #if defined(SQLITE_ENABLE_SESSION)
20064 /*
20065 ** Close a single OpenSession object and release all of its associated
20066 ** resources.
20067 */
20068 static void session_close(OpenSession *pSession){
20069   int i;
20070   sqlite3session_delete(pSession->p);
20071   sqlite3_free(pSession->zName);
20072   for(i=0; i<pSession->nFilter; i++){
20073     sqlite3_free(pSession->azFilter[i]);
20074   }
20075   sqlite3_free(pSession->azFilter);
20076   memset(pSession, 0, sizeof(OpenSession));
20077 }
20078 #endif
20079 
20080 /*
20081 ** Close all OpenSession objects and release all associated resources.
20082 */
20083 #if defined(SQLITE_ENABLE_SESSION)
20084 static void session_close_all(ShellState *p, int i){
20085   int j;
20086   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
20087   for(j=0; j<pAuxDb->nSession; j++){
20088     session_close(&pAuxDb->aSession[j]);
20089   }
20090   pAuxDb->nSession = 0;
20091 }
20092 #else
20093 # define session_close_all(X,Y)
20094 #endif
20095 
20096 /*
20097 ** Implementation of the xFilter function for an open session.  Omit
20098 ** any tables named by ".session filter" but let all other table through.
20099 */
20100 #if defined(SQLITE_ENABLE_SESSION)
20101 static int session_filter(void *pCtx, const char *zTab){
20102   OpenSession *pSession = (OpenSession*)pCtx;
20103   int i;
20104   for(i=0; i<pSession->nFilter; i++){
20105     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
20106   }
20107   return 1;
20108 }
20109 #endif
20110 
20111 /*
20112 ** Try to deduce the type of file for zName based on its content.  Return
20113 ** one of the SHELL_OPEN_* constants.
20114 **
20115 ** If the file does not exist or is empty but its name looks like a ZIP
20116 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
20117 ** Otherwise, assume an ordinary database regardless of the filename if
20118 ** the type cannot be determined from content.
20119 */
20120 int deduceDatabaseType(const char *zName, int dfltZip){
20121   FILE *f = fopen(zName, "rb");
20122   size_t n;
20123   int rc = SHELL_OPEN_UNSPEC;
20124   char zBuf[100];
20125   if( f==0 ){
20126     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
20127        return SHELL_OPEN_ZIPFILE;
20128     }else{
20129        return SHELL_OPEN_NORMAL;
20130     }
20131   }
20132   n = fread(zBuf, 16, 1, f);
20133   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
20134     fclose(f);
20135     return SHELL_OPEN_NORMAL;
20136   }
20137   fseek(f, -25, SEEK_END);
20138   n = fread(zBuf, 25, 1, f);
20139   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
20140     rc = SHELL_OPEN_APPENDVFS;
20141   }else{
20142     fseek(f, -22, SEEK_END);
20143     n = fread(zBuf, 22, 1, f);
20144     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
20145        && zBuf[3]==0x06 ){
20146       rc = SHELL_OPEN_ZIPFILE;
20147     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
20148       rc = SHELL_OPEN_ZIPFILE;
20149     }
20150   }
20151   fclose(f);
20152   return rc;
20153 }
20154 
20155 #ifndef SQLITE_OMIT_DESERIALIZE
20156 /*
20157 ** Reconstruct an in-memory database using the output from the "dbtotxt"
20158 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
20159 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
20160 */
20161 static unsigned char *readHexDb(ShellState *p, int *pnData){
20162   unsigned char *a = 0;
20163   int nLine;
20164   int n = 0;
20165   int pgsz = 0;
20166   int iOffset = 0;
20167   int j, k;
20168   int rc;
20169   FILE *in;
20170   const char *zDbFilename = p->pAuxDb->zDbFilename;
20171   unsigned int x[16];
20172   char zLine[1000];
20173   if( zDbFilename ){
20174     in = fopen(zDbFilename, "r");
20175     if( in==0 ){
20176       utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
20177       return 0;
20178     }
20179     nLine = 0;
20180   }else{
20181     in = p->in;
20182     nLine = p->lineno;
20183     if( in==0 ) in = stdin;
20184   }
20185   *pnData = 0;
20186   nLine++;
20187   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
20188   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
20189   if( rc!=2 ) goto readHexDb_error;
20190   if( n<0 ) goto readHexDb_error;
20191   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
20192   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
20193   a = sqlite3_malloc( n ? n : 1 );
20194   shell_check_oom(a);
20195   memset(a, 0, n);
20196   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
20197     utf8_printf(stderr, "invalid pagesize\n");
20198     goto readHexDb_error;
20199   }
20200   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
20201     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
20202     if( rc==2 ){
20203       iOffset = k;
20204       continue;
20205     }
20206     if( cli_strncmp(zLine, "| end ", 6)==0 ){
20207       break;
20208     }
20209     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
20210                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
20211                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
20212     if( rc==17 ){
20213       k = iOffset+j;
20214       if( k+16<=n && k>=0 ){
20215         int ii;
20216         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
20217       }
20218     }
20219   }
20220   *pnData = n;
20221   if( in!=p->in ){
20222     fclose(in);
20223   }else{
20224     p->lineno = nLine;
20225   }
20226   return a;
20227 
20228 readHexDb_error:
20229   if( in!=p->in ){
20230     fclose(in);
20231   }else{
20232     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
20233       nLine++;
20234       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
20235     }
20236     p->lineno = nLine;
20237   }
20238   sqlite3_free(a);
20239   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
20240   return 0;
20241 }
20242 #endif /* SQLITE_OMIT_DESERIALIZE */
20243 
20244 /*
20245 ** Scalar function "shell_int32". The first argument to this function
20246 ** must be a blob. The second a non-negative integer. This function
20247 ** reads and returns a 32-bit big-endian integer from byte
20248 ** offset (4*<arg2>) of the blob.
20249 */
20250 static void shellInt32(
20251   sqlite3_context *context,
20252   int argc,
20253   sqlite3_value **argv
20254 ){
20255   const unsigned char *pBlob;
20256   int nBlob;
20257   int iInt;
20258 
20259   UNUSED_PARAMETER(argc);
20260   nBlob = sqlite3_value_bytes(argv[0]);
20261   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
20262   iInt = sqlite3_value_int(argv[1]);
20263 
20264   if( iInt>=0 && (iInt+1)*4<=nBlob ){
20265     const unsigned char *a = &pBlob[iInt*4];
20266     sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
20267                        + ((sqlite3_int64)a[1]<<16)
20268                        + ((sqlite3_int64)a[2]<< 8)
20269                        + ((sqlite3_int64)a[3]<< 0);
20270     sqlite3_result_int64(context, iVal);
20271   }
20272 }
20273 
20274 /*
20275 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
20276 ** using "..." with internal double-quote characters doubled.
20277 */
20278 static void shellIdQuote(
20279   sqlite3_context *context,
20280   int argc,
20281   sqlite3_value **argv
20282 ){
20283   const char *zName = (const char*)sqlite3_value_text(argv[0]);
20284   UNUSED_PARAMETER(argc);
20285   if( zName ){
20286     char *z = sqlite3_mprintf("\"%w\"", zName);
20287     sqlite3_result_text(context, z, -1, sqlite3_free);
20288   }
20289 }
20290 
20291 /*
20292 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
20293 */
20294 static void shellUSleepFunc(
20295   sqlite3_context *context,
20296   int argcUnused,
20297   sqlite3_value **argv
20298 ){
20299   int sleep = sqlite3_value_int(argv[0]);
20300   (void)argcUnused;
20301   sqlite3_sleep(sleep/1000);
20302   sqlite3_result_int(context, sleep);
20303 }
20304 
20305 /*
20306 ** Scalar function "shell_escape_crnl" used by the .recover command.
20307 ** The argument passed to this function is the output of built-in
20308 ** function quote(). If the first character of the input is "'",
20309 ** indicating that the value passed to quote() was a text value,
20310 ** then this function searches the input for "\n" and "\r" characters
20311 ** and adds a wrapper similar to the following:
20312 **
20313 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
20314 **
20315 ** Or, if the first character of the input is not "'", then a copy
20316 ** of the input is returned.
20317 */
20318 static void shellEscapeCrnl(
20319   sqlite3_context *context,
20320   int argc,
20321   sqlite3_value **argv
20322 ){
20323   const char *zText = (const char*)sqlite3_value_text(argv[0]);
20324   UNUSED_PARAMETER(argc);
20325   if( zText && zText[0]=='\'' ){
20326     i64 nText = sqlite3_value_bytes(argv[0]);
20327     i64 i;
20328     char zBuf1[20];
20329     char zBuf2[20];
20330     const char *zNL = 0;
20331     const char *zCR = 0;
20332     i64 nCR = 0;
20333     i64 nNL = 0;
20334 
20335     for(i=0; zText[i]; i++){
20336       if( zNL==0 && zText[i]=='\n' ){
20337         zNL = unused_string(zText, "\\n", "\\012", zBuf1);
20338         nNL = strlen(zNL);
20339       }
20340       if( zCR==0 && zText[i]=='\r' ){
20341         zCR = unused_string(zText, "\\r", "\\015", zBuf2);
20342         nCR = strlen(zCR);
20343       }
20344     }
20345 
20346     if( zNL || zCR ){
20347       i64 iOut = 0;
20348       i64 nMax = (nNL > nCR) ? nNL : nCR;
20349       i64 nAlloc = nMax * nText + (nMax+64)*2;
20350       char *zOut = (char*)sqlite3_malloc64(nAlloc);
20351       if( zOut==0 ){
20352         sqlite3_result_error_nomem(context);
20353         return;
20354       }
20355 
20356       if( zNL && zCR ){
20357         memcpy(&zOut[iOut], "replace(replace(", 16);
20358         iOut += 16;
20359       }else{
20360         memcpy(&zOut[iOut], "replace(", 8);
20361         iOut += 8;
20362       }
20363       for(i=0; zText[i]; i++){
20364         if( zText[i]=='\n' ){
20365           memcpy(&zOut[iOut], zNL, nNL);
20366           iOut += nNL;
20367         }else if( zText[i]=='\r' ){
20368           memcpy(&zOut[iOut], zCR, nCR);
20369           iOut += nCR;
20370         }else{
20371           zOut[iOut] = zText[i];
20372           iOut++;
20373         }
20374       }
20375 
20376       if( zNL ){
20377         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
20378         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
20379         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
20380       }
20381       if( zCR ){
20382         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
20383         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
20384         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
20385       }
20386 
20387       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
20388       sqlite3_free(zOut);
20389       return;
20390     }
20391   }
20392 
20393   sqlite3_result_value(context, argv[0]);
20394 }
20395 
20396 /* Flags for open_db().
20397 **
20398 ** The default behavior of open_db() is to exit(1) if the database fails to
20399 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
20400 ** but still returns without calling exit.
20401 **
20402 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
20403 ** ZIP archive if the file does not exist or is empty and its name matches
20404 ** the *.zip pattern.
20405 */
20406 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
20407 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
20408 
20409 /*
20410 ** Make sure the database is open.  If it is not, then open it.  If
20411 ** the database fails to open, print an error message and exit.
20412 */
20413 static void open_db(ShellState *p, int openFlags){
20414   if( p->db==0 ){
20415     const char *zDbFilename = p->pAuxDb->zDbFilename;
20416     if( p->openMode==SHELL_OPEN_UNSPEC ){
20417       if( zDbFilename==0 || zDbFilename[0]==0 ){
20418         p->openMode = SHELL_OPEN_NORMAL;
20419       }else{
20420         p->openMode = (u8)deduceDatabaseType(zDbFilename,
20421                              (openFlags & OPEN_DB_ZIPFILE)!=0);
20422       }
20423     }
20424     switch( p->openMode ){
20425       case SHELL_OPEN_APPENDVFS: {
20426         sqlite3_open_v2(zDbFilename, &p->db,
20427            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
20428         break;
20429       }
20430       case SHELL_OPEN_HEXDB:
20431       case SHELL_OPEN_DESERIALIZE: {
20432         sqlite3_open(0, &p->db);
20433         break;
20434       }
20435       case SHELL_OPEN_ZIPFILE: {
20436         sqlite3_open(":memory:", &p->db);
20437         break;
20438       }
20439       case SHELL_OPEN_READONLY: {
20440         sqlite3_open_v2(zDbFilename, &p->db,
20441             SQLITE_OPEN_READONLY|p->openFlags, 0);
20442         break;
20443       }
20444       case SHELL_OPEN_UNSPEC:
20445       case SHELL_OPEN_NORMAL: {
20446         sqlite3_open_v2(zDbFilename, &p->db,
20447            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
20448         break;
20449       }
20450     }
20451     globalDb = p->db;
20452     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
20453       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
20454           zDbFilename, sqlite3_errmsg(p->db));
20455       if( openFlags & OPEN_DB_KEEPALIVE ){
20456         sqlite3_open(":memory:", &p->db);
20457         return;
20458       }
20459       exit(1);
20460     }
20461 
20462 #ifndef SQLITE_OMIT_LOAD_EXTENSION
20463     sqlite3_enable_load_extension(p->db, 1);
20464 #endif
20465     sqlite3_shathree_init(p->db, 0, 0);
20466     sqlite3_uint_init(p->db, 0, 0);
20467     sqlite3_decimal_init(p->db, 0, 0);
20468     sqlite3_base64_init(p->db, 0, 0);
20469     sqlite3_base85_init(p->db, 0, 0);
20470     sqlite3_regexp_init(p->db, 0, 0);
20471     sqlite3_ieee_init(p->db, 0, 0);
20472     sqlite3_series_init(p->db, 0, 0);
20473 #ifndef SQLITE_SHELL_FIDDLE
20474     sqlite3_fileio_init(p->db, 0, 0);
20475     sqlite3_completion_init(p->db, 0, 0);
20476 #endif
20477 #if SQLITE_SHELL_HAVE_RECOVER
20478     sqlite3_dbdata_init(p->db, 0, 0);
20479 #endif
20480 #ifdef SQLITE_HAVE_ZLIB
20481     if( !p->bSafeModePersist ){
20482       sqlite3_zipfile_init(p->db, 0, 0);
20483       sqlite3_sqlar_init(p->db, 0, 0);
20484     }
20485 #endif
20486 #ifdef SQLITE_SHELL_EXTFUNCS
20487     /* Create a preprocessing mechanism for extensions to make
20488      * their own provisions for being built into the shell.
20489      * This is a short-span macro. See further below for usage.
20490      */
20491 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
20492 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
20493     /* Let custom-included extensions get their ..._init() called.
20494      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
20495      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
20496      * inititialization routine to be called.
20497      */
20498     {
20499       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
20500     /* Let custom-included extensions expose their functionality.
20501      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
20502      * the SQL functions, virtual tables, collating sequences or
20503      * VFS's implemented by the extension to be registered.
20504      */
20505       if( irc==SQLITE_OK
20506           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
20507         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
20508       }
20509 #undef SHELL_SUB_MACRO
20510 #undef SHELL_SUBMACRO
20511     }
20512 #endif
20513 
20514     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
20515                             shellAddSchemaName, 0, 0);
20516     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
20517                             shellModuleSchema, 0, 0);
20518     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
20519                             shellPutsFunc, 0, 0);
20520     sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
20521                             shellEscapeCrnl, 0, 0);
20522     sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
20523                             shellInt32, 0, 0);
20524     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
20525                             shellIdQuote, 0, 0);
20526     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
20527                             shellUSleepFunc, 0, 0);
20528 #ifndef SQLITE_NOHAVE_SYSTEM
20529     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
20530                             editFunc, 0, 0);
20531     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
20532                             editFunc, 0, 0);
20533 #endif
20534 
20535     if( p->openMode==SHELL_OPEN_ZIPFILE ){
20536       char *zSql = sqlite3_mprintf(
20537          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
20538       shell_check_oom(zSql);
20539       sqlite3_exec(p->db, zSql, 0, 0, 0);
20540       sqlite3_free(zSql);
20541     }
20542 #ifndef SQLITE_OMIT_DESERIALIZE
20543     else
20544     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
20545       int rc;
20546       int nData = 0;
20547       unsigned char *aData;
20548       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
20549         aData = (unsigned char*)readFile(zDbFilename, &nData);
20550       }else{
20551         aData = readHexDb(p, &nData);
20552         if( aData==0 ){
20553           return;
20554         }
20555       }
20556       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
20557                    SQLITE_DESERIALIZE_RESIZEABLE |
20558                    SQLITE_DESERIALIZE_FREEONCLOSE);
20559       if( rc ){
20560         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
20561       }
20562       if( p->szMax>0 ){
20563         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
20564       }
20565     }
20566 #endif
20567   }
20568   if( p->bSafeModePersist && p->db!=0 ){
20569     sqlite3_set_authorizer(p->db, safeModeAuth, p);
20570   }
20571 }
20572 
20573 /*
20574 ** Attempt to close the databaes connection.  Report errors.
20575 */
20576 void close_db(sqlite3 *db){
20577   int rc = sqlite3_close(db);
20578   if( rc ){
20579     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
20580         rc, sqlite3_errmsg(db));
20581   }
20582 }
20583 
20584 #if HAVE_READLINE || HAVE_EDITLINE
20585 /*
20586 ** Readline completion callbacks
20587 */
20588 static char *readline_completion_generator(const char *text, int state){
20589   static sqlite3_stmt *pStmt = 0;
20590   char *zRet;
20591   if( state==0 ){
20592     char *zSql;
20593     sqlite3_finalize(pStmt);
20594     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
20595                            "  FROM completion(%Q) ORDER BY 1", text);
20596     shell_check_oom(zSql);
20597     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
20598     sqlite3_free(zSql);
20599   }
20600   if( sqlite3_step(pStmt)==SQLITE_ROW ){
20601     const char *z = (const char*)sqlite3_column_text(pStmt,0);
20602     zRet = z ? strdup(z) : 0;
20603   }else{
20604     sqlite3_finalize(pStmt);
20605     pStmt = 0;
20606     zRet = 0;
20607   }
20608   return zRet;
20609 }
20610 static char **readline_completion(const char *zText, int iStart, int iEnd){
20611   (void)iStart;
20612   (void)iEnd;
20613   rl_attempted_completion_over = 1;
20614   return rl_completion_matches(zText, readline_completion_generator);
20615 }
20616 
20617 #elif HAVE_LINENOISE
20618 /*
20619 ** Linenoise completion callback
20620 */
20621 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
20622   i64 nLine = strlen(zLine);
20623   i64 i, iStart;
20624   sqlite3_stmt *pStmt = 0;
20625   char *zSql;
20626   char zBuf[1000];
20627 
20628   if( nLine>(i64)sizeof(zBuf)-30 ) return;
20629   if( zLine[0]=='.' || zLine[0]=='#') return;
20630   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
20631   if( i==nLine-1 ) return;
20632   iStart = i+1;
20633   memcpy(zBuf, zLine, iStart);
20634   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
20635                          "  FROM completion(%Q,%Q) ORDER BY 1",
20636                          &zLine[iStart], zLine);
20637   shell_check_oom(zSql);
20638   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
20639   sqlite3_free(zSql);
20640   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
20641   while( sqlite3_step(pStmt)==SQLITE_ROW ){
20642     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
20643     int nCompletion = sqlite3_column_bytes(pStmt, 0);
20644     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
20645       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
20646       linenoiseAddCompletion(lc, zBuf);
20647     }
20648   }
20649   sqlite3_finalize(pStmt);
20650 }
20651 #endif
20652 
20653 /*
20654 ** Do C-language style dequoting.
20655 **
20656 **    \a    -> alarm
20657 **    \b    -> backspace
20658 **    \t    -> tab
20659 **    \n    -> newline
20660 **    \v    -> vertical tab
20661 **    \f    -> form feed
20662 **    \r    -> carriage return
20663 **    \s    -> space
20664 **    \"    -> "
20665 **    \'    -> '
20666 **    \\    -> backslash
20667 **    \NNN  -> ascii character NNN in octal
20668 */
20669 static void resolve_backslashes(char *z){
20670   int i, j;
20671   char c;
20672   while( *z && *z!='\\' ) z++;
20673   for(i=j=0; (c = z[i])!=0; i++, j++){
20674     if( c=='\\' && z[i+1]!=0 ){
20675       c = z[++i];
20676       if( c=='a' ){
20677         c = '\a';
20678       }else if( c=='b' ){
20679         c = '\b';
20680       }else if( c=='t' ){
20681         c = '\t';
20682       }else if( c=='n' ){
20683         c = '\n';
20684       }else if( c=='v' ){
20685         c = '\v';
20686       }else if( c=='f' ){
20687         c = '\f';
20688       }else if( c=='r' ){
20689         c = '\r';
20690       }else if( c=='"' ){
20691         c = '"';
20692       }else if( c=='\'' ){
20693         c = '\'';
20694       }else if( c=='\\' ){
20695         c = '\\';
20696       }else if( c>='0' && c<='7' ){
20697         c -= '0';
20698         if( z[i+1]>='0' && z[i+1]<='7' ){
20699           i++;
20700           c = (c<<3) + z[i] - '0';
20701           if( z[i+1]>='0' && z[i+1]<='7' ){
20702             i++;
20703             c = (c<<3) + z[i] - '0';
20704           }
20705         }
20706       }
20707     }
20708     z[j] = c;
20709   }
20710   if( j<i ) z[j] = 0;
20711 }
20712 
20713 /*
20714 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
20715 ** for TRUE and FALSE.  Return the integer value if appropriate.
20716 */
20717 static int booleanValue(const char *zArg){
20718   int i;
20719   if( zArg[0]=='0' && zArg[1]=='x' ){
20720     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
20721   }else{
20722     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
20723   }
20724   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
20725   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
20726     return 1;
20727   }
20728   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
20729     return 0;
20730   }
20731   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
20732           zArg);
20733   return 0;
20734 }
20735 
20736 /*
20737 ** Set or clear a shell flag according to a boolean value.
20738 */
20739 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
20740   if( booleanValue(zArg) ){
20741     ShellSetFlag(p, mFlag);
20742   }else{
20743     ShellClearFlag(p, mFlag);
20744   }
20745 }
20746 
20747 /*
20748 ** Close an output file, assuming it is not stderr or stdout
20749 */
20750 static void output_file_close(FILE *f){
20751   if( f && f!=stdout && f!=stderr ) fclose(f);
20752 }
20753 
20754 /*
20755 ** Try to open an output file.   The names "stdout" and "stderr" are
20756 ** recognized and do the right thing.  NULL is returned if the output
20757 ** filename is "off".
20758 */
20759 static FILE *output_file_open(const char *zFile, int bTextMode){
20760   FILE *f;
20761   if( cli_strcmp(zFile,"stdout")==0 ){
20762     f = stdout;
20763   }else if( cli_strcmp(zFile, "stderr")==0 ){
20764     f = stderr;
20765   }else if( cli_strcmp(zFile, "off")==0 ){
20766     f = 0;
20767   }else{
20768     f = fopen(zFile, bTextMode ? "w" : "wb");
20769     if( f==0 ){
20770       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
20771     }
20772   }
20773   return f;
20774 }
20775 
20776 #ifndef SQLITE_OMIT_TRACE
20777 /*
20778 ** A routine for handling output from sqlite3_trace().
20779 */
20780 static int sql_trace_callback(
20781   unsigned mType,         /* The trace type */
20782   void *pArg,             /* The ShellState pointer */
20783   void *pP,               /* Usually a pointer to sqlite_stmt */
20784   void *pX                /* Auxiliary output */
20785 ){
20786   ShellState *p = (ShellState*)pArg;
20787   sqlite3_stmt *pStmt;
20788   const char *zSql;
20789   i64 nSql;
20790   if( p->traceOut==0 ) return 0;
20791   if( mType==SQLITE_TRACE_CLOSE ){
20792     utf8_printf(p->traceOut, "-- closing database connection\n");
20793     return 0;
20794   }
20795   if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
20796     zSql = (const char*)pX;
20797   }else{
20798     pStmt = (sqlite3_stmt*)pP;
20799     switch( p->eTraceType ){
20800       case SHELL_TRACE_EXPANDED: {
20801         zSql = sqlite3_expanded_sql(pStmt);
20802         break;
20803       }
20804 #ifdef SQLITE_ENABLE_NORMALIZE
20805       case SHELL_TRACE_NORMALIZED: {
20806         zSql = sqlite3_normalized_sql(pStmt);
20807         break;
20808       }
20809 #endif
20810       default: {
20811         zSql = sqlite3_sql(pStmt);
20812         break;
20813       }
20814     }
20815   }
20816   if( zSql==0 ) return 0;
20817   nSql = strlen(zSql);
20818   if( nSql>1000000000 ) nSql = 1000000000;
20819   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
20820   switch( mType ){
20821     case SQLITE_TRACE_ROW:
20822     case SQLITE_TRACE_STMT: {
20823       utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
20824       break;
20825     }
20826     case SQLITE_TRACE_PROFILE: {
20827       sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
20828       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
20829       break;
20830     }
20831   }
20832   return 0;
20833 }
20834 #endif
20835 
20836 /*
20837 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
20838 ** a useful spot to set a debugger breakpoint.
20839 **
20840 ** This routine does not do anything practical.  The code are there simply
20841 ** to prevent the compiler from optimizing this routine out.
20842 */
20843 static void test_breakpoint(void){
20844   static unsigned int nCall = 0;
20845   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
20846 }
20847 
20848 /*
20849 ** An object used to read a CSV and other files for import.
20850 */
20851 typedef struct ImportCtx ImportCtx;
20852 struct ImportCtx {
20853   const char *zFile;  /* Name of the input file */
20854   FILE *in;           /* Read the CSV text from this input stream */
20855   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
20856   char *z;            /* Accumulated text for a field */
20857   int n;              /* Number of bytes in z */
20858   int nAlloc;         /* Space allocated for z[] */
20859   int nLine;          /* Current line number */
20860   int nRow;           /* Number of rows imported */
20861   int nErr;           /* Number of errors encountered */
20862   int bNotFirst;      /* True if one or more bytes already read */
20863   int cTerm;          /* Character that terminated the most recent field */
20864   int cColSep;        /* The column separator character.  (Usually ",") */
20865   int cRowSep;        /* The row separator character.  (Usually "\n") */
20866 };
20867 
20868 /* Clean up resourced used by an ImportCtx */
20869 static void import_cleanup(ImportCtx *p){
20870   if( p->in!=0 && p->xCloser!=0 ){
20871     p->xCloser(p->in);
20872     p->in = 0;
20873   }
20874   sqlite3_free(p->z);
20875   p->z = 0;
20876 }
20877 
20878 /* Append a single byte to z[] */
20879 static void import_append_char(ImportCtx *p, int c){
20880   if( p->n+1>=p->nAlloc ){
20881     p->nAlloc += p->nAlloc + 100;
20882     p->z = sqlite3_realloc64(p->z, p->nAlloc);
20883     shell_check_oom(p->z);
20884   }
20885   p->z[p->n++] = (char)c;
20886 }
20887 
20888 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
20889 ** with the option of having a separator other than ",".
20890 **
20891 **   +  Input comes from p->in.
20892 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
20893 **      from sqlite3_malloc64().
20894 **   +  Use p->cSep as the column separator.  The default is ",".
20895 **   +  Use p->rSep as the row separator.  The default is "\n".
20896 **   +  Keep track of the line number in p->nLine.
20897 **   +  Store the character that terminates the field in p->cTerm.  Store
20898 **      EOF on end-of-file.
20899 **   +  Report syntax errors on stderr
20900 */
20901 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
20902   int c;
20903   int cSep = p->cColSep;
20904   int rSep = p->cRowSep;
20905   p->n = 0;
20906   c = fgetc(p->in);
20907   if( c==EOF || seenInterrupt ){
20908     p->cTerm = EOF;
20909     return 0;
20910   }
20911   if( c=='"' ){
20912     int pc, ppc;
20913     int startLine = p->nLine;
20914     int cQuote = c;
20915     pc = ppc = 0;
20916     while( 1 ){
20917       c = fgetc(p->in);
20918       if( c==rSep ) p->nLine++;
20919       if( c==cQuote ){
20920         if( pc==cQuote ){
20921           pc = 0;
20922           continue;
20923         }
20924       }
20925       if( (c==cSep && pc==cQuote)
20926        || (c==rSep && pc==cQuote)
20927        || (c==rSep && pc=='\r' && ppc==cQuote)
20928        || (c==EOF && pc==cQuote)
20929       ){
20930         do{ p->n--; }while( p->z[p->n]!=cQuote );
20931         p->cTerm = c;
20932         break;
20933       }
20934       if( pc==cQuote && c!='\r' ){
20935         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
20936                 p->zFile, p->nLine, cQuote);
20937       }
20938       if( c==EOF ){
20939         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
20940                 p->zFile, startLine, cQuote);
20941         p->cTerm = c;
20942         break;
20943       }
20944       import_append_char(p, c);
20945       ppc = pc;
20946       pc = c;
20947     }
20948   }else{
20949     /* If this is the first field being parsed and it begins with the
20950     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
20951     if( (c&0xff)==0xef && p->bNotFirst==0 ){
20952       import_append_char(p, c);
20953       c = fgetc(p->in);
20954       if( (c&0xff)==0xbb ){
20955         import_append_char(p, c);
20956         c = fgetc(p->in);
20957         if( (c&0xff)==0xbf ){
20958           p->bNotFirst = 1;
20959           p->n = 0;
20960           return csv_read_one_field(p);
20961         }
20962       }
20963     }
20964     while( c!=EOF && c!=cSep && c!=rSep ){
20965       import_append_char(p, c);
20966       c = fgetc(p->in);
20967     }
20968     if( c==rSep ){
20969       p->nLine++;
20970       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
20971     }
20972     p->cTerm = c;
20973   }
20974   if( p->z ) p->z[p->n] = 0;
20975   p->bNotFirst = 1;
20976   return p->z;
20977 }
20978 
20979 /* Read a single field of ASCII delimited text.
20980 **
20981 **   +  Input comes from p->in.
20982 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
20983 **      from sqlite3_malloc64().
20984 **   +  Use p->cSep as the column separator.  The default is "\x1F".
20985 **   +  Use p->rSep as the row separator.  The default is "\x1E".
20986 **   +  Keep track of the row number in p->nLine.
20987 **   +  Store the character that terminates the field in p->cTerm.  Store
20988 **      EOF on end-of-file.
20989 **   +  Report syntax errors on stderr
20990 */
20991 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
20992   int c;
20993   int cSep = p->cColSep;
20994   int rSep = p->cRowSep;
20995   p->n = 0;
20996   c = fgetc(p->in);
20997   if( c==EOF || seenInterrupt ){
20998     p->cTerm = EOF;
20999     return 0;
21000   }
21001   while( c!=EOF && c!=cSep && c!=rSep ){
21002     import_append_char(p, c);
21003     c = fgetc(p->in);
21004   }
21005   if( c==rSep ){
21006     p->nLine++;
21007   }
21008   p->cTerm = c;
21009   if( p->z ) p->z[p->n] = 0;
21010   return p->z;
21011 }
21012 
21013 /*
21014 ** Try to transfer data for table zTable.  If an error is seen while
21015 ** moving forward, try to go backwards.  The backwards movement won't
21016 ** work for WITHOUT ROWID tables.
21017 */
21018 static void tryToCloneData(
21019   ShellState *p,
21020   sqlite3 *newDb,
21021   const char *zTable
21022 ){
21023   sqlite3_stmt *pQuery = 0;
21024   sqlite3_stmt *pInsert = 0;
21025   char *zQuery = 0;
21026   char *zInsert = 0;
21027   int rc;
21028   int i, j, n;
21029   int nTable = strlen30(zTable);
21030   int k = 0;
21031   int cnt = 0;
21032   const int spinRate = 10000;
21033 
21034   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
21035   shell_check_oom(zQuery);
21036   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21037   if( rc ){
21038     utf8_printf(stderr, "Error %d: %s on [%s]\n",
21039             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21040             zQuery);
21041     goto end_data_xfer;
21042   }
21043   n = sqlite3_column_count(pQuery);
21044   zInsert = sqlite3_malloc64(200 + nTable + n*3);
21045   shell_check_oom(zInsert);
21046   sqlite3_snprintf(200+nTable,zInsert,
21047                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
21048   i = strlen30(zInsert);
21049   for(j=1; j<n; j++){
21050     memcpy(zInsert+i, ",?", 2);
21051     i += 2;
21052   }
21053   memcpy(zInsert+i, ");", 3);
21054   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
21055   if( rc ){
21056     utf8_printf(stderr, "Error %d: %s on [%s]\n",
21057             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
21058             zQuery);
21059     goto end_data_xfer;
21060   }
21061   for(k=0; k<2; k++){
21062     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
21063       for(i=0; i<n; i++){
21064         switch( sqlite3_column_type(pQuery, i) ){
21065           case SQLITE_NULL: {
21066             sqlite3_bind_null(pInsert, i+1);
21067             break;
21068           }
21069           case SQLITE_INTEGER: {
21070             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
21071             break;
21072           }
21073           case SQLITE_FLOAT: {
21074             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
21075             break;
21076           }
21077           case SQLITE_TEXT: {
21078             sqlite3_bind_text(pInsert, i+1,
21079                              (const char*)sqlite3_column_text(pQuery,i),
21080                              -1, SQLITE_STATIC);
21081             break;
21082           }
21083           case SQLITE_BLOB: {
21084             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
21085                                             sqlite3_column_bytes(pQuery,i),
21086                                             SQLITE_STATIC);
21087             break;
21088           }
21089         }
21090       } /* End for */
21091       rc = sqlite3_step(pInsert);
21092       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
21093         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
21094                         sqlite3_errmsg(newDb));
21095       }
21096       sqlite3_reset(pInsert);
21097       cnt++;
21098       if( (cnt%spinRate)==0 ){
21099         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
21100         fflush(stdout);
21101       }
21102     } /* End while */
21103     if( rc==SQLITE_DONE ) break;
21104     sqlite3_finalize(pQuery);
21105     sqlite3_free(zQuery);
21106     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
21107                              zTable);
21108     shell_check_oom(zQuery);
21109     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21110     if( rc ){
21111       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
21112       break;
21113     }
21114   } /* End for(k=0...) */
21115 
21116 end_data_xfer:
21117   sqlite3_finalize(pQuery);
21118   sqlite3_finalize(pInsert);
21119   sqlite3_free(zQuery);
21120   sqlite3_free(zInsert);
21121 }
21122 
21123 
21124 /*
21125 ** Try to transfer all rows of the schema that match zWhere.  For
21126 ** each row, invoke xForEach() on the object defined by that row.
21127 ** If an error is encountered while moving forward through the
21128 ** sqlite_schema table, try again moving backwards.
21129 */
21130 static void tryToCloneSchema(
21131   ShellState *p,
21132   sqlite3 *newDb,
21133   const char *zWhere,
21134   void (*xForEach)(ShellState*,sqlite3*,const char*)
21135 ){
21136   sqlite3_stmt *pQuery = 0;
21137   char *zQuery = 0;
21138   int rc;
21139   const unsigned char *zName;
21140   const unsigned char *zSql;
21141   char *zErrMsg = 0;
21142 
21143   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
21144                            " WHERE %s ORDER BY rowid ASC", zWhere);
21145   shell_check_oom(zQuery);
21146   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21147   if( rc ){
21148     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
21149                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21150                     zQuery);
21151     goto end_schema_xfer;
21152   }
21153   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
21154     zName = sqlite3_column_text(pQuery, 0);
21155     zSql = sqlite3_column_text(pQuery, 1);
21156     if( zName==0 || zSql==0 ) continue;
21157     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
21158       printf("%s... ", zName); fflush(stdout);
21159       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
21160       if( zErrMsg ){
21161         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
21162         sqlite3_free(zErrMsg);
21163         zErrMsg = 0;
21164       }
21165     }
21166     if( xForEach ){
21167       xForEach(p, newDb, (const char*)zName);
21168     }
21169     printf("done\n");
21170   }
21171   if( rc!=SQLITE_DONE ){
21172     sqlite3_finalize(pQuery);
21173     sqlite3_free(zQuery);
21174     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
21175                              " WHERE %s ORDER BY rowid DESC", zWhere);
21176     shell_check_oom(zQuery);
21177     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
21178     if( rc ){
21179       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
21180                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
21181                       zQuery);
21182       goto end_schema_xfer;
21183     }
21184     while( sqlite3_step(pQuery)==SQLITE_ROW ){
21185       zName = sqlite3_column_text(pQuery, 0);
21186       zSql = sqlite3_column_text(pQuery, 1);
21187       if( zName==0 || zSql==0 ) continue;
21188       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ) continue;
21189       printf("%s... ", zName); fflush(stdout);
21190       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
21191       if( zErrMsg ){
21192         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
21193         sqlite3_free(zErrMsg);
21194         zErrMsg = 0;
21195       }
21196       if( xForEach ){
21197         xForEach(p, newDb, (const char*)zName);
21198       }
21199       printf("done\n");
21200     }
21201   }
21202 end_schema_xfer:
21203   sqlite3_finalize(pQuery);
21204   sqlite3_free(zQuery);
21205 }
21206 
21207 /*
21208 ** Open a new database file named "zNewDb".  Try to recover as much information
21209 ** as possible out of the main database (which might be corrupt) and write it
21210 ** into zNewDb.
21211 */
21212 static void tryToClone(ShellState *p, const char *zNewDb){
21213   int rc;
21214   sqlite3 *newDb = 0;
21215   if( access(zNewDb,0)==0 ){
21216     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
21217     return;
21218   }
21219   rc = sqlite3_open(zNewDb, &newDb);
21220   if( rc ){
21221     utf8_printf(stderr, "Cannot create output database: %s\n",
21222             sqlite3_errmsg(newDb));
21223   }else{
21224     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
21225     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
21226     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
21227     tryToCloneSchema(p, newDb, "type!='table'", 0);
21228     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
21229     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
21230   }
21231   close_db(newDb);
21232 }
21233 
21234 /*
21235 ** Change the output file back to stdout.
21236 **
21237 ** If the p->doXdgOpen flag is set, that means the output was being
21238 ** redirected to a temporary file named by p->zTempFile.  In that case,
21239 ** launch start/open/xdg-open on that temporary file.
21240 */
21241 static void output_reset(ShellState *p){
21242   if( p->outfile[0]=='|' ){
21243 #ifndef SQLITE_OMIT_POPEN
21244     pclose(p->out);
21245 #endif
21246   }else{
21247     output_file_close(p->out);
21248 #ifndef SQLITE_NOHAVE_SYSTEM
21249     if( p->doXdgOpen ){
21250       const char *zXdgOpenCmd =
21251 #if defined(_WIN32)
21252       "start";
21253 #elif defined(__APPLE__)
21254       "open";
21255 #else
21256       "xdg-open";
21257 #endif
21258       char *zCmd;
21259       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
21260       if( system(zCmd) ){
21261         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
21262       }else{
21263         /* Give the start/open/xdg-open command some time to get
21264         ** going before we continue, and potential delete the
21265         ** p->zTempFile data file out from under it */
21266         sqlite3_sleep(2000);
21267       }
21268       sqlite3_free(zCmd);
21269       outputModePop(p);
21270       p->doXdgOpen = 0;
21271     }
21272 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
21273   }
21274   p->outfile[0] = 0;
21275   p->out = stdout;
21276 }
21277 
21278 /*
21279 ** Run an SQL command and return the single integer result.
21280 */
21281 static int db_int(sqlite3 *db, const char *zSql){
21282   sqlite3_stmt *pStmt;
21283   int res = 0;
21284   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
21285   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
21286     res = sqlite3_column_int(pStmt,0);
21287   }
21288   sqlite3_finalize(pStmt);
21289   return res;
21290 }
21291 
21292 #if defined(SQLITE_SHELL_HAVE_RECOVER)
21293 /*
21294 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
21295 */
21296 static unsigned int get2byteInt(unsigned char *a){
21297   return (a[0]<<8) + a[1];
21298 }
21299 static unsigned int get4byteInt(unsigned char *a){
21300   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
21301 }
21302 
21303 /*
21304 ** Implementation of the ".dbinfo" command.
21305 **
21306 ** Return 1 on error, 2 to exit, and 0 otherwise.
21307 */
21308 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
21309   static const struct { const char *zName; int ofst; } aField[] = {
21310      { "file change counter:",  24  },
21311      { "database page count:",  28  },
21312      { "freelist page count:",  36  },
21313      { "schema cookie:",        40  },
21314      { "schema format:",        44  },
21315      { "default cache size:",   48  },
21316      { "autovacuum top root:",  52  },
21317      { "incremental vacuum:",   64  },
21318      { "text encoding:",        56  },
21319      { "user version:",         60  },
21320      { "application id:",       68  },
21321      { "software version:",     96  },
21322   };
21323   static const struct { const char *zName; const char *zSql; } aQuery[] = {
21324      { "number of tables:",
21325        "SELECT count(*) FROM %s WHERE type='table'" },
21326      { "number of indexes:",
21327        "SELECT count(*) FROM %s WHERE type='index'" },
21328      { "number of triggers:",
21329        "SELECT count(*) FROM %s WHERE type='trigger'" },
21330      { "number of views:",
21331        "SELECT count(*) FROM %s WHERE type='view'" },
21332      { "schema size:",
21333        "SELECT total(length(sql)) FROM %s" },
21334   };
21335   int i, rc;
21336   unsigned iDataVersion;
21337   char *zSchemaTab;
21338   char *zDb = nArg>=2 ? azArg[1] : "main";
21339   sqlite3_stmt *pStmt = 0;
21340   unsigned char aHdr[100];
21341   open_db(p, 0);
21342   if( p->db==0 ) return 1;
21343   rc = sqlite3_prepare_v2(p->db,
21344              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
21345              -1, &pStmt, 0);
21346   if( rc ){
21347     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
21348     sqlite3_finalize(pStmt);
21349     return 1;
21350   }
21351   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
21352   if( sqlite3_step(pStmt)==SQLITE_ROW
21353    && sqlite3_column_bytes(pStmt,0)>100
21354   ){
21355     memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
21356     sqlite3_finalize(pStmt);
21357   }else{
21358     raw_printf(stderr, "unable to read database header\n");
21359     sqlite3_finalize(pStmt);
21360     return 1;
21361   }
21362   i = get2byteInt(aHdr+16);
21363   if( i==1 ) i = 65536;
21364   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
21365   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
21366   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
21367   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
21368   for(i=0; i<ArraySize(aField); i++){
21369     int ofst = aField[i].ofst;
21370     unsigned int val = get4byteInt(aHdr + ofst);
21371     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
21372     switch( ofst ){
21373       case 56: {
21374         if( val==1 ) raw_printf(p->out, " (utf8)");
21375         if( val==2 ) raw_printf(p->out, " (utf16le)");
21376         if( val==3 ) raw_printf(p->out, " (utf16be)");
21377       }
21378     }
21379     raw_printf(p->out, "\n");
21380   }
21381   if( zDb==0 ){
21382     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
21383   }else if( cli_strcmp(zDb,"temp")==0 ){
21384     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
21385   }else{
21386     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
21387   }
21388   for(i=0; i<ArraySize(aQuery); i++){
21389     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
21390     int val = db_int(p->db, zSql);
21391     sqlite3_free(zSql);
21392     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
21393   }
21394   sqlite3_free(zSchemaTab);
21395   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
21396   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
21397   return 0;
21398 }
21399 #endif /* SQLITE_SHELL_HAVE_RECOVER */
21400 
21401 /*
21402 ** Print the current sqlite3_errmsg() value to stderr and return 1.
21403 */
21404 static int shellDatabaseError(sqlite3 *db){
21405   const char *zErr = sqlite3_errmsg(db);
21406   utf8_printf(stderr, "Error: %s\n", zErr);
21407   return 1;
21408 }
21409 
21410 /*
21411 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
21412 ** if they match and FALSE (0) if they do not match.
21413 **
21414 ** Globbing rules:
21415 **
21416 **      '*'       Matches any sequence of zero or more characters.
21417 **
21418 **      '?'       Matches exactly one character.
21419 **
21420 **     [...]      Matches one character from the enclosed list of
21421 **                characters.
21422 **
21423 **     [^...]     Matches one character not in the enclosed list.
21424 **
21425 **      '#'       Matches any sequence of one or more digits with an
21426 **                optional + or - sign in front
21427 **
21428 **      ' '       Any span of whitespace matches any other span of
21429 **                whitespace.
21430 **
21431 ** Extra whitespace at the end of z[] is ignored.
21432 */
21433 static int testcase_glob(const char *zGlob, const char *z){
21434   int c, c2;
21435   int invert;
21436   int seen;
21437 
21438   while( (c = (*(zGlob++)))!=0 ){
21439     if( IsSpace(c) ){
21440       if( !IsSpace(*z) ) return 0;
21441       while( IsSpace(*zGlob) ) zGlob++;
21442       while( IsSpace(*z) ) z++;
21443     }else if( c=='*' ){
21444       while( (c=(*(zGlob++))) == '*' || c=='?' ){
21445         if( c=='?' && (*(z++))==0 ) return 0;
21446       }
21447       if( c==0 ){
21448         return 1;
21449       }else if( c=='[' ){
21450         while( *z && testcase_glob(zGlob-1,z)==0 ){
21451           z++;
21452         }
21453         return (*z)!=0;
21454       }
21455       while( (c2 = (*(z++)))!=0 ){
21456         while( c2!=c ){
21457           c2 = *(z++);
21458           if( c2==0 ) return 0;
21459         }
21460         if( testcase_glob(zGlob,z) ) return 1;
21461       }
21462       return 0;
21463     }else if( c=='?' ){
21464       if( (*(z++))==0 ) return 0;
21465     }else if( c=='[' ){
21466       int prior_c = 0;
21467       seen = 0;
21468       invert = 0;
21469       c = *(z++);
21470       if( c==0 ) return 0;
21471       c2 = *(zGlob++);
21472       if( c2=='^' ){
21473         invert = 1;
21474         c2 = *(zGlob++);
21475       }
21476       if( c2==']' ){
21477         if( c==']' ) seen = 1;
21478         c2 = *(zGlob++);
21479       }
21480       while( c2 && c2!=']' ){
21481         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
21482           c2 = *(zGlob++);
21483           if( c>=prior_c && c<=c2 ) seen = 1;
21484           prior_c = 0;
21485         }else{
21486           if( c==c2 ){
21487             seen = 1;
21488           }
21489           prior_c = c2;
21490         }
21491         c2 = *(zGlob++);
21492       }
21493       if( c2==0 || (seen ^ invert)==0 ) return 0;
21494     }else if( c=='#' ){
21495       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
21496       if( !IsDigit(z[0]) ) return 0;
21497       z++;
21498       while( IsDigit(z[0]) ){ z++; }
21499     }else{
21500       if( c!=(*(z++)) ) return 0;
21501     }
21502   }
21503   while( IsSpace(*z) ){ z++; }
21504   return *z==0;
21505 }
21506 
21507 
21508 /*
21509 ** Compare the string as a command-line option with either one or two
21510 ** initial "-" characters.
21511 */
21512 static int optionMatch(const char *zStr, const char *zOpt){
21513   if( zStr[0]!='-' ) return 0;
21514   zStr++;
21515   if( zStr[0]=='-' ) zStr++;
21516   return cli_strcmp(zStr, zOpt)==0;
21517 }
21518 
21519 /*
21520 ** Delete a file.
21521 */
21522 int shellDeleteFile(const char *zFilename){
21523   int rc;
21524 #ifdef _WIN32
21525   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
21526   rc = _wunlink(z);
21527   sqlite3_free(z);
21528 #else
21529   rc = unlink(zFilename);
21530 #endif
21531   return rc;
21532 }
21533 
21534 /*
21535 ** Try to delete the temporary file (if there is one) and free the
21536 ** memory used to hold the name of the temp file.
21537 */
21538 static void clearTempFile(ShellState *p){
21539   if( p->zTempFile==0 ) return;
21540   if( p->doXdgOpen ) return;
21541   if( shellDeleteFile(p->zTempFile) ) return;
21542   sqlite3_free(p->zTempFile);
21543   p->zTempFile = 0;
21544 }
21545 
21546 /*
21547 ** Create a new temp file name with the given suffix.
21548 */
21549 static void newTempFile(ShellState *p, const char *zSuffix){
21550   clearTempFile(p);
21551   sqlite3_free(p->zTempFile);
21552   p->zTempFile = 0;
21553   if( p->db ){
21554     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
21555   }
21556   if( p->zTempFile==0 ){
21557     /* If p->db is an in-memory database then the TEMPFILENAME file-control
21558     ** will not work and we will need to fallback to guessing */
21559     char *zTemp;
21560     sqlite3_uint64 r;
21561     sqlite3_randomness(sizeof(r), &r);
21562     zTemp = getenv("TEMP");
21563     if( zTemp==0 ) zTemp = getenv("TMP");
21564     if( zTemp==0 ){
21565 #ifdef _WIN32
21566       zTemp = "\\tmp";
21567 #else
21568       zTemp = "/tmp";
21569 #endif
21570     }
21571     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
21572   }else{
21573     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
21574   }
21575   shell_check_oom(p->zTempFile);
21576 }
21577 
21578 
21579 /*
21580 ** The implementation of SQL scalar function fkey_collate_clause(), used
21581 ** by the ".lint fkey-indexes" command. This scalar function is always
21582 ** called with four arguments - the parent table name, the parent column name,
21583 ** the child table name and the child column name.
21584 **
21585 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
21586 **
21587 ** If either of the named tables or columns do not exist, this function
21588 ** returns an empty string. An empty string is also returned if both tables
21589 ** and columns exist but have the same default collation sequence. Or,
21590 ** if both exist but the default collation sequences are different, this
21591 ** function returns the string " COLLATE <parent-collation>", where
21592 ** <parent-collation> is the default collation sequence of the parent column.
21593 */
21594 static void shellFkeyCollateClause(
21595   sqlite3_context *pCtx,
21596   int nVal,
21597   sqlite3_value **apVal
21598 ){
21599   sqlite3 *db = sqlite3_context_db_handle(pCtx);
21600   const char *zParent;
21601   const char *zParentCol;
21602   const char *zParentSeq;
21603   const char *zChild;
21604   const char *zChildCol;
21605   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
21606   int rc;
21607 
21608   assert( nVal==4 );
21609   zParent = (const char*)sqlite3_value_text(apVal[0]);
21610   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
21611   zChild = (const char*)sqlite3_value_text(apVal[2]);
21612   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
21613 
21614   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
21615   rc = sqlite3_table_column_metadata(
21616       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
21617   );
21618   if( rc==SQLITE_OK ){
21619     rc = sqlite3_table_column_metadata(
21620         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
21621     );
21622   }
21623 
21624   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
21625     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
21626     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
21627     sqlite3_free(z);
21628   }
21629 }
21630 
21631 
21632 /*
21633 ** The implementation of dot-command ".lint fkey-indexes".
21634 */
21635 static int lintFkeyIndexes(
21636   ShellState *pState,             /* Current shell tool state */
21637   char **azArg,                   /* Array of arguments passed to dot command */
21638   int nArg                        /* Number of entries in azArg[] */
21639 ){
21640   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
21641   FILE *out = pState->out;        /* Stream to write non-error output to */
21642   int bVerbose = 0;               /* If -verbose is present */
21643   int bGroupByParent = 0;         /* If -groupbyparent is present */
21644   int i;                          /* To iterate through azArg[] */
21645   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
21646   int rc;                         /* Return code */
21647   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
21648 
21649   /*
21650   ** This SELECT statement returns one row for each foreign key constraint
21651   ** in the schema of the main database. The column values are:
21652   **
21653   ** 0. The text of an SQL statement similar to:
21654   **
21655   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
21656   **
21657   **    This SELECT is similar to the one that the foreign keys implementation
21658   **    needs to run internally on child tables. If there is an index that can
21659   **    be used to optimize this query, then it can also be used by the FK
21660   **    implementation to optimize DELETE or UPDATE statements on the parent
21661   **    table.
21662   **
21663   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
21664   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
21665   **    contains an index that can be used to optimize the query.
21666   **
21667   ** 2. Human readable text that describes the child table and columns. e.g.
21668   **
21669   **       "child_table(child_key1, child_key2)"
21670   **
21671   ** 3. Human readable text that describes the parent table and columns. e.g.
21672   **
21673   **       "parent_table(parent_key1, parent_key2)"
21674   **
21675   ** 4. A full CREATE INDEX statement for an index that could be used to
21676   **    optimize DELETE or UPDATE statements on the parent table. e.g.
21677   **
21678   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
21679   **
21680   ** 5. The name of the parent table.
21681   **
21682   ** These six values are used by the C logic below to generate the report.
21683   */
21684   const char *zSql =
21685   "SELECT "
21686     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
21687     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
21688     "  || fkey_collate_clause("
21689     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
21690     ", "
21691     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
21692     "  || group_concat('*=?', ' AND ') || ')'"
21693     ", "
21694     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
21695     ", "
21696     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
21697     ", "
21698     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
21699     "  || ' ON ' || quote(s.name) || '('"
21700     "  || group_concat(quote(f.[from]) ||"
21701     "        fkey_collate_clause("
21702     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
21703     "  || ');'"
21704     ", "
21705     "     f.[table] "
21706     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
21707     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
21708     "GROUP BY s.name, f.id "
21709     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
21710   ;
21711   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
21712 
21713   for(i=2; i<nArg; i++){
21714     int n = strlen30(azArg[i]);
21715     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
21716       bVerbose = 1;
21717     }
21718     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
21719       bGroupByParent = 1;
21720       zIndent = "    ";
21721     }
21722     else{
21723       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
21724           azArg[0], azArg[1]
21725       );
21726       return SQLITE_ERROR;
21727     }
21728   }
21729 
21730   /* Register the fkey_collate_clause() SQL function */
21731   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
21732       0, shellFkeyCollateClause, 0, 0
21733   );
21734 
21735 
21736   if( rc==SQLITE_OK ){
21737     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
21738   }
21739   if( rc==SQLITE_OK ){
21740     sqlite3_bind_int(pSql, 1, bGroupByParent);
21741   }
21742 
21743   if( rc==SQLITE_OK ){
21744     int rc2;
21745     char *zPrev = 0;
21746     while( SQLITE_ROW==sqlite3_step(pSql) ){
21747       int res = -1;
21748       sqlite3_stmt *pExplain = 0;
21749       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
21750       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
21751       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
21752       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
21753       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
21754       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
21755 
21756       if( zEQP==0 ) continue;
21757       if( zGlob==0 ) continue;
21758       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
21759       if( rc!=SQLITE_OK ) break;
21760       if( SQLITE_ROW==sqlite3_step(pExplain) ){
21761         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
21762         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
21763                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
21764       }
21765       rc = sqlite3_finalize(pExplain);
21766       if( rc!=SQLITE_OK ) break;
21767 
21768       if( res<0 ){
21769         raw_printf(stderr, "Error: internal error");
21770         break;
21771       }else{
21772         if( bGroupByParent
21773         && (bVerbose || res==0)
21774         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
21775         ){
21776           raw_printf(out, "-- Parent table %s\n", zParent);
21777           sqlite3_free(zPrev);
21778           zPrev = sqlite3_mprintf("%s", zParent);
21779         }
21780 
21781         if( res==0 ){
21782           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
21783         }else if( bVerbose ){
21784           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
21785               zIndent, zFrom, zTarget
21786           );
21787         }
21788       }
21789     }
21790     sqlite3_free(zPrev);
21791 
21792     if( rc!=SQLITE_OK ){
21793       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
21794     }
21795 
21796     rc2 = sqlite3_finalize(pSql);
21797     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
21798       rc = rc2;
21799       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
21800     }
21801   }else{
21802     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
21803   }
21804 
21805   return rc;
21806 }
21807 
21808 /*
21809 ** Implementation of ".lint" dot command.
21810 */
21811 static int lintDotCommand(
21812   ShellState *pState,             /* Current shell tool state */
21813   char **azArg,                   /* Array of arguments passed to dot command */
21814   int nArg                        /* Number of entries in azArg[] */
21815 ){
21816   int n;
21817   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
21818   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
21819   return lintFkeyIndexes(pState, azArg, nArg);
21820 
21821  usage:
21822   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
21823   raw_printf(stderr, "Where sub-commands are:\n");
21824   raw_printf(stderr, "    fkey-indexes\n");
21825   return SQLITE_ERROR;
21826 }
21827 
21828 #if !defined SQLITE_OMIT_VIRTUALTABLE
21829 static void shellPrepare(
21830   sqlite3 *db,
21831   int *pRc,
21832   const char *zSql,
21833   sqlite3_stmt **ppStmt
21834 ){
21835   *ppStmt = 0;
21836   if( *pRc==SQLITE_OK ){
21837     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
21838     if( rc!=SQLITE_OK ){
21839       raw_printf(stderr, "sql error: %s (%d)\n",
21840           sqlite3_errmsg(db), sqlite3_errcode(db)
21841       );
21842       *pRc = rc;
21843     }
21844   }
21845 }
21846 
21847 /*
21848 ** Create a prepared statement using printf-style arguments for the SQL.
21849 **
21850 ** This routine is could be marked "static".  But it is not always used,
21851 ** depending on compile-time options.  By omitting the "static", we avoid
21852 ** nuisance compiler warnings about "defined but not used".
21853 */
21854 void shellPreparePrintf(
21855   sqlite3 *db,
21856   int *pRc,
21857   sqlite3_stmt **ppStmt,
21858   const char *zFmt,
21859   ...
21860 ){
21861   *ppStmt = 0;
21862   if( *pRc==SQLITE_OK ){
21863     va_list ap;
21864     char *z;
21865     va_start(ap, zFmt);
21866     z = sqlite3_vmprintf(zFmt, ap);
21867     va_end(ap);
21868     if( z==0 ){
21869       *pRc = SQLITE_NOMEM;
21870     }else{
21871       shellPrepare(db, pRc, z, ppStmt);
21872       sqlite3_free(z);
21873     }
21874   }
21875 }
21876 
21877 /* Finalize the prepared statement created using shellPreparePrintf().
21878 **
21879 ** This routine is could be marked "static".  But it is not always used,
21880 ** depending on compile-time options.  By omitting the "static", we avoid
21881 ** nuisance compiler warnings about "defined but not used".
21882 */
21883 void shellFinalize(
21884   int *pRc,
21885   sqlite3_stmt *pStmt
21886 ){
21887   if( pStmt ){
21888     sqlite3 *db = sqlite3_db_handle(pStmt);
21889     int rc = sqlite3_finalize(pStmt);
21890     if( *pRc==SQLITE_OK ){
21891       if( rc!=SQLITE_OK ){
21892         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
21893       }
21894       *pRc = rc;
21895     }
21896   }
21897 }
21898 
21899 /* Reset the prepared statement created using shellPreparePrintf().
21900 **
21901 ** This routine is could be marked "static".  But it is not always used,
21902 ** depending on compile-time options.  By omitting the "static", we avoid
21903 ** nuisance compiler warnings about "defined but not used".
21904 */
21905 void shellReset(
21906   int *pRc,
21907   sqlite3_stmt *pStmt
21908 ){
21909   int rc = sqlite3_reset(pStmt);
21910   if( *pRc==SQLITE_OK ){
21911     if( rc!=SQLITE_OK ){
21912       sqlite3 *db = sqlite3_db_handle(pStmt);
21913       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
21914     }
21915     *pRc = rc;
21916   }
21917 }
21918 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
21919 
21920 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
21921 /******************************************************************************
21922 ** The ".archive" or ".ar" command.
21923 */
21924 /*
21925 ** Structure representing a single ".ar" command.
21926 */
21927 typedef struct ArCommand ArCommand;
21928 struct ArCommand {
21929   u8 eCmd;                        /* An AR_CMD_* value */
21930   u8 bVerbose;                    /* True if --verbose */
21931   u8 bZip;                        /* True if the archive is a ZIP */
21932   u8 bDryRun;                     /* True if --dry-run */
21933   u8 bAppend;                     /* True if --append */
21934   u8 bGlob;                       /* True if --glob */
21935   u8 fromCmdLine;                 /* Run from -A instead of .archive */
21936   int nArg;                       /* Number of command arguments */
21937   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
21938   const char *zFile;              /* --file argument, or NULL */
21939   const char *zDir;               /* --directory argument, or NULL */
21940   char **azArg;                   /* Array of command arguments */
21941   ShellState *p;                  /* Shell state */
21942   sqlite3 *db;                    /* Database containing the archive */
21943 };
21944 
21945 /*
21946 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
21947 */
21948 static int arUsage(FILE *f){
21949   showHelp(f,"archive");
21950   return SQLITE_ERROR;
21951 }
21952 
21953 /*
21954 ** Print an error message for the .ar command to stderr and return
21955 ** SQLITE_ERROR.
21956 */
21957 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
21958   va_list ap;
21959   char *z;
21960   va_start(ap, zFmt);
21961   z = sqlite3_vmprintf(zFmt, ap);
21962   va_end(ap);
21963   utf8_printf(stderr, "Error: %s\n", z);
21964   if( pAr->fromCmdLine ){
21965     utf8_printf(stderr, "Use \"-A\" for more help\n");
21966   }else{
21967     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
21968   }
21969   sqlite3_free(z);
21970   return SQLITE_ERROR;
21971 }
21972 
21973 /*
21974 ** Values for ArCommand.eCmd.
21975 */
21976 #define AR_CMD_CREATE       1
21977 #define AR_CMD_UPDATE       2
21978 #define AR_CMD_INSERT       3
21979 #define AR_CMD_EXTRACT      4
21980 #define AR_CMD_LIST         5
21981 #define AR_CMD_HELP         6
21982 #define AR_CMD_REMOVE       7
21983 
21984 /*
21985 ** Other (non-command) switches.
21986 */
21987 #define AR_SWITCH_VERBOSE     8
21988 #define AR_SWITCH_FILE        9
21989 #define AR_SWITCH_DIRECTORY  10
21990 #define AR_SWITCH_APPEND     11
21991 #define AR_SWITCH_DRYRUN     12
21992 #define AR_SWITCH_GLOB       13
21993 
21994 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
21995   switch( eSwitch ){
21996     case AR_CMD_CREATE:
21997     case AR_CMD_EXTRACT:
21998     case AR_CMD_LIST:
21999     case AR_CMD_REMOVE:
22000     case AR_CMD_UPDATE:
22001     case AR_CMD_INSERT:
22002     case AR_CMD_HELP:
22003       if( pAr->eCmd ){
22004         return arErrorMsg(pAr, "multiple command options");
22005       }
22006       pAr->eCmd = eSwitch;
22007       break;
22008 
22009     case AR_SWITCH_DRYRUN:
22010       pAr->bDryRun = 1;
22011       break;
22012     case AR_SWITCH_GLOB:
22013       pAr->bGlob = 1;
22014       break;
22015     case AR_SWITCH_VERBOSE:
22016       pAr->bVerbose = 1;
22017       break;
22018     case AR_SWITCH_APPEND:
22019       pAr->bAppend = 1;
22020       deliberate_fall_through;
22021     case AR_SWITCH_FILE:
22022       pAr->zFile = zArg;
22023       break;
22024     case AR_SWITCH_DIRECTORY:
22025       pAr->zDir = zArg;
22026       break;
22027   }
22028 
22029   return SQLITE_OK;
22030 }
22031 
22032 /*
22033 ** Parse the command line for an ".ar" command. The results are written into
22034 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
22035 ** successfully, otherwise an error message is written to stderr and
22036 ** SQLITE_ERROR returned.
22037 */
22038 static int arParseCommand(
22039   char **azArg,                   /* Array of arguments passed to dot command */
22040   int nArg,                       /* Number of entries in azArg[] */
22041   ArCommand *pAr                  /* Populate this object */
22042 ){
22043   struct ArSwitch {
22044     const char *zLong;
22045     char cShort;
22046     u8 eSwitch;
22047     u8 bArg;
22048   } aSwitch[] = {
22049     { "create",    'c', AR_CMD_CREATE,       0 },
22050     { "extract",   'x', AR_CMD_EXTRACT,      0 },
22051     { "insert",    'i', AR_CMD_INSERT,       0 },
22052     { "list",      't', AR_CMD_LIST,         0 },
22053     { "remove",    'r', AR_CMD_REMOVE,       0 },
22054     { "update",    'u', AR_CMD_UPDATE,       0 },
22055     { "help",      'h', AR_CMD_HELP,         0 },
22056     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
22057     { "file",      'f', AR_SWITCH_FILE,      1 },
22058     { "append",    'a', AR_SWITCH_APPEND,    1 },
22059     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
22060     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
22061     { "glob",      'g', AR_SWITCH_GLOB,      0 },
22062   };
22063   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
22064   struct ArSwitch *pEnd = &aSwitch[nSwitch];
22065 
22066   if( nArg<=1 ){
22067     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
22068     return arUsage(stderr);
22069   }else{
22070     char *z = azArg[1];
22071     if( z[0]!='-' ){
22072       /* Traditional style [tar] invocation */
22073       int i;
22074       int iArg = 2;
22075       for(i=0; z[i]; i++){
22076         const char *zArg = 0;
22077         struct ArSwitch *pOpt;
22078         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22079           if( z[i]==pOpt->cShort ) break;
22080         }
22081         if( pOpt==pEnd ){
22082           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
22083         }
22084         if( pOpt->bArg ){
22085           if( iArg>=nArg ){
22086             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
22087           }
22088           zArg = azArg[iArg++];
22089         }
22090         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
22091       }
22092       pAr->nArg = nArg-iArg;
22093       if( pAr->nArg>0 ){
22094         pAr->azArg = &azArg[iArg];
22095       }
22096     }else{
22097       /* Non-traditional invocation */
22098       int iArg;
22099       for(iArg=1; iArg<nArg; iArg++){
22100         int n;
22101         z = azArg[iArg];
22102         if( z[0]!='-' ){
22103           /* All remaining command line words are command arguments. */
22104           pAr->azArg = &azArg[iArg];
22105           pAr->nArg = nArg-iArg;
22106           break;
22107         }
22108         n = strlen30(z);
22109 
22110         if( z[1]!='-' ){
22111           int i;
22112           /* One or more short options */
22113           for(i=1; i<n; i++){
22114             const char *zArg = 0;
22115             struct ArSwitch *pOpt;
22116             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22117               if( z[i]==pOpt->cShort ) break;
22118             }
22119             if( pOpt==pEnd ){
22120               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
22121             }
22122             if( pOpt->bArg ){
22123               if( i<(n-1) ){
22124                 zArg = &z[i+1];
22125                 i = n;
22126               }else{
22127                 if( iArg>=(nArg-1) ){
22128                   return arErrorMsg(pAr, "option requires an argument: %c",
22129                                     z[i]);
22130                 }
22131                 zArg = azArg[++iArg];
22132               }
22133             }
22134             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
22135           }
22136         }else if( z[2]=='\0' ){
22137           /* A -- option, indicating that all remaining command line words
22138           ** are command arguments.  */
22139           pAr->azArg = &azArg[iArg+1];
22140           pAr->nArg = nArg-iArg-1;
22141           break;
22142         }else{
22143           /* A long option */
22144           const char *zArg = 0;             /* Argument for option, if any */
22145           struct ArSwitch *pMatch = 0;      /* Matching option */
22146           struct ArSwitch *pOpt;            /* Iterator */
22147           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
22148             const char *zLong = pOpt->zLong;
22149             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
22150               if( pMatch ){
22151                 return arErrorMsg(pAr, "ambiguous option: %s",z);
22152               }else{
22153                 pMatch = pOpt;
22154               }
22155             }
22156           }
22157 
22158           if( pMatch==0 ){
22159             return arErrorMsg(pAr, "unrecognized option: %s", z);
22160           }
22161           if( pMatch->bArg ){
22162             if( iArg>=(nArg-1) ){
22163               return arErrorMsg(pAr, "option requires an argument: %s", z);
22164             }
22165             zArg = azArg[++iArg];
22166           }
22167           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
22168         }
22169       }
22170     }
22171   }
22172 
22173   return SQLITE_OK;
22174 }
22175 
22176 /*
22177 ** This function assumes that all arguments within the ArCommand.azArg[]
22178 ** array refer to archive members, as for the --extract, --list or --remove
22179 ** commands. It checks that each of them are "present". If any specified
22180 ** file is not present in the archive, an error is printed to stderr and an
22181 ** error code returned. Otherwise, if all specified arguments are present
22182 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
22183 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
22184 ** when pAr->bGlob is true.
22185 **
22186 ** This function strips any trailing '/' characters from each argument.
22187 ** This is consistent with the way the [tar] command seems to work on
22188 ** Linux.
22189 */
22190 static int arCheckEntries(ArCommand *pAr){
22191   int rc = SQLITE_OK;
22192   if( pAr->nArg ){
22193     int i, j;
22194     sqlite3_stmt *pTest = 0;
22195     const char *zSel = (pAr->bGlob)
22196       ? "SELECT name FROM %s WHERE glob($name,name)"
22197       : "SELECT name FROM %s WHERE name=$name";
22198 
22199     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
22200     j = sqlite3_bind_parameter_index(pTest, "$name");
22201     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
22202       char *z = pAr->azArg[i];
22203       int n = strlen30(z);
22204       int bOk = 0;
22205       while( n>0 && z[n-1]=='/' ) n--;
22206       z[n] = '\0';
22207       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
22208       if( SQLITE_ROW==sqlite3_step(pTest) ){
22209         bOk = 1;
22210       }
22211       shellReset(&rc, pTest);
22212       if( rc==SQLITE_OK && bOk==0 ){
22213         utf8_printf(stderr, "not found in archive: %s\n", z);
22214         rc = SQLITE_ERROR;
22215       }
22216     }
22217     shellFinalize(&rc, pTest);
22218   }
22219   return rc;
22220 }
22221 
22222 /*
22223 ** Format a WHERE clause that can be used against the "sqlar" table to
22224 ** identify all archive members that match the command arguments held
22225 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
22226 ** The caller is responsible for eventually calling sqlite3_free() on
22227 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
22228 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
22229 */
22230 static void arWhereClause(
22231   int *pRc,
22232   ArCommand *pAr,
22233   char **pzWhere                  /* OUT: New WHERE clause */
22234 ){
22235   char *zWhere = 0;
22236   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
22237   if( *pRc==SQLITE_OK ){
22238     if( pAr->nArg==0 ){
22239       zWhere = sqlite3_mprintf("1");
22240     }else{
22241       int i;
22242       const char *zSep = "";
22243       for(i=0; i<pAr->nArg; i++){
22244         const char *z = pAr->azArg[i];
22245         zWhere = sqlite3_mprintf(
22246           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
22247           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
22248         );
22249         if( zWhere==0 ){
22250           *pRc = SQLITE_NOMEM;
22251           break;
22252         }
22253         zSep = " OR ";
22254       }
22255     }
22256   }
22257   *pzWhere = zWhere;
22258 }
22259 
22260 /*
22261 ** Implementation of .ar "lisT" command.
22262 */
22263 static int arListCommand(ArCommand *pAr){
22264   const char *zSql = "SELECT %s FROM %s WHERE %s";
22265   const char *azCols[] = {
22266     "name",
22267     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
22268   };
22269 
22270   char *zWhere = 0;
22271   sqlite3_stmt *pSql = 0;
22272   int rc;
22273 
22274   rc = arCheckEntries(pAr);
22275   arWhereClause(&rc, pAr, &zWhere);
22276 
22277   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
22278                      pAr->zSrcTable, zWhere);
22279   if( pAr->bDryRun ){
22280     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
22281   }else{
22282     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
22283       if( pAr->bVerbose ){
22284         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
22285             sqlite3_column_text(pSql, 0),
22286             sqlite3_column_int(pSql, 1),
22287             sqlite3_column_text(pSql, 2),
22288             sqlite3_column_text(pSql, 3)
22289         );
22290       }else{
22291         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
22292       }
22293     }
22294   }
22295   shellFinalize(&rc, pSql);
22296   sqlite3_free(zWhere);
22297   return rc;
22298 }
22299 
22300 
22301 /*
22302 ** Implementation of .ar "Remove" command.
22303 */
22304 static int arRemoveCommand(ArCommand *pAr){
22305   int rc = 0;
22306   char *zSql = 0;
22307   char *zWhere = 0;
22308 
22309   if( pAr->nArg ){
22310     /* Verify that args actually exist within the archive before proceeding.
22311     ** And formulate a WHERE clause to match them.  */
22312     rc = arCheckEntries(pAr);
22313     arWhereClause(&rc, pAr, &zWhere);
22314   }
22315   if( rc==SQLITE_OK ){
22316     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
22317                            pAr->zSrcTable, zWhere);
22318     if( pAr->bDryRun ){
22319       utf8_printf(pAr->p->out, "%s\n", zSql);
22320     }else{
22321       char *zErr = 0;
22322       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
22323       if( rc==SQLITE_OK ){
22324         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
22325         if( rc!=SQLITE_OK ){
22326           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
22327         }else{
22328           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
22329         }
22330       }
22331       if( zErr ){
22332         utf8_printf(stdout, "ERROR: %s\n", zErr);
22333         sqlite3_free(zErr);
22334       }
22335     }
22336   }
22337   sqlite3_free(zWhere);
22338   sqlite3_free(zSql);
22339   return rc;
22340 }
22341 
22342 /*
22343 ** Implementation of .ar "eXtract" command.
22344 */
22345 static int arExtractCommand(ArCommand *pAr){
22346   const char *zSql1 =
22347     "SELECT "
22348     " ($dir || name),"
22349     " writefile(($dir || name), %s, mode, mtime) "
22350     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
22351     " AND name NOT GLOB '*..[/\\]*'";
22352 
22353   const char *azExtraArg[] = {
22354     "sqlar_uncompress(data, sz)",
22355     "data"
22356   };
22357 
22358   sqlite3_stmt *pSql = 0;
22359   int rc = SQLITE_OK;
22360   char *zDir = 0;
22361   char *zWhere = 0;
22362   int i, j;
22363 
22364   /* If arguments are specified, check that they actually exist within
22365   ** the archive before proceeding. And formulate a WHERE clause to
22366   ** match them.  */
22367   rc = arCheckEntries(pAr);
22368   arWhereClause(&rc, pAr, &zWhere);
22369 
22370   if( rc==SQLITE_OK ){
22371     if( pAr->zDir ){
22372       zDir = sqlite3_mprintf("%s/", pAr->zDir);
22373     }else{
22374       zDir = sqlite3_mprintf("");
22375     }
22376     if( zDir==0 ) rc = SQLITE_NOMEM;
22377   }
22378 
22379   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
22380       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
22381   );
22382 
22383   if( rc==SQLITE_OK ){
22384     j = sqlite3_bind_parameter_index(pSql, "$dir");
22385     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
22386 
22387     /* Run the SELECT statement twice. The first time, writefile() is called
22388     ** for all archive members that should be extracted. The second time,
22389     ** only for the directories. This is because the timestamps for
22390     ** extracted directories must be reset after they are populated (as
22391     ** populating them changes the timestamp).  */
22392     for(i=0; i<2; i++){
22393       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
22394       sqlite3_bind_int(pSql, j, i);
22395       if( pAr->bDryRun ){
22396         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
22397       }else{
22398         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
22399           if( i==0 && pAr->bVerbose ){
22400             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
22401           }
22402         }
22403       }
22404       shellReset(&rc, pSql);
22405     }
22406     shellFinalize(&rc, pSql);
22407   }
22408 
22409   sqlite3_free(zDir);
22410   sqlite3_free(zWhere);
22411   return rc;
22412 }
22413 
22414 /*
22415 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
22416 */
22417 static int arExecSql(ArCommand *pAr, const char *zSql){
22418   int rc;
22419   if( pAr->bDryRun ){
22420     utf8_printf(pAr->p->out, "%s\n", zSql);
22421     rc = SQLITE_OK;
22422   }else{
22423     char *zErr = 0;
22424     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
22425     if( zErr ){
22426       utf8_printf(stdout, "ERROR: %s\n", zErr);
22427       sqlite3_free(zErr);
22428     }
22429   }
22430   return rc;
22431 }
22432 
22433 
22434 /*
22435 ** Implementation of .ar "create", "insert", and "update" commands.
22436 **
22437 **     create    ->     Create a new SQL archive
22438 **     insert    ->     Insert or reinsert all files listed
22439 **     update    ->     Insert files that have changed or that were not
22440 **                      previously in the archive
22441 **
22442 ** Create the "sqlar" table in the database if it does not already exist.
22443 ** Then add each file in the azFile[] array to the archive. Directories
22444 ** are added recursively. If argument bVerbose is non-zero, a message is
22445 ** printed on stdout for each file archived.
22446 **
22447 ** The create command is the same as update, except that it drops
22448 ** any existing "sqlar" table before beginning.  The "insert" command
22449 ** always overwrites every file named on the command-line, where as
22450 ** "update" only overwrites if the size or mtime or mode has changed.
22451 */
22452 static int arCreateOrUpdateCommand(
22453   ArCommand *pAr,                 /* Command arguments and options */
22454   int bUpdate,                    /* true for a --create. */
22455   int bOnlyIfChanged              /* Only update if file has changed */
22456 ){
22457   const char *zCreate =
22458       "CREATE TABLE IF NOT EXISTS sqlar(\n"
22459       "  name TEXT PRIMARY KEY,  -- name of the file\n"
22460       "  mode INT,               -- access permissions\n"
22461       "  mtime INT,              -- last modification time\n"
22462       "  sz INT,                 -- original file size\n"
22463       "  data BLOB               -- compressed content\n"
22464       ")";
22465   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
22466   const char *zInsertFmt[2] = {
22467      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
22468      "  SELECT\n"
22469      "    %s,\n"
22470      "    mode,\n"
22471      "    mtime,\n"
22472      "    CASE substr(lsmode(mode),1,1)\n"
22473      "      WHEN '-' THEN length(data)\n"
22474      "      WHEN 'd' THEN 0\n"
22475      "      ELSE -1 END,\n"
22476      "    sqlar_compress(data)\n"
22477      "  FROM fsdir(%Q,%Q) AS disk\n"
22478      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
22479      ,
22480      "REPLACE INTO %s(name,mode,mtime,data)\n"
22481      "  SELECT\n"
22482      "    %s,\n"
22483      "    mode,\n"
22484      "    mtime,\n"
22485      "    data\n"
22486      "  FROM fsdir(%Q,%Q) AS disk\n"
22487      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
22488   };
22489   int i;                          /* For iterating through azFile[] */
22490   int rc;                         /* Return code */
22491   const char *zTab = 0;           /* SQL table into which to insert */
22492   char *zSql;
22493   char zTemp[50];
22494   char *zExists = 0;
22495 
22496   arExecSql(pAr, "PRAGMA page_size=512");
22497   rc = arExecSql(pAr, "SAVEPOINT ar;");
22498   if( rc!=SQLITE_OK ) return rc;
22499   zTemp[0] = 0;
22500   if( pAr->bZip ){
22501     /* Initialize the zipfile virtual table, if necessary */
22502     if( pAr->zFile ){
22503       sqlite3_uint64 r;
22504       sqlite3_randomness(sizeof(r),&r);
22505       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
22506       zTab = zTemp;
22507       zSql = sqlite3_mprintf(
22508          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
22509          zTab, pAr->zFile
22510       );
22511       rc = arExecSql(pAr, zSql);
22512       sqlite3_free(zSql);
22513     }else{
22514       zTab = "zip";
22515     }
22516   }else{
22517     /* Initialize the table for an SQLAR */
22518     zTab = "sqlar";
22519     if( bUpdate==0 ){
22520       rc = arExecSql(pAr, zDrop);
22521       if( rc!=SQLITE_OK ) goto end_ar_transaction;
22522     }
22523     rc = arExecSql(pAr, zCreate);
22524   }
22525   if( bOnlyIfChanged ){
22526     zExists = sqlite3_mprintf(
22527       " AND NOT EXISTS("
22528           "SELECT 1 FROM %s AS mem"
22529           " WHERE mem.name=disk.name"
22530           " AND mem.mtime=disk.mtime"
22531           " AND mem.mode=disk.mode)", zTab);
22532   }else{
22533     zExists = sqlite3_mprintf("");
22534   }
22535   if( zExists==0 ) rc = SQLITE_NOMEM;
22536   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
22537     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
22538         pAr->bVerbose ? "shell_putsnl(name)" : "name",
22539         pAr->azArg[i], pAr->zDir, zExists);
22540     rc = arExecSql(pAr, zSql2);
22541     sqlite3_free(zSql2);
22542   }
22543 end_ar_transaction:
22544   if( rc!=SQLITE_OK ){
22545     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
22546   }else{
22547     rc = arExecSql(pAr, "RELEASE ar;");
22548     if( pAr->bZip && pAr->zFile ){
22549       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
22550       arExecSql(pAr, zSql);
22551       sqlite3_free(zSql);
22552     }
22553   }
22554   sqlite3_free(zExists);
22555   return rc;
22556 }
22557 
22558 /*
22559 ** Implementation of ".ar" dot command.
22560 */
22561 static int arDotCommand(
22562   ShellState *pState,          /* Current shell tool state */
22563   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
22564   char **azArg,                /* Array of arguments passed to dot command */
22565   int nArg                     /* Number of entries in azArg[] */
22566 ){
22567   ArCommand cmd;
22568   int rc;
22569   memset(&cmd, 0, sizeof(cmd));
22570   cmd.fromCmdLine = fromCmdLine;
22571   rc = arParseCommand(azArg, nArg, &cmd);
22572   if( rc==SQLITE_OK ){
22573     int eDbType = SHELL_OPEN_UNSPEC;
22574     cmd.p = pState;
22575     cmd.db = pState->db;
22576     if( cmd.zFile ){
22577       eDbType = deduceDatabaseType(cmd.zFile, 1);
22578     }else{
22579       eDbType = pState->openMode;
22580     }
22581     if( eDbType==SHELL_OPEN_ZIPFILE ){
22582       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
22583         if( cmd.zFile==0 ){
22584           cmd.zSrcTable = sqlite3_mprintf("zip");
22585         }else{
22586           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
22587         }
22588       }
22589       cmd.bZip = 1;
22590     }else if( cmd.zFile ){
22591       int flags;
22592       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
22593       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
22594            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
22595         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
22596       }else{
22597         flags = SQLITE_OPEN_READONLY;
22598       }
22599       cmd.db = 0;
22600       if( cmd.bDryRun ){
22601         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
22602              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
22603       }
22604       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
22605              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
22606       if( rc!=SQLITE_OK ){
22607         utf8_printf(stderr, "cannot open file: %s (%s)\n",
22608             cmd.zFile, sqlite3_errmsg(cmd.db)
22609         );
22610         goto end_ar_command;
22611       }
22612       sqlite3_fileio_init(cmd.db, 0, 0);
22613       sqlite3_sqlar_init(cmd.db, 0, 0);
22614       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
22615                               shellPutsFunc, 0, 0);
22616 
22617     }
22618     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
22619       if( cmd.eCmd!=AR_CMD_CREATE
22620        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
22621       ){
22622         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
22623         rc = SQLITE_ERROR;
22624         goto end_ar_command;
22625       }
22626       cmd.zSrcTable = sqlite3_mprintf("sqlar");
22627     }
22628 
22629     switch( cmd.eCmd ){
22630       case AR_CMD_CREATE:
22631         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
22632         break;
22633 
22634       case AR_CMD_EXTRACT:
22635         rc = arExtractCommand(&cmd);
22636         break;
22637 
22638       case AR_CMD_LIST:
22639         rc = arListCommand(&cmd);
22640         break;
22641 
22642       case AR_CMD_HELP:
22643         arUsage(pState->out);
22644         break;
22645 
22646       case AR_CMD_INSERT:
22647         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
22648         break;
22649 
22650       case AR_CMD_REMOVE:
22651         rc = arRemoveCommand(&cmd);
22652         break;
22653 
22654       default:
22655         assert( cmd.eCmd==AR_CMD_UPDATE );
22656         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
22657         break;
22658     }
22659   }
22660 end_ar_command:
22661   if( cmd.db!=pState->db ){
22662     close_db(cmd.db);
22663   }
22664   sqlite3_free(cmd.zSrcTable);
22665 
22666   return rc;
22667 }
22668 /* End of the ".archive" or ".ar" command logic
22669 *******************************************************************************/
22670 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
22671 
22672 #if SQLITE_SHELL_HAVE_RECOVER
22673 
22674 /*
22675 ** This function is used as a callback by the recover extension. Simply
22676 ** print the supplied SQL statement to stdout.
22677 */
22678 static int recoverSqlCb(void *pCtx, const char *zSql){
22679   ShellState *pState = (ShellState*)pCtx;
22680   utf8_printf(pState->out, "%s;\n", zSql);
22681   return SQLITE_OK;
22682 }
22683 
22684 /*
22685 ** This function is called to recover data from the database. A script
22686 ** to construct a new database containing all recovered data is output
22687 ** on stream pState->out.
22688 */
22689 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
22690   int rc = SQLITE_OK;
22691   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
22692   const char *zLAF = "lost_and_found";
22693   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
22694   int bRowids = 1;                /* 0 if --no-rowids */
22695   sqlite3_recover *p = 0;
22696   int i = 0;
22697 
22698   for(i=1; i<nArg; i++){
22699     char *z = azArg[i];
22700     int n;
22701     if( z[0]=='-' && z[1]=='-' ) z++;
22702     n = strlen30(z);
22703     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
22704       bFreelist = 0;
22705     }else
22706     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
22707       /* This option determines the name of the ATTACH-ed database used
22708       ** internally by the recovery extension.  The default is "" which
22709       ** means to use a temporary database that is automatically deleted
22710       ** when closed.  This option is undocumented and might disappear at
22711       ** any moment. */
22712       i++;
22713       zRecoveryDb = azArg[i];
22714     }else
22715     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
22716       i++;
22717       zLAF = azArg[i];
22718     }else
22719     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
22720       bRowids = 0;
22721     }
22722     else{
22723       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
22724       showHelp(pState->out, azArg[0]);
22725       return 1;
22726     }
22727   }
22728 
22729   p = sqlite3_recover_init_sql(
22730       pState->db, "main", recoverSqlCb, (void*)pState
22731   );
22732 
22733   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
22734   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
22735   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
22736   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
22737 
22738   sqlite3_recover_run(p);
22739   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
22740     const char *zErr = sqlite3_recover_errmsg(p);
22741     int errCode = sqlite3_recover_errcode(p);
22742     raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
22743   }
22744   rc = sqlite3_recover_finish(p);
22745   return rc;
22746 }
22747 #endif /* SQLITE_SHELL_HAVE_RECOVER */
22748 
22749 
22750 /*
22751  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
22752  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
22753  *   close db and set it to 0, and return the columns spec, to later
22754  *   be sqlite3_free()'ed by the caller.
22755  * The return is 0 when either:
22756  *   (a) The db was not initialized and zCol==0 (There are no columns.)
22757  *   (b) zCol!=0  (Column was added, db initialized as needed.)
22758  * The 3rd argument, pRenamed, references an out parameter. If the
22759  * pointer is non-zero, its referent will be set to a summary of renames
22760  * done if renaming was necessary, or set to 0 if none was done. The out
22761  * string (if any) must be sqlite3_free()'ed by the caller.
22762  */
22763 #ifdef SHELL_DEBUG
22764 #define rc_err_oom_die(rc) \
22765   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
22766   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
22767     fprintf(stderr,"E:%d\n",rc), assert(0)
22768 #else
22769 static void rc_err_oom_die(int rc){
22770   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
22771   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
22772 }
22773 #endif
22774 
22775 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
22776 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
22777 #else  /* Otherwise, memory is faster/better for the transient DB. */
22778 static const char *zCOL_DB = ":memory:";
22779 #endif
22780 
22781 /* Define character (as C string) to separate generated column ordinal
22782  * from protected part of incoming column names. This defaults to "_"
22783  * so that incoming column identifiers that did not need not be quoted
22784  * remain usable without being quoted. It must be one character.
22785  */
22786 #ifndef SHELL_AUTOCOLUMN_SEP
22787 # define AUTOCOLUMN_SEP "_"
22788 #else
22789 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
22790 #endif
22791 
22792 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
22793   /* Queries and D{D,M}L used here */
22794   static const char * const zTabMake = "\
22795 CREATE TABLE ColNames(\
22796  cpos INTEGER PRIMARY KEY,\
22797  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
22798 CREATE VIEW RepeatedNames AS \
22799 SELECT DISTINCT t.name FROM ColNames t \
22800 WHERE t.name COLLATE NOCASE IN (\
22801  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
22802 );\
22803 ";
22804   static const char * const zTabFill = "\
22805 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
22806  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
22807 ";
22808   static const char * const zHasDupes = "\
22809 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
22810  <count(name) FROM ColNames\
22811 ";
22812 #ifdef SHELL_COLUMN_RENAME_CLEAN
22813   static const char * const zDedoctor = "\
22814 UPDATE ColNames SET chop=iif(\
22815   (substring(name,nlen,1) BETWEEN '0' AND '9')\
22816   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
22817  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
22818  0\
22819 )\
22820 ";
22821 #endif
22822   static const char * const zSetReps = "\
22823 UPDATE ColNames AS t SET reps=\
22824 (SELECT count(*) FROM ColNames d \
22825  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
22826  COLLATE NOCASE\
22827 )\
22828 ";
22829 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
22830   static const char * const zColDigits = "\
22831 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
22832 ";
22833 #else
22834   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
22835   static const char * const zColDigits = "\
22836 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
22837  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
22838  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
22839 ";
22840 #endif
22841   static const char * const zRenameRank =
22842 #ifdef SHELL_COLUMN_RENAME_CLEAN
22843     "UPDATE ColNames AS t SET suff="
22844     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
22845 #else /* ...RENAME_MINIMAL_ONE_PASS */
22846 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
22847 "  SELECT 0 AS nlz"
22848 "  UNION"
22849 "  SELECT nlz+1 AS nlz FROM Lzn"
22850 "  WHERE EXISTS("
22851 "   SELECT 1"
22852 "   FROM ColNames t, ColNames o"
22853 "   WHERE"
22854 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
22855 "     printf('%s"AUTOCOLUMN_SEP"%s',"
22856 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
22857 "     t.name"
22858 "    )"
22859 "    ="
22860 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
22861 "     printf('%s"AUTOCOLUMN_SEP"%s',"
22862 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
22863 "     o.name"
22864 "    )"
22865 "    COLLATE NOCASE"
22866 "    AND o.cpos<>t.cpos"
22867 "   GROUP BY t.cpos"
22868 "  )"
22869 ") UPDATE Colnames AS t SET"
22870 " chop = 0," /* No chopping, never touch incoming names. */
22871 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
22872 "  printf('"AUTOCOLUMN_SEP"%s', substring("
22873 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
22874 "  ''"
22875 " )"
22876 #endif
22877     ;
22878   static const char * const zCollectVar = "\
22879 SELECT\
22880  '('||x'0a'\
22881  || group_concat(\
22882   cname||' TEXT',\
22883   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
22884  ||')' AS ColsSpec \
22885 FROM (\
22886  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
22887  FROM ColNames ORDER BY cpos\
22888 )";
22889   static const char * const zRenamesDone =
22890     "SELECT group_concat("
22891     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
22892     " ','||x'0a')"
22893     "FROM ColNames WHERE suff<>'' OR chop!=0"
22894     ;
22895   int rc;
22896   sqlite3_stmt *pStmt = 0;
22897   assert(pDb!=0);
22898   if( zColNew ){
22899     /* Add initial or additional column. Init db if necessary. */
22900     if( *pDb==0 ){
22901       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
22902 #ifdef SHELL_COLFIX_DB
22903       if(*zCOL_DB!=':')
22904         sqlite3_exec(*pDb,"drop table if exists ColNames;"
22905                      "drop view if exists RepeatedNames;",0,0,0);
22906 #endif
22907       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
22908       rc_err_oom_die(rc);
22909     }
22910     assert(*pDb!=0);
22911     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
22912     rc_err_oom_die(rc);
22913     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
22914     rc_err_oom_die(rc);
22915     rc = sqlite3_step(pStmt);
22916     rc_err_oom_die(rc);
22917     sqlite3_finalize(pStmt);
22918     return 0;
22919   }else if( *pDb==0 ){
22920     return 0;
22921   }else{
22922     /* Formulate the columns spec, close the DB, zero *pDb. */
22923     char *zColsSpec = 0;
22924     int hasDupes = db_int(*pDb, zHasDupes);
22925     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
22926     if( hasDupes ){
22927 #ifdef SHELL_COLUMN_RENAME_CLEAN
22928       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
22929       rc_err_oom_die(rc);
22930 #endif
22931       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
22932       rc_err_oom_die(rc);
22933       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
22934       rc_err_oom_die(rc);
22935       sqlite3_bind_int(pStmt, 1, nDigits);
22936       rc = sqlite3_step(pStmt);
22937       sqlite3_finalize(pStmt);
22938       assert(rc==SQLITE_DONE);
22939     }
22940     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
22941     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
22942     rc_err_oom_die(rc);
22943     rc = sqlite3_step(pStmt);
22944     if( rc==SQLITE_ROW ){
22945       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
22946     }else{
22947       zColsSpec = 0;
22948     }
22949     if( pzRenamed!=0 ){
22950       if( !hasDupes ) *pzRenamed = 0;
22951       else{
22952         sqlite3_finalize(pStmt);
22953         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
22954             && SQLITE_ROW==sqlite3_step(pStmt) ){
22955           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
22956         }else
22957           *pzRenamed = 0;
22958       }
22959     }
22960     sqlite3_finalize(pStmt);
22961     sqlite3_close(*pDb);
22962     *pDb = 0;
22963     return zColsSpec;
22964   }
22965 }
22966 
22967 /*
22968 ** If an input line begins with "." then invoke this routine to
22969 ** process that line.
22970 **
22971 ** Return 1 on error, 2 to exit, and 0 otherwise.
22972 */
22973 static int do_meta_command(char *zLine, ShellState *p){
22974   int h = 1;
22975   int nArg = 0;
22976   int n, c;
22977   int rc = 0;
22978   char *azArg[52];
22979 
22980 #ifndef SQLITE_OMIT_VIRTUALTABLE
22981   if( p->expert.pExpert ){
22982     expertFinish(p, 1, 0);
22983   }
22984 #endif
22985 
22986   /* Parse the input line into tokens.
22987   */
22988   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
22989     while( IsSpace(zLine[h]) ){ h++; }
22990     if( zLine[h]==0 ) break;
22991     if( zLine[h]=='\'' || zLine[h]=='"' ){
22992       int delim = zLine[h++];
22993       azArg[nArg++] = &zLine[h];
22994       while( zLine[h] && zLine[h]!=delim ){
22995         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
22996         h++;
22997       }
22998       if( zLine[h]==delim ){
22999         zLine[h++] = 0;
23000       }
23001       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
23002     }else{
23003       azArg[nArg++] = &zLine[h];
23004       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
23005       if( zLine[h] ) zLine[h++] = 0;
23006       resolve_backslashes(azArg[nArg-1]);
23007     }
23008   }
23009   azArg[nArg] = 0;
23010 
23011   /* Process the input line.
23012   */
23013   if( nArg==0 ) return 0; /* no tokens, no error */
23014   n = strlen30(azArg[0]);
23015   c = azArg[0][0];
23016   clearTempFile(p);
23017 
23018 #ifndef SQLITE_OMIT_AUTHORIZATION
23019   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
23020     if( nArg!=2 ){
23021       raw_printf(stderr, "Usage: .auth ON|OFF\n");
23022       rc = 1;
23023       goto meta_command_exit;
23024     }
23025     open_db(p, 0);
23026     if( booleanValue(azArg[1]) ){
23027       sqlite3_set_authorizer(p->db, shellAuth, p);
23028     }else if( p->bSafeModePersist ){
23029       sqlite3_set_authorizer(p->db, safeModeAuth, p);
23030     }else{
23031       sqlite3_set_authorizer(p->db, 0, 0);
23032     }
23033   }else
23034 #endif
23035 
23036 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
23037   && !defined(SQLITE_SHELL_FIDDLE)
23038   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
23039     open_db(p, 0);
23040     failIfSafeMode(p, "cannot run .archive in safe mode");
23041     rc = arDotCommand(p, 0, azArg, nArg);
23042   }else
23043 #endif
23044 
23045 #ifndef SQLITE_SHELL_FIDDLE
23046   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
23047    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
23048   ){
23049     const char *zDestFile = 0;
23050     const char *zDb = 0;
23051     sqlite3 *pDest;
23052     sqlite3_backup *pBackup;
23053     int j;
23054     int bAsync = 0;
23055     const char *zVfs = 0;
23056     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
23057     for(j=1; j<nArg; j++){
23058       const char *z = azArg[j];
23059       if( z[0]=='-' ){
23060         if( z[1]=='-' ) z++;
23061         if( cli_strcmp(z, "-append")==0 ){
23062           zVfs = "apndvfs";
23063         }else
23064         if( cli_strcmp(z, "-async")==0 ){
23065           bAsync = 1;
23066         }else
23067         {
23068           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
23069           return 1;
23070         }
23071       }else if( zDestFile==0 ){
23072         zDestFile = azArg[j];
23073       }else if( zDb==0 ){
23074         zDb = zDestFile;
23075         zDestFile = azArg[j];
23076       }else{
23077         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
23078         return 1;
23079       }
23080     }
23081     if( zDestFile==0 ){
23082       raw_printf(stderr, "missing FILENAME argument on .backup\n");
23083       return 1;
23084     }
23085     if( zDb==0 ) zDb = "main";
23086     rc = sqlite3_open_v2(zDestFile, &pDest,
23087                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
23088     if( rc!=SQLITE_OK ){
23089       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
23090       close_db(pDest);
23091       return 1;
23092     }
23093     if( bAsync ){
23094       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
23095                    0, 0, 0);
23096     }
23097     open_db(p, 0);
23098     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
23099     if( pBackup==0 ){
23100       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
23101       close_db(pDest);
23102       return 1;
23103     }
23104     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
23105     sqlite3_backup_finish(pBackup);
23106     if( rc==SQLITE_DONE ){
23107       rc = 0;
23108     }else{
23109       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
23110       rc = 1;
23111     }
23112     close_db(pDest);
23113   }else
23114 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23115 
23116   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
23117     if( nArg==2 ){
23118       bail_on_error = booleanValue(azArg[1]);
23119     }else{
23120       raw_printf(stderr, "Usage: .bail on|off\n");
23121       rc = 1;
23122     }
23123   }else
23124 
23125   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
23126     if( nArg==2 ){
23127       if( booleanValue(azArg[1]) ){
23128         setBinaryMode(p->out, 1);
23129       }else{
23130         setTextMode(p->out, 1);
23131       }
23132     }else{
23133       raw_printf(stderr, "Usage: .binary on|off\n");
23134       rc = 1;
23135     }
23136   }else
23137 
23138   /* The undocumented ".breakpoint" command causes a call to the no-op
23139   ** routine named test_breakpoint().
23140   */
23141   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
23142     test_breakpoint();
23143   }else
23144 
23145 #ifndef SQLITE_SHELL_FIDDLE
23146   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
23147     failIfSafeMode(p, "cannot run .cd in safe mode");
23148     if( nArg==2 ){
23149 #if defined(_WIN32) || defined(WIN32)
23150       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
23151       rc = !SetCurrentDirectoryW(z);
23152       sqlite3_free(z);
23153 #else
23154       rc = chdir(azArg[1]);
23155 #endif
23156       if( rc ){
23157         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
23158         rc = 1;
23159       }
23160     }else{
23161       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
23162       rc = 1;
23163     }
23164   }else
23165 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23166 
23167   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
23168     if( nArg==2 ){
23169       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
23170     }else{
23171       raw_printf(stderr, "Usage: .changes on|off\n");
23172       rc = 1;
23173     }
23174   }else
23175 
23176 #ifndef SQLITE_SHELL_FIDDLE
23177   /* Cancel output redirection, if it is currently set (by .testcase)
23178   ** Then read the content of the testcase-out.txt file and compare against
23179   ** azArg[1].  If there are differences, report an error and exit.
23180   */
23181   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
23182     char *zRes = 0;
23183     output_reset(p);
23184     if( nArg!=2 ){
23185       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
23186       rc = 2;
23187     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
23188       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
23189       rc = 2;
23190     }else if( testcase_glob(azArg[1],zRes)==0 ){
23191       utf8_printf(stderr,
23192                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
23193                  p->zTestcase, azArg[1], zRes);
23194       rc = 1;
23195     }else{
23196       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
23197       p->nCheck++;
23198     }
23199     sqlite3_free(zRes);
23200   }else
23201 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23202 
23203 #ifndef SQLITE_SHELL_FIDDLE
23204   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
23205     failIfSafeMode(p, "cannot run .clone in safe mode");
23206     if( nArg==2 ){
23207       tryToClone(p, azArg[1]);
23208     }else{
23209       raw_printf(stderr, "Usage: .clone FILENAME\n");
23210       rc = 1;
23211     }
23212   }else
23213 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
23214 
23215   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
23216     if( nArg==1 ){
23217       /* List available connections */
23218       int i;
23219       for(i=0; i<ArraySize(p->aAuxDb); i++){
23220         const char *zFile = p->aAuxDb[i].zDbFilename;
23221         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
23222           zFile = "(not open)";
23223         }else if( zFile==0 ){
23224           zFile = "(memory)";
23225         }else if( zFile[0]==0 ){
23226           zFile = "(temporary-file)";
23227         }
23228         if( p->pAuxDb == &p->aAuxDb[i] ){
23229           utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
23230         }else if( p->aAuxDb[i].db!=0 ){
23231           utf8_printf(stdout, "       %d: %s\n", i, zFile);
23232         }
23233       }
23234     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
23235       int i = azArg[1][0] - '0';
23236       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
23237         p->pAuxDb->db = p->db;
23238         p->pAuxDb = &p->aAuxDb[i];
23239         globalDb = p->db = p->pAuxDb->db;
23240         p->pAuxDb->db = 0;
23241       }
23242     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
23243            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
23244       int i = azArg[2][0] - '0';
23245       if( i<0 || i>=ArraySize(p->aAuxDb) ){
23246         /* No-op */
23247       }else if( p->pAuxDb == &p->aAuxDb[i] ){
23248         raw_printf(stderr, "cannot close the active database connection\n");
23249         rc = 1;
23250       }else if( p->aAuxDb[i].db ){
23251         session_close_all(p, i);
23252         close_db(p->aAuxDb[i].db);
23253         p->aAuxDb[i].db = 0;
23254       }
23255     }else{
23256       raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
23257       rc = 1;
23258     }
23259   }else
23260 
23261   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
23262     char **azName = 0;
23263     int nName = 0;
23264     sqlite3_stmt *pStmt;
23265     int i;
23266     open_db(p, 0);
23267     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
23268     if( rc ){
23269       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
23270       rc = 1;
23271     }else{
23272       while( sqlite3_step(pStmt)==SQLITE_ROW ){
23273         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
23274         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
23275         if( zSchema==0 || zFile==0 ) continue;
23276         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
23277         shell_check_oom(azName);
23278         azName[nName*2] = strdup(zSchema);
23279         azName[nName*2+1] = strdup(zFile);
23280         nName++;
23281       }
23282     }
23283     sqlite3_finalize(pStmt);
23284     for(i=0; i<nName; i++){
23285       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
23286       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
23287       const char *z = azName[i*2+1];
23288       utf8_printf(p->out, "%s: %s %s%s\n",
23289          azName[i*2],
23290          z && z[0] ? z : "\"\"",
23291          bRdonly ? "r/o" : "r/w",
23292          eTxn==SQLITE_TXN_NONE ? "" :
23293             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
23294       free(azName[i*2]);
23295       free(azName[i*2+1]);
23296     }
23297     sqlite3_free(azName);
23298   }else
23299 
23300   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
23301     static const struct DbConfigChoices {
23302       const char *zName;
23303       int op;
23304     } aDbConfig[] = {
23305         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
23306         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
23307         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
23308         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
23309         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
23310         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
23311         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
23312         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
23313         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
23314         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
23315         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
23316         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
23317         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
23318         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
23319         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
23320         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
23321     };
23322     int ii, v;
23323     open_db(p, 0);
23324     for(ii=0; ii<ArraySize(aDbConfig); ii++){
23325       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
23326       if( nArg>=3 ){
23327         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
23328       }
23329       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
23330       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
23331       if( nArg>1 ) break;
23332     }
23333     if( nArg>1 && ii==ArraySize(aDbConfig) ){
23334       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
23335       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
23336     }
23337   }else
23338 
23339 #if SQLITE_SHELL_HAVE_RECOVER
23340   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
23341     rc = shell_dbinfo_command(p, nArg, azArg);
23342   }else
23343 
23344   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
23345     open_db(p, 0);
23346     rc = recoverDatabaseCmd(p, nArg, azArg);
23347   }else
23348 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23349 
23350   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
23351     char *zLike = 0;
23352     char *zSql;
23353     int i;
23354     int savedShowHeader = p->showHeader;
23355     int savedShellFlags = p->shellFlgs;
23356     ShellClearFlag(p,
23357        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
23358        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
23359     for(i=1; i<nArg; i++){
23360       if( azArg[i][0]=='-' ){
23361         const char *z = azArg[i]+1;
23362         if( z[0]=='-' ) z++;
23363         if( cli_strcmp(z,"preserve-rowids")==0 ){
23364 #ifdef SQLITE_OMIT_VIRTUALTABLE
23365           raw_printf(stderr, "The --preserve-rowids option is not compatible"
23366                              " with SQLITE_OMIT_VIRTUALTABLE\n");
23367           rc = 1;
23368           sqlite3_free(zLike);
23369           goto meta_command_exit;
23370 #else
23371           ShellSetFlag(p, SHFLG_PreserveRowid);
23372 #endif
23373         }else
23374         if( cli_strcmp(z,"newlines")==0 ){
23375           ShellSetFlag(p, SHFLG_Newlines);
23376         }else
23377         if( cli_strcmp(z,"data-only")==0 ){
23378           ShellSetFlag(p, SHFLG_DumpDataOnly);
23379         }else
23380         if( cli_strcmp(z,"nosys")==0 ){
23381           ShellSetFlag(p, SHFLG_DumpNoSys);
23382         }else
23383         {
23384           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
23385           rc = 1;
23386           sqlite3_free(zLike);
23387           goto meta_command_exit;
23388         }
23389       }else{
23390         /* azArg[i] contains a LIKE pattern. This ".dump" request should
23391         ** only dump data for tables for which either the table name matches
23392         ** the LIKE pattern, or the table appears to be a shadow table of
23393         ** a virtual table for which the name matches the LIKE pattern.
23394         */
23395         char *zExpr = sqlite3_mprintf(
23396             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
23397             "  SELECT 1 FROM sqlite_schema WHERE "
23398             "    name LIKE %Q ESCAPE '\\' AND"
23399             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
23400             "    substr(o.name, 1, length(name)+1) == (name||'_')"
23401             ")", azArg[i], azArg[i]
23402         );
23403 
23404         if( zLike ){
23405           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
23406         }else{
23407           zLike = zExpr;
23408         }
23409       }
23410     }
23411 
23412     open_db(p, 0);
23413 
23414     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23415       /* When playing back a "dump", the content might appear in an order
23416       ** which causes immediate foreign key constraints to be violated.
23417       ** So disable foreign-key constraint enforcement to prevent problems. */
23418       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
23419       raw_printf(p->out, "BEGIN TRANSACTION;\n");
23420     }
23421     p->writableSchema = 0;
23422     p->showHeader = 0;
23423     /* Set writable_schema=ON since doing so forces SQLite to initialize
23424     ** as much of the schema as it can even if the sqlite_schema table is
23425     ** corrupt. */
23426     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
23427     p->nErr = 0;
23428     if( zLike==0 ) zLike = sqlite3_mprintf("true");
23429     zSql = sqlite3_mprintf(
23430       "SELECT name, type, sql FROM sqlite_schema AS o "
23431       "WHERE (%s) AND type=='table'"
23432       "  AND sql NOT NULL"
23433       " ORDER BY tbl_name='sqlite_sequence', rowid",
23434       zLike
23435     );
23436     run_schema_dump_query(p,zSql);
23437     sqlite3_free(zSql);
23438     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23439       zSql = sqlite3_mprintf(
23440         "SELECT sql FROM sqlite_schema AS o "
23441         "WHERE (%s) AND sql NOT NULL"
23442         "  AND type IN ('index','trigger','view')",
23443         zLike
23444       );
23445       run_table_dump_query(p, zSql);
23446       sqlite3_free(zSql);
23447     }
23448     sqlite3_free(zLike);
23449     if( p->writableSchema ){
23450       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
23451       p->writableSchema = 0;
23452     }
23453     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
23454     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
23455     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
23456       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
23457     }
23458     p->showHeader = savedShowHeader;
23459     p->shellFlgs = savedShellFlags;
23460   }else
23461 
23462   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
23463     if( nArg==2 ){
23464       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
23465     }else{
23466       raw_printf(stderr, "Usage: .echo on|off\n");
23467       rc = 1;
23468     }
23469   }else
23470 
23471   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
23472     if( nArg==2 ){
23473       p->autoEQPtest = 0;
23474       if( p->autoEQPtrace ){
23475         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
23476         p->autoEQPtrace = 0;
23477       }
23478       if( cli_strcmp(azArg[1],"full")==0 ){
23479         p->autoEQP = AUTOEQP_full;
23480       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
23481         p->autoEQP = AUTOEQP_trigger;
23482 #ifdef SQLITE_DEBUG
23483       }else if( cli_strcmp(azArg[1],"test")==0 ){
23484         p->autoEQP = AUTOEQP_on;
23485         p->autoEQPtest = 1;
23486       }else if( cli_strcmp(azArg[1],"trace")==0 ){
23487         p->autoEQP = AUTOEQP_full;
23488         p->autoEQPtrace = 1;
23489         open_db(p, 0);
23490         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
23491         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
23492 #endif
23493       }else{
23494         p->autoEQP = (u8)booleanValue(azArg[1]);
23495       }
23496     }else{
23497       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
23498       rc = 1;
23499     }
23500   }else
23501 
23502 #ifndef SQLITE_SHELL_FIDDLE
23503   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
23504     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
23505     rc = 2;
23506   }else
23507 #endif
23508 
23509   /* The ".explain" command is automatic now.  It is largely pointless.  It
23510   ** retained purely for backwards compatibility */
23511   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
23512     int val = 1;
23513     if( nArg>=2 ){
23514       if( cli_strcmp(azArg[1],"auto")==0 ){
23515         val = 99;
23516       }else{
23517         val =  booleanValue(azArg[1]);
23518       }
23519     }
23520     if( val==1 && p->mode!=MODE_Explain ){
23521       p->normalMode = p->mode;
23522       p->mode = MODE_Explain;
23523       p->autoExplain = 0;
23524     }else if( val==0 ){
23525       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
23526       p->autoExplain = 0;
23527     }else if( val==99 ){
23528       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
23529       p->autoExplain = 1;
23530     }
23531   }else
23532 
23533 #ifndef SQLITE_OMIT_VIRTUALTABLE
23534   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
23535     if( p->bSafeMode ){
23536       raw_printf(stderr,
23537         "Cannot run experimental commands such as \"%s\" in safe mode\n",
23538         azArg[0]);
23539       rc = 1;
23540     }else{
23541       open_db(p, 0);
23542       expertDotCommand(p, azArg, nArg);
23543     }
23544   }else
23545 #endif
23546 
23547   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
23548     static const struct {
23549        const char *zCtrlName;   /* Name of a test-control option */
23550        int ctrlCode;            /* Integer code for that option */
23551        const char *zUsage;      /* Usage notes */
23552     } aCtrl[] = {
23553       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
23554       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
23555       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
23556       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
23557       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
23558    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
23559       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
23560       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
23561       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
23562       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
23563    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
23564     };
23565     int filectrl = -1;
23566     int iCtrl = -1;
23567     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
23568     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
23569     int n2, i;
23570     const char *zCmd = 0;
23571     const char *zSchema = 0;
23572 
23573     open_db(p, 0);
23574     zCmd = nArg>=2 ? azArg[1] : "help";
23575 
23576     if( zCmd[0]=='-'
23577      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
23578      && nArg>=4
23579     ){
23580       zSchema = azArg[2];
23581       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
23582       nArg -= 2;
23583       zCmd = azArg[1];
23584     }
23585 
23586     /* The argument can optionally begin with "-" or "--" */
23587     if( zCmd[0]=='-' && zCmd[1] ){
23588       zCmd++;
23589       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
23590     }
23591 
23592     /* --help lists all file-controls */
23593     if( cli_strcmp(zCmd,"help")==0 ){
23594       utf8_printf(p->out, "Available file-controls:\n");
23595       for(i=0; i<ArraySize(aCtrl); i++){
23596         utf8_printf(p->out, "  .filectrl %s %s\n",
23597                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
23598       }
23599       rc = 1;
23600       goto meta_command_exit;
23601     }
23602 
23603     /* convert filectrl text option to value. allow any unique prefix
23604     ** of the option name, or a numerical value. */
23605     n2 = strlen30(zCmd);
23606     for(i=0; i<ArraySize(aCtrl); i++){
23607       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
23608         if( filectrl<0 ){
23609           filectrl = aCtrl[i].ctrlCode;
23610           iCtrl = i;
23611         }else{
23612           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
23613                               "Use \".filectrl --help\" for help\n", zCmd);
23614           rc = 1;
23615           goto meta_command_exit;
23616         }
23617       }
23618     }
23619     if( filectrl<0 ){
23620       utf8_printf(stderr,"Error: unknown file-control: %s\n"
23621                          "Use \".filectrl --help\" for help\n", zCmd);
23622     }else{
23623       switch(filectrl){
23624         case SQLITE_FCNTL_SIZE_LIMIT: {
23625           if( nArg!=2 && nArg!=3 ) break;
23626           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
23627           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
23628           isOk = 1;
23629           break;
23630         }
23631         case SQLITE_FCNTL_LOCK_TIMEOUT:
23632         case SQLITE_FCNTL_CHUNK_SIZE: {
23633           int x;
23634           if( nArg!=3 ) break;
23635           x = (int)integerValue(azArg[2]);
23636           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23637           isOk = 2;
23638           break;
23639         }
23640         case SQLITE_FCNTL_PERSIST_WAL:
23641         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
23642           int x;
23643           if( nArg!=2 && nArg!=3 ) break;
23644           x = nArg==3 ? booleanValue(azArg[2]) : -1;
23645           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23646           iRes = x;
23647           isOk = 1;
23648           break;
23649         }
23650         case SQLITE_FCNTL_DATA_VERSION:
23651         case SQLITE_FCNTL_HAS_MOVED: {
23652           int x;
23653           if( nArg!=2 ) break;
23654           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23655           iRes = x;
23656           isOk = 1;
23657           break;
23658         }
23659         case SQLITE_FCNTL_TEMPFILENAME: {
23660           char *z = 0;
23661           if( nArg!=2 ) break;
23662           sqlite3_file_control(p->db, zSchema, filectrl, &z);
23663           if( z ){
23664             utf8_printf(p->out, "%s\n", z);
23665             sqlite3_free(z);
23666           }
23667           isOk = 2;
23668           break;
23669         }
23670         case SQLITE_FCNTL_RESERVE_BYTES: {
23671           int x;
23672           if( nArg>=3 ){
23673             x = atoi(azArg[2]);
23674             sqlite3_file_control(p->db, zSchema, filectrl, &x);
23675           }
23676           x = -1;
23677           sqlite3_file_control(p->db, zSchema, filectrl, &x);
23678           utf8_printf(p->out,"%d\n", x);
23679           isOk = 2;
23680           break;
23681         }
23682       }
23683     }
23684     if( isOk==0 && iCtrl>=0 ){
23685       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
23686       rc = 1;
23687     }else if( isOk==1 ){
23688       char zBuf[100];
23689       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
23690       raw_printf(p->out, "%s\n", zBuf);
23691     }
23692   }else
23693 
23694   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
23695     ShellState data;
23696     int doStats = 0;
23697     memcpy(&data, p, sizeof(data));
23698     data.showHeader = 0;
23699     data.cMode = data.mode = MODE_Semi;
23700     if( nArg==2 && optionMatch(azArg[1], "indent") ){
23701       data.cMode = data.mode = MODE_Pretty;
23702       nArg = 1;
23703     }
23704     if( nArg!=1 ){
23705       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
23706       rc = 1;
23707       goto meta_command_exit;
23708     }
23709     open_db(p, 0);
23710     rc = sqlite3_exec(p->db,
23711        "SELECT sql FROM"
23712        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
23713        "     FROM sqlite_schema UNION ALL"
23714        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
23715        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
23716        "ORDER BY x",
23717        callback, &data, 0
23718     );
23719     if( rc==SQLITE_OK ){
23720       sqlite3_stmt *pStmt;
23721       rc = sqlite3_prepare_v2(p->db,
23722                "SELECT rowid FROM sqlite_schema"
23723                " WHERE name GLOB 'sqlite_stat[134]'",
23724                -1, &pStmt, 0);
23725       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
23726       sqlite3_finalize(pStmt);
23727     }
23728     if( doStats==0 ){
23729       raw_printf(p->out, "/* No STAT tables available */\n");
23730     }else{
23731       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
23732       data.cMode = data.mode = MODE_Insert;
23733       data.zDestTable = "sqlite_stat1";
23734       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
23735       data.zDestTable = "sqlite_stat4";
23736       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
23737       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
23738     }
23739   }else
23740 
23741   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
23742     if( nArg==2 ){
23743       p->showHeader = booleanValue(azArg[1]);
23744       p->shellFlgs |= SHFLG_HeaderSet;
23745     }else{
23746       raw_printf(stderr, "Usage: .headers on|off\n");
23747       rc = 1;
23748     }
23749   }else
23750 
23751   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
23752     if( nArg>=2 ){
23753       n = showHelp(p->out, azArg[1]);
23754       if( n==0 ){
23755         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
23756       }
23757     }else{
23758       showHelp(p->out, 0);
23759     }
23760   }else
23761 
23762 #ifndef SQLITE_SHELL_FIDDLE
23763   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
23764     char *zTable = 0;           /* Insert data into this table */
23765     char *zSchema = 0;          /* within this schema (may default to "main") */
23766     char *zFile = 0;            /* Name of file to extra content from */
23767     sqlite3_stmt *pStmt = NULL; /* A statement */
23768     int nCol;                   /* Number of columns in the table */
23769     int nByte;                  /* Number of bytes in an SQL string */
23770     int i, j;                   /* Loop counters */
23771     int needCommit;             /* True to COMMIT or ROLLBACK at end */
23772     int nSep;                   /* Number of bytes in p->colSeparator[] */
23773     char *zSql;                 /* An SQL statement */
23774     char *zFullTabName;         /* Table name with schema if applicable */
23775     ImportCtx sCtx;             /* Reader context */
23776     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
23777     int eVerbose = 0;           /* Larger for more console output */
23778     int nSkip = 0;              /* Initial lines to skip */
23779     int useOutputMode = 1;      /* Use output mode to determine separators */
23780     char *zCreate = 0;          /* CREATE TABLE statement text */
23781 
23782     failIfSafeMode(p, "cannot run .import in safe mode");
23783     memset(&sCtx, 0, sizeof(sCtx));
23784     if( p->mode==MODE_Ascii ){
23785       xRead = ascii_read_one_field;
23786     }else{
23787       xRead = csv_read_one_field;
23788     }
23789     rc = 1;
23790     for(i=1; i<nArg; i++){
23791       char *z = azArg[i];
23792       if( z[0]=='-' && z[1]=='-' ) z++;
23793       if( z[0]!='-' ){
23794         if( zFile==0 ){
23795           zFile = z;
23796         }else if( zTable==0 ){
23797           zTable = z;
23798         }else{
23799           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
23800           showHelp(p->out, "import");
23801           goto meta_command_exit;
23802         }
23803       }else if( cli_strcmp(z,"-v")==0 ){
23804         eVerbose++;
23805       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
23806         zSchema = azArg[++i];
23807       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
23808         nSkip = integerValue(azArg[++i]);
23809       }else if( cli_strcmp(z,"-ascii")==0 ){
23810         sCtx.cColSep = SEP_Unit[0];
23811         sCtx.cRowSep = SEP_Record[0];
23812         xRead = ascii_read_one_field;
23813         useOutputMode = 0;
23814       }else if( cli_strcmp(z,"-csv")==0 ){
23815         sCtx.cColSep = ',';
23816         sCtx.cRowSep = '\n';
23817         xRead = csv_read_one_field;
23818         useOutputMode = 0;
23819       }else{
23820         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
23821         showHelp(p->out, "import");
23822         goto meta_command_exit;
23823       }
23824     }
23825     if( zTable==0 ){
23826       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
23827                   zFile==0 ? "FILE" : "TABLE");
23828       showHelp(p->out, "import");
23829       goto meta_command_exit;
23830     }
23831     seenInterrupt = 0;
23832     open_db(p, 0);
23833     if( useOutputMode ){
23834       /* If neither the --csv or --ascii options are specified, then set
23835       ** the column and row separator characters from the output mode. */
23836       nSep = strlen30(p->colSeparator);
23837       if( nSep==0 ){
23838         raw_printf(stderr,
23839                    "Error: non-null column separator required for import\n");
23840         goto meta_command_exit;
23841       }
23842       if( nSep>1 ){
23843         raw_printf(stderr,
23844               "Error: multi-character column separators not allowed"
23845               " for import\n");
23846         goto meta_command_exit;
23847       }
23848       nSep = strlen30(p->rowSeparator);
23849       if( nSep==0 ){
23850         raw_printf(stderr,
23851             "Error: non-null row separator required for import\n");
23852         goto meta_command_exit;
23853       }
23854       if( nSep==2 && p->mode==MODE_Csv
23855        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
23856       ){
23857         /* When importing CSV (only), if the row separator is set to the
23858         ** default output row separator, change it to the default input
23859         ** row separator.  This avoids having to maintain different input
23860         ** and output row separators. */
23861         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
23862         nSep = strlen30(p->rowSeparator);
23863       }
23864       if( nSep>1 ){
23865         raw_printf(stderr, "Error: multi-character row separators not allowed"
23866                            " for import\n");
23867         goto meta_command_exit;
23868       }
23869       sCtx.cColSep = p->colSeparator[0];
23870       sCtx.cRowSep = p->rowSeparator[0];
23871     }
23872     sCtx.zFile = zFile;
23873     sCtx.nLine = 1;
23874     if( sCtx.zFile[0]=='|' ){
23875 #ifdef SQLITE_OMIT_POPEN
23876       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
23877       goto meta_command_exit;
23878 #else
23879       sCtx.in = popen(sCtx.zFile+1, "r");
23880       sCtx.zFile = "<pipe>";
23881       sCtx.xCloser = pclose;
23882 #endif
23883     }else{
23884       sCtx.in = fopen(sCtx.zFile, "rb");
23885       sCtx.xCloser = fclose;
23886     }
23887     if( sCtx.in==0 ){
23888       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
23889       goto meta_command_exit;
23890     }
23891     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
23892       char zSep[2];
23893       zSep[1] = 0;
23894       zSep[0] = sCtx.cColSep;
23895       utf8_printf(p->out, "Column separator ");
23896       output_c_string(p->out, zSep);
23897       utf8_printf(p->out, ", row separator ");
23898       zSep[0] = sCtx.cRowSep;
23899       output_c_string(p->out, zSep);
23900       utf8_printf(p->out, "\n");
23901     }
23902     sCtx.z = sqlite3_malloc64(120);
23903     if( sCtx.z==0 ){
23904       import_cleanup(&sCtx);
23905       shell_out_of_memory();
23906     }
23907     /* Below, resources must be freed before exit. */
23908     while( (nSkip--)>0 ){
23909       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
23910     }
23911     if( zSchema!=0 ){
23912       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
23913     }else{
23914       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
23915     }
23916     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
23917     if( zSql==0 || zFullTabName==0 ){
23918       import_cleanup(&sCtx);
23919       shell_out_of_memory();
23920     }
23921     nByte = strlen30(zSql);
23922     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
23923     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
23924     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
23925       sqlite3 *dbCols = 0;
23926       char *zRenames = 0;
23927       char *zColDefs;
23928       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
23929       while( xRead(&sCtx) ){
23930         zAutoColumn(sCtx.z, &dbCols, 0);
23931         if( sCtx.cTerm!=sCtx.cColSep ) break;
23932       }
23933       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
23934       if( zRenames!=0 ){
23935         utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
23936                     "Columns renamed during .import %s due to duplicates:\n"
23937                     "%s\n", sCtx.zFile, zRenames);
23938         sqlite3_free(zRenames);
23939       }
23940       assert(dbCols==0);
23941       if( zColDefs==0 ){
23942         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
23943       import_fail:
23944         sqlite3_free(zCreate);
23945         sqlite3_free(zSql);
23946         sqlite3_free(zFullTabName);
23947         import_cleanup(&sCtx);
23948         rc = 1;
23949         goto meta_command_exit;
23950       }
23951       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
23952       if( eVerbose>=1 ){
23953         utf8_printf(p->out, "%s\n", zCreate);
23954       }
23955       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
23956       if( rc ){
23957         utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
23958         goto import_fail;
23959       }
23960       sqlite3_free(zCreate);
23961       zCreate = 0;
23962       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
23963     }
23964     if( rc ){
23965       if (pStmt) sqlite3_finalize(pStmt);
23966       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
23967       goto import_fail;
23968     }
23969     sqlite3_free(zSql);
23970     nCol = sqlite3_column_count(pStmt);
23971     sqlite3_finalize(pStmt);
23972     pStmt = 0;
23973     if( nCol==0 ) return 0; /* no columns, no error */
23974     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
23975     if( zSql==0 ){
23976       import_cleanup(&sCtx);
23977       shell_out_of_memory();
23978     }
23979     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
23980     j = strlen30(zSql);
23981     for(i=1; i<nCol; i++){
23982       zSql[j++] = ',';
23983       zSql[j++] = '?';
23984     }
23985     zSql[j++] = ')';
23986     zSql[j] = 0;
23987     if( eVerbose>=2 ){
23988       utf8_printf(p->out, "Insert using: %s\n", zSql);
23989     }
23990     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
23991     if( rc ){
23992       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
23993       if (pStmt) sqlite3_finalize(pStmt);
23994       goto import_fail;
23995     }
23996     sqlite3_free(zSql);
23997     sqlite3_free(zFullTabName);
23998     needCommit = sqlite3_get_autocommit(p->db);
23999     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
24000     do{
24001       int startLine = sCtx.nLine;
24002       for(i=0; i<nCol; i++){
24003         char *z = xRead(&sCtx);
24004         /*
24005         ** Did we reach end-of-file before finding any columns?
24006         ** If so, stop instead of NULL filling the remaining columns.
24007         */
24008         if( z==0 && i==0 ) break;
24009         /*
24010         ** Did we reach end-of-file OR end-of-line before finding any
24011         ** columns in ASCII mode?  If so, stop instead of NULL filling
24012         ** the remaining columns.
24013         */
24014         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
24015         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
24016         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
24017           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
24018                           "filling the rest with NULL\n",
24019                           sCtx.zFile, startLine, nCol, i+1);
24020           i += 2;
24021           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
24022         }
24023       }
24024       if( sCtx.cTerm==sCtx.cColSep ){
24025         do{
24026           xRead(&sCtx);
24027           i++;
24028         }while( sCtx.cTerm==sCtx.cColSep );
24029         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
24030                         "extras ignored\n",
24031                         sCtx.zFile, startLine, nCol, i);
24032       }
24033       if( i>=nCol ){
24034         sqlite3_step(pStmt);
24035         rc = sqlite3_reset(pStmt);
24036         if( rc!=SQLITE_OK ){
24037           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
24038                       startLine, sqlite3_errmsg(p->db));
24039           sCtx.nErr++;
24040         }else{
24041           sCtx.nRow++;
24042         }
24043       }
24044     }while( sCtx.cTerm!=EOF );
24045 
24046     import_cleanup(&sCtx);
24047     sqlite3_finalize(pStmt);
24048     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
24049     if( eVerbose>0 ){
24050       utf8_printf(p->out,
24051           "Added %d rows with %d errors using %d lines of input\n",
24052           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
24053     }
24054   }else
24055 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24056 
24057 #ifndef SQLITE_UNTESTABLE
24058   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
24059     char *zSql;
24060     char *zCollist = 0;
24061     sqlite3_stmt *pStmt;
24062     int tnum = 0;
24063     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
24064     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
24065     int i;
24066     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
24067       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
24068                           "       .imposter off\n");
24069       /* Also allowed, but not documented:
24070       **
24071       **    .imposter TABLE IMPOSTER
24072       **
24073       ** where TABLE is a WITHOUT ROWID table.  In that case, the
24074       ** imposter is another WITHOUT ROWID table with the columns in
24075       ** storage order. */
24076       rc = 1;
24077       goto meta_command_exit;
24078     }
24079     open_db(p, 0);
24080     if( nArg==2 ){
24081       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
24082       goto meta_command_exit;
24083     }
24084     zSql = sqlite3_mprintf(
24085       "SELECT rootpage, 0 FROM sqlite_schema"
24086       " WHERE name='%q' AND type='index'"
24087       "UNION ALL "
24088       "SELECT rootpage, 1 FROM sqlite_schema"
24089       " WHERE name='%q' AND type='table'"
24090       "   AND sql LIKE '%%without%%rowid%%'",
24091       azArg[1], azArg[1]
24092     );
24093     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24094     sqlite3_free(zSql);
24095     if( sqlite3_step(pStmt)==SQLITE_ROW ){
24096       tnum = sqlite3_column_int(pStmt, 0);
24097       isWO = sqlite3_column_int(pStmt, 1);
24098     }
24099     sqlite3_finalize(pStmt);
24100     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
24101     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24102     sqlite3_free(zSql);
24103     i = 0;
24104     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24105       char zLabel[20];
24106       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
24107       i++;
24108       if( zCol==0 ){
24109         if( sqlite3_column_int(pStmt,1)==-1 ){
24110           zCol = "_ROWID_";
24111         }else{
24112           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
24113           zCol = zLabel;
24114         }
24115       }
24116       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
24117         lenPK = (int)strlen(zCollist);
24118       }
24119       if( zCollist==0 ){
24120         zCollist = sqlite3_mprintf("\"%w\"", zCol);
24121       }else{
24122         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
24123       }
24124     }
24125     sqlite3_finalize(pStmt);
24126     if( i==0 || tnum==0 ){
24127       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
24128       rc = 1;
24129       sqlite3_free(zCollist);
24130       goto meta_command_exit;
24131     }
24132     if( lenPK==0 ) lenPK = 100000;
24133     zSql = sqlite3_mprintf(
24134           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
24135           azArg[2], zCollist, lenPK, zCollist);
24136     sqlite3_free(zCollist);
24137     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
24138     if( rc==SQLITE_OK ){
24139       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
24140       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
24141       if( rc ){
24142         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
24143       }else{
24144         utf8_printf(stdout, "%s;\n", zSql);
24145         raw_printf(stdout,
24146           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
24147           azArg[1], isWO ? "table" : "index"
24148         );
24149       }
24150     }else{
24151       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
24152       rc = 1;
24153     }
24154     sqlite3_free(zSql);
24155   }else
24156 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
24157 
24158 #ifdef SQLITE_ENABLE_IOTRACE
24159   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
24160     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
24161     if( iotrace && iotrace!=stdout ) fclose(iotrace);
24162     iotrace = 0;
24163     if( nArg<2 ){
24164       sqlite3IoTrace = 0;
24165     }else if( cli_strcmp(azArg[1], "-")==0 ){
24166       sqlite3IoTrace = iotracePrintf;
24167       iotrace = stdout;
24168     }else{
24169       iotrace = fopen(azArg[1], "w");
24170       if( iotrace==0 ){
24171         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
24172         sqlite3IoTrace = 0;
24173         rc = 1;
24174       }else{
24175         sqlite3IoTrace = iotracePrintf;
24176       }
24177     }
24178   }else
24179 #endif
24180 
24181   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
24182     static const struct {
24183        const char *zLimitName;   /* Name of a limit */
24184        int limitCode;            /* Integer code for that limit */
24185     } aLimit[] = {
24186       { "length",                SQLITE_LIMIT_LENGTH                    },
24187       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
24188       { "column",                SQLITE_LIMIT_COLUMN                    },
24189       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
24190       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
24191       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
24192       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
24193       { "attached",              SQLITE_LIMIT_ATTACHED                  },
24194       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
24195       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
24196       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
24197       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
24198     };
24199     int i, n2;
24200     open_db(p, 0);
24201     if( nArg==1 ){
24202       for(i=0; i<ArraySize(aLimit); i++){
24203         printf("%20s %d\n", aLimit[i].zLimitName,
24204                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
24205       }
24206     }else if( nArg>3 ){
24207       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
24208       rc = 1;
24209       goto meta_command_exit;
24210     }else{
24211       int iLimit = -1;
24212       n2 = strlen30(azArg[1]);
24213       for(i=0; i<ArraySize(aLimit); i++){
24214         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
24215           if( iLimit<0 ){
24216             iLimit = i;
24217           }else{
24218             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
24219             rc = 1;
24220             goto meta_command_exit;
24221           }
24222         }
24223       }
24224       if( iLimit<0 ){
24225         utf8_printf(stderr, "unknown limit: \"%s\"\n"
24226                         "enter \".limits\" with no arguments for a list.\n",
24227                          azArg[1]);
24228         rc = 1;
24229         goto meta_command_exit;
24230       }
24231       if( nArg==3 ){
24232         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
24233                       (int)integerValue(azArg[2]));
24234       }
24235       printf("%20s %d\n", aLimit[iLimit].zLimitName,
24236              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
24237     }
24238   }else
24239 
24240   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
24241     open_db(p, 0);
24242     lintDotCommand(p, azArg, nArg);
24243   }else
24244 
24245 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
24246   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
24247     const char *zFile, *zProc;
24248     char *zErrMsg = 0;
24249     failIfSafeMode(p, "cannot run .load in safe mode");
24250     if( nArg<2 ){
24251       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
24252       rc = 1;
24253       goto meta_command_exit;
24254     }
24255     zFile = azArg[1];
24256     zProc = nArg>=3 ? azArg[2] : 0;
24257     open_db(p, 0);
24258     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
24259     if( rc!=SQLITE_OK ){
24260       utf8_printf(stderr, "Error: %s\n", zErrMsg);
24261       sqlite3_free(zErrMsg);
24262       rc = 1;
24263     }
24264   }else
24265 #endif
24266 
24267 #ifndef SQLITE_SHELL_FIDDLE
24268   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
24269     failIfSafeMode(p, "cannot run .log in safe mode");
24270     if( nArg!=2 ){
24271       raw_printf(stderr, "Usage: .log FILENAME\n");
24272       rc = 1;
24273     }else{
24274       const char *zFile = azArg[1];
24275       output_file_close(p->pLog);
24276       p->pLog = output_file_open(zFile, 0);
24277     }
24278   }else
24279 #endif
24280 
24281   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
24282     const char *zMode = 0;
24283     const char *zTabname = 0;
24284     int i, n2;
24285     ColModeOpts cmOpts = ColModeOpts_default;
24286     for(i=1; i<nArg; i++){
24287       const char *z = azArg[i];
24288       if( optionMatch(z,"wrap") && i+1<nArg ){
24289         cmOpts.iWrap = integerValue(azArg[++i]);
24290       }else if( optionMatch(z,"ww") ){
24291         cmOpts.bWordWrap = 1;
24292       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
24293         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
24294       }else if( optionMatch(z,"quote") ){
24295         cmOpts.bQuote = 1;
24296       }else if( optionMatch(z,"noquote") ){
24297         cmOpts.bQuote = 0;
24298       }else if( zMode==0 ){
24299         zMode = z;
24300         /* Apply defaults for qbox pseudo-mode.  If that
24301          * overwrites already-set values, user was informed of this.
24302          */
24303         if( cli_strcmp(z, "qbox")==0 ){
24304           ColModeOpts cmo = ColModeOpts_default_qbox;
24305           zMode = "box";
24306           cmOpts = cmo;
24307         }
24308       }else if( zTabname==0 ){
24309         zTabname = z;
24310       }else if( z[0]=='-' ){
24311         utf8_printf(stderr, "unknown option: %s\n", z);
24312         utf8_printf(stderr, "options:\n"
24313                             "  --noquote\n"
24314                             "  --quote\n"
24315                             "  --wordwrap on/off\n"
24316                             "  --wrap N\n"
24317                             "  --ww\n");
24318         rc = 1;
24319         goto meta_command_exit;
24320       }else{
24321         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
24322         rc = 1;
24323         goto meta_command_exit;
24324       }
24325     }
24326     if( zMode==0 ){
24327       if( p->mode==MODE_Column
24328        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
24329       ){
24330         raw_printf
24331           (p->out,
24332            "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
24333            modeDescr[p->mode], p->cmOpts.iWrap,
24334            p->cmOpts.bWordWrap ? "on" : "off",
24335            p->cmOpts.bQuote ? "" : "no");
24336       }else{
24337         raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
24338       }
24339       zMode = modeDescr[p->mode];
24340     }
24341     n2 = strlen30(zMode);
24342     if( cli_strncmp(zMode,"lines",n2)==0 ){
24343       p->mode = MODE_Line;
24344       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24345     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
24346       p->mode = MODE_Column;
24347       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
24348         p->showHeader = 1;
24349       }
24350       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24351       p->cmOpts = cmOpts;
24352     }else if( cli_strncmp(zMode,"list",n2)==0 ){
24353       p->mode = MODE_List;
24354       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
24355       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24356     }else if( cli_strncmp(zMode,"html",n2)==0 ){
24357       p->mode = MODE_Html;
24358     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
24359       p->mode = MODE_Tcl;
24360       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
24361       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24362     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
24363       p->mode = MODE_Csv;
24364       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24365       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
24366     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
24367       p->mode = MODE_List;
24368       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
24369     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
24370       p->mode = MODE_Insert;
24371       set_table_name(p, zTabname ? zTabname : "table");
24372     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
24373       p->mode = MODE_Quote;
24374       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24375       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24376     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
24377       p->mode = MODE_Ascii;
24378       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
24379       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
24380     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
24381       p->mode = MODE_Markdown;
24382       p->cmOpts = cmOpts;
24383     }else if( cli_strncmp(zMode,"table",n2)==0 ){
24384       p->mode = MODE_Table;
24385       p->cmOpts = cmOpts;
24386     }else if( cli_strncmp(zMode,"box",n2)==0 ){
24387       p->mode = MODE_Box;
24388       p->cmOpts = cmOpts;
24389     }else if( cli_strncmp(zMode,"count",n2)==0 ){
24390       p->mode = MODE_Count;
24391     }else if( cli_strncmp(zMode,"off",n2)==0 ){
24392       p->mode = MODE_Off;
24393     }else if( cli_strncmp(zMode,"json",n2)==0 ){
24394       p->mode = MODE_Json;
24395     }else{
24396       raw_printf(stderr, "Error: mode should be one of: "
24397          "ascii box column csv html insert json line list markdown "
24398          "qbox quote table tabs tcl\n");
24399       rc = 1;
24400     }
24401     p->cMode = p->mode;
24402   }else
24403 
24404 #ifndef SQLITE_SHELL_FIDDLE
24405   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
24406     if( nArg!=2 ){
24407       raw_printf(stderr, "Usage: .nonce NONCE\n");
24408       rc = 1;
24409     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
24410       raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
24411                  p->lineno, azArg[1]);
24412       exit(1);
24413     }else{
24414       p->bSafeMode = 0;
24415       return 0;  /* Return immediately to bypass the safe mode reset
24416                  ** at the end of this procedure */
24417     }
24418   }else
24419 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24420 
24421   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
24422     if( nArg==2 ){
24423       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
24424                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
24425     }else{
24426       raw_printf(stderr, "Usage: .nullvalue STRING\n");
24427       rc = 1;
24428     }
24429   }else
24430 
24431   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
24432     const char *zFN = 0;     /* Pointer to constant filename */
24433     char *zNewFilename = 0;  /* Name of the database file to open */
24434     int iName = 1;           /* Index in azArg[] of the filename */
24435     int newFlag = 0;         /* True to delete file before opening */
24436     int openMode = SHELL_OPEN_UNSPEC;
24437 
24438     /* Check for command-line arguments */
24439     for(iName=1; iName<nArg; iName++){
24440       const char *z = azArg[iName];
24441 #ifndef SQLITE_SHELL_FIDDLE
24442       if( optionMatch(z,"new") ){
24443         newFlag = 1;
24444 #ifdef SQLITE_HAVE_ZLIB
24445       }else if( optionMatch(z, "zip") ){
24446         openMode = SHELL_OPEN_ZIPFILE;
24447 #endif
24448       }else if( optionMatch(z, "append") ){
24449         openMode = SHELL_OPEN_APPENDVFS;
24450       }else if( optionMatch(z, "readonly") ){
24451         openMode = SHELL_OPEN_READONLY;
24452       }else if( optionMatch(z, "nofollow") ){
24453         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
24454 #ifndef SQLITE_OMIT_DESERIALIZE
24455       }else if( optionMatch(z, "deserialize") ){
24456         openMode = SHELL_OPEN_DESERIALIZE;
24457       }else if( optionMatch(z, "hexdb") ){
24458         openMode = SHELL_OPEN_HEXDB;
24459       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
24460         p->szMax = integerValue(azArg[++iName]);
24461 #endif /* SQLITE_OMIT_DESERIALIZE */
24462       }else
24463 #endif /* !SQLITE_SHELL_FIDDLE */
24464       if( z[0]=='-' ){
24465         utf8_printf(stderr, "unknown option: %s\n", z);
24466         rc = 1;
24467         goto meta_command_exit;
24468       }else if( zFN ){
24469         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
24470         rc = 1;
24471         goto meta_command_exit;
24472       }else{
24473         zFN = z;
24474       }
24475     }
24476 
24477     /* Close the existing database */
24478     session_close_all(p, -1);
24479     close_db(p->db);
24480     p->db = 0;
24481     p->pAuxDb->zDbFilename = 0;
24482     sqlite3_free(p->pAuxDb->zFreeOnClose);
24483     p->pAuxDb->zFreeOnClose = 0;
24484     p->openMode = openMode;
24485     p->openFlags = 0;
24486     p->szMax = 0;
24487 
24488     /* If a filename is specified, try to open it first */
24489     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
24490       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
24491 #ifndef SQLITE_SHELL_FIDDLE
24492       if( p->bSafeMode
24493        && p->openMode!=SHELL_OPEN_HEXDB
24494        && zFN
24495        && cli_strcmp(zFN,":memory:")!=0
24496       ){
24497         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
24498       }
24499 #else
24500       /* WASM mode has its own sandboxed pseudo-filesystem. */
24501 #endif
24502       if( zFN ){
24503         zNewFilename = sqlite3_mprintf("%s", zFN);
24504         shell_check_oom(zNewFilename);
24505       }else{
24506         zNewFilename = 0;
24507       }
24508       p->pAuxDb->zDbFilename = zNewFilename;
24509       open_db(p, OPEN_DB_KEEPALIVE);
24510       if( p->db==0 ){
24511         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
24512         sqlite3_free(zNewFilename);
24513       }else{
24514         p->pAuxDb->zFreeOnClose = zNewFilename;
24515       }
24516     }
24517     if( p->db==0 ){
24518       /* As a fall-back open a TEMP database */
24519       p->pAuxDb->zDbFilename = 0;
24520       open_db(p, 0);
24521     }
24522   }else
24523 
24524 #ifndef SQLITE_SHELL_FIDDLE
24525   if( (c=='o'
24526         && (cli_strncmp(azArg[0], "output", n)==0
24527             || cli_strncmp(azArg[0], "once", n)==0))
24528    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
24529   ){
24530     char *zFile = 0;
24531     int bTxtMode = 0;
24532     int i;
24533     int eMode = 0;
24534     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
24535     unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
24536 
24537     zBOM[0] = 0;
24538     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24539     if( c=='e' ){
24540       eMode = 'x';
24541       bOnce = 2;
24542     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
24543       bOnce = 1;
24544     }
24545     for(i=1; i<nArg; i++){
24546       char *z = azArg[i];
24547       if( z[0]=='-' ){
24548         if( z[1]=='-' ) z++;
24549         if( cli_strcmp(z,"-bom")==0 ){
24550           zBOM[0] = 0xef;
24551           zBOM[1] = 0xbb;
24552           zBOM[2] = 0xbf;
24553           zBOM[3] = 0;
24554         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
24555           eMode = 'x';  /* spreadsheet */
24556         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
24557           eMode = 'e';  /* text editor */
24558         }else{
24559           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
24560                       azArg[i]);
24561           showHelp(p->out, azArg[0]);
24562           rc = 1;
24563           goto meta_command_exit;
24564         }
24565       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
24566         zFile = sqlite3_mprintf("%s", z);
24567         if( zFile && zFile[0]=='|' ){
24568           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
24569           break;
24570         }
24571       }else{
24572         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
24573                     azArg[i]);
24574         showHelp(p->out, azArg[0]);
24575         rc = 1;
24576         sqlite3_free(zFile);
24577         goto meta_command_exit;
24578       }
24579     }
24580     if( zFile==0 ){
24581       zFile = sqlite3_mprintf("stdout");
24582     }
24583     if( bOnce ){
24584       p->outCount = 2;
24585     }else{
24586       p->outCount = 0;
24587     }
24588     output_reset(p);
24589 #ifndef SQLITE_NOHAVE_SYSTEM
24590     if( eMode=='e' || eMode=='x' ){
24591       p->doXdgOpen = 1;
24592       outputModePush(p);
24593       if( eMode=='x' ){
24594         /* spreadsheet mode.  Output as CSV. */
24595         newTempFile(p, "csv");
24596         ShellClearFlag(p, SHFLG_Echo);
24597         p->mode = MODE_Csv;
24598         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
24599         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
24600       }else{
24601         /* text editor mode */
24602         newTempFile(p, "txt");
24603         bTxtMode = 1;
24604       }
24605       sqlite3_free(zFile);
24606       zFile = sqlite3_mprintf("%s", p->zTempFile);
24607     }
24608 #endif /* SQLITE_NOHAVE_SYSTEM */
24609     shell_check_oom(zFile);
24610     if( zFile[0]=='|' ){
24611 #ifdef SQLITE_OMIT_POPEN
24612       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24613       rc = 1;
24614       p->out = stdout;
24615 #else
24616       p->out = popen(zFile + 1, "w");
24617       if( p->out==0 ){
24618         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
24619         p->out = stdout;
24620         rc = 1;
24621       }else{
24622         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
24623         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
24624       }
24625 #endif
24626     }else{
24627       p->out = output_file_open(zFile, bTxtMode);
24628       if( p->out==0 ){
24629         if( cli_strcmp(zFile,"off")!=0 ){
24630           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
24631         }
24632         p->out = stdout;
24633         rc = 1;
24634       } else {
24635         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
24636         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
24637       }
24638     }
24639     sqlite3_free(zFile);
24640   }else
24641 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24642 
24643   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
24644     open_db(p,0);
24645     if( nArg<=1 ) goto parameter_syntax_error;
24646 
24647     /* .parameter clear
24648     ** Clear all bind parameters by dropping the TEMP table that holds them.
24649     */
24650     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
24651       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
24652                    0, 0, 0);
24653     }else
24654 
24655     /* .parameter list
24656     ** List all bind parameters.
24657     */
24658     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
24659       sqlite3_stmt *pStmt = 0;
24660       int rx;
24661       int len = 0;
24662       rx = sqlite3_prepare_v2(p->db,
24663              "SELECT max(length(key)) "
24664              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
24665       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24666         len = sqlite3_column_int(pStmt, 0);
24667         if( len>40 ) len = 40;
24668       }
24669       sqlite3_finalize(pStmt);
24670       pStmt = 0;
24671       if( len ){
24672         rx = sqlite3_prepare_v2(p->db,
24673              "SELECT key, quote(value) "
24674              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
24675         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24676           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
24677                       sqlite3_column_text(pStmt,1));
24678         }
24679         sqlite3_finalize(pStmt);
24680       }
24681     }else
24682 
24683     /* .parameter init
24684     ** Make sure the TEMP table used to hold bind parameters exists.
24685     ** Create it if necessary.
24686     */
24687     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
24688       bind_table_init(p);
24689     }else
24690 
24691     /* .parameter set NAME VALUE
24692     ** Set or reset a bind parameter.  NAME should be the full parameter
24693     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
24694     ** VALUE can be in either SQL literal notation, or if not it will be
24695     ** understood to be a text string.
24696     */
24697     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
24698       int rx;
24699       char *zSql;
24700       sqlite3_stmt *pStmt;
24701       const char *zKey = azArg[2];
24702       const char *zValue = azArg[3];
24703       bind_table_init(p);
24704       zSql = sqlite3_mprintf(
24705                   "REPLACE INTO temp.sqlite_parameters(key,value)"
24706                   "VALUES(%Q,%s);", zKey, zValue);
24707       shell_check_oom(zSql);
24708       pStmt = 0;
24709       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24710       sqlite3_free(zSql);
24711       if( rx!=SQLITE_OK ){
24712         sqlite3_finalize(pStmt);
24713         pStmt = 0;
24714         zSql = sqlite3_mprintf(
24715                    "REPLACE INTO temp.sqlite_parameters(key,value)"
24716                    "VALUES(%Q,%Q);", zKey, zValue);
24717         shell_check_oom(zSql);
24718         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24719         sqlite3_free(zSql);
24720         if( rx!=SQLITE_OK ){
24721           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
24722           sqlite3_finalize(pStmt);
24723           pStmt = 0;
24724           rc = 1;
24725         }
24726       }
24727       sqlite3_step(pStmt);
24728       sqlite3_finalize(pStmt);
24729     }else
24730 
24731     /* .parameter unset NAME
24732     ** Remove the NAME binding from the parameter binding table, if it
24733     ** exists.
24734     */
24735     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
24736       char *zSql = sqlite3_mprintf(
24737           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
24738       shell_check_oom(zSql);
24739       sqlite3_exec(p->db, zSql, 0, 0, 0);
24740       sqlite3_free(zSql);
24741     }else
24742     /* If no command name matches, show a syntax error */
24743     parameter_syntax_error:
24744     showHelp(p->out, "parameter");
24745   }else
24746 
24747   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
24748     int i;
24749     for(i=1; i<nArg; i++){
24750       if( i>1 ) raw_printf(p->out, " ");
24751       utf8_printf(p->out, "%s", azArg[i]);
24752     }
24753     raw_printf(p->out, "\n");
24754   }else
24755 
24756 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
24757   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
24758     int i;
24759     int nn = 0;
24760     p->flgProgress = 0;
24761     p->mxProgress = 0;
24762     p->nProgress = 0;
24763     for(i=1; i<nArg; i++){
24764       const char *z = azArg[i];
24765       if( z[0]=='-' ){
24766         z++;
24767         if( z[0]=='-' ) z++;
24768         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
24769           p->flgProgress |= SHELL_PROGRESS_QUIET;
24770           continue;
24771         }
24772         if( cli_strcmp(z,"reset")==0 ){
24773           p->flgProgress |= SHELL_PROGRESS_RESET;
24774           continue;
24775         }
24776         if( cli_strcmp(z,"once")==0 ){
24777           p->flgProgress |= SHELL_PROGRESS_ONCE;
24778           continue;
24779         }
24780         if( cli_strcmp(z,"limit")==0 ){
24781           if( i+1>=nArg ){
24782             utf8_printf(stderr, "Error: missing argument on --limit\n");
24783             rc = 1;
24784             goto meta_command_exit;
24785           }else{
24786             p->mxProgress = (int)integerValue(azArg[++i]);
24787           }
24788           continue;
24789         }
24790         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
24791         rc = 1;
24792         goto meta_command_exit;
24793       }else{
24794         nn = (int)integerValue(z);
24795       }
24796     }
24797     open_db(p, 0);
24798     sqlite3_progress_handler(p->db, nn, progress_handler, p);
24799   }else
24800 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
24801 
24802   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
24803     if( nArg >= 2) {
24804       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
24805     }
24806     if( nArg >= 3) {
24807       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
24808     }
24809   }else
24810 
24811 #ifndef SQLITE_SHELL_FIDDLE
24812   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
24813     rc = 2;
24814   }else
24815 #endif
24816 
24817 #ifndef SQLITE_SHELL_FIDDLE
24818   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
24819     FILE *inSaved = p->in;
24820     int savedLineno = p->lineno;
24821     failIfSafeMode(p, "cannot run .read in safe mode");
24822     if( nArg!=2 ){
24823       raw_printf(stderr, "Usage: .read FILE\n");
24824       rc = 1;
24825       goto meta_command_exit;
24826     }
24827     if( azArg[1][0]=='|' ){
24828 #ifdef SQLITE_OMIT_POPEN
24829       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24830       rc = 1;
24831       p->out = stdout;
24832 #else
24833       p->in = popen(azArg[1]+1, "r");
24834       if( p->in==0 ){
24835         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
24836         rc = 1;
24837       }else{
24838         rc = process_input(p);
24839         pclose(p->in);
24840       }
24841 #endif
24842     }else if( (p->in = openChrSource(azArg[1]))==0 ){
24843       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
24844       rc = 1;
24845     }else{
24846       rc = process_input(p);
24847       fclose(p->in);
24848     }
24849     p->in = inSaved;
24850     p->lineno = savedLineno;
24851   }else
24852 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24853 
24854 #ifndef SQLITE_SHELL_FIDDLE
24855   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
24856     const char *zSrcFile;
24857     const char *zDb;
24858     sqlite3 *pSrc;
24859     sqlite3_backup *pBackup;
24860     int nTimeout = 0;
24861 
24862     failIfSafeMode(p, "cannot run .restore in safe mode");
24863     if( nArg==2 ){
24864       zSrcFile = azArg[1];
24865       zDb = "main";
24866     }else if( nArg==3 ){
24867       zSrcFile = azArg[2];
24868       zDb = azArg[1];
24869     }else{
24870       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
24871       rc = 1;
24872       goto meta_command_exit;
24873     }
24874     rc = sqlite3_open(zSrcFile, &pSrc);
24875     if( rc!=SQLITE_OK ){
24876       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
24877       close_db(pSrc);
24878       return 1;
24879     }
24880     open_db(p, 0);
24881     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
24882     if( pBackup==0 ){
24883       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24884       close_db(pSrc);
24885       return 1;
24886     }
24887     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
24888           || rc==SQLITE_BUSY  ){
24889       if( rc==SQLITE_BUSY ){
24890         if( nTimeout++ >= 3 ) break;
24891         sqlite3_sleep(100);
24892       }
24893     }
24894     sqlite3_backup_finish(pBackup);
24895     if( rc==SQLITE_DONE ){
24896       rc = 0;
24897     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
24898       raw_printf(stderr, "Error: source database is busy\n");
24899       rc = 1;
24900     }else{
24901       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24902       rc = 1;
24903     }
24904     close_db(pSrc);
24905   }else
24906 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24907 
24908   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
24909     if( nArg==2 ){
24910       if( cli_strcmp(azArg[1], "est")==0 ){
24911         p->scanstatsOn = 2;
24912       }else{
24913         p->scanstatsOn = (u8)booleanValue(azArg[1]);
24914       }
24915 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
24916       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
24917 #endif
24918     }else{
24919       raw_printf(stderr, "Usage: .scanstats on|off|est\n");
24920       rc = 1;
24921     }
24922   }else
24923 
24924   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
24925     ShellText sSelect;
24926     ShellState data;
24927     char *zErrMsg = 0;
24928     const char *zDiv = "(";
24929     const char *zName = 0;
24930     int iSchema = 0;
24931     int bDebug = 0;
24932     int bNoSystemTabs = 0;
24933     int ii;
24934 
24935     open_db(p, 0);
24936     memcpy(&data, p, sizeof(data));
24937     data.showHeader = 0;
24938     data.cMode = data.mode = MODE_Semi;
24939     initText(&sSelect);
24940     for(ii=1; ii<nArg; ii++){
24941       if( optionMatch(azArg[ii],"indent") ){
24942         data.cMode = data.mode = MODE_Pretty;
24943       }else if( optionMatch(azArg[ii],"debug") ){
24944         bDebug = 1;
24945       }else if( optionMatch(azArg[ii],"nosys") ){
24946         bNoSystemTabs = 1;
24947       }else if( azArg[ii][0]=='-' ){
24948         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
24949         rc = 1;
24950         goto meta_command_exit;
24951       }else if( zName==0 ){
24952         zName = azArg[ii];
24953       }else{
24954         raw_printf(stderr,
24955                    "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
24956         rc = 1;
24957         goto meta_command_exit;
24958       }
24959     }
24960     if( zName!=0 ){
24961       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
24962                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
24963                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
24964                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
24965       if( isSchema ){
24966         char *new_argv[2], *new_colv[2];
24967         new_argv[0] = sqlite3_mprintf(
24968                       "CREATE TABLE %s (\n"
24969                       "  type text,\n"
24970                       "  name text,\n"
24971                       "  tbl_name text,\n"
24972                       "  rootpage integer,\n"
24973                       "  sql text\n"
24974                       ")", zName);
24975         shell_check_oom(new_argv[0]);
24976         new_argv[1] = 0;
24977         new_colv[0] = "sql";
24978         new_colv[1] = 0;
24979         callback(&data, 1, new_argv, new_colv);
24980         sqlite3_free(new_argv[0]);
24981       }
24982     }
24983     if( zDiv ){
24984       sqlite3_stmt *pStmt = 0;
24985       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
24986                               -1, &pStmt, 0);
24987       if( rc ){
24988         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24989         sqlite3_finalize(pStmt);
24990         rc = 1;
24991         goto meta_command_exit;
24992       }
24993       appendText(&sSelect, "SELECT sql FROM", 0);
24994       iSchema = 0;
24995       while( sqlite3_step(pStmt)==SQLITE_ROW ){
24996         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
24997         char zScNum[30];
24998         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
24999         appendText(&sSelect, zDiv, 0);
25000         zDiv = " UNION ALL ";
25001         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
25002         if( sqlite3_stricmp(zDb, "main")!=0 ){
25003           appendText(&sSelect, zDb, '\'');
25004         }else{
25005           appendText(&sSelect, "NULL", 0);
25006         }
25007         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
25008         appendText(&sSelect, zScNum, 0);
25009         appendText(&sSelect, " AS snum, ", 0);
25010         appendText(&sSelect, zDb, '\'');
25011         appendText(&sSelect, " AS sname FROM ", 0);
25012         appendText(&sSelect, zDb, quoteChar(zDb));
25013         appendText(&sSelect, ".sqlite_schema", 0);
25014       }
25015       sqlite3_finalize(pStmt);
25016 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
25017       if( zName ){
25018         appendText(&sSelect,
25019            " UNION ALL SELECT shell_module_schema(name),"
25020            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
25021         0);
25022       }
25023 #endif
25024       appendText(&sSelect, ") WHERE ", 0);
25025       if( zName ){
25026         char *zQarg = sqlite3_mprintf("%Q", zName);
25027         int bGlob;
25028         shell_check_oom(zQarg);
25029         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
25030                 strchr(zName, '[') != 0;
25031         if( strchr(zName, '.') ){
25032           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
25033         }else{
25034           appendText(&sSelect, "lower(tbl_name)", 0);
25035         }
25036         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
25037         appendText(&sSelect, zQarg, 0);
25038         if( !bGlob ){
25039           appendText(&sSelect, " ESCAPE '\\' ", 0);
25040         }
25041         appendText(&sSelect, " AND ", 0);
25042         sqlite3_free(zQarg);
25043       }
25044       if( bNoSystemTabs ){
25045         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
25046       }
25047       appendText(&sSelect, "sql IS NOT NULL"
25048                            " ORDER BY snum, rowid", 0);
25049       if( bDebug ){
25050         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
25051       }else{
25052         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
25053       }
25054       freeText(&sSelect);
25055     }
25056     if( zErrMsg ){
25057       utf8_printf(stderr,"Error: %s\n", zErrMsg);
25058       sqlite3_free(zErrMsg);
25059       rc = 1;
25060     }else if( rc != SQLITE_OK ){
25061       raw_printf(stderr,"Error: querying schema information\n");
25062       rc = 1;
25063     }else{
25064       rc = 0;
25065     }
25066   }else
25067 
25068   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
25069    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
25070   ){
25071     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
25072     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
25073   }else
25074 
25075 #if defined(SQLITE_ENABLE_SESSION)
25076   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
25077     struct AuxDb *pAuxDb = p->pAuxDb;
25078     OpenSession *pSession = &pAuxDb->aSession[0];
25079     char **azCmd = &azArg[1];
25080     int iSes = 0;
25081     int nCmd = nArg - 1;
25082     int i;
25083     if( nArg<=1 ) goto session_syntax_error;
25084     open_db(p, 0);
25085     if( nArg>=3 ){
25086       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
25087         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
25088       }
25089       if( iSes<pAuxDb->nSession ){
25090         pSession = &pAuxDb->aSession[iSes];
25091         azCmd++;
25092         nCmd--;
25093       }else{
25094         pSession = &pAuxDb->aSession[0];
25095         iSes = 0;
25096       }
25097     }
25098 
25099     /* .session attach TABLE
25100     ** Invoke the sqlite3session_attach() interface to attach a particular
25101     ** table so that it is never filtered.
25102     */
25103     if( cli_strcmp(azCmd[0],"attach")==0 ){
25104       if( nCmd!=2 ) goto session_syntax_error;
25105       if( pSession->p==0 ){
25106         session_not_open:
25107         raw_printf(stderr, "ERROR: No sessions are open\n");
25108       }else{
25109         rc = sqlite3session_attach(pSession->p, azCmd[1]);
25110         if( rc ){
25111           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
25112           rc = 0;
25113         }
25114       }
25115     }else
25116 
25117     /* .session changeset FILE
25118     ** .session patchset FILE
25119     ** Write a changeset or patchset into a file.  The file is overwritten.
25120     */
25121     if( cli_strcmp(azCmd[0],"changeset")==0
25122      || cli_strcmp(azCmd[0],"patchset")==0
25123     ){
25124       FILE *out = 0;
25125       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
25126       if( nCmd!=2 ) goto session_syntax_error;
25127       if( pSession->p==0 ) goto session_not_open;
25128       out = fopen(azCmd[1], "wb");
25129       if( out==0 ){
25130         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
25131                     azCmd[1]);
25132       }else{
25133         int szChng;
25134         void *pChng;
25135         if( azCmd[0][0]=='c' ){
25136           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
25137         }else{
25138           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
25139         }
25140         if( rc ){
25141           printf("Error: error code %d\n", rc);
25142           rc = 0;
25143         }
25144         if( pChng
25145           && fwrite(pChng, szChng, 1, out)!=1 ){
25146           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
25147                   szChng);
25148         }
25149         sqlite3_free(pChng);
25150         fclose(out);
25151       }
25152     }else
25153 
25154     /* .session close
25155     ** Close the identified session
25156     */
25157     if( cli_strcmp(azCmd[0], "close")==0 ){
25158       if( nCmd!=1 ) goto session_syntax_error;
25159       if( pAuxDb->nSession ){
25160         session_close(pSession);
25161         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
25162       }
25163     }else
25164 
25165     /* .session enable ?BOOLEAN?
25166     ** Query or set the enable flag
25167     */
25168     if( cli_strcmp(azCmd[0], "enable")==0 ){
25169       int ii;
25170       if( nCmd>2 ) goto session_syntax_error;
25171       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
25172       if( pAuxDb->nSession ){
25173         ii = sqlite3session_enable(pSession->p, ii);
25174         utf8_printf(p->out, "session %s enable flag = %d\n",
25175                     pSession->zName, ii);
25176       }
25177     }else
25178 
25179     /* .session filter GLOB ....
25180     ** Set a list of GLOB patterns of table names to be excluded.
25181     */
25182     if( cli_strcmp(azCmd[0], "filter")==0 ){
25183       int ii, nByte;
25184       if( nCmd<2 ) goto session_syntax_error;
25185       if( pAuxDb->nSession ){
25186         for(ii=0; ii<pSession->nFilter; ii++){
25187           sqlite3_free(pSession->azFilter[ii]);
25188         }
25189         sqlite3_free(pSession->azFilter);
25190         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
25191         pSession->azFilter = sqlite3_malloc( nByte );
25192         if( pSession->azFilter==0 ){
25193           raw_printf(stderr, "Error: out or memory\n");
25194           exit(1);
25195         }
25196         for(ii=1; ii<nCmd; ii++){
25197           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
25198           shell_check_oom(x);
25199         }
25200         pSession->nFilter = ii-1;
25201       }
25202     }else
25203 
25204     /* .session indirect ?BOOLEAN?
25205     ** Query or set the indirect flag
25206     */
25207     if( cli_strcmp(azCmd[0], "indirect")==0 ){
25208       int ii;
25209       if( nCmd>2 ) goto session_syntax_error;
25210       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
25211       if( pAuxDb->nSession ){
25212         ii = sqlite3session_indirect(pSession->p, ii);
25213         utf8_printf(p->out, "session %s indirect flag = %d\n",
25214                     pSession->zName, ii);
25215       }
25216     }else
25217 
25218     /* .session isempty
25219     ** Determine if the session is empty
25220     */
25221     if( cli_strcmp(azCmd[0], "isempty")==0 ){
25222       int ii;
25223       if( nCmd!=1 ) goto session_syntax_error;
25224       if( pAuxDb->nSession ){
25225         ii = sqlite3session_isempty(pSession->p);
25226         utf8_printf(p->out, "session %s isempty flag = %d\n",
25227                     pSession->zName, ii);
25228       }
25229     }else
25230 
25231     /* .session list
25232     ** List all currently open sessions
25233     */
25234     if( cli_strcmp(azCmd[0],"list")==0 ){
25235       for(i=0; i<pAuxDb->nSession; i++){
25236         utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
25237       }
25238     }else
25239 
25240     /* .session open DB NAME
25241     ** Open a new session called NAME on the attached database DB.
25242     ** DB is normally "main".
25243     */
25244     if( cli_strcmp(azCmd[0],"open")==0 ){
25245       char *zName;
25246       if( nCmd!=3 ) goto session_syntax_error;
25247       zName = azCmd[2];
25248       if( zName[0]==0 ) goto session_syntax_error;
25249       for(i=0; i<pAuxDb->nSession; i++){
25250         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
25251           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
25252           goto meta_command_exit;
25253         }
25254       }
25255       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
25256         raw_printf(stderr,
25257                    "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
25258         goto meta_command_exit;
25259       }
25260       pSession = &pAuxDb->aSession[pAuxDb->nSession];
25261       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
25262       if( rc ){
25263         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
25264         rc = 0;
25265         goto meta_command_exit;
25266       }
25267       pSession->nFilter = 0;
25268       sqlite3session_table_filter(pSession->p, session_filter, pSession);
25269       pAuxDb->nSession++;
25270       pSession->zName = sqlite3_mprintf("%s", zName);
25271       shell_check_oom(pSession->zName);
25272     }else
25273     /* If no command name matches, show a syntax error */
25274     session_syntax_error:
25275     showHelp(p->out, "session");
25276   }else
25277 #endif
25278 
25279 #ifdef SQLITE_DEBUG
25280   /* Undocumented commands for internal testing.  Subject to change
25281   ** without notice. */
25282   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
25283     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
25284       int i, v;
25285       for(i=1; i<nArg; i++){
25286         v = booleanValue(azArg[i]);
25287         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
25288       }
25289     }
25290     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
25291       int i; sqlite3_int64 v;
25292       for(i=1; i<nArg; i++){
25293         char zBuf[200];
25294         v = integerValue(azArg[i]);
25295         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
25296         utf8_printf(p->out, "%s", zBuf);
25297       }
25298     }
25299   }else
25300 #endif
25301 
25302   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
25303     int bIsInit = 0;         /* True to initialize the SELFTEST table */
25304     int bVerbose = 0;        /* Verbose output */
25305     int bSelftestExists;     /* True if SELFTEST already exists */
25306     int i, k;                /* Loop counters */
25307     int nTest = 0;           /* Number of tests runs */
25308     int nErr = 0;            /* Number of errors seen */
25309     ShellText str;           /* Answer for a query */
25310     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
25311 
25312     open_db(p,0);
25313     for(i=1; i<nArg; i++){
25314       const char *z = azArg[i];
25315       if( z[0]=='-' && z[1]=='-' ) z++;
25316       if( cli_strcmp(z,"-init")==0 ){
25317         bIsInit = 1;
25318       }else
25319       if( cli_strcmp(z,"-v")==0 ){
25320         bVerbose++;
25321       }else
25322       {
25323         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
25324                     azArg[i], azArg[0]);
25325         raw_printf(stderr, "Should be one of: --init -v\n");
25326         rc = 1;
25327         goto meta_command_exit;
25328       }
25329     }
25330     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
25331            != SQLITE_OK ){
25332       bSelftestExists = 0;
25333     }else{
25334       bSelftestExists = 1;
25335     }
25336     if( bIsInit ){
25337       createSelftestTable(p);
25338       bSelftestExists = 1;
25339     }
25340     initText(&str);
25341     appendText(&str, "x", 0);
25342     for(k=bSelftestExists; k>=0; k--){
25343       if( k==1 ){
25344         rc = sqlite3_prepare_v2(p->db,
25345             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
25346             -1, &pStmt, 0);
25347       }else{
25348         rc = sqlite3_prepare_v2(p->db,
25349           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
25350           "      (1,'run','PRAGMA integrity_check','ok')",
25351           -1, &pStmt, 0);
25352       }
25353       if( rc ){
25354         raw_printf(stderr, "Error querying the selftest table\n");
25355         rc = 1;
25356         sqlite3_finalize(pStmt);
25357         goto meta_command_exit;
25358       }
25359       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
25360         int tno = sqlite3_column_int(pStmt, 0);
25361         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
25362         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
25363         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
25364 
25365         if( zOp==0 ) continue;
25366         if( zSql==0 ) continue;
25367         if( zAns==0 ) continue;
25368         k = 0;
25369         if( bVerbose>0 ){
25370           printf("%d: %s %s\n", tno, zOp, zSql);
25371         }
25372         if( cli_strcmp(zOp,"memo")==0 ){
25373           utf8_printf(p->out, "%s\n", zSql);
25374         }else
25375         if( cli_strcmp(zOp,"run")==0 ){
25376           char *zErrMsg = 0;
25377           str.n = 0;
25378           str.z[0] = 0;
25379           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
25380           nTest++;
25381           if( bVerbose ){
25382             utf8_printf(p->out, "Result: %s\n", str.z);
25383           }
25384           if( rc || zErrMsg ){
25385             nErr++;
25386             rc = 1;
25387             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
25388             sqlite3_free(zErrMsg);
25389           }else if( cli_strcmp(zAns,str.z)!=0 ){
25390             nErr++;
25391             rc = 1;
25392             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
25393             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
25394           }
25395         }else
25396         {
25397           utf8_printf(stderr,
25398             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
25399           rc = 1;
25400           break;
25401         }
25402       } /* End loop over rows of content from SELFTEST */
25403       sqlite3_finalize(pStmt);
25404     } /* End loop over k */
25405     freeText(&str);
25406     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
25407   }else
25408 
25409   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
25410     if( nArg<2 || nArg>3 ){
25411       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
25412       rc = 1;
25413     }
25414     if( nArg>=2 ){
25415       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
25416                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
25417     }
25418     if( nArg>=3 ){
25419       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
25420                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
25421     }
25422   }else
25423 
25424   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
25425     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
25426     int i;                   /* Loop counter */
25427     int bSchema = 0;         /* Also hash the schema */
25428     int bSeparate = 0;       /* Hash each table separately */
25429     int iSize = 224;         /* Hash algorithm to use */
25430     int bDebug = 0;          /* Only show the query that would have run */
25431     sqlite3_stmt *pStmt;     /* For querying tables names */
25432     char *zSql;              /* SQL to be run */
25433     char *zSep;              /* Separator */
25434     ShellText sSql;          /* Complete SQL for the query to run the hash */
25435     ShellText sQuery;        /* Set of queries used to read all content */
25436     open_db(p, 0);
25437     for(i=1; i<nArg; i++){
25438       const char *z = azArg[i];
25439       if( z[0]=='-' ){
25440         z++;
25441         if( z[0]=='-' ) z++;
25442         if( cli_strcmp(z,"schema")==0 ){
25443           bSchema = 1;
25444         }else
25445         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
25446          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
25447         ){
25448           iSize = atoi(&z[5]);
25449         }else
25450         if( cli_strcmp(z,"debug")==0 ){
25451           bDebug = 1;
25452         }else
25453         {
25454           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
25455                       azArg[i], azArg[0]);
25456           showHelp(p->out, azArg[0]);
25457           rc = 1;
25458           goto meta_command_exit;
25459         }
25460       }else if( zLike ){
25461         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
25462         rc = 1;
25463         goto meta_command_exit;
25464       }else{
25465         zLike = z;
25466         bSeparate = 1;
25467         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
25468       }
25469     }
25470     if( bSchema ){
25471       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
25472              " WHERE type='table' AND coalesce(rootpage,0)>1"
25473              " UNION ALL SELECT 'sqlite_schema'"
25474              " ORDER BY 1 collate nocase";
25475     }else{
25476       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
25477              " WHERE type='table' AND coalesce(rootpage,0)>1"
25478              " AND name NOT LIKE 'sqlite_%'"
25479              " ORDER BY 1 collate nocase";
25480     }
25481     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25482     initText(&sQuery);
25483     initText(&sSql);
25484     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
25485     zSep = "VALUES(";
25486     while( SQLITE_ROW==sqlite3_step(pStmt) ){
25487       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
25488       if( zTab==0 ) continue;
25489       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
25490       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
25491         appendText(&sQuery,"SELECT * FROM ", 0);
25492         appendText(&sQuery,zTab,'"');
25493         appendText(&sQuery," NOT INDEXED;", 0);
25494       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
25495         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
25496                            " ORDER BY name;", 0);
25497       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
25498         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
25499                            " ORDER BY name;", 0);
25500       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
25501         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
25502                            " ORDER BY tbl,idx;", 0);
25503       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
25504         appendText(&sQuery, "SELECT * FROM ", 0);
25505         appendText(&sQuery, zTab, 0);
25506         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
25507       }
25508       appendText(&sSql, zSep, 0);
25509       appendText(&sSql, sQuery.z, '\'');
25510       sQuery.n = 0;
25511       appendText(&sSql, ",", 0);
25512       appendText(&sSql, zTab, '\'');
25513       zSep = "),(";
25514     }
25515     sqlite3_finalize(pStmt);
25516     if( bSeparate ){
25517       zSql = sqlite3_mprintf(
25518           "%s))"
25519           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
25520           "   FROM [sha3sum$query]",
25521           sSql.z, iSize);
25522     }else{
25523       zSql = sqlite3_mprintf(
25524           "%s))"
25525           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
25526           "   FROM [sha3sum$query]",
25527           sSql.z, iSize);
25528     }
25529     shell_check_oom(zSql);
25530     freeText(&sQuery);
25531     freeText(&sSql);
25532     if( bDebug ){
25533       utf8_printf(p->out, "%s\n", zSql);
25534     }else{
25535       shell_exec(p, zSql, 0);
25536     }
25537 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
25538     {
25539       int lrc;
25540       char *zRevText = /* Query for reversible to-blob-to-text check */
25541         "SELECT lower(name) as tname FROM sqlite_schema\n"
25542         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
25543         "AND name NOT LIKE 'sqlite_%%'%s\n"
25544         "ORDER BY 1 collate nocase";
25545       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
25546       zRevText = sqlite3_mprintf(
25547           /* lower-case query is first run, producing upper-case query. */
25548           "with tabcols as materialized(\n"
25549           "select tname, cname\n"
25550           "from ("
25551           " select ss.tname as tname, ti.name as cname\n"
25552           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
25553           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
25554           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
25555           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
25556           "FROM '||tname||' WHERE '\n"
25557           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
25558           "|| ' AND typeof('||cname||')=''text'' ',\n"
25559           "' OR ') as query, tname from tabcols group by tname)"
25560           , zRevText);
25561       shell_check_oom(zRevText);
25562       if( bDebug ) utf8_printf(p->out, "%s\n", zRevText);
25563       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
25564       assert(lrc==SQLITE_OK);
25565       if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
25566       lrc = SQLITE_ROW==sqlite3_step(pStmt);
25567       if( lrc ){
25568         const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
25569         sqlite3_stmt *pCheckStmt;
25570         lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
25571         if( bDebug ) utf8_printf(p->out, "%s\n", zGenQuery);
25572         if( SQLITE_OK==lrc ){
25573           if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
25574             double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
25575             if( countIrreversible>0 ){
25576               int sz = (int)(countIrreversible + 0.5);
25577               utf8_printf(stderr,
25578                  "Digest includes %d invalidly encoded text field%s.\n",
25579                  sz, (sz>1)? "s": "");
25580             }
25581           }
25582           sqlite3_finalize(pCheckStmt);
25583         }
25584         sqlite3_finalize(pStmt);
25585       }
25586       sqlite3_free(zRevText);
25587     }
25588 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
25589     sqlite3_free(zSql);
25590   }else
25591 
25592 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
25593   if( c=='s'
25594    && (cli_strncmp(azArg[0], "shell", n)==0
25595        || cli_strncmp(azArg[0],"system",n)==0)
25596   ){
25597     char *zCmd;
25598     int i, x;
25599     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
25600     if( nArg<2 ){
25601       raw_printf(stderr, "Usage: .system COMMAND\n");
25602       rc = 1;
25603       goto meta_command_exit;
25604     }
25605     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
25606     for(i=2; i<nArg && zCmd!=0; i++){
25607       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
25608                              zCmd, azArg[i]);
25609     }
25610     x = zCmd!=0 ? system(zCmd) : 1;
25611     sqlite3_free(zCmd);
25612     if( x ) raw_printf(stderr, "System command returns %d\n", x);
25613   }else
25614 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
25615 
25616   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
25617     static const char *azBool[] = { "off", "on", "trigger", "full"};
25618     const char *zOut;
25619     int i;
25620     if( nArg!=1 ){
25621       raw_printf(stderr, "Usage: .show\n");
25622       rc = 1;
25623       goto meta_command_exit;
25624     }
25625     utf8_printf(p->out, "%12.12s: %s\n","echo",
25626                 azBool[ShellHasFlag(p, SHFLG_Echo)]);
25627     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
25628     utf8_printf(p->out, "%12.12s: %s\n","explain",
25629          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
25630     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
25631     if( p->mode==MODE_Column
25632      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
25633     ){
25634       utf8_printf
25635         (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
25636          modeDescr[p->mode], p->cmOpts.iWrap,
25637          p->cmOpts.bWordWrap ? "on" : "off",
25638          p->cmOpts.bQuote ? "" : "no");
25639     }else{
25640       utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
25641     }
25642     utf8_printf(p->out, "%12.12s: ", "nullvalue");
25643       output_c_string(p->out, p->nullValue);
25644       raw_printf(p->out, "\n");
25645     utf8_printf(p->out,"%12.12s: %s\n","output",
25646             strlen30(p->outfile) ? p->outfile : "stdout");
25647     utf8_printf(p->out,"%12.12s: ", "colseparator");
25648       output_c_string(p->out, p->colSeparator);
25649       raw_printf(p->out, "\n");
25650     utf8_printf(p->out,"%12.12s: ", "rowseparator");
25651       output_c_string(p->out, p->rowSeparator);
25652       raw_printf(p->out, "\n");
25653     switch( p->statsOn ){
25654       case 0:  zOut = "off";     break;
25655       default: zOut = "on";      break;
25656       case 2:  zOut = "stmt";    break;
25657       case 3:  zOut = "vmstep";  break;
25658     }
25659     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
25660     utf8_printf(p->out, "%12.12s: ", "width");
25661     for (i=0;i<p->nWidth;i++) {
25662       raw_printf(p->out, "%d ", p->colWidth[i]);
25663     }
25664     raw_printf(p->out, "\n");
25665     utf8_printf(p->out, "%12.12s: %s\n", "filename",
25666                 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
25667   }else
25668 
25669   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
25670     if( nArg==2 ){
25671       if( cli_strcmp(azArg[1],"stmt")==0 ){
25672         p->statsOn = 2;
25673       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
25674         p->statsOn = 3;
25675       }else{
25676         p->statsOn = (u8)booleanValue(azArg[1]);
25677       }
25678     }else if( nArg==1 ){
25679       display_stats(p->db, p, 0);
25680     }else{
25681       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
25682       rc = 1;
25683     }
25684   }else
25685 
25686   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
25687    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
25688                  || cli_strncmp(azArg[0], "indexes", n)==0) )
25689   ){
25690     sqlite3_stmt *pStmt;
25691     char **azResult;
25692     int nRow, nAlloc;
25693     int ii;
25694     ShellText s;
25695     initText(&s);
25696     open_db(p, 0);
25697     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
25698     if( rc ){
25699       sqlite3_finalize(pStmt);
25700       return shellDatabaseError(p->db);
25701     }
25702 
25703     if( nArg>2 && c=='i' ){
25704       /* It is an historical accident that the .indexes command shows an error
25705       ** when called with the wrong number of arguments whereas the .tables
25706       ** command does not. */
25707       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
25708       rc = 1;
25709       sqlite3_finalize(pStmt);
25710       goto meta_command_exit;
25711     }
25712     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
25713       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
25714       if( zDbName==0 ) continue;
25715       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
25716       if( sqlite3_stricmp(zDbName, "main")==0 ){
25717         appendText(&s, "SELECT name FROM ", 0);
25718       }else{
25719         appendText(&s, "SELECT ", 0);
25720         appendText(&s, zDbName, '\'');
25721         appendText(&s, "||'.'||name FROM ", 0);
25722       }
25723       appendText(&s, zDbName, '"');
25724       appendText(&s, ".sqlite_schema ", 0);
25725       if( c=='t' ){
25726         appendText(&s," WHERE type IN ('table','view')"
25727                       "   AND name NOT LIKE 'sqlite_%'"
25728                       "   AND name LIKE ?1", 0);
25729       }else{
25730         appendText(&s," WHERE type='index'"
25731                       "   AND tbl_name LIKE ?1", 0);
25732       }
25733     }
25734     rc = sqlite3_finalize(pStmt);
25735     if( rc==SQLITE_OK ){
25736       appendText(&s, " ORDER BY 1", 0);
25737       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
25738     }
25739     freeText(&s);
25740     if( rc ) return shellDatabaseError(p->db);
25741 
25742     /* Run the SQL statement prepared by the above block. Store the results
25743     ** as an array of nul-terminated strings in azResult[].  */
25744     nRow = nAlloc = 0;
25745     azResult = 0;
25746     if( nArg>1 ){
25747       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
25748     }else{
25749       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
25750     }
25751     while( sqlite3_step(pStmt)==SQLITE_ROW ){
25752       if( nRow>=nAlloc ){
25753         char **azNew;
25754         int n2 = nAlloc*2 + 10;
25755         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
25756         shell_check_oom(azNew);
25757         nAlloc = n2;
25758         azResult = azNew;
25759       }
25760       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
25761       shell_check_oom(azResult[nRow]);
25762       nRow++;
25763     }
25764     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
25765       rc = shellDatabaseError(p->db);
25766     }
25767 
25768     /* Pretty-print the contents of array azResult[] to the output */
25769     if( rc==0 && nRow>0 ){
25770       int len, maxlen = 0;
25771       int i, j;
25772       int nPrintCol, nPrintRow;
25773       for(i=0; i<nRow; i++){
25774         len = strlen30(azResult[i]);
25775         if( len>maxlen ) maxlen = len;
25776       }
25777       nPrintCol = 80/(maxlen+2);
25778       if( nPrintCol<1 ) nPrintCol = 1;
25779       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
25780       for(i=0; i<nPrintRow; i++){
25781         for(j=i; j<nRow; j+=nPrintRow){
25782           char *zSp = j<nPrintRow ? "" : "  ";
25783           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
25784                       azResult[j] ? azResult[j]:"");
25785         }
25786         raw_printf(p->out, "\n");
25787       }
25788     }
25789 
25790     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
25791     sqlite3_free(azResult);
25792   }else
25793 
25794 #ifndef SQLITE_SHELL_FIDDLE
25795   /* Begin redirecting output to the file "testcase-out.txt" */
25796   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
25797     output_reset(p);
25798     p->out = output_file_open("testcase-out.txt", 0);
25799     if( p->out==0 ){
25800       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
25801     }
25802     if( nArg>=2 ){
25803       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
25804     }else{
25805       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
25806     }
25807   }else
25808 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25809 
25810 #ifndef SQLITE_UNTESTABLE
25811   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
25812     static const struct {
25813        const char *zCtrlName;   /* Name of a test-control option */
25814        int ctrlCode;            /* Integer code for that option */
25815        int unSafe;              /* Not valid for --safe mode */
25816        const char *zUsage;      /* Usage notes */
25817     } aCtrl[] = {
25818     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
25819     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
25820   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
25821   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
25822     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
25823     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
25824   /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
25825     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
25826     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
25827     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
25828     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
25829     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
25830 #ifdef YYCOVERAGE
25831     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
25832 #endif
25833     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
25834     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
25835     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
25836     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
25837     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
25838     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
25839     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
25840     };
25841     int testctrl = -1;
25842     int iCtrl = -1;
25843     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
25844     int isOk = 0;
25845     int i, n2;
25846     const char *zCmd = 0;
25847 
25848     open_db(p, 0);
25849     zCmd = nArg>=2 ? azArg[1] : "help";
25850 
25851     /* The argument can optionally begin with "-" or "--" */
25852     if( zCmd[0]=='-' && zCmd[1] ){
25853       zCmd++;
25854       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
25855     }
25856 
25857     /* --help lists all test-controls */
25858     if( cli_strcmp(zCmd,"help")==0 ){
25859       utf8_printf(p->out, "Available test-controls:\n");
25860       for(i=0; i<ArraySize(aCtrl); i++){
25861         utf8_printf(p->out, "  .testctrl %s %s\n",
25862                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
25863       }
25864       rc = 1;
25865       goto meta_command_exit;
25866     }
25867 
25868     /* convert testctrl text option to value. allow any unique prefix
25869     ** of the option name, or a numerical value. */
25870     n2 = strlen30(zCmd);
25871     for(i=0; i<ArraySize(aCtrl); i++){
25872       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
25873         if( testctrl<0 ){
25874           testctrl = aCtrl[i].ctrlCode;
25875           iCtrl = i;
25876         }else{
25877           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
25878                               "Use \".testctrl --help\" for help\n", zCmd);
25879           rc = 1;
25880           goto meta_command_exit;
25881         }
25882       }
25883     }
25884     if( testctrl<0 ){
25885       utf8_printf(stderr,"Error: unknown test-control: %s\n"
25886                          "Use \".testctrl --help\" for help\n", zCmd);
25887     }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
25888       utf8_printf(stderr,
25889          "line %d: \".testctrl %s\" may not be used in safe mode\n",
25890          p->lineno, aCtrl[iCtrl].zCtrlName);
25891       exit(1);
25892     }else{
25893       switch(testctrl){
25894 
25895         /* sqlite3_test_control(int, db, int) */
25896         case SQLITE_TESTCTRL_OPTIMIZATIONS:
25897           if( nArg==3 ){
25898             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
25899             rc2 = sqlite3_test_control(testctrl, p->db, opt);
25900             isOk = 3;
25901           }
25902           break;
25903 
25904         /* sqlite3_test_control(int) */
25905         case SQLITE_TESTCTRL_PRNG_SAVE:
25906         case SQLITE_TESTCTRL_PRNG_RESTORE:
25907         case SQLITE_TESTCTRL_BYTEORDER:
25908           if( nArg==2 ){
25909             rc2 = sqlite3_test_control(testctrl);
25910             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
25911           }
25912           break;
25913 
25914         /* sqlite3_test_control(int, uint) */
25915         case SQLITE_TESTCTRL_PENDING_BYTE:
25916           if( nArg==3 ){
25917             unsigned int opt = (unsigned int)integerValue(azArg[2]);
25918             rc2 = sqlite3_test_control(testctrl, opt);
25919             isOk = 3;
25920           }
25921           break;
25922 
25923         /* sqlite3_test_control(int, int, sqlite3*) */
25924         case SQLITE_TESTCTRL_PRNG_SEED:
25925           if( nArg==3 || nArg==4 ){
25926             int ii = (int)integerValue(azArg[2]);
25927             sqlite3 *db;
25928             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
25929               sqlite3_randomness(sizeof(ii),&ii);
25930               printf("-- random seed: %d\n", ii);
25931             }
25932             if( nArg==3 ){
25933               db = 0;
25934             }else{
25935               db = p->db;
25936               /* Make sure the schema has been loaded */
25937               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
25938             }
25939             rc2 = sqlite3_test_control(testctrl, ii, db);
25940             isOk = 3;
25941           }
25942           break;
25943 
25944         /* sqlite3_test_control(int, int) */
25945         case SQLITE_TESTCTRL_ASSERT:
25946         case SQLITE_TESTCTRL_ALWAYS:
25947           if( nArg==3 ){
25948             int opt = booleanValue(azArg[2]);
25949             rc2 = sqlite3_test_control(testctrl, opt);
25950             isOk = 1;
25951           }
25952           break;
25953 
25954         /* sqlite3_test_control(int, int) */
25955         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
25956         case SQLITE_TESTCTRL_NEVER_CORRUPT:
25957           if( nArg==3 ){
25958             int opt = booleanValue(azArg[2]);
25959             rc2 = sqlite3_test_control(testctrl, opt);
25960             isOk = 3;
25961           }
25962           break;
25963 
25964         /* sqlite3_test_control(sqlite3*) */
25965         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
25966           rc2 = sqlite3_test_control(testctrl, p->db);
25967           isOk = 3;
25968           break;
25969 
25970         case SQLITE_TESTCTRL_IMPOSTER:
25971           if( nArg==5 ){
25972             rc2 = sqlite3_test_control(testctrl, p->db,
25973                           azArg[2],
25974                           integerValue(azArg[3]),
25975                           integerValue(azArg[4]));
25976             isOk = 3;
25977           }
25978           break;
25979 
25980         case SQLITE_TESTCTRL_SEEK_COUNT: {
25981           u64 x = 0;
25982           rc2 = sqlite3_test_control(testctrl, p->db, &x);
25983           utf8_printf(p->out, "%llu\n", x);
25984           isOk = 3;
25985           break;
25986         }
25987 
25988 #ifdef YYCOVERAGE
25989         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
25990           if( nArg==2 ){
25991             sqlite3_test_control(testctrl, p->out);
25992             isOk = 3;
25993           }
25994           break;
25995         }
25996 #endif
25997 #ifdef SQLITE_DEBUG
25998         case SQLITE_TESTCTRL_TUNE: {
25999           if( nArg==4 ){
26000             int id = (int)integerValue(azArg[2]);
26001             int val = (int)integerValue(azArg[3]);
26002             sqlite3_test_control(testctrl, id, &val);
26003             isOk = 3;
26004           }else if( nArg==3 ){
26005             int id = (int)integerValue(azArg[2]);
26006             sqlite3_test_control(testctrl, -id, &rc2);
26007             isOk = 1;
26008           }else if( nArg==2 ){
26009             int id = 1;
26010             while(1){
26011               int val = 0;
26012               rc2 = sqlite3_test_control(testctrl, -id, &val);
26013               if( rc2!=SQLITE_OK ) break;
26014               if( id>1 ) utf8_printf(p->out, "  ");
26015               utf8_printf(p->out, "%d: %d", id, val);
26016               id++;
26017             }
26018             if( id>1 ) utf8_printf(p->out, "\n");
26019             isOk = 3;
26020           }
26021           break;
26022         }
26023 #endif
26024         case SQLITE_TESTCTRL_SORTER_MMAP:
26025           if( nArg==3 ){
26026             int opt = (unsigned int)integerValue(azArg[2]);
26027             rc2 = sqlite3_test_control(testctrl, p->db, opt);
26028             isOk = 3;
26029           }
26030           break;
26031       }
26032     }
26033     if( isOk==0 && iCtrl>=0 ){
26034       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
26035       rc = 1;
26036     }else if( isOk==1 ){
26037       raw_printf(p->out, "%d\n", rc2);
26038     }else if( isOk==2 ){
26039       raw_printf(p->out, "0x%08x\n", rc2);
26040     }
26041   }else
26042 #endif /* !defined(SQLITE_UNTESTABLE) */
26043 
26044   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
26045     open_db(p, 0);
26046     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
26047   }else
26048 
26049   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
26050     if( nArg==2 ){
26051       enableTimer = booleanValue(azArg[1]);
26052       if( enableTimer && !HAS_TIMER ){
26053         raw_printf(stderr, "Error: timer not available on this system.\n");
26054         enableTimer = 0;
26055       }
26056     }else{
26057       raw_printf(stderr, "Usage: .timer on|off\n");
26058       rc = 1;
26059     }
26060   }else
26061 
26062 #ifndef SQLITE_OMIT_TRACE
26063   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
26064     int mType = 0;
26065     int jj;
26066     open_db(p, 0);
26067     for(jj=1; jj<nArg; jj++){
26068       const char *z = azArg[jj];
26069       if( z[0]=='-' ){
26070         if( optionMatch(z, "expanded") ){
26071           p->eTraceType = SHELL_TRACE_EXPANDED;
26072         }
26073 #ifdef SQLITE_ENABLE_NORMALIZE
26074         else if( optionMatch(z, "normalized") ){
26075           p->eTraceType = SHELL_TRACE_NORMALIZED;
26076         }
26077 #endif
26078         else if( optionMatch(z, "plain") ){
26079           p->eTraceType = SHELL_TRACE_PLAIN;
26080         }
26081         else if( optionMatch(z, "profile") ){
26082           mType |= SQLITE_TRACE_PROFILE;
26083         }
26084         else if( optionMatch(z, "row") ){
26085           mType |= SQLITE_TRACE_ROW;
26086         }
26087         else if( optionMatch(z, "stmt") ){
26088           mType |= SQLITE_TRACE_STMT;
26089         }
26090         else if( optionMatch(z, "close") ){
26091           mType |= SQLITE_TRACE_CLOSE;
26092         }
26093         else {
26094           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
26095           rc = 1;
26096           goto meta_command_exit;
26097         }
26098       }else{
26099         output_file_close(p->traceOut);
26100         p->traceOut = output_file_open(z, 0);
26101       }
26102     }
26103     if( p->traceOut==0 ){
26104       sqlite3_trace_v2(p->db, 0, 0, 0);
26105     }else{
26106       if( mType==0 ) mType = SQLITE_TRACE_STMT;
26107       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
26108     }
26109   }else
26110 #endif /* !defined(SQLITE_OMIT_TRACE) */
26111 
26112 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
26113   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
26114     int ii;
26115     int lenOpt;
26116     char *zOpt;
26117     if( nArg<2 ){
26118       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
26119       rc = 1;
26120       goto meta_command_exit;
26121     }
26122     open_db(p, 0);
26123     zOpt = azArg[1];
26124     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
26125     lenOpt = (int)strlen(zOpt);
26126     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
26127       assert( azArg[nArg]==0 );
26128       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
26129     }else{
26130       for(ii=1; ii<nArg; ii++){
26131         sqlite3_create_module(p->db, azArg[ii], 0, 0);
26132       }
26133     }
26134   }else
26135 #endif
26136 
26137 #if SQLITE_USER_AUTHENTICATION
26138   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
26139     if( nArg<2 ){
26140       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
26141       rc = 1;
26142       goto meta_command_exit;
26143     }
26144     open_db(p, 0);
26145     if( cli_strcmp(azArg[1],"login")==0 ){
26146       if( nArg!=4 ){
26147         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
26148         rc = 1;
26149         goto meta_command_exit;
26150       }
26151       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
26152                                      strlen30(azArg[3]));
26153       if( rc ){
26154         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
26155         rc = 1;
26156       }
26157     }else if( cli_strcmp(azArg[1],"add")==0 ){
26158       if( nArg!=5 ){
26159         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
26160         rc = 1;
26161         goto meta_command_exit;
26162       }
26163       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
26164                             booleanValue(azArg[4]));
26165       if( rc ){
26166         raw_printf(stderr, "User-Add failed: %d\n", rc);
26167         rc = 1;
26168       }
26169     }else if( cli_strcmp(azArg[1],"edit")==0 ){
26170       if( nArg!=5 ){
26171         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
26172         rc = 1;
26173         goto meta_command_exit;
26174       }
26175       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
26176                               booleanValue(azArg[4]));
26177       if( rc ){
26178         raw_printf(stderr, "User-Edit failed: %d\n", rc);
26179         rc = 1;
26180       }
26181     }else if( cli_strcmp(azArg[1],"delete")==0 ){
26182       if( nArg!=3 ){
26183         raw_printf(stderr, "Usage: .user delete USER\n");
26184         rc = 1;
26185         goto meta_command_exit;
26186       }
26187       rc = sqlite3_user_delete(p->db, azArg[2]);
26188       if( rc ){
26189         raw_printf(stderr, "User-Delete failed: %d\n", rc);
26190         rc = 1;
26191       }
26192     }else{
26193       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
26194       rc = 1;
26195       goto meta_command_exit;
26196     }
26197   }else
26198 #endif /* SQLITE_USER_AUTHENTICATION */
26199 
26200   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
26201     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
26202         sqlite3_libversion(), sqlite3_sourceid());
26203 #if SQLITE_HAVE_ZLIB
26204     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
26205 #endif
26206 #define CTIMEOPT_VAL_(opt) #opt
26207 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
26208 #if defined(__clang__) && defined(__clang_major__)
26209     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
26210                     CTIMEOPT_VAL(__clang_minor__) "."
26211                     CTIMEOPT_VAL(__clang_patchlevel__) "\n");
26212 #elif defined(_MSC_VER)
26213     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
26214 #elif defined(__GNUC__) && defined(__VERSION__)
26215     utf8_printf(p->out, "gcc-" __VERSION__ "\n");
26216 #endif
26217   }else
26218 
26219   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
26220     const char *zDbName = nArg==2 ? azArg[1] : "main";
26221     sqlite3_vfs *pVfs = 0;
26222     if( p->db ){
26223       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
26224       if( pVfs ){
26225         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
26226         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
26227         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
26228         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
26229       }
26230     }
26231   }else
26232 
26233   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
26234     sqlite3_vfs *pVfs;
26235     sqlite3_vfs *pCurrent = 0;
26236     if( p->db ){
26237       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
26238     }
26239     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
26240       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
26241            pVfs==pCurrent ? "  <--- CURRENT" : "");
26242       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
26243       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
26244       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
26245       if( pVfs->pNext ){
26246         raw_printf(p->out, "-----------------------------------\n");
26247       }
26248     }
26249   }else
26250 
26251   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
26252     const char *zDbName = nArg==2 ? azArg[1] : "main";
26253     char *zVfsName = 0;
26254     if( p->db ){
26255       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
26256       if( zVfsName ){
26257         utf8_printf(p->out, "%s\n", zVfsName);
26258         sqlite3_free(zVfsName);
26259       }
26260     }
26261   }else
26262 
26263   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
26264     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26265     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
26266   }else
26267 
26268   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
26269     int j;
26270     assert( nArg<=ArraySize(azArg) );
26271     p->nWidth = nArg-1;
26272     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
26273     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
26274     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
26275     for(j=1; j<nArg; j++){
26276       p->colWidth[j-1] = (int)integerValue(azArg[j]);
26277     }
26278   }else
26279 
26280   {
26281     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
26282       " \"%s\". Enter \".help\" for help\n", azArg[0]);
26283     rc = 1;
26284   }
26285 
26286 meta_command_exit:
26287   if( p->outCount ){
26288     p->outCount--;
26289     if( p->outCount==0 ) output_reset(p);
26290   }
26291   p->bSafeMode = p->bSafeModePersist;
26292   return rc;
26293 }
26294 
26295 /* Line scan result and intermediate states (supporting scan resumption)
26296 */
26297 #ifndef CHAR_BIT
26298 # define CHAR_BIT 8
26299 #endif
26300 typedef enum {
26301   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
26302   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
26303   QSS_Start = 0
26304 } QuickScanState;
26305 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
26306 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
26307 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
26308 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
26309 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
26310 
26311 /*
26312 ** Scan line for classification to guide shell's handling.
26313 ** The scan is resumable for subsequent lines when prior
26314 ** return values are passed as the 2nd argument.
26315 */
26316 static QuickScanState quickscan(char *zLine, QuickScanState qss,
26317                                 SCAN_TRACKER_REFTYPE pst){
26318   char cin;
26319   char cWait = (char)qss; /* intentional narrowing loss */
26320   if( cWait==0 ){
26321   PlainScan:
26322     assert( cWait==0 );
26323     while( (cin = *zLine++)!=0 ){
26324       if( IsSpace(cin) )
26325         continue;
26326       switch (cin){
26327       case '-':
26328         if( *zLine!='-' )
26329           break;
26330         while((cin = *++zLine)!=0 )
26331           if( cin=='\n')
26332             goto PlainScan;
26333         return qss;
26334       case ';':
26335         qss |= QSS_EndingSemi;
26336         continue;
26337       case '/':
26338         if( *zLine=='*' ){
26339           ++zLine;
26340           cWait = '*';
26341           CONTINUE_PROMPT_AWAITS(pst, "/*");
26342           qss = QSS_SETV(qss, cWait);
26343           goto TermScan;
26344         }
26345         break;
26346       case '[':
26347         cin = ']';
26348         deliberate_fall_through;
26349       case '`': case '\'': case '"':
26350         cWait = cin;
26351         qss = QSS_HasDark | cWait;
26352         CONTINUE_PROMPT_AWAITC(pst, cin);
26353         goto TermScan;
26354       case '(':
26355         CONTINUE_PAREN_INCR(pst, 1);
26356         break;
26357       case ')':
26358         CONTINUE_PAREN_INCR(pst, -1);
26359         break;
26360       default:
26361         break;
26362       }
26363       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
26364     }
26365   }else{
26366   TermScan:
26367     while( (cin = *zLine++)!=0 ){
26368       if( cin==cWait ){
26369         switch( cWait ){
26370         case '*':
26371           if( *zLine != '/' )
26372             continue;
26373           ++zLine;
26374           cWait = 0;
26375           CONTINUE_PROMPT_AWAITC(pst, 0);
26376           qss = QSS_SETV(qss, 0);
26377           goto PlainScan;
26378         case '`': case '\'': case '"':
26379           if(*zLine==cWait){
26380             /* Swallow doubled end-delimiter.*/
26381             ++zLine;
26382             continue;
26383           }
26384           deliberate_fall_through;
26385         case ']':
26386           cWait = 0;
26387           CONTINUE_PROMPT_AWAITC(pst, 0);
26388           qss = QSS_SETV(qss, 0);
26389           goto PlainScan;
26390         default: assert(0);
26391         }
26392       }
26393     }
26394   }
26395   return qss;
26396 }
26397 
26398 /*
26399 ** Return TRUE if the line typed in is an SQL command terminator other
26400 ** than a semi-colon.  The SQL Server style "go" command is understood
26401 ** as is the Oracle "/".
26402 */
26403 static int line_is_command_terminator(char *zLine){
26404   while( IsSpace(zLine[0]) ){ zLine++; };
26405   if( zLine[0]=='/' )
26406     zLine += 1; /* Oracle */
26407   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
26408     zLine += 2; /* SQL Server */
26409   else
26410     return 0;
26411   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
26412 }
26413 
26414 /*
26415 ** The CLI needs a working sqlite3_complete() to work properly.  So error
26416 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
26417 */
26418 #ifdef SQLITE_OMIT_COMPLETE
26419 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
26420 #endif
26421 
26422 /*
26423 ** Return true if zSql is a complete SQL statement.  Return false if it
26424 ** ends in the middle of a string literal or C-style comment.
26425 */
26426 static int line_is_complete(char *zSql, int nSql){
26427   int rc;
26428   if( zSql==0 ) return 1;
26429   zSql[nSql] = ';';
26430   zSql[nSql+1] = 0;
26431   rc = sqlite3_complete(zSql);
26432   zSql[nSql] = 0;
26433   return rc;
26434 }
26435 
26436 /*
26437 ** Run a single line of SQL.  Return the number of errors.
26438 */
26439 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
26440   int rc;
26441   char *zErrMsg = 0;
26442 
26443   open_db(p, 0);
26444   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
26445   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
26446   BEGIN_TIMER;
26447   rc = shell_exec(p, zSql, &zErrMsg);
26448   END_TIMER;
26449   if( rc || zErrMsg ){
26450     char zPrefix[100];
26451     const char *zErrorTail;
26452     const char *zErrorType;
26453     if( zErrMsg==0 ){
26454       zErrorType = "Error";
26455       zErrorTail = sqlite3_errmsg(p->db);
26456     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
26457       zErrorType = "Parse error";
26458       zErrorTail = &zErrMsg[12];
26459     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
26460       zErrorType = "Runtime error";
26461       zErrorTail = &zErrMsg[10];
26462     }else{
26463       zErrorType = "Error";
26464       zErrorTail = zErrMsg;
26465     }
26466     if( in!=0 || !stdin_is_interactive ){
26467       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
26468                        "%s near line %d:", zErrorType, startline);
26469     }else{
26470       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
26471     }
26472     utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
26473     sqlite3_free(zErrMsg);
26474     zErrMsg = 0;
26475     return 1;
26476   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
26477     char zLineBuf[2000];
26478     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
26479             "changes: %lld   total_changes: %lld",
26480             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
26481     raw_printf(p->out, "%s\n", zLineBuf);
26482   }
26483   return 0;
26484 }
26485 
26486 static void echo_group_input(ShellState *p, const char *zDo){
26487   if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
26488 }
26489 
26490 #ifdef SQLITE_SHELL_FIDDLE
26491 /*
26492 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
26493 ** impl because we need the global shellState and cannot access it from that
26494 ** function without moving lots of code around (creating a larger/messier diff).
26495 */
26496 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
26497   /* Parse the next line from shellState.wasm.zInput. */
26498   const char *zBegin = shellState.wasm.zPos;
26499   const char *z = zBegin;
26500   char *zLine = 0;
26501   i64 nZ = 0;
26502 
26503   UNUSED_PARAMETER(in);
26504   UNUSED_PARAMETER(isContinuation);
26505   if(!z || !*z){
26506     return 0;
26507   }
26508   while(*z && isspace(*z)) ++z;
26509   zBegin = z;
26510   for(; *z && '\n'!=*z; ++nZ, ++z){}
26511   if(nZ>0 && '\r'==zBegin[nZ-1]){
26512     --nZ;
26513   }
26514   shellState.wasm.zPos = z;
26515   zLine = realloc(zPrior, nZ+1);
26516   shell_check_oom(zLine);
26517   memcpy(zLine, zBegin, nZ);
26518   zLine[nZ] = 0;
26519   return zLine;
26520 }
26521 #endif /* SQLITE_SHELL_FIDDLE */
26522 
26523 /*
26524 ** Read input from *in and process it.  If *in==0 then input
26525 ** is interactive - the user is typing it it.  Otherwise, input
26526 ** is coming from a file or device.  A prompt is issued and history
26527 ** is saved only if input is interactive.  An interrupt signal will
26528 ** cause this routine to exit immediately, unless input is interactive.
26529 **
26530 ** Return the number of errors.
26531 */
26532 static int process_input(ShellState *p){
26533   char *zLine = 0;          /* A single input line */
26534   char *zSql = 0;           /* Accumulated SQL text */
26535   i64 nLine;                /* Length of current line */
26536   i64 nSql = 0;             /* Bytes of zSql[] used */
26537   i64 nAlloc = 0;           /* Allocated zSql[] space */
26538   int rc;                   /* Error code */
26539   int errCnt = 0;           /* Number of errors seen */
26540   i64 startline = 0;        /* Line number for start of current input */
26541   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
26542 
26543   if( p->inputNesting==MAX_INPUT_NESTING ){
26544     /* This will be more informative in a later version. */
26545     utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
26546                 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
26547     return 1;
26548   }
26549   ++p->inputNesting;
26550   p->lineno = 0;
26551   CONTINUE_PROMPT_RESET;
26552   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
26553     fflush(p->out);
26554     zLine = one_input_line(p->in, zLine, nSql>0);
26555     if( zLine==0 ){
26556       /* End of input */
26557       if( p->in==0 && stdin_is_interactive ) printf("\n");
26558       break;
26559     }
26560     if( seenInterrupt ){
26561       if( p->in!=0 ) break;
26562       seenInterrupt = 0;
26563     }
26564     p->lineno++;
26565     if( QSS_INPLAIN(qss)
26566         && line_is_command_terminator(zLine)
26567         && line_is_complete(zSql, nSql) ){
26568       memcpy(zLine,";",2);
26569     }
26570     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
26571     if( QSS_PLAINWHITE(qss) && nSql==0 ){
26572       /* Just swallow single-line whitespace */
26573       echo_group_input(p, zLine);
26574       qss = QSS_Start;
26575       continue;
26576     }
26577     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
26578       CONTINUE_PROMPT_RESET;
26579       echo_group_input(p, zLine);
26580       if( zLine[0]=='.' ){
26581         rc = do_meta_command(zLine, p);
26582         if( rc==2 ){ /* exit requested */
26583           break;
26584         }else if( rc ){
26585           errCnt++;
26586         }
26587       }
26588       qss = QSS_Start;
26589       continue;
26590     }
26591     /* No single-line dispositions remain; accumulate line(s). */
26592     nLine = strlen(zLine);
26593     if( nSql+nLine+2>=nAlloc ){
26594       /* Grow buffer by half-again increments when big. */
26595       nAlloc = nSql+(nSql>>1)+nLine+100;
26596       zSql = realloc(zSql, nAlloc);
26597       shell_check_oom(zSql);
26598     }
26599     if( nSql==0 ){
26600       i64 i;
26601       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
26602       assert( nAlloc>0 && zSql!=0 );
26603       memcpy(zSql, zLine+i, nLine+1-i);
26604       startline = p->lineno;
26605       nSql = nLine-i;
26606     }else{
26607       zSql[nSql++] = '\n';
26608       memcpy(zSql+nSql, zLine, nLine+1);
26609       nSql += nLine;
26610     }
26611     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
26612       echo_group_input(p, zSql);
26613       errCnt += runOneSqlLine(p, zSql, p->in, startline);
26614       CONTINUE_PROMPT_RESET;
26615       nSql = 0;
26616       if( p->outCount ){
26617         output_reset(p);
26618         p->outCount = 0;
26619       }else{
26620         clearTempFile(p);
26621       }
26622       p->bSafeMode = p->bSafeModePersist;
26623       qss = QSS_Start;
26624     }else if( nSql && QSS_PLAINWHITE(qss) ){
26625       echo_group_input(p, zSql);
26626       nSql = 0;
26627       qss = QSS_Start;
26628     }
26629   }
26630   if( nSql ){
26631     /* This may be incomplete. Let the SQL parser deal with that. */
26632     echo_group_input(p, zSql);
26633     errCnt += runOneSqlLine(p, zSql, p->in, startline);
26634     CONTINUE_PROMPT_RESET;
26635   }
26636   free(zSql);
26637   free(zLine);
26638   --p->inputNesting;
26639   return errCnt>0;
26640 }
26641 
26642 /*
26643 ** Return a pathname which is the user's home directory.  A
26644 ** 0 return indicates an error of some kind.
26645 */
26646 static char *find_home_dir(int clearFlag){
26647   static char *home_dir = NULL;
26648   if( clearFlag ){
26649     free(home_dir);
26650     home_dir = 0;
26651     return 0;
26652   }
26653   if( home_dir ) return home_dir;
26654 
26655 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
26656      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
26657   {
26658     struct passwd *pwent;
26659     uid_t uid = getuid();
26660     if( (pwent=getpwuid(uid)) != NULL) {
26661       home_dir = pwent->pw_dir;
26662     }
26663   }
26664 #endif
26665 
26666 #if defined(_WIN32_WCE)
26667   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
26668    */
26669   home_dir = "/";
26670 #else
26671 
26672 #if defined(_WIN32) || defined(WIN32)
26673   if (!home_dir) {
26674     home_dir = getenv("USERPROFILE");
26675   }
26676 #endif
26677 
26678   if (!home_dir) {
26679     home_dir = getenv("HOME");
26680   }
26681 
26682 #if defined(_WIN32) || defined(WIN32)
26683   if (!home_dir) {
26684     char *zDrive, *zPath;
26685     int n;
26686     zDrive = getenv("HOMEDRIVE");
26687     zPath = getenv("HOMEPATH");
26688     if( zDrive && zPath ){
26689       n = strlen30(zDrive) + strlen30(zPath) + 1;
26690       home_dir = malloc( n );
26691       if( home_dir==0 ) return 0;
26692       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
26693       return home_dir;
26694     }
26695     home_dir = "c:\\";
26696   }
26697 #endif
26698 
26699 #endif /* !_WIN32_WCE */
26700 
26701   if( home_dir ){
26702     i64 n = strlen(home_dir) + 1;
26703     char *z = malloc( n );
26704     if( z ) memcpy(z, home_dir, n);
26705     home_dir = z;
26706   }
26707 
26708   return home_dir;
26709 }
26710 
26711 /*
26712 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
26713 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
26714 ** the path to it, else return 0. The result is cached for
26715 ** subsequent calls.
26716 */
26717 static const char *find_xdg_config(void){
26718 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
26719      || defined(__RTP__) || defined(_WRS_KERNEL)
26720   return 0;
26721 #else
26722   static int alreadyTried = 0;
26723   static char *zConfig = 0;
26724   const char *zXdgHome;
26725 
26726   if( alreadyTried!=0 ){
26727     return zConfig;
26728   }
26729   alreadyTried = 1;
26730   zXdgHome = getenv("XDG_CONFIG_HOME");
26731   if( zXdgHome==0 ){
26732     return 0;
26733   }
26734   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
26735   shell_check_oom(zConfig);
26736   if( access(zConfig,0)!=0 ){
26737     sqlite3_free(zConfig);
26738     zConfig = 0;
26739   }
26740   return zConfig;
26741 #endif
26742 }
26743 
26744 /*
26745 ** Read input from the file given by sqliterc_override.  Or if that
26746 ** parameter is NULL, take input from the first of find_xdg_config()
26747 ** or ~/.sqliterc which is found.
26748 **
26749 ** Returns the number of errors.
26750 */
26751 static void process_sqliterc(
26752   ShellState *p,                  /* Configuration data */
26753   const char *sqliterc_override   /* Name of config file. NULL to use default */
26754 ){
26755   char *home_dir = NULL;
26756   const char *sqliterc = sqliterc_override;
26757   char *zBuf = 0;
26758   FILE *inSaved = p->in;
26759   int savedLineno = p->lineno;
26760 
26761   if( sqliterc == NULL ){
26762     sqliterc = find_xdg_config();
26763   }
26764   if( sqliterc == NULL ){
26765     home_dir = find_home_dir(0);
26766     if( home_dir==0 ){
26767       raw_printf(stderr, "-- warning: cannot find home directory;"
26768                       " cannot read ~/.sqliterc\n");
26769       return;
26770     }
26771     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
26772     shell_check_oom(zBuf);
26773     sqliterc = zBuf;
26774   }
26775   p->in = fopen(sqliterc,"rb");
26776   if( p->in ){
26777     if( stdin_is_interactive ){
26778       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
26779     }
26780     if( process_input(p) && bail_on_error ) exit(1);
26781     fclose(p->in);
26782   }else if( sqliterc_override!=0 ){
26783     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
26784     if( bail_on_error ) exit(1);
26785   }
26786   p->in = inSaved;
26787   p->lineno = savedLineno;
26788   sqlite3_free(zBuf);
26789 }
26790 
26791 /*
26792 ** Show available command line options
26793 */
26794 static const char zOptions[] =
26795 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
26796   "   -A ARGS...           run \".archive ARGS\" and exit\n"
26797 #endif
26798   "   -append              append the database to the end of the file\n"
26799   "   -ascii               set output mode to 'ascii'\n"
26800   "   -bail                stop after hitting an error\n"
26801   "   -batch               force batch I/O\n"
26802   "   -box                 set output mode to 'box'\n"
26803   "   -column              set output mode to 'column'\n"
26804   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
26805   "   -csv                 set output mode to 'csv'\n"
26806 #if !defined(SQLITE_OMIT_DESERIALIZE)
26807   "   -deserialize         open the database using sqlite3_deserialize()\n"
26808 #endif
26809   "   -echo                print inputs before execution\n"
26810   "   -init FILENAME       read/process named file\n"
26811   "   -[no]header          turn headers on or off\n"
26812 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
26813   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
26814 #endif
26815   "   -help                show this message\n"
26816   "   -html                set output mode to HTML\n"
26817   "   -interactive         force interactive I/O\n"
26818   "   -json                set output mode to 'json'\n"
26819   "   -line                set output mode to 'line'\n"
26820   "   -list                set output mode to 'list'\n"
26821   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
26822   "   -markdown            set output mode to 'markdown'\n"
26823 #if !defined(SQLITE_OMIT_DESERIALIZE)
26824   "   -maxsize N           maximum size for a --deserialize database\n"
26825 #endif
26826   "   -memtrace            trace all memory allocations and deallocations\n"
26827   "   -mmap N              default mmap size set to N\n"
26828 #ifdef SQLITE_ENABLE_MULTIPLEX
26829   "   -multiplex           enable the multiplexor VFS\n"
26830 #endif
26831   "   -newline SEP         set output row separator. Default: '\\n'\n"
26832   "   -nofollow            refuse to open symbolic links to database files\n"
26833   "   -nonce STRING        set the safe-mode escape nonce\n"
26834   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
26835   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
26836   "   -quote               set output mode to 'quote'\n"
26837   "   -readonly            open the database read-only\n"
26838   "   -safe                enable safe-mode\n"
26839   "   -separator SEP       set output column separator. Default: '|'\n"
26840 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
26841   "   -sorterref SIZE      sorter references threshold size\n"
26842 #endif
26843   "   -stats               print memory stats before each finalize\n"
26844   "   -table               set output mode to 'table'\n"
26845   "   -tabs                set output mode to 'tabs'\n"
26846   "   -version             show SQLite version\n"
26847   "   -vfs NAME            use NAME as the default VFS\n"
26848 #ifdef SQLITE_ENABLE_VFSTRACE
26849   "   -vfstrace            enable tracing of all VFS calls\n"
26850 #endif
26851 #ifdef SQLITE_HAVE_ZLIB
26852   "   -zip                 open the file as a ZIP Archive\n"
26853 #endif
26854 ;
26855 static void usage(int showDetail){
26856   utf8_printf(stderr,
26857       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
26858       "FILENAME is the name of an SQLite database. A new database is created\n"
26859       "if the file does not previously exist.\n", Argv0);
26860   if( showDetail ){
26861     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
26862   }else{
26863     raw_printf(stderr, "Use the -help option for additional information\n");
26864   }
26865   exit(1);
26866 }
26867 
26868 /*
26869 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
26870 ** error message if it is initialized.
26871 */
26872 static void verify_uninitialized(void){
26873   if( sqlite3_config(-1)==SQLITE_MISUSE ){
26874     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
26875                         " initialization.\n");
26876   }
26877 }
26878 
26879 /*
26880 ** Initialize the state information in data
26881 */
26882 static void main_init(ShellState *data) {
26883   memset(data, 0, sizeof(*data));
26884   data->normalMode = data->cMode = data->mode = MODE_List;
26885   data->autoExplain = 1;
26886   data->pAuxDb = &data->aAuxDb[0];
26887   memcpy(data->colSeparator,SEP_Column, 2);
26888   memcpy(data->rowSeparator,SEP_Row, 2);
26889   data->showHeader = 0;
26890   data->shellFlgs = SHFLG_Lookaside;
26891   verify_uninitialized();
26892   sqlite3_config(SQLITE_CONFIG_URI, 1);
26893   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
26894   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
26895   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
26896   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
26897 }
26898 
26899 /*
26900 ** Output text to the console in a font that attracts extra attention.
26901 */
26902 #ifdef _WIN32
26903 static void printBold(const char *zText){
26904 #if !SQLITE_OS_WINRT
26905   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
26906   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
26907   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
26908   SetConsoleTextAttribute(out,
26909          FOREGROUND_RED|FOREGROUND_INTENSITY
26910   );
26911 #endif
26912   printf("%s", zText);
26913 #if !SQLITE_OS_WINRT
26914   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
26915 #endif
26916 }
26917 #else
26918 static void printBold(const char *zText){
26919   printf("\033[1m%s\033[0m", zText);
26920 }
26921 #endif
26922 
26923 /*
26924 ** Get the argument to an --option.  Throw an error and die if no argument
26925 ** is available.
26926 */
26927 static char *cmdline_option_value(int argc, char **argv, int i){
26928   if( i==argc ){
26929     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
26930             argv[0], argv[argc-1]);
26931     exit(1);
26932   }
26933   return argv[i];
26934 }
26935 
26936 #ifndef SQLITE_SHELL_IS_UTF8
26937 #  if (defined(_WIN32) || defined(WIN32)) \
26938    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
26939 #    define SQLITE_SHELL_IS_UTF8          (0)
26940 #  else
26941 #    define SQLITE_SHELL_IS_UTF8          (1)
26942 #  endif
26943 #endif
26944 
26945 #ifdef SQLITE_SHELL_FIDDLE
26946 #  define main fiddle_main
26947 #endif
26948 
26949 #if SQLITE_SHELL_IS_UTF8
26950 int SQLITE_CDECL main(int argc, char **argv){
26951 #else
26952 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
26953   char **argv;
26954 #endif
26955 #ifdef SQLITE_DEBUG
26956   sqlite3_int64 mem_main_enter = sqlite3_memory_used();
26957 #endif
26958   char *zErrMsg = 0;
26959 #ifdef SQLITE_SHELL_FIDDLE
26960 #  define data shellState
26961 #else
26962   ShellState data;
26963 #endif
26964   const char *zInitFile = 0;
26965   int i;
26966   int rc = 0;
26967   int warnInmemoryDb = 0;
26968   int readStdin = 1;
26969   int nCmd = 0;
26970   char **azCmd = 0;
26971   const char *zVfs = 0;           /* Value of -vfs command-line option */
26972 #if !SQLITE_SHELL_IS_UTF8
26973   char **argvToFree = 0;
26974   int argcToFree = 0;
26975 #endif
26976 
26977   setBinaryMode(stdin, 0);
26978   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
26979 #ifdef SQLITE_SHELL_FIDDLE
26980   stdin_is_interactive = 0;
26981   stdout_is_console = 1;
26982   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
26983 #else
26984   stdin_is_interactive = isatty(0);
26985   stdout_is_console = isatty(1);
26986 #endif
26987 
26988 #if !defined(_WIN32_WCE)
26989   if( getenv("SQLITE_DEBUG_BREAK") ){
26990     if( isatty(0) && isatty(2) ){
26991       fprintf(stderr,
26992           "attach debugger to process %d and press any key to continue.\n",
26993           GETPID());
26994       fgetc(stdin);
26995     }else{
26996 #if defined(_WIN32) || defined(WIN32)
26997 #if SQLITE_OS_WINRT
26998       __debugbreak();
26999 #else
27000       DebugBreak();
27001 #endif
27002 #elif defined(SIGTRAP)
27003       raise(SIGTRAP);
27004 #endif
27005     }
27006   }
27007 #endif
27008 
27009 #if USE_SYSTEM_SQLITE+0!=1
27010   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
27011     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
27012             sqlite3_sourceid(), SQLITE_SOURCE_ID);
27013     exit(1);
27014   }
27015 #endif
27016   main_init(&data);
27017 
27018   /* On Windows, we must translate command-line arguments into UTF-8.
27019   ** The SQLite memory allocator subsystem has to be enabled in order to
27020   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
27021   ** subsequent sqlite3_config() calls will work.  So copy all results into
27022   ** memory that does not come from the SQLite memory allocator.
27023   */
27024 #if !SQLITE_SHELL_IS_UTF8
27025   sqlite3_initialize();
27026   argvToFree = malloc(sizeof(argv[0])*argc*2);
27027   shell_check_oom(argvToFree);
27028   argcToFree = argc;
27029   argv = argvToFree + argc;
27030   for(i=0; i<argc; i++){
27031     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
27032     i64 n;
27033     shell_check_oom(z);
27034     n = strlen(z);
27035     argv[i] = malloc( n+1 );
27036     shell_check_oom(argv[i]);
27037     memcpy(argv[i], z, n+1);
27038     argvToFree[i] = argv[i];
27039     sqlite3_free(z);
27040   }
27041   sqlite3_shutdown();
27042 #endif
27043 
27044   assert( argc>=1 && argv && argv[0] );
27045   Argv0 = argv[0];
27046 
27047   /* Make sure we have a valid signal handler early, before anything
27048   ** else is done.
27049   */
27050 #ifdef SIGINT
27051   signal(SIGINT, interrupt_handler);
27052 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
27053   SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
27054 #endif
27055 
27056 #ifdef SQLITE_SHELL_DBNAME_PROC
27057   {
27058     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
27059     ** of a C-function that will provide the name of the database file.  Use
27060     ** this compile-time option to embed this shell program in larger
27061     ** applications. */
27062     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
27063     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
27064     warnInmemoryDb = 0;
27065   }
27066 #endif
27067 
27068   /* Do an initial pass through the command-line argument to locate
27069   ** the name of the database file, the name of the initialization file,
27070   ** the size of the alternative malloc heap,
27071   ** and the first command to execute.
27072   */
27073   verify_uninitialized();
27074   for(i=1; i<argc; i++){
27075     char *z;
27076     z = argv[i];
27077     if( z[0]!='-' ){
27078       if( data.aAuxDb->zDbFilename==0 ){
27079         data.aAuxDb->zDbFilename = z;
27080       }else{
27081         /* Excesss arguments are interpreted as SQL (or dot-commands) and
27082         ** mean that nothing is read from stdin */
27083         readStdin = 0;
27084         nCmd++;
27085         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
27086         shell_check_oom(azCmd);
27087         azCmd[nCmd-1] = z;
27088       }
27089     }
27090     if( z[1]=='-' ) z++;
27091     if( cli_strcmp(z,"-separator")==0
27092      || cli_strcmp(z,"-nullvalue")==0
27093      || cli_strcmp(z,"-newline")==0
27094      || cli_strcmp(z,"-cmd")==0
27095     ){
27096       (void)cmdline_option_value(argc, argv, ++i);
27097     }else if( cli_strcmp(z,"-init")==0 ){
27098       zInitFile = cmdline_option_value(argc, argv, ++i);
27099     }else if( cli_strcmp(z,"-batch")==0 ){
27100       /* Need to check for batch mode here to so we can avoid printing
27101       ** informational messages (like from process_sqliterc) before
27102       ** we do the actual processing of arguments later in a second pass.
27103       */
27104       stdin_is_interactive = 0;
27105     }else if( cli_strcmp(z,"-heap")==0 ){
27106 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
27107       const char *zSize;
27108       sqlite3_int64 szHeap;
27109 
27110       zSize = cmdline_option_value(argc, argv, ++i);
27111       szHeap = integerValue(zSize);
27112       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
27113       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
27114 #else
27115       (void)cmdline_option_value(argc, argv, ++i);
27116 #endif
27117     }else if( cli_strcmp(z,"-pagecache")==0 ){
27118       sqlite3_int64 n, sz;
27119       sz = integerValue(cmdline_option_value(argc,argv,++i));
27120       if( sz>70000 ) sz = 70000;
27121       if( sz<0 ) sz = 0;
27122       n = integerValue(cmdline_option_value(argc,argv,++i));
27123       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
27124         n = 0xffffffffffffLL/sz;
27125       }
27126       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
27127                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
27128       data.shellFlgs |= SHFLG_Pagecache;
27129     }else if( cli_strcmp(z,"-lookaside")==0 ){
27130       int n, sz;
27131       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
27132       if( sz<0 ) sz = 0;
27133       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
27134       if( n<0 ) n = 0;
27135       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
27136       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
27137     }else if( cli_strcmp(z,"-threadsafe")==0 ){
27138       int n;
27139       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
27140       switch( n ){
27141          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
27142          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
27143          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
27144       }
27145 #ifdef SQLITE_ENABLE_VFSTRACE
27146     }else if( cli_strcmp(z,"-vfstrace")==0 ){
27147       extern int vfstrace_register(
27148          const char *zTraceName,
27149          const char *zOldVfsName,
27150          int (*xOut)(const char*,void*),
27151          void *pOutArg,
27152          int makeDefault
27153       );
27154       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
27155 #endif
27156 #ifdef SQLITE_ENABLE_MULTIPLEX
27157     }else if( cli_strcmp(z,"-multiplex")==0 ){
27158       extern int sqlite3_multiple_initialize(const char*,int);
27159       sqlite3_multiplex_initialize(0, 1);
27160 #endif
27161     }else if( cli_strcmp(z,"-mmap")==0 ){
27162       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
27163       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
27164 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27165     }else if( cli_strcmp(z,"-sorterref")==0 ){
27166       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
27167       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
27168 #endif
27169     }else if( cli_strcmp(z,"-vfs")==0 ){
27170       zVfs = cmdline_option_value(argc, argv, ++i);
27171 #ifdef SQLITE_HAVE_ZLIB
27172     }else if( cli_strcmp(z,"-zip")==0 ){
27173       data.openMode = SHELL_OPEN_ZIPFILE;
27174 #endif
27175     }else if( cli_strcmp(z,"-append")==0 ){
27176       data.openMode = SHELL_OPEN_APPENDVFS;
27177 #ifndef SQLITE_OMIT_DESERIALIZE
27178     }else if( cli_strcmp(z,"-deserialize")==0 ){
27179       data.openMode = SHELL_OPEN_DESERIALIZE;
27180     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
27181       data.szMax = integerValue(argv[++i]);
27182 #endif
27183     }else if( cli_strcmp(z,"-readonly")==0 ){
27184       data.openMode = SHELL_OPEN_READONLY;
27185     }else if( cli_strcmp(z,"-nofollow")==0 ){
27186       data.openFlags = SQLITE_OPEN_NOFOLLOW;
27187 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27188     }else if( cli_strncmp(z, "-A",2)==0 ){
27189       /* All remaining command-line arguments are passed to the ".archive"
27190       ** command, so ignore them */
27191       break;
27192 #endif
27193     }else if( cli_strcmp(z, "-memtrace")==0 ){
27194       sqlite3MemTraceActivate(stderr);
27195     }else if( cli_strcmp(z,"-bail")==0 ){
27196       bail_on_error = 1;
27197     }else if( cli_strcmp(z,"-nonce")==0 ){
27198       free(data.zNonce);
27199       data.zNonce = strdup(argv[++i]);
27200     }else if( cli_strcmp(z,"-safe")==0 ){
27201       /* no-op - catch this on the second pass */
27202     }
27203   }
27204   verify_uninitialized();
27205 
27206 
27207 #ifdef SQLITE_SHELL_INIT_PROC
27208   {
27209     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
27210     ** of a C-function that will perform initialization actions on SQLite that
27211     ** occur just before or after sqlite3_initialize(). Use this compile-time
27212     ** option to embed this shell program in larger applications. */
27213     extern void SQLITE_SHELL_INIT_PROC(void);
27214     SQLITE_SHELL_INIT_PROC();
27215   }
27216 #else
27217   /* All the sqlite3_config() calls have now been made. So it is safe
27218   ** to call sqlite3_initialize() and process any command line -vfs option. */
27219   sqlite3_initialize();
27220 #endif
27221 
27222   if( zVfs ){
27223     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
27224     if( pVfs ){
27225       sqlite3_vfs_register(pVfs, 1);
27226     }else{
27227       utf8_printf(stderr, "no such VFS: \"%s\"\n", zVfs);
27228       exit(1);
27229     }
27230   }
27231 
27232   if( data.pAuxDb->zDbFilename==0 ){
27233 #ifndef SQLITE_OMIT_MEMORYDB
27234     data.pAuxDb->zDbFilename = ":memory:";
27235     warnInmemoryDb = argc==1;
27236 #else
27237     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
27238     return 1;
27239 #endif
27240   }
27241   data.out = stdout;
27242 #ifndef SQLITE_SHELL_FIDDLE
27243   sqlite3_appendvfs_init(0,0,0);
27244 #endif
27245 
27246   /* Go ahead and open the database file if it already exists.  If the
27247   ** file does not exist, delay opening it.  This prevents empty database
27248   ** files from being created if a user mistypes the database name argument
27249   ** to the sqlite command-line tool.
27250   */
27251   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
27252     open_db(&data, 0);
27253   }
27254 
27255   /* Process the initialization file if there is one.  If no -init option
27256   ** is given on the command line, look for a file named ~/.sqliterc and
27257   ** try to process it.
27258   */
27259   process_sqliterc(&data,zInitFile);
27260 
27261   /* Make a second pass through the command-line argument and set
27262   ** options.  This second pass is delayed until after the initialization
27263   ** file is processed so that the command-line arguments will override
27264   ** settings in the initialization file.
27265   */
27266   for(i=1; i<argc; i++){
27267     char *z = argv[i];
27268     if( z[0]!='-' ) continue;
27269     if( z[1]=='-' ){ z++; }
27270     if( cli_strcmp(z,"-init")==0 ){
27271       i++;
27272     }else if( cli_strcmp(z,"-html")==0 ){
27273       data.mode = MODE_Html;
27274     }else if( cli_strcmp(z,"-list")==0 ){
27275       data.mode = MODE_List;
27276     }else if( cli_strcmp(z,"-quote")==0 ){
27277       data.mode = MODE_Quote;
27278       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
27279       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
27280     }else if( cli_strcmp(z,"-line")==0 ){
27281       data.mode = MODE_Line;
27282     }else if( cli_strcmp(z,"-column")==0 ){
27283       data.mode = MODE_Column;
27284     }else if( cli_strcmp(z,"-json")==0 ){
27285       data.mode = MODE_Json;
27286     }else if( cli_strcmp(z,"-markdown")==0 ){
27287       data.mode = MODE_Markdown;
27288     }else if( cli_strcmp(z,"-table")==0 ){
27289       data.mode = MODE_Table;
27290     }else if( cli_strcmp(z,"-box")==0 ){
27291       data.mode = MODE_Box;
27292     }else if( cli_strcmp(z,"-csv")==0 ){
27293       data.mode = MODE_Csv;
27294       memcpy(data.colSeparator,",",2);
27295 #ifdef SQLITE_HAVE_ZLIB
27296     }else if( cli_strcmp(z,"-zip")==0 ){
27297       data.openMode = SHELL_OPEN_ZIPFILE;
27298 #endif
27299     }else if( cli_strcmp(z,"-append")==0 ){
27300       data.openMode = SHELL_OPEN_APPENDVFS;
27301 #ifndef SQLITE_OMIT_DESERIALIZE
27302     }else if( cli_strcmp(z,"-deserialize")==0 ){
27303       data.openMode = SHELL_OPEN_DESERIALIZE;
27304     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
27305       data.szMax = integerValue(argv[++i]);
27306 #endif
27307     }else if( cli_strcmp(z,"-readonly")==0 ){
27308       data.openMode = SHELL_OPEN_READONLY;
27309     }else if( cli_strcmp(z,"-nofollow")==0 ){
27310       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
27311     }else if( cli_strcmp(z,"-ascii")==0 ){
27312       data.mode = MODE_Ascii;
27313       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
27314       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
27315     }else if( cli_strcmp(z,"-tabs")==0 ){
27316       data.mode = MODE_List;
27317       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
27318       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
27319     }else if( cli_strcmp(z,"-separator")==0 ){
27320       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
27321                        "%s",cmdline_option_value(argc,argv,++i));
27322     }else if( cli_strcmp(z,"-newline")==0 ){
27323       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
27324                        "%s",cmdline_option_value(argc,argv,++i));
27325     }else if( cli_strcmp(z,"-nullvalue")==0 ){
27326       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
27327                        "%s",cmdline_option_value(argc,argv,++i));
27328     }else if( cli_strcmp(z,"-header")==0 ){
27329       data.showHeader = 1;
27330       ShellSetFlag(&data, SHFLG_HeaderSet);
27331      }else if( cli_strcmp(z,"-noheader")==0 ){
27332       data.showHeader = 0;
27333       ShellSetFlag(&data, SHFLG_HeaderSet);
27334     }else if( cli_strcmp(z,"-echo")==0 ){
27335       ShellSetFlag(&data, SHFLG_Echo);
27336     }else if( cli_strcmp(z,"-eqp")==0 ){
27337       data.autoEQP = AUTOEQP_on;
27338     }else if( cli_strcmp(z,"-eqpfull")==0 ){
27339       data.autoEQP = AUTOEQP_full;
27340     }else if( cli_strcmp(z,"-stats")==0 ){
27341       data.statsOn = 1;
27342     }else if( cli_strcmp(z,"-scanstats")==0 ){
27343       data.scanstatsOn = 1;
27344     }else if( cli_strcmp(z,"-backslash")==0 ){
27345       /* Undocumented command-line option: -backslash
27346       ** Causes C-style backslash escapes to be evaluated in SQL statements
27347       ** prior to sending the SQL into SQLite.  Useful for injecting
27348       ** crazy bytes in the middle of SQL statements for testing and debugging.
27349       */
27350       ShellSetFlag(&data, SHFLG_Backslash);
27351     }else if( cli_strcmp(z,"-bail")==0 ){
27352       /* No-op.  The bail_on_error flag should already be set. */
27353     }else if( cli_strcmp(z,"-version")==0 ){
27354       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
27355       return 0;
27356     }else if( cli_strcmp(z,"-interactive")==0 ){
27357       stdin_is_interactive = 1;
27358     }else if( cli_strcmp(z,"-batch")==0 ){
27359       stdin_is_interactive = 0;
27360     }else if( cli_strcmp(z,"-heap")==0 ){
27361       i++;
27362     }else if( cli_strcmp(z,"-pagecache")==0 ){
27363       i+=2;
27364     }else if( cli_strcmp(z,"-lookaside")==0 ){
27365       i+=2;
27366     }else if( cli_strcmp(z,"-threadsafe")==0 ){
27367       i+=2;
27368     }else if( cli_strcmp(z,"-nonce")==0 ){
27369       i += 2;
27370     }else if( cli_strcmp(z,"-mmap")==0 ){
27371       i++;
27372     }else if( cli_strcmp(z,"-memtrace")==0 ){
27373       i++;
27374 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27375     }else if( cli_strcmp(z,"-sorterref")==0 ){
27376       i++;
27377 #endif
27378     }else if( cli_strcmp(z,"-vfs")==0 ){
27379       i++;
27380 #ifdef SQLITE_ENABLE_VFSTRACE
27381     }else if( cli_strcmp(z,"-vfstrace")==0 ){
27382       i++;
27383 #endif
27384 #ifdef SQLITE_ENABLE_MULTIPLEX
27385     }else if( cli_strcmp(z,"-multiplex")==0 ){
27386       i++;
27387 #endif
27388     }else if( cli_strcmp(z,"-help")==0 ){
27389       usage(1);
27390     }else if( cli_strcmp(z,"-cmd")==0 ){
27391       /* Run commands that follow -cmd first and separately from commands
27392       ** that simply appear on the command-line.  This seems goofy.  It would
27393       ** be better if all commands ran in the order that they appear.  But
27394       ** we retain the goofy behavior for historical compatibility. */
27395       if( i==argc-1 ) break;
27396       z = cmdline_option_value(argc,argv,++i);
27397       if( z[0]=='.' ){
27398         rc = do_meta_command(z, &data);
27399         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
27400       }else{
27401         open_db(&data, 0);
27402         rc = shell_exec(&data, z, &zErrMsg);
27403         if( zErrMsg!=0 ){
27404           utf8_printf(stderr,"Error: %s\n", zErrMsg);
27405           if( bail_on_error ) return rc!=0 ? rc : 1;
27406         }else if( rc!=0 ){
27407           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
27408           if( bail_on_error ) return rc;
27409         }
27410       }
27411 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
27412     }else if( cli_strncmp(z, "-A", 2)==0 ){
27413       if( nCmd>0 ){
27414         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
27415                             " with \"%s\"\n", z);
27416         return 1;
27417       }
27418       open_db(&data, OPEN_DB_ZIPFILE);
27419       if( z[2] ){
27420         argv[i] = &z[2];
27421         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
27422       }else{
27423         arDotCommand(&data, 1, argv+i, argc-i);
27424       }
27425       readStdin = 0;
27426       break;
27427 #endif
27428     }else if( cli_strcmp(z,"-safe")==0 ){
27429       data.bSafeMode = data.bSafeModePersist = 1;
27430     }else{
27431       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
27432       raw_printf(stderr,"Use -help for a list of options.\n");
27433       return 1;
27434     }
27435     data.cMode = data.mode;
27436   }
27437 
27438   if( !readStdin ){
27439     /* Run all arguments that do not begin with '-' as if they were separate
27440     ** command-line inputs, except for the argToSkip argument which contains
27441     ** the database filename.
27442     */
27443     for(i=0; i<nCmd; i++){
27444       if( azCmd[i][0]=='.' ){
27445         rc = do_meta_command(azCmd[i], &data);
27446         if( rc ){
27447           free(azCmd);
27448           return rc==2 ? 0 : rc;
27449         }
27450       }else{
27451         open_db(&data, 0);
27452         rc = shell_exec(&data, azCmd[i], &zErrMsg);
27453         if( zErrMsg || rc ){
27454           if( zErrMsg!=0 ){
27455             utf8_printf(stderr,"Error: %s\n", zErrMsg);
27456           }else{
27457             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
27458           }
27459           sqlite3_free(zErrMsg);
27460           free(azCmd);
27461           return rc!=0 ? rc : 1;
27462         }
27463       }
27464     }
27465   }else{
27466     /* Run commands received from standard input
27467     */
27468     if( stdin_is_interactive ){
27469       char *zHome;
27470       char *zHistory;
27471       int nHistory;
27472       printf(
27473         "SQLite version %s %.19s\n" /*extra-version-info*/
27474         "Enter \".help\" for usage hints.\n",
27475         sqlite3_libversion(), sqlite3_sourceid()
27476       );
27477       if( warnInmemoryDb ){
27478         printf("Connected to a ");
27479         printBold("transient in-memory database");
27480         printf(".\nUse \".open FILENAME\" to reopen on a "
27481                "persistent database.\n");
27482       }
27483       zHistory = getenv("SQLITE_HISTORY");
27484       if( zHistory ){
27485         zHistory = strdup(zHistory);
27486       }else if( (zHome = find_home_dir(0))!=0 ){
27487         nHistory = strlen30(zHome) + 20;
27488         if( (zHistory = malloc(nHistory))!=0 ){
27489           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
27490         }
27491       }
27492       if( zHistory ){ shell_read_history(zHistory); }
27493 #if HAVE_READLINE || HAVE_EDITLINE
27494       rl_attempted_completion_function = readline_completion;
27495 #elif HAVE_LINENOISE
27496       linenoiseSetCompletionCallback(linenoise_completion);
27497 #endif
27498       data.in = 0;
27499       rc = process_input(&data);
27500       if( zHistory ){
27501         shell_stifle_history(2000);
27502         shell_write_history(zHistory);
27503         free(zHistory);
27504       }
27505     }else{
27506       data.in = stdin;
27507       rc = process_input(&data);
27508     }
27509   }
27510 #ifndef SQLITE_SHELL_FIDDLE
27511   /* In WASM mode we have to leave the db state in place so that
27512   ** client code can "push" SQL into it after this call returns. */
27513   free(azCmd);
27514   set_table_name(&data, 0);
27515   if( data.db ){
27516     session_close_all(&data, -1);
27517     close_db(data.db);
27518   }
27519   for(i=0; i<ArraySize(data.aAuxDb); i++){
27520     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
27521     if( data.aAuxDb[i].db ){
27522       session_close_all(&data, i);
27523       close_db(data.aAuxDb[i].db);
27524     }
27525   }
27526   find_home_dir(1);
27527   output_reset(&data);
27528   data.doXdgOpen = 0;
27529   clearTempFile(&data);
27530 #if !SQLITE_SHELL_IS_UTF8
27531   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
27532   free(argvToFree);
27533 #endif
27534   free(data.colWidth);
27535   free(data.zNonce);
27536   /* Clear the global data structure so that valgrind will detect memory
27537   ** leaks */
27538   memset(&data, 0, sizeof(data));
27539 #ifdef SQLITE_DEBUG
27540   if( sqlite3_memory_used()>mem_main_enter ){
27541     utf8_printf(stderr, "Memory leaked: %u bytes\n",
27542                 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
27543   }
27544 #endif
27545 #endif /* !SQLITE_SHELL_FIDDLE */
27546   return rc;
27547 }
27548 
27549 
27550 #ifdef SQLITE_SHELL_FIDDLE
27551 /* Only for emcc experimentation purposes. */
27552 int fiddle_experiment(int a,int b){
27553   return a + b;
27554 }
27555 
27556 /*
27557 ** Returns a pointer to the current DB handle.
27558 */
27559 sqlite3 * fiddle_db_handle(){
27560   return globalDb;
27561 }
27562 
27563 /*
27564 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
27565 ** "main" is assumed. Returns 0 if no db with the given name is
27566 ** open.
27567 */
27568 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
27569   sqlite3_vfs * pVfs = 0;
27570   if(globalDb){
27571     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
27572                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
27573   }
27574   return pVfs;
27575 }
27576 
27577 /* Only for emcc experimentation purposes. */
27578 sqlite3 * fiddle_db_arg(sqlite3 *arg){
27579     printf("fiddle_db_arg(%p)\n", (const void*)arg);
27580     return arg;
27581 }
27582 
27583 /*
27584 ** Intended to be called via a SharedWorker() while a separate
27585 ** SharedWorker() (which manages the wasm module) is performing work
27586 ** which should be interrupted. Unfortunately, SharedWorker is not
27587 ** portable enough to make real use of.
27588 */
27589 void fiddle_interrupt(void){
27590   if( globalDb ) sqlite3_interrupt(globalDb);
27591 }
27592 
27593 /*
27594 ** Returns the filename of the given db name, assuming "main" if
27595 ** zDbName is NULL. Returns NULL if globalDb is not opened.
27596 */
27597 const char * fiddle_db_filename(const char * zDbName){
27598     return globalDb
27599       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
27600       : NULL;
27601 }
27602 
27603 /*
27604 ** Completely wipes out the contents of the currently-opened database
27605 ** but leaves its storage intact for reuse.
27606 */
27607 void fiddle_reset_db(void){
27608   if( globalDb ){
27609     int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
27610     if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
27611     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
27612   }
27613 }
27614 
27615 /*
27616 ** Uses the current database's VFS xRead to stream the db file's
27617 ** contents out to the given callback. The callback gets a single
27618 ** chunk of size n (its 2nd argument) on each call and must return 0
27619 ** on success, non-0 on error. This function returns 0 on success,
27620 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
27621 ** code from the callback. Note that this is not thread-friendly: it
27622 ** expects that it will be the only thread reading the db file and
27623 ** takes no measures to ensure that is the case.
27624 */
27625 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
27626   sqlite3_int64 nSize = 0;
27627   sqlite3_int64 nPos = 0;
27628   sqlite3_file * pFile = 0;
27629   unsigned char buf[1024 * 8];
27630   int nBuf = (int)sizeof(buf);
27631   int rc = shellState.db
27632     ? sqlite3_file_control(shellState.db, "main",
27633                            SQLITE_FCNTL_FILE_POINTER, &pFile)
27634     : SQLITE_NOTFOUND;
27635   if( rc ) return rc;
27636   rc = pFile->pMethods->xFileSize(pFile, &nSize);
27637   if( rc ) return rc;
27638   if(nSize % nBuf){
27639     /* DB size is not an even multiple of the buffer size. Reduce
27640     ** buffer size so that we do not unduly inflate the db size when
27641     ** exporting. */
27642     if(0 == nSize % 4096) nBuf = 4096;
27643     else if(0 == nSize % 2048) nBuf = 2048;
27644     else if(0 == nSize % 1024) nBuf = 1024;
27645     else nBuf = 512;
27646   }
27647   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
27648     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
27649     if(SQLITE_IOERR_SHORT_READ == rc){
27650       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
27651     }
27652     if( 0==rc ) rc = xCallback(buf, nBuf);
27653   }
27654   return rc;
27655 }
27656 
27657 /*
27658 ** Trivial exportable function for emscripten. It processes zSql as if
27659 ** it were input to the sqlite3 shell and redirects all output to the
27660 ** wasm binding. fiddle_main() must have been called before this
27661 ** is called, or results are undefined.
27662 */
27663 void fiddle_exec(const char * zSql){
27664   if(zSql && *zSql){
27665     if('.'==*zSql) puts(zSql);
27666     shellState.wasm.zInput = zSql;
27667     shellState.wasm.zPos = zSql;
27668     process_input(&shellState);
27669     shellState.wasm.zInput = shellState.wasm.zPos = 0;
27670   }
27671 }
27672 #endif /* SQLITE_SHELL_FIDDLE */
27673