xref: /freebsd/contrib/sqlite3/shell.c (revision 4b9d6057)
1 /* DO NOT EDIT!
2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
6 **
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree.  That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
11 **
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
14 **
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18 */
19 /*
20 ** 2001 September 15
21 **
22 ** The author disclaims copyright to this source code.  In place of
23 ** a legal notice, here is a blessing:
24 **
25 **    May you do good and not evil.
26 **    May you find forgiveness for yourself and forgive others.
27 **    May you share freely, never taking more than you give.
28 **
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
32 */
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
36 #endif
37 typedef unsigned int u32;
38 typedef unsigned short int u16;
39 
40 /*
41 ** Optionally #include a user-defined header, whereby compilation options
42 ** may be set prior to where they take effect, but after platform setup.
43 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
44 ** file. Note that this macro has a like effect on sqlite3.c compilation.
45 */
46 # define SHELL_STRINGIFY_(f) #f
47 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
48 #ifdef SQLITE_CUSTOM_INCLUDE
49 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
50 #endif
51 
52 /*
53 ** Determine if we are dealing with WinRT, which provides only a subset of
54 ** the full Win32 API.
55 */
56 #if !defined(SQLITE_OS_WINRT)
57 # define SQLITE_OS_WINRT 0
58 #endif
59 
60 /*
61 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
62 ** somewhat for use as a WASM module in a web browser. This flag
63 ** should only be used when building the "fiddle" web application, as
64 ** the browser-mode build has much different user input requirements
65 ** and this build mode rewires the user input subsystem to account for
66 ** that.
67 */
68 
69 /*
70 ** Warning pragmas copied from msvc.h in the core.
71 */
72 #if defined(_MSC_VER)
73 #pragma warning(disable : 4054)
74 #pragma warning(disable : 4055)
75 #pragma warning(disable : 4100)
76 #pragma warning(disable : 4127)
77 #pragma warning(disable : 4130)
78 #pragma warning(disable : 4152)
79 #pragma warning(disable : 4189)
80 #pragma warning(disable : 4206)
81 #pragma warning(disable : 4210)
82 #pragma warning(disable : 4232)
83 #pragma warning(disable : 4244)
84 #pragma warning(disable : 4305)
85 #pragma warning(disable : 4306)
86 #pragma warning(disable : 4702)
87 #pragma warning(disable : 4706)
88 #endif /* defined(_MSC_VER) */
89 
90 /*
91 ** No support for loadable extensions in VxWorks.
92 */
93 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
94 # define SQLITE_OMIT_LOAD_EXTENSION 1
95 #endif
96 
97 /*
98 ** Enable large-file support for fopen() and friends on unix.
99 */
100 #ifndef SQLITE_DISABLE_LFS
101 # define _LARGE_FILE       1
102 # ifndef _FILE_OFFSET_BITS
103 #   define _FILE_OFFSET_BITS 64
104 # endif
105 # define _LARGEFILE_SOURCE 1
106 #endif
107 
108 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
109 /*
110 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
111 ** to expose strdup().
112 */
113 # define _POSIX_SOURCE
114 #endif
115 
116 #include <stdlib.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include <assert.h>
120 #include <math.h>
121 #include "sqlite3.h"
122 typedef sqlite3_int64 i64;
123 typedef sqlite3_uint64 u64;
124 typedef unsigned char u8;
125 #if SQLITE_USER_AUTHENTICATION
126 # include "sqlite3userauth.h"
127 #endif
128 #include <ctype.h>
129 #include <stdarg.h>
130 
131 #if !defined(_WIN32) && !defined(WIN32)
132 # include <signal.h>
133 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
134 #  include <pwd.h>
135 # endif
136 #endif
137 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
138 # include <unistd.h>
139 # include <dirent.h>
140 # define GETPID getpid
141 # if defined(__MINGW32__)
142 #  define DIRENT dirent
143 #  ifndef S_ISLNK
144 #   define S_ISLNK(mode) (0)
145 #  endif
146 # endif
147 #else
148 # define GETPID (int)GetCurrentProcessId
149 #endif
150 #include <sys/types.h>
151 #include <sys/stat.h>
152 
153 #if HAVE_READLINE
154 # include <readline/readline.h>
155 # include <readline/history.h>
156 #endif
157 
158 #if HAVE_EDITLINE
159 # include <editline/readline.h>
160 #endif
161 
162 #if HAVE_EDITLINE || HAVE_READLINE
163 
164 # define shell_add_history(X) add_history(X)
165 # define shell_read_history(X) read_history(X)
166 # define shell_write_history(X) write_history(X)
167 # define shell_stifle_history(X) stifle_history(X)
168 # define shell_readline(X) readline(X)
169 
170 #elif HAVE_LINENOISE
171 
172 # include "linenoise.h"
173 # define shell_add_history(X) linenoiseHistoryAdd(X)
174 # define shell_read_history(X) linenoiseHistoryLoad(X)
175 # define shell_write_history(X) linenoiseHistorySave(X)
176 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
177 # define shell_readline(X) linenoise(X)
178 
179 #else
180 
181 # define shell_read_history(X)
182 # define shell_write_history(X)
183 # define shell_stifle_history(X)
184 
185 # define SHELL_USE_LOCAL_GETLINE 1
186 #endif
187 
188 #ifndef deliberate_fall_through
189 /* Quiet some compilers about some of our intentional code. */
190 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
191 #  define deliberate_fall_through __attribute__((fallthrough));
192 # else
193 #  define deliberate_fall_through
194 # endif
195 #endif
196 
197 #if defined(_WIN32) || defined(WIN32)
198 # if SQLITE_OS_WINRT
199 #  define SQLITE_OMIT_POPEN 1
200 # else
201 #  include <io.h>
202 #  include <fcntl.h>
203 #  define isatty(h) _isatty(h)
204 #  ifndef access
205 #   define access(f,m) _access((f),(m))
206 #  endif
207 #  ifndef unlink
208 #   define unlink _unlink
209 #  endif
210 #  ifndef strdup
211 #   define strdup _strdup
212 #  endif
213 #  undef popen
214 #  define popen _popen
215 #  undef pclose
216 #  define pclose _pclose
217 # endif
218 #else
219  /* Make sure isatty() has a prototype. */
220  extern int isatty(int);
221 
222 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
223   /* popen and pclose are not C89 functions and so are
224   ** sometimes omitted from the <stdio.h> header */
225    extern FILE *popen(const char*,const char*);
226    extern int pclose(FILE*);
227 # else
228 #  define SQLITE_OMIT_POPEN 1
229 # endif
230 #endif
231 
232 #if defined(_WIN32_WCE)
233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
234  * thus we always assume that we have a console. That can be
235  * overridden with the -batch command line option.
236  */
237 #define isatty(x) 1
238 #endif
239 
240 /* ctype macros that work with signed characters */
241 #define IsSpace(X)  isspace((unsigned char)X)
242 #define IsDigit(X)  isdigit((unsigned char)X)
243 #define ToLower(X)  (char)tolower((unsigned char)X)
244 
245 #if defined(_WIN32) || defined(WIN32)
246 #if SQLITE_OS_WINRT
247 #include <intrin.h>
248 #endif
249 #undef WIN32_LEAN_AND_MEAN
250 #define WIN32_LEAN_AND_MEAN
251 #include <windows.h>
252 
253 /* string conversion routines only needed on Win32 */
254 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
255 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
256 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
257 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
258 #endif
259 
260 /* On Windows, we normally run with output mode of TEXT so that \n characters
261 ** are automatically translated into \r\n.  However, this behavior needs
262 ** to be disabled in some cases (ex: when generating CSV output and when
263 ** rendering quoted strings that contain \n characters).  The following
264 ** routines take care of that.
265 */
266 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
267 static void setBinaryMode(FILE *file, int isOutput){
268   if( isOutput ) fflush(file);
269   _setmode(_fileno(file), _O_BINARY);
270 }
271 static void setTextMode(FILE *file, int isOutput){
272   if( isOutput ) fflush(file);
273   _setmode(_fileno(file), _O_TEXT);
274 }
275 #else
276 # define setBinaryMode(X,Y)
277 # define setTextMode(X,Y)
278 #endif
279 
280 /* True if the timer is enabled */
281 static int enableTimer = 0;
282 
283 /* A version of strcmp() that works with NULL values */
284 static int cli_strcmp(const char *a, const char *b){
285   if( a==0 ) a = "";
286   if( b==0 ) b = "";
287   return strcmp(a,b);
288 }
289 static int cli_strncmp(const char *a, const char *b, size_t n){
290   if( a==0 ) a = "";
291   if( b==0 ) b = "";
292   return strncmp(a,b,n);
293 }
294 
295 /* Return the current wall-clock time */
296 static sqlite3_int64 timeOfDay(void){
297   static sqlite3_vfs *clockVfs = 0;
298   sqlite3_int64 t;
299   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
300   if( clockVfs==0 ) return 0;  /* Never actually happens */
301   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
302     clockVfs->xCurrentTimeInt64(clockVfs, &t);
303   }else{
304     double r;
305     clockVfs->xCurrentTime(clockVfs, &r);
306     t = (sqlite3_int64)(r*86400000.0);
307   }
308   return t;
309 }
310 
311 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
312 #include <sys/time.h>
313 #include <sys/resource.h>
314 
315 /* VxWorks does not support getrusage() as far as we can determine */
316 #if defined(_WRS_KERNEL) || defined(__RTP__)
317 struct rusage {
318   struct timeval ru_utime; /* user CPU time used */
319   struct timeval ru_stime; /* system CPU time used */
320 };
321 #define getrusage(A,B) memset(B,0,sizeof(*B))
322 #endif
323 
324 /* Saved resource information for the beginning of an operation */
325 static struct rusage sBegin;  /* CPU time at start */
326 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
327 
328 /*
329 ** Begin timing an operation
330 */
331 static void beginTimer(void){
332   if( enableTimer ){
333     getrusage(RUSAGE_SELF, &sBegin);
334     iBegin = timeOfDay();
335   }
336 }
337 
338 /* Return the difference of two time_structs in seconds */
339 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
340   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
341          (double)(pEnd->tv_sec - pStart->tv_sec);
342 }
343 
344 /*
345 ** Print the timing results.
346 */
347 static void endTimer(void){
348   if( enableTimer ){
349     sqlite3_int64 iEnd = timeOfDay();
350     struct rusage sEnd;
351     getrusage(RUSAGE_SELF, &sEnd);
352     printf("Run Time: real %.3f user %f sys %f\n",
353        (iEnd - iBegin)*0.001,
354        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
355        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
356   }
357 }
358 
359 #define BEGIN_TIMER beginTimer()
360 #define END_TIMER endTimer()
361 #define HAS_TIMER 1
362 
363 #elif (defined(_WIN32) || defined(WIN32))
364 
365 /* Saved resource information for the beginning of an operation */
366 static HANDLE hProcess;
367 static FILETIME ftKernelBegin;
368 static FILETIME ftUserBegin;
369 static sqlite3_int64 ftWallBegin;
370 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
371                                     LPFILETIME, LPFILETIME);
372 static GETPROCTIMES getProcessTimesAddr = NULL;
373 
374 /*
375 ** Check to see if we have timer support.  Return 1 if necessary
376 ** support found (or found previously).
377 */
378 static int hasTimer(void){
379   if( getProcessTimesAddr ){
380     return 1;
381   } else {
382 #if !SQLITE_OS_WINRT
383     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
384     ** versions. See if the version we are running on has it, and if it
385     ** does, save off a pointer to it and the current process handle.
386     */
387     hProcess = GetCurrentProcess();
388     if( hProcess ){
389       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
390       if( NULL != hinstLib ){
391         getProcessTimesAddr =
392             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
393         if( NULL != getProcessTimesAddr ){
394           return 1;
395         }
396         FreeLibrary(hinstLib);
397       }
398     }
399 #endif
400   }
401   return 0;
402 }
403 
404 /*
405 ** Begin timing an operation
406 */
407 static void beginTimer(void){
408   if( enableTimer && getProcessTimesAddr ){
409     FILETIME ftCreation, ftExit;
410     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
411                         &ftKernelBegin,&ftUserBegin);
412     ftWallBegin = timeOfDay();
413   }
414 }
415 
416 /* Return the difference of two FILETIME structs in seconds */
417 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
418   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
419   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
420   return (double) ((i64End - i64Start) / 10000000.0);
421 }
422 
423 /*
424 ** Print the timing results.
425 */
426 static void endTimer(void){
427   if( enableTimer && getProcessTimesAddr){
428     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
429     sqlite3_int64 ftWallEnd = timeOfDay();
430     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
431     printf("Run Time: real %.3f user %f sys %f\n",
432        (ftWallEnd - ftWallBegin)*0.001,
433        timeDiff(&ftUserBegin, &ftUserEnd),
434        timeDiff(&ftKernelBegin, &ftKernelEnd));
435   }
436 }
437 
438 #define BEGIN_TIMER beginTimer()
439 #define END_TIMER endTimer()
440 #define HAS_TIMER hasTimer()
441 
442 #else
443 #define BEGIN_TIMER
444 #define END_TIMER
445 #define HAS_TIMER 0
446 #endif
447 
448 /*
449 ** Used to prevent warnings about unused parameters
450 */
451 #define UNUSED_PARAMETER(x) (void)(x)
452 
453 /*
454 ** Number of elements in an array
455 */
456 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
457 
458 /*
459 ** If the following flag is set, then command execution stops
460 ** at an error if we are not interactive.
461 */
462 static int bail_on_error = 0;
463 
464 /*
465 ** Treat stdin as an interactive input if the following variable
466 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
467 */
468 static int stdin_is_interactive = 1;
469 
470 /*
471 ** If build is for non-RT Windows, without 3rd-party line editing,
472 ** console input and output may be done in a UTF-8 compatible way,
473 ** if the OS is capable of it and the --no-utf8 option is not seen.
474 */
475 #if (defined(_WIN32) || defined(WIN32)) && SHELL_USE_LOCAL_GETLINE \
476   && !defined(SHELL_OMIT_WIN_UTF8) && !SQLITE_OS_WINRT
477 # define SHELL_WIN_UTF8_OPT 1
478 /* Record whether to do UTF-8 console I/O translation per stream. */
479   static int console_utf8_in = 0;
480   static int console_utf8_out = 0;
481 /* Record whether can do UTF-8 or --no-utf8 seen in invocation. */
482   static int mbcs_opted = 1; /* Assume cannot do until shown otherwise. */
483 #else
484 # define console_utf8_in 0
485 # define console_utf8_out 0
486 # define SHELL_WIN_UTF8_OPT 0
487 #endif
488 
489 /*
490 ** On Windows systems we have to know if standard output is a console
491 ** in order to translate UTF-8 into MBCS.  The following variable is
492 ** true if translation is required.
493 */
494 static int stdout_is_console = 1;
495 
496 /*
497 ** The following is the open SQLite database.  We make a pointer
498 ** to this database a static variable so that it can be accessed
499 ** by the SIGINT handler to interrupt database processing.
500 */
501 static sqlite3 *globalDb = 0;
502 
503 /*
504 ** True if an interrupt (Control-C) has been received.
505 */
506 static volatile int seenInterrupt = 0;
507 
508 /*
509 ** This is the name of our program. It is set in main(), used
510 ** in a number of other places, mostly for error messages.
511 */
512 static char *Argv0;
513 
514 /*
515 ** Prompt strings. Initialized in main. Settable with
516 **   .prompt main continue
517 */
518 #define PROMPT_LEN_MAX 20
519 /* First line prompt.   default: "sqlite> " */
520 static char mainPrompt[PROMPT_LEN_MAX];
521 /* Continuation prompt. default: "   ...> " */
522 static char continuePrompt[PROMPT_LEN_MAX];
523 
524 /* This is variant of the standard-library strncpy() routine with the
525 ** one change that the destination string is always zero-terminated, even
526 ** if there is no zero-terminator in the first n-1 characters of the source
527 ** string.
528 */
529 static char *shell_strncpy(char *dest, const char *src, size_t n){
530   size_t i;
531   for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
532   dest[i] = 0;
533   return dest;
534 }
535 
536 /*
537 ** Optionally disable dynamic continuation prompt.
538 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
539 ** or open parentheses level if non-zero, or continuation prompt as set.
540 ** This facility interacts with the scanner and process_input() where the
541 ** below 5 macros are used.
542 */
543 #ifdef SQLITE_OMIT_DYNAPROMPT
544 # define CONTINUATION_PROMPT continuePrompt
545 # define CONTINUE_PROMPT_RESET
546 # define CONTINUE_PROMPT_AWAITS(p,s)
547 # define CONTINUE_PROMPT_AWAITC(p,c)
548 # define CONTINUE_PAREN_INCR(p,n)
549 # define CONTINUE_PROMPT_PSTATE 0
550 typedef void *t_NoDynaPrompt;
551 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
552 #else
553 # define CONTINUATION_PROMPT dynamicContinuePrompt()
554 # define CONTINUE_PROMPT_RESET \
555   do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
556 # define CONTINUE_PROMPT_AWAITS(p,s) \
557   if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
558 # define CONTINUE_PROMPT_AWAITC(p,c) \
559   if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
560 # define CONTINUE_PAREN_INCR(p,n) \
561   if(p && stdin_is_interactive) (trackParenLevel(p,n))
562 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
563 typedef struct DynaPrompt *t_DynaPromptRef;
564 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
565 
566 static struct DynaPrompt {
567   char dynamicPrompt[PROMPT_LEN_MAX];
568   char acAwait[2];
569   int inParenLevel;
570   char *zScannerAwaits;
571 } dynPrompt = { {0}, {0}, 0, 0 };
572 
573 /* Record parenthesis nesting level change, or force level to 0. */
574 static void trackParenLevel(struct DynaPrompt *p, int ni){
575   p->inParenLevel += ni;
576   if( ni==0 ) p->inParenLevel = 0;
577   p->zScannerAwaits = 0;
578 }
579 
580 /* Record that a lexeme is opened, or closed with args==0. */
581 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
582   if( s!=0 || c==0 ){
583     p->zScannerAwaits = s;
584     p->acAwait[0] = 0;
585   }else{
586     p->acAwait[0] = c;
587     p->zScannerAwaits = p->acAwait;
588   }
589 }
590 
591 /* Upon demand, derive the continuation prompt to display. */
592 static char *dynamicContinuePrompt(void){
593   if( continuePrompt[0]==0
594       || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
595     return continuePrompt;
596   }else{
597     if( dynPrompt.zScannerAwaits ){
598       size_t ncp = strlen(continuePrompt);
599       size_t ndp = strlen(dynPrompt.zScannerAwaits);
600       if( ndp > ncp-3 ) return continuePrompt;
601       strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
602       while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
603       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
604               PROMPT_LEN_MAX-4);
605     }else{
606       if( dynPrompt.inParenLevel>9 ){
607         shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
608       }else if( dynPrompt.inParenLevel<0 ){
609         shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
610       }else{
611         shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
612         dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
613       }
614       shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, PROMPT_LEN_MAX-4);
615     }
616   }
617   return dynPrompt.dynamicPrompt;
618 }
619 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
620 
621 #if SHELL_WIN_UTF8_OPT
622 /* Following struct is used for UTF-8 console I/O. */
623 static struct ConsoleState {
624   int stdinEof;      /* EOF has been seen on console input */
625   int infsMode;      /* Input file stream mode upon shell start */
626   UINT inCodePage;   /* Input code page upon shell start */
627   UINT outCodePage;  /* Output code page upon shell start */
628   HANDLE hConsole;   /* Console input or output handle */
629   DWORD consoleMode; /* Console mode upon shell start */
630 } conState = { 0, 0, 0, 0, INVALID_HANDLE_VALUE, 0 };
631 
632 #ifndef _O_U16TEXT /* For build environments lacking this constant: */
633 # define _O_U16TEXT 0x20000
634 #endif
635 
636 /*
637 ** If given stream number is a console, return 1 and get some attributes,
638 ** else return 0 and set the output attributes to invalid values.
639 */
640 static short console_attrs(unsigned stnum, HANDLE *pH, DWORD *pConsMode){
641   static int stid[3] = { STD_INPUT_HANDLE,STD_OUTPUT_HANDLE,STD_ERROR_HANDLE };
642   HANDLE h;
643   *pH = INVALID_HANDLE_VALUE;
644   *pConsMode = 0;
645   if( stnum > 2 ) return 0;
646   h = GetStdHandle(stid[stnum]);
647   if( h!=*pH && GetFileType(h)==FILE_TYPE_CHAR && GetConsoleMode(h,pConsMode) ){
648     *pH = h;
649     return 1;
650   }
651   return 0;
652 }
653 
654 /*
655 ** Perform a runtime test of Windows console to determine if it can
656 ** do char-stream I/O correctly when the code page is set to CP_UTF8.
657 ** Returns are: 1 => yes it can, 0 => no it cannot
658 **
659 ** The console's output code page is momentarily set, then restored.
660 ** So this should only be run when the process is given use of the
661 ** console for either input or output.
662 */
663 static short ConsoleDoesUTF8(void){
664   UINT ocp = GetConsoleOutputCP();
665   const char TrialUtf8[] = { '\xC8', '\xAB' }; /* "ȫ" or 2 MBCS characters */
666   WCHAR aReadBack[1] = { 0 }; /* Read back as 0x022B when decoded as UTF-8. */
667   CONSOLE_SCREEN_BUFFER_INFO csbInfo = {0};
668   /* Create an inactive screen buffer with which to do the experiment. */
669   HANDLE hCSB = CreateConsoleScreenBuffer(GENERIC_READ|GENERIC_WRITE, 0, 0,
670                                           CONSOLE_TEXTMODE_BUFFER, NULL);
671   if( hCSB!=INVALID_HANDLE_VALUE ){
672     COORD cpos = {0,0};
673     DWORD rbc;
674     SetConsoleCursorPosition(hCSB, cpos);
675     SetConsoleOutputCP(CP_UTF8);
676     /* Write 2 chars which are a single character in UTF-8 but more in MBCS. */
677     WriteConsoleA(hCSB, TrialUtf8, sizeof(TrialUtf8), NULL, NULL);
678     ReadConsoleOutputCharacterW(hCSB, &aReadBack[0], 1, cpos, &rbc);
679     GetConsoleScreenBufferInfo(hCSB, &csbInfo);
680     SetConsoleOutputCP(ocp);
681     CloseHandle(hCSB);
682   }
683   /* Return 1 if cursor advanced by 1 position, else 0. */
684   return (short)(csbInfo.dwCursorPosition.X == 1 && aReadBack[0] == 0x022B);
685 }
686 
687 static short in_console = 0;
688 static short out_console = 0;
689 
690 /*
691 ** Determine whether either normal I/O stream is the console,
692 ** and whether it can do UTF-8 translation, setting globals
693 ** in_console, out_console and mbcs_opted accordingly.
694 */
695 static void probe_console(void){
696   HANDLE h;
697   DWORD cMode;
698   in_console = console_attrs(0, &h, &cMode);
699   out_console = console_attrs(1, &h, &cMode);
700   if( in_console || out_console ) mbcs_opted = !ConsoleDoesUTF8();
701 }
702 
703 /*
704 ** If console is used for normal I/O, absent a --no-utf8 option,
705 ** prepare console for UTF-8 input (from either typing or suitable
706 ** paste operations) and/or for UTF-8 output rendering.
707 **
708 ** The console state upon entry is preserved, in conState, so that
709 ** console_restore() can later restore the same console state.
710 **
711 ** The globals console_utf8_in and console_utf8_out are set, for
712 ** later use in selecting UTF-8 or MBCS console I/O translations.
713 ** This routine depends upon globals set by probe_console().
714 */
715 static void console_prepare_utf8(void){
716   struct ConsoleState csWork = { 0, 0, 0, 0, INVALID_HANDLE_VALUE, 0 };
717 
718   console_utf8_in = console_utf8_out = 0;
719   if( (!in_console && !out_console) || mbcs_opted ) return;
720   console_attrs((in_console)? 0 : 1, &conState.hConsole, &conState.consoleMode);
721   conState.inCodePage = GetConsoleCP();
722   conState.outCodePage = GetConsoleOutputCP();
723   if( in_console ){
724     SetConsoleCP(CP_UTF8);
725     DWORD newConsoleMode = conState.consoleMode
726       | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
727     SetConsoleMode(conState.hConsole, newConsoleMode);
728     conState.infsMode = _setmode(_fileno(stdin), _O_U16TEXT);
729     console_utf8_in = 1;
730   }
731   if( out_console ){
732     SetConsoleOutputCP(CP_UTF8);
733     console_utf8_out = 1;
734   }
735 }
736 
737 /*
738 ** Undo the effects of console_prepare_utf8(), if any.
739 */
740 static void SQLITE_CDECL console_restore(void){
741   if( (console_utf8_in||console_utf8_out)
742       && conState.hConsole!=INVALID_HANDLE_VALUE ){
743     if( console_utf8_in ){
744       SetConsoleCP(conState.inCodePage);
745       _setmode(_fileno(stdin), conState.infsMode);
746     }
747     if( console_utf8_out ) SetConsoleOutputCP(conState.outCodePage);
748     SetConsoleMode(conState.hConsole, conState.consoleMode);
749     /* Avoid multiple calls. */
750     conState.hConsole = INVALID_HANDLE_VALUE;
751     conState.consoleMode = 0;
752     console_utf8_in = 0;
753     console_utf8_out = 0;
754   }
755 }
756 
757 /*
758 ** Collect input like fgets(...) with special provisions for input
759 ** from the Windows console to get around its strange coding issues.
760 ** Defers to plain fgets() when input is not interactive or when the
761 ** UTF-8 input is unavailable or opted out.
762 */
763 static char* utf8_fgets(char *buf, int ncmax, FILE *fin){
764   if( fin==0 ) fin = stdin;
765   if( fin==stdin && stdin_is_interactive && console_utf8_in ){
766 # define SQLITE_IALIM 150
767     wchar_t wbuf[SQLITE_IALIM];
768     int lend = 0;
769     int noc = 0;
770     if( ncmax==0 || conState.stdinEof ) return 0;
771     buf[0] = 0;
772     while( noc<ncmax-7-1 && !lend ){
773       /* There is room for at least 2 more characters and a 0-terminator. */
774       int na = (ncmax > SQLITE_IALIM*4+1 + noc)
775         ? SQLITE_IALIM : (ncmax-1 - noc)/4;
776 # undef SQLITE_IALIM
777       DWORD nbr = 0;
778       BOOL bRC = ReadConsoleW(conState.hConsole, wbuf, na, &nbr, 0);
779       if( !bRC || (noc==0 && nbr==0) ) return 0;
780       if( nbr > 0 ){
781         int nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
782                                       wbuf,nbr,0,0,0,0);
783         if( nmb !=0 && noc+nmb <= ncmax ){
784           int iseg = noc;
785           nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
786                                     wbuf,nbr,buf+noc,nmb,0,0);
787           noc += nmb;
788           /* Fixup line-ends as coded by Windows for CR (or "Enter".)*/
789           if( noc > 0 ){
790             if( buf[noc-1]=='\n' ){
791               lend = 1;
792               if( noc > 1 && buf[noc-2]=='\r' ){
793                 buf[noc-2] = '\n';
794                 --noc;
795               }
796             }
797           }
798           /* Check for ^Z (anywhere in line) too. */
799           while( iseg < noc ){
800             if( buf[iseg]==0x1a ){
801               conState.stdinEof = 1;
802               noc = iseg; /* Chop ^Z and anything following. */
803               break;
804             }
805             ++iseg;
806           }
807         }else break; /* Drop apparent garbage in. (Could assert.) */
808       }else break;
809     }
810     /* If got nothing, (after ^Z chop), must be at end-of-file. */
811     if( noc == 0 ) return 0;
812     buf[noc] = 0;
813     return buf;
814   }else{
815     return fgets(buf, ncmax, fin);
816   }
817 }
818 
819 # define fgets(b,n,f) utf8_fgets(b,n,f)
820 #endif /* SHELL_WIN_UTF8_OPT */
821 
822 /*
823 ** Render output like fprintf().  Except, if the output is going to the
824 ** console and if this is running on a Windows machine, and if UTF-8
825 ** output unavailable (or available but opted out), translate the
826 ** output from UTF-8 into MBCS for output through 8-bit stdout stream.
827 ** (Without -no-utf8, no translation is needed and must not be done.)
828 */
829 #if defined(_WIN32) || defined(WIN32)
830 void utf8_printf(FILE *out, const char *zFormat, ...){
831   va_list ap;
832   va_start(ap, zFormat);
833   if( stdout_is_console && (out==stdout || out==stderr) && !console_utf8_out ){
834     char *z1 = sqlite3_vmprintf(zFormat, ap);
835     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
836     sqlite3_free(z1);
837     fputs(z2, out);
838     sqlite3_free(z2);
839   }else{
840     vfprintf(out, zFormat, ap);
841   }
842   va_end(ap);
843 }
844 #elif !defined(utf8_printf)
845 # define utf8_printf fprintf
846 #endif
847 
848 /*
849 ** Render output like fprintf().  This should not be used on anything that
850 ** includes string formatting (e.g. "%s").
851 */
852 #if !defined(raw_printf)
853 # define raw_printf fprintf
854 #endif
855 
856 /* Indicate out-of-memory and exit. */
857 static void shell_out_of_memory(void){
858   raw_printf(stderr,"Error: out of memory\n");
859   exit(1);
860 }
861 
862 /* Check a pointer to see if it is NULL.  If it is NULL, exit with an
863 ** out-of-memory error.
864 */
865 static void shell_check_oom(const void *p){
866   if( p==0 ) shell_out_of_memory();
867 }
868 
869 /*
870 ** Write I/O traces to the following stream.
871 */
872 #ifdef SQLITE_ENABLE_IOTRACE
873 static FILE *iotrace = 0;
874 #endif
875 
876 /*
877 ** This routine works like printf in that its first argument is a
878 ** format string and subsequent arguments are values to be substituted
879 ** in place of % fields.  The result of formatting this string
880 ** is written to iotrace.
881 */
882 #ifdef SQLITE_ENABLE_IOTRACE
883 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
884   va_list ap;
885   char *z;
886   if( iotrace==0 ) return;
887   va_start(ap, zFormat);
888   z = sqlite3_vmprintf(zFormat, ap);
889   va_end(ap);
890   utf8_printf(iotrace, "%s", z);
891   sqlite3_free(z);
892 }
893 #endif
894 
895 /*
896 ** Output string zUtf to stream pOut as w characters.  If w is negative,
897 ** then right-justify the text.  W is the width in UTF-8 characters, not
898 ** in bytes.  This is different from the %*.*s specification in printf
899 ** since with %*.*s the width is measured in bytes, not characters.
900 */
901 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
902   int i;
903   int n;
904   int aw = w<0 ? -w : w;
905   if( zUtf==0 ) zUtf = "";
906   for(i=n=0; zUtf[i]; i++){
907     if( (zUtf[i]&0xc0)!=0x80 ){
908       n++;
909       if( n==aw ){
910         do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
911         break;
912       }
913     }
914   }
915   if( n>=aw ){
916     utf8_printf(pOut, "%.*s", i, zUtf);
917   }else if( w<0 ){
918     utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
919   }else{
920     utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
921   }
922 }
923 
924 
925 /*
926 ** Determines if a string is a number of not.
927 */
928 static int isNumber(const char *z, int *realnum){
929   if( *z=='-' || *z=='+' ) z++;
930   if( !IsDigit(*z) ){
931     return 0;
932   }
933   z++;
934   if( realnum ) *realnum = 0;
935   while( IsDigit(*z) ){ z++; }
936   if( *z=='.' ){
937     z++;
938     if( !IsDigit(*z) ) return 0;
939     while( IsDigit(*z) ){ z++; }
940     if( realnum ) *realnum = 1;
941   }
942   if( *z=='e' || *z=='E' ){
943     z++;
944     if( *z=='+' || *z=='-' ) z++;
945     if( !IsDigit(*z) ) return 0;
946     while( IsDigit(*z) ){ z++; }
947     if( realnum ) *realnum = 1;
948   }
949   return *z==0;
950 }
951 
952 /*
953 ** Compute a string length that is limited to what can be stored in
954 ** lower 30 bits of a 32-bit signed integer.
955 */
956 static int strlen30(const char *z){
957   const char *z2 = z;
958   while( *z2 ){ z2++; }
959   return 0x3fffffff & (int)(z2 - z);
960 }
961 
962 /*
963 ** Return the length of a string in characters.  Multibyte UTF8 characters
964 ** count as a single character.
965 */
966 static int strlenChar(const char *z){
967   int n = 0;
968   while( *z ){
969     if( (0xc0&*(z++))!=0x80 ) n++;
970   }
971   return n;
972 }
973 
974 /*
975 ** Return open FILE * if zFile exists, can be opened for read
976 ** and is an ordinary file or a character stream source.
977 ** Otherwise return 0.
978 */
979 static FILE * openChrSource(const char *zFile){
980 #ifdef _WIN32
981   struct _stat x = {0};
982 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
983   /* On Windows, open first, then check the stream nature. This order
984   ** is necessary because _stat() and sibs, when checking a named pipe,
985   ** effectively break the pipe as its supplier sees it. */
986   FILE *rv = fopen(zFile, "rb");
987   if( rv==0 ) return 0;
988   if( _fstat(_fileno(rv), &x) != 0
989       || !STAT_CHR_SRC(x.st_mode)){
990     fclose(rv);
991     rv = 0;
992   }
993   return rv;
994 #else
995   struct stat x = {0};
996   int rc = stat(zFile, &x);
997 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
998   if( rc!=0 ) return 0;
999   if( STAT_CHR_SRC(x.st_mode) ){
1000     return fopen(zFile, "rb");
1001   }else{
1002     return 0;
1003   }
1004 #endif
1005 #undef STAT_CHR_SRC
1006 }
1007 
1008 /*
1009 ** This routine reads a line of text from FILE in, stores
1010 ** the text in memory obtained from malloc() and returns a pointer
1011 ** to the text.  NULL is returned at end of file, or if malloc()
1012 ** fails.
1013 **
1014 ** If zLine is not NULL then it is a malloced buffer returned from
1015 ** a previous call to this routine that may be reused.
1016 */
1017 static char *local_getline(char *zLine, FILE *in){
1018   int nLine = zLine==0 ? 0 : 100;
1019   int n = 0;
1020 
1021   while( 1 ){
1022     if( n+100>nLine ){
1023       nLine = nLine*2 + 100;
1024       zLine = realloc(zLine, nLine);
1025       shell_check_oom(zLine);
1026     }
1027     if( fgets(&zLine[n], nLine - n, in)==0 ){
1028       if( n==0 ){
1029         free(zLine);
1030         return 0;
1031       }
1032       zLine[n] = 0;
1033       break;
1034     }
1035     while( zLine[n] ) n++;
1036     if( n>0 && zLine[n-1]=='\n' ){
1037       n--;
1038       if( n>0 && zLine[n-1]=='\r' ) n--;
1039       zLine[n] = 0;
1040       break;
1041     }
1042   }
1043 #if defined(_WIN32) || defined(WIN32)
1044   /* For interactive input on Windows systems, with -no-utf8,
1045   ** translate the multi-byte characterset characters into UTF-8.
1046   ** This is the translation that predates console UTF-8 input. */
1047   if( stdin_is_interactive && in==stdin && !console_utf8_in ){
1048     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
1049     if( zTrans ){
1050       i64 nTrans = strlen(zTrans)+1;
1051       if( nTrans>nLine ){
1052         zLine = realloc(zLine, nTrans);
1053         shell_check_oom(zLine);
1054       }
1055       memcpy(zLine, zTrans, nTrans);
1056       sqlite3_free(zTrans);
1057     }
1058   }
1059 #endif /* defined(_WIN32) || defined(WIN32) */
1060   return zLine;
1061 }
1062 
1063 /*
1064 ** Retrieve a single line of input text.
1065 **
1066 ** If in==0 then read from standard input and prompt before each line.
1067 ** If isContinuation is true, then a continuation prompt is appropriate.
1068 ** If isContinuation is zero, then the main prompt should be used.
1069 **
1070 ** If zPrior is not NULL then it is a buffer from a prior call to this
1071 ** routine that can be reused.
1072 **
1073 ** The result is stored in space obtained from malloc() and must either
1074 ** be freed by the caller or else passed back into this routine via the
1075 ** zPrior argument for reuse.
1076 */
1077 #ifndef SQLITE_SHELL_FIDDLE
1078 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1079   char *zPrompt;
1080   char *zResult;
1081   if( in!=0 ){
1082     zResult = local_getline(zPrior, in);
1083   }else{
1084     zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1085 #if SHELL_USE_LOCAL_GETLINE
1086     printf("%s", zPrompt);
1087     fflush(stdout);
1088     do{
1089       zResult = local_getline(zPrior, stdin);
1090       zPrior = 0;
1091       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1092       if( zResult==0 ) sqlite3_sleep(50);
1093     }while( zResult==0 && seenInterrupt>0 );
1094 #else
1095     free(zPrior);
1096     zResult = shell_readline(zPrompt);
1097     while( zResult==0 ){
1098       /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1099       sqlite3_sleep(50);
1100       if( seenInterrupt==0 ) break;
1101       zResult = shell_readline("");
1102     }
1103     if( zResult && *zResult ) shell_add_history(zResult);
1104 #endif
1105   }
1106   return zResult;
1107 }
1108 #endif /* !SQLITE_SHELL_FIDDLE */
1109 
1110 /*
1111 ** Return the value of a hexadecimal digit.  Return -1 if the input
1112 ** is not a hex digit.
1113 */
1114 static int hexDigitValue(char c){
1115   if( c>='0' && c<='9' ) return c - '0';
1116   if( c>='a' && c<='f' ) return c - 'a' + 10;
1117   if( c>='A' && c<='F' ) return c - 'A' + 10;
1118   return -1;
1119 }
1120 
1121 /*
1122 ** Interpret zArg as an integer value, possibly with suffixes.
1123 */
1124 static sqlite3_int64 integerValue(const char *zArg){
1125   sqlite3_int64 v = 0;
1126   static const struct { char *zSuffix; int iMult; } aMult[] = {
1127     { "KiB", 1024 },
1128     { "MiB", 1024*1024 },
1129     { "GiB", 1024*1024*1024 },
1130     { "KB",  1000 },
1131     { "MB",  1000000 },
1132     { "GB",  1000000000 },
1133     { "K",   1000 },
1134     { "M",   1000000 },
1135     { "G",   1000000000 },
1136   };
1137   int i;
1138   int isNeg = 0;
1139   if( zArg[0]=='-' ){
1140     isNeg = 1;
1141     zArg++;
1142   }else if( zArg[0]=='+' ){
1143     zArg++;
1144   }
1145   if( zArg[0]=='0' && zArg[1]=='x' ){
1146     int x;
1147     zArg += 2;
1148     while( (x = hexDigitValue(zArg[0]))>=0 ){
1149       v = (v<<4) + x;
1150       zArg++;
1151     }
1152   }else{
1153     while( IsDigit(zArg[0]) ){
1154       v = v*10 + zArg[0] - '0';
1155       zArg++;
1156     }
1157   }
1158   for(i=0; i<ArraySize(aMult); i++){
1159     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1160       v *= aMult[i].iMult;
1161       break;
1162     }
1163   }
1164   return isNeg? -v : v;
1165 }
1166 
1167 /*
1168 ** A variable length string to which one can append text.
1169 */
1170 typedef struct ShellText ShellText;
1171 struct ShellText {
1172   char *z;
1173   int n;
1174   int nAlloc;
1175 };
1176 
1177 /*
1178 ** Initialize and destroy a ShellText object
1179 */
1180 static void initText(ShellText *p){
1181   memset(p, 0, sizeof(*p));
1182 }
1183 static void freeText(ShellText *p){
1184   free(p->z);
1185   initText(p);
1186 }
1187 
1188 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1189 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1190 ** added to zIn, and the result returned in memory obtained from malloc().
1191 ** zIn, if it was not NULL, is freed.
1192 **
1193 ** If the third argument, quote, is not '\0', then it is used as a
1194 ** quote character for zAppend.
1195 */
1196 static void appendText(ShellText *p, const char *zAppend, char quote){
1197   i64 len;
1198   i64 i;
1199   i64 nAppend = strlen30(zAppend);
1200 
1201   len = nAppend+p->n+1;
1202   if( quote ){
1203     len += 2;
1204     for(i=0; i<nAppend; i++){
1205       if( zAppend[i]==quote ) len++;
1206     }
1207   }
1208 
1209   if( p->z==0 || p->n+len>=p->nAlloc ){
1210     p->nAlloc = p->nAlloc*2 + len + 20;
1211     p->z = realloc(p->z, p->nAlloc);
1212     shell_check_oom(p->z);
1213   }
1214 
1215   if( quote ){
1216     char *zCsr = p->z+p->n;
1217     *zCsr++ = quote;
1218     for(i=0; i<nAppend; i++){
1219       *zCsr++ = zAppend[i];
1220       if( zAppend[i]==quote ) *zCsr++ = quote;
1221     }
1222     *zCsr++ = quote;
1223     p->n = (int)(zCsr - p->z);
1224     *zCsr = '\0';
1225   }else{
1226     memcpy(p->z+p->n, zAppend, nAppend);
1227     p->n += nAppend;
1228     p->z[p->n] = '\0';
1229   }
1230 }
1231 
1232 /*
1233 ** Attempt to determine if identifier zName needs to be quoted, either
1234 ** because it contains non-alphanumeric characters, or because it is an
1235 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1236 ** that quoting is required.
1237 **
1238 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
1239 */
1240 static char quoteChar(const char *zName){
1241   int i;
1242   if( zName==0 ) return '"';
1243   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1244   for(i=0; zName[i]; i++){
1245     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1246   }
1247   return sqlite3_keyword_check(zName, i) ? '"' : 0;
1248 }
1249 
1250 /*
1251 ** Construct a fake object name and column list to describe the structure
1252 ** of the view, virtual table, or table valued function zSchema.zName.
1253 */
1254 static char *shellFakeSchema(
1255   sqlite3 *db,            /* The database connection containing the vtab */
1256   const char *zSchema,    /* Schema of the database holding the vtab */
1257   const char *zName       /* The name of the virtual table */
1258 ){
1259   sqlite3_stmt *pStmt = 0;
1260   char *zSql;
1261   ShellText s;
1262   char cQuote;
1263   char *zDiv = "(";
1264   int nRow = 0;
1265 
1266   zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1267                          zSchema ? zSchema : "main", zName);
1268   shell_check_oom(zSql);
1269   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1270   sqlite3_free(zSql);
1271   initText(&s);
1272   if( zSchema ){
1273     cQuote = quoteChar(zSchema);
1274     if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1275     appendText(&s, zSchema, cQuote);
1276     appendText(&s, ".", 0);
1277   }
1278   cQuote = quoteChar(zName);
1279   appendText(&s, zName, cQuote);
1280   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1281     const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1282     nRow++;
1283     appendText(&s, zDiv, 0);
1284     zDiv = ",";
1285     if( zCol==0 ) zCol = "";
1286     cQuote = quoteChar(zCol);
1287     appendText(&s, zCol, cQuote);
1288   }
1289   appendText(&s, ")", 0);
1290   sqlite3_finalize(pStmt);
1291   if( nRow==0 ){
1292     freeText(&s);
1293     s.z = 0;
1294   }
1295   return s.z;
1296 }
1297 
1298 /*
1299 ** SQL function:  strtod(X)
1300 **
1301 ** Use the C-library strtod() function to convert string X into a double.
1302 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1303 ** routines against the C-library.
1304 */
1305 static void shellStrtod(
1306   sqlite3_context *pCtx,
1307   int nVal,
1308   sqlite3_value **apVal
1309 ){
1310   char *z = (char*)sqlite3_value_text(apVal[0]);
1311   UNUSED_PARAMETER(nVal);
1312   if( z==0 ) return;
1313   sqlite3_result_double(pCtx, strtod(z,0));
1314 }
1315 
1316 /*
1317 ** SQL function:  dtostr(X)
1318 **
1319 ** Use the C-library printf() function to convert real value X into a string.
1320 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1321 ** routines against the C-library.
1322 */
1323 static void shellDtostr(
1324   sqlite3_context *pCtx,
1325   int nVal,
1326   sqlite3_value **apVal
1327 ){
1328   double r = sqlite3_value_double(apVal[0]);
1329   int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
1330   char z[400];
1331   if( n<1 ) n = 1;
1332   if( n>350 ) n = 350;
1333   snprintf(z, sizeof(z)-1, "%#+.*e", n, r);
1334   sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
1335 }
1336 
1337 
1338 /*
1339 ** SQL function:  shell_module_schema(X)
1340 **
1341 ** Return a fake schema for the table-valued function or eponymous virtual
1342 ** table X.
1343 */
1344 static void shellModuleSchema(
1345   sqlite3_context *pCtx,
1346   int nVal,
1347   sqlite3_value **apVal
1348 ){
1349   const char *zName;
1350   char *zFake;
1351   UNUSED_PARAMETER(nVal);
1352   zName = (const char*)sqlite3_value_text(apVal[0]);
1353   zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1354   if( zFake ){
1355     sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1356                         -1, sqlite3_free);
1357     free(zFake);
1358   }
1359 }
1360 
1361 /*
1362 ** SQL function:  shell_add_schema(S,X)
1363 **
1364 ** Add the schema name X to the CREATE statement in S and return the result.
1365 ** Examples:
1366 **
1367 **    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
1368 **
1369 ** Also works on
1370 **
1371 **    CREATE INDEX
1372 **    CREATE UNIQUE INDEX
1373 **    CREATE VIEW
1374 **    CREATE TRIGGER
1375 **    CREATE VIRTUAL TABLE
1376 **
1377 ** This UDF is used by the .schema command to insert the schema name of
1378 ** attached databases into the middle of the sqlite_schema.sql field.
1379 */
1380 static void shellAddSchemaName(
1381   sqlite3_context *pCtx,
1382   int nVal,
1383   sqlite3_value **apVal
1384 ){
1385   static const char *aPrefix[] = {
1386      "TABLE",
1387      "INDEX",
1388      "UNIQUE INDEX",
1389      "VIEW",
1390      "TRIGGER",
1391      "VIRTUAL TABLE"
1392   };
1393   int i = 0;
1394   const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1395   const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1396   const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1397   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1398   UNUSED_PARAMETER(nVal);
1399   if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1400     for(i=0; i<ArraySize(aPrefix); i++){
1401       int n = strlen30(aPrefix[i]);
1402       if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1403         char *z = 0;
1404         char *zFake = 0;
1405         if( zSchema ){
1406           char cQuote = quoteChar(zSchema);
1407           if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1408             z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1409           }else{
1410             z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1411           }
1412         }
1413         if( zName
1414          && aPrefix[i][0]=='V'
1415          && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1416         ){
1417           if( z==0 ){
1418             z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1419           }else{
1420             z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1421           }
1422           free(zFake);
1423         }
1424         if( z ){
1425           sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1426           return;
1427         }
1428       }
1429     }
1430   }
1431   sqlite3_result_value(pCtx, apVal[0]);
1432 }
1433 
1434 /*
1435 ** The source code for several run-time loadable extensions is inserted
1436 ** below by the ../tool/mkshellc.tcl script.  Before processing that included
1437 ** code, we need to override some macros to make the included program code
1438 ** work here in the middle of this regular program.
1439 */
1440 #define SQLITE_EXTENSION_INIT1
1441 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1442 
1443 #if defined(_WIN32) && defined(_MSC_VER)
1444 /************************* Begin test_windirent.h ******************/
1445 /*
1446 ** 2015 November 30
1447 **
1448 ** The author disclaims copyright to this source code.  In place of
1449 ** a legal notice, here is a blessing:
1450 **
1451 **    May you do good and not evil.
1452 **    May you find forgiveness for yourself and forgive others.
1453 **    May you share freely, never taking more than you give.
1454 **
1455 *************************************************************************
1456 ** This file contains declarations for most of the opendir() family of
1457 ** POSIX functions on Win32 using the MSVCRT.
1458 */
1459 
1460 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
1461 #define SQLITE_WINDIRENT_H
1462 
1463 /*
1464 ** We need several data types from the Windows SDK header.
1465 */
1466 
1467 #ifndef WIN32_LEAN_AND_MEAN
1468 #define WIN32_LEAN_AND_MEAN
1469 #endif
1470 
1471 #include "windows.h"
1472 
1473 /*
1474 ** We need several support functions from the SQLite core.
1475 */
1476 
1477 /* #include "sqlite3.h" */
1478 
1479 /*
1480 ** We need several things from the ANSI and MSVCRT headers.
1481 */
1482 
1483 #include <stdio.h>
1484 #include <stdlib.h>
1485 #include <errno.h>
1486 #include <io.h>
1487 #include <limits.h>
1488 #include <sys/types.h>
1489 #include <sys/stat.h>
1490 
1491 /*
1492 ** We may need several defines that should have been in "sys/stat.h".
1493 */
1494 
1495 #ifndef S_ISREG
1496 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1497 #endif
1498 
1499 #ifndef S_ISDIR
1500 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1501 #endif
1502 
1503 #ifndef S_ISLNK
1504 #define S_ISLNK(mode) (0)
1505 #endif
1506 
1507 /*
1508 ** We may need to provide the "mode_t" type.
1509 */
1510 
1511 #ifndef MODE_T_DEFINED
1512   #define MODE_T_DEFINED
1513   typedef unsigned short mode_t;
1514 #endif
1515 
1516 /*
1517 ** We may need to provide the "ino_t" type.
1518 */
1519 
1520 #ifndef INO_T_DEFINED
1521   #define INO_T_DEFINED
1522   typedef unsigned short ino_t;
1523 #endif
1524 
1525 /*
1526 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1527 */
1528 
1529 #ifndef NAME_MAX
1530 #  ifdef FILENAME_MAX
1531 #    define NAME_MAX (FILENAME_MAX)
1532 #  else
1533 #    define NAME_MAX (260)
1534 #  endif
1535 #endif
1536 
1537 /*
1538 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1539 */
1540 
1541 #ifndef NULL_INTPTR_T
1542 #  define NULL_INTPTR_T ((intptr_t)(0))
1543 #endif
1544 
1545 #ifndef BAD_INTPTR_T
1546 #  define BAD_INTPTR_T ((intptr_t)(-1))
1547 #endif
1548 
1549 /*
1550 ** We need to provide the necessary structures and related types.
1551 */
1552 
1553 #ifndef DIRENT_DEFINED
1554 #define DIRENT_DEFINED
1555 typedef struct DIRENT DIRENT;
1556 typedef DIRENT *LPDIRENT;
1557 struct DIRENT {
1558   ino_t d_ino;               /* Sequence number, do not use. */
1559   unsigned d_attributes;     /* Win32 file attributes. */
1560   char d_name[NAME_MAX + 1]; /* Name within the directory. */
1561 };
1562 #endif
1563 
1564 #ifndef DIR_DEFINED
1565 #define DIR_DEFINED
1566 typedef struct DIR DIR;
1567 typedef DIR *LPDIR;
1568 struct DIR {
1569   intptr_t d_handle; /* Value returned by "_findfirst". */
1570   DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
1571   DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
1572 };
1573 #endif
1574 
1575 /*
1576 ** Provide a macro, for use by the implementation, to determine if a
1577 ** particular directory entry should be skipped over when searching for
1578 ** the next directory entry that should be returned by the readdir() or
1579 ** readdir_r() functions.
1580 */
1581 
1582 #ifndef is_filtered
1583 #  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1584 #endif
1585 
1586 /*
1587 ** Provide the function prototype for the POSIX compatible getenv()
1588 ** function.  This function is not thread-safe.
1589 */
1590 
1591 extern const char *windirent_getenv(const char *name);
1592 
1593 /*
1594 ** Finally, we can provide the function prototypes for the opendir(),
1595 ** readdir(), readdir_r(), and closedir() POSIX functions.
1596 */
1597 
1598 extern LPDIR opendir(const char *dirname);
1599 extern LPDIRENT readdir(LPDIR dirp);
1600 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1601 extern INT closedir(LPDIR dirp);
1602 
1603 #endif /* defined(WIN32) && defined(_MSC_VER) */
1604 
1605 /************************* End test_windirent.h ********************/
1606 /************************* Begin test_windirent.c ******************/
1607 /*
1608 ** 2015 November 30
1609 **
1610 ** The author disclaims copyright to this source code.  In place of
1611 ** a legal notice, here is a blessing:
1612 **
1613 **    May you do good and not evil.
1614 **    May you find forgiveness for yourself and forgive others.
1615 **    May you share freely, never taking more than you give.
1616 **
1617 *************************************************************************
1618 ** This file contains code to implement most of the opendir() family of
1619 ** POSIX functions on Win32 using the MSVCRT.
1620 */
1621 
1622 #if defined(_WIN32) && defined(_MSC_VER)
1623 /* #include "test_windirent.h" */
1624 
1625 /*
1626 ** Implementation of the POSIX getenv() function using the Win32 API.
1627 ** This function is not thread-safe.
1628 */
1629 const char *windirent_getenv(
1630   const char *name
1631 ){
1632   static char value[32768]; /* Maximum length, per MSDN */
1633   DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1634   DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1635 
1636   memset(value, 0, sizeof(value));
1637   dwRet = GetEnvironmentVariableA(name, value, dwSize);
1638   if( dwRet==0 || dwRet>dwSize ){
1639     /*
1640     ** The function call to GetEnvironmentVariableA() failed -OR-
1641     ** the buffer is not large enough.  Either way, return NULL.
1642     */
1643     return 0;
1644   }else{
1645     /*
1646     ** The function call to GetEnvironmentVariableA() succeeded
1647     ** -AND- the buffer contains the entire value.
1648     */
1649     return value;
1650   }
1651 }
1652 
1653 /*
1654 ** Implementation of the POSIX opendir() function using the MSVCRT.
1655 */
1656 LPDIR opendir(
1657   const char *dirname
1658 ){
1659   struct _finddata_t data;
1660   LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1661   SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1662 
1663   if( dirp==NULL ) return NULL;
1664   memset(dirp, 0, sizeof(DIR));
1665 
1666   /* TODO: Remove this if Unix-style root paths are not used. */
1667   if( sqlite3_stricmp(dirname, "/")==0 ){
1668     dirname = windirent_getenv("SystemDrive");
1669   }
1670 
1671   memset(&data, 0, sizeof(struct _finddata_t));
1672   _snprintf(data.name, namesize, "%s\\*", dirname);
1673   dirp->d_handle = _findfirst(data.name, &data);
1674 
1675   if( dirp->d_handle==BAD_INTPTR_T ){
1676     closedir(dirp);
1677     return NULL;
1678   }
1679 
1680   /* TODO: Remove this block to allow hidden and/or system files. */
1681   if( is_filtered(data) ){
1682 next:
1683 
1684     memset(&data, 0, sizeof(struct _finddata_t));
1685     if( _findnext(dirp->d_handle, &data)==-1 ){
1686       closedir(dirp);
1687       return NULL;
1688     }
1689 
1690     /* TODO: Remove this block to allow hidden and/or system files. */
1691     if( is_filtered(data) ) goto next;
1692   }
1693 
1694   dirp->d_first.d_attributes = data.attrib;
1695   strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1696   dirp->d_first.d_name[NAME_MAX] = '\0';
1697 
1698   return dirp;
1699 }
1700 
1701 /*
1702 ** Implementation of the POSIX readdir() function using the MSVCRT.
1703 */
1704 LPDIRENT readdir(
1705   LPDIR dirp
1706 ){
1707   struct _finddata_t data;
1708 
1709   if( dirp==NULL ) return NULL;
1710 
1711   if( dirp->d_first.d_ino==0 ){
1712     dirp->d_first.d_ino++;
1713     dirp->d_next.d_ino++;
1714 
1715     return &dirp->d_first;
1716   }
1717 
1718 next:
1719 
1720   memset(&data, 0, sizeof(struct _finddata_t));
1721   if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1722 
1723   /* TODO: Remove this block to allow hidden and/or system files. */
1724   if( is_filtered(data) ) goto next;
1725 
1726   dirp->d_next.d_ino++;
1727   dirp->d_next.d_attributes = data.attrib;
1728   strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1729   dirp->d_next.d_name[NAME_MAX] = '\0';
1730 
1731   return &dirp->d_next;
1732 }
1733 
1734 /*
1735 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1736 */
1737 INT readdir_r(
1738   LPDIR dirp,
1739   LPDIRENT entry,
1740   LPDIRENT *result
1741 ){
1742   struct _finddata_t data;
1743 
1744   if( dirp==NULL ) return EBADF;
1745 
1746   if( dirp->d_first.d_ino==0 ){
1747     dirp->d_first.d_ino++;
1748     dirp->d_next.d_ino++;
1749 
1750     entry->d_ino = dirp->d_first.d_ino;
1751     entry->d_attributes = dirp->d_first.d_attributes;
1752     strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1753     entry->d_name[NAME_MAX] = '\0';
1754 
1755     *result = entry;
1756     return 0;
1757   }
1758 
1759 next:
1760 
1761   memset(&data, 0, sizeof(struct _finddata_t));
1762   if( _findnext(dirp->d_handle, &data)==-1 ){
1763     *result = NULL;
1764     return ENOENT;
1765   }
1766 
1767   /* TODO: Remove this block to allow hidden and/or system files. */
1768   if( is_filtered(data) ) goto next;
1769 
1770   entry->d_ino = (ino_t)-1; /* not available */
1771   entry->d_attributes = data.attrib;
1772   strncpy(entry->d_name, data.name, NAME_MAX);
1773   entry->d_name[NAME_MAX] = '\0';
1774 
1775   *result = entry;
1776   return 0;
1777 }
1778 
1779 /*
1780 ** Implementation of the POSIX closedir() function using the MSVCRT.
1781 */
1782 INT closedir(
1783   LPDIR dirp
1784 ){
1785   INT result = 0;
1786 
1787   if( dirp==NULL ) return EINVAL;
1788 
1789   if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1790     result = _findclose(dirp->d_handle);
1791   }
1792 
1793   sqlite3_free(dirp);
1794   return result;
1795 }
1796 
1797 #endif /* defined(WIN32) && defined(_MSC_VER) */
1798 
1799 /************************* End test_windirent.c ********************/
1800 #define dirent DIRENT
1801 #endif
1802 /************************* Begin ../ext/misc/memtrace.c ******************/
1803 /*
1804 ** 2019-01-21
1805 **
1806 ** The author disclaims copyright to this source code.  In place of
1807 ** a legal notice, here is a blessing:
1808 **
1809 **    May you do good and not evil.
1810 **    May you find forgiveness for yourself and forgive others.
1811 **    May you share freely, never taking more than you give.
1812 **
1813 *************************************************************************
1814 **
1815 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
1816 ** mechanism to add a tracing layer on top of SQLite.  If this extension
1817 ** is registered prior to sqlite3_initialize(), it will cause all memory
1818 ** allocation activities to be logged on standard output, or to some other
1819 ** FILE specified by the initializer.
1820 **
1821 ** This file needs to be compiled into the application that uses it.
1822 **
1823 ** This extension is used to implement the --memtrace option of the
1824 ** command-line shell.
1825 */
1826 #include <assert.h>
1827 #include <string.h>
1828 #include <stdio.h>
1829 
1830 /* The original memory allocation routines */
1831 static sqlite3_mem_methods memtraceBase;
1832 static FILE *memtraceOut;
1833 
1834 /* Methods that trace memory allocations */
1835 static void *memtraceMalloc(int n){
1836   if( memtraceOut ){
1837     fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
1838             memtraceBase.xRoundup(n));
1839   }
1840   return memtraceBase.xMalloc(n);
1841 }
1842 static void memtraceFree(void *p){
1843   if( p==0 ) return;
1844   if( memtraceOut ){
1845     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
1846   }
1847   memtraceBase.xFree(p);
1848 }
1849 static void *memtraceRealloc(void *p, int n){
1850   if( p==0 ) return memtraceMalloc(n);
1851   if( n==0 ){
1852     memtraceFree(p);
1853     return 0;
1854   }
1855   if( memtraceOut ){
1856     fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
1857             memtraceBase.xSize(p), memtraceBase.xRoundup(n));
1858   }
1859   return memtraceBase.xRealloc(p, n);
1860 }
1861 static int memtraceSize(void *p){
1862   return memtraceBase.xSize(p);
1863 }
1864 static int memtraceRoundup(int n){
1865   return memtraceBase.xRoundup(n);
1866 }
1867 static int memtraceInit(void *p){
1868   return memtraceBase.xInit(p);
1869 }
1870 static void memtraceShutdown(void *p){
1871   memtraceBase.xShutdown(p);
1872 }
1873 
1874 /* The substitute memory allocator */
1875 static sqlite3_mem_methods ersaztMethods = {
1876   memtraceMalloc,
1877   memtraceFree,
1878   memtraceRealloc,
1879   memtraceSize,
1880   memtraceRoundup,
1881   memtraceInit,
1882   memtraceShutdown,
1883   0
1884 };
1885 
1886 /* Begin tracing memory allocations to out. */
1887 int sqlite3MemTraceActivate(FILE *out){
1888   int rc = SQLITE_OK;
1889   if( memtraceBase.xMalloc==0 ){
1890     rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
1891     if( rc==SQLITE_OK ){
1892       rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
1893     }
1894   }
1895   memtraceOut = out;
1896   return rc;
1897 }
1898 
1899 /* Deactivate memory tracing */
1900 int sqlite3MemTraceDeactivate(void){
1901   int rc = SQLITE_OK;
1902   if( memtraceBase.xMalloc!=0 ){
1903     rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
1904     if( rc==SQLITE_OK ){
1905       memset(&memtraceBase, 0, sizeof(memtraceBase));
1906     }
1907   }
1908   memtraceOut = 0;
1909   return rc;
1910 }
1911 
1912 /************************* End ../ext/misc/memtrace.c ********************/
1913 /************************* Begin ../ext/misc/pcachetrace.c ******************/
1914 /*
1915 ** 2023-06-21
1916 **
1917 ** The author disclaims copyright to this source code.  In place of
1918 ** a legal notice, here is a blessing:
1919 **
1920 **    May you do good and not evil.
1921 **    May you find forgiveness for yourself and forgive others.
1922 **    May you share freely, never taking more than you give.
1923 **
1924 *************************************************************************
1925 **
1926 ** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
1927 ** mechanism to add a tracing layer on top of pluggable page cache of
1928 ** SQLite.  If this extension is registered prior to sqlite3_initialize(),
1929 ** it will cause all page cache activities to be logged on standard output,
1930 ** or to some other FILE specified by the initializer.
1931 **
1932 ** This file needs to be compiled into the application that uses it.
1933 **
1934 ** This extension is used to implement the --pcachetrace option of the
1935 ** command-line shell.
1936 */
1937 #include <assert.h>
1938 #include <string.h>
1939 #include <stdio.h>
1940 
1941 /* The original page cache routines */
1942 static sqlite3_pcache_methods2 pcacheBase;
1943 static FILE *pcachetraceOut;
1944 
1945 /* Methods that trace pcache activity */
1946 static int pcachetraceInit(void *pArg){
1947   int nRes;
1948   if( pcachetraceOut ){
1949     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
1950   }
1951   nRes = pcacheBase.xInit(pArg);
1952   if( pcachetraceOut ){
1953     fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
1954   }
1955   return nRes;
1956 }
1957 static void pcachetraceShutdown(void *pArg){
1958   if( pcachetraceOut ){
1959     fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
1960   }
1961   pcacheBase.xShutdown(pArg);
1962 }
1963 static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
1964   sqlite3_pcache *pRes;
1965   if( pcachetraceOut ){
1966     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
1967             szPage, szExtra, bPurge);
1968   }
1969   pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
1970   if( pcachetraceOut ){
1971     fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
1972             szPage, szExtra, bPurge, pRes);
1973   }
1974   return pRes;
1975 }
1976 static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
1977   if( pcachetraceOut ){
1978     fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
1979   }
1980   pcacheBase.xCachesize(p, nCachesize);
1981 }
1982 static int pcachetracePagecount(sqlite3_pcache *p){
1983   int nRes;
1984   if( pcachetraceOut ){
1985     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
1986   }
1987   nRes = pcacheBase.xPagecount(p);
1988   if( pcachetraceOut ){
1989     fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
1990   }
1991   return nRes;
1992 }
1993 static sqlite3_pcache_page *pcachetraceFetch(
1994   sqlite3_pcache *p,
1995   unsigned key,
1996   int crFg
1997 ){
1998   sqlite3_pcache_page *pRes;
1999   if( pcachetraceOut ){
2000     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2001   }
2002   pRes = pcacheBase.xFetch(p, key, crFg);
2003   if( pcachetraceOut ){
2004     fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2005             p, key, crFg, pRes);
2006   }
2007   return pRes;
2008 }
2009 static void pcachetraceUnpin(
2010   sqlite3_pcache *p,
2011   sqlite3_pcache_page *pPg,
2012   int bDiscard
2013 ){
2014   if( pcachetraceOut ){
2015     fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2016             p, pPg, bDiscard);
2017   }
2018   pcacheBase.xUnpin(p, pPg, bDiscard);
2019 }
2020 static void pcachetraceRekey(
2021   sqlite3_pcache *p,
2022   sqlite3_pcache_page *pPg,
2023   unsigned oldKey,
2024   unsigned newKey
2025 ){
2026   if( pcachetraceOut ){
2027     fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2028         p, pPg, oldKey, newKey);
2029   }
2030   pcacheBase.xRekey(p, pPg, oldKey, newKey);
2031 }
2032 static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2033   if( pcachetraceOut ){
2034     fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2035   }
2036   pcacheBase.xTruncate(p, n);
2037 }
2038 static void pcachetraceDestroy(sqlite3_pcache *p){
2039   if( pcachetraceOut ){
2040     fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2041   }
2042   pcacheBase.xDestroy(p);
2043 }
2044 static void pcachetraceShrink(sqlite3_pcache *p){
2045   if( pcachetraceOut ){
2046     fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2047   }
2048   pcacheBase.xShrink(p);
2049 }
2050 
2051 /* The substitute pcache methods */
2052 static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2053   0,
2054   0,
2055   pcachetraceInit,
2056   pcachetraceShutdown,
2057   pcachetraceCreate,
2058   pcachetraceCachesize,
2059   pcachetracePagecount,
2060   pcachetraceFetch,
2061   pcachetraceUnpin,
2062   pcachetraceRekey,
2063   pcachetraceTruncate,
2064   pcachetraceDestroy,
2065   pcachetraceShrink
2066 };
2067 
2068 /* Begin tracing memory allocations to out. */
2069 int sqlite3PcacheTraceActivate(FILE *out){
2070   int rc = SQLITE_OK;
2071   if( pcacheBase.xFetch==0 ){
2072     rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2073     if( rc==SQLITE_OK ){
2074       rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2075     }
2076   }
2077   pcachetraceOut = out;
2078   return rc;
2079 }
2080 
2081 /* Deactivate memory tracing */
2082 int sqlite3PcacheTraceDeactivate(void){
2083   int rc = SQLITE_OK;
2084   if( pcacheBase.xFetch!=0 ){
2085     rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2086     if( rc==SQLITE_OK ){
2087       memset(&pcacheBase, 0, sizeof(pcacheBase));
2088     }
2089   }
2090   pcachetraceOut = 0;
2091   return rc;
2092 }
2093 
2094 /************************* End ../ext/misc/pcachetrace.c ********************/
2095 /************************* Begin ../ext/misc/shathree.c ******************/
2096 /*
2097 ** 2017-03-08
2098 **
2099 ** The author disclaims copyright to this source code.  In place of
2100 ** a legal notice, here is a blessing:
2101 **
2102 **    May you do good and not evil.
2103 **    May you find forgiveness for yourself and forgive others.
2104 **    May you share freely, never taking more than you give.
2105 **
2106 ******************************************************************************
2107 **
2108 ** This SQLite extension implements functions that compute SHA3 hashes
2109 ** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2110 ** Two SQL functions are implemented:
2111 **
2112 **     sha3(X,SIZE)
2113 **     sha3_query(Y,SIZE)
2114 **
2115 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2116 ** X is NULL.
2117 **
2118 ** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2119 ** and returns a hash of their results.
2120 **
2121 ** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2122 ** is used.  If SIZE is included it must be one of the integers 224, 256,
2123 ** 384, or 512, to determine SHA3 hash variant that is computed.
2124 */
2125 /* #include "sqlite3ext.h" */
2126 SQLITE_EXTENSION_INIT1
2127 #include <assert.h>
2128 #include <string.h>
2129 #include <stdarg.h>
2130 
2131 #ifndef SQLITE_AMALGAMATION
2132 /* typedef sqlite3_uint64 u64; */
2133 #endif /* SQLITE_AMALGAMATION */
2134 
2135 /******************************************************************************
2136 ** The Hash Engine
2137 */
2138 /*
2139 ** Macros to determine whether the machine is big or little endian,
2140 ** and whether or not that determination is run-time or compile-time.
2141 **
2142 ** For best performance, an attempt is made to guess at the byte-order
2143 ** using C-preprocessor macros.  If that is unsuccessful, or if
2144 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2145 ** at run-time.
2146 */
2147 #ifndef SHA3_BYTEORDER
2148 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2149      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2150      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2151      defined(__arm__)
2152 #   define SHA3_BYTEORDER    1234
2153 # elif defined(sparc)    || defined(__ppc__)
2154 #   define SHA3_BYTEORDER    4321
2155 # else
2156 #   define SHA3_BYTEORDER 0
2157 # endif
2158 #endif
2159 
2160 
2161 /*
2162 ** State structure for a SHA3 hash in progress
2163 */
2164 typedef struct SHA3Context SHA3Context;
2165 struct SHA3Context {
2166   union {
2167     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2168     unsigned char x[1600];    /* ... or 1600 bytes */
2169   } u;
2170   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2171   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2172   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2173 };
2174 
2175 /*
2176 ** A single step of the Keccak mixing function for a 1600-bit state
2177 */
2178 static void KeccakF1600Step(SHA3Context *p){
2179   int i;
2180   u64 b0, b1, b2, b3, b4;
2181   u64 c0, c1, c2, c3, c4;
2182   u64 d0, d1, d2, d3, d4;
2183   static const u64 RC[] = {
2184     0x0000000000000001ULL,  0x0000000000008082ULL,
2185     0x800000000000808aULL,  0x8000000080008000ULL,
2186     0x000000000000808bULL,  0x0000000080000001ULL,
2187     0x8000000080008081ULL,  0x8000000000008009ULL,
2188     0x000000000000008aULL,  0x0000000000000088ULL,
2189     0x0000000080008009ULL,  0x000000008000000aULL,
2190     0x000000008000808bULL,  0x800000000000008bULL,
2191     0x8000000000008089ULL,  0x8000000000008003ULL,
2192     0x8000000000008002ULL,  0x8000000000000080ULL,
2193     0x000000000000800aULL,  0x800000008000000aULL,
2194     0x8000000080008081ULL,  0x8000000000008080ULL,
2195     0x0000000080000001ULL,  0x8000000080008008ULL
2196   };
2197 # define a00 (p->u.s[0])
2198 # define a01 (p->u.s[1])
2199 # define a02 (p->u.s[2])
2200 # define a03 (p->u.s[3])
2201 # define a04 (p->u.s[4])
2202 # define a10 (p->u.s[5])
2203 # define a11 (p->u.s[6])
2204 # define a12 (p->u.s[7])
2205 # define a13 (p->u.s[8])
2206 # define a14 (p->u.s[9])
2207 # define a20 (p->u.s[10])
2208 # define a21 (p->u.s[11])
2209 # define a22 (p->u.s[12])
2210 # define a23 (p->u.s[13])
2211 # define a24 (p->u.s[14])
2212 # define a30 (p->u.s[15])
2213 # define a31 (p->u.s[16])
2214 # define a32 (p->u.s[17])
2215 # define a33 (p->u.s[18])
2216 # define a34 (p->u.s[19])
2217 # define a40 (p->u.s[20])
2218 # define a41 (p->u.s[21])
2219 # define a42 (p->u.s[22])
2220 # define a43 (p->u.s[23])
2221 # define a44 (p->u.s[24])
2222 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2223 
2224   for(i=0; i<24; i+=4){
2225     c0 = a00^a10^a20^a30^a40;
2226     c1 = a01^a11^a21^a31^a41;
2227     c2 = a02^a12^a22^a32^a42;
2228     c3 = a03^a13^a23^a33^a43;
2229     c4 = a04^a14^a24^a34^a44;
2230     d0 = c4^ROL64(c1, 1);
2231     d1 = c0^ROL64(c2, 1);
2232     d2 = c1^ROL64(c3, 1);
2233     d3 = c2^ROL64(c4, 1);
2234     d4 = c3^ROL64(c0, 1);
2235 
2236     b0 = (a00^d0);
2237     b1 = ROL64((a11^d1), 44);
2238     b2 = ROL64((a22^d2), 43);
2239     b3 = ROL64((a33^d3), 21);
2240     b4 = ROL64((a44^d4), 14);
2241     a00 =   b0 ^((~b1)&  b2 );
2242     a00 ^= RC[i];
2243     a11 =   b1 ^((~b2)&  b3 );
2244     a22 =   b2 ^((~b3)&  b4 );
2245     a33 =   b3 ^((~b4)&  b0 );
2246     a44 =   b4 ^((~b0)&  b1 );
2247 
2248     b2 = ROL64((a20^d0), 3);
2249     b3 = ROL64((a31^d1), 45);
2250     b4 = ROL64((a42^d2), 61);
2251     b0 = ROL64((a03^d3), 28);
2252     b1 = ROL64((a14^d4), 20);
2253     a20 =   b0 ^((~b1)&  b2 );
2254     a31 =   b1 ^((~b2)&  b3 );
2255     a42 =   b2 ^((~b3)&  b4 );
2256     a03 =   b3 ^((~b4)&  b0 );
2257     a14 =   b4 ^((~b0)&  b1 );
2258 
2259     b4 = ROL64((a40^d0), 18);
2260     b0 = ROL64((a01^d1), 1);
2261     b1 = ROL64((a12^d2), 6);
2262     b2 = ROL64((a23^d3), 25);
2263     b3 = ROL64((a34^d4), 8);
2264     a40 =   b0 ^((~b1)&  b2 );
2265     a01 =   b1 ^((~b2)&  b3 );
2266     a12 =   b2 ^((~b3)&  b4 );
2267     a23 =   b3 ^((~b4)&  b0 );
2268     a34 =   b4 ^((~b0)&  b1 );
2269 
2270     b1 = ROL64((a10^d0), 36);
2271     b2 = ROL64((a21^d1), 10);
2272     b3 = ROL64((a32^d2), 15);
2273     b4 = ROL64((a43^d3), 56);
2274     b0 = ROL64((a04^d4), 27);
2275     a10 =   b0 ^((~b1)&  b2 );
2276     a21 =   b1 ^((~b2)&  b3 );
2277     a32 =   b2 ^((~b3)&  b4 );
2278     a43 =   b3 ^((~b4)&  b0 );
2279     a04 =   b4 ^((~b0)&  b1 );
2280 
2281     b3 = ROL64((a30^d0), 41);
2282     b4 = ROL64((a41^d1), 2);
2283     b0 = ROL64((a02^d2), 62);
2284     b1 = ROL64((a13^d3), 55);
2285     b2 = ROL64((a24^d4), 39);
2286     a30 =   b0 ^((~b1)&  b2 );
2287     a41 =   b1 ^((~b2)&  b3 );
2288     a02 =   b2 ^((~b3)&  b4 );
2289     a13 =   b3 ^((~b4)&  b0 );
2290     a24 =   b4 ^((~b0)&  b1 );
2291 
2292     c0 = a00^a20^a40^a10^a30;
2293     c1 = a11^a31^a01^a21^a41;
2294     c2 = a22^a42^a12^a32^a02;
2295     c3 = a33^a03^a23^a43^a13;
2296     c4 = a44^a14^a34^a04^a24;
2297     d0 = c4^ROL64(c1, 1);
2298     d1 = c0^ROL64(c2, 1);
2299     d2 = c1^ROL64(c3, 1);
2300     d3 = c2^ROL64(c4, 1);
2301     d4 = c3^ROL64(c0, 1);
2302 
2303     b0 = (a00^d0);
2304     b1 = ROL64((a31^d1), 44);
2305     b2 = ROL64((a12^d2), 43);
2306     b3 = ROL64((a43^d3), 21);
2307     b4 = ROL64((a24^d4), 14);
2308     a00 =   b0 ^((~b1)&  b2 );
2309     a00 ^= RC[i+1];
2310     a31 =   b1 ^((~b2)&  b3 );
2311     a12 =   b2 ^((~b3)&  b4 );
2312     a43 =   b3 ^((~b4)&  b0 );
2313     a24 =   b4 ^((~b0)&  b1 );
2314 
2315     b2 = ROL64((a40^d0), 3);
2316     b3 = ROL64((a21^d1), 45);
2317     b4 = ROL64((a02^d2), 61);
2318     b0 = ROL64((a33^d3), 28);
2319     b1 = ROL64((a14^d4), 20);
2320     a40 =   b0 ^((~b1)&  b2 );
2321     a21 =   b1 ^((~b2)&  b3 );
2322     a02 =   b2 ^((~b3)&  b4 );
2323     a33 =   b3 ^((~b4)&  b0 );
2324     a14 =   b4 ^((~b0)&  b1 );
2325 
2326     b4 = ROL64((a30^d0), 18);
2327     b0 = ROL64((a11^d1), 1);
2328     b1 = ROL64((a42^d2), 6);
2329     b2 = ROL64((a23^d3), 25);
2330     b3 = ROL64((a04^d4), 8);
2331     a30 =   b0 ^((~b1)&  b2 );
2332     a11 =   b1 ^((~b2)&  b3 );
2333     a42 =   b2 ^((~b3)&  b4 );
2334     a23 =   b3 ^((~b4)&  b0 );
2335     a04 =   b4 ^((~b0)&  b1 );
2336 
2337     b1 = ROL64((a20^d0), 36);
2338     b2 = ROL64((a01^d1), 10);
2339     b3 = ROL64((a32^d2), 15);
2340     b4 = ROL64((a13^d3), 56);
2341     b0 = ROL64((a44^d4), 27);
2342     a20 =   b0 ^((~b1)&  b2 );
2343     a01 =   b1 ^((~b2)&  b3 );
2344     a32 =   b2 ^((~b3)&  b4 );
2345     a13 =   b3 ^((~b4)&  b0 );
2346     a44 =   b4 ^((~b0)&  b1 );
2347 
2348     b3 = ROL64((a10^d0), 41);
2349     b4 = ROL64((a41^d1), 2);
2350     b0 = ROL64((a22^d2), 62);
2351     b1 = ROL64((a03^d3), 55);
2352     b2 = ROL64((a34^d4), 39);
2353     a10 =   b0 ^((~b1)&  b2 );
2354     a41 =   b1 ^((~b2)&  b3 );
2355     a22 =   b2 ^((~b3)&  b4 );
2356     a03 =   b3 ^((~b4)&  b0 );
2357     a34 =   b4 ^((~b0)&  b1 );
2358 
2359     c0 = a00^a40^a30^a20^a10;
2360     c1 = a31^a21^a11^a01^a41;
2361     c2 = a12^a02^a42^a32^a22;
2362     c3 = a43^a33^a23^a13^a03;
2363     c4 = a24^a14^a04^a44^a34;
2364     d0 = c4^ROL64(c1, 1);
2365     d1 = c0^ROL64(c2, 1);
2366     d2 = c1^ROL64(c3, 1);
2367     d3 = c2^ROL64(c4, 1);
2368     d4 = c3^ROL64(c0, 1);
2369 
2370     b0 = (a00^d0);
2371     b1 = ROL64((a21^d1), 44);
2372     b2 = ROL64((a42^d2), 43);
2373     b3 = ROL64((a13^d3), 21);
2374     b4 = ROL64((a34^d4), 14);
2375     a00 =   b0 ^((~b1)&  b2 );
2376     a00 ^= RC[i+2];
2377     a21 =   b1 ^((~b2)&  b3 );
2378     a42 =   b2 ^((~b3)&  b4 );
2379     a13 =   b3 ^((~b4)&  b0 );
2380     a34 =   b4 ^((~b0)&  b1 );
2381 
2382     b2 = ROL64((a30^d0), 3);
2383     b3 = ROL64((a01^d1), 45);
2384     b4 = ROL64((a22^d2), 61);
2385     b0 = ROL64((a43^d3), 28);
2386     b1 = ROL64((a14^d4), 20);
2387     a30 =   b0 ^((~b1)&  b2 );
2388     a01 =   b1 ^((~b2)&  b3 );
2389     a22 =   b2 ^((~b3)&  b4 );
2390     a43 =   b3 ^((~b4)&  b0 );
2391     a14 =   b4 ^((~b0)&  b1 );
2392 
2393     b4 = ROL64((a10^d0), 18);
2394     b0 = ROL64((a31^d1), 1);
2395     b1 = ROL64((a02^d2), 6);
2396     b2 = ROL64((a23^d3), 25);
2397     b3 = ROL64((a44^d4), 8);
2398     a10 =   b0 ^((~b1)&  b2 );
2399     a31 =   b1 ^((~b2)&  b3 );
2400     a02 =   b2 ^((~b3)&  b4 );
2401     a23 =   b3 ^((~b4)&  b0 );
2402     a44 =   b4 ^((~b0)&  b1 );
2403 
2404     b1 = ROL64((a40^d0), 36);
2405     b2 = ROL64((a11^d1), 10);
2406     b3 = ROL64((a32^d2), 15);
2407     b4 = ROL64((a03^d3), 56);
2408     b0 = ROL64((a24^d4), 27);
2409     a40 =   b0 ^((~b1)&  b2 );
2410     a11 =   b1 ^((~b2)&  b3 );
2411     a32 =   b2 ^((~b3)&  b4 );
2412     a03 =   b3 ^((~b4)&  b0 );
2413     a24 =   b4 ^((~b0)&  b1 );
2414 
2415     b3 = ROL64((a20^d0), 41);
2416     b4 = ROL64((a41^d1), 2);
2417     b0 = ROL64((a12^d2), 62);
2418     b1 = ROL64((a33^d3), 55);
2419     b2 = ROL64((a04^d4), 39);
2420     a20 =   b0 ^((~b1)&  b2 );
2421     a41 =   b1 ^((~b2)&  b3 );
2422     a12 =   b2 ^((~b3)&  b4 );
2423     a33 =   b3 ^((~b4)&  b0 );
2424     a04 =   b4 ^((~b0)&  b1 );
2425 
2426     c0 = a00^a30^a10^a40^a20;
2427     c1 = a21^a01^a31^a11^a41;
2428     c2 = a42^a22^a02^a32^a12;
2429     c3 = a13^a43^a23^a03^a33;
2430     c4 = a34^a14^a44^a24^a04;
2431     d0 = c4^ROL64(c1, 1);
2432     d1 = c0^ROL64(c2, 1);
2433     d2 = c1^ROL64(c3, 1);
2434     d3 = c2^ROL64(c4, 1);
2435     d4 = c3^ROL64(c0, 1);
2436 
2437     b0 = (a00^d0);
2438     b1 = ROL64((a01^d1), 44);
2439     b2 = ROL64((a02^d2), 43);
2440     b3 = ROL64((a03^d3), 21);
2441     b4 = ROL64((a04^d4), 14);
2442     a00 =   b0 ^((~b1)&  b2 );
2443     a00 ^= RC[i+3];
2444     a01 =   b1 ^((~b2)&  b3 );
2445     a02 =   b2 ^((~b3)&  b4 );
2446     a03 =   b3 ^((~b4)&  b0 );
2447     a04 =   b4 ^((~b0)&  b1 );
2448 
2449     b2 = ROL64((a10^d0), 3);
2450     b3 = ROL64((a11^d1), 45);
2451     b4 = ROL64((a12^d2), 61);
2452     b0 = ROL64((a13^d3), 28);
2453     b1 = ROL64((a14^d4), 20);
2454     a10 =   b0 ^((~b1)&  b2 );
2455     a11 =   b1 ^((~b2)&  b3 );
2456     a12 =   b2 ^((~b3)&  b4 );
2457     a13 =   b3 ^((~b4)&  b0 );
2458     a14 =   b4 ^((~b0)&  b1 );
2459 
2460     b4 = ROL64((a20^d0), 18);
2461     b0 = ROL64((a21^d1), 1);
2462     b1 = ROL64((a22^d2), 6);
2463     b2 = ROL64((a23^d3), 25);
2464     b3 = ROL64((a24^d4), 8);
2465     a20 =   b0 ^((~b1)&  b2 );
2466     a21 =   b1 ^((~b2)&  b3 );
2467     a22 =   b2 ^((~b3)&  b4 );
2468     a23 =   b3 ^((~b4)&  b0 );
2469     a24 =   b4 ^((~b0)&  b1 );
2470 
2471     b1 = ROL64((a30^d0), 36);
2472     b2 = ROL64((a31^d1), 10);
2473     b3 = ROL64((a32^d2), 15);
2474     b4 = ROL64((a33^d3), 56);
2475     b0 = ROL64((a34^d4), 27);
2476     a30 =   b0 ^((~b1)&  b2 );
2477     a31 =   b1 ^((~b2)&  b3 );
2478     a32 =   b2 ^((~b3)&  b4 );
2479     a33 =   b3 ^((~b4)&  b0 );
2480     a34 =   b4 ^((~b0)&  b1 );
2481 
2482     b3 = ROL64((a40^d0), 41);
2483     b4 = ROL64((a41^d1), 2);
2484     b0 = ROL64((a42^d2), 62);
2485     b1 = ROL64((a43^d3), 55);
2486     b2 = ROL64((a44^d4), 39);
2487     a40 =   b0 ^((~b1)&  b2 );
2488     a41 =   b1 ^((~b2)&  b3 );
2489     a42 =   b2 ^((~b3)&  b4 );
2490     a43 =   b3 ^((~b4)&  b0 );
2491     a44 =   b4 ^((~b0)&  b1 );
2492   }
2493 }
2494 
2495 /*
2496 ** Initialize a new hash.  iSize determines the size of the hash
2497 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
2498 ** can be zero to use the default hash size of 256 bits.
2499 */
2500 static void SHA3Init(SHA3Context *p, int iSize){
2501   memset(p, 0, sizeof(*p));
2502   if( iSize>=128 && iSize<=512 ){
2503     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
2504   }else{
2505     p->nRate = (1600 - 2*256)/8;
2506   }
2507 #if SHA3_BYTEORDER==1234
2508   /* Known to be little-endian at compile-time. No-op */
2509 #elif SHA3_BYTEORDER==4321
2510   p->ixMask = 7;  /* Big-endian */
2511 #else
2512   {
2513     static unsigned int one = 1;
2514     if( 1==*(unsigned char*)&one ){
2515       /* Little endian.  No byte swapping. */
2516       p->ixMask = 0;
2517     }else{
2518       /* Big endian.  Byte swap. */
2519       p->ixMask = 7;
2520     }
2521   }
2522 #endif
2523 }
2524 
2525 /*
2526 ** Make consecutive calls to the SHA3Update function to add new content
2527 ** to the hash
2528 */
2529 static void SHA3Update(
2530   SHA3Context *p,
2531   const unsigned char *aData,
2532   unsigned int nData
2533 ){
2534   unsigned int i = 0;
2535   if( aData==0 ) return;
2536 #if SHA3_BYTEORDER==1234
2537   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
2538     for(; i+7<nData; i+=8){
2539       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
2540       p->nLoaded += 8;
2541       if( p->nLoaded>=p->nRate ){
2542         KeccakF1600Step(p);
2543         p->nLoaded = 0;
2544       }
2545     }
2546   }
2547 #endif
2548   for(; i<nData; i++){
2549 #if SHA3_BYTEORDER==1234
2550     p->u.x[p->nLoaded] ^= aData[i];
2551 #elif SHA3_BYTEORDER==4321
2552     p->u.x[p->nLoaded^0x07] ^= aData[i];
2553 #else
2554     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
2555 #endif
2556     p->nLoaded++;
2557     if( p->nLoaded==p->nRate ){
2558       KeccakF1600Step(p);
2559       p->nLoaded = 0;
2560     }
2561   }
2562 }
2563 
2564 /*
2565 ** After all content has been added, invoke SHA3Final() to compute
2566 ** the final hash.  The function returns a pointer to the binary
2567 ** hash value.
2568 */
2569 static unsigned char *SHA3Final(SHA3Context *p){
2570   unsigned int i;
2571   if( p->nLoaded==p->nRate-1 ){
2572     const unsigned char c1 = 0x86;
2573     SHA3Update(p, &c1, 1);
2574   }else{
2575     const unsigned char c2 = 0x06;
2576     const unsigned char c3 = 0x80;
2577     SHA3Update(p, &c2, 1);
2578     p->nLoaded = p->nRate - 1;
2579     SHA3Update(p, &c3, 1);
2580   }
2581   for(i=0; i<p->nRate; i++){
2582     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
2583   }
2584   return &p->u.x[p->nRate];
2585 }
2586 /* End of the hashing logic
2587 *****************************************************************************/
2588 
2589 /*
2590 ** Implementation of the sha3(X,SIZE) function.
2591 **
2592 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
2593 ** size is 256.  If X is a BLOB, it is hashed as is.
2594 ** For all other non-NULL types of input, X is converted into a UTF-8 string
2595 ** and the string is hashed without the trailing 0x00 terminator.  The hash
2596 ** of a NULL value is NULL.
2597 */
2598 static void sha3Func(
2599   sqlite3_context *context,
2600   int argc,
2601   sqlite3_value **argv
2602 ){
2603   SHA3Context cx;
2604   int eType = sqlite3_value_type(argv[0]);
2605   int nByte = sqlite3_value_bytes(argv[0]);
2606   int iSize;
2607   if( argc==1 ){
2608     iSize = 256;
2609   }else{
2610     iSize = sqlite3_value_int(argv[1]);
2611     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2612       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2613                                     "384 512", -1);
2614       return;
2615     }
2616   }
2617   if( eType==SQLITE_NULL ) return;
2618   SHA3Init(&cx, iSize);
2619   if( eType==SQLITE_BLOB ){
2620     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
2621   }else{
2622     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
2623   }
2624   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2625 }
2626 
2627 /* Compute a string using sqlite3_vsnprintf() with a maximum length
2628 ** of 50 bytes and add it to the hash.
2629 */
2630 static void sha3_step_vformat(
2631   SHA3Context *p,                 /* Add content to this context */
2632   const char *zFormat,
2633   ...
2634 ){
2635   va_list ap;
2636   int n;
2637   char zBuf[50];
2638   va_start(ap, zFormat);
2639   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
2640   va_end(ap);
2641   n = (int)strlen(zBuf);
2642   SHA3Update(p, (unsigned char*)zBuf, n);
2643 }
2644 
2645 /*
2646 ** Implementation of the sha3_query(SQL,SIZE) function.
2647 **
2648 ** This function compiles and runs the SQL statement(s) given in the
2649 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
2650 ** size is 256.
2651 **
2652 ** The format of the byte stream that is hashed is summarized as follows:
2653 **
2654 **       S<n>:<sql>
2655 **       R
2656 **       N
2657 **       I<int>
2658 **       F<ieee-float>
2659 **       B<size>:<bytes>
2660 **       T<size>:<text>
2661 **
2662 ** <sql> is the original SQL text for each statement run and <n> is
2663 ** the size of that text.  The SQL text is UTF-8.  A single R character
2664 ** occurs before the start of each row.  N means a NULL value.
2665 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
2666 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
2667 ** B means blobs of <size> bytes.  T means text rendered as <size>
2668 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
2669 ** text integers.
2670 **
2671 ** For each SQL statement in the X input, there is one S segment.  Each
2672 ** S segment is followed by zero or more R segments, one for each row in the
2673 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
2674 ** one for each column in the result set.  Segments are concatentated directly
2675 ** with no delimiters of any kind.
2676 */
2677 static void sha3QueryFunc(
2678   sqlite3_context *context,
2679   int argc,
2680   sqlite3_value **argv
2681 ){
2682   sqlite3 *db = sqlite3_context_db_handle(context);
2683   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
2684   sqlite3_stmt *pStmt = 0;
2685   int nCol;                   /* Number of columns in the result set */
2686   int i;                      /* Loop counter */
2687   int rc;
2688   int n;
2689   const char *z;
2690   SHA3Context cx;
2691   int iSize;
2692 
2693   if( argc==1 ){
2694     iSize = 256;
2695   }else{
2696     iSize = sqlite3_value_int(argv[1]);
2697     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
2698       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
2699                                     "384 512", -1);
2700       return;
2701     }
2702   }
2703   if( zSql==0 ) return;
2704   SHA3Init(&cx, iSize);
2705   while( zSql[0] ){
2706     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
2707     if( rc ){
2708       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
2709                                    zSql, sqlite3_errmsg(db));
2710       sqlite3_finalize(pStmt);
2711       sqlite3_result_error(context, zMsg, -1);
2712       sqlite3_free(zMsg);
2713       return;
2714     }
2715     if( !sqlite3_stmt_readonly(pStmt) ){
2716       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
2717       sqlite3_finalize(pStmt);
2718       sqlite3_result_error(context, zMsg, -1);
2719       sqlite3_free(zMsg);
2720       return;
2721     }
2722     nCol = sqlite3_column_count(pStmt);
2723     z = sqlite3_sql(pStmt);
2724     if( z ){
2725       n = (int)strlen(z);
2726       sha3_step_vformat(&cx,"S%d:",n);
2727       SHA3Update(&cx,(unsigned char*)z,n);
2728     }
2729 
2730     /* Compute a hash over the result of the query */
2731     while( SQLITE_ROW==sqlite3_step(pStmt) ){
2732       SHA3Update(&cx,(const unsigned char*)"R",1);
2733       for(i=0; i<nCol; i++){
2734         switch( sqlite3_column_type(pStmt,i) ){
2735           case SQLITE_NULL: {
2736             SHA3Update(&cx, (const unsigned char*)"N",1);
2737             break;
2738           }
2739           case SQLITE_INTEGER: {
2740             sqlite3_uint64 u;
2741             int j;
2742             unsigned char x[9];
2743             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
2744             memcpy(&u, &v, 8);
2745             for(j=8; j>=1; j--){
2746               x[j] = u & 0xff;
2747               u >>= 8;
2748             }
2749             x[0] = 'I';
2750             SHA3Update(&cx, x, 9);
2751             break;
2752           }
2753           case SQLITE_FLOAT: {
2754             sqlite3_uint64 u;
2755             int j;
2756             unsigned char x[9];
2757             double r = sqlite3_column_double(pStmt,i);
2758             memcpy(&u, &r, 8);
2759             for(j=8; j>=1; j--){
2760               x[j] = u & 0xff;
2761               u >>= 8;
2762             }
2763             x[0] = 'F';
2764             SHA3Update(&cx,x,9);
2765             break;
2766           }
2767           case SQLITE_TEXT: {
2768             int n2 = sqlite3_column_bytes(pStmt, i);
2769             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
2770             sha3_step_vformat(&cx,"T%d:",n2);
2771             SHA3Update(&cx, z2, n2);
2772             break;
2773           }
2774           case SQLITE_BLOB: {
2775             int n2 = sqlite3_column_bytes(pStmt, i);
2776             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
2777             sha3_step_vformat(&cx,"B%d:",n2);
2778             SHA3Update(&cx, z2, n2);
2779             break;
2780           }
2781         }
2782       }
2783     }
2784     sqlite3_finalize(pStmt);
2785   }
2786   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
2787 }
2788 
2789 
2790 #ifdef _WIN32
2791 
2792 #endif
2793 int sqlite3_shathree_init(
2794   sqlite3 *db,
2795   char **pzErrMsg,
2796   const sqlite3_api_routines *pApi
2797 ){
2798   int rc = SQLITE_OK;
2799   SQLITE_EXTENSION_INIT2(pApi);
2800   (void)pzErrMsg;  /* Unused parameter */
2801   rc = sqlite3_create_function(db, "sha3", 1,
2802                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2803                       0, sha3Func, 0, 0);
2804   if( rc==SQLITE_OK ){
2805     rc = sqlite3_create_function(db, "sha3", 2,
2806                       SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
2807                       0, sha3Func, 0, 0);
2808   }
2809   if( rc==SQLITE_OK ){
2810     rc = sqlite3_create_function(db, "sha3_query", 1,
2811                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2812                       0, sha3QueryFunc, 0, 0);
2813   }
2814   if( rc==SQLITE_OK ){
2815     rc = sqlite3_create_function(db, "sha3_query", 2,
2816                       SQLITE_UTF8 | SQLITE_DIRECTONLY,
2817                       0, sha3QueryFunc, 0, 0);
2818   }
2819   return rc;
2820 }
2821 
2822 /************************* End ../ext/misc/shathree.c ********************/
2823 /************************* Begin ../ext/misc/uint.c ******************/
2824 /*
2825 ** 2020-04-14
2826 **
2827 ** The author disclaims copyright to this source code.  In place of
2828 ** a legal notice, here is a blessing:
2829 **
2830 **    May you do good and not evil.
2831 **    May you find forgiveness for yourself and forgive others.
2832 **    May you share freely, never taking more than you give.
2833 **
2834 ******************************************************************************
2835 **
2836 ** This SQLite extension implements the UINT collating sequence.
2837 **
2838 ** UINT works like BINARY for text, except that embedded strings
2839 ** of digits compare in numeric order.
2840 **
2841 **     *   Leading zeros are handled properly, in the sense that
2842 **         they do not mess of the maginitude comparison of embedded
2843 **         strings of digits.  "x00123y" is equal to "x123y".
2844 **
2845 **     *   Only unsigned integers are recognized.  Plus and minus
2846 **         signs are ignored.  Decimal points and exponential notation
2847 **         are ignored.
2848 **
2849 **     *   Embedded integers can be of arbitrary length.  Comparison
2850 **         is *not* limited integers that can be expressed as a
2851 **         64-bit machine integer.
2852 */
2853 /* #include "sqlite3ext.h" */
2854 SQLITE_EXTENSION_INIT1
2855 #include <assert.h>
2856 #include <string.h>
2857 #include <ctype.h>
2858 
2859 /*
2860 ** Compare text in lexicographic order, except strings of digits
2861 ** compare in numeric order.
2862 */
2863 static int uintCollFunc(
2864   void *notUsed,
2865   int nKey1, const void *pKey1,
2866   int nKey2, const void *pKey2
2867 ){
2868   const unsigned char *zA = (const unsigned char*)pKey1;
2869   const unsigned char *zB = (const unsigned char*)pKey2;
2870   int i=0, j=0, x;
2871   (void)notUsed;
2872   while( i<nKey1 && j<nKey2 ){
2873     x = zA[i] - zB[j];
2874     if( isdigit(zA[i]) ){
2875       int k;
2876       if( !isdigit(zB[j]) ) return x;
2877       while( i<nKey1 && zA[i]=='0' ){ i++; }
2878       while( j<nKey2 && zB[j]=='0' ){ j++; }
2879       k = 0;
2880       while( i+k<nKey1 && isdigit(zA[i+k])
2881              && j+k<nKey2 && isdigit(zB[j+k]) ){
2882         k++;
2883       }
2884       if( i+k<nKey1 && isdigit(zA[i+k]) ){
2885         return +1;
2886       }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
2887         return -1;
2888       }else{
2889         x = memcmp(zA+i, zB+j, k);
2890         if( x ) return x;
2891         i += k;
2892         j += k;
2893       }
2894     }else if( x ){
2895       return x;
2896     }else{
2897       i++;
2898       j++;
2899     }
2900   }
2901   return (nKey1 - i) - (nKey2 - j);
2902 }
2903 
2904 #ifdef _WIN32
2905 
2906 #endif
2907 int sqlite3_uint_init(
2908   sqlite3 *db,
2909   char **pzErrMsg,
2910   const sqlite3_api_routines *pApi
2911 ){
2912   SQLITE_EXTENSION_INIT2(pApi);
2913   (void)pzErrMsg;  /* Unused parameter */
2914   return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
2915 }
2916 
2917 /************************* End ../ext/misc/uint.c ********************/
2918 /************************* Begin ../ext/misc/decimal.c ******************/
2919 /*
2920 ** 2020-06-22
2921 **
2922 ** The author disclaims copyright to this source code.  In place of
2923 ** a legal notice, here is a blessing:
2924 **
2925 **    May you do good and not evil.
2926 **    May you find forgiveness for yourself and forgive others.
2927 **    May you share freely, never taking more than you give.
2928 **
2929 ******************************************************************************
2930 **
2931 ** Routines to implement arbitrary-precision decimal math.
2932 **
2933 ** The focus here is on simplicity and correctness, not performance.
2934 */
2935 /* #include "sqlite3ext.h" */
2936 SQLITE_EXTENSION_INIT1
2937 #include <assert.h>
2938 #include <string.h>
2939 #include <ctype.h>
2940 #include <stdlib.h>
2941 
2942 /* Mark a function parameter as unused, to suppress nuisance compiler
2943 ** warnings. */
2944 #ifndef UNUSED_PARAMETER
2945 # define UNUSED_PARAMETER(X)  (void)(X)
2946 #endif
2947 
2948 
2949 /* A decimal object */
2950 typedef struct Decimal Decimal;
2951 struct Decimal {
2952   char sign;        /* 0 for positive, 1 for negative */
2953   char oom;         /* True if an OOM is encountered */
2954   char isNull;      /* True if holds a NULL rather than a number */
2955   char isInit;      /* True upon initialization */
2956   int nDigit;       /* Total number of digits */
2957   int nFrac;        /* Number of digits to the right of the decimal point */
2958   signed char *a;   /* Array of digits.  Most significant first. */
2959 };
2960 
2961 /*
2962 ** Release memory held by a Decimal, but do not free the object itself.
2963 */
2964 static void decimal_clear(Decimal *p){
2965   sqlite3_free(p->a);
2966 }
2967 
2968 /*
2969 ** Destroy a Decimal object
2970 */
2971 static void decimal_free(Decimal *p){
2972   if( p ){
2973     decimal_clear(p);
2974     sqlite3_free(p);
2975   }
2976 }
2977 
2978 /*
2979 ** Allocate a new Decimal object initialized to the text in zIn[].
2980 ** Return NULL if any kind of error occurs.
2981 */
2982 static Decimal *decimalNewFromText(const char *zIn, int n){
2983   Decimal *p = 0;
2984   int i;
2985   int iExp = 0;
2986 
2987   p = sqlite3_malloc( sizeof(*p) );
2988   if( p==0 ) goto new_from_text_failed;
2989   p->sign = 0;
2990   p->oom = 0;
2991   p->isInit = 1;
2992   p->isNull = 0;
2993   p->nDigit = 0;
2994   p->nFrac = 0;
2995   p->a = sqlite3_malloc64( n+1 );
2996   if( p->a==0 ) goto new_from_text_failed;
2997   for(i=0; isspace(zIn[i]); i++){}
2998   if( zIn[i]=='-' ){
2999     p->sign = 1;
3000     i++;
3001   }else if( zIn[i]=='+' ){
3002     i++;
3003   }
3004   while( i<n && zIn[i]=='0' ) i++;
3005   while( i<n ){
3006     char c = zIn[i];
3007     if( c>='0' && c<='9' ){
3008       p->a[p->nDigit++] = c - '0';
3009     }else if( c=='.' ){
3010       p->nFrac = p->nDigit + 1;
3011     }else if( c=='e' || c=='E' ){
3012       int j = i+1;
3013       int neg = 0;
3014       if( j>=n ) break;
3015       if( zIn[j]=='-' ){
3016         neg = 1;
3017         j++;
3018       }else if( zIn[j]=='+' ){
3019         j++;
3020       }
3021       while( j<n && iExp<1000000 ){
3022         if( zIn[j]>='0' && zIn[j]<='9' ){
3023           iExp = iExp*10 + zIn[j] - '0';
3024         }
3025         j++;
3026       }
3027       if( neg ) iExp = -iExp;
3028       break;
3029     }
3030     i++;
3031   }
3032   if( p->nFrac ){
3033     p->nFrac = p->nDigit - (p->nFrac - 1);
3034   }
3035   if( iExp>0 ){
3036     if( p->nFrac>0 ){
3037       if( iExp<=p->nFrac ){
3038         p->nFrac -= iExp;
3039         iExp = 0;
3040       }else{
3041         iExp -= p->nFrac;
3042         p->nFrac = 0;
3043       }
3044     }
3045     if( iExp>0 ){
3046       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3047       if( p->a==0 ) goto new_from_text_failed;
3048       memset(p->a+p->nDigit, 0, iExp);
3049       p->nDigit += iExp;
3050     }
3051   }else if( iExp<0 ){
3052     int nExtra;
3053     iExp = -iExp;
3054     nExtra = p->nDigit - p->nFrac - 1;
3055     if( nExtra ){
3056       if( nExtra>=iExp ){
3057         p->nFrac += iExp;
3058         iExp  = 0;
3059       }else{
3060         iExp -= nExtra;
3061         p->nFrac = p->nDigit - 1;
3062       }
3063     }
3064     if( iExp>0 ){
3065       p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3066       if( p->a==0 ) goto new_from_text_failed;
3067       memmove(p->a+iExp, p->a, p->nDigit);
3068       memset(p->a, 0, iExp);
3069       p->nDigit += iExp;
3070       p->nFrac += iExp;
3071     }
3072   }
3073   return p;
3074 
3075 new_from_text_failed:
3076   if( p ){
3077     if( p->a ) sqlite3_free(p->a);
3078     sqlite3_free(p);
3079   }
3080   return 0;
3081 }
3082 
3083 /* Forward reference */
3084 static Decimal *decimalFromDouble(double);
3085 
3086 /*
3087 ** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3088 ** to the new object, or NULL if there is an error.  If the pCtx argument
3089 ** is not NULL, then errors are reported on it as well.
3090 **
3091 ** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3092 ** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3093 ** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3094 ** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3095 ** then NULL is returned.
3096 */
3097 static Decimal *decimal_new(
3098   sqlite3_context *pCtx,       /* Report error here, if not null */
3099   sqlite3_value *pIn,          /* Construct the decimal object from this */
3100   int bTextOnly                /* Always interpret pIn as text if true */
3101 ){
3102   Decimal *p = 0;
3103   int eType = sqlite3_value_type(pIn);
3104   if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3105     eType = SQLITE_TEXT;
3106   }
3107   switch( eType ){
3108     case SQLITE_TEXT:
3109     case SQLITE_INTEGER: {
3110       const char *zIn = (const char*)sqlite3_value_text(pIn);
3111       int n = sqlite3_value_bytes(pIn);
3112       p = decimalNewFromText(zIn, n);
3113       if( p==0 ) goto new_failed;
3114       break;
3115     }
3116 
3117     case SQLITE_FLOAT: {
3118       p = decimalFromDouble(sqlite3_value_double(pIn));
3119       break;
3120     }
3121 
3122     case SQLITE_BLOB: {
3123       const unsigned char *x;
3124       unsigned int i;
3125       sqlite3_uint64 v = 0;
3126       double r;
3127 
3128       if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3129       x = sqlite3_value_blob(pIn);
3130       for(i=0; i<sizeof(r); i++){
3131         v = (v<<8) | x[i];
3132       }
3133       memcpy(&r, &v, sizeof(r));
3134       p = decimalFromDouble(r);
3135       break;
3136     }
3137 
3138     case SQLITE_NULL: {
3139       break;
3140     }
3141   }
3142   return p;
3143 
3144 new_failed:
3145   if( pCtx ) sqlite3_result_error_nomem(pCtx);
3146   sqlite3_free(p);
3147   return 0;
3148 }
3149 
3150 /*
3151 ** Make the given Decimal the result.
3152 */
3153 static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3154   char *z;
3155   int i, j;
3156   int n;
3157   if( p==0 || p->oom ){
3158     sqlite3_result_error_nomem(pCtx);
3159     return;
3160   }
3161   if( p->isNull ){
3162     sqlite3_result_null(pCtx);
3163     return;
3164   }
3165   z = sqlite3_malloc( p->nDigit+4 );
3166   if( z==0 ){
3167     sqlite3_result_error_nomem(pCtx);
3168     return;
3169   }
3170   i = 0;
3171   if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3172     p->sign = 0;
3173   }
3174   if( p->sign ){
3175     z[0] = '-';
3176     i = 1;
3177   }
3178   n = p->nDigit - p->nFrac;
3179   if( n<=0 ){
3180     z[i++] = '0';
3181   }
3182   j = 0;
3183   while( n>1 && p->a[j]==0 ){
3184     j++;
3185     n--;
3186   }
3187   while( n>0  ){
3188     z[i++] = p->a[j] + '0';
3189     j++;
3190     n--;
3191   }
3192   if( p->nFrac ){
3193     z[i++] = '.';
3194     do{
3195       z[i++] = p->a[j] + '0';
3196       j++;
3197     }while( j<p->nDigit );
3198   }
3199   z[i] = 0;
3200   sqlite3_result_text(pCtx, z, i, sqlite3_free);
3201 }
3202 
3203 /*
3204 ** Make the given Decimal the result in an format similar to  '%+#e'.
3205 ** In other words, show exponential notation with leading and trailing
3206 ** zeros omitted.
3207 */
3208 static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3209   char *z;       /* The output buffer */
3210   int i;         /* Loop counter */
3211   int nZero;     /* Number of leading zeros */
3212   int nDigit;    /* Number of digits not counting trailing zeros */
3213   int nFrac;     /* Digits to the right of the decimal point */
3214   int exp;       /* Exponent value */
3215   signed char zero;     /* Zero value */
3216   signed char *a;       /* Array of digits */
3217 
3218   if( p==0 || p->oom ){
3219     sqlite3_result_error_nomem(pCtx);
3220     return;
3221   }
3222   if( p->isNull ){
3223     sqlite3_result_null(pCtx);
3224     return;
3225   }
3226   for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
3227   for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
3228   nFrac = p->nFrac + (nDigit - p->nDigit);
3229   nDigit -= nZero;
3230   z = sqlite3_malloc( nDigit+20 );
3231   if( z==0 ){
3232     sqlite3_result_error_nomem(pCtx);
3233     return;
3234   }
3235   if( nDigit==0 ){
3236     zero = 0;
3237     a = &zero;
3238     nDigit = 1;
3239     nFrac = 0;
3240   }else{
3241     a = &p->a[nZero];
3242   }
3243   if( p->sign && nDigit>0 ){
3244     z[0] = '-';
3245   }else{
3246     z[0] = '+';
3247   }
3248   z[1] = a[0]+'0';
3249   z[2] = '.';
3250   if( nDigit==1 ){
3251     z[3] = '0';
3252     i = 4;
3253   }else{
3254     for(i=1; i<nDigit; i++){
3255       z[2+i] = a[i]+'0';
3256     }
3257     i = nDigit+2;
3258   }
3259   exp = nDigit - nFrac - 1;
3260   sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
3261   sqlite3_result_text(pCtx, z, -1, sqlite3_free);
3262 }
3263 
3264 /*
3265 ** Compare to Decimal objects.  Return negative, 0, or positive if the
3266 ** first object is less than, equal to, or greater than the second.
3267 **
3268 ** Preconditions for this routine:
3269 **
3270 **    pA!=0
3271 **    pA->isNull==0
3272 **    pB!=0
3273 **    pB->isNull==0
3274 */
3275 static int decimal_cmp(const Decimal *pA, const Decimal *pB){
3276   int nASig, nBSig, rc, n;
3277   if( pA->sign!=pB->sign ){
3278     return pA->sign ? -1 : +1;
3279   }
3280   if( pA->sign ){
3281     const Decimal *pTemp = pA;
3282     pA = pB;
3283     pB = pTemp;
3284   }
3285   nASig = pA->nDigit - pA->nFrac;
3286   nBSig = pB->nDigit - pB->nFrac;
3287   if( nASig!=nBSig ){
3288     return nASig - nBSig;
3289   }
3290   n = pA->nDigit;
3291   if( n>pB->nDigit ) n = pB->nDigit;
3292   rc = memcmp(pA->a, pB->a, n);
3293   if( rc==0 ){
3294     rc = pA->nDigit - pB->nDigit;
3295   }
3296   return rc;
3297 }
3298 
3299 /*
3300 ** SQL Function:   decimal_cmp(X, Y)
3301 **
3302 ** Return negative, zero, or positive if X is less then, equal to, or
3303 ** greater than Y.
3304 */
3305 static void decimalCmpFunc(
3306   sqlite3_context *context,
3307   int argc,
3308   sqlite3_value **argv
3309 ){
3310   Decimal *pA = 0, *pB = 0;
3311   int rc;
3312 
3313   UNUSED_PARAMETER(argc);
3314   pA = decimal_new(context, argv[0], 1);
3315   if( pA==0 || pA->isNull ) goto cmp_done;
3316   pB = decimal_new(context, argv[1], 1);
3317   if( pB==0 || pB->isNull ) goto cmp_done;
3318   rc = decimal_cmp(pA, pB);
3319   if( rc<0 ) rc = -1;
3320   else if( rc>0 ) rc = +1;
3321   sqlite3_result_int(context, rc);
3322 cmp_done:
3323   decimal_free(pA);
3324   decimal_free(pB);
3325 }
3326 
3327 /*
3328 ** Expand the Decimal so that it has a least nDigit digits and nFrac
3329 ** digits to the right of the decimal point.
3330 */
3331 static void decimal_expand(Decimal *p, int nDigit, int nFrac){
3332   int nAddSig;
3333   int nAddFrac;
3334   if( p==0 ) return;
3335   nAddFrac = nFrac - p->nFrac;
3336   nAddSig = (nDigit - p->nDigit) - nAddFrac;
3337   if( nAddFrac==0 && nAddSig==0 ) return;
3338   p->a = sqlite3_realloc64(p->a, nDigit+1);
3339   if( p->a==0 ){
3340     p->oom = 1;
3341     return;
3342   }
3343   if( nAddSig ){
3344     memmove(p->a+nAddSig, p->a, p->nDigit);
3345     memset(p->a, 0, nAddSig);
3346     p->nDigit += nAddSig;
3347   }
3348   if( nAddFrac ){
3349     memset(p->a+p->nDigit, 0, nAddFrac);
3350     p->nDigit += nAddFrac;
3351     p->nFrac += nAddFrac;
3352   }
3353 }
3354 
3355 /*
3356 ** Add the value pB into pA.   A := A + B.
3357 **
3358 ** Both pA and pB might become denormalized by this routine.
3359 */
3360 static void decimal_add(Decimal *pA, Decimal *pB){
3361   int nSig, nFrac, nDigit;
3362   int i, rc;
3363   if( pA==0 ){
3364     return;
3365   }
3366   if( pA->oom || pB==0 || pB->oom ){
3367     pA->oom = 1;
3368     return;
3369   }
3370   if( pA->isNull || pB->isNull ){
3371     pA->isNull = 1;
3372     return;
3373   }
3374   nSig = pA->nDigit - pA->nFrac;
3375   if( nSig && pA->a[0]==0 ) nSig--;
3376   if( nSig<pB->nDigit-pB->nFrac ){
3377     nSig = pB->nDigit - pB->nFrac;
3378   }
3379   nFrac = pA->nFrac;
3380   if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
3381   nDigit = nSig + nFrac + 1;
3382   decimal_expand(pA, nDigit, nFrac);
3383   decimal_expand(pB, nDigit, nFrac);
3384   if( pA->oom || pB->oom ){
3385     pA->oom = 1;
3386   }else{
3387     if( pA->sign==pB->sign ){
3388       int carry = 0;
3389       for(i=nDigit-1; i>=0; i--){
3390         int x = pA->a[i] + pB->a[i] + carry;
3391         if( x>=10 ){
3392           carry = 1;
3393           pA->a[i] = x - 10;
3394         }else{
3395           carry = 0;
3396           pA->a[i] = x;
3397         }
3398       }
3399     }else{
3400       signed char *aA, *aB;
3401       int borrow = 0;
3402       rc = memcmp(pA->a, pB->a, nDigit);
3403       if( rc<0 ){
3404         aA = pB->a;
3405         aB = pA->a;
3406         pA->sign = !pA->sign;
3407       }else{
3408         aA = pA->a;
3409         aB = pB->a;
3410       }
3411       for(i=nDigit-1; i>=0; i--){
3412         int x = aA[i] - aB[i] - borrow;
3413         if( x<0 ){
3414           pA->a[i] = x+10;
3415           borrow = 1;
3416         }else{
3417           pA->a[i] = x;
3418           borrow = 0;
3419         }
3420       }
3421     }
3422   }
3423 }
3424 
3425 /*
3426 ** Multiply A by B.   A := A * B
3427 **
3428 ** All significant digits after the decimal point are retained.
3429 ** Trailing zeros after the decimal point are omitted as long as
3430 ** the number of digits after the decimal point is no less than
3431 ** either the number of digits in either input.
3432 */
3433 static void decimalMul(Decimal *pA, Decimal *pB){
3434   signed char *acc = 0;
3435   int i, j, k;
3436   int minFrac;
3437 
3438   if( pA==0 || pA->oom || pA->isNull
3439    || pB==0 || pB->oom || pB->isNull
3440   ){
3441     goto mul_end;
3442   }
3443   acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
3444   if( acc==0 ){
3445     pA->oom = 1;
3446     goto mul_end;
3447   }
3448   memset(acc, 0, pA->nDigit + pB->nDigit + 2);
3449   minFrac = pA->nFrac;
3450   if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
3451   for(i=pA->nDigit-1; i>=0; i--){
3452     signed char f = pA->a[i];
3453     int carry = 0, x;
3454     for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
3455       x = acc[k] + f*pB->a[j] + carry;
3456       acc[k] = x%10;
3457       carry = x/10;
3458     }
3459     x = acc[k] + carry;
3460     acc[k] = x%10;
3461     acc[k-1] += x/10;
3462   }
3463   sqlite3_free(pA->a);
3464   pA->a = acc;
3465   acc = 0;
3466   pA->nDigit += pB->nDigit + 2;
3467   pA->nFrac += pB->nFrac;
3468   pA->sign ^= pB->sign;
3469   while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
3470     pA->nFrac--;
3471     pA->nDigit--;
3472   }
3473 
3474 mul_end:
3475   sqlite3_free(acc);
3476 }
3477 
3478 /*
3479 ** Create a new Decimal object that contains an integer power of 2.
3480 */
3481 static Decimal *decimalPow2(int N){
3482   Decimal *pA = 0;      /* The result to be returned */
3483   Decimal *pX = 0;      /* Multiplier */
3484   if( N<-20000 || N>20000 ) goto pow2_fault;
3485   pA = decimalNewFromText("1.0", 3);
3486   if( pA==0 || pA->oom ) goto pow2_fault;
3487   if( N==0 ) return pA;
3488   if( N>0 ){
3489     pX = decimalNewFromText("2.0", 3);
3490   }else{
3491     N = -N;
3492     pX = decimalNewFromText("0.5", 3);
3493   }
3494   if( pX==0 || pX->oom ) goto pow2_fault;
3495   while( 1 /* Exit by break */ ){
3496     if( N & 1 ){
3497       decimalMul(pA, pX);
3498       if( pA->oom ) goto pow2_fault;
3499     }
3500     N >>= 1;
3501     if( N==0 ) break;
3502     decimalMul(pX, pX);
3503   }
3504   decimal_free(pX);
3505   return pA;
3506 
3507 pow2_fault:
3508   decimal_free(pA);
3509   decimal_free(pX);
3510   return 0;
3511 }
3512 
3513 /*
3514 ** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
3515 */
3516 static Decimal *decimalFromDouble(double r){
3517   sqlite3_int64 m, a;
3518   int e;
3519   int isNeg;
3520   Decimal *pA;
3521   Decimal *pX;
3522   char zNum[100];
3523   if( r<0.0 ){
3524     isNeg = 1;
3525     r = -r;
3526   }else{
3527     isNeg = 0;
3528   }
3529   memcpy(&a,&r,sizeof(a));
3530   if( a==0 ){
3531     e = 0;
3532     m = 0;
3533   }else{
3534     e = a>>52;
3535     m = a & ((((sqlite3_int64)1)<<52)-1);
3536     if( e==0 ){
3537       m <<= 1;
3538     }else{
3539       m |= ((sqlite3_int64)1)<<52;
3540     }
3541     while( e<1075 && m>0 && (m&1)==0 ){
3542       m >>= 1;
3543       e++;
3544     }
3545     if( isNeg ) m = -m;
3546     e = e - 1075;
3547     if( e>971 ){
3548       return 0;  /* A NaN or an Infinity */
3549     }
3550   }
3551 
3552   /* At this point m is the integer significand and e is the exponent */
3553   sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
3554   pA = decimalNewFromText(zNum, (int)strlen(zNum));
3555   pX = decimalPow2(e);
3556   decimalMul(pA, pX);
3557   decimal_free(pX);
3558   return pA;
3559 }
3560 
3561 /*
3562 ** SQL Function:   decimal(X)
3563 ** OR:             decimal_exp(X)
3564 **
3565 ** Convert input X into decimal and then back into text.
3566 **
3567 ** If X is originally a float, then a full decimal expansion of that floating
3568 ** point value is done.  Or if X is an 8-byte blob, it is interpreted
3569 ** as a float and similarly expanded.
3570 **
3571 ** The decimal_exp(X) function returns the result in exponential notation.
3572 ** decimal(X) returns a complete decimal, without the e+NNN at the end.
3573 */
3574 static void decimalFunc(
3575   sqlite3_context *context,
3576   int argc,
3577   sqlite3_value **argv
3578 ){
3579   Decimal *p =  decimal_new(context, argv[0], 0);
3580   UNUSED_PARAMETER(argc);
3581   if( p ){
3582     if( sqlite3_user_data(context)!=0 ){
3583       decimal_result_sci(context, p);
3584     }else{
3585       decimal_result(context, p);
3586     }
3587     decimal_free(p);
3588   }
3589 }
3590 
3591 /*
3592 ** Compare text in decimal order.
3593 */
3594 static int decimalCollFunc(
3595   void *notUsed,
3596   int nKey1, const void *pKey1,
3597   int nKey2, const void *pKey2
3598 ){
3599   const unsigned char *zA = (const unsigned char*)pKey1;
3600   const unsigned char *zB = (const unsigned char*)pKey2;
3601   Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
3602   Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
3603   int rc;
3604   UNUSED_PARAMETER(notUsed);
3605   if( pA==0 || pB==0 ){
3606     rc = 0;
3607   }else{
3608     rc = decimal_cmp(pA, pB);
3609   }
3610   decimal_free(pA);
3611   decimal_free(pB);
3612   return rc;
3613 }
3614 
3615 
3616 /*
3617 ** SQL Function:   decimal_add(X, Y)
3618 **                 decimal_sub(X, Y)
3619 **
3620 ** Return the sum or difference of X and Y.
3621 */
3622 static void decimalAddFunc(
3623   sqlite3_context *context,
3624   int argc,
3625   sqlite3_value **argv
3626 ){
3627   Decimal *pA = decimal_new(context, argv[0], 1);
3628   Decimal *pB = decimal_new(context, argv[1], 1);
3629   UNUSED_PARAMETER(argc);
3630   decimal_add(pA, pB);
3631   decimal_result(context, pA);
3632   decimal_free(pA);
3633   decimal_free(pB);
3634 }
3635 static void decimalSubFunc(
3636   sqlite3_context *context,
3637   int argc,
3638   sqlite3_value **argv
3639 ){
3640   Decimal *pA = decimal_new(context, argv[0], 1);
3641   Decimal *pB = decimal_new(context, argv[1], 1);
3642   UNUSED_PARAMETER(argc);
3643   if( pB ){
3644     pB->sign = !pB->sign;
3645     decimal_add(pA, pB);
3646     decimal_result(context, pA);
3647   }
3648   decimal_free(pA);
3649   decimal_free(pB);
3650 }
3651 
3652 /* Aggregate funcion:   decimal_sum(X)
3653 **
3654 ** Works like sum() except that it uses decimal arithmetic for unlimited
3655 ** precision.
3656 */
3657 static void decimalSumStep(
3658   sqlite3_context *context,
3659   int argc,
3660   sqlite3_value **argv
3661 ){
3662   Decimal *p;
3663   Decimal *pArg;
3664   UNUSED_PARAMETER(argc);
3665   p = sqlite3_aggregate_context(context, sizeof(*p));
3666   if( p==0 ) return;
3667   if( !p->isInit ){
3668     p->isInit = 1;
3669     p->a = sqlite3_malloc(2);
3670     if( p->a==0 ){
3671       p->oom = 1;
3672     }else{
3673       p->a[0] = 0;
3674     }
3675     p->nDigit = 1;
3676     p->nFrac = 0;
3677   }
3678   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
3679   pArg = decimal_new(context, argv[0], 1);
3680   decimal_add(p, pArg);
3681   decimal_free(pArg);
3682 }
3683 static void decimalSumInverse(
3684   sqlite3_context *context,
3685   int argc,
3686   sqlite3_value **argv
3687 ){
3688   Decimal *p;
3689   Decimal *pArg;
3690   UNUSED_PARAMETER(argc);
3691   p = sqlite3_aggregate_context(context, sizeof(*p));
3692   if( p==0 ) return;
3693   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
3694   pArg = decimal_new(context, argv[0], 1);
3695   if( pArg ) pArg->sign = !pArg->sign;
3696   decimal_add(p, pArg);
3697   decimal_free(pArg);
3698 }
3699 static void decimalSumValue(sqlite3_context *context){
3700   Decimal *p = sqlite3_aggregate_context(context, 0);
3701   if( p==0 ) return;
3702   decimal_result(context, p);
3703 }
3704 static void decimalSumFinalize(sqlite3_context *context){
3705   Decimal *p = sqlite3_aggregate_context(context, 0);
3706   if( p==0 ) return;
3707   decimal_result(context, p);
3708   decimal_clear(p);
3709 }
3710 
3711 /*
3712 ** SQL Function:   decimal_mul(X, Y)
3713 **
3714 ** Return the product of X and Y.
3715 */
3716 static void decimalMulFunc(
3717   sqlite3_context *context,
3718   int argc,
3719   sqlite3_value **argv
3720 ){
3721   Decimal *pA = decimal_new(context, argv[0], 1);
3722   Decimal *pB = decimal_new(context, argv[1], 1);
3723   UNUSED_PARAMETER(argc);
3724   if( pA==0 || pA->oom || pA->isNull
3725    || pB==0 || pB->oom || pB->isNull
3726   ){
3727     goto mul_end;
3728   }
3729   decimalMul(pA, pB);
3730   if( pA->oom ){
3731     goto mul_end;
3732   }
3733   decimal_result(context, pA);
3734 
3735 mul_end:
3736   decimal_free(pA);
3737   decimal_free(pB);
3738 }
3739 
3740 /*
3741 ** SQL Function:   decimal_pow2(N)
3742 **
3743 ** Return the N-th power of 2.  N must be an integer.
3744 */
3745 static void decimalPow2Func(
3746   sqlite3_context *context,
3747   int argc,
3748   sqlite3_value **argv
3749 ){
3750   UNUSED_PARAMETER(argc);
3751   if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
3752     Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
3753     decimal_result_sci(context, pA);
3754     decimal_free(pA);
3755   }
3756 }
3757 
3758 #ifdef _WIN32
3759 
3760 #endif
3761 int sqlite3_decimal_init(
3762   sqlite3 *db,
3763   char **pzErrMsg,
3764   const sqlite3_api_routines *pApi
3765 ){
3766   int rc = SQLITE_OK;
3767   static const struct {
3768     const char *zFuncName;
3769     int nArg;
3770     int iArg;
3771     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
3772   } aFunc[] = {
3773     { "decimal",       1, 0,  decimalFunc        },
3774     { "decimal_exp",   1, 1,  decimalFunc        },
3775     { "decimal_cmp",   2, 0,  decimalCmpFunc     },
3776     { "decimal_add",   2, 0,  decimalAddFunc     },
3777     { "decimal_sub",   2, 0,  decimalSubFunc     },
3778     { "decimal_mul",   2, 0,  decimalMulFunc     },
3779     { "decimal_pow2",  1, 0,  decimalPow2Func    },
3780   };
3781   unsigned int i;
3782   (void)pzErrMsg;  /* Unused parameter */
3783 
3784   SQLITE_EXTENSION_INIT2(pApi);
3785 
3786   for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
3787     rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
3788                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
3789                    aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
3790   }
3791   if( rc==SQLITE_OK ){
3792     rc = sqlite3_create_window_function(db, "decimal_sum", 1,
3793                    SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
3794                    decimalSumStep, decimalSumFinalize,
3795                    decimalSumValue, decimalSumInverse, 0);
3796   }
3797   if( rc==SQLITE_OK ){
3798     rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
3799                                   0, decimalCollFunc);
3800   }
3801   return rc;
3802 }
3803 
3804 /************************* End ../ext/misc/decimal.c ********************/
3805 #undef sqlite3_base_init
3806 #define sqlite3_base_init sqlite3_base64_init
3807 /************************* Begin ../ext/misc/base64.c ******************/
3808 /*
3809 ** 2022-11-18
3810 **
3811 ** The author disclaims copyright to this source code.  In place of
3812 ** a legal notice, here is a blessing:
3813 **
3814 **    May you do good and not evil.
3815 **    May you find forgiveness for yourself and forgive others.
3816 **    May you share freely, never taking more than you give.
3817 **
3818 *************************************************************************
3819 **
3820 ** This is a SQLite extension for converting in either direction
3821 ** between a (binary) blob and base64 text. Base64 can transit a
3822 ** sane USASCII channel unmolested. It also plays nicely in CSV or
3823 ** written as TCL brace-enclosed literals or SQL string literals,
3824 ** and can be used unmodified in XML-like documents.
3825 **
3826 ** This is an independent implementation of conversions specified in
3827 ** RFC 4648, done on the above date by the author (Larry Brasfield)
3828 ** who thereby has the right to put this into the public domain.
3829 **
3830 ** The conversions meet RFC 4648 requirements, provided that this
3831 ** C source specifies that line-feeds are included in the encoded
3832 ** data to limit visible line lengths to 72 characters and to
3833 ** terminate any encoded blob having non-zero length.
3834 **
3835 ** Length limitations are not imposed except that the runtime
3836 ** SQLite string or blob length limits are respected. Otherwise,
3837 ** any length binary sequence can be represented and recovered.
3838 ** Generated base64 sequences, with their line-feeds included,
3839 ** can be concatenated; the result converted back to binary will
3840 ** be the concatenation of the represented binary sequences.
3841 **
3842 ** This SQLite3 extension creates a function, base64(x), which
3843 ** either: converts text x containing base64 to a returned blob;
3844 ** or converts a blob x to returned text containing base64. An
3845 ** error will be thrown for other input argument types.
3846 **
3847 ** This code relies on UTF-8 encoding only with respect to the
3848 ** meaning of the first 128 (7-bit) codes matching that of USASCII.
3849 ** It will fail miserably if somehow made to try to convert EBCDIC.
3850 ** Because it is table-driven, it could be enhanced to handle that,
3851 ** but the world and SQLite have moved on from that anachronism.
3852 **
3853 ** To build the extension:
3854 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
3855 ** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
3856 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
3857 ** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
3858 ** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
3859 */
3860 
3861 #include <assert.h>
3862 
3863 /* #include "sqlite3ext.h" */
3864 
3865 #ifndef deliberate_fall_through
3866 /* Quiet some compilers about some of our intentional code. */
3867 # if GCC_VERSION>=7000000
3868 #  define deliberate_fall_through __attribute__((fallthrough));
3869 # else
3870 #  define deliberate_fall_through
3871 # endif
3872 #endif
3873 
3874 SQLITE_EXTENSION_INIT1;
3875 
3876 #define PC 0x80 /* pad character */
3877 #define WS 0x81 /* whitespace */
3878 #define ND 0x82 /* Not above or digit-value */
3879 #define PAD_CHAR '='
3880 
3881 #ifndef U8_TYPEDEF
3882 /* typedef unsigned char u8; */
3883 #define U8_TYPEDEF
3884 #endif
3885 
3886 /* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
3887 static const u8 b64DigitValues[128] = {
3888   /*                             HT LF VT  FF CR       */
3889     ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
3890   /*                                                US */
3891     ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
3892   /*sp                                  +            / */
3893     WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
3894   /* 0  1            5            9            =       */
3895     52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
3896   /*    A                                            O */
3897     ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
3898   /* P                               Z                 */
3899     15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
3900   /*    a                                            o */
3901     ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
3902   /* p                               z                 */
3903     41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
3904 };
3905 
3906 static const char b64Numerals[64+1]
3907 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3908 
3909 #define BX_DV_PROTO(c) \
3910   ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
3911 #define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
3912 #define IS_BX_WS(bdp) ((bdp)==WS)
3913 #define IS_BX_PAD(bdp) ((bdp)==PC)
3914 #define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
3915 /* Width of base64 lines. Should be an integer multiple of 4. */
3916 #define B64_DARK_MAX 72
3917 
3918 /* Encode a byte buffer into base64 text with linefeeds appended to limit
3919 ** encoded group lengths to B64_DARK_MAX or to terminate the last group.
3920 */
3921 static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
3922   int nCol = 0;
3923   while( nbIn >= 3 ){
3924     /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
3925     pOut[0] = BX_NUMERAL(pIn[0]>>2);
3926     pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
3927     pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
3928     pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
3929     pOut += 4;
3930     nbIn -= 3;
3931     pIn += 3;
3932     if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
3933       *pOut++ = '\n';
3934       nCol = 0;
3935     }
3936   }
3937   if( nbIn > 0 ){
3938     signed char nco = nbIn+1;
3939     int nbe;
3940     unsigned long qv = *pIn++;
3941     for( nbe=1; nbe<3; ++nbe ){
3942       qv <<= 8;
3943       if( nbe<nbIn ) qv |= *pIn++;
3944     }
3945     for( nbe=3; nbe>=0; --nbe ){
3946       char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
3947       qv >>= 6;
3948       pOut[nbe] = ce;
3949     }
3950     pOut += 4;
3951     *pOut++ = '\n';
3952   }
3953   *pOut = 0;
3954   return pOut;
3955 }
3956 
3957 /* Skip over text which is not base64 numeral(s). */
3958 static char * skipNonB64( char *s, int nc ){
3959   char c;
3960   while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
3961   return s;
3962 }
3963 
3964 /* Decode base64 text into a byte buffer. */
3965 static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
3966   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
3967   while( ncIn>0 && *pIn!=PAD_CHAR ){
3968     static signed char nboi[] = { 0, 0, 1, 2, 3 };
3969     char *pUse = skipNonB64(pIn, ncIn);
3970     unsigned long qv = 0L;
3971     int nti, nbo, nac;
3972     ncIn -= (pUse - pIn);
3973     pIn = pUse;
3974     nti = (ncIn>4)? 4 : ncIn;
3975     ncIn -= nti;
3976     nbo = nboi[nti];
3977     if( nbo==0 ) break;
3978     for( nac=0; nac<4; ++nac ){
3979       char c = (nac<nti)? *pIn++ : b64Numerals[0];
3980       u8 bdp = BX_DV_PROTO(c);
3981       switch( bdp ){
3982       case ND:
3983         /*  Treat dark non-digits as pad, but they terminate decode too. */
3984         ncIn = 0;
3985         deliberate_fall_through;
3986       case WS:
3987         /* Treat whitespace as pad and terminate this group.*/
3988         nti = nac;
3989         deliberate_fall_through;
3990       case PC:
3991         bdp = 0;
3992         --nbo;
3993         deliberate_fall_through;
3994       default: /* bdp is the digit value. */
3995         qv = qv<<6 | bdp;
3996         break;
3997       }
3998     }
3999     switch( nbo ){
4000     case 3:
4001       pOut[2] = (qv) & 0xff;
4002     case 2:
4003       pOut[1] = (qv>>8) & 0xff;
4004     case 1:
4005       pOut[0] = (qv>>16) & 0xff;
4006     }
4007     pOut += nbo;
4008   }
4009   return pOut;
4010 }
4011 
4012 /* This function does the work for the SQLite base64(x) UDF. */
4013 static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
4014   int nb, nc, nv = sqlite3_value_bytes(av[0]);
4015   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4016                             SQLITE_LIMIT_LENGTH, -1);
4017   char *cBuf;
4018   u8 *bBuf;
4019   assert(na==1);
4020   switch( sqlite3_value_type(av[0]) ){
4021   case SQLITE_BLOB:
4022     nb = nv;
4023     nc = 4*(nv+2/3); /* quads needed */
4024     nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
4025     if( nvMax < nc ){
4026       sqlite3_result_error(context, "blob expanded to base64 too big", -1);
4027       return;
4028     }
4029     bBuf = (u8*)sqlite3_value_blob(av[0]);
4030     if( !bBuf ){
4031       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4032         goto memFail;
4033       }
4034       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4035       break;
4036     }
4037     cBuf = sqlite3_malloc(nc);
4038     if( !cBuf ) goto memFail;
4039     nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
4040     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4041     break;
4042   case SQLITE_TEXT:
4043     nc = nv;
4044     nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
4045     if( nvMax < nb ){
4046       sqlite3_result_error(context, "blob from base64 may be too big", -1);
4047       return;
4048     }else if( nb<1 ){
4049       nb = 1;
4050     }
4051     cBuf = (char *)sqlite3_value_text(av[0]);
4052     if( !cBuf ){
4053       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4054         goto memFail;
4055       }
4056       sqlite3_result_zeroblob(context, 0);
4057       break;
4058     }
4059     bBuf = sqlite3_malloc(nb);
4060     if( !bBuf ) goto memFail;
4061     nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
4062     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4063     break;
4064   default:
4065     sqlite3_result_error(context, "base64 accepts only blob or text", -1);
4066     return;
4067   }
4068   return;
4069  memFail:
4070   sqlite3_result_error(context, "base64 OOM", -1);
4071 }
4072 
4073 /*
4074 ** Establish linkage to running SQLite library.
4075 */
4076 #ifndef SQLITE_SHELL_EXTFUNCS
4077 #ifdef _WIN32
4078 
4079 #endif
4080 int sqlite3_base_init
4081 #else
4082 static int sqlite3_base64_init
4083 #endif
4084 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4085   SQLITE_EXTENSION_INIT2(pApi);
4086   (void)pzErr;
4087   return sqlite3_create_function
4088     (db, "base64", 1,
4089      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4090      0, base64, 0, 0);
4091 }
4092 
4093 /*
4094 ** Define some macros to allow this extension to be built into the shell
4095 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4096 ** allows shell.c, as distributed, to have this extension built in.
4097 */
4098 #define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
4099 #define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4100 
4101 /************************* End ../ext/misc/base64.c ********************/
4102 #undef sqlite3_base_init
4103 #define sqlite3_base_init sqlite3_base85_init
4104 #define OMIT_BASE85_CHECKER
4105 /************************* Begin ../ext/misc/base85.c ******************/
4106 /*
4107 ** 2022-11-16
4108 **
4109 ** The author disclaims copyright to this source code.  In place of
4110 ** a legal notice, here is a blessing:
4111 **
4112 **    May you do good and not evil.
4113 **    May you find forgiveness for yourself and forgive others.
4114 **    May you share freely, never taking more than you give.
4115 **
4116 *************************************************************************
4117 **
4118 ** This is a utility for converting binary to base85 or vice-versa.
4119 ** It can be built as a standalone program or an SQLite3 extension.
4120 **
4121 ** Much like base64 representations, base85 can be sent through a
4122 ** sane USASCII channel unmolested. It also plays nicely in CSV or
4123 ** written as TCL brace-enclosed literals or SQL string literals.
4124 ** It is not suited for unmodified use in XML-like documents.
4125 **
4126 ** The encoding used resembles Ascii85, but was devised by the author
4127 ** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
4128 ** variant sources existed, in the 1984 timeframe on a VAX mainframe.
4129 ** Further, this is an independent implementation of a base85 system.
4130 ** Hence, the author has rightfully put this into the public domain.
4131 **
4132 ** Base85 numerals are taken from the set of 7-bit USASCII codes,
4133 ** excluding control characters and Space ! " ' ( ) { | } ~ Del
4134 ** in code order representing digit values 0 to 84 (base 10.)
4135 **
4136 ** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4137 ** are represented as 5-digit base85 numbers with MS to LS digit
4138 ** order. Groups of 1-3 bytes are represented with 2-4 digits,
4139 ** still big-endian but 8-24 bit values. (Using big-endian yields
4140 ** the simplest transition to byte groups smaller than 4 bytes.
4141 ** These byte groups can also be considered base-256 numbers.)
4142 ** Groups of 0 bytes are represented with 0 digits and vice-versa.
4143 ** No pad characters are used; Encoded base85 numeral sequence
4144 ** (aka "group") length maps 1-to-1 to the decoded binary length.
4145 **
4146 ** Any character not in the base85 numeral set delimits groups.
4147 ** When base85 is streamed or stored in containers of indefinite
4148 ** size, newline is used to separate it into sub-sequences of no
4149 ** more than 80 digits so that fgets() can be used to read it.
4150 **
4151 ** Length limitations are not imposed except that the runtime
4152 ** SQLite string or blob length limits are respected. Otherwise,
4153 ** any length binary sequence can be represented and recovered.
4154 ** Base85 sequences can be concatenated by separating them with
4155 ** a non-base85 character; the conversion to binary will then
4156 ** be the concatenation of the represented binary sequences.
4157 
4158 ** The standalone program either converts base85 on stdin to create
4159 ** a binary file or converts a binary file to base85 on stdout.
4160 ** Read or make it blurt its help for invocation details.
4161 **
4162 ** The SQLite3 extension creates a function, base85(x), which will
4163 ** either convert text base85 to a blob or a blob to text base85
4164 ** and return the result (or throw an error for other types.)
4165 ** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
4166 ** function, is_base85(t), which returns 1 iff the text t contains
4167 ** nothing other than base85 numerals and whitespace, or 0 otherwise.
4168 **
4169 ** To build the extension:
4170 ** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4171 ** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4172 ** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4173 ** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4174 ** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4175 ** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4176 **
4177 ** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
4178 ** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4179 ** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4180 ** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4181 */
4182 
4183 #include <stdio.h>
4184 #include <memory.h>
4185 #include <string.h>
4186 #include <assert.h>
4187 #ifndef OMIT_BASE85_CHECKER
4188 # include <ctype.h>
4189 #endif
4190 
4191 #ifndef BASE85_STANDALONE
4192 
4193 /* # include "sqlite3ext.h" */
4194 
4195 SQLITE_EXTENSION_INIT1;
4196 
4197 #else
4198 
4199 # ifdef _WIN32
4200 #  include <io.h>
4201 #  include <fcntl.h>
4202 # else
4203 #  define setmode(fd,m)
4204 # endif
4205 
4206 static char *zHelp =
4207   "Usage: base85 <dirFlag> <binFile>\n"
4208   " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4209   "   content to be converted to/from base85 on stdout/stdin.\n"
4210   " <binFile> names a binary file to be rendered or created.\n"
4211   "   Or, the name '-' refers to the stdin or stdout stream.\n"
4212   ;
4213 
4214 static void sayHelp(){
4215   printf("%s", zHelp);
4216 }
4217 #endif
4218 
4219 #ifndef U8_TYPEDEF
4220 /* typedef unsigned char u8; */
4221 #define U8_TYPEDEF
4222 #endif
4223 
4224 /* Classify c according to interval within USASCII set w.r.t. base85
4225  * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
4226  */
4227 #define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
4228 
4229 /* Provide digitValue to b85Numeral offset as a function of above class. */
4230 static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4231 #define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
4232 
4233 /* Say whether c is a base85 numeral. */
4234 #define IS_B85( c ) (B85_CLASS(c) & 1)
4235 
4236 #if 0 /* Not used, */
4237 static u8 base85DigitValue( char c ){
4238   u8 dv = (u8)(c - '#');
4239   if( dv>87 ) return 0xff;
4240   return (dv > 3)? dv-3 : dv;
4241 }
4242 #endif
4243 
4244 /* Width of base64 lines. Should be an integer multiple of 5. */
4245 #define B85_DARK_MAX 80
4246 
4247 
4248 static char * skipNonB85( char *s, int nc ){
4249   char c;
4250   while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
4251   return s;
4252 }
4253 
4254 /* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
4255  * Do not use the macro form with argument expression having a side-effect.*/
4256 #if 0
4257 static char base85Numeral( u8 b ){
4258   return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
4259 }
4260 #else
4261 # define base85Numeral( dn )\
4262   ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
4263 #endif
4264 
4265 static char *putcs(char *pc, char *s){
4266   char c;
4267   while( (c = *s++)!=0 ) *pc++ = c;
4268   return pc;
4269 }
4270 
4271 /* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
4272 ** to be appended to encoded groups to limit their length to B85_DARK_MAX
4273 ** or to terminate the last group (to aid concatenation.)
4274 */
4275 static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
4276   int nCol = 0;
4277   while( nbIn >= 4 ){
4278     int nco = 5;
4279     unsigned long qbv = (((unsigned long)pIn[0])<<24) |
4280                         (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
4281     while( nco > 0 ){
4282       unsigned nqv = (unsigned)(qbv/85UL);
4283       unsigned char dv = qbv - 85UL*nqv;
4284       qbv = nqv;
4285       pOut[--nco] = base85Numeral(dv);
4286     }
4287     nbIn -= 4;
4288     pIn += 4;
4289     pOut += 5;
4290     if( pSep && (nCol += 5)>=B85_DARK_MAX ){
4291       pOut = putcs(pOut, pSep);
4292       nCol = 0;
4293     }
4294   }
4295   if( nbIn > 0 ){
4296     int nco = nbIn + 1;
4297     unsigned long qv = *pIn++;
4298     int nbe = 1;
4299     while( nbe++ < nbIn ){
4300       qv = (qv<<8) | *pIn++;
4301     }
4302     nCol += nco;
4303     while( nco > 0 ){
4304       u8 dv = (u8)(qv % 85);
4305       qv /= 85;
4306       pOut[--nco] = base85Numeral(dv);
4307     }
4308     pOut += (nbIn+1);
4309   }
4310   if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
4311   *pOut = 0;
4312   return pOut;
4313 }
4314 
4315 /* Decode base85 text into a byte buffer. */
4316 static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
4317   if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
4318   while( ncIn>0 ){
4319     static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
4320     char *pUse = skipNonB85(pIn, ncIn);
4321     unsigned long qv = 0L;
4322     int nti, nbo;
4323     ncIn -= (pUse - pIn);
4324     pIn = pUse;
4325     nti = (ncIn>5)? 5 : ncIn;
4326     nbo = nboi[nti];
4327     if( nbo==0 ) break;
4328     while( nti>0 ){
4329       char c = *pIn++;
4330       u8 cdo = B85_DNOS(c);
4331       --ncIn;
4332       if( cdo==0 ) break;
4333       qv = 85 * qv + (c - cdo);
4334       --nti;
4335     }
4336     nbo -= nti; /* Adjust for early (non-digit) end of group. */
4337     switch( nbo ){
4338     case 4:
4339       *pOut++ = (qv >> 24)&0xff;
4340     case 3:
4341       *pOut++ = (qv >> 16)&0xff;
4342     case 2:
4343       *pOut++ = (qv >> 8)&0xff;
4344     case 1:
4345       *pOut++ = qv&0xff;
4346     case 0:
4347       break;
4348     }
4349   }
4350   return pOut;
4351 }
4352 
4353 #ifndef OMIT_BASE85_CHECKER
4354 /* Say whether input char sequence is all (base85 and/or whitespace).*/
4355 static int allBase85( char *p, int len ){
4356   char c;
4357   while( len-- > 0 && (c = *p++) != 0 ){
4358     if( !IS_B85(c) && !isspace(c) ) return 0;
4359   }
4360   return 1;
4361 }
4362 #endif
4363 
4364 #ifndef BASE85_STANDALONE
4365 
4366 # ifndef OMIT_BASE85_CHECKER
4367 /* This function does the work for the SQLite is_base85(t) UDF. */
4368 static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
4369   assert(na==1);
4370   switch( sqlite3_value_type(av[0]) ){
4371   case SQLITE_TEXT:
4372     {
4373       int rv = allBase85( (char *)sqlite3_value_text(av[0]),
4374                           sqlite3_value_bytes(av[0]) );
4375       sqlite3_result_int(context, rv);
4376     }
4377     break;
4378   case SQLITE_NULL:
4379     sqlite3_result_null(context);
4380     break;
4381   default:
4382     sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
4383     return;
4384   }
4385 }
4386 # endif
4387 
4388 /* This function does the work for the SQLite base85(x) UDF. */
4389 static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
4390   int nb, nc, nv = sqlite3_value_bytes(av[0]);
4391   int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4392                             SQLITE_LIMIT_LENGTH, -1);
4393   char *cBuf;
4394   u8 *bBuf;
4395   assert(na==1);
4396   switch( sqlite3_value_type(av[0]) ){
4397   case SQLITE_BLOB:
4398     nb = nv;
4399     /*    ulongs    tail   newlines  tailenc+nul*/
4400     nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
4401     if( nvMax < nc ){
4402       sqlite3_result_error(context, "blob expanded to base85 too big", -1);
4403       return;
4404     }
4405     bBuf = (u8*)sqlite3_value_blob(av[0]);
4406     if( !bBuf ){
4407       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4408         goto memFail;
4409       }
4410       sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4411       break;
4412     }
4413     cBuf = sqlite3_malloc(nc);
4414     if( !cBuf ) goto memFail;
4415     nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
4416     sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4417     break;
4418   case SQLITE_TEXT:
4419     nc = nv;
4420     nb = 4*(nv/5) + nv%5; /* may overestimate */
4421     if( nvMax < nb ){
4422       sqlite3_result_error(context, "blob from base85 may be too big", -1);
4423       return;
4424     }else if( nb<1 ){
4425       nb = 1;
4426     }
4427     cBuf = (char *)sqlite3_value_text(av[0]);
4428     if( !cBuf ){
4429       if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4430         goto memFail;
4431       }
4432       sqlite3_result_zeroblob(context, 0);
4433       break;
4434     }
4435     bBuf = sqlite3_malloc(nb);
4436     if( !bBuf ) goto memFail;
4437     nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
4438     sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4439     break;
4440   default:
4441     sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
4442     return;
4443   }
4444   return;
4445  memFail:
4446   sqlite3_result_error(context, "base85 OOM", -1);
4447 }
4448 
4449 /*
4450 ** Establish linkage to running SQLite library.
4451 */
4452 #ifndef SQLITE_SHELL_EXTFUNCS
4453 #ifdef _WIN32
4454 
4455 #endif
4456 int sqlite3_base_init
4457 #else
4458 static int sqlite3_base85_init
4459 #endif
4460 (sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4461   SQLITE_EXTENSION_INIT2(pApi);
4462   (void)pzErr;
4463 # ifndef OMIT_BASE85_CHECKER
4464   {
4465     int rc = sqlite3_create_function
4466       (db, "is_base85", 1,
4467        SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
4468        0, is_base85, 0, 0);
4469     if( rc!=SQLITE_OK ) return rc;
4470   }
4471 # endif
4472   return sqlite3_create_function
4473     (db, "base85", 1,
4474      SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4475      0, base85, 0, 0);
4476 }
4477 
4478 /*
4479 ** Define some macros to allow this extension to be built into the shell
4480 ** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4481 ** allows shell.c, as distributed, to have this extension built in.
4482 */
4483 # define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
4484 # define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4485 
4486 #else /* standalone program */
4487 
4488 int main(int na, char *av[]){
4489   int cin;
4490   int rc = 0;
4491   u8 bBuf[4*(B85_DARK_MAX/5)];
4492   char cBuf[5*(sizeof(bBuf)/4)+2];
4493   size_t nio;
4494 # ifndef OMIT_BASE85_CHECKER
4495   int b85Clean = 1;
4496 # endif
4497   char rw;
4498   FILE *fb = 0, *foc = 0;
4499   char fmode[3] = "xb";
4500   if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
4501     sayHelp();
4502     return 0;
4503   }
4504   fmode[0] = rw;
4505   if( av[2][0]=='-' && av[2][1]==0 ){
4506     switch( rw ){
4507     case 'r':
4508       fb = stdin;
4509       setmode(fileno(stdin), O_BINARY);
4510       break;
4511     case 'w':
4512       fb = stdout;
4513       setmode(fileno(stdout), O_BINARY);
4514       break;
4515     }
4516   }else{
4517     fb = fopen(av[2], fmode);
4518     foc = fb;
4519   }
4520   if( !fb ){
4521     fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
4522     rc = 1;
4523   }else{
4524     switch( rw ){
4525     case 'r':
4526       while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
4527         toBase85( bBuf, (int)nio, cBuf, 0 );
4528         fprintf(stdout, "%s\n", cBuf);
4529       }
4530       break;
4531     case 'w':
4532       while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
4533         int nc = strlen(cBuf);
4534         size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
4535         if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
4536 # ifndef OMIT_BASE85_CHECKER
4537         b85Clean &= allBase85( cBuf, nc );
4538 # endif
4539       }
4540       break;
4541     default:
4542       sayHelp();
4543       rc = 1;
4544     }
4545     if( foc ) fclose(foc);
4546   }
4547 # ifndef OMIT_BASE85_CHECKER
4548   if( !b85Clean ){
4549     fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
4550   }
4551 # endif
4552   return rc;
4553 }
4554 
4555 #endif
4556 
4557 /************************* End ../ext/misc/base85.c ********************/
4558 /************************* Begin ../ext/misc/ieee754.c ******************/
4559 /*
4560 ** 2013-04-17
4561 **
4562 ** The author disclaims copyright to this source code.  In place of
4563 ** a legal notice, here is a blessing:
4564 **
4565 **    May you do good and not evil.
4566 **    May you find forgiveness for yourself and forgive others.
4567 **    May you share freely, never taking more than you give.
4568 **
4569 ******************************************************************************
4570 **
4571 ** This SQLite extension implements functions for the exact display
4572 ** and input of IEEE754 Binary64 floating-point numbers.
4573 **
4574 **   ieee754(X)
4575 **   ieee754(Y,Z)
4576 **
4577 ** In the first form, the value X should be a floating-point number.
4578 ** The function will return a string of the form 'ieee754(Y,Z)' where
4579 ** Y and Z are integers such that X==Y*pow(2,Z).
4580 **
4581 ** In the second form, Y and Z are integers which are the mantissa and
4582 ** base-2 exponent of a new floating point number.  The function returns
4583 ** a floating-point value equal to Y*pow(2,Z).
4584 **
4585 ** Examples:
4586 **
4587 **     ieee754(2.0)             ->     'ieee754(2,0)'
4588 **     ieee754(45.25)           ->     'ieee754(181,-2)'
4589 **     ieee754(2, 0)            ->     2.0
4590 **     ieee754(181, -2)         ->     45.25
4591 **
4592 ** Two additional functions break apart the one-argument ieee754()
4593 ** result into separate integer values:
4594 **
4595 **     ieee754_mantissa(45.25)  ->     181
4596 **     ieee754_exponent(45.25)  ->     -2
4597 **
4598 ** These functions convert binary64 numbers into blobs and back again.
4599 **
4600 **     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
4601 **     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
4602 **
4603 ** In all single-argument functions, if the argument is an 8-byte blob
4604 ** then that blob is interpreted as a big-endian binary64 value.
4605 **
4606 **
4607 ** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
4608 ** -----------------------------------------------
4609 **
4610 ** This extension in combination with the separate 'decimal' extension
4611 ** can be used to compute the exact decimal representation of binary64
4612 ** values.  To begin, first compute a table of exponent values:
4613 **
4614 **    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
4615 **    WITH RECURSIVE c(x,v) AS (
4616 **      VALUES(0,'1')
4617 **      UNION ALL
4618 **      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
4619 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
4620 **    WITH RECURSIVE c(x,v) AS (
4621 **      VALUES(-1,'0.5')
4622 **      UNION ALL
4623 **      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
4624 **    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
4625 **
4626 ** Then, to compute the exact decimal representation of a floating
4627 ** point value (the value 47.49 is used in the example) do:
4628 **
4629 **    WITH c(n) AS (VALUES(47.49))
4630 **          ---------------^^^^^---- Replace with whatever you want
4631 **    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
4632 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
4633 **
4634 ** Here is a query to show various boundry values for the binary64
4635 ** number format:
4636 **
4637 **    WITH c(name,bin) AS (VALUES
4638 **       ('minimum positive value',        x'0000000000000001'),
4639 **       ('maximum subnormal value',       x'000fffffffffffff'),
4640 **       ('mininum positive nornal value', x'0010000000000000'),
4641 **       ('maximum value',                 x'7fefffffffffffff'))
4642 **    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
4643 **      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
4644 **
4645 */
4646 /* #include "sqlite3ext.h" */
4647 SQLITE_EXTENSION_INIT1
4648 #include <assert.h>
4649 #include <string.h>
4650 
4651 /* Mark a function parameter as unused, to suppress nuisance compiler
4652 ** warnings. */
4653 #ifndef UNUSED_PARAMETER
4654 # define UNUSED_PARAMETER(X)  (void)(X)
4655 #endif
4656 
4657 /*
4658 ** Implementation of the ieee754() function
4659 */
4660 static void ieee754func(
4661   sqlite3_context *context,
4662   int argc,
4663   sqlite3_value **argv
4664 ){
4665   if( argc==1 ){
4666     sqlite3_int64 m, a;
4667     double r;
4668     int e;
4669     int isNeg;
4670     char zResult[100];
4671     assert( sizeof(m)==sizeof(r) );
4672     if( sqlite3_value_type(argv[0])==SQLITE_BLOB
4673      && sqlite3_value_bytes(argv[0])==sizeof(r)
4674     ){
4675       const unsigned char *x = sqlite3_value_blob(argv[0]);
4676       unsigned int i;
4677       sqlite3_uint64 v = 0;
4678       for(i=0; i<sizeof(r); i++){
4679         v = (v<<8) | x[i];
4680       }
4681       memcpy(&r, &v, sizeof(r));
4682     }else{
4683       r = sqlite3_value_double(argv[0]);
4684     }
4685     if( r<0.0 ){
4686       isNeg = 1;
4687       r = -r;
4688     }else{
4689       isNeg = 0;
4690     }
4691     memcpy(&a,&r,sizeof(a));
4692     if( a==0 ){
4693       e = 0;
4694       m = 0;
4695     }else{
4696       e = a>>52;
4697       m = a & ((((sqlite3_int64)1)<<52)-1);
4698       if( e==0 ){
4699         m <<= 1;
4700       }else{
4701         m |= ((sqlite3_int64)1)<<52;
4702       }
4703       while( e<1075 && m>0 && (m&1)==0 ){
4704         m >>= 1;
4705         e++;
4706       }
4707       if( isNeg ) m = -m;
4708     }
4709     switch( *(int*)sqlite3_user_data(context) ){
4710       case 0:
4711         sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
4712                          m, e-1075);
4713         sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
4714         break;
4715       case 1:
4716         sqlite3_result_int64(context, m);
4717         break;
4718       case 2:
4719         sqlite3_result_int(context, e-1075);
4720         break;
4721     }
4722   }else{
4723     sqlite3_int64 m, e, a;
4724     double r;
4725     int isNeg = 0;
4726     m = sqlite3_value_int64(argv[0]);
4727     e = sqlite3_value_int64(argv[1]);
4728 
4729     /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
4730     if( e>10000 ){
4731       e = 10000;
4732     }else if( e<-10000 ){
4733       e = -10000;
4734     }
4735 
4736     if( m<0 ){
4737       isNeg = 1;
4738       m = -m;
4739       if( m<0 ) return;
4740     }else if( m==0 && e>-1000 && e<1000 ){
4741       sqlite3_result_double(context, 0.0);
4742       return;
4743     }
4744     while( (m>>32)&0xffe00000 ){
4745       m >>= 1;
4746       e++;
4747     }
4748     while( m!=0 && ((m>>32)&0xfff00000)==0 ){
4749       m <<= 1;
4750       e--;
4751     }
4752     e += 1075;
4753     if( e<=0 ){
4754       /* Subnormal */
4755       if( 1-e >= 64 ){
4756         m = 0;
4757       }else{
4758         m >>= 1-e;
4759       }
4760       e = 0;
4761     }else if( e>0x7ff ){
4762       e = 0x7ff;
4763     }
4764     a = m & ((((sqlite3_int64)1)<<52)-1);
4765     a |= e<<52;
4766     if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
4767     memcpy(&r, &a, sizeof(r));
4768     sqlite3_result_double(context, r);
4769   }
4770 }
4771 
4772 /*
4773 ** Functions to convert between blobs and floats.
4774 */
4775 static void ieee754func_from_blob(
4776   sqlite3_context *context,
4777   int argc,
4778   sqlite3_value **argv
4779 ){
4780   UNUSED_PARAMETER(argc);
4781   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
4782    && sqlite3_value_bytes(argv[0])==sizeof(double)
4783   ){
4784     double r;
4785     const unsigned char *x = sqlite3_value_blob(argv[0]);
4786     unsigned int i;
4787     sqlite3_uint64 v = 0;
4788     for(i=0; i<sizeof(r); i++){
4789       v = (v<<8) | x[i];
4790     }
4791     memcpy(&r, &v, sizeof(r));
4792     sqlite3_result_double(context, r);
4793   }
4794 }
4795 static void ieee754func_to_blob(
4796   sqlite3_context *context,
4797   int argc,
4798   sqlite3_value **argv
4799 ){
4800   UNUSED_PARAMETER(argc);
4801   if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
4802    || sqlite3_value_type(argv[0])==SQLITE_INTEGER
4803   ){
4804     double r = sqlite3_value_double(argv[0]);
4805     sqlite3_uint64 v;
4806     unsigned char a[sizeof(r)];
4807     unsigned int i;
4808     memcpy(&v, &r, sizeof(r));
4809     for(i=1; i<=sizeof(r); i++){
4810       a[sizeof(r)-i] = v&0xff;
4811       v >>= 8;
4812     }
4813     sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
4814   }
4815 }
4816 
4817 /*
4818 ** SQL Function:   ieee754_inc(r,N)
4819 **
4820 ** Move the floating point value r by N quantums and return the new
4821 ** values.
4822 **
4823 ** Behind the scenes: this routine merely casts r into a 64-bit unsigned
4824 ** integer, adds N, then casts the value back into float.
4825 **
4826 ** Example:  To find the smallest positive number:
4827 **
4828 **     SELECT ieee754_inc(0.0,+1);
4829 */
4830 static void ieee754inc(
4831   sqlite3_context *context,
4832   int argc,
4833   sqlite3_value **argv
4834 ){
4835   double r;
4836   sqlite3_int64 N;
4837   sqlite3_uint64 m1, m2;
4838   double r2;
4839   UNUSED_PARAMETER(argc);
4840   r = sqlite3_value_double(argv[0]);
4841   N = sqlite3_value_int64(argv[1]);
4842   memcpy(&m1, &r, 8);
4843   m2 = m1 + N;
4844   memcpy(&r2, &m2, 8);
4845   sqlite3_result_double(context, r2);
4846 }
4847 
4848 
4849 #ifdef _WIN32
4850 
4851 #endif
4852 int sqlite3_ieee_init(
4853   sqlite3 *db,
4854   char **pzErrMsg,
4855   const sqlite3_api_routines *pApi
4856 ){
4857   static const struct {
4858     char *zFName;
4859     int nArg;
4860     int iAux;
4861     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4862   } aFunc[] = {
4863     { "ieee754",           1,   0, ieee754func },
4864     { "ieee754",           2,   0, ieee754func },
4865     { "ieee754_mantissa",  1,   1, ieee754func },
4866     { "ieee754_exponent",  1,   2, ieee754func },
4867     { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
4868     { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
4869     { "ieee754_inc",       2,   0, ieee754inc  },
4870   };
4871   unsigned int i;
4872   int rc = SQLITE_OK;
4873   SQLITE_EXTENSION_INIT2(pApi);
4874   (void)pzErrMsg;  /* Unused parameter */
4875   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
4876     rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
4877                                SQLITE_UTF8|SQLITE_INNOCUOUS,
4878                                (void*)&aFunc[i].iAux,
4879                                aFunc[i].xFunc, 0, 0);
4880   }
4881   return rc;
4882 }
4883 
4884 /************************* End ../ext/misc/ieee754.c ********************/
4885 /************************* Begin ../ext/misc/series.c ******************/
4886 /*
4887 ** 2015-08-18, 2023-04-28
4888 **
4889 ** The author disclaims copyright to this source code.  In place of
4890 ** a legal notice, here is a blessing:
4891 **
4892 **    May you do good and not evil.
4893 **    May you find forgiveness for yourself and forgive others.
4894 **    May you share freely, never taking more than you give.
4895 **
4896 *************************************************************************
4897 **
4898 ** This file demonstrates how to create a table-valued-function using
4899 ** a virtual table.  This demo implements the generate_series() function
4900 ** which gives the same results as the eponymous function in PostgreSQL,
4901 ** within the limitation that its arguments are signed 64-bit integers.
4902 **
4903 ** Considering its equivalents to generate_series(start,stop,step): A
4904 ** value V[n] sequence is produced for integer n ascending from 0 where
4905 **  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
4906 ** for each produced value (independent of production time ordering.)
4907 **
4908 ** All parameters must be either integer or convertable to integer.
4909 ** The start parameter is required.
4910 ** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
4911 ** The step parameter defaults to 1 and 0 is treated as 1.
4912 **
4913 ** Examples:
4914 **
4915 **      SELECT * FROM generate_series(0,100,5);
4916 **
4917 ** The query above returns integers from 0 through 100 counting by steps
4918 ** of 5.
4919 **
4920 **      SELECT * FROM generate_series(0,100);
4921 **
4922 ** Integers from 0 through 100 with a step size of 1.
4923 **
4924 **      SELECT * FROM generate_series(20) LIMIT 10;
4925 **
4926 ** Integers 20 through 29.
4927 **
4928 **      SELECT * FROM generate_series(0,-100,-5);
4929 **
4930 ** Integers 0 -5 -10 ... -100.
4931 **
4932 **      SELECT * FROM generate_series(0,-1);
4933 **
4934 ** Empty sequence.
4935 **
4936 ** HOW IT WORKS
4937 **
4938 ** The generate_series "function" is really a virtual table with the
4939 ** following schema:
4940 **
4941 **     CREATE TABLE generate_series(
4942 **       value,
4943 **       start HIDDEN,
4944 **       stop HIDDEN,
4945 **       step HIDDEN
4946 **     );
4947 **
4948 ** The virtual table also has a rowid, logically equivalent to n+1 where
4949 ** "n" is the ascending integer in the aforesaid production definition.
4950 **
4951 ** Function arguments in queries against this virtual table are translated
4952 ** into equality constraints against successive hidden columns.  In other
4953 ** words, the following pairs of queries are equivalent to each other:
4954 **
4955 **    SELECT * FROM generate_series(0,100,5);
4956 **    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
4957 **
4958 **    SELECT * FROM generate_series(0,100);
4959 **    SELECT * FROM generate_series WHERE start=0 AND stop=100;
4960 **
4961 **    SELECT * FROM generate_series(20) LIMIT 10;
4962 **    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
4963 **
4964 ** The generate_series virtual table implementation leaves the xCreate method
4965 ** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
4966 ** TABLE command with "generate_series" as the USING argument.  Instead, there
4967 ** is a single generate_series virtual table that is always available without
4968 ** having to be created first.
4969 **
4970 ** The xBestIndex method looks for equality constraints against the hidden
4971 ** start, stop, and step columns, and if present, it uses those constraints
4972 ** to bound the sequence of generated values.  If the equality constraints
4973 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
4974 ** xBestIndex returns a small cost when both start and stop are available,
4975 ** and a very large cost if either start or stop are unavailable.  This
4976 ** encourages the query planner to order joins such that the bounds of the
4977 ** series are well-defined.
4978 */
4979 /* #include "sqlite3ext.h" */
4980 SQLITE_EXTENSION_INIT1
4981 #include <assert.h>
4982 #include <string.h>
4983 #include <limits.h>
4984 
4985 #ifndef SQLITE_OMIT_VIRTUALTABLE
4986 /*
4987 ** Return that member of a generate_series(...) sequence whose 0-based
4988 ** index is ix. The 0th member is given by smBase. The sequence members
4989 ** progress per ix increment by smStep.
4990 */
4991 static sqlite3_int64 genSeqMember(sqlite3_int64 smBase,
4992                                   sqlite3_int64 smStep,
4993                                   sqlite3_uint64 ix){
4994   if( ix>=(sqlite3_uint64)LLONG_MAX ){
4995     /* Get ix into signed i64 range. */
4996     ix -= (sqlite3_uint64)LLONG_MAX;
4997     /* With 2's complement ALU, this next can be 1 step, but is split into
4998      * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
4999     smBase += (LLONG_MAX/2) * smStep;
5000     smBase += (LLONG_MAX - LLONG_MAX/2) * smStep;
5001   }
5002   /* Under UBSAN (or on 1's complement machines), must do this last term
5003    * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
5004   if( ix>=2 ){
5005     sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
5006     smBase += ix2*smStep;
5007     ix -= ix2;
5008   }
5009   return smBase + ((sqlite3_int64)ix)*smStep;
5010 }
5011 
5012 /* typedef unsigned char u8; */
5013 
5014 typedef struct SequenceSpec {
5015   sqlite3_int64 iBase;         /* Starting value ("start") */
5016   sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
5017   sqlite3_int64 iStep;         /* Increment ("step") */
5018   sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
5019   sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
5020   sqlite3_int64 iValueNow;     /* Current value during generation */
5021   u8 isNotEOF;                 /* Sequence generation not exhausted */
5022   u8 isReversing;              /* Sequence is being reverse generated */
5023 } SequenceSpec;
5024 
5025 /*
5026 ** Prepare a SequenceSpec for use in generating an integer series
5027 ** given initialized iBase, iTerm and iStep values. Sequence is
5028 ** initialized per given isReversing. Other members are computed.
5029 */
5030 static void setupSequence( SequenceSpec *pss ){
5031   int bSameSigns;
5032   pss->uSeqIndexMax = 0;
5033   pss->isNotEOF = 0;
5034   bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
5035   if( pss->iTerm < pss->iBase ){
5036     sqlite3_uint64 nuspan = 0;
5037     if( bSameSigns ){
5038       nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
5039     }else{
5040       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5041        * In this clause, iBase>=0 and iTerm<0 . */
5042       nuspan = 1;
5043       nuspan += pss->iBase;
5044       nuspan += -(pss->iTerm+1);
5045     }
5046     if( pss->iStep<0 ){
5047       pss->isNotEOF = 1;
5048       if( nuspan==ULONG_MAX ){
5049         pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
5050       }else if( pss->iStep>LLONG_MIN ){
5051         pss->uSeqIndexMax = nuspan/-pss->iStep;
5052       }
5053     }
5054   }else if( pss->iTerm > pss->iBase ){
5055     sqlite3_uint64 puspan = 0;
5056     if( bSameSigns ){
5057       puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
5058     }else{
5059       /* Under UBSAN (or on 1's complement machines), must do this in steps.
5060        * In this clause, iTerm>=0 and iBase<0 . */
5061       puspan = 1;
5062       puspan += pss->iTerm;
5063       puspan += -(pss->iBase+1);
5064     }
5065     if( pss->iStep>0 ){
5066       pss->isNotEOF = 1;
5067       pss->uSeqIndexMax = puspan/pss->iStep;
5068     }
5069   }else if( pss->iTerm == pss->iBase ){
5070       pss->isNotEOF = 1;
5071       pss->uSeqIndexMax = 0;
5072   }
5073   pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
5074   pss->iValueNow = (pss->isReversing)
5075     ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
5076     : pss->iBase;
5077 }
5078 
5079 /*
5080 ** Progress sequence generator to yield next value, if any.
5081 ** Leave its state to either yield next value or be at EOF.
5082 ** Return whether there is a next value, or 0 at EOF.
5083 */
5084 static int progressSequence( SequenceSpec *pss ){
5085   if( !pss->isNotEOF ) return 0;
5086   if( pss->isReversing ){
5087     if( pss->uSeqIndexNow > 0 ){
5088       pss->uSeqIndexNow--;
5089       pss->iValueNow -= pss->iStep;
5090     }else{
5091       pss->isNotEOF = 0;
5092     }
5093   }else{
5094     if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
5095       pss->uSeqIndexNow++;
5096       pss->iValueNow += pss->iStep;
5097     }else{
5098       pss->isNotEOF = 0;
5099     }
5100   }
5101   return pss->isNotEOF;
5102 }
5103 
5104 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
5105 ** serve as the underlying representation of a cursor that scans
5106 ** over rows of the result
5107 */
5108 typedef struct series_cursor series_cursor;
5109 struct series_cursor {
5110   sqlite3_vtab_cursor base;  /* Base class - must be first */
5111   SequenceSpec ss;           /* (this) Derived class data */
5112 };
5113 
5114 /*
5115 ** The seriesConnect() method is invoked to create a new
5116 ** series_vtab that describes the generate_series virtual table.
5117 **
5118 ** Think of this routine as the constructor for series_vtab objects.
5119 **
5120 ** All this routine needs to do is:
5121 **
5122 **    (1) Allocate the series_vtab object and initialize all fields.
5123 **
5124 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5125 **        result set of queries against generate_series will look like.
5126 */
5127 static int seriesConnect(
5128   sqlite3 *db,
5129   void *pUnused,
5130   int argcUnused, const char *const*argvUnused,
5131   sqlite3_vtab **ppVtab,
5132   char **pzErrUnused
5133 ){
5134   sqlite3_vtab *pNew;
5135   int rc;
5136 
5137 /* Column numbers */
5138 #define SERIES_COLUMN_VALUE 0
5139 #define SERIES_COLUMN_START 1
5140 #define SERIES_COLUMN_STOP  2
5141 #define SERIES_COLUMN_STEP  3
5142 
5143   (void)pUnused;
5144   (void)argcUnused;
5145   (void)argvUnused;
5146   (void)pzErrUnused;
5147   rc = sqlite3_declare_vtab(db,
5148      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5149   if( rc==SQLITE_OK ){
5150     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5151     if( pNew==0 ) return SQLITE_NOMEM;
5152     memset(pNew, 0, sizeof(*pNew));
5153     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5154   }
5155   return rc;
5156 }
5157 
5158 /*
5159 ** This method is the destructor for series_cursor objects.
5160 */
5161 static int seriesDisconnect(sqlite3_vtab *pVtab){
5162   sqlite3_free(pVtab);
5163   return SQLITE_OK;
5164 }
5165 
5166 /*
5167 ** Constructor for a new series_cursor object.
5168 */
5169 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5170   series_cursor *pCur;
5171   (void)pUnused;
5172   pCur = sqlite3_malloc( sizeof(*pCur) );
5173   if( pCur==0 ) return SQLITE_NOMEM;
5174   memset(pCur, 0, sizeof(*pCur));
5175   *ppCursor = &pCur->base;
5176   return SQLITE_OK;
5177 }
5178 
5179 /*
5180 ** Destructor for a series_cursor.
5181 */
5182 static int seriesClose(sqlite3_vtab_cursor *cur){
5183   sqlite3_free(cur);
5184   return SQLITE_OK;
5185 }
5186 
5187 
5188 /*
5189 ** Advance a series_cursor to its next row of output.
5190 */
5191 static int seriesNext(sqlite3_vtab_cursor *cur){
5192   series_cursor *pCur = (series_cursor*)cur;
5193   progressSequence( & pCur->ss );
5194   return SQLITE_OK;
5195 }
5196 
5197 /*
5198 ** Return values of columns for the row at which the series_cursor
5199 ** is currently pointing.
5200 */
5201 static int seriesColumn(
5202   sqlite3_vtab_cursor *cur,   /* The cursor */
5203   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5204   int i                       /* Which column to return */
5205 ){
5206   series_cursor *pCur = (series_cursor*)cur;
5207   sqlite3_int64 x = 0;
5208   switch( i ){
5209     case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
5210     case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
5211     case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
5212     default:                   x = pCur->ss.iValueNow;  break;
5213   }
5214   sqlite3_result_int64(ctx, x);
5215   return SQLITE_OK;
5216 }
5217 
5218 #ifndef LARGEST_UINT64
5219 #define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
5220 #endif
5221 
5222 /*
5223 ** Return the rowid for the current row, logically equivalent to n+1 where
5224 ** "n" is the ascending integer in the aforesaid production definition.
5225 */
5226 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5227   series_cursor *pCur = (series_cursor*)cur;
5228   sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
5229   *pRowid = (sqlite3_int64)((n<LARGEST_UINT64)? n+1 : 0);
5230   return SQLITE_OK;
5231 }
5232 
5233 /*
5234 ** Return TRUE if the cursor has been moved off of the last
5235 ** row of output.
5236 */
5237 static int seriesEof(sqlite3_vtab_cursor *cur){
5238   series_cursor *pCur = (series_cursor*)cur;
5239   return !pCur->ss.isNotEOF;
5240 }
5241 
5242 /* True to cause run-time checking of the start=, stop=, and/or step=
5243 ** parameters.  The only reason to do this is for testing the
5244 ** constraint checking logic for virtual tables in the SQLite core.
5245 */
5246 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5247 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5248 #endif
5249 
5250 /*
5251 ** This method is called to "rewind" the series_cursor object back
5252 ** to the first row of output.  This method is always called at least
5253 ** once prior to any call to seriesColumn() or seriesRowid() or
5254 ** seriesEof().
5255 **
5256 ** The query plan selected by seriesBestIndex is passed in the idxNum
5257 ** parameter.  (idxStr is not used in this implementation.)  idxNum
5258 ** is a bitmask showing which constraints are available:
5259 **
5260 **    1:    start=VALUE
5261 **    2:    stop=VALUE
5262 **    4:    step=VALUE
5263 **
5264 ** Also, if bit 8 is set, that means that the series should be output
5265 ** in descending order rather than in ascending order.  If bit 16 is
5266 ** set, then output must appear in ascending order.
5267 **
5268 ** This routine should initialize the cursor and position it so that it
5269 ** is pointing at the first row, or pointing off the end of the table
5270 ** (so that seriesEof() will return true) if the table is empty.
5271 */
5272 static int seriesFilter(
5273   sqlite3_vtab_cursor *pVtabCursor,
5274   int idxNum, const char *idxStrUnused,
5275   int argc, sqlite3_value **argv
5276 ){
5277   series_cursor *pCur = (series_cursor *)pVtabCursor;
5278   int i = 0;
5279   (void)idxStrUnused;
5280   if( idxNum & 1 ){
5281     pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
5282   }else{
5283     pCur->ss.iBase = 0;
5284   }
5285   if( idxNum & 2 ){
5286     pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
5287   }else{
5288     pCur->ss.iTerm = 0xffffffff;
5289   }
5290   if( idxNum & 4 ){
5291     pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
5292     if( pCur->ss.iStep==0 ){
5293       pCur->ss.iStep = 1;
5294     }else if( pCur->ss.iStep<0 ){
5295       if( (idxNum & 16)==0 ) idxNum |= 8;
5296     }
5297   }else{
5298     pCur->ss.iStep = 1;
5299   }
5300   for(i=0; i<argc; i++){
5301     if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
5302       /* If any of the constraints have a NULL value, then return no rows.
5303       ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
5304       pCur->ss.iBase = 1;
5305       pCur->ss.iTerm = 0;
5306       pCur->ss.iStep = 1;
5307       break;
5308     }
5309   }
5310   if( idxNum & 8 ){
5311     pCur->ss.isReversing = pCur->ss.iStep > 0;
5312   }else{
5313     pCur->ss.isReversing = pCur->ss.iStep < 0;
5314   }
5315   setupSequence( &pCur->ss );
5316   return SQLITE_OK;
5317 }
5318 
5319 /*
5320 ** SQLite will invoke this method one or more times while planning a query
5321 ** that uses the generate_series virtual table.  This routine needs to create
5322 ** a query plan for each invocation and compute an estimated cost for that
5323 ** plan.
5324 **
5325 ** In this implementation idxNum is used to represent the
5326 ** query plan.  idxStr is unused.
5327 **
5328 ** The query plan is represented by bits in idxNum:
5329 **
5330 **  (1)  start = $value  -- constraint exists
5331 **  (2)  stop = $value   -- constraint exists
5332 **  (4)  step = $value   -- constraint exists
5333 **  (8)  output in descending order
5334 */
5335 static int seriesBestIndex(
5336   sqlite3_vtab *pVTab,
5337   sqlite3_index_info *pIdxInfo
5338 ){
5339   int i, j;              /* Loop over constraints */
5340   int idxNum = 0;        /* The query plan bitmask */
5341   int bStartSeen = 0;    /* EQ constraint seen on the START column */
5342   int unusableMask = 0;  /* Mask of unusable constraints */
5343   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
5344   int aIdx[3];           /* Constraints on start, stop, and step */
5345   const struct sqlite3_index_constraint *pConstraint;
5346 
5347   /* This implementation assumes that the start, stop, and step columns
5348   ** are the last three columns in the virtual table. */
5349   assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
5350   assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
5351 
5352   aIdx[0] = aIdx[1] = aIdx[2] = -1;
5353   pConstraint = pIdxInfo->aConstraint;
5354   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
5355     int iCol;    /* 0 for start, 1 for stop, 2 for step */
5356     int iMask;   /* bitmask for those column */
5357     if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
5358     iCol = pConstraint->iColumn - SERIES_COLUMN_START;
5359     assert( iCol>=0 && iCol<=2 );
5360     iMask = 1 << iCol;
5361     if( iCol==0 ) bStartSeen = 1;
5362     if( pConstraint->usable==0 ){
5363       unusableMask |=  iMask;
5364       continue;
5365     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
5366       idxNum |= iMask;
5367       aIdx[iCol] = i;
5368     }
5369   }
5370   for(i=0; i<3; i++){
5371     if( (j = aIdx[i])>=0 ){
5372       pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
5373       pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
5374     }
5375   }
5376   /* The current generate_column() implementation requires at least one
5377   ** argument (the START value).  Legacy versions assumed START=0 if the
5378   ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
5379   ** to obtain the legacy behavior */
5380 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
5381   if( !bStartSeen ){
5382     sqlite3_free(pVTab->zErrMsg);
5383     pVTab->zErrMsg = sqlite3_mprintf(
5384         "first argument to \"generate_series()\" missing or unusable");
5385     return SQLITE_ERROR;
5386   }
5387 #endif
5388   if( (unusableMask & ~idxNum)!=0 ){
5389     /* The start, stop, and step columns are inputs.  Therefore if there
5390     ** are unusable constraints on any of start, stop, or step then
5391     ** this plan is unusable */
5392     return SQLITE_CONSTRAINT;
5393   }
5394   if( (idxNum & 3)==3 ){
5395     /* Both start= and stop= boundaries are available.  This is the
5396     ** the preferred case */
5397     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
5398     pIdxInfo->estimatedRows = 1000;
5399     if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
5400       if( pIdxInfo->aOrderBy[0].desc ){
5401         idxNum |= 8;
5402       }else{
5403         idxNum |= 16;
5404       }
5405       pIdxInfo->orderByConsumed = 1;
5406     }
5407   }else{
5408     /* If either boundary is missing, we have to generate a huge span
5409     ** of numbers.  Make this case very expensive so that the query
5410     ** planner will work hard to avoid it. */
5411     pIdxInfo->estimatedRows = 2147483647;
5412   }
5413   pIdxInfo->idxNum = idxNum;
5414   return SQLITE_OK;
5415 }
5416 
5417 /*
5418 ** This following structure defines all the methods for the
5419 ** generate_series virtual table.
5420 */
5421 static sqlite3_module seriesModule = {
5422   0,                         /* iVersion */
5423   0,                         /* xCreate */
5424   seriesConnect,             /* xConnect */
5425   seriesBestIndex,           /* xBestIndex */
5426   seriesDisconnect,          /* xDisconnect */
5427   0,                         /* xDestroy */
5428   seriesOpen,                /* xOpen - open a cursor */
5429   seriesClose,               /* xClose - close a cursor */
5430   seriesFilter,              /* xFilter - configure scan constraints */
5431   seriesNext,                /* xNext - advance a cursor */
5432   seriesEof,                 /* xEof - check for end of scan */
5433   seriesColumn,              /* xColumn - read data */
5434   seriesRowid,               /* xRowid - read data */
5435   0,                         /* xUpdate */
5436   0,                         /* xBegin */
5437   0,                         /* xSync */
5438   0,                         /* xCommit */
5439   0,                         /* xRollback */
5440   0,                         /* xFindMethod */
5441   0,                         /* xRename */
5442   0,                         /* xSavepoint */
5443   0,                         /* xRelease */
5444   0,                         /* xRollbackTo */
5445   0,                         /* xShadowName */
5446   0                          /* xIntegrity */
5447 };
5448 
5449 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5450 
5451 #ifdef _WIN32
5452 
5453 #endif
5454 int sqlite3_series_init(
5455   sqlite3 *db,
5456   char **pzErrMsg,
5457   const sqlite3_api_routines *pApi
5458 ){
5459   int rc = SQLITE_OK;
5460   SQLITE_EXTENSION_INIT2(pApi);
5461 #ifndef SQLITE_OMIT_VIRTUALTABLE
5462   if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
5463     *pzErrMsg = sqlite3_mprintf(
5464         "generate_series() requires SQLite 3.8.12 or later");
5465     return SQLITE_ERROR;
5466   }
5467   rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
5468 #endif
5469   return rc;
5470 }
5471 
5472 /************************* End ../ext/misc/series.c ********************/
5473 /************************* Begin ../ext/misc/regexp.c ******************/
5474 /*
5475 ** 2012-11-13
5476 **
5477 ** The author disclaims copyright to this source code.  In place of
5478 ** a legal notice, here is a blessing:
5479 **
5480 **    May you do good and not evil.
5481 **    May you find forgiveness for yourself and forgive others.
5482 **    May you share freely, never taking more than you give.
5483 **
5484 ******************************************************************************
5485 **
5486 ** The code in this file implements a compact but reasonably
5487 ** efficient regular-expression matcher for posix extended regular
5488 ** expressions against UTF8 text.
5489 **
5490 ** This file is an SQLite extension.  It registers a single function
5491 ** named "regexp(A,B)" where A is the regular expression and B is the
5492 ** string to be matched.  By registering this function, SQLite will also
5493 ** then implement the "B regexp A" operator.  Note that with the function
5494 ** the regular expression comes first, but with the operator it comes
5495 ** second.
5496 **
5497 **  The following regular expression syntax is supported:
5498 **
5499 **     X*      zero or more occurrences of X
5500 **     X+      one or more occurrences of X
5501 **     X?      zero or one occurrences of X
5502 **     X{p,q}  between p and q occurrences of X
5503 **     (X)     match X
5504 **     X|Y     X or Y
5505 **     ^X      X occurring at the beginning of the string
5506 **     X$      X occurring at the end of the string
5507 **     .       Match any single character
5508 **     \c      Character c where c is one of \{}()[]|*+?.
5509 **     \c      C-language escapes for c in afnrtv.  ex: \t or \n
5510 **     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
5511 **     \xXX    Where XX is exactly 2 hex digits, unicode value XX
5512 **     [abc]   Any single character from the set abc
5513 **     [^abc]  Any single character not in the set abc
5514 **     [a-z]   Any single character in the range a-z
5515 **     [^a-z]  Any single character not in the range a-z
5516 **     \b      Word boundary
5517 **     \w      Word character.  [A-Za-z0-9_]
5518 **     \W      Non-word character
5519 **     \d      Digit
5520 **     \D      Non-digit
5521 **     \s      Whitespace character
5522 **     \S      Non-whitespace character
5523 **
5524 ** A nondeterministic finite automaton (NFA) is used for matching, so the
5525 ** performance is bounded by O(N*M) where N is the size of the regular
5526 ** expression and M is the size of the input string.  The matcher never
5527 ** exhibits exponential behavior.  Note that the X{p,q} operator expands
5528 ** to p copies of X following by q-p copies of X? and that the size of the
5529 ** regular expression in the O(N*M) performance bound is computed after
5530 ** this expansion.
5531 */
5532 #include <string.h>
5533 #include <stdlib.h>
5534 /* #include "sqlite3ext.h" */
5535 SQLITE_EXTENSION_INIT1
5536 
5537 /*
5538 ** The following #defines change the names of some functions implemented in
5539 ** this file to prevent name collisions with C-library functions of the
5540 ** same name.
5541 */
5542 #define re_match   sqlite3re_match
5543 #define re_compile sqlite3re_compile
5544 #define re_free    sqlite3re_free
5545 
5546 /* The end-of-input character */
5547 #define RE_EOF            0    /* End of input */
5548 #define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
5549 
5550 /* The NFA is implemented as sequence of opcodes taken from the following
5551 ** set.  Each opcode has a single integer argument.
5552 */
5553 #define RE_OP_MATCH       1    /* Match the one character in the argument */
5554 #define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
5555 #define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
5556 #define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
5557 #define RE_OP_GOTO        5    /* Jump to opcode at iArg */
5558 #define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
5559 #define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
5560 #define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
5561 #define RE_OP_CC_VALUE    9    /* Single value in a character class */
5562 #define RE_OP_CC_RANGE   10    /* Range of values in a character class */
5563 #define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
5564 #define RE_OP_NOTWORD    12    /* Not a perl word character */
5565 #define RE_OP_DIGIT      13    /* digit:  [0-9] */
5566 #define RE_OP_NOTDIGIT   14    /* Not a digit */
5567 #define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
5568 #define RE_OP_NOTSPACE   16    /* Not a digit */
5569 #define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
5570 #define RE_OP_ATSTART    18    /* Currently at the start of the string */
5571 
5572 #if defined(SQLITE_DEBUG)
5573 /* Opcode names used for symbolic debugging */
5574 static const char *ReOpName[] = {
5575   "EOF",
5576   "MATCH",
5577   "ANY",
5578   "ANYSTAR",
5579   "FORK",
5580   "GOTO",
5581   "ACCEPT",
5582   "CC_INC",
5583   "CC_EXC",
5584   "CC_VALUE",
5585   "CC_RANGE",
5586   "WORD",
5587   "NOTWORD",
5588   "DIGIT",
5589   "NOTDIGIT",
5590   "SPACE",
5591   "NOTSPACE",
5592   "BOUNDARY",
5593   "ATSTART",
5594 };
5595 #endif /* SQLITE_DEBUG */
5596 
5597 
5598 /* Each opcode is a "state" in the NFA */
5599 typedef unsigned short ReStateNumber;
5600 
5601 /* Because this is an NFA and not a DFA, multiple states can be active at
5602 ** once.  An instance of the following object records all active states in
5603 ** the NFA.  The implementation is optimized for the common case where the
5604 ** number of actives states is small.
5605 */
5606 typedef struct ReStateSet {
5607   unsigned nState;            /* Number of current states */
5608   ReStateNumber *aState;      /* Current states */
5609 } ReStateSet;
5610 
5611 /* An input string read one character at a time.
5612 */
5613 typedef struct ReInput ReInput;
5614 struct ReInput {
5615   const unsigned char *z;  /* All text */
5616   int i;                   /* Next byte to read */
5617   int mx;                  /* EOF when i>=mx */
5618 };
5619 
5620 /* A compiled NFA (or an NFA that is in the process of being compiled) is
5621 ** an instance of the following object.
5622 */
5623 typedef struct ReCompiled ReCompiled;
5624 struct ReCompiled {
5625   ReInput sIn;                /* Regular expression text */
5626   const char *zErr;           /* Error message to return */
5627   char *aOp;                  /* Operators for the virtual machine */
5628   int *aArg;                  /* Arguments to each operator */
5629   unsigned (*xNextChar)(ReInput*);  /* Next character function */
5630   unsigned char zInit[12];    /* Initial text to match */
5631   int nInit;                  /* Number of bytes in zInit */
5632   unsigned nState;            /* Number of entries in aOp[] and aArg[] */
5633   unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
5634 };
5635 
5636 /* Add a state to the given state set if it is not already there */
5637 static void re_add_state(ReStateSet *pSet, int newState){
5638   unsigned i;
5639   for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
5640   pSet->aState[pSet->nState++] = (ReStateNumber)newState;
5641 }
5642 
5643 /* Extract the next unicode character from *pzIn and return it.  Advance
5644 ** *pzIn to the first byte past the end of the character returned.  To
5645 ** be clear:  this routine converts utf8 to unicode.  This routine is
5646 ** optimized for the common case where the next character is a single byte.
5647 */
5648 static unsigned re_next_char(ReInput *p){
5649   unsigned c;
5650   if( p->i>=p->mx ) return 0;
5651   c = p->z[p->i++];
5652   if( c>=0x80 ){
5653     if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
5654       c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
5655       if( c<0x80 ) c = 0xfffd;
5656     }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
5657            && (p->z[p->i+1]&0xc0)==0x80 ){
5658       c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
5659       p->i += 2;
5660       if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
5661     }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
5662            && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
5663       c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
5664                        | (p->z[p->i+2]&0x3f);
5665       p->i += 3;
5666       if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
5667     }else{
5668       c = 0xfffd;
5669     }
5670   }
5671   return c;
5672 }
5673 static unsigned re_next_char_nocase(ReInput *p){
5674   unsigned c = re_next_char(p);
5675   if( c>='A' && c<='Z' ) c += 'a' - 'A';
5676   return c;
5677 }
5678 
5679 /* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
5680 static int re_word_char(int c){
5681   return (c>='0' && c<='9') || (c>='a' && c<='z')
5682       || (c>='A' && c<='Z') || c=='_';
5683 }
5684 
5685 /* Return true if c is a "digit" character:  [0-9] */
5686 static int re_digit_char(int c){
5687   return (c>='0' && c<='9');
5688 }
5689 
5690 /* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
5691 static int re_space_char(int c){
5692   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
5693 }
5694 
5695 /* Run a compiled regular expression on the zero-terminated input
5696 ** string zIn[].  Return true on a match and false if there is no match.
5697 */
5698 static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
5699   ReStateSet aStateSet[2], *pThis, *pNext;
5700   ReStateNumber aSpace[100];
5701   ReStateNumber *pToFree;
5702   unsigned int i = 0;
5703   unsigned int iSwap = 0;
5704   int c = RE_START;
5705   int cPrev = 0;
5706   int rc = 0;
5707   ReInput in;
5708 
5709   in.z = zIn;
5710   in.i = 0;
5711   in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
5712 
5713   /* Look for the initial prefix match, if there is one. */
5714   if( pRe->nInit ){
5715     unsigned char x = pRe->zInit[0];
5716     while( in.i+pRe->nInit<=in.mx
5717      && (zIn[in.i]!=x ||
5718          strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
5719     ){
5720       in.i++;
5721     }
5722     if( in.i+pRe->nInit>in.mx ) return 0;
5723     c = RE_START-1;
5724   }
5725 
5726   if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
5727     pToFree = 0;
5728     aStateSet[0].aState = aSpace;
5729   }else{
5730     pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
5731     if( pToFree==0 ) return -1;
5732     aStateSet[0].aState = pToFree;
5733   }
5734   aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
5735   pNext = &aStateSet[1];
5736   pNext->nState = 0;
5737   re_add_state(pNext, 0);
5738   while( c!=RE_EOF && pNext->nState>0 ){
5739     cPrev = c;
5740     c = pRe->xNextChar(&in);
5741     pThis = pNext;
5742     pNext = &aStateSet[iSwap];
5743     iSwap = 1 - iSwap;
5744     pNext->nState = 0;
5745     for(i=0; i<pThis->nState; i++){
5746       int x = pThis->aState[i];
5747       switch( pRe->aOp[x] ){
5748         case RE_OP_MATCH: {
5749           if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
5750           break;
5751         }
5752         case RE_OP_ATSTART: {
5753           if( cPrev==RE_START ) re_add_state(pThis, x+1);
5754           break;
5755         }
5756         case RE_OP_ANY: {
5757           if( c!=0 ) re_add_state(pNext, x+1);
5758           break;
5759         }
5760         case RE_OP_WORD: {
5761           if( re_word_char(c) ) re_add_state(pNext, x+1);
5762           break;
5763         }
5764         case RE_OP_NOTWORD: {
5765           if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
5766           break;
5767         }
5768         case RE_OP_DIGIT: {
5769           if( re_digit_char(c) ) re_add_state(pNext, x+1);
5770           break;
5771         }
5772         case RE_OP_NOTDIGIT: {
5773           if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
5774           break;
5775         }
5776         case RE_OP_SPACE: {
5777           if( re_space_char(c) ) re_add_state(pNext, x+1);
5778           break;
5779         }
5780         case RE_OP_NOTSPACE: {
5781           if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
5782           break;
5783         }
5784         case RE_OP_BOUNDARY: {
5785           if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
5786           break;
5787         }
5788         case RE_OP_ANYSTAR: {
5789           re_add_state(pNext, x);
5790           re_add_state(pThis, x+1);
5791           break;
5792         }
5793         case RE_OP_FORK: {
5794           re_add_state(pThis, x+pRe->aArg[x]);
5795           re_add_state(pThis, x+1);
5796           break;
5797         }
5798         case RE_OP_GOTO: {
5799           re_add_state(pThis, x+pRe->aArg[x]);
5800           break;
5801         }
5802         case RE_OP_ACCEPT: {
5803           rc = 1;
5804           goto re_match_end;
5805         }
5806         case RE_OP_CC_EXC: {
5807           if( c==0 ) break;
5808           /* fall-through */ goto re_op_cc_inc;
5809         }
5810         case RE_OP_CC_INC: re_op_cc_inc: {
5811           int j = 1;
5812           int n = pRe->aArg[x];
5813           int hit = 0;
5814           for(j=1; j>0 && j<n; j++){
5815             if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
5816               if( pRe->aArg[x+j]==c ){
5817                 hit = 1;
5818                 j = -1;
5819               }
5820             }else{
5821               if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
5822                 hit = 1;
5823                 j = -1;
5824               }else{
5825                 j++;
5826               }
5827             }
5828           }
5829           if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
5830           if( hit ) re_add_state(pNext, x+n);
5831           break;
5832         }
5833       }
5834     }
5835   }
5836   for(i=0; i<pNext->nState; i++){
5837     int x = pNext->aState[i];
5838     while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
5839     if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
5840   }
5841 re_match_end:
5842   sqlite3_free(pToFree);
5843   return rc;
5844 }
5845 
5846 /* Resize the opcode and argument arrays for an RE under construction.
5847 */
5848 static int re_resize(ReCompiled *p, int N){
5849   char *aOp;
5850   int *aArg;
5851   aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
5852   if( aOp==0 ) return 1;
5853   p->aOp = aOp;
5854   aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
5855   if( aArg==0 ) return 1;
5856   p->aArg = aArg;
5857   p->nAlloc = N;
5858   return 0;
5859 }
5860 
5861 /* Insert a new opcode and argument into an RE under construction.  The
5862 ** insertion point is just prior to existing opcode iBefore.
5863 */
5864 static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
5865   int i;
5866   if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
5867   for(i=p->nState; i>iBefore; i--){
5868     p->aOp[i] = p->aOp[i-1];
5869     p->aArg[i] = p->aArg[i-1];
5870   }
5871   p->nState++;
5872   p->aOp[iBefore] = (char)op;
5873   p->aArg[iBefore] = arg;
5874   return iBefore;
5875 }
5876 
5877 /* Append a new opcode and argument to the end of the RE under construction.
5878 */
5879 static int re_append(ReCompiled *p, int op, int arg){
5880   return re_insert(p, p->nState, op, arg);
5881 }
5882 
5883 /* Make a copy of N opcodes starting at iStart onto the end of the RE
5884 ** under construction.
5885 */
5886 static void re_copy(ReCompiled *p, int iStart, int N){
5887   if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
5888   memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
5889   memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
5890   p->nState += N;
5891 }
5892 
5893 /* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
5894 ** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
5895 ** c is not a hex digit *pV is unchanged.
5896 */
5897 static int re_hex(int c, int *pV){
5898   if( c>='0' && c<='9' ){
5899     c -= '0';
5900   }else if( c>='a' && c<='f' ){
5901     c -= 'a' - 10;
5902   }else if( c>='A' && c<='F' ){
5903     c -= 'A' - 10;
5904   }else{
5905     return 0;
5906   }
5907   *pV = (*pV)*16 + (c & 0xff);
5908   return 1;
5909 }
5910 
5911 /* A backslash character has been seen, read the next character and
5912 ** return its interpretation.
5913 */
5914 static unsigned re_esc_char(ReCompiled *p){
5915   static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
5916   static const char zTrans[] = "\a\f\n\r\t\v";
5917   int i, v = 0;
5918   char c;
5919   if( p->sIn.i>=p->sIn.mx ) return 0;
5920   c = p->sIn.z[p->sIn.i];
5921   if( c=='u' && p->sIn.i+4<p->sIn.mx ){
5922     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5923     if( re_hex(zIn[1],&v)
5924      && re_hex(zIn[2],&v)
5925      && re_hex(zIn[3],&v)
5926      && re_hex(zIn[4],&v)
5927     ){
5928       p->sIn.i += 5;
5929       return v;
5930     }
5931   }
5932   if( c=='x' && p->sIn.i+2<p->sIn.mx ){
5933     const unsigned char *zIn = p->sIn.z + p->sIn.i;
5934     if( re_hex(zIn[1],&v)
5935      && re_hex(zIn[2],&v)
5936     ){
5937       p->sIn.i += 3;
5938       return v;
5939     }
5940   }
5941   for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
5942   if( zEsc[i] ){
5943     if( i<6 ) c = zTrans[i];
5944     p->sIn.i++;
5945   }else{
5946     p->zErr = "unknown \\ escape";
5947   }
5948   return c;
5949 }
5950 
5951 /* Forward declaration */
5952 static const char *re_subcompile_string(ReCompiled*);
5953 
5954 /* Peek at the next byte of input */
5955 static unsigned char rePeek(ReCompiled *p){
5956   return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
5957 }
5958 
5959 /* Compile RE text into a sequence of opcodes.  Continue up to the
5960 ** first unmatched ")" character, then return.  If an error is found,
5961 ** return a pointer to the error message string.
5962 */
5963 static const char *re_subcompile_re(ReCompiled *p){
5964   const char *zErr;
5965   int iStart, iEnd, iGoto;
5966   iStart = p->nState;
5967   zErr = re_subcompile_string(p);
5968   if( zErr ) return zErr;
5969   while( rePeek(p)=='|' ){
5970     iEnd = p->nState;
5971     re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
5972     iGoto = re_append(p, RE_OP_GOTO, 0);
5973     p->sIn.i++;
5974     zErr = re_subcompile_string(p);
5975     if( zErr ) return zErr;
5976     p->aArg[iGoto] = p->nState - iGoto;
5977   }
5978   return 0;
5979 }
5980 
5981 /* Compile an element of regular expression text (anything that can be
5982 ** an operand to the "|" operator).  Return NULL on success or a pointer
5983 ** to the error message if there is a problem.
5984 */
5985 static const char *re_subcompile_string(ReCompiled *p){
5986   int iPrev = -1;
5987   int iStart;
5988   unsigned c;
5989   const char *zErr;
5990   while( (c = p->xNextChar(&p->sIn))!=0 ){
5991     iStart = p->nState;
5992     switch( c ){
5993       case '|':
5994       case ')': {
5995         p->sIn.i--;
5996         return 0;
5997       }
5998       case '(': {
5999         zErr = re_subcompile_re(p);
6000         if( zErr ) return zErr;
6001         if( rePeek(p)!=')' ) return "unmatched '('";
6002         p->sIn.i++;
6003         break;
6004       }
6005       case '.': {
6006         if( rePeek(p)=='*' ){
6007           re_append(p, RE_OP_ANYSTAR, 0);
6008           p->sIn.i++;
6009         }else{
6010           re_append(p, RE_OP_ANY, 0);
6011         }
6012         break;
6013       }
6014       case '*': {
6015         if( iPrev<0 ) return "'*' without operand";
6016         re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6017         re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6018         break;
6019       }
6020       case '+': {
6021         if( iPrev<0 ) return "'+' without operand";
6022         re_append(p, RE_OP_FORK, iPrev - p->nState);
6023         break;
6024       }
6025       case '?': {
6026         if( iPrev<0 ) return "'?' without operand";
6027         re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6028         break;
6029       }
6030       case '$': {
6031         re_append(p, RE_OP_MATCH, RE_EOF);
6032         break;
6033       }
6034       case '^': {
6035         re_append(p, RE_OP_ATSTART, 0);
6036         break;
6037       }
6038       case '{': {
6039         int m = 0, n = 0;
6040         int sz, j;
6041         if( iPrev<0 ) return "'{m,n}' without operand";
6042         while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6043         n = m;
6044         if( c==',' ){
6045           p->sIn.i++;
6046           n = 0;
6047           while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6048         }
6049         if( c!='}' ) return "unmatched '{'";
6050         if( n>0 && n<m ) return "n less than m in '{m,n}'";
6051         p->sIn.i++;
6052         sz = p->nState - iPrev;
6053         if( m==0 ){
6054           if( n==0 ) return "both m and n are zero in '{m,n}'";
6055           re_insert(p, iPrev, RE_OP_FORK, sz+1);
6056           iPrev++;
6057           n--;
6058         }else{
6059           for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6060         }
6061         for(j=m; j<n; j++){
6062           re_append(p, RE_OP_FORK, sz+1);
6063           re_copy(p, iPrev, sz);
6064         }
6065         if( n==0 && m>0 ){
6066           re_append(p, RE_OP_FORK, -sz);
6067         }
6068         break;
6069       }
6070       case '[': {
6071         unsigned int iFirst = p->nState;
6072         if( rePeek(p)=='^' ){
6073           re_append(p, RE_OP_CC_EXC, 0);
6074           p->sIn.i++;
6075         }else{
6076           re_append(p, RE_OP_CC_INC, 0);
6077         }
6078         while( (c = p->xNextChar(&p->sIn))!=0 ){
6079           if( c=='[' && rePeek(p)==':' ){
6080             return "POSIX character classes not supported";
6081           }
6082           if( c=='\\' ) c = re_esc_char(p);
6083           if( rePeek(p)=='-' ){
6084             re_append(p, RE_OP_CC_RANGE, c);
6085             p->sIn.i++;
6086             c = p->xNextChar(&p->sIn);
6087             if( c=='\\' ) c = re_esc_char(p);
6088             re_append(p, RE_OP_CC_RANGE, c);
6089           }else{
6090             re_append(p, RE_OP_CC_VALUE, c);
6091           }
6092           if( rePeek(p)==']' ){ p->sIn.i++; break; }
6093         }
6094         if( c==0 ) return "unclosed '['";
6095         if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
6096         break;
6097       }
6098       case '\\': {
6099         int specialOp = 0;
6100         switch( rePeek(p) ){
6101           case 'b': specialOp = RE_OP_BOUNDARY;   break;
6102           case 'd': specialOp = RE_OP_DIGIT;      break;
6103           case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6104           case 's': specialOp = RE_OP_SPACE;      break;
6105           case 'S': specialOp = RE_OP_NOTSPACE;   break;
6106           case 'w': specialOp = RE_OP_WORD;       break;
6107           case 'W': specialOp = RE_OP_NOTWORD;    break;
6108         }
6109         if( specialOp ){
6110           p->sIn.i++;
6111           re_append(p, specialOp, 0);
6112         }else{
6113           c = re_esc_char(p);
6114           re_append(p, RE_OP_MATCH, c);
6115         }
6116         break;
6117       }
6118       default: {
6119         re_append(p, RE_OP_MATCH, c);
6120         break;
6121       }
6122     }
6123     iPrev = iStart;
6124   }
6125   return 0;
6126 }
6127 
6128 /* Free and reclaim all the memory used by a previously compiled
6129 ** regular expression.  Applications should invoke this routine once
6130 ** for every call to re_compile() to avoid memory leaks.
6131 */
6132 static void re_free(ReCompiled *pRe){
6133   if( pRe ){
6134     sqlite3_free(pRe->aOp);
6135     sqlite3_free(pRe->aArg);
6136     sqlite3_free(pRe);
6137   }
6138 }
6139 
6140 /*
6141 ** Compile a textual regular expression in zIn[] into a compiled regular
6142 ** expression suitable for us by re_match() and return a pointer to the
6143 ** compiled regular expression in *ppRe.  Return NULL on success or an
6144 ** error message if something goes wrong.
6145 */
6146 static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6147   ReCompiled *pRe;
6148   const char *zErr;
6149   int i, j;
6150 
6151   *ppRe = 0;
6152   pRe = sqlite3_malloc( sizeof(*pRe) );
6153   if( pRe==0 ){
6154     return "out of memory";
6155   }
6156   memset(pRe, 0, sizeof(*pRe));
6157   pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6158   if( re_resize(pRe, 30) ){
6159     re_free(pRe);
6160     return "out of memory";
6161   }
6162   if( zIn[0]=='^' ){
6163     zIn++;
6164   }else{
6165     re_append(pRe, RE_OP_ANYSTAR, 0);
6166   }
6167   pRe->sIn.z = (unsigned char*)zIn;
6168   pRe->sIn.i = 0;
6169   pRe->sIn.mx = (int)strlen(zIn);
6170   zErr = re_subcompile_re(pRe);
6171   if( zErr ){
6172     re_free(pRe);
6173     return zErr;
6174   }
6175   if( pRe->sIn.i>=pRe->sIn.mx ){
6176     re_append(pRe, RE_OP_ACCEPT, 0);
6177     *ppRe = pRe;
6178   }else{
6179     re_free(pRe);
6180     return "unrecognized character";
6181   }
6182 
6183   /* The following is a performance optimization.  If the regex begins with
6184   ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6185   ** one or more matching characters, enter those matching characters into
6186   ** zInit[].  The re_match() routine can then search ahead in the input
6187   ** string looking for the initial match without having to run the whole
6188   ** regex engine over the string.  Do not worry about trying to match
6189   ** unicode characters beyond plane 0 - those are very rare and this is
6190   ** just an optimization. */
6191   if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6192     for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6193       unsigned x = pRe->aArg[i];
6194       if( x<=0x7f ){
6195         pRe->zInit[j++] = (unsigned char)x;
6196       }else if( x<=0x7ff ){
6197         pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6198         pRe->zInit[j++] = 0x80 | (x&0x3f);
6199       }else if( x<=0xffff ){
6200         pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
6201         pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
6202         pRe->zInit[j++] = 0x80 | (x&0x3f);
6203       }else{
6204         break;
6205       }
6206     }
6207     if( j>0 && pRe->zInit[j-1]==0 ) j--;
6208     pRe->nInit = j;
6209   }
6210   return pRe->zErr;
6211 }
6212 
6213 /*
6214 ** Implementation of the regexp() SQL function.  This function implements
6215 ** the build-in REGEXP operator.  The first argument to the function is the
6216 ** pattern and the second argument is the string.  So, the SQL statements:
6217 **
6218 **       A REGEXP B
6219 **
6220 ** is implemented as regexp(B,A).
6221 */
6222 static void re_sql_func(
6223   sqlite3_context *context,
6224   int argc,
6225   sqlite3_value **argv
6226 ){
6227   ReCompiled *pRe;          /* Compiled regular expression */
6228   const char *zPattern;     /* The regular expression */
6229   const unsigned char *zStr;/* String being searched */
6230   const char *zErr;         /* Compile error message */
6231   int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
6232 
6233   (void)argc;  /* Unused */
6234   pRe = sqlite3_get_auxdata(context, 0);
6235   if( pRe==0 ){
6236     zPattern = (const char*)sqlite3_value_text(argv[0]);
6237     if( zPattern==0 ) return;
6238     zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
6239     if( zErr ){
6240       re_free(pRe);
6241       sqlite3_result_error(context, zErr, -1);
6242       return;
6243     }
6244     if( pRe==0 ){
6245       sqlite3_result_error_nomem(context);
6246       return;
6247     }
6248     setAux = 1;
6249   }
6250   zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
6251   if( zStr!=0 ){
6252     sqlite3_result_int(context, re_match(pRe, zStr, -1));
6253   }
6254   if( setAux ){
6255     sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
6256   }
6257 }
6258 
6259 #if defined(SQLITE_DEBUG)
6260 /*
6261 ** This function is used for testing and debugging only.  It is only available
6262 ** if the SQLITE_DEBUG compile-time option is used.
6263 **
6264 ** Compile a regular expression and then convert the compiled expression into
6265 ** text and return that text.
6266 */
6267 static void re_bytecode_func(
6268   sqlite3_context *context,
6269   int argc,
6270   sqlite3_value **argv
6271 ){
6272   const char *zPattern;
6273   const char *zErr;
6274   ReCompiled *pRe;
6275   sqlite3_str *pStr;
6276   int i;
6277   int n;
6278   char *z;
6279   (void)argc;
6280 
6281   zPattern = (const char*)sqlite3_value_text(argv[0]);
6282   if( zPattern==0 ) return;
6283   zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
6284   if( zErr ){
6285     re_free(pRe);
6286     sqlite3_result_error(context, zErr, -1);
6287     return;
6288   }
6289   if( pRe==0 ){
6290     sqlite3_result_error_nomem(context);
6291     return;
6292   }
6293   pStr = sqlite3_str_new(0);
6294   if( pStr==0 ) goto re_bytecode_func_err;
6295   if( pRe->nInit>0 ){
6296     sqlite3_str_appendf(pStr, "INIT     ");
6297     for(i=0; i<pRe->nInit; i++){
6298       sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
6299     }
6300     sqlite3_str_appendf(pStr, "\n");
6301   }
6302   for(i=0; (unsigned)i<pRe->nState; i++){
6303     sqlite3_str_appendf(pStr, "%-8s %4d\n",
6304          ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
6305   }
6306   n = sqlite3_str_length(pStr);
6307   z = sqlite3_str_finish(pStr);
6308   if( n==0 ){
6309     sqlite3_free(z);
6310   }else{
6311     sqlite3_result_text(context, z, n-1, sqlite3_free);
6312   }
6313 
6314 re_bytecode_func_err:
6315   re_free(pRe);
6316 }
6317 
6318 #endif /* SQLITE_DEBUG */
6319 
6320 
6321 /*
6322 ** Invoke this routine to register the regexp() function with the
6323 ** SQLite database connection.
6324 */
6325 #ifdef _WIN32
6326 
6327 #endif
6328 int sqlite3_regexp_init(
6329   sqlite3 *db,
6330   char **pzErrMsg,
6331   const sqlite3_api_routines *pApi
6332 ){
6333   int rc = SQLITE_OK;
6334   SQLITE_EXTENSION_INIT2(pApi);
6335   (void)pzErrMsg;  /* Unused */
6336   rc = sqlite3_create_function(db, "regexp", 2,
6337                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
6338                             0, re_sql_func, 0, 0);
6339   if( rc==SQLITE_OK ){
6340     /* The regexpi(PATTERN,STRING) function is a case-insensitive version
6341     ** of regexp(PATTERN,STRING). */
6342     rc = sqlite3_create_function(db, "regexpi", 2,
6343                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
6344                             (void*)db, re_sql_func, 0, 0);
6345 #if defined(SQLITE_DEBUG)
6346     if( rc==SQLITE_OK ){
6347       rc = sqlite3_create_function(db, "regexp_bytecode", 1,
6348                             SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
6349                             0, re_bytecode_func, 0, 0);
6350     }
6351 #endif /* SQLITE_DEBUG */
6352   }
6353   return rc;
6354 }
6355 
6356 /************************* End ../ext/misc/regexp.c ********************/
6357 #ifndef SQLITE_SHELL_FIDDLE
6358 /************************* Begin ../ext/misc/fileio.c ******************/
6359 /*
6360 ** 2014-06-13
6361 **
6362 ** The author disclaims copyright to this source code.  In place of
6363 ** a legal notice, here is a blessing:
6364 **
6365 **    May you do good and not evil.
6366 **    May you find forgiveness for yourself and forgive others.
6367 **    May you share freely, never taking more than you give.
6368 **
6369 ******************************************************************************
6370 **
6371 ** This SQLite extension implements SQL functions readfile() and
6372 ** writefile(), and eponymous virtual type "fsdir".
6373 **
6374 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
6375 **
6376 **   If neither of the optional arguments is present, then this UDF
6377 **   function writes blob DATA to file FILE. If successful, the number
6378 **   of bytes written is returned. If an error occurs, NULL is returned.
6379 **
6380 **   If the first option argument - MODE - is present, then it must
6381 **   be passed an integer value that corresponds to a POSIX mode
6382 **   value (file type + permissions, as returned in the stat.st_mode
6383 **   field by the stat() system call). Three types of files may
6384 **   be written/created:
6385 **
6386 **     regular files:  (mode & 0170000)==0100000
6387 **     symbolic links: (mode & 0170000)==0120000
6388 **     directories:    (mode & 0170000)==0040000
6389 **
6390 **   For a directory, the DATA is ignored. For a symbolic link, it is
6391 **   interpreted as text and used as the target of the link. For a
6392 **   regular file, it is interpreted as a blob and written into the
6393 **   named file. Regardless of the type of file, its permissions are
6394 **   set to (mode & 0777) before returning.
6395 **
6396 **   If the optional MTIME argument is present, then it is interpreted
6397 **   as an integer - the number of seconds since the unix epoch. The
6398 **   modification-time of the target file is set to this value before
6399 **   returning.
6400 **
6401 **   If three or more arguments are passed to this function and an
6402 **   error is encountered, an exception is raised.
6403 **
6404 ** READFILE(FILE):
6405 **
6406 **   Read and return the contents of file FILE (type blob) from disk.
6407 **
6408 ** FSDIR:
6409 **
6410 **   Used as follows:
6411 **
6412 **     SELECT * FROM fsdir($path [, $dir]);
6413 **
6414 **   Parameter $path is an absolute or relative pathname. If the file that it
6415 **   refers to does not exist, it is an error. If the path refers to a regular
6416 **   file or symbolic link, it returns a single row. Or, if the path refers
6417 **   to a directory, it returns one row for the directory, and one row for each
6418 **   file within the hierarchy rooted at $path.
6419 **
6420 **   Each row has the following columns:
6421 **
6422 **     name:  Path to file or directory (text value).
6423 **     mode:  Value of stat.st_mode for directory entry (an integer).
6424 **     mtime: Value of stat.st_mtime for directory entry (an integer).
6425 **     data:  For a regular file, a blob containing the file data. For a
6426 **            symlink, a text value containing the text of the link. For a
6427 **            directory, NULL.
6428 **
6429 **   If a non-NULL value is specified for the optional $dir parameter and
6430 **   $path is a relative path, then $path is interpreted relative to $dir.
6431 **   And the paths returned in the "name" column of the table are also
6432 **   relative to directory $dir.
6433 **
6434 ** Notes on building this extension for Windows:
6435 **   Unless linked statically with the SQLite library, a preprocessor
6436 **   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
6437 **   DLL form of this extension for WIN32. See its use below for details.
6438 */
6439 /* #include "sqlite3ext.h" */
6440 SQLITE_EXTENSION_INIT1
6441 #include <stdio.h>
6442 #include <string.h>
6443 #include <assert.h>
6444 
6445 #include <sys/types.h>
6446 #include <sys/stat.h>
6447 #include <fcntl.h>
6448 #if !defined(_WIN32) && !defined(WIN32)
6449 #  include <unistd.h>
6450 #  include <dirent.h>
6451 #  include <utime.h>
6452 #  include <sys/time.h>
6453 #else
6454 #  include "windows.h"
6455 #  include <io.h>
6456 #  include <direct.h>
6457 /* #  include "test_windirent.h" */
6458 #  define dirent DIRENT
6459 #  ifndef chmod
6460 #    define chmod _chmod
6461 #  endif
6462 #  ifndef stat
6463 #    define stat _stat
6464 #  endif
6465 #  define mkdir(path,mode) _mkdir(path)
6466 #  define lstat(path,buf) stat(path,buf)
6467 #endif
6468 #include <time.h>
6469 #include <errno.h>
6470 
6471 
6472 /*
6473 ** Structure of the fsdir() table-valued function
6474 */
6475                  /*    0    1    2     3    4           5             */
6476 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
6477 #define FSDIR_COLUMN_NAME     0     /* Name of the file */
6478 #define FSDIR_COLUMN_MODE     1     /* Access mode */
6479 #define FSDIR_COLUMN_MTIME    2     /* Last modification time */
6480 #define FSDIR_COLUMN_DATA     3     /* File content */
6481 #define FSDIR_COLUMN_PATH     4     /* Path to top of search */
6482 #define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
6483 
6484 
6485 /*
6486 ** Set the result stored by context ctx to a blob containing the
6487 ** contents of file zName.  Or, leave the result unchanged (NULL)
6488 ** if the file does not exist or is unreadable.
6489 **
6490 ** If the file exceeds the SQLite blob size limit, through an
6491 ** SQLITE_TOOBIG error.
6492 **
6493 ** Throw an SQLITE_IOERR if there are difficulties pulling the file
6494 ** off of disk.
6495 */
6496 static void readFileContents(sqlite3_context *ctx, const char *zName){
6497   FILE *in;
6498   sqlite3_int64 nIn;
6499   void *pBuf;
6500   sqlite3 *db;
6501   int mxBlob;
6502 
6503   in = fopen(zName, "rb");
6504   if( in==0 ){
6505     /* File does not exist or is unreadable. Leave the result set to NULL. */
6506     return;
6507   }
6508   fseek(in, 0, SEEK_END);
6509   nIn = ftell(in);
6510   rewind(in);
6511   db = sqlite3_context_db_handle(ctx);
6512   mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
6513   if( nIn>mxBlob ){
6514     sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
6515     fclose(in);
6516     return;
6517   }
6518   pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
6519   if( pBuf==0 ){
6520     sqlite3_result_error_nomem(ctx);
6521     fclose(in);
6522     return;
6523   }
6524   if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
6525     sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
6526   }else{
6527     sqlite3_result_error_code(ctx, SQLITE_IOERR);
6528     sqlite3_free(pBuf);
6529   }
6530   fclose(in);
6531 }
6532 
6533 /*
6534 ** Implementation of the "readfile(X)" SQL function.  The entire content
6535 ** of the file named X is read and returned as a BLOB.  NULL is returned
6536 ** if the file does not exist or is unreadable.
6537 */
6538 static void readfileFunc(
6539   sqlite3_context *context,
6540   int argc,
6541   sqlite3_value **argv
6542 ){
6543   const char *zName;
6544   (void)(argc);  /* Unused parameter */
6545   zName = (const char*)sqlite3_value_text(argv[0]);
6546   if( zName==0 ) return;
6547   readFileContents(context, zName);
6548 }
6549 
6550 /*
6551 ** Set the error message contained in context ctx to the results of
6552 ** vprintf(zFmt, ...).
6553 */
6554 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
6555   char *zMsg = 0;
6556   va_list ap;
6557   va_start(ap, zFmt);
6558   zMsg = sqlite3_vmprintf(zFmt, ap);
6559   sqlite3_result_error(ctx, zMsg, -1);
6560   sqlite3_free(zMsg);
6561   va_end(ap);
6562 }
6563 
6564 #if defined(_WIN32)
6565 /*
6566 ** This function is designed to convert a Win32 FILETIME structure into the
6567 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
6568 */
6569 static sqlite3_uint64 fileTimeToUnixTime(
6570   LPFILETIME pFileTime
6571 ){
6572   SYSTEMTIME epochSystemTime;
6573   ULARGE_INTEGER epochIntervals;
6574   FILETIME epochFileTime;
6575   ULARGE_INTEGER fileIntervals;
6576 
6577   memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
6578   epochSystemTime.wYear = 1970;
6579   epochSystemTime.wMonth = 1;
6580   epochSystemTime.wDay = 1;
6581   SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
6582   epochIntervals.LowPart = epochFileTime.dwLowDateTime;
6583   epochIntervals.HighPart = epochFileTime.dwHighDateTime;
6584 
6585   fileIntervals.LowPart = pFileTime->dwLowDateTime;
6586   fileIntervals.HighPart = pFileTime->dwHighDateTime;
6587 
6588   return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
6589 }
6590 
6591 
6592 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
6593 #  /* To allow a standalone DLL, use this next replacement function: */
6594 #  undef sqlite3_win32_utf8_to_unicode
6595 #  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
6596 #
6597 LPWSTR utf8_to_utf16(const char *z){
6598   int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
6599   LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
6600   if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
6601     return rv;
6602   sqlite3_free(rv);
6603   return 0;
6604 }
6605 #endif
6606 
6607 /*
6608 ** This function attempts to normalize the time values found in the stat()
6609 ** buffer to UTC.  This is necessary on Win32, where the runtime library
6610 ** appears to return these values as local times.
6611 */
6612 static void statTimesToUtc(
6613   const char *zPath,
6614   struct stat *pStatBuf
6615 ){
6616   HANDLE hFindFile;
6617   WIN32_FIND_DATAW fd;
6618   LPWSTR zUnicodeName;
6619   extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
6620   zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
6621   if( zUnicodeName ){
6622     memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
6623     hFindFile = FindFirstFileW(zUnicodeName, &fd);
6624     if( hFindFile!=NULL ){
6625       pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
6626       pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
6627       pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
6628       FindClose(hFindFile);
6629     }
6630     sqlite3_free(zUnicodeName);
6631   }
6632 }
6633 #endif
6634 
6635 /*
6636 ** This function is used in place of stat().  On Windows, special handling
6637 ** is required in order for the included time to be returned as UTC.  On all
6638 ** other systems, this function simply calls stat().
6639 */
6640 static int fileStat(
6641   const char *zPath,
6642   struct stat *pStatBuf
6643 ){
6644 #if defined(_WIN32)
6645   int rc = stat(zPath, pStatBuf);
6646   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
6647   return rc;
6648 #else
6649   return stat(zPath, pStatBuf);
6650 #endif
6651 }
6652 
6653 /*
6654 ** This function is used in place of lstat().  On Windows, special handling
6655 ** is required in order for the included time to be returned as UTC.  On all
6656 ** other systems, this function simply calls lstat().
6657 */
6658 static int fileLinkStat(
6659   const char *zPath,
6660   struct stat *pStatBuf
6661 ){
6662 #if defined(_WIN32)
6663   int rc = lstat(zPath, pStatBuf);
6664   if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
6665   return rc;
6666 #else
6667   return lstat(zPath, pStatBuf);
6668 #endif
6669 }
6670 
6671 /*
6672 ** Argument zFile is the name of a file that will be created and/or written
6673 ** by SQL function writefile(). This function ensures that the directory
6674 ** zFile will be written to exists, creating it if required. The permissions
6675 ** for any path components created by this function are set in accordance
6676 ** with the current umask.
6677 **
6678 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
6679 ** SQLITE_OK is returned if the directory is successfully created, or
6680 ** SQLITE_ERROR otherwise.
6681 */
6682 static int makeDirectory(
6683   const char *zFile
6684 ){
6685   char *zCopy = sqlite3_mprintf("%s", zFile);
6686   int rc = SQLITE_OK;
6687 
6688   if( zCopy==0 ){
6689     rc = SQLITE_NOMEM;
6690   }else{
6691     int nCopy = (int)strlen(zCopy);
6692     int i = 1;
6693 
6694     while( rc==SQLITE_OK ){
6695       struct stat sStat;
6696       int rc2;
6697 
6698       for(; zCopy[i]!='/' && i<nCopy; i++);
6699       if( i==nCopy ) break;
6700       zCopy[i] = '\0';
6701 
6702       rc2 = fileStat(zCopy, &sStat);
6703       if( rc2!=0 ){
6704         if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
6705       }else{
6706         if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
6707       }
6708       zCopy[i] = '/';
6709       i++;
6710     }
6711 
6712     sqlite3_free(zCopy);
6713   }
6714 
6715   return rc;
6716 }
6717 
6718 /*
6719 ** This function does the work for the writefile() UDF. Refer to
6720 ** header comments at the top of this file for details.
6721 */
6722 static int writeFile(
6723   sqlite3_context *pCtx,          /* Context to return bytes written in */
6724   const char *zFile,              /* File to write */
6725   sqlite3_value *pData,           /* Data to write */
6726   mode_t mode,                    /* MODE parameter passed to writefile() */
6727   sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
6728 ){
6729   if( zFile==0 ) return 1;
6730 #if !defined(_WIN32) && !defined(WIN32)
6731   if( S_ISLNK(mode) ){
6732     const char *zTo = (const char*)sqlite3_value_text(pData);
6733     if( zTo==0 || symlink(zTo, zFile)<0 ) return 1;
6734   }else
6735 #endif
6736   {
6737     if( S_ISDIR(mode) ){
6738       if( mkdir(zFile, mode) ){
6739         /* The mkdir() call to create the directory failed. This might not
6740         ** be an error though - if there is already a directory at the same
6741         ** path and either the permissions already match or can be changed
6742         ** to do so using chmod(), it is not an error.  */
6743         struct stat sStat;
6744         if( errno!=EEXIST
6745          || 0!=fileStat(zFile, &sStat)
6746          || !S_ISDIR(sStat.st_mode)
6747          || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
6748         ){
6749           return 1;
6750         }
6751       }
6752     }else{
6753       sqlite3_int64 nWrite = 0;
6754       const char *z;
6755       int rc = 0;
6756       FILE *out = fopen(zFile, "wb");
6757       if( out==0 ) return 1;
6758       z = (const char*)sqlite3_value_blob(pData);
6759       if( z ){
6760         sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
6761         nWrite = sqlite3_value_bytes(pData);
6762         if( nWrite!=n ){
6763           rc = 1;
6764         }
6765       }
6766       fclose(out);
6767       if( rc==0 && mode && chmod(zFile, mode & 0777) ){
6768         rc = 1;
6769       }
6770       if( rc ) return 2;
6771       sqlite3_result_int64(pCtx, nWrite);
6772     }
6773   }
6774 
6775   if( mtime>=0 ){
6776 #if defined(_WIN32)
6777 #if !SQLITE_OS_WINRT
6778     /* Windows */
6779     FILETIME lastAccess;
6780     FILETIME lastWrite;
6781     SYSTEMTIME currentTime;
6782     LONGLONG intervals;
6783     HANDLE hFile;
6784     LPWSTR zUnicodeName;
6785     extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
6786 
6787     GetSystemTime(&currentTime);
6788     SystemTimeToFileTime(&currentTime, &lastAccess);
6789     intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
6790     lastWrite.dwLowDateTime = (DWORD)intervals;
6791     lastWrite.dwHighDateTime = intervals >> 32;
6792     zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
6793     if( zUnicodeName==0 ){
6794       return 1;
6795     }
6796     hFile = CreateFileW(
6797       zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
6798       FILE_FLAG_BACKUP_SEMANTICS, NULL
6799     );
6800     sqlite3_free(zUnicodeName);
6801     if( hFile!=INVALID_HANDLE_VALUE ){
6802       BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
6803       CloseHandle(hFile);
6804       return !bResult;
6805     }else{
6806       return 1;
6807     }
6808 #endif
6809 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
6810     /* Recent unix */
6811     struct timespec times[2];
6812     times[0].tv_nsec = times[1].tv_nsec = 0;
6813     times[0].tv_sec = time(0);
6814     times[1].tv_sec = mtime;
6815     if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
6816       return 1;
6817     }
6818 #else
6819     /* Legacy unix */
6820     struct timeval times[2];
6821     times[0].tv_usec = times[1].tv_usec = 0;
6822     times[0].tv_sec = time(0);
6823     times[1].tv_sec = mtime;
6824     if( utimes(zFile, times) ){
6825       return 1;
6826     }
6827 #endif
6828   }
6829 
6830   return 0;
6831 }
6832 
6833 /*
6834 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
6835 ** Refer to header comments at the top of this file for details.
6836 */
6837 static void writefileFunc(
6838   sqlite3_context *context,
6839   int argc,
6840   sqlite3_value **argv
6841 ){
6842   const char *zFile;
6843   mode_t mode = 0;
6844   int res;
6845   sqlite3_int64 mtime = -1;
6846 
6847   if( argc<2 || argc>4 ){
6848     sqlite3_result_error(context,
6849         "wrong number of arguments to function writefile()", -1
6850     );
6851     return;
6852   }
6853 
6854   zFile = (const char*)sqlite3_value_text(argv[0]);
6855   if( zFile==0 ) return;
6856   if( argc>=3 ){
6857     mode = (mode_t)sqlite3_value_int(argv[2]);
6858   }
6859   if( argc==4 ){
6860     mtime = sqlite3_value_int64(argv[3]);
6861   }
6862 
6863   res = writeFile(context, zFile, argv[1], mode, mtime);
6864   if( res==1 && errno==ENOENT ){
6865     if( makeDirectory(zFile)==SQLITE_OK ){
6866       res = writeFile(context, zFile, argv[1], mode, mtime);
6867     }
6868   }
6869 
6870   if( argc>2 && res!=0 ){
6871     if( S_ISLNK(mode) ){
6872       ctxErrorMsg(context, "failed to create symlink: %s", zFile);
6873     }else if( S_ISDIR(mode) ){
6874       ctxErrorMsg(context, "failed to create directory: %s", zFile);
6875     }else{
6876       ctxErrorMsg(context, "failed to write file: %s", zFile);
6877     }
6878   }
6879 }
6880 
6881 /*
6882 ** SQL function:   lsmode(MODE)
6883 **
6884 ** Given a numberic st_mode from stat(), convert it into a human-readable
6885 ** text string in the style of "ls -l".
6886 */
6887 static void lsModeFunc(
6888   sqlite3_context *context,
6889   int argc,
6890   sqlite3_value **argv
6891 ){
6892   int i;
6893   int iMode = sqlite3_value_int(argv[0]);
6894   char z[16];
6895   (void)argc;
6896   if( S_ISLNK(iMode) ){
6897     z[0] = 'l';
6898   }else if( S_ISREG(iMode) ){
6899     z[0] = '-';
6900   }else if( S_ISDIR(iMode) ){
6901     z[0] = 'd';
6902   }else{
6903     z[0] = '?';
6904   }
6905   for(i=0; i<3; i++){
6906     int m = (iMode >> ((2-i)*3));
6907     char *a = &z[1 + i*3];
6908     a[0] = (m & 0x4) ? 'r' : '-';
6909     a[1] = (m & 0x2) ? 'w' : '-';
6910     a[2] = (m & 0x1) ? 'x' : '-';
6911   }
6912   z[10] = '\0';
6913   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
6914 }
6915 
6916 #ifndef SQLITE_OMIT_VIRTUALTABLE
6917 
6918 /*
6919 ** Cursor type for recursively iterating through a directory structure.
6920 */
6921 typedef struct fsdir_cursor fsdir_cursor;
6922 typedef struct FsdirLevel FsdirLevel;
6923 
6924 struct FsdirLevel {
6925   DIR *pDir;                 /* From opendir() */
6926   char *zDir;                /* Name of directory (nul-terminated) */
6927 };
6928 
6929 struct fsdir_cursor {
6930   sqlite3_vtab_cursor base;  /* Base class - must be first */
6931 
6932   int nLvl;                  /* Number of entries in aLvl[] array */
6933   int iLvl;                  /* Index of current entry */
6934   FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
6935 
6936   const char *zBase;
6937   int nBase;
6938 
6939   struct stat sStat;         /* Current lstat() results */
6940   char *zPath;               /* Path to current entry */
6941   sqlite3_int64 iRowid;      /* Current rowid */
6942 };
6943 
6944 typedef struct fsdir_tab fsdir_tab;
6945 struct fsdir_tab {
6946   sqlite3_vtab base;         /* Base class - must be first */
6947 };
6948 
6949 /*
6950 ** Construct a new fsdir virtual table object.
6951 */
6952 static int fsdirConnect(
6953   sqlite3 *db,
6954   void *pAux,
6955   int argc, const char *const*argv,
6956   sqlite3_vtab **ppVtab,
6957   char **pzErr
6958 ){
6959   fsdir_tab *pNew = 0;
6960   int rc;
6961   (void)pAux;
6962   (void)argc;
6963   (void)argv;
6964   (void)pzErr;
6965   rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
6966   if( rc==SQLITE_OK ){
6967     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
6968     if( pNew==0 ) return SQLITE_NOMEM;
6969     memset(pNew, 0, sizeof(*pNew));
6970     sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
6971   }
6972   *ppVtab = (sqlite3_vtab*)pNew;
6973   return rc;
6974 }
6975 
6976 /*
6977 ** This method is the destructor for fsdir vtab objects.
6978 */
6979 static int fsdirDisconnect(sqlite3_vtab *pVtab){
6980   sqlite3_free(pVtab);
6981   return SQLITE_OK;
6982 }
6983 
6984 /*
6985 ** Constructor for a new fsdir_cursor object.
6986 */
6987 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
6988   fsdir_cursor *pCur;
6989   (void)p;
6990   pCur = sqlite3_malloc( sizeof(*pCur) );
6991   if( pCur==0 ) return SQLITE_NOMEM;
6992   memset(pCur, 0, sizeof(*pCur));
6993   pCur->iLvl = -1;
6994   *ppCursor = &pCur->base;
6995   return SQLITE_OK;
6996 }
6997 
6998 /*
6999 ** Reset a cursor back to the state it was in when first returned
7000 ** by fsdirOpen().
7001 */
7002 static void fsdirResetCursor(fsdir_cursor *pCur){
7003   int i;
7004   for(i=0; i<=pCur->iLvl; i++){
7005     FsdirLevel *pLvl = &pCur->aLvl[i];
7006     if( pLvl->pDir ) closedir(pLvl->pDir);
7007     sqlite3_free(pLvl->zDir);
7008   }
7009   sqlite3_free(pCur->zPath);
7010   sqlite3_free(pCur->aLvl);
7011   pCur->aLvl = 0;
7012   pCur->zPath = 0;
7013   pCur->zBase = 0;
7014   pCur->nBase = 0;
7015   pCur->nLvl = 0;
7016   pCur->iLvl = -1;
7017   pCur->iRowid = 1;
7018 }
7019 
7020 /*
7021 ** Destructor for an fsdir_cursor.
7022 */
7023 static int fsdirClose(sqlite3_vtab_cursor *cur){
7024   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7025 
7026   fsdirResetCursor(pCur);
7027   sqlite3_free(pCur);
7028   return SQLITE_OK;
7029 }
7030 
7031 /*
7032 ** Set the error message for the virtual table associated with cursor
7033 ** pCur to the results of vprintf(zFmt, ...).
7034 */
7035 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
7036   va_list ap;
7037   va_start(ap, zFmt);
7038   pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7039   va_end(ap);
7040 }
7041 
7042 
7043 /*
7044 ** Advance an fsdir_cursor to its next row of output.
7045 */
7046 static int fsdirNext(sqlite3_vtab_cursor *cur){
7047   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7048   mode_t m = pCur->sStat.st_mode;
7049 
7050   pCur->iRowid++;
7051   if( S_ISDIR(m) ){
7052     /* Descend into this directory */
7053     int iNew = pCur->iLvl + 1;
7054     FsdirLevel *pLvl;
7055     if( iNew>=pCur->nLvl ){
7056       int nNew = iNew+1;
7057       sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
7058       FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
7059       if( aNew==0 ) return SQLITE_NOMEM;
7060       memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
7061       pCur->aLvl = aNew;
7062       pCur->nLvl = nNew;
7063     }
7064     pCur->iLvl = iNew;
7065     pLvl = &pCur->aLvl[iNew];
7066 
7067     pLvl->zDir = pCur->zPath;
7068     pCur->zPath = 0;
7069     pLvl->pDir = opendir(pLvl->zDir);
7070     if( pLvl->pDir==0 ){
7071       fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
7072       return SQLITE_ERROR;
7073     }
7074   }
7075 
7076   while( pCur->iLvl>=0 ){
7077     FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
7078     struct dirent *pEntry = readdir(pLvl->pDir);
7079     if( pEntry ){
7080       if( pEntry->d_name[0]=='.' ){
7081        if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
7082        if( pEntry->d_name[1]=='\0' ) continue;
7083       }
7084       sqlite3_free(pCur->zPath);
7085       pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
7086       if( pCur->zPath==0 ) return SQLITE_NOMEM;
7087       if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7088         fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7089         return SQLITE_ERROR;
7090       }
7091       return SQLITE_OK;
7092     }
7093     closedir(pLvl->pDir);
7094     sqlite3_free(pLvl->zDir);
7095     pLvl->pDir = 0;
7096     pLvl->zDir = 0;
7097     pCur->iLvl--;
7098   }
7099 
7100   /* EOF */
7101   sqlite3_free(pCur->zPath);
7102   pCur->zPath = 0;
7103   return SQLITE_OK;
7104 }
7105 
7106 /*
7107 ** Return values of columns for the row at which the series_cursor
7108 ** is currently pointing.
7109 */
7110 static int fsdirColumn(
7111   sqlite3_vtab_cursor *cur,   /* The cursor */
7112   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7113   int i                       /* Which column to return */
7114 ){
7115   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7116   switch( i ){
7117     case FSDIR_COLUMN_NAME: {
7118       sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
7119       break;
7120     }
7121 
7122     case FSDIR_COLUMN_MODE:
7123       sqlite3_result_int64(ctx, pCur->sStat.st_mode);
7124       break;
7125 
7126     case FSDIR_COLUMN_MTIME:
7127       sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
7128       break;
7129 
7130     case FSDIR_COLUMN_DATA: {
7131       mode_t m = pCur->sStat.st_mode;
7132       if( S_ISDIR(m) ){
7133         sqlite3_result_null(ctx);
7134 #if !defined(_WIN32) && !defined(WIN32)
7135       }else if( S_ISLNK(m) ){
7136         char aStatic[64];
7137         char *aBuf = aStatic;
7138         sqlite3_int64 nBuf = 64;
7139         int n;
7140 
7141         while( 1 ){
7142           n = readlink(pCur->zPath, aBuf, nBuf);
7143           if( n<nBuf ) break;
7144           if( aBuf!=aStatic ) sqlite3_free(aBuf);
7145           nBuf = nBuf*2;
7146           aBuf = sqlite3_malloc64(nBuf);
7147           if( aBuf==0 ){
7148             sqlite3_result_error_nomem(ctx);
7149             return SQLITE_NOMEM;
7150           }
7151         }
7152 
7153         sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
7154         if( aBuf!=aStatic ) sqlite3_free(aBuf);
7155 #endif
7156       }else{
7157         readFileContents(ctx, pCur->zPath);
7158       }
7159     }
7160     case FSDIR_COLUMN_PATH:
7161     default: {
7162       /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
7163       ** always return their values as NULL */
7164       break;
7165     }
7166   }
7167   return SQLITE_OK;
7168 }
7169 
7170 /*
7171 ** Return the rowid for the current row. In this implementation, the
7172 ** first row returned is assigned rowid value 1, and each subsequent
7173 ** row a value 1 more than that of the previous.
7174 */
7175 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7176   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7177   *pRowid = pCur->iRowid;
7178   return SQLITE_OK;
7179 }
7180 
7181 /*
7182 ** Return TRUE if the cursor has been moved off of the last
7183 ** row of output.
7184 */
7185 static int fsdirEof(sqlite3_vtab_cursor *cur){
7186   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7187   return (pCur->zPath==0);
7188 }
7189 
7190 /*
7191 ** xFilter callback.
7192 **
7193 ** idxNum==1   PATH parameter only
7194 ** idxNum==2   Both PATH and DIR supplied
7195 */
7196 static int fsdirFilter(
7197   sqlite3_vtab_cursor *cur,
7198   int idxNum, const char *idxStr,
7199   int argc, sqlite3_value **argv
7200 ){
7201   const char *zDir = 0;
7202   fsdir_cursor *pCur = (fsdir_cursor*)cur;
7203   (void)idxStr;
7204   fsdirResetCursor(pCur);
7205 
7206   if( idxNum==0 ){
7207     fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
7208     return SQLITE_ERROR;
7209   }
7210 
7211   assert( argc==idxNum && (argc==1 || argc==2) );
7212   zDir = (const char*)sqlite3_value_text(argv[0]);
7213   if( zDir==0 ){
7214     fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
7215     return SQLITE_ERROR;
7216   }
7217   if( argc==2 ){
7218     pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
7219   }
7220   if( pCur->zBase ){
7221     pCur->nBase = (int)strlen(pCur->zBase)+1;
7222     pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
7223   }else{
7224     pCur->zPath = sqlite3_mprintf("%s", zDir);
7225   }
7226 
7227   if( pCur->zPath==0 ){
7228     return SQLITE_NOMEM;
7229   }
7230   if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7231     fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7232     return SQLITE_ERROR;
7233   }
7234 
7235   return SQLITE_OK;
7236 }
7237 
7238 /*
7239 ** SQLite will invoke this method one or more times while planning a query
7240 ** that uses the generate_series virtual table.  This routine needs to create
7241 ** a query plan for each invocation and compute an estimated cost for that
7242 ** plan.
7243 **
7244 ** In this implementation idxNum is used to represent the
7245 ** query plan.  idxStr is unused.
7246 **
7247 ** The query plan is represented by values of idxNum:
7248 **
7249 **  (1)  The path value is supplied by argv[0]
7250 **  (2)  Path is in argv[0] and dir is in argv[1]
7251 */
7252 static int fsdirBestIndex(
7253   sqlite3_vtab *tab,
7254   sqlite3_index_info *pIdxInfo
7255 ){
7256   int i;                 /* Loop over constraints */
7257   int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
7258   int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
7259   int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
7260   int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
7261   const struct sqlite3_index_constraint *pConstraint;
7262 
7263   (void)tab;
7264   pConstraint = pIdxInfo->aConstraint;
7265   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
7266     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
7267     switch( pConstraint->iColumn ){
7268       case FSDIR_COLUMN_PATH: {
7269         if( pConstraint->usable ){
7270           idxPath = i;
7271           seenPath = 0;
7272         }else if( idxPath<0 ){
7273           seenPath = 1;
7274         }
7275         break;
7276       }
7277       case FSDIR_COLUMN_DIR: {
7278         if( pConstraint->usable ){
7279           idxDir = i;
7280           seenDir = 0;
7281         }else if( idxDir<0 ){
7282           seenDir = 1;
7283         }
7284         break;
7285       }
7286     }
7287   }
7288   if( seenPath || seenDir ){
7289     /* If input parameters are unusable, disallow this plan */
7290     return SQLITE_CONSTRAINT;
7291   }
7292 
7293   if( idxPath<0 ){
7294     pIdxInfo->idxNum = 0;
7295     /* The pIdxInfo->estimatedCost should have been initialized to a huge
7296     ** number.  Leave it unchanged. */
7297     pIdxInfo->estimatedRows = 0x7fffffff;
7298   }else{
7299     pIdxInfo->aConstraintUsage[idxPath].omit = 1;
7300     pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
7301     if( idxDir>=0 ){
7302       pIdxInfo->aConstraintUsage[idxDir].omit = 1;
7303       pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
7304       pIdxInfo->idxNum = 2;
7305       pIdxInfo->estimatedCost = 10.0;
7306     }else{
7307       pIdxInfo->idxNum = 1;
7308       pIdxInfo->estimatedCost = 100.0;
7309     }
7310   }
7311 
7312   return SQLITE_OK;
7313 }
7314 
7315 /*
7316 ** Register the "fsdir" virtual table.
7317 */
7318 static int fsdirRegister(sqlite3 *db){
7319   static sqlite3_module fsdirModule = {
7320     0,                         /* iVersion */
7321     0,                         /* xCreate */
7322     fsdirConnect,              /* xConnect */
7323     fsdirBestIndex,            /* xBestIndex */
7324     fsdirDisconnect,           /* xDisconnect */
7325     0,                         /* xDestroy */
7326     fsdirOpen,                 /* xOpen - open a cursor */
7327     fsdirClose,                /* xClose - close a cursor */
7328     fsdirFilter,               /* xFilter - configure scan constraints */
7329     fsdirNext,                 /* xNext - advance a cursor */
7330     fsdirEof,                  /* xEof - check for end of scan */
7331     fsdirColumn,               /* xColumn - read data */
7332     fsdirRowid,                /* xRowid - read data */
7333     0,                         /* xUpdate */
7334     0,                         /* xBegin */
7335     0,                         /* xSync */
7336     0,                         /* xCommit */
7337     0,                         /* xRollback */
7338     0,                         /* xFindMethod */
7339     0,                         /* xRename */
7340     0,                         /* xSavepoint */
7341     0,                         /* xRelease */
7342     0,                         /* xRollbackTo */
7343     0,                         /* xShadowName */
7344     0                          /* xIntegrity */
7345   };
7346 
7347   int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
7348   return rc;
7349 }
7350 #else         /* SQLITE_OMIT_VIRTUALTABLE */
7351 # define fsdirRegister(x) SQLITE_OK
7352 #endif
7353 
7354 #ifdef _WIN32
7355 
7356 #endif
7357 int sqlite3_fileio_init(
7358   sqlite3 *db,
7359   char **pzErrMsg,
7360   const sqlite3_api_routines *pApi
7361 ){
7362   int rc = SQLITE_OK;
7363   SQLITE_EXTENSION_INIT2(pApi);
7364   (void)pzErrMsg;  /* Unused parameter */
7365   rc = sqlite3_create_function(db, "readfile", 1,
7366                                SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
7367                                readfileFunc, 0, 0);
7368   if( rc==SQLITE_OK ){
7369     rc = sqlite3_create_function(db, "writefile", -1,
7370                                  SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
7371                                  writefileFunc, 0, 0);
7372   }
7373   if( rc==SQLITE_OK ){
7374     rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
7375                                  lsModeFunc, 0, 0);
7376   }
7377   if( rc==SQLITE_OK ){
7378     rc = fsdirRegister(db);
7379   }
7380   return rc;
7381 }
7382 
7383 #if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
7384 /* To allow a standalone DLL, make test_windirent.c use the same
7385  * redefined SQLite API calls as the above extension code does.
7386  * Just pull in this .c to accomplish this. As a beneficial side
7387  * effect, this extension becomes a single translation unit. */
7388 #  include "test_windirent.c"
7389 #endif
7390 
7391 /************************* End ../ext/misc/fileio.c ********************/
7392 /************************* Begin ../ext/misc/completion.c ******************/
7393 /*
7394 ** 2017-07-10
7395 **
7396 ** The author disclaims copyright to this source code.  In place of
7397 ** a legal notice, here is a blessing:
7398 **
7399 **    May you do good and not evil.
7400 **    May you find forgiveness for yourself and forgive others.
7401 **    May you share freely, never taking more than you give.
7402 **
7403 *************************************************************************
7404 **
7405 ** This file implements an eponymous virtual table that returns suggested
7406 ** completions for a partial SQL input.
7407 **
7408 ** Suggested usage:
7409 **
7410 **     SELECT DISTINCT candidate COLLATE nocase
7411 **       FROM completion($prefix,$wholeline)
7412 **      ORDER BY 1;
7413 **
7414 ** The two query parameters are optional.  $prefix is the text of the
7415 ** current word being typed and that is to be completed.  $wholeline is
7416 ** the complete input line, used for context.
7417 **
7418 ** The raw completion() table might return the same candidate multiple
7419 ** times, for example if the same column name is used to two or more
7420 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
7421 ** the DISTINCT and ORDER BY are recommended.
7422 **
7423 ** This virtual table operates at the speed of human typing, and so there
7424 ** is no attempt to make it fast.  Even a slow implementation will be much
7425 ** faster than any human can type.
7426 **
7427 */
7428 /* #include "sqlite3ext.h" */
7429 SQLITE_EXTENSION_INIT1
7430 #include <assert.h>
7431 #include <string.h>
7432 #include <ctype.h>
7433 
7434 #ifndef SQLITE_OMIT_VIRTUALTABLE
7435 
7436 /* completion_vtab is a subclass of sqlite3_vtab which will
7437 ** serve as the underlying representation of a completion virtual table
7438 */
7439 typedef struct completion_vtab completion_vtab;
7440 struct completion_vtab {
7441   sqlite3_vtab base;  /* Base class - must be first */
7442   sqlite3 *db;        /* Database connection for this completion vtab */
7443 };
7444 
7445 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
7446 ** serve as the underlying representation of a cursor that scans
7447 ** over rows of the result
7448 */
7449 typedef struct completion_cursor completion_cursor;
7450 struct completion_cursor {
7451   sqlite3_vtab_cursor base;  /* Base class - must be first */
7452   sqlite3 *db;               /* Database connection for this cursor */
7453   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
7454   char *zPrefix;             /* The prefix for the word we want to complete */
7455   char *zLine;               /* The whole that we want to complete */
7456   const char *zCurrentRow;   /* Current output row */
7457   int szRow;                 /* Length of the zCurrentRow string */
7458   sqlite3_stmt *pStmt;       /* Current statement */
7459   sqlite3_int64 iRowid;      /* The rowid */
7460   int ePhase;                /* Current phase */
7461   int j;                     /* inter-phase counter */
7462 };
7463 
7464 /* Values for ePhase:
7465 */
7466 #define COMPLETION_FIRST_PHASE   1
7467 #define COMPLETION_KEYWORDS      1
7468 #define COMPLETION_PRAGMAS       2
7469 #define COMPLETION_FUNCTIONS     3
7470 #define COMPLETION_COLLATIONS    4
7471 #define COMPLETION_INDEXES       5
7472 #define COMPLETION_TRIGGERS      6
7473 #define COMPLETION_DATABASES     7
7474 #define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
7475 #define COMPLETION_COLUMNS       9
7476 #define COMPLETION_MODULES       10
7477 #define COMPLETION_EOF           11
7478 
7479 /*
7480 ** The completionConnect() method is invoked to create a new
7481 ** completion_vtab that describes the completion virtual table.
7482 **
7483 ** Think of this routine as the constructor for completion_vtab objects.
7484 **
7485 ** All this routine needs to do is:
7486 **
7487 **    (1) Allocate the completion_vtab object and initialize all fields.
7488 **
7489 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
7490 **        result set of queries against completion will look like.
7491 */
7492 static int completionConnect(
7493   sqlite3 *db,
7494   void *pAux,
7495   int argc, const char *const*argv,
7496   sqlite3_vtab **ppVtab,
7497   char **pzErr
7498 ){
7499   completion_vtab *pNew;
7500   int rc;
7501 
7502   (void)(pAux);    /* Unused parameter */
7503   (void)(argc);    /* Unused parameter */
7504   (void)(argv);    /* Unused parameter */
7505   (void)(pzErr);   /* Unused parameter */
7506 
7507 /* Column numbers */
7508 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
7509 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
7510 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
7511 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
7512 
7513   sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
7514   rc = sqlite3_declare_vtab(db,
7515       "CREATE TABLE x("
7516       "  candidate TEXT,"
7517       "  prefix TEXT HIDDEN,"
7518       "  wholeline TEXT HIDDEN,"
7519       "  phase INT HIDDEN"        /* Used for debugging only */
7520       ")");
7521   if( rc==SQLITE_OK ){
7522     pNew = sqlite3_malloc( sizeof(*pNew) );
7523     *ppVtab = (sqlite3_vtab*)pNew;
7524     if( pNew==0 ) return SQLITE_NOMEM;
7525     memset(pNew, 0, sizeof(*pNew));
7526     pNew->db = db;
7527   }
7528   return rc;
7529 }
7530 
7531 /*
7532 ** This method is the destructor for completion_cursor objects.
7533 */
7534 static int completionDisconnect(sqlite3_vtab *pVtab){
7535   sqlite3_free(pVtab);
7536   return SQLITE_OK;
7537 }
7538 
7539 /*
7540 ** Constructor for a new completion_cursor object.
7541 */
7542 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
7543   completion_cursor *pCur;
7544   pCur = sqlite3_malloc( sizeof(*pCur) );
7545   if( pCur==0 ) return SQLITE_NOMEM;
7546   memset(pCur, 0, sizeof(*pCur));
7547   pCur->db = ((completion_vtab*)p)->db;
7548   *ppCursor = &pCur->base;
7549   return SQLITE_OK;
7550 }
7551 
7552 /*
7553 ** Reset the completion_cursor.
7554 */
7555 static void completionCursorReset(completion_cursor *pCur){
7556   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
7557   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
7558   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
7559   pCur->j = 0;
7560 }
7561 
7562 /*
7563 ** Destructor for a completion_cursor.
7564 */
7565 static int completionClose(sqlite3_vtab_cursor *cur){
7566   completionCursorReset((completion_cursor*)cur);
7567   sqlite3_free(cur);
7568   return SQLITE_OK;
7569 }
7570 
7571 /*
7572 ** Advance a completion_cursor to its next row of output.
7573 **
7574 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
7575 ** record the current state of the scan.  This routine sets ->zCurrentRow
7576 ** to the current row of output and then returns.  If no more rows remain,
7577 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
7578 ** table that has reached the end of its scan.
7579 **
7580 ** The current implementation just lists potential identifiers and
7581 ** keywords and filters them by zPrefix.  Future enhancements should
7582 ** take zLine into account to try to restrict the set of identifiers and
7583 ** keywords based on what would be legal at the current point of input.
7584 */
7585 static int completionNext(sqlite3_vtab_cursor *cur){
7586   completion_cursor *pCur = (completion_cursor*)cur;
7587   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
7588   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
7589   pCur->iRowid++;
7590   while( pCur->ePhase!=COMPLETION_EOF ){
7591     switch( pCur->ePhase ){
7592       case COMPLETION_KEYWORDS: {
7593         if( pCur->j >= sqlite3_keyword_count() ){
7594           pCur->zCurrentRow = 0;
7595           pCur->ePhase = COMPLETION_DATABASES;
7596         }else{
7597           sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
7598         }
7599         iCol = -1;
7600         break;
7601       }
7602       case COMPLETION_DATABASES: {
7603         if( pCur->pStmt==0 ){
7604           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
7605                              &pCur->pStmt, 0);
7606         }
7607         iCol = 1;
7608         eNextPhase = COMPLETION_TABLES;
7609         break;
7610       }
7611       case COMPLETION_TABLES: {
7612         if( pCur->pStmt==0 ){
7613           sqlite3_stmt *pS2;
7614           char *zSql = 0;
7615           const char *zSep = "";
7616           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
7617           while( sqlite3_step(pS2)==SQLITE_ROW ){
7618             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
7619             zSql = sqlite3_mprintf(
7620                "%z%s"
7621                "SELECT name FROM \"%w\".sqlite_schema",
7622                zSql, zSep, zDb
7623             );
7624             if( zSql==0 ) return SQLITE_NOMEM;
7625             zSep = " UNION ";
7626           }
7627           sqlite3_finalize(pS2);
7628           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
7629           sqlite3_free(zSql);
7630         }
7631         iCol = 0;
7632         eNextPhase = COMPLETION_COLUMNS;
7633         break;
7634       }
7635       case COMPLETION_COLUMNS: {
7636         if( pCur->pStmt==0 ){
7637           sqlite3_stmt *pS2;
7638           char *zSql = 0;
7639           const char *zSep = "";
7640           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
7641           while( sqlite3_step(pS2)==SQLITE_ROW ){
7642             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
7643             zSql = sqlite3_mprintf(
7644                "%z%s"
7645                "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
7646                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
7647                " WHERE sm.type='table'",
7648                zSql, zSep, zDb, zDb
7649             );
7650             if( zSql==0 ) return SQLITE_NOMEM;
7651             zSep = " UNION ";
7652           }
7653           sqlite3_finalize(pS2);
7654           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
7655           sqlite3_free(zSql);
7656         }
7657         iCol = 0;
7658         eNextPhase = COMPLETION_EOF;
7659         break;
7660       }
7661     }
7662     if( iCol<0 ){
7663       /* This case is when the phase presets zCurrentRow */
7664       if( pCur->zCurrentRow==0 ) continue;
7665     }else{
7666       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
7667         /* Extract the next row of content */
7668         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
7669         pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
7670       }else{
7671         /* When all rows are finished, advance to the next phase */
7672         sqlite3_finalize(pCur->pStmt);
7673         pCur->pStmt = 0;
7674         pCur->ePhase = eNextPhase;
7675         continue;
7676       }
7677     }
7678     if( pCur->nPrefix==0 ) break;
7679     if( pCur->nPrefix<=pCur->szRow
7680      && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
7681     ){
7682       break;
7683     }
7684   }
7685 
7686   return SQLITE_OK;
7687 }
7688 
7689 /*
7690 ** Return values of columns for the row at which the completion_cursor
7691 ** is currently pointing.
7692 */
7693 static int completionColumn(
7694   sqlite3_vtab_cursor *cur,   /* The cursor */
7695   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7696   int i                       /* Which column to return */
7697 ){
7698   completion_cursor *pCur = (completion_cursor*)cur;
7699   switch( i ){
7700     case COMPLETION_COLUMN_CANDIDATE: {
7701       sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
7702       break;
7703     }
7704     case COMPLETION_COLUMN_PREFIX: {
7705       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
7706       break;
7707     }
7708     case COMPLETION_COLUMN_WHOLELINE: {
7709       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
7710       break;
7711     }
7712     case COMPLETION_COLUMN_PHASE: {
7713       sqlite3_result_int(ctx, pCur->ePhase);
7714       break;
7715     }
7716   }
7717   return SQLITE_OK;
7718 }
7719 
7720 /*
7721 ** Return the rowid for the current row.  In this implementation, the
7722 ** rowid is the same as the output value.
7723 */
7724 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7725   completion_cursor *pCur = (completion_cursor*)cur;
7726   *pRowid = pCur->iRowid;
7727   return SQLITE_OK;
7728 }
7729 
7730 /*
7731 ** Return TRUE if the cursor has been moved off of the last
7732 ** row of output.
7733 */
7734 static int completionEof(sqlite3_vtab_cursor *cur){
7735   completion_cursor *pCur = (completion_cursor*)cur;
7736   return pCur->ePhase >= COMPLETION_EOF;
7737 }
7738 
7739 /*
7740 ** This method is called to "rewind" the completion_cursor object back
7741 ** to the first row of output.  This method is always called at least
7742 ** once prior to any call to completionColumn() or completionRowid() or
7743 ** completionEof().
7744 */
7745 static int completionFilter(
7746   sqlite3_vtab_cursor *pVtabCursor,
7747   int idxNum, const char *idxStr,
7748   int argc, sqlite3_value **argv
7749 ){
7750   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
7751   int iArg = 0;
7752   (void)(idxStr);   /* Unused parameter */
7753   (void)(argc);     /* Unused parameter */
7754   completionCursorReset(pCur);
7755   if( idxNum & 1 ){
7756     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
7757     if( pCur->nPrefix>0 ){
7758       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
7759       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
7760     }
7761     iArg = 1;
7762   }
7763   if( idxNum & 2 ){
7764     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
7765     if( pCur->nLine>0 ){
7766       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
7767       if( pCur->zLine==0 ) return SQLITE_NOMEM;
7768     }
7769   }
7770   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
7771     int i = pCur->nLine;
7772     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
7773       i--;
7774     }
7775     pCur->nPrefix = pCur->nLine - i;
7776     if( pCur->nPrefix>0 ){
7777       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
7778       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
7779     }
7780   }
7781   pCur->iRowid = 0;
7782   pCur->ePhase = COMPLETION_FIRST_PHASE;
7783   return completionNext(pVtabCursor);
7784 }
7785 
7786 /*
7787 ** SQLite will invoke this method one or more times while planning a query
7788 ** that uses the completion virtual table.  This routine needs to create
7789 ** a query plan for each invocation and compute an estimated cost for that
7790 ** plan.
7791 **
7792 ** There are two hidden parameters that act as arguments to the table-valued
7793 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
7794 ** is available and bit 1 is set if "wholeline" is available.
7795 */
7796 static int completionBestIndex(
7797   sqlite3_vtab *tab,
7798   sqlite3_index_info *pIdxInfo
7799 ){
7800   int i;                 /* Loop over constraints */
7801   int idxNum = 0;        /* The query plan bitmask */
7802   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
7803   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
7804   int nArg = 0;          /* Number of arguments that completeFilter() expects */
7805   const struct sqlite3_index_constraint *pConstraint;
7806 
7807   (void)(tab);    /* Unused parameter */
7808   pConstraint = pIdxInfo->aConstraint;
7809   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
7810     if( pConstraint->usable==0 ) continue;
7811     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
7812     switch( pConstraint->iColumn ){
7813       case COMPLETION_COLUMN_PREFIX:
7814         prefixIdx = i;
7815         idxNum |= 1;
7816         break;
7817       case COMPLETION_COLUMN_WHOLELINE:
7818         wholelineIdx = i;
7819         idxNum |= 2;
7820         break;
7821     }
7822   }
7823   if( prefixIdx>=0 ){
7824     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
7825     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
7826   }
7827   if( wholelineIdx>=0 ){
7828     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
7829     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
7830   }
7831   pIdxInfo->idxNum = idxNum;
7832   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
7833   pIdxInfo->estimatedRows = 500 - 100*nArg;
7834   return SQLITE_OK;
7835 }
7836 
7837 /*
7838 ** This following structure defines all the methods for the
7839 ** completion virtual table.
7840 */
7841 static sqlite3_module completionModule = {
7842   0,                         /* iVersion */
7843   0,                         /* xCreate */
7844   completionConnect,         /* xConnect */
7845   completionBestIndex,       /* xBestIndex */
7846   completionDisconnect,      /* xDisconnect */
7847   0,                         /* xDestroy */
7848   completionOpen,            /* xOpen - open a cursor */
7849   completionClose,           /* xClose - close a cursor */
7850   completionFilter,          /* xFilter - configure scan constraints */
7851   completionNext,            /* xNext - advance a cursor */
7852   completionEof,             /* xEof - check for end of scan */
7853   completionColumn,          /* xColumn - read data */
7854   completionRowid,           /* xRowid - read data */
7855   0,                         /* xUpdate */
7856   0,                         /* xBegin */
7857   0,                         /* xSync */
7858   0,                         /* xCommit */
7859   0,                         /* xRollback */
7860   0,                         /* xFindMethod */
7861   0,                         /* xRename */
7862   0,                         /* xSavepoint */
7863   0,                         /* xRelease */
7864   0,                         /* xRollbackTo */
7865   0,                         /* xShadowName */
7866   0                          /* xIntegrity */
7867 };
7868 
7869 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7870 
7871 int sqlite3CompletionVtabInit(sqlite3 *db){
7872   int rc = SQLITE_OK;
7873 #ifndef SQLITE_OMIT_VIRTUALTABLE
7874   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
7875 #endif
7876   return rc;
7877 }
7878 
7879 #ifdef _WIN32
7880 
7881 #endif
7882 int sqlite3_completion_init(
7883   sqlite3 *db,
7884   char **pzErrMsg,
7885   const sqlite3_api_routines *pApi
7886 ){
7887   int rc = SQLITE_OK;
7888   SQLITE_EXTENSION_INIT2(pApi);
7889   (void)(pzErrMsg);  /* Unused parameter */
7890 #ifndef SQLITE_OMIT_VIRTUALTABLE
7891   rc = sqlite3CompletionVtabInit(db);
7892 #endif
7893   return rc;
7894 }
7895 
7896 /************************* End ../ext/misc/completion.c ********************/
7897 /************************* Begin ../ext/misc/appendvfs.c ******************/
7898 /*
7899 ** 2017-10-20
7900 **
7901 ** The author disclaims copyright to this source code.  In place of
7902 ** a legal notice, here is a blessing:
7903 **
7904 **    May you do good and not evil.
7905 **    May you find forgiveness for yourself and forgive others.
7906 **    May you share freely, never taking more than you give.
7907 **
7908 ******************************************************************************
7909 **
7910 ** This file implements a VFS shim that allows an SQLite database to be
7911 ** appended onto the end of some other file, such as an executable.
7912 **
7913 ** A special record must appear at the end of the file that identifies the
7914 ** file as an appended database and provides the offset to the first page
7915 ** of the exposed content. (Or, it is the length of the content prefix.)
7916 ** For best performance page 1 should be located at a disk page boundary,
7917 ** though that is not required.
7918 **
7919 ** When opening a database using this VFS, the connection might treat
7920 ** the file as an ordinary SQLite database, or it might treat it as a
7921 ** database appended onto some other file.  The decision is made by
7922 ** applying the following rules in order:
7923 **
7924 **  (1)  An empty file is an ordinary database.
7925 **
7926 **  (2)  If the file ends with the appendvfs trailer string
7927 **       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
7928 **
7929 **  (3)  If the file begins with the standard SQLite prefix string
7930 **       "SQLite format 3", that file is an ordinary database.
7931 **
7932 **  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
7933 **       set, then a new database is appended to the already existing file.
7934 **
7935 **  (5)  Otherwise, SQLITE_CANTOPEN is returned.
7936 **
7937 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
7938 ** the file containing the database is limited to 1GiB. (1073741824 bytes)
7939 ** This VFS will not read or write past the 1GiB mark.  This restriction
7940 ** might be lifted in future versions.  For now, if you need a larger
7941 ** database, then keep it in a separate file.
7942 **
7943 ** If the file being opened is a plain database (not an appended one), then
7944 ** this shim is a pass-through into the default underlying VFS. (rule 3)
7945 **/
7946 /* #include "sqlite3ext.h" */
7947 SQLITE_EXTENSION_INIT1
7948 #include <string.h>
7949 #include <assert.h>
7950 
7951 /* The append mark at the end of the database is:
7952 **
7953 **     Start-Of-SQLite3-NNNNNNNN
7954 **     123456789 123456789 12345
7955 **
7956 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
7957 ** the offset to page 1, and also the length of the prefix content.
7958 */
7959 #define APND_MARK_PREFIX     "Start-Of-SQLite3-"
7960 #define APND_MARK_PREFIX_SZ  17
7961 #define APND_MARK_FOS_SZ      8
7962 #define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
7963 
7964 /*
7965 ** Maximum size of the combined prefix + database + append-mark.  This
7966 ** must be less than 0x40000000 to avoid locking issues on Windows.
7967 */
7968 #define APND_MAX_SIZE  (0x40000000)
7969 
7970 /*
7971 ** Try to align the database to an even multiple of APND_ROUNDUP bytes.
7972 */
7973 #ifndef APND_ROUNDUP
7974 #define APND_ROUNDUP 4096
7975 #endif
7976 #define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
7977 #define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
7978 
7979 /*
7980 ** Forward declaration of objects used by this utility
7981 */
7982 typedef struct sqlite3_vfs ApndVfs;
7983 typedef struct ApndFile ApndFile;
7984 
7985 /* Access to a lower-level VFS that (might) implement dynamic loading,
7986 ** access to randomness, etc.
7987 */
7988 #define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
7989 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
7990 
7991 /* An open appendvfs file
7992 **
7993 ** An instance of this structure describes the appended database file.
7994 ** A separate sqlite3_file object is always appended. The appended
7995 ** sqlite3_file object (which can be accessed using ORIGFILE()) describes
7996 ** the entire file, including the prefix, the database, and the
7997 ** append-mark.
7998 **
7999 ** The structure of an AppendVFS database is like this:
8000 **
8001 **   +-------------+---------+----------+-------------+
8002 **   | prefix-file | padding | database | append-mark |
8003 **   +-------------+---------+----------+-------------+
8004 **                           ^          ^
8005 **                           |          |
8006 **                         iPgOne      iMark
8007 **
8008 **
8009 ** "prefix file" -  file onto which the database has been appended.
8010 ** "padding"     -  zero or more bytes inserted so that "database"
8011 **                  starts on an APND_ROUNDUP boundary
8012 ** "database"    -  The SQLite database file
8013 ** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8014 **                  the offset from the start of prefix-file to the start
8015 **                  of "database".
8016 **
8017 ** The size of the database is iMark - iPgOne.
8018 **
8019 ** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8020 ** of iPgOne stored as a big-ending 64-bit integer.
8021 **
8022 ** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
8023 ** Or, iMark is -1 to indicate that it has not yet been written.
8024 */
8025 struct ApndFile {
8026   sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
8027   sqlite3_int64 iPgOne;     /* Offset to the start of the database */
8028   sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
8029   /* Always followed by another sqlite3_file that describes the whole file */
8030 };
8031 
8032 /*
8033 ** Methods for ApndFile
8034 */
8035 static int apndClose(sqlite3_file*);
8036 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
8037 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
8038 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
8039 static int apndSync(sqlite3_file*, int flags);
8040 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
8041 static int apndLock(sqlite3_file*, int);
8042 static int apndUnlock(sqlite3_file*, int);
8043 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
8044 static int apndFileControl(sqlite3_file*, int op, void *pArg);
8045 static int apndSectorSize(sqlite3_file*);
8046 static int apndDeviceCharacteristics(sqlite3_file*);
8047 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
8048 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
8049 static void apndShmBarrier(sqlite3_file*);
8050 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
8051 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
8052 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
8053 
8054 /*
8055 ** Methods for ApndVfs
8056 */
8057 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
8058 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
8059 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
8060 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
8061 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
8062 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
8063 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
8064 static void apndDlClose(sqlite3_vfs*, void*);
8065 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
8066 static int apndSleep(sqlite3_vfs*, int microseconds);
8067 static int apndCurrentTime(sqlite3_vfs*, double*);
8068 static int apndGetLastError(sqlite3_vfs*, int, char *);
8069 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
8070 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
8071 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
8072 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
8073 
8074 static sqlite3_vfs apnd_vfs = {
8075   3,                            /* iVersion (set when registered) */
8076   0,                            /* szOsFile (set when registered) */
8077   1024,                         /* mxPathname */
8078   0,                            /* pNext */
8079   "apndvfs",                    /* zName */
8080   0,                            /* pAppData (set when registered) */
8081   apndOpen,                     /* xOpen */
8082   apndDelete,                   /* xDelete */
8083   apndAccess,                   /* xAccess */
8084   apndFullPathname,             /* xFullPathname */
8085   apndDlOpen,                   /* xDlOpen */
8086   apndDlError,                  /* xDlError */
8087   apndDlSym,                    /* xDlSym */
8088   apndDlClose,                  /* xDlClose */
8089   apndRandomness,               /* xRandomness */
8090   apndSleep,                    /* xSleep */
8091   apndCurrentTime,              /* xCurrentTime */
8092   apndGetLastError,             /* xGetLastError */
8093   apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
8094   apndSetSystemCall,            /* xSetSystemCall */
8095   apndGetSystemCall,            /* xGetSystemCall */
8096   apndNextSystemCall            /* xNextSystemCall */
8097 };
8098 
8099 static const sqlite3_io_methods apnd_io_methods = {
8100   3,                              /* iVersion */
8101   apndClose,                      /* xClose */
8102   apndRead,                       /* xRead */
8103   apndWrite,                      /* xWrite */
8104   apndTruncate,                   /* xTruncate */
8105   apndSync,                       /* xSync */
8106   apndFileSize,                   /* xFileSize */
8107   apndLock,                       /* xLock */
8108   apndUnlock,                     /* xUnlock */
8109   apndCheckReservedLock,          /* xCheckReservedLock */
8110   apndFileControl,                /* xFileControl */
8111   apndSectorSize,                 /* xSectorSize */
8112   apndDeviceCharacteristics,      /* xDeviceCharacteristics */
8113   apndShmMap,                     /* xShmMap */
8114   apndShmLock,                    /* xShmLock */
8115   apndShmBarrier,                 /* xShmBarrier */
8116   apndShmUnmap,                   /* xShmUnmap */
8117   apndFetch,                      /* xFetch */
8118   apndUnfetch                     /* xUnfetch */
8119 };
8120 
8121 /*
8122 ** Close an apnd-file.
8123 */
8124 static int apndClose(sqlite3_file *pFile){
8125   pFile = ORIGFILE(pFile);
8126   return pFile->pMethods->xClose(pFile);
8127 }
8128 
8129 /*
8130 ** Read data from an apnd-file.
8131 */
8132 static int apndRead(
8133   sqlite3_file *pFile,
8134   void *zBuf,
8135   int iAmt,
8136   sqlite_int64 iOfst
8137 ){
8138   ApndFile *paf = (ApndFile *)pFile;
8139   pFile = ORIGFILE(pFile);
8140   return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8141 }
8142 
8143 /*
8144 ** Add the append-mark onto what should become the end of the file.
8145 *  If and only if this succeeds, internal ApndFile.iMark is updated.
8146 *  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8147 */
8148 static int apndWriteMark(
8149   ApndFile *paf,
8150   sqlite3_file *pFile,
8151   sqlite_int64 iWriteEnd
8152 ){
8153   sqlite_int64 iPgOne = paf->iPgOne;
8154   unsigned char a[APND_MARK_SIZE];
8155   int i = APND_MARK_FOS_SZ;
8156   int rc;
8157   assert(pFile == ORIGFILE(paf));
8158   memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
8159   while( --i >= 0 ){
8160     a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
8161     iPgOne >>= 8;
8162   }
8163   iWriteEnd += paf->iPgOne;
8164   if( SQLITE_OK==(rc = pFile->pMethods->xWrite
8165                   (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
8166     paf->iMark = iWriteEnd;
8167   }
8168   return rc;
8169 }
8170 
8171 /*
8172 ** Write data to an apnd-file.
8173 */
8174 static int apndWrite(
8175   sqlite3_file *pFile,
8176   const void *zBuf,
8177   int iAmt,
8178   sqlite_int64 iOfst
8179 ){
8180   ApndFile *paf = (ApndFile *)pFile;
8181   sqlite_int64 iWriteEnd = iOfst + iAmt;
8182   if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
8183   pFile = ORIGFILE(pFile);
8184   /* If append-mark is absent or will be overwritten, write it. */
8185   if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
8186     int rc = apndWriteMark(paf, pFile, iWriteEnd);
8187     if( SQLITE_OK!=rc ) return rc;
8188   }
8189   return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8190 }
8191 
8192 /*
8193 ** Truncate an apnd-file.
8194 */
8195 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
8196   ApndFile *paf = (ApndFile *)pFile;
8197   pFile = ORIGFILE(pFile);
8198   /* The append mark goes out first so truncate failure does not lose it. */
8199   if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
8200   /* Truncate underlying file just past append mark */
8201   return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
8202 }
8203 
8204 /*
8205 ** Sync an apnd-file.
8206 */
8207 static int apndSync(sqlite3_file *pFile, int flags){
8208   pFile = ORIGFILE(pFile);
8209   return pFile->pMethods->xSync(pFile, flags);
8210 }
8211 
8212 /*
8213 ** Return the current file-size of an apnd-file.
8214 ** If the append mark is not yet there, the file-size is 0.
8215 */
8216 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
8217   ApndFile *paf = (ApndFile *)pFile;
8218   *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
8219   return SQLITE_OK;
8220 }
8221 
8222 /*
8223 ** Lock an apnd-file.
8224 */
8225 static int apndLock(sqlite3_file *pFile, int eLock){
8226   pFile = ORIGFILE(pFile);
8227   return pFile->pMethods->xLock(pFile, eLock);
8228 }
8229 
8230 /*
8231 ** Unlock an apnd-file.
8232 */
8233 static int apndUnlock(sqlite3_file *pFile, int eLock){
8234   pFile = ORIGFILE(pFile);
8235   return pFile->pMethods->xUnlock(pFile, eLock);
8236 }
8237 
8238 /*
8239 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
8240 */
8241 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
8242   pFile = ORIGFILE(pFile);
8243   return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
8244 }
8245 
8246 /*
8247 ** File control method. For custom operations on an apnd-file.
8248 */
8249 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
8250   ApndFile *paf = (ApndFile *)pFile;
8251   int rc;
8252   pFile = ORIGFILE(pFile);
8253   if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
8254   rc = pFile->pMethods->xFileControl(pFile, op, pArg);
8255   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
8256     *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
8257   }
8258   return rc;
8259 }
8260 
8261 /*
8262 ** Return the sector-size in bytes for an apnd-file.
8263 */
8264 static int apndSectorSize(sqlite3_file *pFile){
8265   pFile = ORIGFILE(pFile);
8266   return pFile->pMethods->xSectorSize(pFile);
8267 }
8268 
8269 /*
8270 ** Return the device characteristic flags supported by an apnd-file.
8271 */
8272 static int apndDeviceCharacteristics(sqlite3_file *pFile){
8273   pFile = ORIGFILE(pFile);
8274   return pFile->pMethods->xDeviceCharacteristics(pFile);
8275 }
8276 
8277 /* Create a shared memory file mapping */
8278 static int apndShmMap(
8279   sqlite3_file *pFile,
8280   int iPg,
8281   int pgsz,
8282   int bExtend,
8283   void volatile **pp
8284 ){
8285   pFile = ORIGFILE(pFile);
8286   return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
8287 }
8288 
8289 /* Perform locking on a shared-memory segment */
8290 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
8291   pFile = ORIGFILE(pFile);
8292   return pFile->pMethods->xShmLock(pFile,offset,n,flags);
8293 }
8294 
8295 /* Memory barrier operation on shared memory */
8296 static void apndShmBarrier(sqlite3_file *pFile){
8297   pFile = ORIGFILE(pFile);
8298   pFile->pMethods->xShmBarrier(pFile);
8299 }
8300 
8301 /* Unmap a shared memory segment */
8302 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
8303   pFile = ORIGFILE(pFile);
8304   return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
8305 }
8306 
8307 /* Fetch a page of a memory-mapped file */
8308 static int apndFetch(
8309   sqlite3_file *pFile,
8310   sqlite3_int64 iOfst,
8311   int iAmt,
8312   void **pp
8313 ){
8314   ApndFile *p = (ApndFile *)pFile;
8315   if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
8316     return SQLITE_IOERR; /* Cannot read what is not yet there. */
8317   }
8318   pFile = ORIGFILE(pFile);
8319   return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
8320 }
8321 
8322 /* Release a memory-mapped page */
8323 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
8324   ApndFile *p = (ApndFile *)pFile;
8325   pFile = ORIGFILE(pFile);
8326   return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
8327 }
8328 
8329 /*
8330 ** Try to read the append-mark off the end of a file.  Return the
8331 ** start of the appended database if the append-mark is present.
8332 ** If there is no valid append-mark, return -1;
8333 **
8334 ** An append-mark is only valid if the NNNNNNNN start-of-database offset
8335 ** indicates that the appended database contains at least one page.  The
8336 ** start-of-database value must be a multiple of 512.
8337 */
8338 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
8339   int rc, i;
8340   sqlite3_int64 iMark;
8341   int msbs = 8 * (APND_MARK_FOS_SZ-1);
8342   unsigned char a[APND_MARK_SIZE];
8343 
8344   if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
8345   rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
8346   if( rc ) return -1;
8347   if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
8348   iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
8349   for(i=1; i<8; i++){
8350     msbs -= 8;
8351     iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
8352   }
8353   if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
8354   if( iMark & 0x1ff ) return -1;
8355   return iMark;
8356 }
8357 
8358 static const char apvfsSqliteHdr[] = "SQLite format 3";
8359 /*
8360 ** Check to see if the file is an appendvfs SQLite database file.
8361 ** Return true iff it is such. Parameter sz is the file's size.
8362 */
8363 static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
8364   int rc;
8365   char zHdr[16];
8366   sqlite3_int64 iMark = apndReadMark(sz, pFile);
8367   if( iMark>=0 ){
8368     /* If file has the correct end-marker, the expected odd size, and the
8369     ** SQLite DB type marker where the end-marker puts it, then it
8370     ** is an appendvfs database.
8371     */
8372     rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
8373     if( SQLITE_OK==rc
8374      && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
8375      && (sz & 0x1ff) == APND_MARK_SIZE
8376      && sz>=512+APND_MARK_SIZE
8377     ){
8378       return 1; /* It's an appendvfs database */
8379     }
8380   }
8381   return 0;
8382 }
8383 
8384 /*
8385 ** Check to see if the file is an ordinary SQLite database file.
8386 ** Return true iff so. Parameter sz is the file's size.
8387 */
8388 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
8389   char zHdr[16];
8390   if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
8391    || (sz & 0x1ff) != 0
8392    || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
8393    || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
8394   ){
8395     return 0;
8396   }else{
8397     return 1;
8398   }
8399 }
8400 
8401 /*
8402 ** Open an apnd file handle.
8403 */
8404 static int apndOpen(
8405   sqlite3_vfs *pApndVfs,
8406   const char *zName,
8407   sqlite3_file *pFile,
8408   int flags,
8409   int *pOutFlags
8410 ){
8411   ApndFile *pApndFile = (ApndFile*)pFile;
8412   sqlite3_file *pBaseFile = ORIGFILE(pFile);
8413   sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
8414   int rc;
8415   sqlite3_int64 sz = 0;
8416   if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
8417     /* The appendvfs is not to be used for transient or temporary databases.
8418     ** Just use the base VFS open to initialize the given file object and
8419     ** open the underlying file. (Appendvfs is then unused for this file.)
8420     */
8421     return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
8422   }
8423   memset(pApndFile, 0, sizeof(ApndFile));
8424   pFile->pMethods = &apnd_io_methods;
8425   pApndFile->iMark = -1;    /* Append mark not yet written */
8426 
8427   rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
8428   if( rc==SQLITE_OK ){
8429     rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
8430     if( rc ){
8431       pBaseFile->pMethods->xClose(pBaseFile);
8432     }
8433   }
8434   if( rc ){
8435     pFile->pMethods = 0;
8436     return rc;
8437   }
8438   if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
8439     /* The file being opened appears to be just an ordinary DB. Copy
8440     ** the base dispatch-table so this instance mimics the base VFS.
8441     */
8442     memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
8443     return SQLITE_OK;
8444   }
8445   pApndFile->iPgOne = apndReadMark(sz, pFile);
8446   if( pApndFile->iPgOne>=0 ){
8447     pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
8448     return SQLITE_OK;
8449   }
8450   if( (flags & SQLITE_OPEN_CREATE)==0 ){
8451     pBaseFile->pMethods->xClose(pBaseFile);
8452     rc = SQLITE_CANTOPEN;
8453     pFile->pMethods = 0;
8454   }else{
8455     /* Round newly added appendvfs location to #define'd page boundary.
8456     ** Note that nothing has yet been written to the underlying file.
8457     ** The append mark will be written along with first content write.
8458     ** Until then, paf->iMark value indicates it is not yet written.
8459     */
8460     pApndFile->iPgOne = APND_START_ROUNDUP(sz);
8461   }
8462   return rc;
8463 }
8464 
8465 /*
8466 ** Delete an apnd file.
8467 ** For an appendvfs, this could mean delete the appendvfs portion,
8468 ** leaving the appendee as it was before it gained an appendvfs.
8469 ** For now, this code deletes the underlying file too.
8470 */
8471 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
8472   return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
8473 }
8474 
8475 /*
8476 ** All other VFS methods are pass-thrus.
8477 */
8478 static int apndAccess(
8479   sqlite3_vfs *pVfs,
8480   const char *zPath,
8481   int flags,
8482   int *pResOut
8483 ){
8484   return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
8485 }
8486 static int apndFullPathname(
8487   sqlite3_vfs *pVfs,
8488   const char *zPath,
8489   int nOut,
8490   char *zOut
8491 ){
8492   return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
8493 }
8494 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
8495   return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
8496 }
8497 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
8498   ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
8499 }
8500 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
8501   return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
8502 }
8503 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
8504   ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
8505 }
8506 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
8507   return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
8508 }
8509 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
8510   return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
8511 }
8512 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
8513   return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
8514 }
8515 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
8516   return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
8517 }
8518 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
8519   return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
8520 }
8521 static int apndSetSystemCall(
8522   sqlite3_vfs *pVfs,
8523   const char *zName,
8524   sqlite3_syscall_ptr pCall
8525 ){
8526   return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
8527 }
8528 static sqlite3_syscall_ptr apndGetSystemCall(
8529   sqlite3_vfs *pVfs,
8530   const char *zName
8531 ){
8532   return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
8533 }
8534 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
8535   return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
8536 }
8537 
8538 
8539 #ifdef _WIN32
8540 
8541 #endif
8542 /*
8543 ** This routine is called when the extension is loaded.
8544 ** Register the new VFS.
8545 */
8546 int sqlite3_appendvfs_init(
8547   sqlite3 *db,
8548   char **pzErrMsg,
8549   const sqlite3_api_routines *pApi
8550 ){
8551   int rc = SQLITE_OK;
8552   sqlite3_vfs *pOrig;
8553   SQLITE_EXTENSION_INIT2(pApi);
8554   (void)pzErrMsg;
8555   (void)db;
8556   pOrig = sqlite3_vfs_find(0);
8557   if( pOrig==0 ) return SQLITE_ERROR;
8558   apnd_vfs.iVersion = pOrig->iVersion;
8559   apnd_vfs.pAppData = pOrig;
8560   apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
8561   rc = sqlite3_vfs_register(&apnd_vfs, 0);
8562 #ifdef APPENDVFS_TEST
8563   if( rc==SQLITE_OK ){
8564     rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
8565   }
8566 #endif
8567   if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
8568   return rc;
8569 }
8570 
8571 /************************* End ../ext/misc/appendvfs.c ********************/
8572 #endif
8573 #ifdef SQLITE_HAVE_ZLIB
8574 /************************* Begin ../ext/misc/zipfile.c ******************/
8575 /*
8576 ** 2017-12-26
8577 **
8578 ** The author disclaims copyright to this source code.  In place of
8579 ** a legal notice, here is a blessing:
8580 **
8581 **    May you do good and not evil.
8582 **    May you find forgiveness for yourself and forgive others.
8583 **    May you share freely, never taking more than you give.
8584 **
8585 ******************************************************************************
8586 **
8587 ** This file implements a virtual table for reading and writing ZIP archive
8588 ** files.
8589 **
8590 ** Usage example:
8591 **
8592 **     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
8593 **
8594 ** Current limitations:
8595 **
8596 **    *  No support for encryption
8597 **    *  No support for ZIP archives spanning multiple files
8598 **    *  No support for zip64 extensions
8599 **    *  Only the "inflate/deflate" (zlib) compression method is supported
8600 */
8601 /* #include "sqlite3ext.h" */
8602 SQLITE_EXTENSION_INIT1
8603 #include <stdio.h>
8604 #include <string.h>
8605 #include <assert.h>
8606 #include <stdint.h>
8607 
8608 #include <zlib.h>
8609 
8610 #ifndef SQLITE_OMIT_VIRTUALTABLE
8611 
8612 #ifndef SQLITE_AMALGAMATION
8613 
8614 #ifndef UINT32_TYPE
8615 # ifdef HAVE_UINT32_T
8616 #  define UINT32_TYPE uint32_t
8617 # else
8618 #  define UINT32_TYPE unsigned int
8619 # endif
8620 #endif
8621 #ifndef UINT16_TYPE
8622 # ifdef HAVE_UINT16_T
8623 #  define UINT16_TYPE uint16_t
8624 # else
8625 #  define UINT16_TYPE unsigned short int
8626 # endif
8627 #endif
8628 /* typedef sqlite3_int64 i64; */
8629 /* typedef unsigned char u8; */
8630 /* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
8631 /* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
8632 #define MIN(a,b) ((a)<(b) ? (a) : (b))
8633 
8634 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
8635 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
8636 #endif
8637 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
8638 # define ALWAYS(X)      (1)
8639 # define NEVER(X)       (0)
8640 #elif !defined(NDEBUG)
8641 # define ALWAYS(X)      ((X)?1:(assert(0),0))
8642 # define NEVER(X)       ((X)?(assert(0),1):0)
8643 #else
8644 # define ALWAYS(X)      (X)
8645 # define NEVER(X)       (X)
8646 #endif
8647 
8648 #endif   /* SQLITE_AMALGAMATION */
8649 
8650 /*
8651 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
8652 **
8653 ** In some ways it would be better to obtain these values from system
8654 ** header files. But, the dependency is undesirable and (a) these
8655 ** have been stable for decades, (b) the values are part of POSIX and
8656 ** are also made explicit in [man stat], and (c) are part of the
8657 ** file format for zip archives.
8658 */
8659 #ifndef S_IFDIR
8660 # define S_IFDIR 0040000
8661 #endif
8662 #ifndef S_IFREG
8663 # define S_IFREG 0100000
8664 #endif
8665 #ifndef S_IFLNK
8666 # define S_IFLNK 0120000
8667 #endif
8668 
8669 static const char ZIPFILE_SCHEMA[] =
8670   "CREATE TABLE y("
8671     "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
8672     "mode,"              /* 1: POSIX mode for file */
8673     "mtime,"             /* 2: Last modification time (secs since 1970)*/
8674     "sz,"                /* 3: Size of object */
8675     "rawdata,"           /* 4: Raw data */
8676     "data,"              /* 5: Uncompressed data */
8677     "method,"            /* 6: Compression method (integer) */
8678     "z HIDDEN"           /* 7: Name of zip file */
8679   ") WITHOUT ROWID;";
8680 
8681 #define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
8682 #define ZIPFILE_BUFFER_SIZE (64*1024)
8683 
8684 
8685 /*
8686 ** Magic numbers used to read and write zip files.
8687 **
8688 ** ZIPFILE_NEWENTRY_MADEBY:
8689 **   Use this value for the "version-made-by" field in new zip file
8690 **   entries. The upper byte indicates "unix", and the lower byte
8691 **   indicates that the zip file matches pkzip specification 3.0.
8692 **   This is what info-zip seems to do.
8693 **
8694 ** ZIPFILE_NEWENTRY_REQUIRED:
8695 **   Value for "version-required-to-extract" field of new entries.
8696 **   Version 2.0 is required to support folders and deflate compression.
8697 **
8698 ** ZIPFILE_NEWENTRY_FLAGS:
8699 **   Value for "general-purpose-bit-flags" field of new entries. Bit
8700 **   11 means "utf-8 filename and comment".
8701 **
8702 ** ZIPFILE_SIGNATURE_CDS:
8703 **   First 4 bytes of a valid CDS record.
8704 **
8705 ** ZIPFILE_SIGNATURE_LFH:
8706 **   First 4 bytes of a valid LFH record.
8707 **
8708 ** ZIPFILE_SIGNATURE_EOCD
8709 **   First 4 bytes of a valid EOCD record.
8710 */
8711 #define ZIPFILE_EXTRA_TIMESTAMP   0x5455
8712 #define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
8713 #define ZIPFILE_NEWENTRY_REQUIRED 20
8714 #define ZIPFILE_NEWENTRY_FLAGS    0x800
8715 #define ZIPFILE_SIGNATURE_CDS     0x02014b50
8716 #define ZIPFILE_SIGNATURE_LFH     0x04034b50
8717 #define ZIPFILE_SIGNATURE_EOCD    0x06054b50
8718 
8719 /*
8720 ** The sizes of the fixed-size part of each of the three main data
8721 ** structures in a zip archive.
8722 */
8723 #define ZIPFILE_LFH_FIXED_SZ      30
8724 #define ZIPFILE_EOCD_FIXED_SZ     22
8725 #define ZIPFILE_CDS_FIXED_SZ      46
8726 
8727 /*
8728 *** 4.3.16  End of central directory record:
8729 ***
8730 ***   end of central dir signature    4 bytes  (0x06054b50)
8731 ***   number of this disk             2 bytes
8732 ***   number of the disk with the
8733 ***   start of the central directory  2 bytes
8734 ***   total number of entries in the
8735 ***   central directory on this disk  2 bytes
8736 ***   total number of entries in
8737 ***   the central directory           2 bytes
8738 ***   size of the central directory   4 bytes
8739 ***   offset of start of central
8740 ***   directory with respect to
8741 ***   the starting disk number        4 bytes
8742 ***   .ZIP file comment length        2 bytes
8743 ***   .ZIP file comment       (variable size)
8744 */
8745 typedef struct ZipfileEOCD ZipfileEOCD;
8746 struct ZipfileEOCD {
8747   u16 iDisk;
8748   u16 iFirstDisk;
8749   u16 nEntry;
8750   u16 nEntryTotal;
8751   u32 nSize;
8752   u32 iOffset;
8753 };
8754 
8755 /*
8756 *** 4.3.12  Central directory structure:
8757 ***
8758 *** ...
8759 ***
8760 ***   central file header signature   4 bytes  (0x02014b50)
8761 ***   version made by                 2 bytes
8762 ***   version needed to extract       2 bytes
8763 ***   general purpose bit flag        2 bytes
8764 ***   compression method              2 bytes
8765 ***   last mod file time              2 bytes
8766 ***   last mod file date              2 bytes
8767 ***   crc-32                          4 bytes
8768 ***   compressed size                 4 bytes
8769 ***   uncompressed size               4 bytes
8770 ***   file name length                2 bytes
8771 ***   extra field length              2 bytes
8772 ***   file comment length             2 bytes
8773 ***   disk number start               2 bytes
8774 ***   internal file attributes        2 bytes
8775 ***   external file attributes        4 bytes
8776 ***   relative offset of local header 4 bytes
8777 */
8778 typedef struct ZipfileCDS ZipfileCDS;
8779 struct ZipfileCDS {
8780   u16 iVersionMadeBy;
8781   u16 iVersionExtract;
8782   u16 flags;
8783   u16 iCompression;
8784   u16 mTime;
8785   u16 mDate;
8786   u32 crc32;
8787   u32 szCompressed;
8788   u32 szUncompressed;
8789   u16 nFile;
8790   u16 nExtra;
8791   u16 nComment;
8792   u16 iDiskStart;
8793   u16 iInternalAttr;
8794   u32 iExternalAttr;
8795   u32 iOffset;
8796   char *zFile;                    /* Filename (sqlite3_malloc()) */
8797 };
8798 
8799 /*
8800 *** 4.3.7  Local file header:
8801 ***
8802 ***   local file header signature     4 bytes  (0x04034b50)
8803 ***   version needed to extract       2 bytes
8804 ***   general purpose bit flag        2 bytes
8805 ***   compression method              2 bytes
8806 ***   last mod file time              2 bytes
8807 ***   last mod file date              2 bytes
8808 ***   crc-32                          4 bytes
8809 ***   compressed size                 4 bytes
8810 ***   uncompressed size               4 bytes
8811 ***   file name length                2 bytes
8812 ***   extra field length              2 bytes
8813 ***
8814 */
8815 typedef struct ZipfileLFH ZipfileLFH;
8816 struct ZipfileLFH {
8817   u16 iVersionExtract;
8818   u16 flags;
8819   u16 iCompression;
8820   u16 mTime;
8821   u16 mDate;
8822   u32 crc32;
8823   u32 szCompressed;
8824   u32 szUncompressed;
8825   u16 nFile;
8826   u16 nExtra;
8827 };
8828 
8829 typedef struct ZipfileEntry ZipfileEntry;
8830 struct ZipfileEntry {
8831   ZipfileCDS cds;            /* Parsed CDS record */
8832   u32 mUnixTime;             /* Modification time, in UNIX format */
8833   u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
8834   i64 iDataOff;              /* Offset to data in file (if aData==0) */
8835   u8 *aData;                 /* cds.szCompressed bytes of compressed data */
8836   ZipfileEntry *pNext;       /* Next element in in-memory CDS */
8837 };
8838 
8839 /*
8840 ** Cursor type for zipfile tables.
8841 */
8842 typedef struct ZipfileCsr ZipfileCsr;
8843 struct ZipfileCsr {
8844   sqlite3_vtab_cursor base;  /* Base class - must be first */
8845   i64 iId;                   /* Cursor ID */
8846   u8 bEof;                   /* True when at EOF */
8847   u8 bNoop;                  /* If next xNext() call is no-op */
8848 
8849   /* Used outside of write transactions */
8850   FILE *pFile;               /* Zip file */
8851   i64 iNextOff;              /* Offset of next record in central directory */
8852   ZipfileEOCD eocd;          /* Parse of central directory record */
8853 
8854   ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
8855   ZipfileEntry *pCurrent;    /* Current entry */
8856   ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
8857 };
8858 
8859 typedef struct ZipfileTab ZipfileTab;
8860 struct ZipfileTab {
8861   sqlite3_vtab base;         /* Base class - must be first */
8862   char *zFile;               /* Zip file this table accesses (may be NULL) */
8863   sqlite3 *db;               /* Host database connection */
8864   u8 *aBuffer;               /* Temporary buffer used for various tasks */
8865 
8866   ZipfileCsr *pCsrList;      /* List of cursors */
8867   i64 iNextCsrid;
8868 
8869   /* The following are used by write transactions only */
8870   ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
8871   ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
8872   FILE *pWriteFd;            /* File handle open on zip archive */
8873   i64 szCurrent;             /* Current size of zip archive */
8874   i64 szOrig;                /* Size of archive at start of transaction */
8875 };
8876 
8877 /*
8878 ** Set the error message contained in context ctx to the results of
8879 ** vprintf(zFmt, ...).
8880 */
8881 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
8882   char *zMsg = 0;
8883   va_list ap;
8884   va_start(ap, zFmt);
8885   zMsg = sqlite3_vmprintf(zFmt, ap);
8886   sqlite3_result_error(ctx, zMsg, -1);
8887   sqlite3_free(zMsg);
8888   va_end(ap);
8889 }
8890 
8891 /*
8892 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
8893 ** is not quoted, do nothing.
8894 */
8895 static void zipfileDequote(char *zIn){
8896   char q = zIn[0];
8897   if( q=='"' || q=='\'' || q=='`' || q=='[' ){
8898     int iIn = 1;
8899     int iOut = 0;
8900     if( q=='[' ) q = ']';
8901     while( ALWAYS(zIn[iIn]) ){
8902       char c = zIn[iIn++];
8903       if( c==q && zIn[iIn++]!=q ) break;
8904       zIn[iOut++] = c;
8905     }
8906     zIn[iOut] = '\0';
8907   }
8908 }
8909 
8910 /*
8911 ** Construct a new ZipfileTab virtual table object.
8912 **
8913 **   argv[0]   -> module name  ("zipfile")
8914 **   argv[1]   -> database name
8915 **   argv[2]   -> table name
8916 **   argv[...] -> "column name" and other module argument fields.
8917 */
8918 static int zipfileConnect(
8919   sqlite3 *db,
8920   void *pAux,
8921   int argc, const char *const*argv,
8922   sqlite3_vtab **ppVtab,
8923   char **pzErr
8924 ){
8925   int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
8926   int nFile = 0;
8927   const char *zFile = 0;
8928   ZipfileTab *pNew = 0;
8929   int rc;
8930   (void)pAux;
8931 
8932   /* If the table name is not "zipfile", require that the argument be
8933   ** specified. This stops zipfile tables from being created as:
8934   **
8935   **   CREATE VIRTUAL TABLE zzz USING zipfile();
8936   **
8937   ** It does not prevent:
8938   **
8939   **   CREATE VIRTUAL TABLE zipfile USING zipfile();
8940   */
8941   assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
8942   if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
8943     *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
8944     return SQLITE_ERROR;
8945   }
8946 
8947   if( argc>3 ){
8948     zFile = argv[3];
8949     nFile = (int)strlen(zFile)+1;
8950   }
8951 
8952   rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
8953   if( rc==SQLITE_OK ){
8954     pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
8955     if( pNew==0 ) return SQLITE_NOMEM;
8956     memset(pNew, 0, nByte+nFile);
8957     pNew->db = db;
8958     pNew->aBuffer = (u8*)&pNew[1];
8959     if( zFile ){
8960       pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
8961       memcpy(pNew->zFile, zFile, nFile);
8962       zipfileDequote(pNew->zFile);
8963     }
8964   }
8965   sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
8966   *ppVtab = (sqlite3_vtab*)pNew;
8967   return rc;
8968 }
8969 
8970 /*
8971 ** Free the ZipfileEntry structure indicated by the only argument.
8972 */
8973 static void zipfileEntryFree(ZipfileEntry *p){
8974   if( p ){
8975     sqlite3_free(p->cds.zFile);
8976     sqlite3_free(p);
8977   }
8978 }
8979 
8980 /*
8981 ** Release resources that should be freed at the end of a write
8982 ** transaction.
8983 */
8984 static void zipfileCleanupTransaction(ZipfileTab *pTab){
8985   ZipfileEntry *pEntry;
8986   ZipfileEntry *pNext;
8987 
8988   if( pTab->pWriteFd ){
8989     fclose(pTab->pWriteFd);
8990     pTab->pWriteFd = 0;
8991   }
8992   for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
8993     pNext = pEntry->pNext;
8994     zipfileEntryFree(pEntry);
8995   }
8996   pTab->pFirstEntry = 0;
8997   pTab->pLastEntry = 0;
8998   pTab->szCurrent = 0;
8999   pTab->szOrig = 0;
9000 }
9001 
9002 /*
9003 ** This method is the destructor for zipfile vtab objects.
9004 */
9005 static int zipfileDisconnect(sqlite3_vtab *pVtab){
9006   zipfileCleanupTransaction((ZipfileTab*)pVtab);
9007   sqlite3_free(pVtab);
9008   return SQLITE_OK;
9009 }
9010 
9011 /*
9012 ** Constructor for a new ZipfileCsr object.
9013 */
9014 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9015   ZipfileTab *pTab = (ZipfileTab*)p;
9016   ZipfileCsr *pCsr;
9017   pCsr = sqlite3_malloc(sizeof(*pCsr));
9018   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
9019   if( pCsr==0 ){
9020     return SQLITE_NOMEM;
9021   }
9022   memset(pCsr, 0, sizeof(*pCsr));
9023   pCsr->iId = ++pTab->iNextCsrid;
9024   pCsr->pCsrNext = pTab->pCsrList;
9025   pTab->pCsrList = pCsr;
9026   return SQLITE_OK;
9027 }
9028 
9029 /*
9030 ** Reset a cursor back to the state it was in when first returned
9031 ** by zipfileOpen().
9032 */
9033 static void zipfileResetCursor(ZipfileCsr *pCsr){
9034   ZipfileEntry *p;
9035   ZipfileEntry *pNext;
9036 
9037   pCsr->bEof = 0;
9038   if( pCsr->pFile ){
9039     fclose(pCsr->pFile);
9040     pCsr->pFile = 0;
9041     zipfileEntryFree(pCsr->pCurrent);
9042     pCsr->pCurrent = 0;
9043   }
9044 
9045   for(p=pCsr->pFreeEntry; p; p=pNext){
9046     pNext = p->pNext;
9047     zipfileEntryFree(p);
9048   }
9049 }
9050 
9051 /*
9052 ** Destructor for an ZipfileCsr.
9053 */
9054 static int zipfileClose(sqlite3_vtab_cursor *cur){
9055   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9056   ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
9057   ZipfileCsr **pp;
9058   zipfileResetCursor(pCsr);
9059 
9060   /* Remove this cursor from the ZipfileTab.pCsrList list. */
9061   for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
9062   *pp = pCsr->pCsrNext;
9063 
9064   sqlite3_free(pCsr);
9065   return SQLITE_OK;
9066 }
9067 
9068 /*
9069 ** Set the error message for the virtual table associated with cursor
9070 ** pCsr to the results of vprintf(zFmt, ...).
9071 */
9072 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
9073   va_list ap;
9074   va_start(ap, zFmt);
9075   sqlite3_free(pTab->base.zErrMsg);
9076   pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
9077   va_end(ap);
9078 }
9079 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
9080   va_list ap;
9081   va_start(ap, zFmt);
9082   sqlite3_free(pCsr->base.pVtab->zErrMsg);
9083   pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
9084   va_end(ap);
9085 }
9086 
9087 /*
9088 ** Read nRead bytes of data from offset iOff of file pFile into buffer
9089 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
9090 ** otherwise.
9091 **
9092 ** If an error does occur, output variable (*pzErrmsg) may be set to point
9093 ** to an English language error message. It is the responsibility of the
9094 ** caller to eventually free this buffer using
9095 ** sqlite3_free().
9096 */
9097 static int zipfileReadData(
9098   FILE *pFile,                    /* Read from this file */
9099   u8 *aRead,                      /* Read into this buffer */
9100   int nRead,                      /* Number of bytes to read */
9101   i64 iOff,                       /* Offset to read from */
9102   char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
9103 ){
9104   size_t n;
9105   fseek(pFile, (long)iOff, SEEK_SET);
9106   n = fread(aRead, 1, nRead, pFile);
9107   if( (int)n!=nRead ){
9108     *pzErrmsg = sqlite3_mprintf("error in fread()");
9109     return SQLITE_ERROR;
9110   }
9111   return SQLITE_OK;
9112 }
9113 
9114 static int zipfileAppendData(
9115   ZipfileTab *pTab,
9116   const u8 *aWrite,
9117   int nWrite
9118 ){
9119   if( nWrite>0 ){
9120     size_t n = nWrite;
9121     fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
9122     n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
9123     if( (int)n!=nWrite ){
9124       pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
9125       return SQLITE_ERROR;
9126     }
9127     pTab->szCurrent += nWrite;
9128   }
9129   return SQLITE_OK;
9130 }
9131 
9132 /*
9133 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9134 */
9135 static u16 zipfileGetU16(const u8 *aBuf){
9136   return (aBuf[1] << 8) + aBuf[0];
9137 }
9138 
9139 /*
9140 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9141 */
9142 static u32 zipfileGetU32(const u8 *aBuf){
9143   if( aBuf==0 ) return 0;
9144   return ((u32)(aBuf[3]) << 24)
9145        + ((u32)(aBuf[2]) << 16)
9146        + ((u32)(aBuf[1]) <<  8)
9147        + ((u32)(aBuf[0]) <<  0);
9148 }
9149 
9150 /*
9151 ** Write a 16-bit little endiate integer into buffer aBuf.
9152 */
9153 static void zipfilePutU16(u8 *aBuf, u16 val){
9154   aBuf[0] = val & 0xFF;
9155   aBuf[1] = (val>>8) & 0xFF;
9156 }
9157 
9158 /*
9159 ** Write a 32-bit little endiate integer into buffer aBuf.
9160 */
9161 static void zipfilePutU32(u8 *aBuf, u32 val){
9162   aBuf[0] = val & 0xFF;
9163   aBuf[1] = (val>>8) & 0xFF;
9164   aBuf[2] = (val>>16) & 0xFF;
9165   aBuf[3] = (val>>24) & 0xFF;
9166 }
9167 
9168 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9169 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9170 
9171 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
9172 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
9173 
9174 /*
9175 ** Magic numbers used to read CDS records.
9176 */
9177 #define ZIPFILE_CDS_NFILE_OFF        28
9178 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
9179 
9180 /*
9181 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
9182 ** if the record is not well-formed, or SQLITE_OK otherwise.
9183 */
9184 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
9185   u8 *aRead = aBuf;
9186   u32 sig = zipfileRead32(aRead);
9187   int rc = SQLITE_OK;
9188   if( sig!=ZIPFILE_SIGNATURE_CDS ){
9189     rc = SQLITE_ERROR;
9190   }else{
9191     pCDS->iVersionMadeBy = zipfileRead16(aRead);
9192     pCDS->iVersionExtract = zipfileRead16(aRead);
9193     pCDS->flags = zipfileRead16(aRead);
9194     pCDS->iCompression = zipfileRead16(aRead);
9195     pCDS->mTime = zipfileRead16(aRead);
9196     pCDS->mDate = zipfileRead16(aRead);
9197     pCDS->crc32 = zipfileRead32(aRead);
9198     pCDS->szCompressed = zipfileRead32(aRead);
9199     pCDS->szUncompressed = zipfileRead32(aRead);
9200     assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
9201     pCDS->nFile = zipfileRead16(aRead);
9202     pCDS->nExtra = zipfileRead16(aRead);
9203     pCDS->nComment = zipfileRead16(aRead);
9204     pCDS->iDiskStart = zipfileRead16(aRead);
9205     pCDS->iInternalAttr = zipfileRead16(aRead);
9206     pCDS->iExternalAttr = zipfileRead32(aRead);
9207     pCDS->iOffset = zipfileRead32(aRead);
9208     assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
9209   }
9210 
9211   return rc;
9212 }
9213 
9214 /*
9215 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
9216 ** if the record is not well-formed, or SQLITE_OK otherwise.
9217 */
9218 static int zipfileReadLFH(
9219   u8 *aBuffer,
9220   ZipfileLFH *pLFH
9221 ){
9222   u8 *aRead = aBuffer;
9223   int rc = SQLITE_OK;
9224 
9225   u32 sig = zipfileRead32(aRead);
9226   if( sig!=ZIPFILE_SIGNATURE_LFH ){
9227     rc = SQLITE_ERROR;
9228   }else{
9229     pLFH->iVersionExtract = zipfileRead16(aRead);
9230     pLFH->flags = zipfileRead16(aRead);
9231     pLFH->iCompression = zipfileRead16(aRead);
9232     pLFH->mTime = zipfileRead16(aRead);
9233     pLFH->mDate = zipfileRead16(aRead);
9234     pLFH->crc32 = zipfileRead32(aRead);
9235     pLFH->szCompressed = zipfileRead32(aRead);
9236     pLFH->szUncompressed = zipfileRead32(aRead);
9237     pLFH->nFile = zipfileRead16(aRead);
9238     pLFH->nExtra = zipfileRead16(aRead);
9239   }
9240   return rc;
9241 }
9242 
9243 
9244 /*
9245 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
9246 ** Scan through this buffer to find an "extra-timestamp" field. If one
9247 ** exists, extract the 32-bit modification-timestamp from it and store
9248 ** the value in output parameter *pmTime.
9249 **
9250 ** Zero is returned if no extra-timestamp record could be found (and so
9251 ** *pmTime is left unchanged), or non-zero otherwise.
9252 **
9253 ** The general format of an extra field is:
9254 **
9255 **   Header ID    2 bytes
9256 **   Data Size    2 bytes
9257 **   Data         N bytes
9258 */
9259 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
9260   int ret = 0;
9261   u8 *p = aExtra;
9262   u8 *pEnd = &aExtra[nExtra];
9263 
9264   while( p<pEnd ){
9265     u16 id = zipfileRead16(p);
9266     u16 nByte = zipfileRead16(p);
9267 
9268     switch( id ){
9269       case ZIPFILE_EXTRA_TIMESTAMP: {
9270         u8 b = p[0];
9271         if( b & 0x01 ){     /* 0x01 -> modtime is present */
9272           *pmTime = zipfileGetU32(&p[1]);
9273           ret = 1;
9274         }
9275         break;
9276       }
9277     }
9278 
9279     p += nByte;
9280   }
9281   return ret;
9282 }
9283 
9284 /*
9285 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
9286 ** fields of the CDS structure passed as the only argument to a 32-bit
9287 ** UNIX seconds-since-the-epoch timestamp. Return the result.
9288 **
9289 ** "Standard" MS-DOS time format:
9290 **
9291 **   File modification time:
9292 **     Bits 00-04: seconds divided by 2
9293 **     Bits 05-10: minute
9294 **     Bits 11-15: hour
9295 **   File modification date:
9296 **     Bits 00-04: day
9297 **     Bits 05-08: month (1-12)
9298 **     Bits 09-15: years from 1980
9299 **
9300 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
9301 */
9302 static u32 zipfileMtime(ZipfileCDS *pCDS){
9303   int Y,M,D,X1,X2,A,B,sec,min,hr;
9304   i64 JDsec;
9305   Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
9306   M = ((pCDS->mDate >> 5) & 0x0F);
9307   D = (pCDS->mDate & 0x1F);
9308   sec = (pCDS->mTime & 0x1F)*2;
9309   min = (pCDS->mTime >> 5) & 0x3F;
9310   hr = (pCDS->mTime >> 11) & 0x1F;
9311   if( M<=2 ){
9312     Y--;
9313     M += 12;
9314   }
9315   X1 = 36525*(Y+4716)/100;
9316   X2 = 306001*(M+1)/10000;
9317   A = Y/100;
9318   B = 2 - A + (A/4);
9319   JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
9320   return (u32)(JDsec - (i64)24405875*(i64)8640);
9321 }
9322 
9323 /*
9324 ** The opposite of zipfileMtime(). This function populates the mTime and
9325 ** mDate fields of the CDS structure passed as the first argument according
9326 ** to the UNIX timestamp value passed as the second.
9327 */
9328 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
9329   /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
9330   i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
9331 
9332   int A, B, C, D, E;
9333   int yr, mon, day;
9334   int hr, min, sec;
9335 
9336   A = (int)((JD - 1867216.25)/36524.25);
9337   A = (int)(JD + 1 + A - (A/4));
9338   B = A + 1524;
9339   C = (int)((B - 122.1)/365.25);
9340   D = (36525*(C&32767))/100;
9341   E = (int)((B-D)/30.6001);
9342 
9343   day = B - D - (int)(30.6001*E);
9344   mon = (E<14 ? E-1 : E-13);
9345   yr = mon>2 ? C-4716 : C-4715;
9346 
9347   hr = (mUnixTime % (24*60*60)) / (60*60);
9348   min = (mUnixTime % (60*60)) / 60;
9349   sec = (mUnixTime % 60);
9350 
9351   if( yr>=1980 ){
9352     pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
9353     pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
9354   }else{
9355     pCds->mDate = pCds->mTime = 0;
9356   }
9357 
9358   assert( mUnixTime<315507600
9359        || mUnixTime==zipfileMtime(pCds)
9360        || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
9361        /* || (mUnixTime % 2) */
9362   );
9363 }
9364 
9365 /*
9366 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
9367 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
9368 ** then pFile is a file-handle open on a zip file. In either case, this
9369 ** function creates a ZipfileEntry object based on the zip archive entry
9370 ** for which the CDS record is at offset iOff.
9371 **
9372 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
9373 ** the new object. Otherwise, an SQLite error code is returned and the
9374 ** final value of (*ppEntry) undefined.
9375 */
9376 static int zipfileGetEntry(
9377   ZipfileTab *pTab,               /* Store any error message here */
9378   const u8 *aBlob,                /* Pointer to in-memory file image */
9379   int nBlob,                      /* Size of aBlob[] in bytes */
9380   FILE *pFile,                    /* If aBlob==0, read from this file */
9381   i64 iOff,                       /* Offset of CDS record */
9382   ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
9383 ){
9384   u8 *aRead;
9385   char **pzErr = &pTab->base.zErrMsg;
9386   int rc = SQLITE_OK;
9387   (void)nBlob;
9388 
9389   if( aBlob==0 ){
9390     aRead = pTab->aBuffer;
9391     rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
9392   }else{
9393     aRead = (u8*)&aBlob[iOff];
9394   }
9395 
9396   if( rc==SQLITE_OK ){
9397     sqlite3_int64 nAlloc;
9398     ZipfileEntry *pNew;
9399 
9400     int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
9401     int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
9402     nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
9403 
9404     nAlloc = sizeof(ZipfileEntry) + nExtra;
9405     if( aBlob ){
9406       nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
9407     }
9408 
9409     pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
9410     if( pNew==0 ){
9411       rc = SQLITE_NOMEM;
9412     }else{
9413       memset(pNew, 0, sizeof(ZipfileEntry));
9414       rc = zipfileReadCDS(aRead, &pNew->cds);
9415       if( rc!=SQLITE_OK ){
9416         *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
9417       }else if( aBlob==0 ){
9418         rc = zipfileReadData(
9419             pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
9420         );
9421       }else{
9422         aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
9423       }
9424     }
9425 
9426     if( rc==SQLITE_OK ){
9427       u32 *pt = &pNew->mUnixTime;
9428       pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
9429       pNew->aExtra = (u8*)&pNew[1];
9430       memcpy(pNew->aExtra, &aRead[nFile], nExtra);
9431       if( pNew->cds.zFile==0 ){
9432         rc = SQLITE_NOMEM;
9433       }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
9434         pNew->mUnixTime = zipfileMtime(&pNew->cds);
9435       }
9436     }
9437 
9438     if( rc==SQLITE_OK ){
9439       static const int szFix = ZIPFILE_LFH_FIXED_SZ;
9440       ZipfileLFH lfh;
9441       if( pFile ){
9442         rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
9443       }else{
9444         aRead = (u8*)&aBlob[pNew->cds.iOffset];
9445       }
9446 
9447       if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
9448       if( rc==SQLITE_OK ){
9449         pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
9450         pNew->iDataOff += lfh.nFile + lfh.nExtra;
9451         if( aBlob && pNew->cds.szCompressed ){
9452           pNew->aData = &pNew->aExtra[nExtra];
9453           memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
9454         }
9455       }else{
9456         *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
9457             (int)pNew->cds.iOffset
9458         );
9459       }
9460     }
9461 
9462     if( rc!=SQLITE_OK ){
9463       zipfileEntryFree(pNew);
9464     }else{
9465       *ppEntry = pNew;
9466     }
9467   }
9468 
9469   return rc;
9470 }
9471 
9472 /*
9473 ** Advance an ZipfileCsr to its next row of output.
9474 */
9475 static int zipfileNext(sqlite3_vtab_cursor *cur){
9476   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9477   int rc = SQLITE_OK;
9478 
9479   if( pCsr->pFile ){
9480     i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
9481     zipfileEntryFree(pCsr->pCurrent);
9482     pCsr->pCurrent = 0;
9483     if( pCsr->iNextOff>=iEof ){
9484       pCsr->bEof = 1;
9485     }else{
9486       ZipfileEntry *p = 0;
9487       ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
9488       rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
9489       if( rc==SQLITE_OK ){
9490         pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
9491         pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
9492       }
9493       pCsr->pCurrent = p;
9494     }
9495   }else{
9496     if( !pCsr->bNoop ){
9497       pCsr->pCurrent = pCsr->pCurrent->pNext;
9498     }
9499     if( pCsr->pCurrent==0 ){
9500       pCsr->bEof = 1;
9501     }
9502   }
9503 
9504   pCsr->bNoop = 0;
9505   return rc;
9506 }
9507 
9508 static void zipfileFree(void *p) {
9509   sqlite3_free(p);
9510 }
9511 
9512 /*
9513 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
9514 ** size is nOut bytes. This function uncompresses the data and sets the
9515 ** return value in context pCtx to the result (a blob).
9516 **
9517 ** If an error occurs, an error code is left in pCtx instead.
9518 */
9519 static void zipfileInflate(
9520   sqlite3_context *pCtx,          /* Store result here */
9521   const u8 *aIn,                  /* Compressed data */
9522   int nIn,                        /* Size of buffer aIn[] in bytes */
9523   int nOut                        /* Expected output size */
9524 ){
9525   u8 *aRes = sqlite3_malloc(nOut);
9526   if( aRes==0 ){
9527     sqlite3_result_error_nomem(pCtx);
9528   }else{
9529     int err;
9530     z_stream str;
9531     memset(&str, 0, sizeof(str));
9532 
9533     str.next_in = (Byte*)aIn;
9534     str.avail_in = nIn;
9535     str.next_out = (Byte*)aRes;
9536     str.avail_out = nOut;
9537 
9538     err = inflateInit2(&str, -15);
9539     if( err!=Z_OK ){
9540       zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
9541     }else{
9542       err = inflate(&str, Z_NO_FLUSH);
9543       if( err!=Z_STREAM_END ){
9544         zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
9545       }else{
9546         sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
9547         aRes = 0;
9548       }
9549     }
9550     sqlite3_free(aRes);
9551     inflateEnd(&str);
9552   }
9553 }
9554 
9555 /*
9556 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
9557 ** compresses it and sets (*ppOut) to point to a buffer containing the
9558 ** compressed data. The caller is responsible for eventually calling
9559 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
9560 ** is set to the size of buffer (*ppOut) in bytes.
9561 **
9562 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
9563 ** code is returned and an error message left in virtual-table handle
9564 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
9565 ** case.
9566 */
9567 static int zipfileDeflate(
9568   const u8 *aIn, int nIn,         /* Input */
9569   u8 **ppOut, int *pnOut,         /* Output */
9570   char **pzErr                    /* OUT: Error message */
9571 ){
9572   int rc = SQLITE_OK;
9573   sqlite3_int64 nAlloc;
9574   z_stream str;
9575   u8 *aOut;
9576 
9577   memset(&str, 0, sizeof(str));
9578   str.next_in = (Bytef*)aIn;
9579   str.avail_in = nIn;
9580   deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
9581 
9582   nAlloc = deflateBound(&str, nIn);
9583   aOut = (u8*)sqlite3_malloc64(nAlloc);
9584   if( aOut==0 ){
9585     rc = SQLITE_NOMEM;
9586   }else{
9587     int res;
9588     str.next_out = aOut;
9589     str.avail_out = nAlloc;
9590     res = deflate(&str, Z_FINISH);
9591     if( res==Z_STREAM_END ){
9592       *ppOut = aOut;
9593       *pnOut = (int)str.total_out;
9594     }else{
9595       sqlite3_free(aOut);
9596       *pzErr = sqlite3_mprintf("zipfile: deflate() error");
9597       rc = SQLITE_ERROR;
9598     }
9599     deflateEnd(&str);
9600   }
9601 
9602   return rc;
9603 }
9604 
9605 
9606 /*
9607 ** Return values of columns for the row at which the series_cursor
9608 ** is currently pointing.
9609 */
9610 static int zipfileColumn(
9611   sqlite3_vtab_cursor *cur,   /* The cursor */
9612   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
9613   int i                       /* Which column to return */
9614 ){
9615   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9616   ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
9617   int rc = SQLITE_OK;
9618   switch( i ){
9619     case 0:   /* name */
9620       sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
9621       break;
9622     case 1:   /* mode */
9623       /* TODO: Whether or not the following is correct surely depends on
9624       ** the platform on which the archive was created.  */
9625       sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
9626       break;
9627     case 2: { /* mtime */
9628       sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
9629       break;
9630     }
9631     case 3: { /* sz */
9632       if( sqlite3_vtab_nochange(ctx)==0 ){
9633         sqlite3_result_int64(ctx, pCDS->szUncompressed);
9634       }
9635       break;
9636     }
9637     case 4:   /* rawdata */
9638       if( sqlite3_vtab_nochange(ctx) ) break;
9639     case 5: { /* data */
9640       if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
9641         int sz = pCDS->szCompressed;
9642         int szFinal = pCDS->szUncompressed;
9643         if( szFinal>0 ){
9644           u8 *aBuf;
9645           u8 *aFree = 0;
9646           if( pCsr->pCurrent->aData ){
9647             aBuf = pCsr->pCurrent->aData;
9648           }else{
9649             aBuf = aFree = sqlite3_malloc64(sz);
9650             if( aBuf==0 ){
9651               rc = SQLITE_NOMEM;
9652             }else{
9653               FILE *pFile = pCsr->pFile;
9654               if( pFile==0 ){
9655                 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
9656               }
9657               rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
9658                   &pCsr->base.pVtab->zErrMsg
9659               );
9660             }
9661           }
9662           if( rc==SQLITE_OK ){
9663             if( i==5 && pCDS->iCompression ){
9664               zipfileInflate(ctx, aBuf, sz, szFinal);
9665             }else{
9666               sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
9667             }
9668           }
9669           sqlite3_free(aFree);
9670         }else{
9671           /* Figure out if this is a directory or a zero-sized file. Consider
9672           ** it to be a directory either if the mode suggests so, or if
9673           ** the final character in the name is '/'.  */
9674           u32 mode = pCDS->iExternalAttr >> 16;
9675           if( !(mode & S_IFDIR)
9676            && pCDS->nFile>=1
9677            && pCDS->zFile[pCDS->nFile-1]!='/'
9678           ){
9679             sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
9680           }
9681         }
9682       }
9683       break;
9684     }
9685     case 6:   /* method */
9686       sqlite3_result_int(ctx, pCDS->iCompression);
9687       break;
9688     default:  /* z */
9689       assert( i==7 );
9690       sqlite3_result_int64(ctx, pCsr->iId);
9691       break;
9692   }
9693 
9694   return rc;
9695 }
9696 
9697 /*
9698 ** Return TRUE if the cursor is at EOF.
9699 */
9700 static int zipfileEof(sqlite3_vtab_cursor *cur){
9701   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9702   return pCsr->bEof;
9703 }
9704 
9705 /*
9706 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
9707 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
9708 ** is guaranteed to be a file-handle open on a zip file.
9709 **
9710 ** This function attempts to locate the EOCD record within the zip archive
9711 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
9712 ** returned if successful. Otherwise, an SQLite error code is returned and
9713 ** an English language error message may be left in virtual-table pTab.
9714 */
9715 static int zipfileReadEOCD(
9716   ZipfileTab *pTab,               /* Return errors here */
9717   const u8 *aBlob,                /* Pointer to in-memory file image */
9718   int nBlob,                      /* Size of aBlob[] in bytes */
9719   FILE *pFile,                    /* Read from this file if aBlob==0 */
9720   ZipfileEOCD *pEOCD              /* Object to populate */
9721 ){
9722   u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
9723   int nRead;                      /* Bytes to read from file */
9724   int rc = SQLITE_OK;
9725 
9726   memset(pEOCD, 0, sizeof(ZipfileEOCD));
9727   if( aBlob==0 ){
9728     i64 iOff;                     /* Offset to read from */
9729     i64 szFile;                   /* Total size of file in bytes */
9730     fseek(pFile, 0, SEEK_END);
9731     szFile = (i64)ftell(pFile);
9732     if( szFile==0 ){
9733       return SQLITE_OK;
9734     }
9735     nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
9736     iOff = szFile - nRead;
9737     rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
9738   }else{
9739     nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
9740     aRead = (u8*)&aBlob[nBlob-nRead];
9741   }
9742 
9743   if( rc==SQLITE_OK ){
9744     int i;
9745 
9746     /* Scan backwards looking for the signature bytes */
9747     for(i=nRead-20; i>=0; i--){
9748       if( aRead[i]==0x50 && aRead[i+1]==0x4b
9749        && aRead[i+2]==0x05 && aRead[i+3]==0x06
9750       ){
9751         break;
9752       }
9753     }
9754     if( i<0 ){
9755       pTab->base.zErrMsg = sqlite3_mprintf(
9756           "cannot find end of central directory record"
9757       );
9758       return SQLITE_ERROR;
9759     }
9760 
9761     aRead += i+4;
9762     pEOCD->iDisk = zipfileRead16(aRead);
9763     pEOCD->iFirstDisk = zipfileRead16(aRead);
9764     pEOCD->nEntry = zipfileRead16(aRead);
9765     pEOCD->nEntryTotal = zipfileRead16(aRead);
9766     pEOCD->nSize = zipfileRead32(aRead);
9767     pEOCD->iOffset = zipfileRead32(aRead);
9768   }
9769 
9770   return rc;
9771 }
9772 
9773 /*
9774 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
9775 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
9776 ** to the end of the list. Otherwise, it is added to the list immediately
9777 ** before pBefore (which is guaranteed to be a part of said list).
9778 */
9779 static void zipfileAddEntry(
9780   ZipfileTab *pTab,
9781   ZipfileEntry *pBefore,
9782   ZipfileEntry *pNew
9783 ){
9784   assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
9785   assert( pNew->pNext==0 );
9786   if( pBefore==0 ){
9787     if( pTab->pFirstEntry==0 ){
9788       pTab->pFirstEntry = pTab->pLastEntry = pNew;
9789     }else{
9790       assert( pTab->pLastEntry->pNext==0 );
9791       pTab->pLastEntry->pNext = pNew;
9792       pTab->pLastEntry = pNew;
9793     }
9794   }else{
9795     ZipfileEntry **pp;
9796     for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
9797     pNew->pNext = pBefore;
9798     *pp = pNew;
9799   }
9800 }
9801 
9802 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
9803   ZipfileEOCD eocd;
9804   int rc;
9805   int i;
9806   i64 iOff;
9807 
9808   rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
9809   iOff = eocd.iOffset;
9810   for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
9811     ZipfileEntry *pNew = 0;
9812     rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
9813 
9814     if( rc==SQLITE_OK ){
9815       zipfileAddEntry(pTab, 0, pNew);
9816       iOff += ZIPFILE_CDS_FIXED_SZ;
9817       iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
9818     }
9819   }
9820   return rc;
9821 }
9822 
9823 /*
9824 ** xFilter callback.
9825 */
9826 static int zipfileFilter(
9827   sqlite3_vtab_cursor *cur,
9828   int idxNum, const char *idxStr,
9829   int argc, sqlite3_value **argv
9830 ){
9831   ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
9832   ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9833   const char *zFile = 0;          /* Zip file to scan */
9834   int rc = SQLITE_OK;             /* Return Code */
9835   int bInMemory = 0;              /* True for an in-memory zipfile */
9836 
9837   (void)idxStr;
9838   (void)argc;
9839 
9840   zipfileResetCursor(pCsr);
9841 
9842   if( pTab->zFile ){
9843     zFile = pTab->zFile;
9844   }else if( idxNum==0 ){
9845     zipfileCursorErr(pCsr, "zipfile() function requires an argument");
9846     return SQLITE_ERROR;
9847   }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
9848     static const u8 aEmptyBlob = 0;
9849     const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
9850     int nBlob = sqlite3_value_bytes(argv[0]);
9851     assert( pTab->pFirstEntry==0 );
9852     if( aBlob==0 ){
9853       aBlob = &aEmptyBlob;
9854       nBlob = 0;
9855     }
9856     rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
9857     pCsr->pFreeEntry = pTab->pFirstEntry;
9858     pTab->pFirstEntry = pTab->pLastEntry = 0;
9859     if( rc!=SQLITE_OK ) return rc;
9860     bInMemory = 1;
9861   }else{
9862     zFile = (const char*)sqlite3_value_text(argv[0]);
9863   }
9864 
9865   if( 0==pTab->pWriteFd && 0==bInMemory ){
9866     pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
9867     if( pCsr->pFile==0 ){
9868       zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
9869       rc = SQLITE_ERROR;
9870     }else{
9871       rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
9872       if( rc==SQLITE_OK ){
9873         if( pCsr->eocd.nEntry==0 ){
9874           pCsr->bEof = 1;
9875         }else{
9876           pCsr->iNextOff = pCsr->eocd.iOffset;
9877           rc = zipfileNext(cur);
9878         }
9879       }
9880     }
9881   }else{
9882     pCsr->bNoop = 1;
9883     pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
9884     rc = zipfileNext(cur);
9885   }
9886 
9887   return rc;
9888 }
9889 
9890 /*
9891 ** xBestIndex callback.
9892 */
9893 static int zipfileBestIndex(
9894   sqlite3_vtab *tab,
9895   sqlite3_index_info *pIdxInfo
9896 ){
9897   int i;
9898   int idx = -1;
9899   int unusable = 0;
9900   (void)tab;
9901 
9902   for(i=0; i<pIdxInfo->nConstraint; i++){
9903     const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
9904     if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
9905     if( pCons->usable==0 ){
9906       unusable = 1;
9907     }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
9908       idx = i;
9909     }
9910   }
9911   pIdxInfo->estimatedCost = 1000.0;
9912   if( idx>=0 ){
9913     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
9914     pIdxInfo->aConstraintUsage[idx].omit = 1;
9915     pIdxInfo->idxNum = 1;
9916   }else if( unusable ){
9917     return SQLITE_CONSTRAINT;
9918   }
9919   return SQLITE_OK;
9920 }
9921 
9922 static ZipfileEntry *zipfileNewEntry(const char *zPath){
9923   ZipfileEntry *pNew;
9924   pNew = sqlite3_malloc(sizeof(ZipfileEntry));
9925   if( pNew ){
9926     memset(pNew, 0, sizeof(ZipfileEntry));
9927     pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
9928     if( pNew->cds.zFile==0 ){
9929       sqlite3_free(pNew);
9930       pNew = 0;
9931     }
9932   }
9933   return pNew;
9934 }
9935 
9936 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
9937   ZipfileCDS *pCds = &pEntry->cds;
9938   u8 *a = aBuf;
9939 
9940   pCds->nExtra = 9;
9941 
9942   /* Write the LFH itself */
9943   zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
9944   zipfileWrite16(a, pCds->iVersionExtract);
9945   zipfileWrite16(a, pCds->flags);
9946   zipfileWrite16(a, pCds->iCompression);
9947   zipfileWrite16(a, pCds->mTime);
9948   zipfileWrite16(a, pCds->mDate);
9949   zipfileWrite32(a, pCds->crc32);
9950   zipfileWrite32(a, pCds->szCompressed);
9951   zipfileWrite32(a, pCds->szUncompressed);
9952   zipfileWrite16(a, (u16)pCds->nFile);
9953   zipfileWrite16(a, pCds->nExtra);
9954   assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
9955 
9956   /* Add the file name */
9957   memcpy(a, pCds->zFile, (int)pCds->nFile);
9958   a += (int)pCds->nFile;
9959 
9960   /* The "extra" data */
9961   zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
9962   zipfileWrite16(a, 5);
9963   *a++ = 0x01;
9964   zipfileWrite32(a, pEntry->mUnixTime);
9965 
9966   return a-aBuf;
9967 }
9968 
9969 static int zipfileAppendEntry(
9970   ZipfileTab *pTab,
9971   ZipfileEntry *pEntry,
9972   const u8 *pData,
9973   int nData
9974 ){
9975   u8 *aBuf = pTab->aBuffer;
9976   int nBuf;
9977   int rc;
9978 
9979   nBuf = zipfileSerializeLFH(pEntry, aBuf);
9980   rc = zipfileAppendData(pTab, aBuf, nBuf);
9981   if( rc==SQLITE_OK ){
9982     pEntry->iDataOff = pTab->szCurrent;
9983     rc = zipfileAppendData(pTab, pData, nData);
9984   }
9985 
9986   return rc;
9987 }
9988 
9989 static int zipfileGetMode(
9990   sqlite3_value *pVal,
9991   int bIsDir,                     /* If true, default to directory */
9992   u32 *pMode,                     /* OUT: Mode value */
9993   char **pzErr                    /* OUT: Error message */
9994 ){
9995   const char *z = (const char*)sqlite3_value_text(pVal);
9996   u32 mode = 0;
9997   if( z==0 ){
9998     mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
9999   }else if( z[0]>='0' && z[0]<='9' ){
10000     mode = (unsigned int)sqlite3_value_int(pVal);
10001   }else{
10002     const char zTemplate[11] = "-rwxrwxrwx";
10003     int i;
10004     if( strlen(z)!=10 ) goto parse_error;
10005     switch( z[0] ){
10006       case '-': mode |= S_IFREG; break;
10007       case 'd': mode |= S_IFDIR; break;
10008       case 'l': mode |= S_IFLNK; break;
10009       default: goto parse_error;
10010     }
10011     for(i=1; i<10; i++){
10012       if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
10013       else if( z[i]!='-' ) goto parse_error;
10014     }
10015   }
10016   if( ((mode & S_IFDIR)==0)==bIsDir ){
10017     /* The "mode" attribute is a directory, but data has been specified.
10018     ** Or vice-versa - no data but "mode" is a file or symlink.  */
10019     *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
10020     return SQLITE_CONSTRAINT;
10021   }
10022   *pMode = mode;
10023   return SQLITE_OK;
10024 
10025  parse_error:
10026   *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
10027   return SQLITE_ERROR;
10028 }
10029 
10030 /*
10031 ** Both (const char*) arguments point to nul-terminated strings. Argument
10032 ** nB is the value of strlen(zB). This function returns 0 if the strings are
10033 ** identical, ignoring any trailing '/' character in either path.  */
10034 static int zipfileComparePath(const char *zA, const char *zB, int nB){
10035   int nA = (int)strlen(zA);
10036   if( nA>0 && zA[nA-1]=='/' ) nA--;
10037   if( nB>0 && zB[nB-1]=='/' ) nB--;
10038   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
10039   return 1;
10040 }
10041 
10042 static int zipfileBegin(sqlite3_vtab *pVtab){
10043   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10044   int rc = SQLITE_OK;
10045 
10046   assert( pTab->pWriteFd==0 );
10047   if( pTab->zFile==0 || pTab->zFile[0]==0 ){
10048     pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
10049     return SQLITE_ERROR;
10050   }
10051 
10052   /* Open a write fd on the file. Also load the entire central directory
10053   ** structure into memory. During the transaction any new file data is
10054   ** appended to the archive file, but the central directory is accumulated
10055   ** in main-memory until the transaction is committed.  */
10056   pTab->pWriteFd = fopen(pTab->zFile, "ab+");
10057   if( pTab->pWriteFd==0 ){
10058     pTab->base.zErrMsg = sqlite3_mprintf(
10059         "zipfile: failed to open file %s for writing", pTab->zFile
10060         );
10061     rc = SQLITE_ERROR;
10062   }else{
10063     fseek(pTab->pWriteFd, 0, SEEK_END);
10064     pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
10065     rc = zipfileLoadDirectory(pTab, 0, 0);
10066   }
10067 
10068   if( rc!=SQLITE_OK ){
10069     zipfileCleanupTransaction(pTab);
10070   }
10071 
10072   return rc;
10073 }
10074 
10075 /*
10076 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10077 ** time(2)).
10078 */
10079 static u32 zipfileTime(void){
10080   sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
10081   u32 ret;
10082   if( pVfs==0 ) return 0;
10083   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
10084     i64 ms;
10085     pVfs->xCurrentTimeInt64(pVfs, &ms);
10086     ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
10087   }else{
10088     double day;
10089     pVfs->xCurrentTime(pVfs, &day);
10090     ret = (u32)((day - 2440587.5) * 86400);
10091   }
10092   return ret;
10093 }
10094 
10095 /*
10096 ** Return a 32-bit timestamp in UNIX epoch format.
10097 **
10098 ** If the value passed as the only argument is either NULL or an SQL NULL,
10099 ** return the current time. Otherwise, return the value stored in (*pVal)
10100 ** cast to a 32-bit unsigned integer.
10101 */
10102 static u32 zipfileGetTime(sqlite3_value *pVal){
10103   if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
10104     return zipfileTime();
10105   }
10106   return (u32)sqlite3_value_int64(pVal);
10107 }
10108 
10109 /*
10110 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10111 ** linked list.  Remove it from the list and free the object.
10112 */
10113 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
10114   if( pOld ){
10115     if( pTab->pFirstEntry==pOld ){
10116       pTab->pFirstEntry = pOld->pNext;
10117       if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
10118     }else{
10119       ZipfileEntry *p;
10120       for(p=pTab->pFirstEntry; p; p=p->pNext){
10121         if( p->pNext==pOld ){
10122           p->pNext = pOld->pNext;
10123           if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
10124           break;
10125         }
10126       }
10127     }
10128     zipfileEntryFree(pOld);
10129   }
10130 }
10131 
10132 /*
10133 ** xUpdate method.
10134 */
10135 static int zipfileUpdate(
10136   sqlite3_vtab *pVtab,
10137   int nVal,
10138   sqlite3_value **apVal,
10139   sqlite_int64 *pRowid
10140 ){
10141   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10142   int rc = SQLITE_OK;             /* Return Code */
10143   ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
10144 
10145   u32 mode = 0;                   /* Mode for new entry */
10146   u32 mTime = 0;                  /* Modification time for new entry */
10147   i64 sz = 0;                     /* Uncompressed size */
10148   const char *zPath = 0;          /* Path for new entry */
10149   int nPath = 0;                  /* strlen(zPath) */
10150   const u8 *pData = 0;            /* Pointer to buffer containing content */
10151   int nData = 0;                  /* Size of pData buffer in bytes */
10152   int iMethod = 0;                /* Compression method for new entry */
10153   u8 *pFree = 0;                  /* Free this */
10154   char *zFree = 0;                /* Also free this */
10155   ZipfileEntry *pOld = 0;
10156   ZipfileEntry *pOld2 = 0;
10157   int bUpdate = 0;                /* True for an update that modifies "name" */
10158   int bIsDir = 0;
10159   u32 iCrc32 = 0;
10160 
10161   (void)pRowid;
10162 
10163   if( pTab->pWriteFd==0 ){
10164     rc = zipfileBegin(pVtab);
10165     if( rc!=SQLITE_OK ) return rc;
10166   }
10167 
10168   /* If this is a DELETE or UPDATE, find the archive entry to delete. */
10169   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
10170     const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
10171     int nDelete = (int)strlen(zDelete);
10172     if( nVal>1 ){
10173       const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
10174       if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
10175         bUpdate = 1;
10176       }
10177     }
10178     for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
10179       if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
10180         break;
10181       }
10182       assert( pOld->pNext );
10183     }
10184   }
10185 
10186   if( nVal>1 ){
10187     /* Check that "sz" and "rawdata" are both NULL: */
10188     if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
10189       zipfileTableErr(pTab, "sz must be NULL");
10190       rc = SQLITE_CONSTRAINT;
10191     }
10192     if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
10193       zipfileTableErr(pTab, "rawdata must be NULL");
10194       rc = SQLITE_CONSTRAINT;
10195     }
10196 
10197     if( rc==SQLITE_OK ){
10198       if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
10199         /* data=NULL. A directory */
10200         bIsDir = 1;
10201       }else{
10202         /* Value specified for "data", and possibly "method". This must be
10203         ** a regular file or a symlink. */
10204         const u8 *aIn = sqlite3_value_blob(apVal[7]);
10205         int nIn = sqlite3_value_bytes(apVal[7]);
10206         int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
10207 
10208         iMethod = sqlite3_value_int(apVal[8]);
10209         sz = nIn;
10210         pData = aIn;
10211         nData = nIn;
10212         if( iMethod!=0 && iMethod!=8 ){
10213           zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
10214           rc = SQLITE_CONSTRAINT;
10215         }else{
10216           if( bAuto || iMethod ){
10217             int nCmp;
10218             rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
10219             if( rc==SQLITE_OK ){
10220               if( iMethod || nCmp<nIn ){
10221                 iMethod = 8;
10222                 pData = pFree;
10223                 nData = nCmp;
10224               }
10225             }
10226           }
10227           iCrc32 = crc32(0, aIn, nIn);
10228         }
10229       }
10230     }
10231 
10232     if( rc==SQLITE_OK ){
10233       rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
10234     }
10235 
10236     if( rc==SQLITE_OK ){
10237       zPath = (const char*)sqlite3_value_text(apVal[2]);
10238       if( zPath==0 ) zPath = "";
10239       nPath = (int)strlen(zPath);
10240       mTime = zipfileGetTime(apVal[4]);
10241     }
10242 
10243     if( rc==SQLITE_OK && bIsDir ){
10244       /* For a directory, check that the last character in the path is a
10245       ** '/'. This appears to be required for compatibility with info-zip
10246       ** (the unzip command on unix). It does not create directories
10247       ** otherwise.  */
10248       if( nPath<=0 || zPath[nPath-1]!='/' ){
10249         zFree = sqlite3_mprintf("%s/", zPath);
10250         zPath = (const char*)zFree;
10251         if( zFree==0 ){
10252           rc = SQLITE_NOMEM;
10253           nPath = 0;
10254         }else{
10255           nPath = (int)strlen(zPath);
10256         }
10257       }
10258     }
10259 
10260     /* Check that we're not inserting a duplicate entry -OR- updating an
10261     ** entry with a path, thereby making it into a duplicate. */
10262     if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
10263       ZipfileEntry *p;
10264       for(p=pTab->pFirstEntry; p; p=p->pNext){
10265         if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
10266           switch( sqlite3_vtab_on_conflict(pTab->db) ){
10267             case SQLITE_IGNORE: {
10268               goto zipfile_update_done;
10269             }
10270             case SQLITE_REPLACE: {
10271               pOld2 = p;
10272               break;
10273             }
10274             default: {
10275               zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
10276               rc = SQLITE_CONSTRAINT;
10277               break;
10278             }
10279           }
10280           break;
10281         }
10282       }
10283     }
10284 
10285     if( rc==SQLITE_OK ){
10286       /* Create the new CDS record. */
10287       pNew = zipfileNewEntry(zPath);
10288       if( pNew==0 ){
10289         rc = SQLITE_NOMEM;
10290       }else{
10291         pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
10292         pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
10293         pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
10294         pNew->cds.iCompression = (u16)iMethod;
10295         zipfileMtimeToDos(&pNew->cds, mTime);
10296         pNew->cds.crc32 = iCrc32;
10297         pNew->cds.szCompressed = nData;
10298         pNew->cds.szUncompressed = (u32)sz;
10299         pNew->cds.iExternalAttr = (mode<<16);
10300         pNew->cds.iOffset = (u32)pTab->szCurrent;
10301         pNew->cds.nFile = (u16)nPath;
10302         pNew->mUnixTime = (u32)mTime;
10303         rc = zipfileAppendEntry(pTab, pNew, pData, nData);
10304         zipfileAddEntry(pTab, pOld, pNew);
10305       }
10306     }
10307   }
10308 
10309   if( rc==SQLITE_OK && (pOld || pOld2) ){
10310     ZipfileCsr *pCsr;
10311     for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
10312       if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
10313         pCsr->pCurrent = pCsr->pCurrent->pNext;
10314         pCsr->bNoop = 1;
10315       }
10316     }
10317 
10318     zipfileRemoveEntryFromList(pTab, pOld);
10319     zipfileRemoveEntryFromList(pTab, pOld2);
10320   }
10321 
10322 zipfile_update_done:
10323   sqlite3_free(pFree);
10324   sqlite3_free(zFree);
10325   return rc;
10326 }
10327 
10328 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
10329   u8 *a = aBuf;
10330   zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
10331   zipfileWrite16(a, p->iDisk);
10332   zipfileWrite16(a, p->iFirstDisk);
10333   zipfileWrite16(a, p->nEntry);
10334   zipfileWrite16(a, p->nEntryTotal);
10335   zipfileWrite32(a, p->nSize);
10336   zipfileWrite32(a, p->iOffset);
10337   zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
10338 
10339   return a-aBuf;
10340 }
10341 
10342 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
10343   int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
10344   assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
10345   return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
10346 }
10347 
10348 /*
10349 ** Serialize the CDS structure into buffer aBuf[]. Return the number
10350 ** of bytes written.
10351 */
10352 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
10353   u8 *a = aBuf;
10354   ZipfileCDS *pCDS = &pEntry->cds;
10355 
10356   if( pEntry->aExtra==0 ){
10357     pCDS->nExtra = 9;
10358   }
10359 
10360   zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
10361   zipfileWrite16(a, pCDS->iVersionMadeBy);
10362   zipfileWrite16(a, pCDS->iVersionExtract);
10363   zipfileWrite16(a, pCDS->flags);
10364   zipfileWrite16(a, pCDS->iCompression);
10365   zipfileWrite16(a, pCDS->mTime);
10366   zipfileWrite16(a, pCDS->mDate);
10367   zipfileWrite32(a, pCDS->crc32);
10368   zipfileWrite32(a, pCDS->szCompressed);
10369   zipfileWrite32(a, pCDS->szUncompressed);
10370   assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
10371   zipfileWrite16(a, pCDS->nFile);
10372   zipfileWrite16(a, pCDS->nExtra);
10373   zipfileWrite16(a, pCDS->nComment);
10374   zipfileWrite16(a, pCDS->iDiskStart);
10375   zipfileWrite16(a, pCDS->iInternalAttr);
10376   zipfileWrite32(a, pCDS->iExternalAttr);
10377   zipfileWrite32(a, pCDS->iOffset);
10378 
10379   memcpy(a, pCDS->zFile, pCDS->nFile);
10380   a += pCDS->nFile;
10381 
10382   if( pEntry->aExtra ){
10383     int n = (int)pCDS->nExtra + (int)pCDS->nComment;
10384     memcpy(a, pEntry->aExtra, n);
10385     a += n;
10386   }else{
10387     assert( pCDS->nExtra==9 );
10388     zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
10389     zipfileWrite16(a, 5);
10390     *a++ = 0x01;
10391     zipfileWrite32(a, pEntry->mUnixTime);
10392   }
10393 
10394   return a-aBuf;
10395 }
10396 
10397 static int zipfileCommit(sqlite3_vtab *pVtab){
10398   ZipfileTab *pTab = (ZipfileTab*)pVtab;
10399   int rc = SQLITE_OK;
10400   if( pTab->pWriteFd ){
10401     i64 iOffset = pTab->szCurrent;
10402     ZipfileEntry *p;
10403     ZipfileEOCD eocd;
10404     int nEntry = 0;
10405 
10406     /* Write out all entries */
10407     for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
10408       int n = zipfileSerializeCDS(p, pTab->aBuffer);
10409       rc = zipfileAppendData(pTab, pTab->aBuffer, n);
10410       nEntry++;
10411     }
10412 
10413     /* Write out the EOCD record */
10414     eocd.iDisk = 0;
10415     eocd.iFirstDisk = 0;
10416     eocd.nEntry = (u16)nEntry;
10417     eocd.nEntryTotal = (u16)nEntry;
10418     eocd.nSize = (u32)(pTab->szCurrent - iOffset);
10419     eocd.iOffset = (u32)iOffset;
10420     rc = zipfileAppendEOCD(pTab, &eocd);
10421 
10422     zipfileCleanupTransaction(pTab);
10423   }
10424   return rc;
10425 }
10426 
10427 static int zipfileRollback(sqlite3_vtab *pVtab){
10428   return zipfileCommit(pVtab);
10429 }
10430 
10431 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
10432   ZipfileCsr *pCsr;
10433   for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
10434     if( iId==pCsr->iId ) break;
10435   }
10436   return pCsr;
10437 }
10438 
10439 static void zipfileFunctionCds(
10440   sqlite3_context *context,
10441   int argc,
10442   sqlite3_value **argv
10443 ){
10444   ZipfileCsr *pCsr;
10445   ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
10446   assert( argc>0 );
10447 
10448   pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
10449   if( pCsr ){
10450     ZipfileCDS *p = &pCsr->pCurrent->cds;
10451     char *zRes = sqlite3_mprintf("{"
10452         "\"version-made-by\" : %u, "
10453         "\"version-to-extract\" : %u, "
10454         "\"flags\" : %u, "
10455         "\"compression\" : %u, "
10456         "\"time\" : %u, "
10457         "\"date\" : %u, "
10458         "\"crc32\" : %u, "
10459         "\"compressed-size\" : %u, "
10460         "\"uncompressed-size\" : %u, "
10461         "\"file-name-length\" : %u, "
10462         "\"extra-field-length\" : %u, "
10463         "\"file-comment-length\" : %u, "
10464         "\"disk-number-start\" : %u, "
10465         "\"internal-attr\" : %u, "
10466         "\"external-attr\" : %u, "
10467         "\"offset\" : %u }",
10468         (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
10469         (u32)p->flags, (u32)p->iCompression,
10470         (u32)p->mTime, (u32)p->mDate,
10471         (u32)p->crc32, (u32)p->szCompressed,
10472         (u32)p->szUncompressed, (u32)p->nFile,
10473         (u32)p->nExtra, (u32)p->nComment,
10474         (u32)p->iDiskStart, (u32)p->iInternalAttr,
10475         (u32)p->iExternalAttr, (u32)p->iOffset
10476     );
10477 
10478     if( zRes==0 ){
10479       sqlite3_result_error_nomem(context);
10480     }else{
10481       sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
10482       sqlite3_free(zRes);
10483     }
10484   }
10485 }
10486 
10487 /*
10488 ** xFindFunction method.
10489 */
10490 static int zipfileFindFunction(
10491   sqlite3_vtab *pVtab,            /* Virtual table handle */
10492   int nArg,                       /* Number of SQL function arguments */
10493   const char *zName,              /* Name of SQL function */
10494   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
10495   void **ppArg                    /* OUT: User data for *pxFunc */
10496 ){
10497   (void)nArg;
10498   if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
10499     *pxFunc = zipfileFunctionCds;
10500     *ppArg = (void*)pVtab;
10501     return 1;
10502   }
10503   return 0;
10504 }
10505 
10506 typedef struct ZipfileBuffer ZipfileBuffer;
10507 struct ZipfileBuffer {
10508   u8 *a;                          /* Pointer to buffer */
10509   int n;                          /* Size of buffer in bytes */
10510   int nAlloc;                     /* Byte allocated at a[] */
10511 };
10512 
10513 typedef struct ZipfileCtx ZipfileCtx;
10514 struct ZipfileCtx {
10515   int nEntry;
10516   ZipfileBuffer body;
10517   ZipfileBuffer cds;
10518 };
10519 
10520 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
10521   if( pBuf->n+nByte>pBuf->nAlloc ){
10522     u8 *aNew;
10523     sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
10524     int nReq = pBuf->n + nByte;
10525 
10526     while( nNew<nReq ) nNew = nNew*2;
10527     aNew = sqlite3_realloc64(pBuf->a, nNew);
10528     if( aNew==0 ) return SQLITE_NOMEM;
10529     pBuf->a = aNew;
10530     pBuf->nAlloc = (int)nNew;
10531   }
10532   return SQLITE_OK;
10533 }
10534 
10535 /*
10536 ** xStep() callback for the zipfile() aggregate. This can be called in
10537 ** any of the following ways:
10538 **
10539 **   SELECT zipfile(name,data) ...
10540 **   SELECT zipfile(name,mode,mtime,data) ...
10541 **   SELECT zipfile(name,mode,mtime,data,method) ...
10542 */
10543 static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
10544   ZipfileCtx *p;                  /* Aggregate function context */
10545   ZipfileEntry e;                 /* New entry to add to zip archive */
10546 
10547   sqlite3_value *pName = 0;
10548   sqlite3_value *pMode = 0;
10549   sqlite3_value *pMtime = 0;
10550   sqlite3_value *pData = 0;
10551   sqlite3_value *pMethod = 0;
10552 
10553   int bIsDir = 0;
10554   u32 mode;
10555   int rc = SQLITE_OK;
10556   char *zErr = 0;
10557 
10558   int iMethod = -1;               /* Compression method to use (0 or 8) */
10559 
10560   const u8 *aData = 0;            /* Possibly compressed data for new entry */
10561   int nData = 0;                  /* Size of aData[] in bytes */
10562   int szUncompressed = 0;         /* Size of data before compression */
10563   u8 *aFree = 0;                  /* Free this before returning */
10564   u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
10565 
10566   char *zName = 0;                /* Path (name) of new entry */
10567   int nName = 0;                  /* Size of zName in bytes */
10568   char *zFree = 0;                /* Free this before returning */
10569   int nByte;
10570 
10571   memset(&e, 0, sizeof(e));
10572   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
10573   if( p==0 ) return;
10574 
10575   /* Martial the arguments into stack variables */
10576   if( nVal!=2 && nVal!=4 && nVal!=5 ){
10577     zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
10578     rc = SQLITE_ERROR;
10579     goto zipfile_step_out;
10580   }
10581   pName = apVal[0];
10582   if( nVal==2 ){
10583     pData = apVal[1];
10584   }else{
10585     pMode = apVal[1];
10586     pMtime = apVal[2];
10587     pData = apVal[3];
10588     if( nVal==5 ){
10589       pMethod = apVal[4];
10590     }
10591   }
10592 
10593   /* Check that the 'name' parameter looks ok. */
10594   zName = (char*)sqlite3_value_text(pName);
10595   nName = sqlite3_value_bytes(pName);
10596   if( zName==0 ){
10597     zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
10598     rc = SQLITE_ERROR;
10599     goto zipfile_step_out;
10600   }
10601 
10602   /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
10603   ** deflate compression) or NULL (choose automatically).  */
10604   if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
10605     iMethod = (int)sqlite3_value_int64(pMethod);
10606     if( iMethod!=0 && iMethod!=8 ){
10607       zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
10608       rc = SQLITE_ERROR;
10609       goto zipfile_step_out;
10610     }
10611   }
10612 
10613   /* Now inspect the data. If this is NULL, then the new entry must be a
10614   ** directory.  Otherwise, figure out whether or not the data should
10615   ** be deflated or simply stored in the zip archive. */
10616   if( sqlite3_value_type(pData)==SQLITE_NULL ){
10617     bIsDir = 1;
10618     iMethod = 0;
10619   }else{
10620     aData = sqlite3_value_blob(pData);
10621     szUncompressed = nData = sqlite3_value_bytes(pData);
10622     iCrc32 = crc32(0, aData, nData);
10623     if( iMethod<0 || iMethod==8 ){
10624       int nOut = 0;
10625       rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
10626       if( rc!=SQLITE_OK ){
10627         goto zipfile_step_out;
10628       }
10629       if( iMethod==8 || nOut<nData ){
10630         aData = aFree;
10631         nData = nOut;
10632         iMethod = 8;
10633       }else{
10634         iMethod = 0;
10635       }
10636     }
10637   }
10638 
10639   /* Decode the "mode" argument. */
10640   rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
10641   if( rc ) goto zipfile_step_out;
10642 
10643   /* Decode the "mtime" argument. */
10644   e.mUnixTime = zipfileGetTime(pMtime);
10645 
10646   /* If this is a directory entry, ensure that there is exactly one '/'
10647   ** at the end of the path. Or, if this is not a directory and the path
10648   ** ends in '/' it is an error. */
10649   if( bIsDir==0 ){
10650     if( nName>0 && zName[nName-1]=='/' ){
10651       zErr = sqlite3_mprintf("non-directory name must not end with /");
10652       rc = SQLITE_ERROR;
10653       goto zipfile_step_out;
10654     }
10655   }else{
10656     if( nName==0 || zName[nName-1]!='/' ){
10657       zName = zFree = sqlite3_mprintf("%s/", zName);
10658       if( zName==0 ){
10659         rc = SQLITE_NOMEM;
10660         goto zipfile_step_out;
10661       }
10662       nName = (int)strlen(zName);
10663     }else{
10664       while( nName>1 && zName[nName-2]=='/' ) nName--;
10665     }
10666   }
10667 
10668   /* Assemble the ZipfileEntry object for the new zip archive entry */
10669   e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
10670   e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
10671   e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
10672   e.cds.iCompression = (u16)iMethod;
10673   zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
10674   e.cds.crc32 = iCrc32;
10675   e.cds.szCompressed = nData;
10676   e.cds.szUncompressed = szUncompressed;
10677   e.cds.iExternalAttr = (mode<<16);
10678   e.cds.iOffset = p->body.n;
10679   e.cds.nFile = (u16)nName;
10680   e.cds.zFile = zName;
10681 
10682   /* Append the LFH to the body of the new archive */
10683   nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
10684   if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
10685   p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
10686 
10687   /* Append the data to the body of the new archive */
10688   if( nData>0 ){
10689     if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
10690     memcpy(&p->body.a[p->body.n], aData, nData);
10691     p->body.n += nData;
10692   }
10693 
10694   /* Append the CDS record to the directory of the new archive */
10695   nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
10696   if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
10697   p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
10698 
10699   /* Increment the count of entries in the archive */
10700   p->nEntry++;
10701 
10702  zipfile_step_out:
10703   sqlite3_free(aFree);
10704   sqlite3_free(zFree);
10705   if( rc ){
10706     if( zErr ){
10707       sqlite3_result_error(pCtx, zErr, -1);
10708     }else{
10709       sqlite3_result_error_code(pCtx, rc);
10710     }
10711   }
10712   sqlite3_free(zErr);
10713 }
10714 
10715 /*
10716 ** xFinalize() callback for zipfile aggregate function.
10717 */
10718 static void zipfileFinal(sqlite3_context *pCtx){
10719   ZipfileCtx *p;
10720   ZipfileEOCD eocd;
10721   sqlite3_int64 nZip;
10722   u8 *aZip;
10723 
10724   p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
10725   if( p==0 ) return;
10726   if( p->nEntry>0 ){
10727     memset(&eocd, 0, sizeof(eocd));
10728     eocd.nEntry = (u16)p->nEntry;
10729     eocd.nEntryTotal = (u16)p->nEntry;
10730     eocd.nSize = p->cds.n;
10731     eocd.iOffset = p->body.n;
10732 
10733     nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
10734     aZip = (u8*)sqlite3_malloc64(nZip);
10735     if( aZip==0 ){
10736       sqlite3_result_error_nomem(pCtx);
10737     }else{
10738       memcpy(aZip, p->body.a, p->body.n);
10739       memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
10740       zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
10741       sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
10742     }
10743   }
10744 
10745   sqlite3_free(p->body.a);
10746   sqlite3_free(p->cds.a);
10747 }
10748 
10749 
10750 /*
10751 ** Register the "zipfile" virtual table.
10752 */
10753 static int zipfileRegister(sqlite3 *db){
10754   static sqlite3_module zipfileModule = {
10755     1,                         /* iVersion */
10756     zipfileConnect,            /* xCreate */
10757     zipfileConnect,            /* xConnect */
10758     zipfileBestIndex,          /* xBestIndex */
10759     zipfileDisconnect,         /* xDisconnect */
10760     zipfileDisconnect,         /* xDestroy */
10761     zipfileOpen,               /* xOpen - open a cursor */
10762     zipfileClose,              /* xClose - close a cursor */
10763     zipfileFilter,             /* xFilter - configure scan constraints */
10764     zipfileNext,               /* xNext - advance a cursor */
10765     zipfileEof,                /* xEof - check for end of scan */
10766     zipfileColumn,             /* xColumn - read data */
10767     0,                         /* xRowid - read data */
10768     zipfileUpdate,             /* xUpdate */
10769     zipfileBegin,              /* xBegin */
10770     0,                         /* xSync */
10771     zipfileCommit,             /* xCommit */
10772     zipfileRollback,           /* xRollback */
10773     zipfileFindFunction,       /* xFindMethod */
10774     0,                         /* xRename */
10775     0,                         /* xSavepoint */
10776     0,                         /* xRelease */
10777     0,                         /* xRollback */
10778     0,                         /* xShadowName */
10779     0                          /* xIntegrity */
10780   };
10781 
10782   int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
10783   if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
10784   if( rc==SQLITE_OK ){
10785     rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
10786         zipfileStep, zipfileFinal
10787     );
10788   }
10789   assert( sizeof(i64)==8 );
10790   assert( sizeof(u32)==4 );
10791   assert( sizeof(u16)==2 );
10792   assert( sizeof(u8)==1 );
10793   return rc;
10794 }
10795 #else         /* SQLITE_OMIT_VIRTUALTABLE */
10796 # define zipfileRegister(x) SQLITE_OK
10797 #endif
10798 
10799 #ifdef _WIN32
10800 
10801 #endif
10802 int sqlite3_zipfile_init(
10803   sqlite3 *db,
10804   char **pzErrMsg,
10805   const sqlite3_api_routines *pApi
10806 ){
10807   SQLITE_EXTENSION_INIT2(pApi);
10808   (void)pzErrMsg;  /* Unused parameter */
10809   return zipfileRegister(db);
10810 }
10811 
10812 /************************* End ../ext/misc/zipfile.c ********************/
10813 /************************* Begin ../ext/misc/sqlar.c ******************/
10814 /*
10815 ** 2017-12-17
10816 **
10817 ** The author disclaims copyright to this source code.  In place of
10818 ** a legal notice, here is a blessing:
10819 **
10820 **    May you do good and not evil.
10821 **    May you find forgiveness for yourself and forgive others.
10822 **    May you share freely, never taking more than you give.
10823 **
10824 ******************************************************************************
10825 **
10826 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
10827 ** for working with sqlar archives and used by the shell tool's built-in
10828 ** sqlar support.
10829 */
10830 /* #include "sqlite3ext.h" */
10831 SQLITE_EXTENSION_INIT1
10832 #include <zlib.h>
10833 #include <assert.h>
10834 
10835 /*
10836 ** Implementation of the "sqlar_compress(X)" SQL function.
10837 **
10838 ** If the type of X is SQLITE_BLOB, and compressing that blob using
10839 ** zlib utility function compress() yields a smaller blob, return the
10840 ** compressed blob. Otherwise, return a copy of X.
10841 **
10842 ** SQLar uses the "zlib format" for compressed content.  The zlib format
10843 ** contains a two-byte identification header and a four-byte checksum at
10844 ** the end.  This is different from ZIP which uses the raw deflate format.
10845 **
10846 ** Future enhancements to SQLar might add support for new compression formats.
10847 ** If so, those new formats will be identified by alternative headers in the
10848 ** compressed data.
10849 */
10850 static void sqlarCompressFunc(
10851   sqlite3_context *context,
10852   int argc,
10853   sqlite3_value **argv
10854 ){
10855   assert( argc==1 );
10856   if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10857     const Bytef *pData = sqlite3_value_blob(argv[0]);
10858     uLong nData = sqlite3_value_bytes(argv[0]);
10859     uLongf nOut = compressBound(nData);
10860     Bytef *pOut;
10861 
10862     pOut = (Bytef*)sqlite3_malloc(nOut);
10863     if( pOut==0 ){
10864       sqlite3_result_error_nomem(context);
10865       return;
10866     }else{
10867       if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
10868         sqlite3_result_error(context, "error in compress()", -1);
10869       }else if( nOut<nData ){
10870         sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
10871       }else{
10872         sqlite3_result_value(context, argv[0]);
10873       }
10874       sqlite3_free(pOut);
10875     }
10876   }else{
10877     sqlite3_result_value(context, argv[0]);
10878   }
10879 }
10880 
10881 /*
10882 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
10883 **
10884 ** Parameter SZ is interpreted as an integer. If it is less than or
10885 ** equal to zero, then this function returns a copy of X. Or, if
10886 ** SZ is equal to the size of X when interpreted as a blob, also
10887 ** return a copy of X. Otherwise, decompress blob X using zlib
10888 ** utility function uncompress() and return the results (another
10889 ** blob).
10890 */
10891 static void sqlarUncompressFunc(
10892   sqlite3_context *context,
10893   int argc,
10894   sqlite3_value **argv
10895 ){
10896   uLong nData;
10897   uLongf sz;
10898 
10899   assert( argc==2 );
10900   sz = sqlite3_value_int(argv[1]);
10901 
10902   if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
10903     sqlite3_result_value(context, argv[0]);
10904   }else{
10905     const Bytef *pData= sqlite3_value_blob(argv[0]);
10906     Bytef *pOut = sqlite3_malloc(sz);
10907     if( pOut==0 ){
10908       sqlite3_result_error_nomem(context);
10909     }else if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
10910       sqlite3_result_error(context, "error in uncompress()", -1);
10911     }else{
10912       sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
10913     }
10914     sqlite3_free(pOut);
10915   }
10916 }
10917 
10918 #ifdef _WIN32
10919 
10920 #endif
10921 int sqlite3_sqlar_init(
10922   sqlite3 *db,
10923   char **pzErrMsg,
10924   const sqlite3_api_routines *pApi
10925 ){
10926   int rc = SQLITE_OK;
10927   SQLITE_EXTENSION_INIT2(pApi);
10928   (void)pzErrMsg;  /* Unused parameter */
10929   rc = sqlite3_create_function(db, "sqlar_compress", 1,
10930                                SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10931                                sqlarCompressFunc, 0, 0);
10932   if( rc==SQLITE_OK ){
10933     rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
10934                                  SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
10935                                  sqlarUncompressFunc, 0, 0);
10936   }
10937   return rc;
10938 }
10939 
10940 /************************* End ../ext/misc/sqlar.c ********************/
10941 #endif
10942 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
10943 /*
10944 ** 2017 April 07
10945 **
10946 ** The author disclaims copyright to this source code.  In place of
10947 ** a legal notice, here is a blessing:
10948 **
10949 **    May you do good and not evil.
10950 **    May you find forgiveness for yourself and forgive others.
10951 **    May you share freely, never taking more than you give.
10952 **
10953 *************************************************************************
10954 */
10955 #if !defined(SQLITEEXPERT_H)
10956 #define SQLITEEXPERT_H 1
10957 /* #include "sqlite3.h" */
10958 
10959 typedef struct sqlite3expert sqlite3expert;
10960 
10961 /*
10962 ** Create a new sqlite3expert object.
10963 **
10964 ** If successful, a pointer to the new object is returned and (*pzErr) set
10965 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
10966 ** an English-language error message. In this case it is the responsibility
10967 ** of the caller to eventually free the error message buffer using
10968 ** sqlite3_free().
10969 */
10970 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
10971 
10972 /*
10973 ** Configure an sqlite3expert object.
10974 **
10975 ** EXPERT_CONFIG_SAMPLE:
10976 **   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
10977 **   each candidate index. This involves scanning and sorting the entire
10978 **   contents of each user database table once for each candidate index
10979 **   associated with the table. For large databases, this can be
10980 **   prohibitively slow. This option allows the sqlite3expert object to
10981 **   be configured so that sqlite_stat1 data is instead generated based on a
10982 **   subset of each table, or so that no sqlite_stat1 data is used at all.
10983 **
10984 **   A single integer argument is passed to this option. If the value is less
10985 **   than or equal to zero, then no sqlite_stat1 data is generated or used by
10986 **   the analysis - indexes are recommended based on the database schema only.
10987 **   Or, if the value is 100 or greater, complete sqlite_stat1 data is
10988 **   generated for each candidate index (this is the default). Finally, if the
10989 **   value falls between 0 and 100, then it represents the percentage of user
10990 **   table rows that should be considered when generating sqlite_stat1 data.
10991 **
10992 **   Examples:
10993 **
10994 **     // Do not generate any sqlite_stat1 data
10995 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
10996 **
10997 **     // Generate sqlite_stat1 data based on 10% of the rows in each table.
10998 **     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
10999 */
11000 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
11001 
11002 #define EXPERT_CONFIG_SAMPLE 1    /* int */
11003 
11004 /*
11005 ** Specify zero or more SQL statements to be included in the analysis.
11006 **
11007 ** Buffer zSql must contain zero or more complete SQL statements. This
11008 ** function parses all statements contained in the buffer and adds them
11009 ** to the internal list of statements to analyze. If successful, SQLITE_OK
11010 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11011 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11012 ** may be set to point to an English language error message. In this case
11013 ** the caller is responsible for eventually freeing the error message buffer
11014 ** using sqlite3_free().
11015 **
11016 ** If an error does occur while processing one of the statements in the
11017 ** buffer passed as the second argument, none of the statements in the
11018 ** buffer are added to the analysis.
11019 **
11020 ** This function must be called before sqlite3_expert_analyze(). If a call
11021 ** to this function is made on an sqlite3expert object that has already
11022 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
11023 ** immediately and no statements are added to the analysis.
11024 */
11025 int sqlite3_expert_sql(
11026   sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
11027   const char *zSql,               /* SQL statement(s) to add */
11028   char **pzErr                    /* OUT: Error message (if any) */
11029 );
11030 
11031 
11032 /*
11033 ** This function is called after the sqlite3expert object has been configured
11034 ** with all SQL statements using sqlite3_expert_sql() to actually perform
11035 ** the analysis. Once this function has been called, it is not possible to
11036 ** add further SQL statements to the analysis.
11037 **
11038 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
11039 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
11040 ** point to a buffer containing an English language error message. In this
11041 ** case it is the responsibility of the caller to eventually free the buffer
11042 ** using sqlite3_free().
11043 **
11044 ** If an error does occur within this function, the sqlite3expert object
11045 ** is no longer useful for any purpose. At that point it is no longer
11046 ** possible to add further SQL statements to the object or to re-attempt
11047 ** the analysis. The sqlite3expert object must still be freed using a call
11048 ** sqlite3_expert_destroy().
11049 */
11050 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
11051 
11052 /*
11053 ** Return the total number of statements loaded using sqlite3_expert_sql().
11054 ** The total number of SQL statements may be different from the total number
11055 ** to calls to sqlite3_expert_sql().
11056 */
11057 int sqlite3_expert_count(sqlite3expert*);
11058 
11059 /*
11060 ** Return a component of the report.
11061 **
11062 ** This function is called after sqlite3_expert_analyze() to extract the
11063 ** results of the analysis. Each call to this function returns either a
11064 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11065 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
11066 ** #define constants defined below.
11067 **
11068 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
11069 ** information relating to a specific SQL statement. In these cases that
11070 ** SQL statement is identified by the value passed as the second argument.
11071 ** SQL statements are numbered from 0 in the order in which they are parsed.
11072 ** If an out-of-range value (less than zero or equal to or greater than the
11073 ** value returned by sqlite3_expert_count()) is passed as the second argument
11074 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
11075 **
11076 ** EXPERT_REPORT_SQL:
11077 **   Return the text of SQL statement iStmt.
11078 **
11079 ** EXPERT_REPORT_INDEXES:
11080 **   Return a buffer containing the CREATE INDEX statements for all recommended
11081 **   indexes for statement iStmt. If there are no new recommeded indexes, NULL
11082 **   is returned.
11083 **
11084 ** EXPERT_REPORT_PLAN:
11085 **   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
11086 **   iStmt after the proposed indexes have been added to the database schema.
11087 **
11088 ** EXPERT_REPORT_CANDIDATES:
11089 **   Return a pointer to a buffer containing the CREATE INDEX statements
11090 **   for all indexes that were tested (for all SQL statements). The iStmt
11091 **   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
11092 */
11093 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
11094 
11095 /*
11096 ** Values for the third argument passed to sqlite3_expert_report().
11097 */
11098 #define EXPERT_REPORT_SQL        1
11099 #define EXPERT_REPORT_INDEXES    2
11100 #define EXPERT_REPORT_PLAN       3
11101 #define EXPERT_REPORT_CANDIDATES 4
11102 
11103 /*
11104 ** Free an (sqlite3expert*) handle and all associated resources. There
11105 ** should be one call to this function for each successful call to
11106 ** sqlite3-expert_new().
11107 */
11108 void sqlite3_expert_destroy(sqlite3expert*);
11109 
11110 #endif  /* !defined(SQLITEEXPERT_H) */
11111 
11112 /************************* End ../ext/expert/sqlite3expert.h ********************/
11113 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
11114 /*
11115 ** 2017 April 09
11116 **
11117 ** The author disclaims copyright to this source code.  In place of
11118 ** a legal notice, here is a blessing:
11119 **
11120 **    May you do good and not evil.
11121 **    May you find forgiveness for yourself and forgive others.
11122 **    May you share freely, never taking more than you give.
11123 **
11124 *************************************************************************
11125 */
11126 /* #include "sqlite3expert.h" */
11127 #include <assert.h>
11128 #include <string.h>
11129 #include <stdio.h>
11130 
11131 #if !defined(SQLITE_AMALGAMATION)
11132 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11133 # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
11134 #endif
11135 #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
11136 # define ALWAYS(X)      (1)
11137 # define NEVER(X)       (0)
11138 #elif !defined(NDEBUG)
11139 # define ALWAYS(X)      ((X)?1:(assert(0),0))
11140 # define NEVER(X)       ((X)?(assert(0),1):0)
11141 #else
11142 # define ALWAYS(X)      (X)
11143 # define NEVER(X)       (X)
11144 #endif
11145 #endif /* !defined(SQLITE_AMALGAMATION) */
11146 
11147 
11148 #ifndef SQLITE_OMIT_VIRTUALTABLE
11149 
11150 /* typedef sqlite3_int64 i64; */
11151 /* typedef sqlite3_uint64 u64; */
11152 
11153 typedef struct IdxColumn IdxColumn;
11154 typedef struct IdxConstraint IdxConstraint;
11155 typedef struct IdxScan IdxScan;
11156 typedef struct IdxStatement IdxStatement;
11157 typedef struct IdxTable IdxTable;
11158 typedef struct IdxWrite IdxWrite;
11159 
11160 #define STRLEN  (int)strlen
11161 
11162 /*
11163 ** A temp table name that we assume no user database will actually use.
11164 ** If this assumption proves incorrect triggers on the table with the
11165 ** conflicting name will be ignored.
11166 */
11167 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
11168 
11169 /*
11170 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
11171 ** any other type of single-ended range constraint on a column).
11172 **
11173 ** pLink:
11174 **   Used to temporarily link IdxConstraint objects into lists while
11175 **   creating candidate indexes.
11176 */
11177 struct IdxConstraint {
11178   char *zColl;                    /* Collation sequence */
11179   int bRange;                     /* True for range, false for eq */
11180   int iCol;                       /* Constrained table column */
11181   int bFlag;                      /* Used by idxFindCompatible() */
11182   int bDesc;                      /* True if ORDER BY <expr> DESC */
11183   IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
11184   IdxConstraint *pLink;           /* See above */
11185 };
11186 
11187 /*
11188 ** A single scan of a single table.
11189 */
11190 struct IdxScan {
11191   IdxTable *pTab;                 /* Associated table object */
11192   int iDb;                        /* Database containing table zTable */
11193   i64 covering;                   /* Mask of columns required for cov. index */
11194   IdxConstraint *pOrder;          /* ORDER BY columns */
11195   IdxConstraint *pEq;             /* List of == constraints */
11196   IdxConstraint *pRange;          /* List of < constraints */
11197   IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
11198 };
11199 
11200 /*
11201 ** Information regarding a single database table. Extracted from
11202 ** "PRAGMA table_info" by function idxGetTableInfo().
11203 */
11204 struct IdxColumn {
11205   char *zName;
11206   char *zColl;
11207   int iPk;
11208 };
11209 struct IdxTable {
11210   int nCol;
11211   char *zName;                    /* Table name */
11212   IdxColumn *aCol;
11213   IdxTable *pNext;                /* Next table in linked list of all tables */
11214 };
11215 
11216 /*
11217 ** An object of the following type is created for each unique table/write-op
11218 ** seen. The objects are stored in a singly-linked list beginning at
11219 ** sqlite3expert.pWrite.
11220 */
11221 struct IdxWrite {
11222   IdxTable *pTab;
11223   int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
11224   IdxWrite *pNext;
11225 };
11226 
11227 /*
11228 ** Each statement being analyzed is represented by an instance of this
11229 ** structure.
11230 */
11231 struct IdxStatement {
11232   int iId;                        /* Statement number */
11233   char *zSql;                     /* SQL statement */
11234   char *zIdx;                     /* Indexes */
11235   char *zEQP;                     /* Plan */
11236   IdxStatement *pNext;
11237 };
11238 
11239 
11240 /*
11241 ** A hash table for storing strings. With space for a payload string
11242 ** with each entry. Methods are:
11243 **
11244 **   idxHashInit()
11245 **   idxHashClear()
11246 **   idxHashAdd()
11247 **   idxHashSearch()
11248 */
11249 #define IDX_HASH_SIZE 1023
11250 typedef struct IdxHashEntry IdxHashEntry;
11251 typedef struct IdxHash IdxHash;
11252 struct IdxHashEntry {
11253   char *zKey;                     /* nul-terminated key */
11254   char *zVal;                     /* nul-terminated value string */
11255   char *zVal2;                    /* nul-terminated value string 2 */
11256   IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
11257   IdxHashEntry *pNext;            /* Next entry in hash */
11258 };
11259 struct IdxHash {
11260   IdxHashEntry *pFirst;
11261   IdxHashEntry *aHash[IDX_HASH_SIZE];
11262 };
11263 
11264 /*
11265 ** sqlite3expert object.
11266 */
11267 struct sqlite3expert {
11268   int iSample;                    /* Percentage of tables to sample for stat1 */
11269   sqlite3 *db;                    /* User database */
11270   sqlite3 *dbm;                   /* In-memory db for this analysis */
11271   sqlite3 *dbv;                   /* Vtab schema for this analysis */
11272   IdxTable *pTable;               /* List of all IdxTable objects */
11273   IdxScan *pScan;                 /* List of scan objects */
11274   IdxWrite *pWrite;               /* List of write objects */
11275   IdxStatement *pStatement;       /* List of IdxStatement objects */
11276   int bRun;                       /* True once analysis has run */
11277   char **pzErrmsg;
11278   int rc;                         /* Error code from whereinfo hook */
11279   IdxHash hIdx;                   /* Hash containing all candidate indexes */
11280   char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
11281 };
11282 
11283 
11284 /*
11285 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
11286 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
11287 */
11288 static void *idxMalloc(int *pRc, int nByte){
11289   void *pRet;
11290   assert( *pRc==SQLITE_OK );
11291   assert( nByte>0 );
11292   pRet = sqlite3_malloc(nByte);
11293   if( pRet ){
11294     memset(pRet, 0, nByte);
11295   }else{
11296     *pRc = SQLITE_NOMEM;
11297   }
11298   return pRet;
11299 }
11300 
11301 /*
11302 ** Initialize an IdxHash hash table.
11303 */
11304 static void idxHashInit(IdxHash *pHash){
11305   memset(pHash, 0, sizeof(IdxHash));
11306 }
11307 
11308 /*
11309 ** Reset an IdxHash hash table.
11310 */
11311 static void idxHashClear(IdxHash *pHash){
11312   int i;
11313   for(i=0; i<IDX_HASH_SIZE; i++){
11314     IdxHashEntry *pEntry;
11315     IdxHashEntry *pNext;
11316     for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
11317       pNext = pEntry->pHashNext;
11318       sqlite3_free(pEntry->zVal2);
11319       sqlite3_free(pEntry);
11320     }
11321   }
11322   memset(pHash, 0, sizeof(IdxHash));
11323 }
11324 
11325 /*
11326 ** Return the index of the hash bucket that the string specified by the
11327 ** arguments to this function belongs.
11328 */
11329 static int idxHashString(const char *z, int n){
11330   unsigned int ret = 0;
11331   int i;
11332   for(i=0; i<n; i++){
11333     ret += (ret<<3) + (unsigned char)(z[i]);
11334   }
11335   return (int)(ret % IDX_HASH_SIZE);
11336 }
11337 
11338 /*
11339 ** If zKey is already present in the hash table, return non-zero and do
11340 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
11341 ** the hash table passed as the second argument.
11342 */
11343 static int idxHashAdd(
11344   int *pRc,
11345   IdxHash *pHash,
11346   const char *zKey,
11347   const char *zVal
11348 ){
11349   int nKey = STRLEN(zKey);
11350   int iHash = idxHashString(zKey, nKey);
11351   int nVal = (zVal ? STRLEN(zVal) : 0);
11352   IdxHashEntry *pEntry;
11353   assert( iHash>=0 );
11354   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
11355     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
11356       return 1;
11357     }
11358   }
11359   pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
11360   if( pEntry ){
11361     pEntry->zKey = (char*)&pEntry[1];
11362     memcpy(pEntry->zKey, zKey, nKey);
11363     if( zVal ){
11364       pEntry->zVal = &pEntry->zKey[nKey+1];
11365       memcpy(pEntry->zVal, zVal, nVal);
11366     }
11367     pEntry->pHashNext = pHash->aHash[iHash];
11368     pHash->aHash[iHash] = pEntry;
11369 
11370     pEntry->pNext = pHash->pFirst;
11371     pHash->pFirst = pEntry;
11372   }
11373   return 0;
11374 }
11375 
11376 /*
11377 ** If zKey/nKey is present in the hash table, return a pointer to the
11378 ** hash-entry object.
11379 */
11380 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
11381   int iHash;
11382   IdxHashEntry *pEntry;
11383   if( nKey<0 ) nKey = STRLEN(zKey);
11384   iHash = idxHashString(zKey, nKey);
11385   assert( iHash>=0 );
11386   for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
11387     if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
11388       return pEntry;
11389     }
11390   }
11391   return 0;
11392 }
11393 
11394 /*
11395 ** If the hash table contains an entry with a key equal to the string
11396 ** passed as the final two arguments to this function, return a pointer
11397 ** to the payload string. Otherwise, if zKey/nKey is not present in the
11398 ** hash table, return NULL.
11399 */
11400 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
11401   IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
11402   if( pEntry ) return pEntry->zVal;
11403   return 0;
11404 }
11405 
11406 /*
11407 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
11408 ** variable to point to a copy of nul-terminated string zColl.
11409 */
11410 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
11411   IdxConstraint *pNew;
11412   int nColl = STRLEN(zColl);
11413 
11414   assert( *pRc==SQLITE_OK );
11415   pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
11416   if( pNew ){
11417     pNew->zColl = (char*)&pNew[1];
11418     memcpy(pNew->zColl, zColl, nColl+1);
11419   }
11420   return pNew;
11421 }
11422 
11423 /*
11424 ** An error associated with database handle db has just occurred. Pass
11425 ** the error message to callback function xOut.
11426 */
11427 static void idxDatabaseError(
11428   sqlite3 *db,                    /* Database handle */
11429   char **pzErrmsg                 /* Write error here */
11430 ){
11431   *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
11432 }
11433 
11434 /*
11435 ** Prepare an SQL statement.
11436 */
11437 static int idxPrepareStmt(
11438   sqlite3 *db,                    /* Database handle to compile against */
11439   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
11440   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
11441   const char *zSql                /* SQL statement to compile */
11442 ){
11443   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
11444   if( rc!=SQLITE_OK ){
11445     *ppStmt = 0;
11446     idxDatabaseError(db, pzErrmsg);
11447   }
11448   return rc;
11449 }
11450 
11451 /*
11452 ** Prepare an SQL statement using the results of a printf() formatting.
11453 */
11454 static int idxPrintfPrepareStmt(
11455   sqlite3 *db,                    /* Database handle to compile against */
11456   sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
11457   char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
11458   const char *zFmt,               /* printf() format of SQL statement */
11459   ...                             /* Trailing printf() arguments */
11460 ){
11461   va_list ap;
11462   int rc;
11463   char *zSql;
11464   va_start(ap, zFmt);
11465   zSql = sqlite3_vmprintf(zFmt, ap);
11466   if( zSql==0 ){
11467     rc = SQLITE_NOMEM;
11468   }else{
11469     rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
11470     sqlite3_free(zSql);
11471   }
11472   va_end(ap);
11473   return rc;
11474 }
11475 
11476 
11477 /*************************************************************************
11478 ** Beginning of virtual table implementation.
11479 */
11480 typedef struct ExpertVtab ExpertVtab;
11481 struct ExpertVtab {
11482   sqlite3_vtab base;
11483   IdxTable *pTab;
11484   sqlite3expert *pExpert;
11485 };
11486 
11487 typedef struct ExpertCsr ExpertCsr;
11488 struct ExpertCsr {
11489   sqlite3_vtab_cursor base;
11490   sqlite3_stmt *pData;
11491 };
11492 
11493 static char *expertDequote(const char *zIn){
11494   int n = STRLEN(zIn);
11495   char *zRet = sqlite3_malloc(n);
11496 
11497   assert( zIn[0]=='\'' );
11498   assert( zIn[n-1]=='\'' );
11499 
11500   if( zRet ){
11501     int iOut = 0;
11502     int iIn = 0;
11503     for(iIn=1; iIn<(n-1); iIn++){
11504       if( zIn[iIn]=='\'' ){
11505         assert( zIn[iIn+1]=='\'' );
11506         iIn++;
11507       }
11508       zRet[iOut++] = zIn[iIn];
11509     }
11510     zRet[iOut] = '\0';
11511   }
11512 
11513   return zRet;
11514 }
11515 
11516 /*
11517 ** This function is the implementation of both the xConnect and xCreate
11518 ** methods of the r-tree virtual table.
11519 **
11520 **   argv[0]   -> module name
11521 **   argv[1]   -> database name
11522 **   argv[2]   -> table name
11523 **   argv[...] -> column names...
11524 */
11525 static int expertConnect(
11526   sqlite3 *db,
11527   void *pAux,
11528   int argc, const char *const*argv,
11529   sqlite3_vtab **ppVtab,
11530   char **pzErr
11531 ){
11532   sqlite3expert *pExpert = (sqlite3expert*)pAux;
11533   ExpertVtab *p = 0;
11534   int rc;
11535 
11536   if( argc!=4 ){
11537     *pzErr = sqlite3_mprintf("internal error!");
11538     rc = SQLITE_ERROR;
11539   }else{
11540     char *zCreateTable = expertDequote(argv[3]);
11541     if( zCreateTable ){
11542       rc = sqlite3_declare_vtab(db, zCreateTable);
11543       if( rc==SQLITE_OK ){
11544         p = idxMalloc(&rc, sizeof(ExpertVtab));
11545       }
11546       if( rc==SQLITE_OK ){
11547         p->pExpert = pExpert;
11548         p->pTab = pExpert->pTable;
11549         assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
11550       }
11551       sqlite3_free(zCreateTable);
11552     }else{
11553       rc = SQLITE_NOMEM;
11554     }
11555   }
11556 
11557   *ppVtab = (sqlite3_vtab*)p;
11558   return rc;
11559 }
11560 
11561 static int expertDisconnect(sqlite3_vtab *pVtab){
11562   ExpertVtab *p = (ExpertVtab*)pVtab;
11563   sqlite3_free(p);
11564   return SQLITE_OK;
11565 }
11566 
11567 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
11568   ExpertVtab *p = (ExpertVtab*)pVtab;
11569   int rc = SQLITE_OK;
11570   int n = 0;
11571   IdxScan *pScan;
11572   const int opmask =
11573     SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
11574     SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
11575     SQLITE_INDEX_CONSTRAINT_LE;
11576 
11577   pScan = idxMalloc(&rc, sizeof(IdxScan));
11578   if( pScan ){
11579     int i;
11580 
11581     /* Link the new scan object into the list */
11582     pScan->pTab = p->pTab;
11583     pScan->pNextScan = p->pExpert->pScan;
11584     p->pExpert->pScan = pScan;
11585 
11586     /* Add the constraints to the IdxScan object */
11587     for(i=0; i<pIdxInfo->nConstraint; i++){
11588       struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
11589       if( pCons->usable
11590        && pCons->iColumn>=0
11591        && p->pTab->aCol[pCons->iColumn].iPk==0
11592        && (pCons->op & opmask)
11593       ){
11594         IdxConstraint *pNew;
11595         const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
11596         pNew = idxNewConstraint(&rc, zColl);
11597         if( pNew ){
11598           pNew->iCol = pCons->iColumn;
11599           if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
11600             pNew->pNext = pScan->pEq;
11601             pScan->pEq = pNew;
11602           }else{
11603             pNew->bRange = 1;
11604             pNew->pNext = pScan->pRange;
11605             pScan->pRange = pNew;
11606           }
11607         }
11608         n++;
11609         pIdxInfo->aConstraintUsage[i].argvIndex = n;
11610       }
11611     }
11612 
11613     /* Add the ORDER BY to the IdxScan object */
11614     for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
11615       int iCol = pIdxInfo->aOrderBy[i].iColumn;
11616       if( iCol>=0 ){
11617         IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
11618         if( pNew ){
11619           pNew->iCol = iCol;
11620           pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
11621           pNew->pNext = pScan->pOrder;
11622           pNew->pLink = pScan->pOrder;
11623           pScan->pOrder = pNew;
11624           n++;
11625         }
11626       }
11627     }
11628   }
11629 
11630   pIdxInfo->estimatedCost = 1000000.0 / (n+1);
11631   return rc;
11632 }
11633 
11634 static int expertUpdate(
11635   sqlite3_vtab *pVtab,
11636   int nData,
11637   sqlite3_value **azData,
11638   sqlite_int64 *pRowid
11639 ){
11640   (void)pVtab;
11641   (void)nData;
11642   (void)azData;
11643   (void)pRowid;
11644   return SQLITE_OK;
11645 }
11646 
11647 /*
11648 ** Virtual table module xOpen method.
11649 */
11650 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
11651   int rc = SQLITE_OK;
11652   ExpertCsr *pCsr;
11653   (void)pVTab;
11654   pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
11655   *ppCursor = (sqlite3_vtab_cursor*)pCsr;
11656   return rc;
11657 }
11658 
11659 /*
11660 ** Virtual table module xClose method.
11661 */
11662 static int expertClose(sqlite3_vtab_cursor *cur){
11663   ExpertCsr *pCsr = (ExpertCsr*)cur;
11664   sqlite3_finalize(pCsr->pData);
11665   sqlite3_free(pCsr);
11666   return SQLITE_OK;
11667 }
11668 
11669 /*
11670 ** Virtual table module xEof method.
11671 **
11672 ** Return non-zero if the cursor does not currently point to a valid
11673 ** record (i.e if the scan has finished), or zero otherwise.
11674 */
11675 static int expertEof(sqlite3_vtab_cursor *cur){
11676   ExpertCsr *pCsr = (ExpertCsr*)cur;
11677   return pCsr->pData==0;
11678 }
11679 
11680 /*
11681 ** Virtual table module xNext method.
11682 */
11683 static int expertNext(sqlite3_vtab_cursor *cur){
11684   ExpertCsr *pCsr = (ExpertCsr*)cur;
11685   int rc = SQLITE_OK;
11686 
11687   assert( pCsr->pData );
11688   rc = sqlite3_step(pCsr->pData);
11689   if( rc!=SQLITE_ROW ){
11690     rc = sqlite3_finalize(pCsr->pData);
11691     pCsr->pData = 0;
11692   }else{
11693     rc = SQLITE_OK;
11694   }
11695 
11696   return rc;
11697 }
11698 
11699 /*
11700 ** Virtual table module xRowid method.
11701 */
11702 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
11703   (void)cur;
11704   *pRowid = 0;
11705   return SQLITE_OK;
11706 }
11707 
11708 /*
11709 ** Virtual table module xColumn method.
11710 */
11711 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
11712   ExpertCsr *pCsr = (ExpertCsr*)cur;
11713   sqlite3_value *pVal;
11714   pVal = sqlite3_column_value(pCsr->pData, i);
11715   if( pVal ){
11716     sqlite3_result_value(ctx, pVal);
11717   }
11718   return SQLITE_OK;
11719 }
11720 
11721 /*
11722 ** Virtual table module xFilter method.
11723 */
11724 static int expertFilter(
11725   sqlite3_vtab_cursor *cur,
11726   int idxNum, const char *idxStr,
11727   int argc, sqlite3_value **argv
11728 ){
11729   ExpertCsr *pCsr = (ExpertCsr*)cur;
11730   ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
11731   sqlite3expert *pExpert = pVtab->pExpert;
11732   int rc;
11733 
11734   (void)idxNum;
11735   (void)idxStr;
11736   (void)argc;
11737   (void)argv;
11738   rc = sqlite3_finalize(pCsr->pData);
11739   pCsr->pData = 0;
11740   if( rc==SQLITE_OK ){
11741     rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
11742         "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
11743     );
11744   }
11745 
11746   if( rc==SQLITE_OK ){
11747     rc = expertNext(cur);
11748   }
11749   return rc;
11750 }
11751 
11752 static int idxRegisterVtab(sqlite3expert *p){
11753   static sqlite3_module expertModule = {
11754     2,                            /* iVersion */
11755     expertConnect,                /* xCreate - create a table */
11756     expertConnect,                /* xConnect - connect to an existing table */
11757     expertBestIndex,              /* xBestIndex - Determine search strategy */
11758     expertDisconnect,             /* xDisconnect - Disconnect from a table */
11759     expertDisconnect,             /* xDestroy - Drop a table */
11760     expertOpen,                   /* xOpen - open a cursor */
11761     expertClose,                  /* xClose - close a cursor */
11762     expertFilter,                 /* xFilter - configure scan constraints */
11763     expertNext,                   /* xNext - advance a cursor */
11764     expertEof,                    /* xEof */
11765     expertColumn,                 /* xColumn - read data */
11766     expertRowid,                  /* xRowid - read data */
11767     expertUpdate,                 /* xUpdate - write data */
11768     0,                            /* xBegin - begin transaction */
11769     0,                            /* xSync - sync transaction */
11770     0,                            /* xCommit - commit transaction */
11771     0,                            /* xRollback - rollback transaction */
11772     0,                            /* xFindFunction - function overloading */
11773     0,                            /* xRename - rename the table */
11774     0,                            /* xSavepoint */
11775     0,                            /* xRelease */
11776     0,                            /* xRollbackTo */
11777     0,                            /* xShadowName */
11778     0,                            /* xIntegrity */
11779   };
11780 
11781   return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
11782 }
11783 /*
11784 ** End of virtual table implementation.
11785 *************************************************************************/
11786 /*
11787 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
11788 ** is called, set it to the return value of sqlite3_finalize() before
11789 ** returning. Otherwise, discard the sqlite3_finalize() return value.
11790 */
11791 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
11792   int rc = sqlite3_finalize(pStmt);
11793   if( *pRc==SQLITE_OK ) *pRc = rc;
11794 }
11795 
11796 /*
11797 ** Attempt to allocate an IdxTable structure corresponding to table zTab
11798 ** in the main database of connection db. If successful, set (*ppOut) to
11799 ** point to the new object and return SQLITE_OK. Otherwise, return an
11800 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
11801 ** set to point to an error string.
11802 **
11803 ** It is the responsibility of the caller to eventually free either the
11804 ** IdxTable object or error message using sqlite3_free().
11805 */
11806 static int idxGetTableInfo(
11807   sqlite3 *db,                    /* Database connection to read details from */
11808   const char *zTab,               /* Table name */
11809   IdxTable **ppOut,               /* OUT: New object (if successful) */
11810   char **pzErrmsg                 /* OUT: Error message (if not) */
11811 ){
11812   sqlite3_stmt *p1 = 0;
11813   int nCol = 0;
11814   int nTab;
11815   int nByte;
11816   IdxTable *pNew = 0;
11817   int rc, rc2;
11818   char *pCsr = 0;
11819   int nPk = 0;
11820 
11821   *ppOut = 0;
11822   if( zTab==0 ) return SQLITE_ERROR;
11823   nTab = STRLEN(zTab);
11824   nByte = sizeof(IdxTable) + nTab + 1;
11825   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
11826   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
11827     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
11828     const char *zColSeq = 0;
11829     if( zCol==0 ){
11830       rc = SQLITE_ERROR;
11831       break;
11832     }
11833     nByte += 1 + STRLEN(zCol);
11834     rc = sqlite3_table_column_metadata(
11835         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
11836     );
11837     if( zColSeq==0 ) zColSeq = "binary";
11838     nByte += 1 + STRLEN(zColSeq);
11839     nCol++;
11840     nPk += (sqlite3_column_int(p1, 5)>0);
11841   }
11842   rc2 = sqlite3_reset(p1);
11843   if( rc==SQLITE_OK ) rc = rc2;
11844 
11845   nByte += sizeof(IdxColumn) * nCol;
11846   if( rc==SQLITE_OK ){
11847     pNew = idxMalloc(&rc, nByte);
11848   }
11849   if( rc==SQLITE_OK ){
11850     pNew->aCol = (IdxColumn*)&pNew[1];
11851     pNew->nCol = nCol;
11852     pCsr = (char*)&pNew->aCol[nCol];
11853   }
11854 
11855   nCol = 0;
11856   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
11857     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
11858     const char *zColSeq = 0;
11859     int nCopy;
11860     if( zCol==0 ) continue;
11861     nCopy = STRLEN(zCol) + 1;
11862     pNew->aCol[nCol].zName = pCsr;
11863     pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
11864     memcpy(pCsr, zCol, nCopy);
11865     pCsr += nCopy;
11866 
11867     rc = sqlite3_table_column_metadata(
11868         db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
11869     );
11870     if( rc==SQLITE_OK ){
11871       if( zColSeq==0 ) zColSeq = "binary";
11872       nCopy = STRLEN(zColSeq) + 1;
11873       pNew->aCol[nCol].zColl = pCsr;
11874       memcpy(pCsr, zColSeq, nCopy);
11875       pCsr += nCopy;
11876     }
11877 
11878     nCol++;
11879   }
11880   idxFinalize(&rc, p1);
11881 
11882   if( rc!=SQLITE_OK ){
11883     sqlite3_free(pNew);
11884     pNew = 0;
11885   }else if( ALWAYS(pNew!=0) ){
11886     pNew->zName = pCsr;
11887     if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
11888   }
11889 
11890   *ppOut = pNew;
11891   return rc;
11892 }
11893 
11894 /*
11895 ** This function is a no-op if *pRc is set to anything other than
11896 ** SQLITE_OK when it is called.
11897 **
11898 ** If *pRc is initially set to SQLITE_OK, then the text specified by
11899 ** the printf() style arguments is appended to zIn and the result returned
11900 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
11901 ** zIn before returning.
11902 */
11903 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
11904   va_list ap;
11905   char *zAppend = 0;
11906   char *zRet = 0;
11907   int nIn = zIn ? STRLEN(zIn) : 0;
11908   int nAppend = 0;
11909   va_start(ap, zFmt);
11910   if( *pRc==SQLITE_OK ){
11911     zAppend = sqlite3_vmprintf(zFmt, ap);
11912     if( zAppend ){
11913       nAppend = STRLEN(zAppend);
11914       zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
11915     }
11916     if( zAppend && zRet ){
11917       if( nIn ) memcpy(zRet, zIn, nIn);
11918       memcpy(&zRet[nIn], zAppend, nAppend+1);
11919     }else{
11920       sqlite3_free(zRet);
11921       zRet = 0;
11922       *pRc = SQLITE_NOMEM;
11923     }
11924     sqlite3_free(zAppend);
11925     sqlite3_free(zIn);
11926   }
11927   va_end(ap);
11928   return zRet;
11929 }
11930 
11931 /*
11932 ** Return true if zId must be quoted in order to use it as an SQL
11933 ** identifier, or false otherwise.
11934 */
11935 static int idxIdentifierRequiresQuotes(const char *zId){
11936   int i;
11937   int nId = STRLEN(zId);
11938 
11939   if( sqlite3_keyword_check(zId, nId) ) return 1;
11940 
11941   for(i=0; zId[i]; i++){
11942     if( !(zId[i]=='_')
11943      && !(zId[i]>='0' && zId[i]<='9')
11944      && !(zId[i]>='a' && zId[i]<='z')
11945      && !(zId[i]>='A' && zId[i]<='Z')
11946     ){
11947       return 1;
11948     }
11949   }
11950   return 0;
11951 }
11952 
11953 /*
11954 ** This function appends an index column definition suitable for constraint
11955 ** pCons to the string passed as zIn and returns the result.
11956 */
11957 static char *idxAppendColDefn(
11958   int *pRc,                       /* IN/OUT: Error code */
11959   char *zIn,                      /* Column defn accumulated so far */
11960   IdxTable *pTab,                 /* Table index will be created on */
11961   IdxConstraint *pCons
11962 ){
11963   char *zRet = zIn;
11964   IdxColumn *p = &pTab->aCol[pCons->iCol];
11965   if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
11966 
11967   if( idxIdentifierRequiresQuotes(p->zName) ){
11968     zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
11969   }else{
11970     zRet = idxAppendText(pRc, zRet, "%s", p->zName);
11971   }
11972 
11973   if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
11974     if( idxIdentifierRequiresQuotes(pCons->zColl) ){
11975       zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
11976     }else{
11977       zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
11978     }
11979   }
11980 
11981   if( pCons->bDesc ){
11982     zRet = idxAppendText(pRc, zRet, " DESC");
11983   }
11984   return zRet;
11985 }
11986 
11987 /*
11988 ** Search database dbm for an index compatible with the one idxCreateFromCons()
11989 ** would create from arguments pScan, pEq and pTail. If no error occurs and
11990 ** such an index is found, return non-zero. Or, if no such index is found,
11991 ** return zero.
11992 **
11993 ** If an error occurs, set *pRc to an SQLite error code and return zero.
11994 */
11995 static int idxFindCompatible(
11996   int *pRc,                       /* OUT: Error code */
11997   sqlite3* dbm,                   /* Database to search */
11998   IdxScan *pScan,                 /* Scan for table to search for index on */
11999   IdxConstraint *pEq,             /* List of == constraints */
12000   IdxConstraint *pTail            /* List of range constraints */
12001 ){
12002   const char *zTbl = pScan->pTab->zName;
12003   sqlite3_stmt *pIdxList = 0;
12004   IdxConstraint *pIter;
12005   int nEq = 0;                    /* Number of elements in pEq */
12006   int rc;
12007 
12008   /* Count the elements in list pEq */
12009   for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
12010 
12011   rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
12012   while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
12013     int bMatch = 1;
12014     IdxConstraint *pT = pTail;
12015     sqlite3_stmt *pInfo = 0;
12016     const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
12017     if( zIdx==0 ) continue;
12018 
12019     /* Zero the IdxConstraint.bFlag values in the pEq list */
12020     for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
12021 
12022     rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
12023     while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
12024       int iIdx = sqlite3_column_int(pInfo, 0);
12025       int iCol = sqlite3_column_int(pInfo, 1);
12026       const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
12027 
12028       if( iIdx<nEq ){
12029         for(pIter=pEq; pIter; pIter=pIter->pLink){
12030           if( pIter->bFlag ) continue;
12031           if( pIter->iCol!=iCol ) continue;
12032           if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
12033           pIter->bFlag = 1;
12034           break;
12035         }
12036         if( pIter==0 ){
12037           bMatch = 0;
12038           break;
12039         }
12040       }else{
12041         if( pT ){
12042           if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
12043             bMatch = 0;
12044             break;
12045           }
12046           pT = pT->pLink;
12047         }
12048       }
12049     }
12050     idxFinalize(&rc, pInfo);
12051 
12052     if( rc==SQLITE_OK && bMatch ){
12053       sqlite3_finalize(pIdxList);
12054       return 1;
12055     }
12056   }
12057   idxFinalize(&rc, pIdxList);
12058 
12059   *pRc = rc;
12060   return 0;
12061 }
12062 
12063 /* Callback for sqlite3_exec() with query with leading count(*) column.
12064  * The first argument is expected to be an int*, referent to be incremented
12065  * if that leading column is not exactly '0'.
12066  */
12067 static int countNonzeros(void* pCount, int nc,
12068                          char* azResults[], char* azColumns[]){
12069   (void)azColumns;  /* Suppress unused parameter warning */
12070   if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
12071     *((int *)pCount) += 1;
12072   }
12073   return 0;
12074 }
12075 
12076 static int idxCreateFromCons(
12077   sqlite3expert *p,
12078   IdxScan *pScan,
12079   IdxConstraint *pEq,
12080   IdxConstraint *pTail
12081 ){
12082   sqlite3 *dbm = p->dbm;
12083   int rc = SQLITE_OK;
12084   if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
12085     IdxTable *pTab = pScan->pTab;
12086     char *zCols = 0;
12087     char *zIdx = 0;
12088     IdxConstraint *pCons;
12089     unsigned int h = 0;
12090     const char *zFmt;
12091 
12092     for(pCons=pEq; pCons; pCons=pCons->pLink){
12093       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12094     }
12095     for(pCons=pTail; pCons; pCons=pCons->pLink){
12096       zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12097     }
12098 
12099     if( rc==SQLITE_OK ){
12100       /* Hash the list of columns to come up with a name for the index */
12101       const char *zTable = pScan->pTab->zName;
12102       int quoteTable = idxIdentifierRequiresQuotes(zTable);
12103       char *zName = 0;          /* Index name */
12104       int collisions = 0;
12105       do{
12106         int i;
12107         char *zFind;
12108         for(i=0; zCols[i]; i++){
12109           h += ((h<<3) + zCols[i]);
12110         }
12111         sqlite3_free(zName);
12112         zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
12113         if( zName==0 ) break;
12114         /* Is is unique among table, view and index names? */
12115         zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
12116           " AND type in ('index','table','view')";
12117         zFind = sqlite3_mprintf(zFmt, zName);
12118         i = 0;
12119         rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
12120         assert(rc==SQLITE_OK);
12121         sqlite3_free(zFind);
12122         if( i==0 ){
12123           collisions = 0;
12124           break;
12125         }
12126         ++collisions;
12127       }while( collisions<50 && zName!=0 );
12128       if( collisions ){
12129         /* This return means "Gave up trying to find a unique index name." */
12130         rc = SQLITE_BUSY_TIMEOUT;
12131       }else if( zName==0 ){
12132         rc = SQLITE_NOMEM;
12133       }else{
12134         if( quoteTable ){
12135           zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
12136         }else{
12137           zFmt = "CREATE INDEX %s ON %s(%s)";
12138         }
12139         zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
12140         if( !zIdx ){
12141           rc = SQLITE_NOMEM;
12142         }else{
12143           rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
12144           if( rc!=SQLITE_OK ){
12145             rc = SQLITE_BUSY_TIMEOUT;
12146           }else{
12147             idxHashAdd(&rc, &p->hIdx, zName, zIdx);
12148           }
12149         }
12150         sqlite3_free(zName);
12151         sqlite3_free(zIdx);
12152       }
12153     }
12154 
12155     sqlite3_free(zCols);
12156   }
12157   return rc;
12158 }
12159 
12160 /*
12161 ** Return true if list pList (linked by IdxConstraint.pLink) contains
12162 ** a constraint compatible with *p. Otherwise return false.
12163 */
12164 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
12165   IdxConstraint *pCmp;
12166   for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
12167     if( p->iCol==pCmp->iCol ) return 1;
12168   }
12169   return 0;
12170 }
12171 
12172 static int idxCreateFromWhere(
12173   sqlite3expert *p,
12174   IdxScan *pScan,                 /* Create indexes for this scan */
12175   IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
12176 ){
12177   IdxConstraint *p1 = 0;
12178   IdxConstraint *pCon;
12179   int rc;
12180 
12181   /* Gather up all the == constraints. */
12182   for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
12183     if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12184       pCon->pLink = p1;
12185       p1 = pCon;
12186     }
12187   }
12188 
12189   /* Create an index using the == constraints collected above. And the
12190   ** range constraint/ORDER BY terms passed in by the caller, if any. */
12191   rc = idxCreateFromCons(p, pScan, p1, pTail);
12192 
12193   /* If no range/ORDER BY passed by the caller, create a version of the
12194   ** index for each range constraint.  */
12195   if( pTail==0 ){
12196     for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
12197       assert( pCon->pLink==0 );
12198       if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12199         rc = idxCreateFromCons(p, pScan, p1, pCon);
12200       }
12201     }
12202   }
12203 
12204   return rc;
12205 }
12206 
12207 /*
12208 ** Create candidate indexes in database [dbm] based on the data in
12209 ** linked-list pScan.
12210 */
12211 static int idxCreateCandidates(sqlite3expert *p){
12212   int rc = SQLITE_OK;
12213   IdxScan *pIter;
12214 
12215   for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
12216     rc = idxCreateFromWhere(p, pIter, 0);
12217     if( rc==SQLITE_OK && pIter->pOrder ){
12218       rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
12219     }
12220   }
12221 
12222   return rc;
12223 }
12224 
12225 /*
12226 ** Free all elements of the linked list starting at pConstraint.
12227 */
12228 static void idxConstraintFree(IdxConstraint *pConstraint){
12229   IdxConstraint *pNext;
12230   IdxConstraint *p;
12231 
12232   for(p=pConstraint; p; p=pNext){
12233     pNext = p->pNext;
12234     sqlite3_free(p);
12235   }
12236 }
12237 
12238 /*
12239 ** Free all elements of the linked list starting from pScan up until pLast
12240 ** (pLast is not freed).
12241 */
12242 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
12243   IdxScan *p;
12244   IdxScan *pNext;
12245   for(p=pScan; p!=pLast; p=pNext){
12246     pNext = p->pNextScan;
12247     idxConstraintFree(p->pOrder);
12248     idxConstraintFree(p->pEq);
12249     idxConstraintFree(p->pRange);
12250     sqlite3_free(p);
12251   }
12252 }
12253 
12254 /*
12255 ** Free all elements of the linked list starting from pStatement up
12256 ** until pLast (pLast is not freed).
12257 */
12258 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
12259   IdxStatement *p;
12260   IdxStatement *pNext;
12261   for(p=pStatement; p!=pLast; p=pNext){
12262     pNext = p->pNext;
12263     sqlite3_free(p->zEQP);
12264     sqlite3_free(p->zIdx);
12265     sqlite3_free(p);
12266   }
12267 }
12268 
12269 /*
12270 ** Free the linked list of IdxTable objects starting at pTab.
12271 */
12272 static void idxTableFree(IdxTable *pTab){
12273   IdxTable *pIter;
12274   IdxTable *pNext;
12275   for(pIter=pTab; pIter; pIter=pNext){
12276     pNext = pIter->pNext;
12277     sqlite3_free(pIter);
12278   }
12279 }
12280 
12281 /*
12282 ** Free the linked list of IdxWrite objects starting at pTab.
12283 */
12284 static void idxWriteFree(IdxWrite *pTab){
12285   IdxWrite *pIter;
12286   IdxWrite *pNext;
12287   for(pIter=pTab; pIter; pIter=pNext){
12288     pNext = pIter->pNext;
12289     sqlite3_free(pIter);
12290   }
12291 }
12292 
12293 
12294 
12295 /*
12296 ** This function is called after candidate indexes have been created. It
12297 ** runs all the queries to see which indexes they prefer, and populates
12298 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
12299 */
12300 static int idxFindIndexes(
12301   sqlite3expert *p,
12302   char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
12303 ){
12304   IdxStatement *pStmt;
12305   sqlite3 *dbm = p->dbm;
12306   int rc = SQLITE_OK;
12307 
12308   IdxHash hIdx;
12309   idxHashInit(&hIdx);
12310 
12311   for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
12312     IdxHashEntry *pEntry;
12313     sqlite3_stmt *pExplain = 0;
12314     idxHashClear(&hIdx);
12315     rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
12316         "EXPLAIN QUERY PLAN %s", pStmt->zSql
12317     );
12318     while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
12319       /* int iId = sqlite3_column_int(pExplain, 0); */
12320       /* int iParent = sqlite3_column_int(pExplain, 1); */
12321       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
12322       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
12323       int nDetail;
12324       int i;
12325 
12326       if( !zDetail ) continue;
12327       nDetail = STRLEN(zDetail);
12328 
12329       for(i=0; i<nDetail; i++){
12330         const char *zIdx = 0;
12331         if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
12332           zIdx = &zDetail[i+13];
12333         }else if( i+22<nDetail
12334             && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
12335         ){
12336           zIdx = &zDetail[i+22];
12337         }
12338         if( zIdx ){
12339           const char *zSql;
12340           int nIdx = 0;
12341           while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
12342             nIdx++;
12343           }
12344           zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
12345           if( zSql ){
12346             idxHashAdd(&rc, &hIdx, zSql, 0);
12347             if( rc ) goto find_indexes_out;
12348           }
12349           break;
12350         }
12351       }
12352 
12353       if( zDetail[0]!='-' ){
12354         pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
12355       }
12356     }
12357 
12358     for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
12359       pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
12360     }
12361 
12362     idxFinalize(&rc, pExplain);
12363   }
12364 
12365  find_indexes_out:
12366   idxHashClear(&hIdx);
12367   return rc;
12368 }
12369 
12370 static int idxAuthCallback(
12371   void *pCtx,
12372   int eOp,
12373   const char *z3,
12374   const char *z4,
12375   const char *zDb,
12376   const char *zTrigger
12377 ){
12378   int rc = SQLITE_OK;
12379   (void)z4;
12380   (void)zTrigger;
12381   if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
12382     if( sqlite3_stricmp(zDb, "main")==0 ){
12383       sqlite3expert *p = (sqlite3expert*)pCtx;
12384       IdxTable *pTab;
12385       for(pTab=p->pTable; pTab; pTab=pTab->pNext){
12386         if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
12387       }
12388       if( pTab ){
12389         IdxWrite *pWrite;
12390         for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
12391           if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
12392         }
12393         if( pWrite==0 ){
12394           pWrite = idxMalloc(&rc, sizeof(IdxWrite));
12395           if( rc==SQLITE_OK ){
12396             pWrite->pTab = pTab;
12397             pWrite->eOp = eOp;
12398             pWrite->pNext = p->pWrite;
12399             p->pWrite = pWrite;
12400           }
12401         }
12402       }
12403     }
12404   }
12405   return rc;
12406 }
12407 
12408 static int idxProcessOneTrigger(
12409   sqlite3expert *p,
12410   IdxWrite *pWrite,
12411   char **pzErr
12412 ){
12413   static const char *zInt = UNIQUE_TABLE_NAME;
12414   static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
12415   IdxTable *pTab = pWrite->pTab;
12416   const char *zTab = pTab->zName;
12417   const char *zSql =
12418     "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
12419     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
12420     "ORDER BY type;";
12421   sqlite3_stmt *pSelect = 0;
12422   int rc = SQLITE_OK;
12423   char *zWrite = 0;
12424 
12425   /* Create the table and its triggers in the temp schema */
12426   rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
12427   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
12428     const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
12429     if( zCreate==0 ) continue;
12430     rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
12431   }
12432   idxFinalize(&rc, pSelect);
12433 
12434   /* Rename the table in the temp schema to zInt */
12435   if( rc==SQLITE_OK ){
12436     char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
12437     if( z==0 ){
12438       rc = SQLITE_NOMEM;
12439     }else{
12440       rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
12441       sqlite3_free(z);
12442     }
12443   }
12444 
12445   switch( pWrite->eOp ){
12446     case SQLITE_INSERT: {
12447       int i;
12448       zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
12449       for(i=0; i<pTab->nCol; i++){
12450         zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
12451       }
12452       zWrite = idxAppendText(&rc, zWrite, ")");
12453       break;
12454     }
12455     case SQLITE_UPDATE: {
12456       int i;
12457       zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
12458       for(i=0; i<pTab->nCol; i++){
12459         zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
12460             pTab->aCol[i].zName
12461         );
12462       }
12463       break;
12464     }
12465     default: {
12466       assert( pWrite->eOp==SQLITE_DELETE );
12467       if( rc==SQLITE_OK ){
12468         zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
12469         if( zWrite==0 ) rc = SQLITE_NOMEM;
12470       }
12471     }
12472   }
12473 
12474   if( rc==SQLITE_OK ){
12475     sqlite3_stmt *pX = 0;
12476     rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
12477     idxFinalize(&rc, pX);
12478     if( rc!=SQLITE_OK ){
12479       idxDatabaseError(p->dbv, pzErr);
12480     }
12481   }
12482   sqlite3_free(zWrite);
12483 
12484   if( rc==SQLITE_OK ){
12485     rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
12486   }
12487 
12488   return rc;
12489 }
12490 
12491 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
12492   int rc = SQLITE_OK;
12493   IdxWrite *pEnd = 0;
12494   IdxWrite *pFirst = p->pWrite;
12495 
12496   while( rc==SQLITE_OK && pFirst!=pEnd ){
12497     IdxWrite *pIter;
12498     for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
12499       rc = idxProcessOneTrigger(p, pIter, pzErr);
12500     }
12501     pEnd = pFirst;
12502     pFirst = p->pWrite;
12503   }
12504 
12505   return rc;
12506 }
12507 
12508 
12509 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
12510   int rc = idxRegisterVtab(p);
12511   sqlite3_stmt *pSchema = 0;
12512 
12513   /* For each table in the main db schema:
12514   **
12515   **   1) Add an entry to the p->pTable list, and
12516   **   2) Create the equivalent virtual table in dbv.
12517   */
12518   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
12519       "SELECT type, name, sql, 1 FROM sqlite_schema "
12520       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
12521       " UNION ALL "
12522       "SELECT type, name, sql, 2 FROM sqlite_schema "
12523       "WHERE type = 'trigger'"
12524       "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
12525       "ORDER BY 4, 1"
12526   );
12527   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
12528     const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
12529     const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
12530     const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
12531 
12532     if( zType==0 || zName==0 ) continue;
12533     if( zType[0]=='v' || zType[1]=='r' ){
12534       if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
12535     }else{
12536       IdxTable *pTab;
12537       rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
12538       if( rc==SQLITE_OK ){
12539         int i;
12540         char *zInner = 0;
12541         char *zOuter = 0;
12542         pTab->pNext = p->pTable;
12543         p->pTable = pTab;
12544 
12545         /* The statement the vtab will pass to sqlite3_declare_vtab() */
12546         zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
12547         for(i=0; i<pTab->nCol; i++){
12548           zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
12549               (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
12550           );
12551         }
12552         zInner = idxAppendText(&rc, zInner, ")");
12553 
12554         /* The CVT statement to create the vtab */
12555         zOuter = idxAppendText(&rc, 0,
12556             "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
12557         );
12558         if( rc==SQLITE_OK ){
12559           rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
12560         }
12561         sqlite3_free(zInner);
12562         sqlite3_free(zOuter);
12563       }
12564     }
12565   }
12566   idxFinalize(&rc, pSchema);
12567   return rc;
12568 }
12569 
12570 struct IdxSampleCtx {
12571   int iTarget;
12572   double target;                  /* Target nRet/nRow value */
12573   double nRow;                    /* Number of rows seen */
12574   double nRet;                    /* Number of rows returned */
12575 };
12576 
12577 static void idxSampleFunc(
12578   sqlite3_context *pCtx,
12579   int argc,
12580   sqlite3_value **argv
12581 ){
12582   struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
12583   int bRet;
12584 
12585   (void)argv;
12586   assert( argc==0 );
12587   if( p->nRow==0.0 ){
12588     bRet = 1;
12589   }else{
12590     bRet = (p->nRet / p->nRow) <= p->target;
12591     if( bRet==0 ){
12592       unsigned short rnd;
12593       sqlite3_randomness(2, (void*)&rnd);
12594       bRet = ((int)rnd % 100) <= p->iTarget;
12595     }
12596   }
12597 
12598   sqlite3_result_int(pCtx, bRet);
12599   p->nRow += 1.0;
12600   p->nRet += (double)bRet;
12601 }
12602 
12603 struct IdxRemCtx {
12604   int nSlot;
12605   struct IdxRemSlot {
12606     int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
12607     i64 iVal;                     /* SQLITE_INTEGER value */
12608     double rVal;                  /* SQLITE_FLOAT value */
12609     int nByte;                    /* Bytes of space allocated at z */
12610     int n;                        /* Size of buffer z */
12611     char *z;                      /* SQLITE_TEXT/BLOB value */
12612   } aSlot[1];
12613 };
12614 
12615 /*
12616 ** Implementation of scalar function rem().
12617 */
12618 static void idxRemFunc(
12619   sqlite3_context *pCtx,
12620   int argc,
12621   sqlite3_value **argv
12622 ){
12623   struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
12624   struct IdxRemSlot *pSlot;
12625   int iSlot;
12626   assert( argc==2 );
12627 
12628   iSlot = sqlite3_value_int(argv[0]);
12629   assert( iSlot<=p->nSlot );
12630   pSlot = &p->aSlot[iSlot];
12631 
12632   switch( pSlot->eType ){
12633     case SQLITE_NULL:
12634       /* no-op */
12635       break;
12636 
12637     case SQLITE_INTEGER:
12638       sqlite3_result_int64(pCtx, pSlot->iVal);
12639       break;
12640 
12641     case SQLITE_FLOAT:
12642       sqlite3_result_double(pCtx, pSlot->rVal);
12643       break;
12644 
12645     case SQLITE_BLOB:
12646       sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
12647       break;
12648 
12649     case SQLITE_TEXT:
12650       sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
12651       break;
12652   }
12653 
12654   pSlot->eType = sqlite3_value_type(argv[1]);
12655   switch( pSlot->eType ){
12656     case SQLITE_NULL:
12657       /* no-op */
12658       break;
12659 
12660     case SQLITE_INTEGER:
12661       pSlot->iVal = sqlite3_value_int64(argv[1]);
12662       break;
12663 
12664     case SQLITE_FLOAT:
12665       pSlot->rVal = sqlite3_value_double(argv[1]);
12666       break;
12667 
12668     case SQLITE_BLOB:
12669     case SQLITE_TEXT: {
12670       int nByte = sqlite3_value_bytes(argv[1]);
12671       const void *pData = 0;
12672       if( nByte>pSlot->nByte ){
12673         char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
12674         if( zNew==0 ){
12675           sqlite3_result_error_nomem(pCtx);
12676           return;
12677         }
12678         pSlot->nByte = nByte*2;
12679         pSlot->z = zNew;
12680       }
12681       pSlot->n = nByte;
12682       if( pSlot->eType==SQLITE_BLOB ){
12683         pData = sqlite3_value_blob(argv[1]);
12684         if( pData ) memcpy(pSlot->z, pData, nByte);
12685       }else{
12686         pData = sqlite3_value_text(argv[1]);
12687         memcpy(pSlot->z, pData, nByte);
12688       }
12689       break;
12690     }
12691   }
12692 }
12693 
12694 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
12695   int rc = SQLITE_OK;
12696   const char *zMax =
12697     "SELECT max(i.seqno) FROM "
12698     "  sqlite_schema AS s, "
12699     "  pragma_index_list(s.name) AS l, "
12700     "  pragma_index_info(l.name) AS i "
12701     "WHERE s.type = 'table'";
12702   sqlite3_stmt *pMax = 0;
12703 
12704   *pnMax = 0;
12705   rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
12706   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
12707     *pnMax = sqlite3_column_int(pMax, 0) + 1;
12708   }
12709   idxFinalize(&rc, pMax);
12710 
12711   return rc;
12712 }
12713 
12714 static int idxPopulateOneStat1(
12715   sqlite3expert *p,
12716   sqlite3_stmt *pIndexXInfo,
12717   sqlite3_stmt *pWriteStat,
12718   const char *zTab,
12719   const char *zIdx,
12720   char **pzErr
12721 ){
12722   char *zCols = 0;
12723   char *zOrder = 0;
12724   char *zQuery = 0;
12725   int nCol = 0;
12726   int i;
12727   sqlite3_stmt *pQuery = 0;
12728   int *aStat = 0;
12729   int rc = SQLITE_OK;
12730 
12731   assert( p->iSample>0 );
12732 
12733   /* Formulate the query text */
12734   sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
12735   while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
12736     const char *zComma = zCols==0 ? "" : ", ";
12737     const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
12738     const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
12739     zCols = idxAppendText(&rc, zCols,
12740         "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
12741     );
12742     zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
12743   }
12744   sqlite3_reset(pIndexXInfo);
12745   if( rc==SQLITE_OK ){
12746     if( p->iSample==100 ){
12747       zQuery = sqlite3_mprintf(
12748           "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
12749       );
12750     }else{
12751       zQuery = sqlite3_mprintf(
12752           "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
12753       );
12754     }
12755   }
12756   sqlite3_free(zCols);
12757   sqlite3_free(zOrder);
12758 
12759   /* Formulate the query text */
12760   if( rc==SQLITE_OK ){
12761     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
12762     rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
12763   }
12764   sqlite3_free(zQuery);
12765 
12766   if( rc==SQLITE_OK ){
12767     aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
12768   }
12769   if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
12770     IdxHashEntry *pEntry;
12771     char *zStat = 0;
12772     for(i=0; i<=nCol; i++) aStat[i] = 1;
12773     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
12774       aStat[0]++;
12775       for(i=0; i<nCol; i++){
12776         if( sqlite3_column_int(pQuery, i)==0 ) break;
12777       }
12778       for(/*no-op*/; i<nCol; i++){
12779         aStat[i+1]++;
12780       }
12781     }
12782 
12783     if( rc==SQLITE_OK ){
12784       int s0 = aStat[0];
12785       zStat = sqlite3_mprintf("%d", s0);
12786       if( zStat==0 ) rc = SQLITE_NOMEM;
12787       for(i=1; rc==SQLITE_OK && i<=nCol; i++){
12788         zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
12789       }
12790     }
12791 
12792     if( rc==SQLITE_OK ){
12793       sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
12794       sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
12795       sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
12796       sqlite3_step(pWriteStat);
12797       rc = sqlite3_reset(pWriteStat);
12798     }
12799 
12800     pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
12801     if( pEntry ){
12802       assert( pEntry->zVal2==0 );
12803       pEntry->zVal2 = zStat;
12804     }else{
12805       sqlite3_free(zStat);
12806     }
12807   }
12808   sqlite3_free(aStat);
12809   idxFinalize(&rc, pQuery);
12810 
12811   return rc;
12812 }
12813 
12814 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
12815   int rc;
12816   char *zSql;
12817 
12818   rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
12819   if( rc!=SQLITE_OK ) return rc;
12820 
12821   zSql = sqlite3_mprintf(
12822       "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
12823   );
12824   if( zSql==0 ) return SQLITE_NOMEM;
12825   rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
12826   sqlite3_free(zSql);
12827 
12828   return rc;
12829 }
12830 
12831 /*
12832 ** This function is called as part of sqlite3_expert_analyze(). Candidate
12833 ** indexes have already been created in database sqlite3expert.dbm, this
12834 ** function populates sqlite_stat1 table in the same database.
12835 **
12836 ** The stat1 data is generated by querying the
12837 */
12838 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
12839   int rc = SQLITE_OK;
12840   int nMax =0;
12841   struct IdxRemCtx *pCtx = 0;
12842   struct IdxSampleCtx samplectx;
12843   int i;
12844   i64 iPrev = -100000;
12845   sqlite3_stmt *pAllIndex = 0;
12846   sqlite3_stmt *pIndexXInfo = 0;
12847   sqlite3_stmt *pWrite = 0;
12848 
12849   const char *zAllIndex =
12850     "SELECT s.rowid, s.name, l.name FROM "
12851     "  sqlite_schema AS s, "
12852     "  pragma_index_list(s.name) AS l "
12853     "WHERE s.type = 'table'";
12854   const char *zIndexXInfo =
12855     "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
12856   const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
12857 
12858   /* If iSample==0, no sqlite_stat1 data is required. */
12859   if( p->iSample==0 ) return SQLITE_OK;
12860 
12861   rc = idxLargestIndex(p->dbm, &nMax, pzErr);
12862   if( nMax<=0 || rc!=SQLITE_OK ) return rc;
12863 
12864   rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
12865 
12866   if( rc==SQLITE_OK ){
12867     int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
12868     pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
12869   }
12870 
12871   if( rc==SQLITE_OK ){
12872     sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
12873     rc = sqlite3_create_function(
12874         dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
12875     );
12876   }
12877   if( rc==SQLITE_OK ){
12878     rc = sqlite3_create_function(
12879         p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
12880     );
12881   }
12882 
12883   if( rc==SQLITE_OK ){
12884     pCtx->nSlot = nMax+1;
12885     rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
12886   }
12887   if( rc==SQLITE_OK ){
12888     rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
12889   }
12890   if( rc==SQLITE_OK ){
12891     rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
12892   }
12893 
12894   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
12895     i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
12896     const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
12897     const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
12898     if( zTab==0 || zIdx==0 ) continue;
12899     if( p->iSample<100 && iPrev!=iRowid ){
12900       samplectx.target = (double)p->iSample / 100.0;
12901       samplectx.iTarget = p->iSample;
12902       samplectx.nRow = 0.0;
12903       samplectx.nRet = 0.0;
12904       rc = idxBuildSampleTable(p, zTab);
12905       if( rc!=SQLITE_OK ) break;
12906     }
12907     rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
12908     iPrev = iRowid;
12909   }
12910   if( rc==SQLITE_OK && p->iSample<100 ){
12911     rc = sqlite3_exec(p->dbv,
12912         "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
12913     );
12914   }
12915 
12916   idxFinalize(&rc, pAllIndex);
12917   idxFinalize(&rc, pIndexXInfo);
12918   idxFinalize(&rc, pWrite);
12919 
12920   if( pCtx ){
12921     for(i=0; i<pCtx->nSlot; i++){
12922       sqlite3_free(pCtx->aSlot[i].z);
12923     }
12924     sqlite3_free(pCtx);
12925   }
12926 
12927   if( rc==SQLITE_OK ){
12928     rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
12929   }
12930 
12931   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
12932   return rc;
12933 }
12934 
12935 /*
12936 ** Define and possibly pretend to use a useless collation sequence.
12937 ** This pretense allows expert to accept SQL using custom collations.
12938 */
12939 int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
12940   (void)up1;
12941   (void)up2;
12942   (void)up3;
12943   (void)up4;
12944   (void)up5;
12945   assert(0); /* VDBE should never be run. */
12946   return 0;
12947 }
12948 /* And a callback to register above upon actual need */
12949 void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
12950   (void)up1;
12951   sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
12952 }
12953 
12954 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
12955   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
12956 /*
12957 ** dummy functions for no-op implementation of UDFs during expert's work
12958 */
12959 void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
12960   (void)up1;
12961   (void)up2;
12962   (void)up3;
12963   assert(0); /* VDBE should never be run. */
12964 }
12965 void dummyUDFvalue(sqlite3_context *up1){
12966   (void)up1;
12967   assert(0); /* VDBE should never be run. */
12968 }
12969 
12970 /*
12971 ** Register UDFs from user database with another.
12972 */
12973 int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
12974   sqlite3_stmt *pStmt;
12975   int rc = sqlite3_prepare_v2(dbSrc,
12976             "SELECT name,type,enc,narg,flags "
12977             "FROM pragma_function_list() "
12978             "WHERE builtin==0", -1, &pStmt, 0);
12979   if( rc==SQLITE_OK ){
12980     while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
12981       int nargs = sqlite3_column_int(pStmt,3);
12982       int flags = sqlite3_column_int(pStmt,4);
12983       const char *name = (char*)sqlite3_column_text(pStmt,0);
12984       const char *type = (char*)sqlite3_column_text(pStmt,1);
12985       const char *enc = (char*)sqlite3_column_text(pStmt,2);
12986       if( name==0 || type==0 || enc==0 ){
12987         /* no-op.  Only happens on OOM */
12988       }else{
12989         int ienc = SQLITE_UTF8;
12990         int rcf = SQLITE_ERROR;
12991         if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
12992         else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
12993         ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
12994         if( strcmp(type,"w")==0 ){
12995           rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
12996                                                dummyUDF,dummyUDFvalue,0,0,0);
12997         }else if( strcmp(type,"a")==0 ){
12998           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
12999                                         0,dummyUDF,dummyUDFvalue);
13000         }else if( strcmp(type,"s")==0 ){
13001           rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13002                                         dummyUDF,0,0);
13003         }
13004         if( rcf!=SQLITE_OK ){
13005           rc = rcf;
13006           break;
13007         }
13008       }
13009     }
13010     sqlite3_finalize(pStmt);
13011     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
13012   }
13013   return rc;
13014 }
13015 #endif
13016 
13017 /*
13018 ** Allocate a new sqlite3expert object.
13019 */
13020 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
13021   int rc = SQLITE_OK;
13022   sqlite3expert *pNew;
13023 
13024   pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
13025 
13026   /* Open two in-memory databases to work with. The "vtab database" (dbv)
13027   ** will contain a virtual table corresponding to each real table in
13028   ** the user database schema, and a copy of each view. It is used to
13029   ** collect information regarding the WHERE, ORDER BY and other clauses
13030   ** of the user's query.
13031   */
13032   if( rc==SQLITE_OK ){
13033     pNew->db = db;
13034     pNew->iSample = 100;
13035     rc = sqlite3_open(":memory:", &pNew->dbv);
13036   }
13037   if( rc==SQLITE_OK ){
13038     rc = sqlite3_open(":memory:", &pNew->dbm);
13039     if( rc==SQLITE_OK ){
13040       sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
13041     }
13042   }
13043 
13044   /* Allow custom collations to be dealt with through prepare. */
13045   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
13046   if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
13047 
13048 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13049   && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13050   /* Register UDFs from database [db] with [dbm] and [dbv]. */
13051   if( rc==SQLITE_OK ){
13052     rc = registerUDFs(pNew->db, pNew->dbm);
13053   }
13054   if( rc==SQLITE_OK ){
13055     rc = registerUDFs(pNew->db, pNew->dbv);
13056   }
13057 #endif
13058 
13059   /* Copy the entire schema of database [db] into [dbm]. */
13060   if( rc==SQLITE_OK ){
13061     sqlite3_stmt *pSql = 0;
13062     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
13063         "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
13064         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
13065     );
13066     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
13067       const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
13068       if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
13069     }
13070     idxFinalize(&rc, pSql);
13071   }
13072 
13073   /* Create the vtab schema */
13074   if( rc==SQLITE_OK ){
13075     rc = idxCreateVtabSchema(pNew, pzErrmsg);
13076   }
13077 
13078   /* Register the auth callback with dbv */
13079   if( rc==SQLITE_OK ){
13080     sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
13081   }
13082 
13083   /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
13084   ** return the new sqlite3expert handle.  */
13085   if( rc!=SQLITE_OK ){
13086     sqlite3_expert_destroy(pNew);
13087     pNew = 0;
13088   }
13089   return pNew;
13090 }
13091 
13092 /*
13093 ** Configure an sqlite3expert object.
13094 */
13095 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
13096   int rc = SQLITE_OK;
13097   va_list ap;
13098   va_start(ap, op);
13099   switch( op ){
13100     case EXPERT_CONFIG_SAMPLE: {
13101       int iVal = va_arg(ap, int);
13102       if( iVal<0 ) iVal = 0;
13103       if( iVal>100 ) iVal = 100;
13104       p->iSample = iVal;
13105       break;
13106     }
13107     default:
13108       rc = SQLITE_NOTFOUND;
13109       break;
13110   }
13111 
13112   va_end(ap);
13113   return rc;
13114 }
13115 
13116 /*
13117 ** Add an SQL statement to the analysis.
13118 */
13119 int sqlite3_expert_sql(
13120   sqlite3expert *p,               /* From sqlite3_expert_new() */
13121   const char *zSql,               /* SQL statement to add */
13122   char **pzErr                    /* OUT: Error message (if any) */
13123 ){
13124   IdxScan *pScanOrig = p->pScan;
13125   IdxStatement *pStmtOrig = p->pStatement;
13126   int rc = SQLITE_OK;
13127   const char *zStmt = zSql;
13128 
13129   if( p->bRun ) return SQLITE_MISUSE;
13130 
13131   while( rc==SQLITE_OK && zStmt && zStmt[0] ){
13132     sqlite3_stmt *pStmt = 0;
13133     /* Ensure that the provided statement compiles against user's DB. */
13134     rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
13135     if( rc!=SQLITE_OK ) break;
13136     sqlite3_finalize(pStmt);
13137     rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
13138     if( rc==SQLITE_OK ){
13139       if( pStmt ){
13140         IdxStatement *pNew;
13141         const char *z = sqlite3_sql(pStmt);
13142         int n = STRLEN(z);
13143         pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
13144         if( rc==SQLITE_OK ){
13145           pNew->zSql = (char*)&pNew[1];
13146           memcpy(pNew->zSql, z, n+1);
13147           pNew->pNext = p->pStatement;
13148           if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
13149           p->pStatement = pNew;
13150         }
13151         sqlite3_finalize(pStmt);
13152       }
13153     }else{
13154       idxDatabaseError(p->dbv, pzErr);
13155     }
13156   }
13157 
13158   if( rc!=SQLITE_OK ){
13159     idxScanFree(p->pScan, pScanOrig);
13160     idxStatementFree(p->pStatement, pStmtOrig);
13161     p->pScan = pScanOrig;
13162     p->pStatement = pStmtOrig;
13163   }
13164 
13165   return rc;
13166 }
13167 
13168 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
13169   int rc;
13170   IdxHashEntry *pEntry;
13171 
13172   /* Do trigger processing to collect any extra IdxScan structures */
13173   rc = idxProcessTriggers(p, pzErr);
13174 
13175   /* Create candidate indexes within the in-memory database file */
13176   if( rc==SQLITE_OK ){
13177     rc = idxCreateCandidates(p);
13178   }else if ( rc==SQLITE_BUSY_TIMEOUT ){
13179     if( pzErr )
13180       *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
13181     return rc;
13182   }
13183 
13184   /* Generate the stat1 data */
13185   if( rc==SQLITE_OK ){
13186     rc = idxPopulateStat1(p, pzErr);
13187   }
13188 
13189   /* Formulate the EXPERT_REPORT_CANDIDATES text */
13190   for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13191     p->zCandidates = idxAppendText(&rc, p->zCandidates,
13192         "%s;%s%s\n", pEntry->zVal,
13193         pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
13194     );
13195   }
13196 
13197   /* Figure out which of the candidate indexes are preferred by the query
13198   ** planner and report the results to the user.  */
13199   if( rc==SQLITE_OK ){
13200     rc = idxFindIndexes(p, pzErr);
13201   }
13202 
13203   if( rc==SQLITE_OK ){
13204     p->bRun = 1;
13205   }
13206   return rc;
13207 }
13208 
13209 /*
13210 ** Return the total number of statements that have been added to this
13211 ** sqlite3expert using sqlite3_expert_sql().
13212 */
13213 int sqlite3_expert_count(sqlite3expert *p){
13214   int nRet = 0;
13215   if( p->pStatement ) nRet = p->pStatement->iId+1;
13216   return nRet;
13217 }
13218 
13219 /*
13220 ** Return a component of the report.
13221 */
13222 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
13223   const char *zRet = 0;
13224   IdxStatement *pStmt;
13225 
13226   if( p->bRun==0 ) return 0;
13227   for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
13228   switch( eReport ){
13229     case EXPERT_REPORT_SQL:
13230       if( pStmt ) zRet = pStmt->zSql;
13231       break;
13232     case EXPERT_REPORT_INDEXES:
13233       if( pStmt ) zRet = pStmt->zIdx;
13234       break;
13235     case EXPERT_REPORT_PLAN:
13236       if( pStmt ) zRet = pStmt->zEQP;
13237       break;
13238     case EXPERT_REPORT_CANDIDATES:
13239       zRet = p->zCandidates;
13240       break;
13241   }
13242   return zRet;
13243 }
13244 
13245 /*
13246 ** Free an sqlite3expert object.
13247 */
13248 void sqlite3_expert_destroy(sqlite3expert *p){
13249   if( p ){
13250     sqlite3_close(p->dbm);
13251     sqlite3_close(p->dbv);
13252     idxScanFree(p->pScan, 0);
13253     idxStatementFree(p->pStatement, 0);
13254     idxTableFree(p->pTable);
13255     idxWriteFree(p->pWrite);
13256     idxHashClear(&p->hIdx);
13257     sqlite3_free(p->zCandidates);
13258     sqlite3_free(p);
13259   }
13260 }
13261 
13262 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
13263 
13264 /************************* End ../ext/expert/sqlite3expert.c ********************/
13265 
13266 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
13267 #define SQLITE_SHELL_HAVE_RECOVER 1
13268 #else
13269 #define SQLITE_SHELL_HAVE_RECOVER 0
13270 #endif
13271 #if SQLITE_SHELL_HAVE_RECOVER
13272 /************************* Begin ../ext/recover/sqlite3recover.h ******************/
13273 /*
13274 ** 2022-08-27
13275 **
13276 ** The author disclaims copyright to this source code.  In place of
13277 ** a legal notice, here is a blessing:
13278 **
13279 **    May you do good and not evil.
13280 **    May you find forgiveness for yourself and forgive others.
13281 **    May you share freely, never taking more than you give.
13282 **
13283 *************************************************************************
13284 **
13285 ** This file contains the public interface to the "recover" extension -
13286 ** an SQLite extension designed to recover data from corrupted database
13287 ** files.
13288 */
13289 
13290 /*
13291 ** OVERVIEW:
13292 **
13293 ** To use the API to recover data from a corrupted database, an
13294 ** application:
13295 **
13296 **   1) Creates an sqlite3_recover handle by calling either
13297 **      sqlite3_recover_init() or sqlite3_recover_init_sql().
13298 **
13299 **   2) Configures the new handle using one or more calls to
13300 **      sqlite3_recover_config().
13301 **
13302 **   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
13303 **      the handle until it returns something other than SQLITE_OK. If it
13304 **      returns SQLITE_DONE, then the recovery operation completed without
13305 **      error. If it returns some other non-SQLITE_OK value, then an error
13306 **      has occurred.
13307 **
13308 **   4) Retrieves any error code and English language error message using the
13309 **      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
13310 **      respectively.
13311 **
13312 **   5) Destroys the sqlite3_recover handle and frees all resources
13313 **      using sqlite3_recover_finish().
13314 **
13315 ** The application may abandon the recovery operation at any point
13316 ** before it is finished by passing the sqlite3_recover handle to
13317 ** sqlite3_recover_finish(). This is not an error, but the final state
13318 ** of the output database, or the results of running the partial script
13319 ** delivered to the SQL callback, are undefined.
13320 */
13321 
13322 #ifndef _SQLITE_RECOVER_H
13323 #define _SQLITE_RECOVER_H
13324 
13325 /* #include "sqlite3.h" */
13326 
13327 #ifdef __cplusplus
13328 extern "C" {
13329 #endif
13330 
13331 /*
13332 ** An instance of the sqlite3_recover object represents a recovery
13333 ** operation in progress.
13334 **
13335 ** Constructors:
13336 **
13337 **    sqlite3_recover_init()
13338 **    sqlite3_recover_init_sql()
13339 **
13340 ** Destructor:
13341 **
13342 **    sqlite3_recover_finish()
13343 **
13344 ** Methods:
13345 **
13346 **    sqlite3_recover_config()
13347 **    sqlite3_recover_errcode()
13348 **    sqlite3_recover_errmsg()
13349 **    sqlite3_recover_run()
13350 **    sqlite3_recover_step()
13351 */
13352 typedef struct sqlite3_recover sqlite3_recover;
13353 
13354 /*
13355 ** These two APIs attempt to create and return a new sqlite3_recover object.
13356 ** In both cases the first two arguments identify the (possibly
13357 ** corrupt) database to recover data from. The first argument is an open
13358 ** database handle and the second the name of a database attached to that
13359 ** handle (i.e. "main", "temp" or the name of an attached database).
13360 **
13361 ** If sqlite3_recover_init() is used to create the new sqlite3_recover
13362 ** handle, then data is recovered into a new database, identified by
13363 ** string parameter zUri. zUri may be an absolute or relative file path,
13364 ** or may be an SQLite URI. If the identified database file already exists,
13365 ** it is overwritten.
13366 **
13367 ** If sqlite3_recover_init_sql() is invoked, then any recovered data will
13368 ** be returned to the user as a series of SQL statements. Executing these
13369 ** SQL statements results in the same database as would have been created
13370 ** had sqlite3_recover_init() been used. For each SQL statement in the
13371 ** output, the callback function passed as the third argument (xSql) is
13372 ** invoked once. The first parameter is a passed a copy of the fourth argument
13373 ** to this function (pCtx) as its first parameter, and a pointer to a
13374 ** nul-terminated buffer containing the SQL statement formated as UTF-8 as
13375 ** the second. If the xSql callback returns any value other than SQLITE_OK,
13376 ** then processing is immediately abandoned and the value returned used as
13377 ** the recover handle error code (see below).
13378 **
13379 ** If an out-of-memory error occurs, NULL may be returned instead of
13380 ** a valid handle. In all other cases, it is the responsibility of the
13381 ** application to avoid resource leaks by ensuring that
13382 ** sqlite3_recover_finish() is called on all allocated handles.
13383 */
13384 sqlite3_recover *sqlite3_recover_init(
13385   sqlite3* db,
13386   const char *zDb,
13387   const char *zUri
13388 );
13389 sqlite3_recover *sqlite3_recover_init_sql(
13390   sqlite3* db,
13391   const char *zDb,
13392   int (*xSql)(void*, const char*),
13393   void *pCtx
13394 );
13395 
13396 /*
13397 ** Configure an sqlite3_recover object that has just been created using
13398 ** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
13399 ** may only be called before the first call to sqlite3_recover_step()
13400 ** or sqlite3_recover_run() on the object.
13401 **
13402 ** The second argument passed to this function must be one of the
13403 ** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
13404 ** depend on the specific SQLITE_RECOVER_* symbol in use.
13405 **
13406 ** SQLITE_OK is returned if the configuration operation was successful,
13407 ** or an SQLite error code otherwise.
13408 */
13409 int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
13410 
13411 /*
13412 ** SQLITE_RECOVER_LOST_AND_FOUND:
13413 **   The pArg argument points to a string buffer containing the name
13414 **   of a "lost-and-found" table in the output database, or NULL. If
13415 **   the argument is non-NULL and the database contains seemingly
13416 **   valid pages that cannot be associated with any table in the
13417 **   recovered part of the schema, data is extracted from these
13418 **   pages to add to the lost-and-found table.
13419 **
13420 ** SQLITE_RECOVER_FREELIST_CORRUPT:
13421 **   The pArg value must actually be a pointer to a value of type
13422 **   int containing value 0 or 1 cast as a (void*). If this option is set
13423 **   (argument is 1) and a lost-and-found table has been configured using
13424 **   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
13425 **   corrupt and an attempt is made to recover records from pages that
13426 **   appear to be linked into the freelist. Otherwise, pages on the freelist
13427 **   are ignored. Setting this option can recover more data from the
13428 **   database, but often ends up "recovering" deleted records. The default
13429 **   value is 0 (clear).
13430 **
13431 ** SQLITE_RECOVER_ROWIDS:
13432 **   The pArg value must actually be a pointer to a value of type
13433 **   int containing value 0 or 1 cast as a (void*). If this option is set
13434 **   (argument is 1), then an attempt is made to recover rowid values
13435 **   that are not also INTEGER PRIMARY KEY values. If this option is
13436 **   clear, then new rowids are assigned to all recovered rows. The
13437 **   default value is 1 (set).
13438 **
13439 ** SQLITE_RECOVER_SLOWINDEXES:
13440 **   The pArg value must actually be a pointer to a value of type
13441 **   int containing value 0 or 1 cast as a (void*). If this option is clear
13442 **   (argument is 0), then when creating an output database, the recover
13443 **   module creates and populates non-UNIQUE indexes right at the end of the
13444 **   recovery operation - after all recoverable data has been inserted
13445 **   into the new database. This is faster overall, but means that the
13446 **   final call to sqlite3_recover_step() for a recovery operation may
13447 **   be need to create a large number of indexes, which may be very slow.
13448 **
13449 **   Or, if this option is set (argument is 1), then non-UNIQUE indexes
13450 **   are created in the output database before it is populated with
13451 **   recovered data. This is slower overall, but avoids the slow call
13452 **   to sqlite3_recover_step() at the end of the recovery operation.
13453 **
13454 **   The default option value is 0.
13455 */
13456 #define SQLITE_RECOVER_LOST_AND_FOUND   1
13457 #define SQLITE_RECOVER_FREELIST_CORRUPT 2
13458 #define SQLITE_RECOVER_ROWIDS           3
13459 #define SQLITE_RECOVER_SLOWINDEXES      4
13460 
13461 /*
13462 ** Perform a unit of work towards the recovery operation. This function
13463 ** must normally be called multiple times to complete database recovery.
13464 **
13465 ** If no error occurs but the recovery operation is not completed, this
13466 ** function returns SQLITE_OK. If recovery has been completed successfully
13467 ** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
13468 ** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
13469 ** considered an error if some or all of the data cannot be recovered
13470 ** due to database corruption.
13471 **
13472 ** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
13473 ** all further such calls on the same recover handle are no-ops that return
13474 ** the same non-SQLITE_OK value.
13475 */
13476 int sqlite3_recover_step(sqlite3_recover*);
13477 
13478 /*
13479 ** Run the recovery operation to completion. Return SQLITE_OK if successful,
13480 ** or an SQLite error code otherwise. Calling this function is the same
13481 ** as executing:
13482 **
13483 **     while( SQLITE_OK==sqlite3_recover_step(p) );
13484 **     return sqlite3_recover_errcode(p);
13485 */
13486 int sqlite3_recover_run(sqlite3_recover*);
13487 
13488 /*
13489 ** If an error has been encountered during a prior call to
13490 ** sqlite3_recover_step(), then this function attempts to return a
13491 ** pointer to a buffer containing an English language explanation of
13492 ** the error. If no error message is available, or if an out-of memory
13493 ** error occurs while attempting to allocate a buffer in which to format
13494 ** the error message, NULL is returned.
13495 **
13496 ** The returned buffer remains valid until the sqlite3_recover handle is
13497 ** destroyed using sqlite3_recover_finish().
13498 */
13499 const char *sqlite3_recover_errmsg(sqlite3_recover*);
13500 
13501 /*
13502 ** If this function is called on an sqlite3_recover handle after
13503 ** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
13504 */
13505 int sqlite3_recover_errcode(sqlite3_recover*);
13506 
13507 /*
13508 ** Clean up a recovery object created by a call to sqlite3_recover_init().
13509 ** The results of using a recovery object with any API after it has been
13510 ** passed to this function are undefined.
13511 **
13512 ** This function returns the same value as sqlite3_recover_errcode().
13513 */
13514 int sqlite3_recover_finish(sqlite3_recover*);
13515 
13516 
13517 #ifdef __cplusplus
13518 }  /* end of the 'extern "C"' block */
13519 #endif
13520 
13521 #endif /* ifndef _SQLITE_RECOVER_H */
13522 
13523 /************************* End ../ext/recover/sqlite3recover.h ********************/
13524 # ifndef SQLITE_HAVE_SQLITE3R
13525 /************************* Begin ../ext/recover/dbdata.c ******************/
13526 /*
13527 ** 2019-04-17
13528 **
13529 ** The author disclaims copyright to this source code.  In place of
13530 ** a legal notice, here is a blessing:
13531 **
13532 **    May you do good and not evil.
13533 **    May you find forgiveness for yourself and forgive others.
13534 **    May you share freely, never taking more than you give.
13535 **
13536 ******************************************************************************
13537 **
13538 ** This file contains an implementation of two eponymous virtual tables,
13539 ** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
13540 ** "sqlite_dbpage" eponymous virtual table be available.
13541 **
13542 ** SQLITE_DBDATA:
13543 **   sqlite_dbdata is used to extract data directly from a database b-tree
13544 **   page and its associated overflow pages, bypassing the b-tree layer.
13545 **   The table schema is equivalent to:
13546 **
13547 **     CREATE TABLE sqlite_dbdata(
13548 **       pgno INTEGER,
13549 **       cell INTEGER,
13550 **       field INTEGER,
13551 **       value ANY,
13552 **       schema TEXT HIDDEN
13553 **     );
13554 **
13555 **   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
13556 **   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
13557 **   "schema".
13558 **
13559 **   Each page of the database is inspected. If it cannot be interpreted as
13560 **   a b-tree page, or if it is a b-tree page containing 0 entries, the
13561 **   sqlite_dbdata table contains no rows for that page.  Otherwise, the
13562 **   table contains one row for each field in the record associated with
13563 **   each cell on the page. For intkey b-trees, the key value is stored in
13564 **   field -1.
13565 **
13566 **   For example, for the database:
13567 **
13568 **     CREATE TABLE t1(a, b);     -- root page is page 2
13569 **     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
13570 **     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
13571 **
13572 **   the sqlite_dbdata table contains, as well as from entries related to
13573 **   page 1, content equivalent to:
13574 **
13575 **     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
13576 **         (2, 0, -1, 5     ),
13577 **         (2, 0,  0, 'v'   ),
13578 **         (2, 0,  1, 'five'),
13579 **         (2, 1, -1, 10    ),
13580 **         (2, 1,  0, 'x'   ),
13581 **         (2, 1,  1, 'ten' );
13582 **
13583 **   If database corruption is encountered, this module does not report an
13584 **   error. Instead, it attempts to extract as much data as possible and
13585 **   ignores the corruption.
13586 **
13587 ** SQLITE_DBPTR:
13588 **   The sqlite_dbptr table has the following schema:
13589 **
13590 **     CREATE TABLE sqlite_dbptr(
13591 **       pgno INTEGER,
13592 **       child INTEGER,
13593 **       schema TEXT HIDDEN
13594 **     );
13595 **
13596 **   It contains one entry for each b-tree pointer between a parent and
13597 **   child page in the database.
13598 */
13599 
13600 #if !defined(SQLITEINT_H)
13601 /* #include "sqlite3.h" */
13602 
13603 /* typedef unsigned char u8; */
13604 /* typedef unsigned int u32; */
13605 
13606 #endif
13607 #include <string.h>
13608 #include <assert.h>
13609 
13610 #ifndef SQLITE_OMIT_VIRTUALTABLE
13611 
13612 #define DBDATA_PADDING_BYTES 100
13613 
13614 typedef struct DbdataTable DbdataTable;
13615 typedef struct DbdataCursor DbdataCursor;
13616 
13617 /* Cursor object */
13618 struct DbdataCursor {
13619   sqlite3_vtab_cursor base;       /* Base class.  Must be first */
13620   sqlite3_stmt *pStmt;            /* For fetching database pages */
13621 
13622   int iPgno;                      /* Current page number */
13623   u8 *aPage;                      /* Buffer containing page */
13624   int nPage;                      /* Size of aPage[] in bytes */
13625   int nCell;                      /* Number of cells on aPage[] */
13626   int iCell;                      /* Current cell number */
13627   int bOnePage;                   /* True to stop after one page */
13628   int szDb;
13629   sqlite3_int64 iRowid;
13630 
13631   /* Only for the sqlite_dbdata table */
13632   u8 *pRec;                       /* Buffer containing current record */
13633   sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
13634   sqlite3_int64 nHdr;             /* Size of header in bytes */
13635   int iField;                     /* Current field number */
13636   u8 *pHdrPtr;
13637   u8 *pPtr;
13638   u32 enc;                        /* Text encoding */
13639 
13640   sqlite3_int64 iIntkey;          /* Integer key value */
13641 };
13642 
13643 /* Table object */
13644 struct DbdataTable {
13645   sqlite3_vtab base;              /* Base class.  Must be first */
13646   sqlite3 *db;                    /* The database connection */
13647   sqlite3_stmt *pStmt;            /* For fetching database pages */
13648   int bPtr;                       /* True for sqlite3_dbptr table */
13649 };
13650 
13651 /* Column and schema definitions for sqlite_dbdata */
13652 #define DBDATA_COLUMN_PGNO        0
13653 #define DBDATA_COLUMN_CELL        1
13654 #define DBDATA_COLUMN_FIELD       2
13655 #define DBDATA_COLUMN_VALUE       3
13656 #define DBDATA_COLUMN_SCHEMA      4
13657 #define DBDATA_SCHEMA             \
13658       "CREATE TABLE x("           \
13659       "  pgno INTEGER,"           \
13660       "  cell INTEGER,"           \
13661       "  field INTEGER,"          \
13662       "  value ANY,"              \
13663       "  schema TEXT HIDDEN"      \
13664       ")"
13665 
13666 /* Column and schema definitions for sqlite_dbptr */
13667 #define DBPTR_COLUMN_PGNO         0
13668 #define DBPTR_COLUMN_CHILD        1
13669 #define DBPTR_COLUMN_SCHEMA       2
13670 #define DBPTR_SCHEMA              \
13671       "CREATE TABLE x("           \
13672       "  pgno INTEGER,"           \
13673       "  child INTEGER,"          \
13674       "  schema TEXT HIDDEN"      \
13675       ")"
13676 
13677 /*
13678 ** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
13679 ** table.
13680 */
13681 static int dbdataConnect(
13682   sqlite3 *db,
13683   void *pAux,
13684   int argc, const char *const*argv,
13685   sqlite3_vtab **ppVtab,
13686   char **pzErr
13687 ){
13688   DbdataTable *pTab = 0;
13689   int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
13690 
13691   (void)argc;
13692   (void)argv;
13693   (void)pzErr;
13694   sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
13695   if( rc==SQLITE_OK ){
13696     pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
13697     if( pTab==0 ){
13698       rc = SQLITE_NOMEM;
13699     }else{
13700       memset(pTab, 0, sizeof(DbdataTable));
13701       pTab->db = db;
13702       pTab->bPtr = (pAux!=0);
13703     }
13704   }
13705 
13706   *ppVtab = (sqlite3_vtab*)pTab;
13707   return rc;
13708 }
13709 
13710 /*
13711 ** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
13712 */
13713 static int dbdataDisconnect(sqlite3_vtab *pVtab){
13714   DbdataTable *pTab = (DbdataTable*)pVtab;
13715   if( pTab ){
13716     sqlite3_finalize(pTab->pStmt);
13717     sqlite3_free(pVtab);
13718   }
13719   return SQLITE_OK;
13720 }
13721 
13722 /*
13723 ** This function interprets two types of constraints:
13724 **
13725 **       schema=?
13726 **       pgno=?
13727 **
13728 ** If neither are present, idxNum is set to 0. If schema=? is present,
13729 ** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
13730 ** in idxNum is set.
13731 **
13732 ** If both parameters are present, schema is in position 0 and pgno in
13733 ** position 1.
13734 */
13735 static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
13736   DbdataTable *pTab = (DbdataTable*)tab;
13737   int i;
13738   int iSchema = -1;
13739   int iPgno = -1;
13740   int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
13741 
13742   for(i=0; i<pIdx->nConstraint; i++){
13743     struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
13744     if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
13745       if( p->iColumn==colSchema ){
13746         if( p->usable==0 ) return SQLITE_CONSTRAINT;
13747         iSchema = i;
13748       }
13749       if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
13750         iPgno = i;
13751       }
13752     }
13753   }
13754 
13755   if( iSchema>=0 ){
13756     pIdx->aConstraintUsage[iSchema].argvIndex = 1;
13757     pIdx->aConstraintUsage[iSchema].omit = 1;
13758   }
13759   if( iPgno>=0 ){
13760     pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
13761     pIdx->aConstraintUsage[iPgno].omit = 1;
13762     pIdx->estimatedCost = 100;
13763     pIdx->estimatedRows =  50;
13764 
13765     if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
13766       int iCol = pIdx->aOrderBy[0].iColumn;
13767       if( pIdx->nOrderBy==1 ){
13768         pIdx->orderByConsumed = (iCol==0 || iCol==1);
13769       }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
13770         pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
13771       }
13772     }
13773 
13774   }else{
13775     pIdx->estimatedCost = 100000000;
13776     pIdx->estimatedRows = 1000000000;
13777   }
13778   pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
13779   return SQLITE_OK;
13780 }
13781 
13782 /*
13783 ** Open a new sqlite_dbdata or sqlite_dbptr cursor.
13784 */
13785 static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
13786   DbdataCursor *pCsr;
13787 
13788   pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
13789   if( pCsr==0 ){
13790     return SQLITE_NOMEM;
13791   }else{
13792     memset(pCsr, 0, sizeof(DbdataCursor));
13793     pCsr->base.pVtab = pVTab;
13794   }
13795 
13796   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
13797   return SQLITE_OK;
13798 }
13799 
13800 /*
13801 ** Restore a cursor object to the state it was in when first allocated
13802 ** by dbdataOpen().
13803 */
13804 static void dbdataResetCursor(DbdataCursor *pCsr){
13805   DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
13806   if( pTab->pStmt==0 ){
13807     pTab->pStmt = pCsr->pStmt;
13808   }else{
13809     sqlite3_finalize(pCsr->pStmt);
13810   }
13811   pCsr->pStmt = 0;
13812   pCsr->iPgno = 1;
13813   pCsr->iCell = 0;
13814   pCsr->iField = 0;
13815   pCsr->bOnePage = 0;
13816   sqlite3_free(pCsr->aPage);
13817   sqlite3_free(pCsr->pRec);
13818   pCsr->pRec = 0;
13819   pCsr->aPage = 0;
13820 }
13821 
13822 /*
13823 ** Close an sqlite_dbdata or sqlite_dbptr cursor.
13824 */
13825 static int dbdataClose(sqlite3_vtab_cursor *pCursor){
13826   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
13827   dbdataResetCursor(pCsr);
13828   sqlite3_free(pCsr);
13829   return SQLITE_OK;
13830 }
13831 
13832 /*
13833 ** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
13834 */
13835 static u32 get_uint16(unsigned char *a){
13836   return (a[0]<<8)|a[1];
13837 }
13838 static u32 get_uint32(unsigned char *a){
13839   return ((u32)a[0]<<24)
13840        | ((u32)a[1]<<16)
13841        | ((u32)a[2]<<8)
13842        | ((u32)a[3]);
13843 }
13844 
13845 /*
13846 ** Load page pgno from the database via the sqlite_dbpage virtual table.
13847 ** If successful, set (*ppPage) to point to a buffer containing the page
13848 ** data, (*pnPage) to the size of that buffer in bytes and return
13849 ** SQLITE_OK. In this case it is the responsibility of the caller to
13850 ** eventually free the buffer using sqlite3_free().
13851 **
13852 ** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
13853 ** return an SQLite error code.
13854 */
13855 static int dbdataLoadPage(
13856   DbdataCursor *pCsr,             /* Cursor object */
13857   u32 pgno,                       /* Page number of page to load */
13858   u8 **ppPage,                    /* OUT: pointer to page buffer */
13859   int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
13860 ){
13861   int rc2;
13862   int rc = SQLITE_OK;
13863   sqlite3_stmt *pStmt = pCsr->pStmt;
13864 
13865   *ppPage = 0;
13866   *pnPage = 0;
13867   if( pgno>0 ){
13868     sqlite3_bind_int64(pStmt, 2, pgno);
13869     if( SQLITE_ROW==sqlite3_step(pStmt) ){
13870       int nCopy = sqlite3_column_bytes(pStmt, 0);
13871       if( nCopy>0 ){
13872         u8 *pPage;
13873         pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
13874         if( pPage==0 ){
13875           rc = SQLITE_NOMEM;
13876         }else{
13877           const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
13878           memcpy(pPage, pCopy, nCopy);
13879           memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
13880         }
13881         *ppPage = pPage;
13882         *pnPage = nCopy;
13883       }
13884     }
13885     rc2 = sqlite3_reset(pStmt);
13886     if( rc==SQLITE_OK ) rc = rc2;
13887   }
13888 
13889   return rc;
13890 }
13891 
13892 /*
13893 ** Read a varint.  Put the value in *pVal and return the number of bytes.
13894 */
13895 static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
13896   sqlite3_uint64 u = 0;
13897   int i;
13898   for(i=0; i<8; i++){
13899     u = (u<<7) + (z[i]&0x7f);
13900     if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
13901   }
13902   u = (u<<8) + (z[i]&0xff);
13903   *pVal = (sqlite3_int64)u;
13904   return 9;
13905 }
13906 
13907 /*
13908 ** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
13909 ** or greater than 0xFFFFFFFF. This can be used for all varints in an
13910 ** SQLite database except for key values in intkey tables.
13911 */
13912 static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
13913   sqlite3_int64 val;
13914   int nRet = dbdataGetVarint(z, &val);
13915   if( val<0 || val>0xFFFFFFFF ) val = 0;
13916   *pVal = val;
13917   return nRet;
13918 }
13919 
13920 /*
13921 ** Return the number of bytes of space used by an SQLite value of type
13922 ** eType.
13923 */
13924 static int dbdataValueBytes(int eType){
13925   switch( eType ){
13926     case 0: case 8: case 9:
13927     case 10: case 11:
13928       return 0;
13929     case 1:
13930       return 1;
13931     case 2:
13932       return 2;
13933     case 3:
13934       return 3;
13935     case 4:
13936       return 4;
13937     case 5:
13938       return 6;
13939     case 6:
13940     case 7:
13941       return 8;
13942     default:
13943       if( eType>0 ){
13944         return ((eType-12) / 2);
13945       }
13946       return 0;
13947   }
13948 }
13949 
13950 /*
13951 ** Load a value of type eType from buffer pData and use it to set the
13952 ** result of context object pCtx.
13953 */
13954 static void dbdataValue(
13955   sqlite3_context *pCtx,
13956   u32 enc,
13957   int eType,
13958   u8 *pData,
13959   sqlite3_int64 nData
13960 ){
13961   if( eType>=0 && dbdataValueBytes(eType)<=nData ){
13962     switch( eType ){
13963       case 0:
13964       case 10:
13965       case 11:
13966         sqlite3_result_null(pCtx);
13967         break;
13968 
13969       case 8:
13970         sqlite3_result_int(pCtx, 0);
13971         break;
13972       case 9:
13973         sqlite3_result_int(pCtx, 1);
13974         break;
13975 
13976       case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
13977         sqlite3_uint64 v = (signed char)pData[0];
13978         pData++;
13979         switch( eType ){
13980           case 7:
13981           case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
13982           case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
13983           case 4:  v = (v<<8) + pData[0];  pData++;
13984           case 3:  v = (v<<8) + pData[0];  pData++;
13985           case 2:  v = (v<<8) + pData[0];  pData++;
13986         }
13987 
13988         if( eType==7 ){
13989           double r;
13990           memcpy(&r, &v, sizeof(r));
13991           sqlite3_result_double(pCtx, r);
13992         }else{
13993           sqlite3_result_int64(pCtx, (sqlite3_int64)v);
13994         }
13995         break;
13996       }
13997 
13998       default: {
13999         int n = ((eType-12) / 2);
14000         if( eType % 2 ){
14001           switch( enc ){
14002 #ifndef SQLITE_OMIT_UTF16
14003             case SQLITE_UTF16BE:
14004               sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14005               break;
14006             case SQLITE_UTF16LE:
14007               sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
14008               break;
14009 #endif
14010             default:
14011               sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
14012               break;
14013           }
14014         }else{
14015           sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
14016         }
14017       }
14018     }
14019   }
14020 }
14021 
14022 /*
14023 ** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
14024 */
14025 static int dbdataNext(sqlite3_vtab_cursor *pCursor){
14026   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14027   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
14028 
14029   pCsr->iRowid++;
14030   while( 1 ){
14031     int rc;
14032     int iOff = (pCsr->iPgno==1 ? 100 : 0);
14033     int bNextPage = 0;
14034 
14035     if( pCsr->aPage==0 ){
14036       while( 1 ){
14037         if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
14038         rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
14039         if( rc!=SQLITE_OK ) return rc;
14040         if( pCsr->aPage && pCsr->nPage>=256 ) break;
14041         sqlite3_free(pCsr->aPage);
14042         pCsr->aPage = 0;
14043         if( pCsr->bOnePage ) return SQLITE_OK;
14044         pCsr->iPgno++;
14045       }
14046 
14047       assert( iOff+3+2<=pCsr->nPage );
14048       pCsr->iCell = pTab->bPtr ? -2 : 0;
14049       pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
14050     }
14051 
14052     if( pTab->bPtr ){
14053       if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
14054         pCsr->iCell = pCsr->nCell;
14055       }
14056       pCsr->iCell++;
14057       if( pCsr->iCell>=pCsr->nCell ){
14058         sqlite3_free(pCsr->aPage);
14059         pCsr->aPage = 0;
14060         if( pCsr->bOnePage ) return SQLITE_OK;
14061         pCsr->iPgno++;
14062       }else{
14063         return SQLITE_OK;
14064       }
14065     }else{
14066       /* If there is no record loaded, load it now. */
14067       if( pCsr->pRec==0 ){
14068         int bHasRowid = 0;
14069         int nPointer = 0;
14070         sqlite3_int64 nPayload = 0;
14071         sqlite3_int64 nHdr = 0;
14072         int iHdr;
14073         int U, X;
14074         int nLocal;
14075 
14076         switch( pCsr->aPage[iOff] ){
14077           case 0x02:
14078             nPointer = 4;
14079             break;
14080           case 0x0a:
14081             break;
14082           case 0x0d:
14083             bHasRowid = 1;
14084             break;
14085           default:
14086             /* This is not a b-tree page with records on it. Continue. */
14087             pCsr->iCell = pCsr->nCell;
14088             break;
14089         }
14090 
14091         if( pCsr->iCell>=pCsr->nCell ){
14092           bNextPage = 1;
14093         }else{
14094 
14095           iOff += 8 + nPointer + pCsr->iCell*2;
14096           if( iOff>pCsr->nPage ){
14097             bNextPage = 1;
14098           }else{
14099             iOff = get_uint16(&pCsr->aPage[iOff]);
14100           }
14101 
14102           /* For an interior node cell, skip past the child-page number */
14103           iOff += nPointer;
14104 
14105           /* Load the "byte of payload including overflow" field */
14106           if( bNextPage || iOff>pCsr->nPage ){
14107             bNextPage = 1;
14108           }else{
14109             iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
14110           }
14111 
14112           /* If this is a leaf intkey cell, load the rowid */
14113           if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
14114             iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
14115           }
14116 
14117           /* Figure out how much data to read from the local page */
14118           U = pCsr->nPage;
14119           if( bHasRowid ){
14120             X = U-35;
14121           }else{
14122             X = ((U-12)*64/255)-23;
14123           }
14124           if( nPayload<=X ){
14125             nLocal = nPayload;
14126           }else{
14127             int M, K;
14128             M = ((U-12)*32/255)-23;
14129             K = M+((nPayload-M)%(U-4));
14130             if( K<=X ){
14131               nLocal = K;
14132             }else{
14133               nLocal = M;
14134             }
14135           }
14136 
14137           if( bNextPage || nLocal+iOff>pCsr->nPage ){
14138             bNextPage = 1;
14139           }else{
14140 
14141             /* Allocate space for payload. And a bit more to catch small buffer
14142             ** overruns caused by attempting to read a varint or similar from
14143             ** near the end of a corrupt record.  */
14144             pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES);
14145             if( pCsr->pRec==0 ) return SQLITE_NOMEM;
14146             memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES);
14147             pCsr->nRec = nPayload;
14148 
14149             /* Load the nLocal bytes of payload */
14150             memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal);
14151             iOff += nLocal;
14152 
14153             /* Load content from overflow pages */
14154             if( nPayload>nLocal ){
14155               sqlite3_int64 nRem = nPayload - nLocal;
14156               u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
14157               while( nRem>0 ){
14158                 u8 *aOvfl = 0;
14159                 int nOvfl = 0;
14160                 int nCopy;
14161                 rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
14162                 assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
14163                 if( rc!=SQLITE_OK ) return rc;
14164                 if( aOvfl==0 ) break;
14165 
14166                 nCopy = U-4;
14167                 if( nCopy>nRem ) nCopy = nRem;
14168                 memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy);
14169                 nRem -= nCopy;
14170 
14171                 pgnoOvfl = get_uint32(aOvfl);
14172                 sqlite3_free(aOvfl);
14173               }
14174             }
14175 
14176             iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr);
14177             if( nHdr>nPayload ) nHdr = 0;
14178             pCsr->nHdr = nHdr;
14179             pCsr->pHdrPtr = &pCsr->pRec[iHdr];
14180             pCsr->pPtr = &pCsr->pRec[pCsr->nHdr];
14181             pCsr->iField = (bHasRowid ? -1 : 0);
14182           }
14183         }
14184       }else{
14185         pCsr->iField++;
14186         if( pCsr->iField>0 ){
14187           sqlite3_int64 iType;
14188           if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){
14189             bNextPage = 1;
14190           }else{
14191             int szField = 0;
14192             pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
14193             szField = dbdataValueBytes(iType);
14194             if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))<szField ){
14195               pCsr->pPtr = &pCsr->pRec[pCsr->nRec];
14196             }else{
14197               pCsr->pPtr += szField;
14198             }
14199           }
14200         }
14201       }
14202 
14203       if( bNextPage ){
14204         sqlite3_free(pCsr->aPage);
14205         sqlite3_free(pCsr->pRec);
14206         pCsr->aPage = 0;
14207         pCsr->pRec = 0;
14208         if( pCsr->bOnePage ) return SQLITE_OK;
14209         pCsr->iPgno++;
14210       }else{
14211         if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){
14212           return SQLITE_OK;
14213         }
14214 
14215         /* Advance to the next cell. The next iteration of the loop will load
14216         ** the record and so on. */
14217         sqlite3_free(pCsr->pRec);
14218         pCsr->pRec = 0;
14219         pCsr->iCell++;
14220       }
14221     }
14222   }
14223 
14224   assert( !"can't get here" );
14225   return SQLITE_OK;
14226 }
14227 
14228 /*
14229 ** Return true if the cursor is at EOF.
14230 */
14231 static int dbdataEof(sqlite3_vtab_cursor *pCursor){
14232   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14233   return pCsr->aPage==0;
14234 }
14235 
14236 /*
14237 ** Return true if nul-terminated string zSchema ends in "()". Or false
14238 ** otherwise.
14239 */
14240 static int dbdataIsFunction(const char *zSchema){
14241   size_t n = strlen(zSchema);
14242   if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
14243     return (int)n-2;
14244   }
14245   return 0;
14246 }
14247 
14248 /*
14249 ** Determine the size in pages of database zSchema (where zSchema is
14250 ** "main", "temp" or the name of an attached database) and set
14251 ** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
14252 ** an SQLite error code.
14253 */
14254 static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
14255   DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
14256   char *zSql = 0;
14257   int rc, rc2;
14258   int nFunc = 0;
14259   sqlite3_stmt *pStmt = 0;
14260 
14261   if( (nFunc = dbdataIsFunction(zSchema))>0 ){
14262     zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
14263   }else{
14264     zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
14265   }
14266   if( zSql==0 ) return SQLITE_NOMEM;
14267 
14268   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
14269   sqlite3_free(zSql);
14270   if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
14271     pCsr->szDb = sqlite3_column_int(pStmt, 0);
14272   }
14273   rc2 = sqlite3_finalize(pStmt);
14274   if( rc==SQLITE_OK ) rc = rc2;
14275   return rc;
14276 }
14277 
14278 /*
14279 ** Attempt to figure out the encoding of the database by retrieving page 1
14280 ** and inspecting the header field. If successful, set the pCsr->enc variable
14281 ** and return SQLITE_OK. Otherwise, return an SQLite error code.
14282 */
14283 static int dbdataGetEncoding(DbdataCursor *pCsr){
14284   int rc = SQLITE_OK;
14285   int nPg1 = 0;
14286   u8 *aPg1 = 0;
14287   rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
14288   if( rc==SQLITE_OK && nPg1>=(56+4) ){
14289     pCsr->enc = get_uint32(&aPg1[56]);
14290   }
14291   sqlite3_free(aPg1);
14292   return rc;
14293 }
14294 
14295 
14296 /*
14297 ** xFilter method for sqlite_dbdata and sqlite_dbptr.
14298 */
14299 static int dbdataFilter(
14300   sqlite3_vtab_cursor *pCursor,
14301   int idxNum, const char *idxStr,
14302   int argc, sqlite3_value **argv
14303 ){
14304   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14305   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
14306   int rc = SQLITE_OK;
14307   const char *zSchema = "main";
14308   (void)idxStr;
14309   (void)argc;
14310 
14311   dbdataResetCursor(pCsr);
14312   assert( pCsr->iPgno==1 );
14313   if( idxNum & 0x01 ){
14314     zSchema = (const char*)sqlite3_value_text(argv[0]);
14315     if( zSchema==0 ) zSchema = "";
14316   }
14317   if( idxNum & 0x02 ){
14318     pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
14319     pCsr->bOnePage = 1;
14320   }else{
14321     rc = dbdataDbsize(pCsr, zSchema);
14322   }
14323 
14324   if( rc==SQLITE_OK ){
14325     int nFunc = 0;
14326     if( pTab->pStmt ){
14327       pCsr->pStmt = pTab->pStmt;
14328       pTab->pStmt = 0;
14329     }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
14330       char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
14331       if( zSql==0 ){
14332         rc = SQLITE_NOMEM;
14333       }else{
14334         rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
14335         sqlite3_free(zSql);
14336       }
14337     }else{
14338       rc = sqlite3_prepare_v2(pTab->db,
14339           "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
14340           &pCsr->pStmt, 0
14341       );
14342     }
14343   }
14344   if( rc==SQLITE_OK ){
14345     rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
14346   }
14347 
14348   /* Try to determine the encoding of the db by inspecting the header
14349   ** field on page 1. */
14350   if( rc==SQLITE_OK ){
14351     rc = dbdataGetEncoding(pCsr);
14352   }
14353 
14354   if( rc!=SQLITE_OK ){
14355     pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
14356   }
14357 
14358   if( rc==SQLITE_OK ){
14359     rc = dbdataNext(pCursor);
14360   }
14361   return rc;
14362 }
14363 
14364 /*
14365 ** Return a column for the sqlite_dbdata or sqlite_dbptr table.
14366 */
14367 static int dbdataColumn(
14368   sqlite3_vtab_cursor *pCursor,
14369   sqlite3_context *ctx,
14370   int i
14371 ){
14372   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14373   DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
14374   if( pTab->bPtr ){
14375     switch( i ){
14376       case DBPTR_COLUMN_PGNO:
14377         sqlite3_result_int64(ctx, pCsr->iPgno);
14378         break;
14379       case DBPTR_COLUMN_CHILD: {
14380         int iOff = pCsr->iPgno==1 ? 100 : 0;
14381         if( pCsr->iCell<0 ){
14382           iOff += 8;
14383         }else{
14384           iOff += 12 + pCsr->iCell*2;
14385           if( iOff>pCsr->nPage ) return SQLITE_OK;
14386           iOff = get_uint16(&pCsr->aPage[iOff]);
14387         }
14388         if( iOff<=pCsr->nPage ){
14389           sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
14390         }
14391         break;
14392       }
14393     }
14394   }else{
14395     switch( i ){
14396       case DBDATA_COLUMN_PGNO:
14397         sqlite3_result_int64(ctx, pCsr->iPgno);
14398         break;
14399       case DBDATA_COLUMN_CELL:
14400         sqlite3_result_int(ctx, pCsr->iCell);
14401         break;
14402       case DBDATA_COLUMN_FIELD:
14403         sqlite3_result_int(ctx, pCsr->iField);
14404         break;
14405       case DBDATA_COLUMN_VALUE: {
14406         if( pCsr->iField<0 ){
14407           sqlite3_result_int64(ctx, pCsr->iIntkey);
14408         }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){
14409           sqlite3_int64 iType;
14410           dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
14411           dbdataValue(
14412               ctx, pCsr->enc, iType, pCsr->pPtr,
14413               &pCsr->pRec[pCsr->nRec] - pCsr->pPtr
14414           );
14415         }
14416         break;
14417       }
14418     }
14419   }
14420   return SQLITE_OK;
14421 }
14422 
14423 /*
14424 ** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
14425 */
14426 static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
14427   DbdataCursor *pCsr = (DbdataCursor*)pCursor;
14428   *pRowid = pCsr->iRowid;
14429   return SQLITE_OK;
14430 }
14431 
14432 
14433 /*
14434 ** Invoke this routine to register the "sqlite_dbdata" virtual table module
14435 */
14436 static int sqlite3DbdataRegister(sqlite3 *db){
14437   static sqlite3_module dbdata_module = {
14438     0,                            /* iVersion */
14439     0,                            /* xCreate */
14440     dbdataConnect,                /* xConnect */
14441     dbdataBestIndex,              /* xBestIndex */
14442     dbdataDisconnect,             /* xDisconnect */
14443     0,                            /* xDestroy */
14444     dbdataOpen,                   /* xOpen - open a cursor */
14445     dbdataClose,                  /* xClose - close a cursor */
14446     dbdataFilter,                 /* xFilter - configure scan constraints */
14447     dbdataNext,                   /* xNext - advance a cursor */
14448     dbdataEof,                    /* xEof - check for end of scan */
14449     dbdataColumn,                 /* xColumn - read data */
14450     dbdataRowid,                  /* xRowid - read data */
14451     0,                            /* xUpdate */
14452     0,                            /* xBegin */
14453     0,                            /* xSync */
14454     0,                            /* xCommit */
14455     0,                            /* xRollback */
14456     0,                            /* xFindMethod */
14457     0,                            /* xRename */
14458     0,                            /* xSavepoint */
14459     0,                            /* xRelease */
14460     0,                            /* xRollbackTo */
14461     0,                            /* xShadowName */
14462     0                             /* xIntegrity */
14463   };
14464 
14465   int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
14466   if( rc==SQLITE_OK ){
14467     rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
14468   }
14469   return rc;
14470 }
14471 
14472 int sqlite3_dbdata_init(
14473   sqlite3 *db,
14474   char **pzErrMsg,
14475   const sqlite3_api_routines *pApi
14476 ){
14477   (void)pzErrMsg;
14478   return sqlite3DbdataRegister(db);
14479 }
14480 
14481 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
14482 
14483 /************************* End ../ext/recover/dbdata.c ********************/
14484 /************************* Begin ../ext/recover/sqlite3recover.c ******************/
14485 /*
14486 ** 2022-08-27
14487 **
14488 ** The author disclaims copyright to this source code.  In place of
14489 ** a legal notice, here is a blessing:
14490 **
14491 **    May you do good and not evil.
14492 **    May you find forgiveness for yourself and forgive others.
14493 **    May you share freely, never taking more than you give.
14494 **
14495 *************************************************************************
14496 **
14497 */
14498 
14499 
14500 /* #include "sqlite3recover.h" */
14501 #include <assert.h>
14502 #include <string.h>
14503 
14504 #ifndef SQLITE_OMIT_VIRTUALTABLE
14505 
14506 /*
14507 ** Declaration for public API function in file dbdata.c. This may be called
14508 ** with NULL as the final two arguments to register the sqlite_dbptr and
14509 ** sqlite_dbdata virtual tables with a database handle.
14510 */
14511 #ifdef _WIN32
14512 
14513 #endif
14514 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
14515 
14516 /* typedef unsigned int u32; */
14517 /* typedef unsigned char u8; */
14518 /* typedef sqlite3_int64 i64; */
14519 
14520 typedef struct RecoverTable RecoverTable;
14521 typedef struct RecoverColumn RecoverColumn;
14522 
14523 /*
14524 ** When recovering rows of data that can be associated with table
14525 ** definitions recovered from the sqlite_schema table, each table is
14526 ** represented by an instance of the following object.
14527 **
14528 ** iRoot:
14529 **   The root page in the original database. Not necessarily (and usually
14530 **   not) the same in the recovered database.
14531 **
14532 ** zTab:
14533 **   Name of the table.
14534 **
14535 ** nCol/aCol[]:
14536 **   aCol[] is an array of nCol columns. In the order in which they appear
14537 **   in the table.
14538 **
14539 ** bIntkey:
14540 **   Set to true for intkey tables, false for WITHOUT ROWID.
14541 **
14542 ** iRowidBind:
14543 **   Each column in the aCol[] array has associated with it the index of
14544 **   the bind parameter its values will be bound to in the INSERT statement
14545 **   used to construct the output database. If the table does has a rowid
14546 **   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
14547 **   index of the bind paramater to which the rowid value should be bound.
14548 **   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
14549 **   KEY column, then the rowid value should be bound to the index associated
14550 **   with the column.
14551 **
14552 ** pNext:
14553 **   All RecoverTable objects used by the recovery operation are allocated
14554 **   and populated as part of creating the recovered database schema in
14555 **   the output database, before any non-schema data are recovered. They
14556 **   are then stored in a singly-linked list linked by this variable beginning
14557 **   at sqlite3_recover.pTblList.
14558 */
14559 struct RecoverTable {
14560   u32 iRoot;                      /* Root page in original database */
14561   char *zTab;                     /* Name of table */
14562   int nCol;                       /* Number of columns in table */
14563   RecoverColumn *aCol;            /* Array of columns */
14564   int bIntkey;                    /* True for intkey, false for without rowid */
14565   int iRowidBind;                 /* If >0, bind rowid to INSERT here */
14566   RecoverTable *pNext;
14567 };
14568 
14569 /*
14570 ** Each database column is represented by an instance of the following object
14571 ** stored in the RecoverTable.aCol[] array of the associated table.
14572 **
14573 ** iField:
14574 **   The index of the associated field within database records. Or -1 if
14575 **   there is no associated field (e.g. for virtual generated columns).
14576 **
14577 ** iBind:
14578 **   The bind index of the INSERT statement to bind this columns values
14579 **   to. Or 0 if there is no such index (iff (iField<0)).
14580 **
14581 ** bIPK:
14582 **   True if this is the INTEGER PRIMARY KEY column.
14583 **
14584 ** zCol:
14585 **   Name of column.
14586 **
14587 ** eHidden:
14588 **   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
14589 */
14590 struct RecoverColumn {
14591   int iField;                     /* Field in record on disk */
14592   int iBind;                      /* Binding to use in INSERT */
14593   int bIPK;                       /* True for IPK column */
14594   char *zCol;
14595   int eHidden;
14596 };
14597 
14598 #define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
14599 #define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
14600 #define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
14601 #define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
14602 
14603 /*
14604 ** Bitmap object used to track pages in the input database. Allocated
14605 ** and manipulated only by the following functions:
14606 **
14607 **     recoverBitmapAlloc()
14608 **     recoverBitmapFree()
14609 **     recoverBitmapSet()
14610 **     recoverBitmapQuery()
14611 **
14612 ** nPg:
14613 **   Largest page number that may be stored in the bitmap. The range
14614 **   of valid keys is 1 to nPg, inclusive.
14615 **
14616 ** aElem[]:
14617 **   Array large enough to contain a bit for each key. For key value
14618 **   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
14619 **   In other words, the following is true if bit iKey is set, or
14620 **   false if it is clear:
14621 **
14622 **       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
14623 */
14624 typedef struct RecoverBitmap RecoverBitmap;
14625 struct RecoverBitmap {
14626   i64 nPg;                        /* Size of bitmap */
14627   u32 aElem[1];                   /* Array of 32-bit bitmasks */
14628 };
14629 
14630 /*
14631 ** State variables (part of the sqlite3_recover structure) used while
14632 ** recovering data for tables identified in the recovered schema (state
14633 ** RECOVER_STATE_WRITING).
14634 */
14635 typedef struct RecoverStateW1 RecoverStateW1;
14636 struct RecoverStateW1 {
14637   sqlite3_stmt *pTbls;
14638   sqlite3_stmt *pSel;
14639   sqlite3_stmt *pInsert;
14640   int nInsert;
14641 
14642   RecoverTable *pTab;             /* Table currently being written */
14643   int nMax;                       /* Max column count in any schema table */
14644   sqlite3_value **apVal;          /* Array of nMax values */
14645   int nVal;                       /* Number of valid entries in apVal[] */
14646   int bHaveRowid;
14647   i64 iRowid;
14648   i64 iPrevPage;
14649   int iPrevCell;
14650 };
14651 
14652 /*
14653 ** State variables (part of the sqlite3_recover structure) used while
14654 ** recovering data destined for the lost and found table (states
14655 ** RECOVER_STATE_LOSTANDFOUND[123]).
14656 */
14657 typedef struct RecoverStateLAF RecoverStateLAF;
14658 struct RecoverStateLAF {
14659   RecoverBitmap *pUsed;
14660   i64 nPg;                        /* Size of db in pages */
14661   sqlite3_stmt *pAllAndParent;
14662   sqlite3_stmt *pMapInsert;
14663   sqlite3_stmt *pMaxField;
14664   sqlite3_stmt *pUsedPages;
14665   sqlite3_stmt *pFindRoot;
14666   sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
14667   sqlite3_stmt *pAllPage;
14668   sqlite3_stmt *pPageData;
14669   sqlite3_value **apVal;
14670   int nMaxField;
14671 };
14672 
14673 /*
14674 ** Main recover handle structure.
14675 */
14676 struct sqlite3_recover {
14677   /* Copies of sqlite3_recover_init[_sql]() parameters */
14678   sqlite3 *dbIn;                  /* Input database */
14679   char *zDb;                      /* Name of input db ("main" etc.) */
14680   char *zUri;                     /* URI for output database */
14681   void *pSqlCtx;                  /* SQL callback context */
14682   int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
14683 
14684   /* Values configured by sqlite3_recover_config() */
14685   char *zStateDb;                 /* State database to use (or NULL) */
14686   char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
14687   int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
14688   int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
14689   int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
14690 
14691   int pgsz;
14692   int detected_pgsz;
14693   int nReserve;
14694   u8 *pPage1Disk;
14695   u8 *pPage1Cache;
14696 
14697   /* Error code and error message */
14698   int errCode;                    /* For sqlite3_recover_errcode() */
14699   char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
14700 
14701   int eState;
14702   int bCloseTransaction;
14703 
14704   /* Variables used with eState==RECOVER_STATE_WRITING */
14705   RecoverStateW1 w1;
14706 
14707   /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
14708   RecoverStateLAF laf;
14709 
14710   /* Fields used within sqlite3_recover_run() */
14711   sqlite3 *dbOut;                 /* Output database */
14712   sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
14713   RecoverTable *pTblList;         /* List of tables recovered from schema */
14714 };
14715 
14716 /*
14717 ** The various states in which an sqlite3_recover object may exist:
14718 **
14719 **   RECOVER_STATE_INIT:
14720 **    The object is initially created in this state. sqlite3_recover_step()
14721 **    has yet to be called. This is the only state in which it is permitted
14722 **    to call sqlite3_recover_config().
14723 **
14724 **   RECOVER_STATE_WRITING:
14725 **
14726 **   RECOVER_STATE_LOSTANDFOUND1:
14727 **    State to populate the bitmap of pages used by other tables or the
14728 **    database freelist.
14729 **
14730 **   RECOVER_STATE_LOSTANDFOUND2:
14731 **    Populate the recovery.map table - used to figure out a "root" page
14732 **    for each lost page from in the database from which records are
14733 **    extracted.
14734 **
14735 **   RECOVER_STATE_LOSTANDFOUND3:
14736 **    Populate the lost-and-found table itself.
14737 */
14738 #define RECOVER_STATE_INIT           0
14739 #define RECOVER_STATE_WRITING        1
14740 #define RECOVER_STATE_LOSTANDFOUND1  2
14741 #define RECOVER_STATE_LOSTANDFOUND2  3
14742 #define RECOVER_STATE_LOSTANDFOUND3  4
14743 #define RECOVER_STATE_SCHEMA2        5
14744 #define RECOVER_STATE_DONE           6
14745 
14746 
14747 /*
14748 ** Global variables used by this extension.
14749 */
14750 typedef struct RecoverGlobal RecoverGlobal;
14751 struct RecoverGlobal {
14752   const sqlite3_io_methods *pMethods;
14753   sqlite3_recover *p;
14754 };
14755 static RecoverGlobal recover_g;
14756 
14757 /*
14758 ** Use this static SQLite mutex to protect the globals during the
14759 ** first call to sqlite3_recover_step().
14760 */
14761 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
14762 
14763 
14764 /*
14765 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
14766 */
14767 #define RECOVER_ROWID_DEFAULT 1
14768 
14769 /*
14770 ** Mutex handling:
14771 **
14772 **    recoverEnterMutex()       -   Enter the recovery mutex
14773 **    recoverLeaveMutex()       -   Leave the recovery mutex
14774 **    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
14775 */
14776 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
14777 # define recoverEnterMutex()
14778 # define recoverLeaveMutex()
14779 #else
14780 static void recoverEnterMutex(void){
14781   sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
14782 }
14783 static void recoverLeaveMutex(void){
14784   sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
14785 }
14786 #endif
14787 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
14788 static void recoverAssertMutexHeld(void){
14789   assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
14790 }
14791 #else
14792 # define recoverAssertMutexHeld()
14793 #endif
14794 
14795 
14796 /*
14797 ** Like strlen(). But handles NULL pointer arguments.
14798 */
14799 static int recoverStrlen(const char *zStr){
14800   if( zStr==0 ) return 0;
14801   return (int)(strlen(zStr)&0x7fffffff);
14802 }
14803 
14804 /*
14805 ** This function is a no-op if the recover handle passed as the first
14806 ** argument already contains an error (if p->errCode!=SQLITE_OK).
14807 **
14808 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
14809 ** bytes in size. If successful, a pointer to the new buffer is returned. Or,
14810 ** if an OOM error occurs, NULL is returned and the handle error code
14811 ** (p->errCode) set to SQLITE_NOMEM.
14812 */
14813 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
14814   void *pRet = 0;
14815   assert( nByte>0 );
14816   if( p->errCode==SQLITE_OK ){
14817     pRet = sqlite3_malloc64(nByte);
14818     if( pRet ){
14819       memset(pRet, 0, nByte);
14820     }else{
14821       p->errCode = SQLITE_NOMEM;
14822     }
14823   }
14824   return pRet;
14825 }
14826 
14827 /*
14828 ** Set the error code and error message for the recover handle passed as
14829 ** the first argument. The error code is set to the value of parameter
14830 ** errCode.
14831 **
14832 ** Parameter zFmt must be a printf() style formatting string. The handle
14833 ** error message is set to the result of using any trailing arguments for
14834 ** parameter substitutions in the formatting string.
14835 **
14836 ** For example:
14837 **
14838 **   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
14839 */
14840 static int recoverError(
14841   sqlite3_recover *p,
14842   int errCode,
14843   const char *zFmt, ...
14844 ){
14845   char *z = 0;
14846   va_list ap;
14847   va_start(ap, zFmt);
14848   if( zFmt ){
14849     z = sqlite3_vmprintf(zFmt, ap);
14850     va_end(ap);
14851   }
14852   sqlite3_free(p->zErrMsg);
14853   p->zErrMsg = z;
14854   p->errCode = errCode;
14855   return errCode;
14856 }
14857 
14858 
14859 /*
14860 ** This function is a no-op if p->errCode is initially other than SQLITE_OK.
14861 ** In this case it returns NULL.
14862 **
14863 ** Otherwise, an attempt is made to allocate and return a bitmap object
14864 ** large enough to store a bit for all page numbers between 1 and nPg,
14865 ** inclusive. The bitmap is initially zeroed.
14866 */
14867 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
14868   int nElem = (nPg+1+31) / 32;
14869   int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
14870   RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
14871 
14872   if( pRet ){
14873     pRet->nPg = nPg;
14874   }
14875   return pRet;
14876 }
14877 
14878 /*
14879 ** Free a bitmap object allocated by recoverBitmapAlloc().
14880 */
14881 static void recoverBitmapFree(RecoverBitmap *pMap){
14882   sqlite3_free(pMap);
14883 }
14884 
14885 /*
14886 ** Set the bit associated with page iPg in bitvec pMap.
14887 */
14888 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
14889   if( iPg<=pMap->nPg ){
14890     int iElem = (iPg / 32);
14891     int iBit = (iPg % 32);
14892     pMap->aElem[iElem] |= (((u32)1) << iBit);
14893   }
14894 }
14895 
14896 /*
14897 ** Query bitmap object pMap for the state of the bit associated with page
14898 ** iPg. Return 1 if it is set, or 0 otherwise.
14899 */
14900 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
14901   int ret = 1;
14902   if( iPg<=pMap->nPg && iPg>0 ){
14903     int iElem = (iPg / 32);
14904     int iBit = (iPg % 32);
14905     ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
14906   }
14907   return ret;
14908 }
14909 
14910 /*
14911 ** Set the recover handle error to the error code and message returned by
14912 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
14913 ** handle db.
14914 */
14915 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
14916   return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
14917 }
14918 
14919 /*
14920 ** This function is a no-op if recover handle p already contains an error
14921 ** (if p->errCode!=SQLITE_OK).
14922 **
14923 ** Otherwise, it attempts to prepare the SQL statement in zSql against
14924 ** database handle db. If successful, the statement handle is returned.
14925 ** Or, if an error occurs, NULL is returned and an error left in the
14926 ** recover handle.
14927 */
14928 static sqlite3_stmt *recoverPrepare(
14929   sqlite3_recover *p,
14930   sqlite3 *db,
14931   const char *zSql
14932 ){
14933   sqlite3_stmt *pStmt = 0;
14934   if( p->errCode==SQLITE_OK ){
14935     if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
14936       recoverDbError(p, db);
14937     }
14938   }
14939   return pStmt;
14940 }
14941 
14942 /*
14943 ** This function is a no-op if recover handle p already contains an error
14944 ** (if p->errCode!=SQLITE_OK).
14945 **
14946 ** Otherwise, argument zFmt is used as a printf() style format string,
14947 ** along with any trailing arguments, to create an SQL statement. This
14948 ** SQL statement is prepared against database handle db and, if successful,
14949 ** the statment handle returned. Or, if an error occurs - either during
14950 ** the printf() formatting or when preparing the resulting SQL - an
14951 ** error code and message are left in the recover handle.
14952 */
14953 static sqlite3_stmt *recoverPreparePrintf(
14954   sqlite3_recover *p,
14955   sqlite3 *db,
14956   const char *zFmt, ...
14957 ){
14958   sqlite3_stmt *pStmt = 0;
14959   if( p->errCode==SQLITE_OK ){
14960     va_list ap;
14961     char *z;
14962     va_start(ap, zFmt);
14963     z = sqlite3_vmprintf(zFmt, ap);
14964     va_end(ap);
14965     if( z==0 ){
14966       p->errCode = SQLITE_NOMEM;
14967     }else{
14968       pStmt = recoverPrepare(p, db, z);
14969       sqlite3_free(z);
14970     }
14971   }
14972   return pStmt;
14973 }
14974 
14975 /*
14976 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
14977 ** indicates that an error occurred, and there is not already an error
14978 ** in the recover handle passed as the first argument, set the error
14979 ** code and error message appropriately.
14980 **
14981 ** This function returns a copy of the statement handle pointer passed
14982 ** as the second argument.
14983 */
14984 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
14985   int rc = sqlite3_reset(pStmt);
14986   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
14987     recoverDbError(p, sqlite3_db_handle(pStmt));
14988   }
14989   return pStmt;
14990 }
14991 
14992 /*
14993 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
14994 ** indicates that an error occurred, and there is not already an error
14995 ** in the recover handle passed as the first argument, set the error
14996 ** code and error message appropriately.
14997 */
14998 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
14999   sqlite3 *db = sqlite3_db_handle(pStmt);
15000   int rc = sqlite3_finalize(pStmt);
15001   if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
15002     recoverDbError(p, db);
15003   }
15004 }
15005 
15006 /*
15007 ** This function is a no-op if recover handle p already contains an error
15008 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
15009 ** case.
15010 **
15011 ** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
15012 ** Or, if an error occurs, leave an error code and message in the recover
15013 ** handle and return a copy of the error code.
15014 */
15015 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
15016   if( p->errCode==SQLITE_OK ){
15017     int rc = sqlite3_exec(db, zSql, 0, 0, 0);
15018     if( rc ){
15019       recoverDbError(p, db);
15020     }
15021   }
15022   return p->errCode;
15023 }
15024 
15025 /*
15026 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an
15027 ** error in the recover handle passed as the first argument if an error
15028 ** (e.g. an OOM) occurs.
15029 */
15030 static void recoverBindValue(
15031   sqlite3_recover *p,
15032   sqlite3_stmt *pStmt,
15033   int iBind,
15034   sqlite3_value *pVal
15035 ){
15036   if( p->errCode==SQLITE_OK ){
15037     int rc = sqlite3_bind_value(pStmt, iBind, pVal);
15038     if( rc ) recoverError(p, rc, 0);
15039   }
15040 }
15041 
15042 /*
15043 ** This function is a no-op if recover handle p already contains an error
15044 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
15045 **
15046 ** Otherwise, an attempt is made to interpret zFmt as a printf() style
15047 ** formatting string and the result of using the trailing arguments for
15048 ** parameter substitution with it written into a buffer obtained from
15049 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
15050 ** It is the responsibility of the caller to eventually free the buffer
15051 ** using sqlite3_free().
15052 **
15053 ** Or, if an error occurs, an error code and message is left in the recover
15054 ** handle and NULL returned.
15055 */
15056 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
15057   va_list ap;
15058   char *z;
15059   va_start(ap, zFmt);
15060   z = sqlite3_vmprintf(zFmt, ap);
15061   va_end(ap);
15062   if( p->errCode==SQLITE_OK ){
15063     if( z==0 ) p->errCode = SQLITE_NOMEM;
15064   }else{
15065     sqlite3_free(z);
15066     z = 0;
15067   }
15068   return z;
15069 }
15070 
15071 /*
15072 ** This function is a no-op if recover handle p already contains an error
15073 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
15074 **
15075 ** Otherwise, execute "PRAGMA page_count" against the input database. If
15076 ** successful, return the integer result. Or, if an error occurs, leave an
15077 ** error code and error message in the sqlite3_recover handle and return
15078 ** zero.
15079 */
15080 static i64 recoverPageCount(sqlite3_recover *p){
15081   i64 nPg = 0;
15082   if( p->errCode==SQLITE_OK ){
15083     sqlite3_stmt *pStmt = 0;
15084     pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
15085     if( pStmt ){
15086       sqlite3_step(pStmt);
15087       nPg = sqlite3_column_int64(pStmt, 0);
15088     }
15089     recoverFinalize(p, pStmt);
15090   }
15091   return nPg;
15092 }
15093 
15094 /*
15095 ** Implementation of SQL scalar function "read_i32". The first argument to
15096 ** this function must be a blob. The second a non-negative integer. This
15097 ** function reads and returns a 32-bit big-endian integer from byte
15098 ** offset (4*<arg2>) of the blob.
15099 **
15100 **     SELECT read_i32(<blob>, <idx>)
15101 */
15102 static void recoverReadI32(
15103   sqlite3_context *context,
15104   int argc,
15105   sqlite3_value **argv
15106 ){
15107   const unsigned char *pBlob;
15108   int nBlob;
15109   int iInt;
15110 
15111   assert( argc==2 );
15112   nBlob = sqlite3_value_bytes(argv[0]);
15113   pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
15114   iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
15115 
15116   if( (iInt+1)*4<=nBlob ){
15117     const unsigned char *a = &pBlob[iInt*4];
15118     i64 iVal = ((i64)a[0]<<24)
15119              + ((i64)a[1]<<16)
15120              + ((i64)a[2]<< 8)
15121              + ((i64)a[3]<< 0);
15122     sqlite3_result_int64(context, iVal);
15123   }
15124 }
15125 
15126 /*
15127 ** Implementation of SQL scalar function "page_is_used". This function
15128 ** is used as part of the procedure for locating orphan rows for the
15129 ** lost-and-found table, and it depends on those routines having populated
15130 ** the sqlite3_recover.laf.pUsed variable.
15131 **
15132 ** The only argument to this function is a page-number. It returns true
15133 ** if the page has already been used somehow during data recovery, or false
15134 ** otherwise.
15135 **
15136 **     SELECT page_is_used(<pgno>);
15137 */
15138 static void recoverPageIsUsed(
15139   sqlite3_context *pCtx,
15140   int nArg,
15141   sqlite3_value **apArg
15142 ){
15143   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15144   i64 pgno = sqlite3_value_int64(apArg[0]);
15145   assert( nArg==1 );
15146   sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
15147 }
15148 
15149 /*
15150 ** The implementation of a user-defined SQL function invoked by the
15151 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
15152 ** of the database being recovered.
15153 **
15154 ** This function always takes a single integer argument. If the argument
15155 ** is zero, then the value returned is the number of pages in the db being
15156 ** recovered. If the argument is greater than zero, it is a page number.
15157 ** The value returned in this case is an SQL blob containing the data for
15158 ** the identified page of the db being recovered. e.g.
15159 **
15160 **     SELECT getpage(0);       -- return number of pages in db
15161 **     SELECT getpage(4);       -- return page 4 of db as a blob of data
15162 */
15163 static void recoverGetPage(
15164   sqlite3_context *pCtx,
15165   int nArg,
15166   sqlite3_value **apArg
15167 ){
15168   sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
15169   i64 pgno = sqlite3_value_int64(apArg[0]);
15170   sqlite3_stmt *pStmt = 0;
15171 
15172   assert( nArg==1 );
15173   if( pgno==0 ){
15174     i64 nPg = recoverPageCount(p);
15175     sqlite3_result_int64(pCtx, nPg);
15176     return;
15177   }else{
15178     if( p->pGetPage==0 ){
15179       pStmt = p->pGetPage = recoverPreparePrintf(
15180           p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
15181       );
15182     }else if( p->errCode==SQLITE_OK ){
15183       pStmt = p->pGetPage;
15184     }
15185 
15186     if( pStmt ){
15187       sqlite3_bind_int64(pStmt, 1, pgno);
15188       if( SQLITE_ROW==sqlite3_step(pStmt) ){
15189         const u8 *aPg;
15190         int nPg;
15191         assert( p->errCode==SQLITE_OK );
15192         aPg = sqlite3_column_blob(pStmt, 0);
15193         nPg = sqlite3_column_bytes(pStmt, 0);
15194         if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
15195           aPg = p->pPage1Disk;
15196         }
15197         sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
15198       }
15199       recoverReset(p, pStmt);
15200     }
15201   }
15202 
15203   if( p->errCode ){
15204     if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
15205     sqlite3_result_error_code(pCtx, p->errCode);
15206   }
15207 }
15208 
15209 /*
15210 ** Find a string that is not found anywhere in z[].  Return a pointer
15211 ** to that string.
15212 **
15213 ** Try to use zA and zB first.  If both of those are already found in z[]
15214 ** then make up some string and store it in the buffer zBuf.
15215 */
15216 static const char *recoverUnusedString(
15217   const char *z,                    /* Result must not appear anywhere in z */
15218   const char *zA, const char *zB,   /* Try these first */
15219   char *zBuf                        /* Space to store a generated string */
15220 ){
15221   unsigned i = 0;
15222   if( strstr(z, zA)==0 ) return zA;
15223   if( strstr(z, zB)==0 ) return zB;
15224   do{
15225     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
15226   }while( strstr(z,zBuf)!=0 );
15227   return zBuf;
15228 }
15229 
15230 /*
15231 ** Implementation of scalar SQL function "escape_crnl".  The argument passed to
15232 ** this function is the output of built-in function quote(). If the first
15233 ** character of the input is "'", indicating that the value passed to quote()
15234 ** was a text value, then this function searches the input for "\n" and "\r"
15235 ** characters and adds a wrapper similar to the following:
15236 **
15237 **   replace(replace(<input>, '\n', char(10), '\r', char(13));
15238 **
15239 ** Or, if the first character of the input is not "'", then a copy of the input
15240 ** is returned.
15241 */
15242 static void recoverEscapeCrnl(
15243   sqlite3_context *context,
15244   int argc,
15245   sqlite3_value **argv
15246 ){
15247   const char *zText = (const char*)sqlite3_value_text(argv[0]);
15248   (void)argc;
15249   if( zText && zText[0]=='\'' ){
15250     int nText = sqlite3_value_bytes(argv[0]);
15251     int i;
15252     char zBuf1[20];
15253     char zBuf2[20];
15254     const char *zNL = 0;
15255     const char *zCR = 0;
15256     int nCR = 0;
15257     int nNL = 0;
15258 
15259     for(i=0; zText[i]; i++){
15260       if( zNL==0 && zText[i]=='\n' ){
15261         zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
15262         nNL = (int)strlen(zNL);
15263       }
15264       if( zCR==0 && zText[i]=='\r' ){
15265         zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
15266         nCR = (int)strlen(zCR);
15267       }
15268     }
15269 
15270     if( zNL || zCR ){
15271       int iOut = 0;
15272       i64 nMax = (nNL > nCR) ? nNL : nCR;
15273       i64 nAlloc = nMax * nText + (nMax+64)*2;
15274       char *zOut = (char*)sqlite3_malloc64(nAlloc);
15275       if( zOut==0 ){
15276         sqlite3_result_error_nomem(context);
15277         return;
15278       }
15279 
15280       if( zNL && zCR ){
15281         memcpy(&zOut[iOut], "replace(replace(", 16);
15282         iOut += 16;
15283       }else{
15284         memcpy(&zOut[iOut], "replace(", 8);
15285         iOut += 8;
15286       }
15287       for(i=0; zText[i]; i++){
15288         if( zText[i]=='\n' ){
15289           memcpy(&zOut[iOut], zNL, nNL);
15290           iOut += nNL;
15291         }else if( zText[i]=='\r' ){
15292           memcpy(&zOut[iOut], zCR, nCR);
15293           iOut += nCR;
15294         }else{
15295           zOut[iOut] = zText[i];
15296           iOut++;
15297         }
15298       }
15299 
15300       if( zNL ){
15301         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
15302         memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
15303         memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
15304       }
15305       if( zCR ){
15306         memcpy(&zOut[iOut], ",'", 2); iOut += 2;
15307         memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
15308         memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
15309       }
15310 
15311       sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
15312       sqlite3_free(zOut);
15313       return;
15314     }
15315   }
15316 
15317   sqlite3_result_value(context, argv[0]);
15318 }
15319 
15320 /*
15321 ** This function is a no-op if recover handle p already contains an error
15322 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
15323 ** this case.
15324 **
15325 ** Otherwise, attempt to populate temporary table "recovery.schema" with the
15326 ** parts of the database schema that can be extracted from the input database.
15327 **
15328 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
15329 ** and error message are left in the recover handle and a copy of the
15330 ** error code returned. It is not considered an error if part of all of
15331 ** the database schema cannot be recovered due to corruption.
15332 */
15333 static int recoverCacheSchema(sqlite3_recover *p){
15334   return recoverExec(p, p->dbOut,
15335     "WITH RECURSIVE pages(p) AS ("
15336     "  SELECT 1"
15337     "    UNION"
15338     "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
15339     ")"
15340     "INSERT INTO recovery.schema SELECT"
15341     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
15342     "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
15343     "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
15344     "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
15345     "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
15346     "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
15347     "  SELECT p FROM pages"
15348     ") GROUP BY pgno, cell"
15349   );
15350 }
15351 
15352 /*
15353 ** If this recover handle is not in SQL callback mode (i.e. was not created
15354 ** using sqlite3_recover_init_sql()) of if an error has already occurred,
15355 ** this function is a no-op. Otherwise, issue a callback with SQL statement
15356 ** zSql as the parameter.
15357 **
15358 ** If the callback returns non-zero, set the recover handle error code to
15359 ** the value returned (so that the caller will abandon processing).
15360 */
15361 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
15362   if( p->errCode==SQLITE_OK && p->xSql ){
15363     int res = p->xSql(p->pSqlCtx, zSql);
15364     if( res ){
15365       recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
15366     }
15367   }
15368 }
15369 
15370 /*
15371 ** Transfer the following settings from the input database to the output
15372 ** database:
15373 **
15374 **   + page-size,
15375 **   + auto-vacuum settings,
15376 **   + database encoding,
15377 **   + user-version (PRAGMA user_version), and
15378 **   + application-id (PRAGMA application_id), and
15379 */
15380 static void recoverTransferSettings(sqlite3_recover *p){
15381   const char *aPragma[] = {
15382     "encoding",
15383     "page_size",
15384     "auto_vacuum",
15385     "user_version",
15386     "application_id"
15387   };
15388   int ii;
15389 
15390   /* Truncate the output database to 0 pages in size. This is done by
15391   ** opening a new, empty, temp db, then using the backup API to clobber
15392   ** any existing output db with a copy of it. */
15393   if( p->errCode==SQLITE_OK ){
15394     sqlite3 *db2 = 0;
15395     int rc = sqlite3_open("", &db2);
15396     if( rc!=SQLITE_OK ){
15397       recoverDbError(p, db2);
15398       return;
15399     }
15400 
15401     for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
15402       const char *zPrag = aPragma[ii];
15403       sqlite3_stmt *p1 = 0;
15404       p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
15405       if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
15406         const char *zArg = (const char*)sqlite3_column_text(p1, 0);
15407         char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
15408         recoverSqlCallback(p, z2);
15409         recoverExec(p, db2, z2);
15410         sqlite3_free(z2);
15411         if( zArg==0 ){
15412           recoverError(p, SQLITE_NOMEM, 0);
15413         }
15414       }
15415       recoverFinalize(p, p1);
15416     }
15417     recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
15418 
15419     if( p->errCode==SQLITE_OK ){
15420       sqlite3 *db = p->dbOut;
15421       sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
15422       if( pBackup ){
15423         sqlite3_backup_step(pBackup, -1);
15424         p->errCode = sqlite3_backup_finish(pBackup);
15425       }else{
15426         recoverDbError(p, db);
15427       }
15428     }
15429 
15430     sqlite3_close(db2);
15431   }
15432 }
15433 
15434 /*
15435 ** This function is a no-op if recover handle p already contains an error
15436 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
15437 ** this case.
15438 **
15439 ** Otherwise, an attempt is made to open the output database, attach
15440 ** and create the schema of the temporary database used to store
15441 ** intermediate data, and to register all required user functions and
15442 ** virtual table modules with the output handle.
15443 **
15444 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
15445 ** and error message are left in the recover handle and a copy of the
15446 ** error code returned.
15447 */
15448 static int recoverOpenOutput(sqlite3_recover *p){
15449   struct Func {
15450     const char *zName;
15451     int nArg;
15452     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
15453   } aFunc[] = {
15454     { "getpage", 1, recoverGetPage },
15455     { "page_is_used", 1, recoverPageIsUsed },
15456     { "read_i32", 2, recoverReadI32 },
15457     { "escape_crnl", 1, recoverEscapeCrnl },
15458   };
15459 
15460   const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
15461   sqlite3 *db = 0;                /* New database handle */
15462   int ii;                         /* For iterating through aFunc[] */
15463 
15464   assert( p->dbOut==0 );
15465 
15466   if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
15467     recoverDbError(p, db);
15468   }
15469 
15470   /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
15471   ** These two are registered with the output database handle - this
15472   ** module depends on the input handle supporting the sqlite_dbpage
15473   ** virtual table only.  */
15474   if( p->errCode==SQLITE_OK ){
15475     p->errCode = sqlite3_dbdata_init(db, 0, 0);
15476   }
15477 
15478   /* Register the custom user-functions with the output handle. */
15479   for(ii=0;
15480       p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
15481       ii++){
15482     p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
15483         aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
15484     );
15485   }
15486 
15487   p->dbOut = db;
15488   return p->errCode;
15489 }
15490 
15491 /*
15492 ** Attach the auxiliary database 'recovery' to the output database handle.
15493 ** This temporary database is used during the recovery process and then
15494 ** discarded.
15495 */
15496 static void recoverOpenRecovery(sqlite3_recover *p){
15497   char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
15498   recoverExec(p, p->dbOut, zSql);
15499   recoverExec(p, p->dbOut,
15500       "PRAGMA writable_schema = 1;"
15501       "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
15502       "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
15503   );
15504   sqlite3_free(zSql);
15505 }
15506 
15507 
15508 /*
15509 ** This function is a no-op if recover handle p already contains an error
15510 ** (if p->errCode!=SQLITE_OK).
15511 **
15512 ** Otherwise, argument zName must be the name of a table that has just been
15513 ** created in the output database. This function queries the output db
15514 ** for the schema of said table, and creates a RecoverTable object to
15515 ** store the schema in memory. The new RecoverTable object is linked into
15516 ** the list at sqlite3_recover.pTblList.
15517 **
15518 ** Parameter iRoot must be the root page of table zName in the INPUT
15519 ** database.
15520 */
15521 static void recoverAddTable(
15522   sqlite3_recover *p,
15523   const char *zName,              /* Name of table created in output db */
15524   i64 iRoot                       /* Root page of same table in INPUT db */
15525 ){
15526   sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
15527       "PRAGMA table_xinfo(%Q)", zName
15528   );
15529 
15530   if( pStmt ){
15531     int iPk = -1;
15532     int iBind = 1;
15533     RecoverTable *pNew = 0;
15534     int nCol = 0;
15535     int nName = recoverStrlen(zName);
15536     int nByte = 0;
15537     while( sqlite3_step(pStmt)==SQLITE_ROW ){
15538       nCol++;
15539       nByte += (sqlite3_column_bytes(pStmt, 1)+1);
15540     }
15541     nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
15542     recoverReset(p, pStmt);
15543 
15544     pNew = recoverMalloc(p, nByte);
15545     if( pNew ){
15546       int i = 0;
15547       int iField = 0;
15548       char *csr = 0;
15549       pNew->aCol = (RecoverColumn*)&pNew[1];
15550       pNew->zTab = csr = (char*)&pNew->aCol[nCol];
15551       pNew->nCol = nCol;
15552       pNew->iRoot = iRoot;
15553       memcpy(csr, zName, nName);
15554       csr += nName+1;
15555 
15556       for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
15557         int iPKF = sqlite3_column_int(pStmt, 5);
15558         int n = sqlite3_column_bytes(pStmt, 1);
15559         const char *z = (const char*)sqlite3_column_text(pStmt, 1);
15560         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
15561         int eHidden = sqlite3_column_int(pStmt, 6);
15562 
15563         if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
15564         if( iPKF>1 ) iPk = -2;
15565         pNew->aCol[i].zCol = csr;
15566         pNew->aCol[i].eHidden = eHidden;
15567         if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
15568           pNew->aCol[i].iField = -1;
15569         }else{
15570           pNew->aCol[i].iField = iField++;
15571         }
15572         if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
15573          && eHidden!=RECOVER_EHIDDEN_STORED
15574         ){
15575           pNew->aCol[i].iBind = iBind++;
15576         }
15577         memcpy(csr, z, n);
15578         csr += (n+1);
15579       }
15580 
15581       pNew->pNext = p->pTblList;
15582       p->pTblList = pNew;
15583       pNew->bIntkey = 1;
15584     }
15585 
15586     recoverFinalize(p, pStmt);
15587 
15588     pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
15589     while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
15590       int iField = sqlite3_column_int(pStmt, 0);
15591       int iCol = sqlite3_column_int(pStmt, 1);
15592 
15593       assert( iCol<pNew->nCol );
15594       pNew->aCol[iCol].iField = iField;
15595 
15596       pNew->bIntkey = 0;
15597       iPk = -2;
15598     }
15599     recoverFinalize(p, pStmt);
15600 
15601     if( p->errCode==SQLITE_OK ){
15602       if( iPk>=0 ){
15603         pNew->aCol[iPk].bIPK = 1;
15604       }else if( pNew->bIntkey ){
15605         pNew->iRowidBind = iBind++;
15606       }
15607     }
15608   }
15609 }
15610 
15611 /*
15612 ** This function is called after recoverCacheSchema() has cached those parts
15613 ** of the input database schema that could be recovered in temporary table
15614 ** "recovery.schema". This function creates in the output database copies
15615 ** of all parts of that schema that must be created before the tables can
15616 ** be populated. Specifically, this means:
15617 **
15618 **     * all tables that are not VIRTUAL, and
15619 **     * UNIQUE indexes.
15620 **
15621 ** If the recovery handle uses SQL callbacks, then callbacks containing
15622 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
15623 **
15624 ** Additionally, records are added to the sqlite_schema table of the
15625 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
15626 ** records are written directly to sqlite_schema, not actually executed.
15627 ** If the handle is in SQL callback mode, then callbacks are invoked
15628 ** with equivalent SQL statements.
15629 */
15630 static int recoverWriteSchema1(sqlite3_recover *p){
15631   sqlite3_stmt *pSelect = 0;
15632   sqlite3_stmt *pTblname = 0;
15633 
15634   pSelect = recoverPrepare(p, p->dbOut,
15635       "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
15636       "  SELECT rootpage, name, sql, "
15637       "    type='table', "
15638       "    sql LIKE 'create virtual%',"
15639       "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
15640       "  FROM recovery.schema"
15641       ")"
15642       "SELECT rootpage, tbl, isVirtual, name, sql"
15643       " FROM dbschema "
15644       "  WHERE tbl OR isIndex"
15645       "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
15646   );
15647 
15648   pTblname = recoverPrepare(p, p->dbOut,
15649       "SELECT name FROM sqlite_schema "
15650       "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
15651   );
15652 
15653   if( pSelect ){
15654     sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
15655     while( sqlite3_step(pSelect)==SQLITE_ROW ){
15656       i64 iRoot = sqlite3_column_int64(pSelect, 0);
15657       int bTable = sqlite3_column_int(pSelect, 1);
15658       int bVirtual = sqlite3_column_int(pSelect, 2);
15659       const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
15660       const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
15661       char *zFree = 0;
15662       int rc = SQLITE_OK;
15663 
15664       if( bVirtual ){
15665         zSql = (const char*)(zFree = recoverMPrintf(p,
15666             "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
15667             zName, zName, zSql
15668         ));
15669       }
15670       rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
15671       if( rc==SQLITE_OK ){
15672         recoverSqlCallback(p, zSql);
15673         if( bTable && !bVirtual ){
15674           if( SQLITE_ROW==sqlite3_step(pTblname) ){
15675             const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
15676             recoverAddTable(p, zTbl, iRoot);
15677           }
15678           recoverReset(p, pTblname);
15679         }
15680       }else if( rc!=SQLITE_ERROR ){
15681         recoverDbError(p, p->dbOut);
15682       }
15683       sqlite3_free(zFree);
15684     }
15685   }
15686   recoverFinalize(p, pSelect);
15687   recoverFinalize(p, pTblname);
15688 
15689   return p->errCode;
15690 }
15691 
15692 /*
15693 ** This function is called after the output database has been populated. It
15694 ** adds all recovered schema elements that were not created in the output
15695 ** database by recoverWriteSchema1() - everything except for tables and
15696 ** UNIQUE indexes. Specifically:
15697 **
15698 **     * views,
15699 **     * triggers,
15700 **     * non-UNIQUE indexes.
15701 **
15702 ** If the recover handle is in SQL callback mode, then equivalent callbacks
15703 ** are issued to create the schema elements.
15704 */
15705 static int recoverWriteSchema2(sqlite3_recover *p){
15706   sqlite3_stmt *pSelect = 0;
15707 
15708   pSelect = recoverPrepare(p, p->dbOut,
15709       p->bSlowIndexes ?
15710       "SELECT rootpage, sql FROM recovery.schema "
15711       "  WHERE type!='table' AND type!='index'"
15712       :
15713       "SELECT rootpage, sql FROM recovery.schema "
15714       "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
15715   );
15716 
15717   if( pSelect ){
15718     while( sqlite3_step(pSelect)==SQLITE_ROW ){
15719       const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
15720       int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
15721       if( rc==SQLITE_OK ){
15722         recoverSqlCallback(p, zSql);
15723       }else if( rc!=SQLITE_ERROR ){
15724         recoverDbError(p, p->dbOut);
15725       }
15726     }
15727   }
15728   recoverFinalize(p, pSelect);
15729 
15730   return p->errCode;
15731 }
15732 
15733 /*
15734 ** This function is a no-op if recover handle p already contains an error
15735 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
15736 **
15737 ** Otherwise, if the recover handle is configured to create an output
15738 ** database (was created by sqlite3_recover_init()), then this function
15739 ** prepares and returns an SQL statement to INSERT a new record into table
15740 ** pTab, assuming the first nField fields of a record extracted from disk
15741 ** are valid.
15742 **
15743 ** For example, if table pTab is:
15744 **
15745 **     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
15746 **
15747 ** And nField is 4, then the SQL statement prepared and returned is:
15748 **
15749 **     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
15750 **
15751 ** In this case even though 4 values were extracted from the input db,
15752 ** only 3 are written to the output, as the generated STORED column
15753 ** cannot be written.
15754 **
15755 ** If the recover handle is in SQL callback mode, then the SQL statement
15756 ** prepared is such that evaluating it returns a single row containing
15757 ** a single text value - itself an SQL statement similar to the above,
15758 ** except with SQL literals in place of the variables. For example:
15759 **
15760 **     SELECT 'INSERT INTO (a, c, d) VALUES ('
15761 **          || quote(?1) || ', '
15762 **          || quote(?2) || ', '
15763 **          || quote(?3) || ')';
15764 **
15765 ** In either case, it is the responsibility of the caller to eventually
15766 ** free the statement handle using sqlite3_finalize().
15767 */
15768 static sqlite3_stmt *recoverInsertStmt(
15769   sqlite3_recover *p,
15770   RecoverTable *pTab,
15771   int nField
15772 ){
15773   sqlite3_stmt *pRet = 0;
15774   const char *zSep = "";
15775   const char *zSqlSep = "";
15776   char *zSql = 0;
15777   char *zFinal = 0;
15778   char *zBind = 0;
15779   int ii;
15780   int bSql = p->xSql ? 1 : 0;
15781 
15782   if( nField<=0 ) return 0;
15783 
15784   assert( nField<=pTab->nCol );
15785 
15786   zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
15787 
15788   if( pTab->iRowidBind ){
15789     assert( pTab->bIntkey );
15790     zSql = recoverMPrintf(p, "%z_rowid_", zSql);
15791     if( bSql ){
15792       zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
15793     }else{
15794       zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
15795     }
15796     zSqlSep = "||', '||";
15797     zSep = ", ";
15798   }
15799 
15800   for(ii=0; ii<nField; ii++){
15801     int eHidden = pTab->aCol[ii].eHidden;
15802     if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
15803      && eHidden!=RECOVER_EHIDDEN_STORED
15804     ){
15805       assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
15806       zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
15807 
15808       if( bSql ){
15809         zBind = recoverMPrintf(p,
15810             "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
15811         );
15812         zSqlSep = "||', '||";
15813       }else{
15814         zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
15815       }
15816       zSep = ", ";
15817     }
15818   }
15819 
15820   if( bSql ){
15821     zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
15822         zSql, zBind
15823     );
15824   }else{
15825     zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
15826   }
15827 
15828   pRet = recoverPrepare(p, p->dbOut, zFinal);
15829   sqlite3_free(zSql);
15830   sqlite3_free(zBind);
15831   sqlite3_free(zFinal);
15832 
15833   return pRet;
15834 }
15835 
15836 
15837 /*
15838 ** Search the list of RecoverTable objects at p->pTblList for one that
15839 ** has root page iRoot in the input database. If such an object is found,
15840 ** return a pointer to it. Otherwise, return NULL.
15841 */
15842 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
15843   RecoverTable *pRet = 0;
15844   for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
15845   return pRet;
15846 }
15847 
15848 /*
15849 ** This function attempts to create a lost and found table within the
15850 ** output db. If successful, it returns a pointer to a buffer containing
15851 ** the name of the new table. It is the responsibility of the caller to
15852 ** eventually free this buffer using sqlite3_free().
15853 **
15854 ** If an error occurs, NULL is returned and an error code and error
15855 ** message left in the recover handle.
15856 */
15857 static char *recoverLostAndFoundCreate(
15858   sqlite3_recover *p,             /* Recover object */
15859   int nField                      /* Number of column fields in new table */
15860 ){
15861   char *zTbl = 0;
15862   sqlite3_stmt *pProbe = 0;
15863   int ii = 0;
15864 
15865   pProbe = recoverPrepare(p, p->dbOut,
15866     "SELECT 1 FROM sqlite_schema WHERE name=?"
15867   );
15868   for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
15869     int bFail = 0;
15870     if( ii<0 ){
15871       zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
15872     }else{
15873       zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
15874     }
15875 
15876     if( p->errCode==SQLITE_OK ){
15877       sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
15878       if( SQLITE_ROW==sqlite3_step(pProbe) ){
15879         bFail = 1;
15880       }
15881       recoverReset(p, pProbe);
15882     }
15883 
15884     if( bFail ){
15885       sqlite3_clear_bindings(pProbe);
15886       sqlite3_free(zTbl);
15887       zTbl = 0;
15888     }
15889   }
15890   recoverFinalize(p, pProbe);
15891 
15892   if( zTbl ){
15893     const char *zSep = 0;
15894     char *zField = 0;
15895     char *zSql = 0;
15896 
15897     zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
15898     for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
15899       zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
15900       zSep = ", ";
15901     }
15902 
15903     zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
15904     sqlite3_free(zField);
15905 
15906     recoverExec(p, p->dbOut, zSql);
15907     recoverSqlCallback(p, zSql);
15908     sqlite3_free(zSql);
15909   }else if( p->errCode==SQLITE_OK ){
15910     recoverError(
15911         p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
15912     );
15913   }
15914 
15915   return zTbl;
15916 }
15917 
15918 /*
15919 ** Synthesize and prepare an INSERT statement to write to the lost_and_found
15920 ** table in the output database. The name of the table is zTab, and it has
15921 ** nField c* fields.
15922 */
15923 static sqlite3_stmt *recoverLostAndFoundInsert(
15924   sqlite3_recover *p,
15925   const char *zTab,
15926   int nField
15927 ){
15928   int nTotal = nField + 4;
15929   int ii;
15930   char *zBind = 0;
15931   sqlite3_stmt *pRet = 0;
15932 
15933   if( p->xSql==0 ){
15934     for(ii=0; ii<nTotal; ii++){
15935       zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
15936     }
15937     pRet = recoverPreparePrintf(
15938         p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
15939     );
15940   }else{
15941     const char *zSep = "";
15942     for(ii=0; ii<nTotal; ii++){
15943       zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
15944       zSep = "|| ', ' ||";
15945     }
15946     pRet = recoverPreparePrintf(
15947         p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
15948     );
15949   }
15950 
15951   sqlite3_free(zBind);
15952   return pRet;
15953 }
15954 
15955 /*
15956 ** Input database page iPg contains data that will be written to the
15957 ** lost-and-found table of the output database. This function attempts
15958 ** to identify the root page of the tree that page iPg belonged to.
15959 ** If successful, it sets output variable (*piRoot) to the page number
15960 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
15961 ** an SQLite error code is returned and the final value of *piRoot
15962 ** undefined.
15963 */
15964 static int recoverLostAndFoundFindRoot(
15965   sqlite3_recover *p,
15966   i64 iPg,
15967   i64 *piRoot
15968 ){
15969   RecoverStateLAF *pLaf = &p->laf;
15970 
15971   if( pLaf->pFindRoot==0 ){
15972     pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
15973         "WITH RECURSIVE p(pgno) AS ("
15974         "  SELECT ?"
15975         "    UNION"
15976         "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
15977         ") "
15978         "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
15979         "    AND m.parent IS NULL"
15980     );
15981   }
15982   if( p->errCode==SQLITE_OK ){
15983     sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
15984     if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
15985       *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
15986     }else{
15987       *piRoot = iPg;
15988     }
15989     recoverReset(p, pLaf->pFindRoot);
15990   }
15991   return p->errCode;
15992 }
15993 
15994 /*
15995 ** Recover data from page iPage of the input database and write it to
15996 ** the lost-and-found table in the output database.
15997 */
15998 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
15999   RecoverStateLAF *pLaf = &p->laf;
16000   sqlite3_value **apVal = pLaf->apVal;
16001   sqlite3_stmt *pPageData = pLaf->pPageData;
16002   sqlite3_stmt *pInsert = pLaf->pInsert;
16003 
16004   int nVal = -1;
16005   int iPrevCell = 0;
16006   i64 iRoot = 0;
16007   int bHaveRowid = 0;
16008   i64 iRowid = 0;
16009   int ii = 0;
16010 
16011   if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
16012   sqlite3_bind_int64(pPageData, 1, iPage);
16013   while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
16014     int iCell = sqlite3_column_int64(pPageData, 0);
16015     int iField = sqlite3_column_int64(pPageData, 1);
16016 
16017     if( iPrevCell!=iCell && nVal>=0 ){
16018       /* Insert the new row */
16019       sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
16020       sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
16021       sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
16022       if( bHaveRowid ){
16023         sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
16024       }
16025       for(ii=0; ii<nVal; ii++){
16026         recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
16027       }
16028       if( sqlite3_step(pInsert)==SQLITE_ROW ){
16029         recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
16030       }
16031       recoverReset(p, pInsert);
16032 
16033       /* Discard the accumulated row data */
16034       for(ii=0; ii<nVal; ii++){
16035         sqlite3_value_free(apVal[ii]);
16036         apVal[ii] = 0;
16037       }
16038       sqlite3_clear_bindings(pInsert);
16039       bHaveRowid = 0;
16040       nVal = -1;
16041     }
16042 
16043     if( iCell<0 ) break;
16044 
16045     if( iField<0 ){
16046       assert( nVal==-1 );
16047       iRowid = sqlite3_column_int64(pPageData, 2);
16048       bHaveRowid = 1;
16049       nVal = 0;
16050     }else if( iField<pLaf->nMaxField ){
16051       sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
16052       apVal[iField] = sqlite3_value_dup(pVal);
16053       assert( iField==nVal || (nVal==-1 && iField==0) );
16054       nVal = iField+1;
16055       if( apVal[iField]==0 ){
16056         recoverError(p, SQLITE_NOMEM, 0);
16057       }
16058     }
16059 
16060     iPrevCell = iCell;
16061   }
16062   recoverReset(p, pPageData);
16063 
16064   for(ii=0; ii<nVal; ii++){
16065     sqlite3_value_free(apVal[ii]);
16066     apVal[ii] = 0;
16067   }
16068 }
16069 
16070 /*
16071 ** Perform one step (sqlite3_recover_step()) of work for the connection
16072 ** passed as the only argument, which is guaranteed to be in
16073 ** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
16074 ** table of the output database is populated with recovered data that can
16075 ** not be assigned to any recovered schema object.
16076 */
16077 static int recoverLostAndFound3Step(sqlite3_recover *p){
16078   RecoverStateLAF *pLaf = &p->laf;
16079   if( p->errCode==SQLITE_OK ){
16080     if( pLaf->pInsert==0 ){
16081       return SQLITE_DONE;
16082     }else{
16083       if( p->errCode==SQLITE_OK ){
16084         int res = sqlite3_step(pLaf->pAllPage);
16085         if( res==SQLITE_ROW ){
16086           i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
16087           if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
16088             recoverLostAndFoundOnePage(p, iPage);
16089           }
16090         }else{
16091           recoverReset(p, pLaf->pAllPage);
16092           return SQLITE_DONE;
16093         }
16094       }
16095     }
16096   }
16097   return SQLITE_OK;
16098 }
16099 
16100 /*
16101 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
16102 ** state - during which the lost-and-found table of the output database
16103 ** is populated with recovered data that can not be assigned to any
16104 ** recovered schema object.
16105 */
16106 static void recoverLostAndFound3Init(sqlite3_recover *p){
16107   RecoverStateLAF *pLaf = &p->laf;
16108 
16109   if( pLaf->nMaxField>0 ){
16110     char *zTab = 0;               /* Name of lost_and_found table */
16111 
16112     zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
16113     pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
16114     sqlite3_free(zTab);
16115 
16116     pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
16117         "WITH RECURSIVE seq(ii) AS ("
16118         "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
16119         ")"
16120         "SELECT ii FROM seq" , p->laf.nPg
16121     );
16122     pLaf->pPageData = recoverPrepare(p, p->dbOut,
16123         "SELECT cell, field, value "
16124         "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
16125         "UNION ALL "
16126         "SELECT -1, -1, -1"
16127     );
16128 
16129     pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
16130         pLaf->nMaxField*sizeof(sqlite3_value*)
16131     );
16132   }
16133 }
16134 
16135 /*
16136 ** Initialize resources required in RECOVER_STATE_WRITING state - during which
16137 ** tables recovered from the schema of the input database are populated with
16138 ** recovered data.
16139 */
16140 static int recoverWriteDataInit(sqlite3_recover *p){
16141   RecoverStateW1 *p1 = &p->w1;
16142   RecoverTable *pTbl = 0;
16143   int nByte = 0;
16144 
16145   /* Figure out the maximum number of columns for any table in the schema */
16146   assert( p1->nMax==0 );
16147   for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
16148     if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
16149   }
16150 
16151   /* Allocate an array of (sqlite3_value*) in which to accumulate the values
16152   ** that will be written to the output database in a single row. */
16153   nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
16154   p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
16155   if( p1->apVal==0 ) return p->errCode;
16156 
16157   /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
16158   ** to loop through cells that appear to belong to a single table (pSel). */
16159   p1->pTbls = recoverPrepare(p, p->dbOut,
16160       "SELECT rootpage FROM recovery.schema "
16161       "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
16162       "  ORDER BY (tbl_name='sqlite_sequence') ASC"
16163   );
16164   p1->pSel = recoverPrepare(p, p->dbOut,
16165       "WITH RECURSIVE pages(page) AS ("
16166       "  SELECT ?1"
16167       "    UNION"
16168       "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
16169       "    WHERE pgno=page"
16170       ") "
16171       "SELECT page, cell, field, value "
16172       "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
16173       "UNION ALL "
16174       "SELECT 0, 0, 0, 0"
16175   );
16176 
16177   return p->errCode;
16178 }
16179 
16180 /*
16181 ** Clean up resources allocated by recoverWriteDataInit() (stuff in
16182 ** sqlite3_recover.w1).
16183 */
16184 static void recoverWriteDataCleanup(sqlite3_recover *p){
16185   RecoverStateW1 *p1 = &p->w1;
16186   int ii;
16187   for(ii=0; ii<p1->nVal; ii++){
16188     sqlite3_value_free(p1->apVal[ii]);
16189   }
16190   sqlite3_free(p1->apVal);
16191   recoverFinalize(p, p1->pInsert);
16192   recoverFinalize(p, p1->pTbls);
16193   recoverFinalize(p, p1->pSel);
16194   memset(p1, 0, sizeof(*p1));
16195 }
16196 
16197 /*
16198 ** Perform one step (sqlite3_recover_step()) of work for the connection
16199 ** passed as the only argument, which is guaranteed to be in
16200 ** RECOVER_STATE_WRITING state - during which tables recovered from the
16201 ** schema of the input database are populated with recovered data.
16202 */
16203 static int recoverWriteDataStep(sqlite3_recover *p){
16204   RecoverStateW1 *p1 = &p->w1;
16205   sqlite3_stmt *pSel = p1->pSel;
16206   sqlite3_value **apVal = p1->apVal;
16207 
16208   if( p->errCode==SQLITE_OK && p1->pTab==0 ){
16209     if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
16210       i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
16211       p1->pTab = recoverFindTable(p, iRoot);
16212 
16213       recoverFinalize(p, p1->pInsert);
16214       p1->pInsert = 0;
16215 
16216       /* If this table is unknown, return early. The caller will invoke this
16217       ** function again and it will move on to the next table.  */
16218       if( p1->pTab==0 ) return p->errCode;
16219 
16220       /* If this is the sqlite_sequence table, delete any rows added by
16221       ** earlier INSERT statements on tables with AUTOINCREMENT primary
16222       ** keys before recovering its contents. The p1->pTbls SELECT statement
16223       ** is rigged to deliver "sqlite_sequence" last of all, so we don't
16224       ** worry about it being modified after it is recovered. */
16225       if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
16226         recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
16227         recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
16228       }
16229 
16230       /* Bind the root page of this table within the original database to
16231       ** SELECT statement p1->pSel. The SELECT statement will then iterate
16232       ** through cells that look like they belong to table pTab.  */
16233       sqlite3_bind_int64(pSel, 1, iRoot);
16234 
16235       p1->nVal = 0;
16236       p1->bHaveRowid = 0;
16237       p1->iPrevPage = -1;
16238       p1->iPrevCell = -1;
16239     }else{
16240       return SQLITE_DONE;
16241     }
16242   }
16243   assert( p->errCode!=SQLITE_OK || p1->pTab );
16244 
16245   if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
16246     RecoverTable *pTab = p1->pTab;
16247 
16248     i64 iPage = sqlite3_column_int64(pSel, 0);
16249     int iCell = sqlite3_column_int(pSel, 1);
16250     int iField = sqlite3_column_int(pSel, 2);
16251     sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
16252     int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
16253 
16254     assert( bNewCell==0 || (iField==-1 || iField==0) );
16255     assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
16256 
16257     if( bNewCell ){
16258       int ii = 0;
16259       if( p1->nVal>=0 ){
16260         if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
16261           recoverFinalize(p, p1->pInsert);
16262           p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
16263           p1->nInsert = p1->nVal;
16264         }
16265         if( p1->nVal>0 ){
16266           sqlite3_stmt *pInsert = p1->pInsert;
16267           for(ii=0; ii<pTab->nCol; ii++){
16268             RecoverColumn *pCol = &pTab->aCol[ii];
16269             int iBind = pCol->iBind;
16270             if( iBind>0 ){
16271               if( pCol->bIPK ){
16272                 sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
16273               }else if( pCol->iField<p1->nVal ){
16274                 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
16275               }
16276             }
16277           }
16278           if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
16279             sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
16280           }
16281           if( SQLITE_ROW==sqlite3_step(pInsert) ){
16282             const char *z = (const char*)sqlite3_column_text(pInsert, 0);
16283             recoverSqlCallback(p, z);
16284           }
16285           recoverReset(p, pInsert);
16286           assert( p->errCode || pInsert );
16287           if( pInsert ) sqlite3_clear_bindings(pInsert);
16288         }
16289       }
16290 
16291       for(ii=0; ii<p1->nVal; ii++){
16292         sqlite3_value_free(apVal[ii]);
16293         apVal[ii] = 0;
16294       }
16295       p1->nVal = -1;
16296       p1->bHaveRowid = 0;
16297     }
16298 
16299     if( iPage!=0 ){
16300       if( iField<0 ){
16301         p1->iRowid = sqlite3_column_int64(pSel, 3);
16302         assert( p1->nVal==-1 );
16303         p1->nVal = 0;
16304         p1->bHaveRowid = 1;
16305       }else if( iField<pTab->nCol ){
16306         assert( apVal[iField]==0 );
16307         apVal[iField] = sqlite3_value_dup( pVal );
16308         if( apVal[iField]==0 ){
16309           recoverError(p, SQLITE_NOMEM, 0);
16310         }
16311         p1->nVal = iField+1;
16312       }
16313       p1->iPrevCell = iCell;
16314       p1->iPrevPage = iPage;
16315     }
16316   }else{
16317     recoverReset(p, pSel);
16318     p1->pTab = 0;
16319   }
16320 
16321   return p->errCode;
16322 }
16323 
16324 /*
16325 ** Initialize resources required by sqlite3_recover_step() in
16326 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
16327 ** already allocated to a recovered schema element is determined.
16328 */
16329 static void recoverLostAndFound1Init(sqlite3_recover *p){
16330   RecoverStateLAF *pLaf = &p->laf;
16331   sqlite3_stmt *pStmt = 0;
16332 
16333   assert( p->laf.pUsed==0 );
16334   pLaf->nPg = recoverPageCount(p);
16335   pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
16336 
16337   /* Prepare a statement to iterate through all pages that are part of any tree
16338   ** in the recoverable part of the input database schema to the bitmap. And,
16339   ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
16340   ** freelist.  */
16341   pStmt = recoverPrepare(
16342       p, p->dbOut,
16343       "WITH trunk(pgno) AS ("
16344       "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
16345       "    UNION"
16346       "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
16347       "),"
16348       "trunkdata(pgno, data) AS ("
16349       "  SELECT pgno, getpage(pgno) FROM trunk"
16350       "),"
16351       "freelist(data, n, freepgno) AS ("
16352       "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
16353       "    UNION ALL"
16354       "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
16355       "),"
16356       ""
16357       "roots(r) AS ("
16358       "  SELECT 1 UNION ALL"
16359       "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
16360       "),"
16361       "used(page) AS ("
16362       "  SELECT r FROM roots"
16363       "    UNION"
16364       "  SELECT child FROM sqlite_dbptr('getpage()'), used "
16365       "    WHERE pgno=page"
16366       ") "
16367       "SELECT page FROM used"
16368       " UNION ALL "
16369       "SELECT freepgno FROM freelist WHERE NOT ?"
16370   );
16371   if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
16372   pLaf->pUsedPages = pStmt;
16373 }
16374 
16375 /*
16376 ** Perform one step (sqlite3_recover_step()) of work for the connection
16377 ** passed as the only argument, which is guaranteed to be in
16378 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
16379 ** already allocated to a recovered schema element is determined.
16380 */
16381 static int recoverLostAndFound1Step(sqlite3_recover *p){
16382   RecoverStateLAF *pLaf = &p->laf;
16383   int rc = p->errCode;
16384   if( rc==SQLITE_OK ){
16385     rc = sqlite3_step(pLaf->pUsedPages);
16386     if( rc==SQLITE_ROW ){
16387       i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
16388       recoverBitmapSet(pLaf->pUsed, iPg);
16389       rc = SQLITE_OK;
16390     }else{
16391       recoverFinalize(p, pLaf->pUsedPages);
16392       pLaf->pUsedPages = 0;
16393     }
16394   }
16395   return rc;
16396 }
16397 
16398 /*
16399 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
16400 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
16401 ** are sorted into sets that likely belonged to the same database tree.
16402 */
16403 static void recoverLostAndFound2Init(sqlite3_recover *p){
16404   RecoverStateLAF *pLaf = &p->laf;
16405 
16406   assert( p->laf.pAllAndParent==0 );
16407   assert( p->laf.pMapInsert==0 );
16408   assert( p->laf.pMaxField==0 );
16409   assert( p->laf.nMaxField==0 );
16410 
16411   pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
16412       "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
16413   );
16414   pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
16415       "WITH RECURSIVE seq(ii) AS ("
16416       "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
16417       ")"
16418       "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
16419       " UNION ALL "
16420       "SELECT NULL, ii FROM seq", p->laf.nPg
16421   );
16422   pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
16423       "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
16424   );
16425 }
16426 
16427 /*
16428 ** Perform one step (sqlite3_recover_step()) of work for the connection
16429 ** passed as the only argument, which is guaranteed to be in
16430 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
16431 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
16432 ** to the same database tree.
16433 */
16434 static int recoverLostAndFound2Step(sqlite3_recover *p){
16435   RecoverStateLAF *pLaf = &p->laf;
16436   if( p->errCode==SQLITE_OK ){
16437     int res = sqlite3_step(pLaf->pAllAndParent);
16438     if( res==SQLITE_ROW ){
16439       i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
16440       if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
16441         sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
16442         sqlite3_bind_value(pLaf->pMapInsert, 2,
16443             sqlite3_column_value(pLaf->pAllAndParent, 0)
16444         );
16445         sqlite3_step(pLaf->pMapInsert);
16446         recoverReset(p, pLaf->pMapInsert);
16447         sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
16448         if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
16449           int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
16450           if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
16451         }
16452         recoverReset(p, pLaf->pMaxField);
16453       }
16454     }else{
16455       recoverFinalize(p, pLaf->pAllAndParent);
16456       pLaf->pAllAndParent =0;
16457       return SQLITE_DONE;
16458     }
16459   }
16460   return p->errCode;
16461 }
16462 
16463 /*
16464 ** Free all resources allocated as part of sqlite3_recover_step() calls
16465 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
16466 */
16467 static void recoverLostAndFoundCleanup(sqlite3_recover *p){
16468   recoverBitmapFree(p->laf.pUsed);
16469   p->laf.pUsed = 0;
16470   sqlite3_finalize(p->laf.pUsedPages);
16471   sqlite3_finalize(p->laf.pAllAndParent);
16472   sqlite3_finalize(p->laf.pMapInsert);
16473   sqlite3_finalize(p->laf.pMaxField);
16474   sqlite3_finalize(p->laf.pFindRoot);
16475   sqlite3_finalize(p->laf.pInsert);
16476   sqlite3_finalize(p->laf.pAllPage);
16477   sqlite3_finalize(p->laf.pPageData);
16478   p->laf.pUsedPages = 0;
16479   p->laf.pAllAndParent = 0;
16480   p->laf.pMapInsert = 0;
16481   p->laf.pMaxField = 0;
16482   p->laf.pFindRoot = 0;
16483   p->laf.pInsert = 0;
16484   p->laf.pAllPage = 0;
16485   p->laf.pPageData = 0;
16486   sqlite3_free(p->laf.apVal);
16487   p->laf.apVal = 0;
16488 }
16489 
16490 /*
16491 ** Free all resources allocated as part of sqlite3_recover_step() calls.
16492 */
16493 static void recoverFinalCleanup(sqlite3_recover *p){
16494   RecoverTable *pTab = 0;
16495   RecoverTable *pNext = 0;
16496 
16497   recoverWriteDataCleanup(p);
16498   recoverLostAndFoundCleanup(p);
16499 
16500   for(pTab=p->pTblList; pTab; pTab=pNext){
16501     pNext = pTab->pNext;
16502     sqlite3_free(pTab);
16503   }
16504   p->pTblList = 0;
16505   sqlite3_finalize(p->pGetPage);
16506   p->pGetPage = 0;
16507   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
16508 
16509   {
16510 #ifndef NDEBUG
16511     int res =
16512 #endif
16513        sqlite3_close(p->dbOut);
16514     assert( res==SQLITE_OK );
16515   }
16516   p->dbOut = 0;
16517 }
16518 
16519 /*
16520 ** Decode and return an unsigned 16-bit big-endian integer value from
16521 ** buffer a[].
16522 */
16523 static u32 recoverGetU16(const u8 *a){
16524   return (((u32)a[0])<<8) + ((u32)a[1]);
16525 }
16526 
16527 /*
16528 ** Decode and return an unsigned 32-bit big-endian integer value from
16529 ** buffer a[].
16530 */
16531 static u32 recoverGetU32(const u8 *a){
16532   return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
16533 }
16534 
16535 /*
16536 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
16537 ** and return the number of bytes consumed.
16538 */
16539 static int recoverGetVarint(const u8 *a, i64 *pVal){
16540   sqlite3_uint64 u = 0;
16541   int i;
16542   for(i=0; i<8; i++){
16543     u = (u<<7) + (a[i]&0x7f);
16544     if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
16545   }
16546   u = (u<<8) + (a[i]&0xff);
16547   *pVal = (sqlite3_int64)u;
16548   return 9;
16549 }
16550 
16551 /*
16552 ** The second argument points to a buffer n bytes in size. If this buffer
16553 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
16554 ** return the page-size in bytes. Otherwise, if the buffer does not
16555 ** appear to contain a well-formed b-tree page, return 0.
16556 */
16557 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
16558   u8 *aUsed = aTmp;
16559   int nFrag = 0;
16560   int nActual = 0;
16561   int iFree = 0;
16562   int nCell = 0;                  /* Number of cells on page */
16563   int iCellOff = 0;               /* Offset of cell array in page */
16564   int iContent = 0;
16565   int eType = 0;
16566   int ii = 0;
16567 
16568   eType = (int)a[0];
16569   if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
16570 
16571   iFree = (int)recoverGetU16(&a[1]);
16572   nCell = (int)recoverGetU16(&a[3]);
16573   iContent = (int)recoverGetU16(&a[5]);
16574   if( iContent==0 ) iContent = 65536;
16575   nFrag = (int)a[7];
16576 
16577   if( iContent>n ) return 0;
16578 
16579   memset(aUsed, 0, n);
16580   memset(aUsed, 0xFF, iContent);
16581 
16582   /* Follow the free-list. This is the same format for all b-tree pages. */
16583   if( iFree && iFree<=iContent ) return 0;
16584   while( iFree ){
16585     int iNext = 0;
16586     int nByte = 0;
16587     if( iFree>(n-4) ) return 0;
16588     iNext = recoverGetU16(&a[iFree]);
16589     nByte = recoverGetU16(&a[iFree+2]);
16590     if( iFree+nByte>n || nByte<4 ) return 0;
16591     if( iNext && iNext<iFree+nByte ) return 0;
16592     memset(&aUsed[iFree], 0xFF, nByte);
16593     iFree = iNext;
16594   }
16595 
16596   /* Run through the cells */
16597   if( eType==0x02 || eType==0x05 ){
16598     iCellOff = 12;
16599   }else{
16600     iCellOff = 8;
16601   }
16602   if( (iCellOff + 2*nCell)>iContent ) return 0;
16603   for(ii=0; ii<nCell; ii++){
16604     int iByte;
16605     i64 nPayload = 0;
16606     int nByte = 0;
16607     int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
16608     if( iOff<iContent || iOff>n ){
16609       return 0;
16610     }
16611     if( eType==0x05 || eType==0x02 ) nByte += 4;
16612     nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
16613     if( eType==0x0D ){
16614       i64 dummy = 0;
16615       nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
16616     }
16617     if( eType!=0x05 ){
16618       int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
16619       int M = ((n-12)*32/255)-23;
16620       int K = M+((nPayload-M)%(n-4));
16621 
16622       if( nPayload<X ){
16623         nByte += nPayload;
16624       }else if( K<=X ){
16625         nByte += K+4;
16626       }else{
16627         nByte += M+4;
16628       }
16629     }
16630 
16631     if( iOff+nByte>n ){
16632       return 0;
16633     }
16634     for(iByte=iOff; iByte<(iOff+nByte); iByte++){
16635       if( aUsed[iByte]!=0 ){
16636         return 0;
16637       }
16638       aUsed[iByte] = 0xFF;
16639     }
16640   }
16641 
16642   nActual = 0;
16643   for(ii=0; ii<n; ii++){
16644     if( aUsed[ii]==0 ) nActual++;
16645   }
16646   return (nActual==nFrag);
16647 }
16648 
16649 
16650 static int recoverVfsClose(sqlite3_file*);
16651 static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
16652 static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
16653 static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
16654 static int recoverVfsSync(sqlite3_file*, int flags);
16655 static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
16656 static int recoverVfsLock(sqlite3_file*, int);
16657 static int recoverVfsUnlock(sqlite3_file*, int);
16658 static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
16659 static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
16660 static int recoverVfsSectorSize(sqlite3_file*);
16661 static int recoverVfsDeviceCharacteristics(sqlite3_file*);
16662 static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
16663 static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
16664 static void recoverVfsShmBarrier(sqlite3_file*);
16665 static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
16666 static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
16667 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
16668 
16669 static sqlite3_io_methods recover_methods = {
16670   2, /* iVersion */
16671   recoverVfsClose,
16672   recoverVfsRead,
16673   recoverVfsWrite,
16674   recoverVfsTruncate,
16675   recoverVfsSync,
16676   recoverVfsFileSize,
16677   recoverVfsLock,
16678   recoverVfsUnlock,
16679   recoverVfsCheckReservedLock,
16680   recoverVfsFileControl,
16681   recoverVfsSectorSize,
16682   recoverVfsDeviceCharacteristics,
16683   recoverVfsShmMap,
16684   recoverVfsShmLock,
16685   recoverVfsShmBarrier,
16686   recoverVfsShmUnmap,
16687   recoverVfsFetch,
16688   recoverVfsUnfetch
16689 };
16690 
16691 static int recoverVfsClose(sqlite3_file *pFd){
16692   assert( pFd->pMethods!=&recover_methods );
16693   return pFd->pMethods->xClose(pFd);
16694 }
16695 
16696 /*
16697 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
16698 */
16699 static void recoverPutU16(u8 *a, u32 v){
16700   a[0] = (v>>8) & 0x00FF;
16701   a[1] = (v>>0) & 0x00FF;
16702 }
16703 
16704 /*
16705 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
16706 */
16707 static void recoverPutU32(u8 *a, u32 v){
16708   a[0] = (v>>24) & 0x00FF;
16709   a[1] = (v>>16) & 0x00FF;
16710   a[2] = (v>>8) & 0x00FF;
16711   a[3] = (v>>0) & 0x00FF;
16712 }
16713 
16714 /*
16715 ** Detect the page-size of the database opened by file-handle pFd by
16716 ** searching the first part of the file for a well-formed SQLite b-tree
16717 ** page. If parameter nReserve is non-zero, then as well as searching for
16718 ** a b-tree page with zero reserved bytes, this function searches for one
16719 ** with nReserve reserved bytes at the end of it.
16720 **
16721 ** If successful, set variable p->detected_pgsz to the detected page-size
16722 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
16723 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
16724 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
16725 ** is returned. The final value of p->detected_pgsz is undefined in this
16726 ** case.
16727 */
16728 static int recoverVfsDetectPagesize(
16729   sqlite3_recover *p,             /* Recover handle */
16730   sqlite3_file *pFd,              /* File-handle open on input database */
16731   u32 nReserve,                   /* Possible nReserve value */
16732   i64 nSz                         /* Size of database file in bytes */
16733 ){
16734   int rc = SQLITE_OK;
16735   const int nMin = 512;
16736   const int nMax = 65536;
16737   const int nMaxBlk = 4;
16738   u32 pgsz = 0;
16739   int iBlk = 0;
16740   u8 *aPg = 0;
16741   u8 *aTmp = 0;
16742   int nBlk = 0;
16743 
16744   aPg = (u8*)sqlite3_malloc(2*nMax);
16745   if( aPg==0 ) return SQLITE_NOMEM;
16746   aTmp = &aPg[nMax];
16747 
16748   nBlk = (nSz+nMax-1)/nMax;
16749   if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
16750 
16751   do {
16752     for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
16753       int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
16754       memset(aPg, 0, nMax);
16755       rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
16756       if( rc==SQLITE_OK ){
16757         int pgsz2;
16758         for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
16759           int iOff;
16760           for(iOff=0; iOff<nMax; iOff+=pgsz2){
16761             if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
16762               pgsz = pgsz2;
16763               break;
16764             }
16765           }
16766         }
16767       }
16768     }
16769     if( pgsz>(u32)p->detected_pgsz ){
16770       p->detected_pgsz = pgsz;
16771       p->nReserve = nReserve;
16772     }
16773     if( nReserve==0 ) break;
16774     nReserve = 0;
16775   }while( 1 );
16776 
16777   p->detected_pgsz = pgsz;
16778   sqlite3_free(aPg);
16779   return rc;
16780 }
16781 
16782 /*
16783 ** The xRead() method of the wrapper VFS. This is used to intercept calls
16784 ** to read page 1 of the input database.
16785 */
16786 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
16787   int rc = SQLITE_OK;
16788   if( pFd->pMethods==&recover_methods ){
16789     pFd->pMethods = recover_g.pMethods;
16790     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
16791     if( nByte==16 ){
16792       sqlite3_randomness(16, aBuf);
16793     }else
16794     if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
16795       /* Ensure that the database has a valid header file. The only fields
16796       ** that really matter to recovery are:
16797       **
16798       **   + Database page size (16-bits at offset 16)
16799       **   + Size of db in pages (32-bits at offset 28)
16800       **   + Database encoding (32-bits at offset 56)
16801       **
16802       ** Also preserved are:
16803       **
16804       **   + first freelist page (32-bits at offset 32)
16805       **   + size of freelist (32-bits at offset 36)
16806       **   + the wal-mode flags (16-bits at offset 18)
16807       **
16808       ** We also try to preserve the auto-vacuum, incr-value, user-version
16809       ** and application-id fields - all 32 bit quantities at offsets
16810       ** 52, 60, 64 and 68. All other fields are set to known good values.
16811       **
16812       ** Byte offset 105 should also contain the page-size as a 16-bit
16813       ** integer.
16814       */
16815       const int aPreserve[] = {32, 36, 52, 60, 64, 68};
16816       u8 aHdr[108] = {
16817         0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
16818         0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
16819         0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
16820         0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
16821         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
16822         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
16823         0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
16824         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
16825         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
16826         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
16827         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
16828         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
16829         0x00, 0x2e, 0x5b, 0x30,
16830 
16831         0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
16832       };
16833       u8 *a = (u8*)aBuf;
16834 
16835       u32 pgsz = recoverGetU16(&a[16]);
16836       u32 nReserve = a[20];
16837       u32 enc = recoverGetU32(&a[56]);
16838       u32 dbsz = 0;
16839       i64 dbFileSize = 0;
16840       int ii;
16841       sqlite3_recover *p = recover_g.p;
16842 
16843       if( pgsz==0x01 ) pgsz = 65536;
16844       rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
16845 
16846       if( rc==SQLITE_OK && p->detected_pgsz==0 ){
16847         rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
16848       }
16849       if( p->detected_pgsz ){
16850         pgsz = p->detected_pgsz;
16851         nReserve = p->nReserve;
16852       }
16853 
16854       if( pgsz ){
16855         dbsz = dbFileSize / pgsz;
16856       }
16857       if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
16858         enc = SQLITE_UTF8;
16859       }
16860 
16861       sqlite3_free(p->pPage1Cache);
16862       p->pPage1Cache = 0;
16863       p->pPage1Disk = 0;
16864 
16865       p->pgsz = nByte;
16866       p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
16867       if( p->pPage1Cache ){
16868         p->pPage1Disk = &p->pPage1Cache[nByte];
16869         memcpy(p->pPage1Disk, aBuf, nByte);
16870         aHdr[18] = a[18];
16871         aHdr[19] = a[19];
16872         recoverPutU32(&aHdr[28], dbsz);
16873         recoverPutU32(&aHdr[56], enc);
16874         recoverPutU16(&aHdr[105], pgsz-nReserve);
16875         if( pgsz==65536 ) pgsz = 1;
16876         recoverPutU16(&aHdr[16], pgsz);
16877         aHdr[20] = nReserve;
16878         for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
16879           memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
16880         }
16881         memcpy(aBuf, aHdr, sizeof(aHdr));
16882         memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
16883 
16884         memcpy(p->pPage1Cache, aBuf, nByte);
16885       }else{
16886         rc = p->errCode;
16887       }
16888 
16889     }
16890     pFd->pMethods = &recover_methods;
16891   }else{
16892     rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
16893   }
16894   return rc;
16895 }
16896 
16897 /*
16898 ** Used to make sqlite3_io_methods wrapper methods less verbose.
16899 */
16900 #define RECOVER_VFS_WRAPPER(code)                         \
16901   int rc = SQLITE_OK;                                     \
16902   if( pFd->pMethods==&recover_methods ){                  \
16903     pFd->pMethods = recover_g.pMethods;                   \
16904     rc = code;                                            \
16905     pFd->pMethods = &recover_methods;                     \
16906   }else{                                                  \
16907     rc = code;                                            \
16908   }                                                       \
16909   return rc;
16910 
16911 /*
16912 ** Methods of the wrapper VFS. All methods except for xRead() and xClose()
16913 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
16914 ** method on the lower level VFS, then reinstall the wrapper before returning.
16915 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
16916 */
16917 static int recoverVfsWrite(
16918   sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
16919 ){
16920   RECOVER_VFS_WRAPPER (
16921       pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
16922   );
16923 }
16924 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
16925   RECOVER_VFS_WRAPPER (
16926       pFd->pMethods->xTruncate(pFd, size)
16927   );
16928 }
16929 static int recoverVfsSync(sqlite3_file *pFd, int flags){
16930   RECOVER_VFS_WRAPPER (
16931       pFd->pMethods->xSync(pFd, flags)
16932   );
16933 }
16934 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
16935   RECOVER_VFS_WRAPPER (
16936       pFd->pMethods->xFileSize(pFd, pSize)
16937   );
16938 }
16939 static int recoverVfsLock(sqlite3_file *pFd, int eLock){
16940   RECOVER_VFS_WRAPPER (
16941       pFd->pMethods->xLock(pFd, eLock)
16942   );
16943 }
16944 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
16945   RECOVER_VFS_WRAPPER (
16946       pFd->pMethods->xUnlock(pFd, eLock)
16947   );
16948 }
16949 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
16950   RECOVER_VFS_WRAPPER (
16951       pFd->pMethods->xCheckReservedLock(pFd, pResOut)
16952   );
16953 }
16954 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
16955   RECOVER_VFS_WRAPPER (
16956     (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
16957   );
16958 }
16959 static int recoverVfsSectorSize(sqlite3_file *pFd){
16960   RECOVER_VFS_WRAPPER (
16961       pFd->pMethods->xSectorSize(pFd)
16962   );
16963 }
16964 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
16965   RECOVER_VFS_WRAPPER (
16966       pFd->pMethods->xDeviceCharacteristics(pFd)
16967   );
16968 }
16969 static int recoverVfsShmMap(
16970   sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
16971 ){
16972   RECOVER_VFS_WRAPPER (
16973       pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
16974   );
16975 }
16976 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
16977   RECOVER_VFS_WRAPPER (
16978       pFd->pMethods->xShmLock(pFd, offset, n, flags)
16979   );
16980 }
16981 static void recoverVfsShmBarrier(sqlite3_file *pFd){
16982   if( pFd->pMethods==&recover_methods ){
16983     pFd->pMethods = recover_g.pMethods;
16984     pFd->pMethods->xShmBarrier(pFd);
16985     pFd->pMethods = &recover_methods;
16986   }else{
16987     pFd->pMethods->xShmBarrier(pFd);
16988   }
16989 }
16990 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
16991   RECOVER_VFS_WRAPPER (
16992       pFd->pMethods->xShmUnmap(pFd, deleteFlag)
16993   );
16994 }
16995 
16996 static int recoverVfsFetch(
16997   sqlite3_file *pFd,
16998   sqlite3_int64 iOff,
16999   int iAmt,
17000   void **pp
17001 ){
17002   (void)pFd;
17003   (void)iOff;
17004   (void)iAmt;
17005   *pp = 0;
17006   return SQLITE_OK;
17007 }
17008 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
17009   (void)pFd;
17010   (void)iOff;
17011   (void)p;
17012   return SQLITE_OK;
17013 }
17014 
17015 /*
17016 ** Install the VFS wrapper around the file-descriptor open on the input
17017 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
17018 ** when this function is called.
17019 */
17020 static void recoverInstallWrapper(sqlite3_recover *p){
17021   sqlite3_file *pFd = 0;
17022   assert( recover_g.pMethods==0 );
17023   recoverAssertMutexHeld();
17024   sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
17025   assert( pFd==0 || pFd->pMethods!=&recover_methods );
17026   if( pFd && pFd->pMethods ){
17027     int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
17028     recover_g.pMethods = pFd->pMethods;
17029     recover_g.p = p;
17030     recover_methods.iVersion = iVersion;
17031     pFd->pMethods = &recover_methods;
17032   }
17033 }
17034 
17035 /*
17036 ** Uninstall the VFS wrapper that was installed around the file-descriptor open
17037 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
17038 ** held when this function is called.
17039 */
17040 static void recoverUninstallWrapper(sqlite3_recover *p){
17041   sqlite3_file *pFd = 0;
17042   recoverAssertMutexHeld();
17043   sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
17044   if( pFd && pFd->pMethods ){
17045     pFd->pMethods = recover_g.pMethods;
17046     recover_g.pMethods = 0;
17047     recover_g.p = 0;
17048   }
17049 }
17050 
17051 /*
17052 ** This function does the work of a single sqlite3_recover_step() call. It
17053 ** is guaranteed that the handle is not in an error state when this
17054 ** function is called.
17055 */
17056 static void recoverStep(sqlite3_recover *p){
17057   assert( p && p->errCode==SQLITE_OK );
17058   switch( p->eState ){
17059     case RECOVER_STATE_INIT:
17060       /* This is the very first call to sqlite3_recover_step() on this object.
17061       */
17062       recoverSqlCallback(p, "BEGIN");
17063       recoverSqlCallback(p, "PRAGMA writable_schema = on");
17064 
17065       recoverEnterMutex();
17066       recoverInstallWrapper(p);
17067 
17068       /* Open the output database. And register required virtual tables and
17069       ** user functions with the new handle. */
17070       recoverOpenOutput(p);
17071 
17072       /* Open transactions on both the input and output databases. */
17073       sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
17074       recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
17075       recoverExec(p, p->dbIn, "BEGIN");
17076       if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
17077       recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
17078       recoverTransferSettings(p);
17079       recoverOpenRecovery(p);
17080       recoverCacheSchema(p);
17081 
17082       recoverUninstallWrapper(p);
17083       recoverLeaveMutex();
17084 
17085       recoverExec(p, p->dbOut, "BEGIN");
17086 
17087       recoverWriteSchema1(p);
17088       p->eState = RECOVER_STATE_WRITING;
17089       break;
17090 
17091     case RECOVER_STATE_WRITING: {
17092       if( p->w1.pTbls==0 ){
17093         recoverWriteDataInit(p);
17094       }
17095       if( SQLITE_DONE==recoverWriteDataStep(p) ){
17096         recoverWriteDataCleanup(p);
17097         if( p->zLostAndFound ){
17098           p->eState = RECOVER_STATE_LOSTANDFOUND1;
17099         }else{
17100           p->eState = RECOVER_STATE_SCHEMA2;
17101         }
17102       }
17103       break;
17104     }
17105 
17106     case RECOVER_STATE_LOSTANDFOUND1: {
17107       if( p->laf.pUsed==0 ){
17108         recoverLostAndFound1Init(p);
17109       }
17110       if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
17111         p->eState = RECOVER_STATE_LOSTANDFOUND2;
17112       }
17113       break;
17114     }
17115     case RECOVER_STATE_LOSTANDFOUND2: {
17116       if( p->laf.pAllAndParent==0 ){
17117         recoverLostAndFound2Init(p);
17118       }
17119       if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
17120         p->eState = RECOVER_STATE_LOSTANDFOUND3;
17121       }
17122       break;
17123     }
17124 
17125     case RECOVER_STATE_LOSTANDFOUND3: {
17126       if( p->laf.pInsert==0 ){
17127         recoverLostAndFound3Init(p);
17128       }
17129       if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
17130         p->eState = RECOVER_STATE_SCHEMA2;
17131       }
17132       break;
17133     }
17134 
17135     case RECOVER_STATE_SCHEMA2: {
17136       int rc = SQLITE_OK;
17137 
17138       recoverWriteSchema2(p);
17139       p->eState = RECOVER_STATE_DONE;
17140 
17141       /* If no error has occurred, commit the write transaction on the output
17142       ** database. Regardless of whether or not an error has occurred, make
17143       ** an attempt to end the read transaction on the input database.  */
17144       recoverExec(p, p->dbOut, "COMMIT");
17145       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
17146       if( p->errCode==SQLITE_OK ) p->errCode = rc;
17147 
17148       recoverSqlCallback(p, "PRAGMA writable_schema = off");
17149       recoverSqlCallback(p, "COMMIT");
17150       p->eState = RECOVER_STATE_DONE;
17151       recoverFinalCleanup(p);
17152       break;
17153     };
17154 
17155     case RECOVER_STATE_DONE: {
17156       /* no-op */
17157       break;
17158     };
17159   }
17160 }
17161 
17162 
17163 /*
17164 ** This is a worker function that does the heavy lifting for both init
17165 ** functions:
17166 **
17167 **     sqlite3_recover_init()
17168 **     sqlite3_recover_init_sql()
17169 **
17170 ** All this function does is allocate space for the recover handle and
17171 ** take copies of the input parameters. All the real work is done within
17172 ** sqlite3_recover_run().
17173 */
17174 sqlite3_recover *recoverInit(
17175   sqlite3* db,
17176   const char *zDb,
17177   const char *zUri,               /* Output URI for _recover_init() */
17178   int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
17179   void *pSqlCtx                   /* Context arg for _recover_init_sql() */
17180 ){
17181   sqlite3_recover *pRet = 0;
17182   int nDb = 0;
17183   int nUri = 0;
17184   int nByte = 0;
17185 
17186   if( zDb==0 ){ zDb = "main"; }
17187 
17188   nDb = recoverStrlen(zDb);
17189   nUri = recoverStrlen(zUri);
17190 
17191   nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
17192   pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
17193   if( pRet ){
17194     memset(pRet, 0, nByte);
17195     pRet->dbIn = db;
17196     pRet->zDb = (char*)&pRet[1];
17197     pRet->zUri = &pRet->zDb[nDb+1];
17198     memcpy(pRet->zDb, zDb, nDb);
17199     if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
17200     pRet->xSql = xSql;
17201     pRet->pSqlCtx = pSqlCtx;
17202     pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
17203   }
17204 
17205   return pRet;
17206 }
17207 
17208 /*
17209 ** Initialize a recovery handle that creates a new database containing
17210 ** the recovered data.
17211 */
17212 sqlite3_recover *sqlite3_recover_init(
17213   sqlite3* db,
17214   const char *zDb,
17215   const char *zUri
17216 ){
17217   return recoverInit(db, zDb, zUri, 0, 0);
17218 }
17219 
17220 /*
17221 ** Initialize a recovery handle that returns recovered data in the
17222 ** form of SQL statements via a callback.
17223 */
17224 sqlite3_recover *sqlite3_recover_init_sql(
17225   sqlite3* db,
17226   const char *zDb,
17227   int (*xSql)(void*, const char*),
17228   void *pSqlCtx
17229 ){
17230   return recoverInit(db, zDb, 0, xSql, pSqlCtx);
17231 }
17232 
17233 /*
17234 ** Return the handle error message, if any.
17235 */
17236 const char *sqlite3_recover_errmsg(sqlite3_recover *p){
17237   return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
17238 }
17239 
17240 /*
17241 ** Return the handle error code.
17242 */
17243 int sqlite3_recover_errcode(sqlite3_recover *p){
17244   return p ? p->errCode : SQLITE_NOMEM;
17245 }
17246 
17247 /*
17248 ** Configure the handle.
17249 */
17250 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
17251   int rc = SQLITE_OK;
17252   if( p==0 ){
17253     rc = SQLITE_NOMEM;
17254   }else if( p->eState!=RECOVER_STATE_INIT ){
17255     rc = SQLITE_MISUSE;
17256   }else{
17257     switch( op ){
17258       case 789:
17259         /* This undocumented magic configuration option is used to set the
17260         ** name of the auxiliary database that is ATTACH-ed to the database
17261         ** connection and used to hold state information during the
17262         ** recovery process.  This option is for debugging use only and
17263         ** is subject to change or removal at any time. */
17264         sqlite3_free(p->zStateDb);
17265         p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
17266         break;
17267 
17268       case SQLITE_RECOVER_LOST_AND_FOUND: {
17269         const char *zArg = (const char*)pArg;
17270         sqlite3_free(p->zLostAndFound);
17271         if( zArg ){
17272           p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
17273         }else{
17274           p->zLostAndFound = 0;
17275         }
17276         break;
17277       }
17278 
17279       case SQLITE_RECOVER_FREELIST_CORRUPT:
17280         p->bFreelistCorrupt = *(int*)pArg;
17281         break;
17282 
17283       case SQLITE_RECOVER_ROWIDS:
17284         p->bRecoverRowid = *(int*)pArg;
17285         break;
17286 
17287       case SQLITE_RECOVER_SLOWINDEXES:
17288         p->bSlowIndexes = *(int*)pArg;
17289         break;
17290 
17291       default:
17292         rc = SQLITE_NOTFOUND;
17293         break;
17294     }
17295   }
17296 
17297   return rc;
17298 }
17299 
17300 /*
17301 ** Do a unit of work towards the recovery job. Return SQLITE_OK if
17302 ** no error has occurred but database recovery is not finished, SQLITE_DONE
17303 ** if database recovery has been successfully completed, or an SQLite
17304 ** error code if an error has occurred.
17305 */
17306 int sqlite3_recover_step(sqlite3_recover *p){
17307   if( p==0 ) return SQLITE_NOMEM;
17308   if( p->errCode==SQLITE_OK ) recoverStep(p);
17309   if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
17310     return SQLITE_DONE;
17311   }
17312   return p->errCode;
17313 }
17314 
17315 /*
17316 ** Do the configured recovery operation. Return SQLITE_OK if successful, or
17317 ** else an SQLite error code.
17318 */
17319 int sqlite3_recover_run(sqlite3_recover *p){
17320   while( SQLITE_OK==sqlite3_recover_step(p) );
17321   return sqlite3_recover_errcode(p);
17322 }
17323 
17324 
17325 /*
17326 ** Free all resources associated with the recover handle passed as the only
17327 ** argument. The results of using a handle with any sqlite3_recover_**
17328 ** API function after it has been passed to this function are undefined.
17329 **
17330 ** A copy of the value returned by the first call made to sqlite3_recover_run()
17331 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
17332 ** not been called on this handle.
17333 */
17334 int sqlite3_recover_finish(sqlite3_recover *p){
17335   int rc;
17336   if( p==0 ){
17337     rc = SQLITE_NOMEM;
17338   }else{
17339     recoverFinalCleanup(p);
17340     if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
17341       rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
17342       if( p->errCode==SQLITE_OK ) p->errCode = rc;
17343     }
17344     rc = p->errCode;
17345     sqlite3_free(p->zErrMsg);
17346     sqlite3_free(p->zStateDb);
17347     sqlite3_free(p->zLostAndFound);
17348     sqlite3_free(p->pPage1Cache);
17349     sqlite3_free(p);
17350   }
17351   return rc;
17352 }
17353 
17354 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
17355 
17356 /************************* End ../ext/recover/sqlite3recover.c ********************/
17357 # endif /* SQLITE_HAVE_SQLITE3R */
17358 #endif
17359 #ifdef SQLITE_SHELL_EXTSRC
17360 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
17361 #endif
17362 
17363 #if defined(SQLITE_ENABLE_SESSION)
17364 /*
17365 ** State information for a single open session
17366 */
17367 typedef struct OpenSession OpenSession;
17368 struct OpenSession {
17369   char *zName;             /* Symbolic name for this session */
17370   int nFilter;             /* Number of xFilter rejection GLOB patterns */
17371   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
17372   sqlite3_session *p;      /* The open session */
17373 };
17374 #endif
17375 
17376 typedef struct ExpertInfo ExpertInfo;
17377 struct ExpertInfo {
17378   sqlite3expert *pExpert;
17379   int bVerbose;
17380 };
17381 
17382 /* A single line in the EQP output */
17383 typedef struct EQPGraphRow EQPGraphRow;
17384 struct EQPGraphRow {
17385   int iEqpId;           /* ID for this row */
17386   int iParentId;        /* ID of the parent row */
17387   EQPGraphRow *pNext;   /* Next row in sequence */
17388   char zText[1];        /* Text to display for this row */
17389 };
17390 
17391 /* All EQP output is collected into an instance of the following */
17392 typedef struct EQPGraph EQPGraph;
17393 struct EQPGraph {
17394   EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
17395   EQPGraphRow *pLast;   /* Last element of the pRow list */
17396   char zPrefix[100];    /* Graph prefix */
17397 };
17398 
17399 /* Parameters affecting columnar mode result display (defaulting together) */
17400 typedef struct ColModeOpts {
17401   int iWrap;            /* In columnar modes, wrap lines reaching this limit */
17402   u8 bQuote;            /* Quote results for .mode box and table */
17403   u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
17404 } ColModeOpts;
17405 #define ColModeOpts_default { 60, 0, 0 }
17406 #define ColModeOpts_default_qbox { 60, 1, 0 }
17407 
17408 /*
17409 ** State information about the database connection is contained in an
17410 ** instance of the following structure.
17411 */
17412 typedef struct ShellState ShellState;
17413 struct ShellState {
17414   sqlite3 *db;           /* The database */
17415   u8 autoExplain;        /* Automatically turn on .explain mode */
17416   u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
17417   u8 autoEQPtest;        /* autoEQP is in test mode */
17418   u8 autoEQPtrace;       /* autoEQP is in trace mode */
17419   u8 scanstatsOn;        /* True to display scan stats before each finalize */
17420   u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
17421   u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
17422   u8 nEqpLevel;          /* Depth of the EQP output graph */
17423   u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
17424   u8 bSafeMode;          /* True to prohibit unsafe operations */
17425   u8 bSafeModePersist;   /* The long-term value of bSafeMode */
17426   ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
17427   unsigned statsOn;      /* True to display memory stats before each finalize */
17428   unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
17429   int inputNesting;      /* Track nesting level of .read and other redirects */
17430   int outCount;          /* Revert to stdout when reaching zero */
17431   int cnt;               /* Number of records displayed so far */
17432   int lineno;            /* Line number of last line read from in */
17433   int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
17434   FILE *in;              /* Read commands from this stream */
17435   FILE *out;             /* Write results here */
17436   FILE *traceOut;        /* Output for sqlite3_trace() */
17437   int nErr;              /* Number of errors seen */
17438   int mode;              /* An output mode setting */
17439   int modePrior;         /* Saved mode */
17440   int cMode;             /* temporary output mode for the current query */
17441   int normalMode;        /* Output mode before ".explain on" */
17442   int writableSchema;    /* True if PRAGMA writable_schema=ON */
17443   int showHeader;        /* True to show column names in List or Column mode */
17444   int nCheck;            /* Number of ".check" commands run */
17445   unsigned nProgress;    /* Number of progress callbacks encountered */
17446   unsigned mxProgress;   /* Maximum progress callbacks before failing */
17447   unsigned flgProgress;  /* Flags for the progress callback */
17448   unsigned shellFlgs;    /* Various flags */
17449   unsigned priorShFlgs;  /* Saved copy of flags */
17450   sqlite3_int64 szMax;   /* --maxsize argument to .open */
17451   char *zDestTable;      /* Name of destination table when MODE_Insert */
17452   char *zTempFile;       /* Temporary file that might need deleting */
17453   char zTestcase[30];    /* Name of current test case */
17454   char colSeparator[20]; /* Column separator character for several modes */
17455   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
17456   char colSepPrior[20];  /* Saved column separator */
17457   char rowSepPrior[20];  /* Saved row separator */
17458   int *colWidth;         /* Requested width of each column in columnar modes */
17459   int *actualWidth;      /* Actual width of each column */
17460   int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
17461   char nullValue[20];    /* The text to print when a NULL comes back from
17462                          ** the database */
17463   char outfile[FILENAME_MAX]; /* Filename for *out */
17464   sqlite3_stmt *pStmt;   /* Current statement if any. */
17465   FILE *pLog;            /* Write log output here */
17466   struct AuxDb {         /* Storage space for auxiliary database connections */
17467     sqlite3 *db;               /* Connection pointer */
17468     const char *zDbFilename;   /* Filename used to open the connection */
17469     char *zFreeOnClose;        /* Free this memory allocation on close */
17470 #if defined(SQLITE_ENABLE_SESSION)
17471     int nSession;              /* Number of active sessions */
17472     OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
17473 #endif
17474   } aAuxDb[5],           /* Array of all database connections */
17475     *pAuxDb;             /* Currently active database connection */
17476   int *aiIndent;         /* Array of indents used in MODE_Explain */
17477   int nIndent;           /* Size of array aiIndent[] */
17478   int iIndent;           /* Index of current op in aiIndent[] */
17479   char *zNonce;          /* Nonce for temporary safe-mode escapes */
17480   EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
17481   ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
17482 #ifdef SQLITE_SHELL_FIDDLE
17483   struct {
17484     const char * zInput; /* Input string from wasm/JS proxy */
17485     const char * zPos;   /* Cursor pos into zInput */
17486     const char * zDefaultDbName; /* Default name for db file */
17487   } wasm;
17488 #endif
17489 };
17490 
17491 #ifdef SQLITE_SHELL_FIDDLE
17492 static ShellState shellState;
17493 #endif
17494 
17495 
17496 /* Allowed values for ShellState.autoEQP
17497 */
17498 #define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
17499 #define AUTOEQP_on       1           /* Automatic EQP is on */
17500 #define AUTOEQP_trigger  2           /* On and also show plans for triggers */
17501 #define AUTOEQP_full     3           /* Show full EXPLAIN */
17502 
17503 /* Allowed values for ShellState.openMode
17504 */
17505 #define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
17506 #define SHELL_OPEN_NORMAL      1      /* Normal database file */
17507 #define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
17508 #define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
17509 #define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
17510 #define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
17511 #define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
17512 
17513 /* Allowed values for ShellState.eTraceType
17514 */
17515 #define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
17516 #define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
17517 #define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
17518 
17519 /* Bits in the ShellState.flgProgress variable */
17520 #define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
17521 #define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
17522                                    ** callback limit is reached, and for each
17523                                    ** top-level SQL statement */
17524 #define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
17525 
17526 /*
17527 ** These are the allowed shellFlgs values
17528 */
17529 #define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
17530 #define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
17531 #define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
17532 #define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
17533 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
17534 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
17535 #define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
17536 #define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
17537 #define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
17538 #define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
17539 #define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
17540 
17541 /*
17542 ** Macros for testing and setting shellFlgs
17543 */
17544 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
17545 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
17546 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
17547 
17548 /*
17549 ** These are the allowed modes.
17550 */
17551 #define MODE_Line     0  /* One column per line.  Blank line between records */
17552 #define MODE_Column   1  /* One record per line in neat columns */
17553 #define MODE_List     2  /* One record per line with a separator */
17554 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
17555 #define MODE_Html     4  /* Generate an XHTML table */
17556 #define MODE_Insert   5  /* Generate SQL "insert" statements */
17557 #define MODE_Quote    6  /* Quote values as for SQL */
17558 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
17559 #define MODE_Csv      8  /* Quote strings, numbers are plain */
17560 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
17561 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
17562 #define MODE_Pretty  11  /* Pretty-print schemas */
17563 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
17564 #define MODE_Json    13  /* Output JSON */
17565 #define MODE_Markdown 14 /* Markdown formatting */
17566 #define MODE_Table   15  /* MySQL-style table formatting */
17567 #define MODE_Box     16  /* Unicode box-drawing characters */
17568 #define MODE_Count   17  /* Output only a count of the rows of output */
17569 #define MODE_Off     18  /* No query output shown */
17570 #define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
17571 
17572 static const char *modeDescr[] = {
17573   "line",
17574   "column",
17575   "list",
17576   "semi",
17577   "html",
17578   "insert",
17579   "quote",
17580   "tcl",
17581   "csv",
17582   "explain",
17583   "ascii",
17584   "prettyprint",
17585   "eqp",
17586   "json",
17587   "markdown",
17588   "table",
17589   "box",
17590   "count",
17591   "off"
17592 };
17593 
17594 /*
17595 ** These are the column/row/line separators used by the various
17596 ** import/export modes.
17597 */
17598 #define SEP_Column    "|"
17599 #define SEP_Row       "\n"
17600 #define SEP_Tab       "\t"
17601 #define SEP_Space     " "
17602 #define SEP_Comma     ","
17603 #define SEP_CrLf      "\r\n"
17604 #define SEP_Unit      "\x1F"
17605 #define SEP_Record    "\x1E"
17606 
17607 /*
17608 ** Limit input nesting via .read or any other input redirect.
17609 ** It's not too expensive, so a generous allowance can be made.
17610 */
17611 #define MAX_INPUT_NESTING 25
17612 
17613 /*
17614 ** A callback for the sqlite3_log() interface.
17615 */
17616 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
17617   ShellState *p = (ShellState*)pArg;
17618   if( p->pLog==0 ) return;
17619   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
17620   fflush(p->pLog);
17621 }
17622 
17623 /*
17624 ** SQL function:  shell_putsnl(X)
17625 **
17626 ** Write the text X to the screen (or whatever output is being directed)
17627 ** adding a newline at the end, and then return X.
17628 */
17629 static void shellPutsFunc(
17630   sqlite3_context *pCtx,
17631   int nVal,
17632   sqlite3_value **apVal
17633 ){
17634   ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
17635   (void)nVal;
17636   utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
17637   sqlite3_result_value(pCtx, apVal[0]);
17638 }
17639 
17640 /*
17641 ** If in safe mode, print an error message described by the arguments
17642 ** and exit immediately.
17643 */
17644 static void failIfSafeMode(
17645   ShellState *p,
17646   const char *zErrMsg,
17647   ...
17648 ){
17649   if( p->bSafeMode ){
17650     va_list ap;
17651     char *zMsg;
17652     va_start(ap, zErrMsg);
17653     zMsg = sqlite3_vmprintf(zErrMsg, ap);
17654     va_end(ap);
17655     raw_printf(stderr, "line %d: ", p->lineno);
17656     utf8_printf(stderr, "%s\n", zMsg);
17657     exit(1);
17658   }
17659 }
17660 
17661 /*
17662 ** SQL function:   edit(VALUE)
17663 **                 edit(VALUE,EDITOR)
17664 **
17665 ** These steps:
17666 **
17667 **     (1) Write VALUE into a temporary file.
17668 **     (2) Run program EDITOR on that temporary file.
17669 **     (3) Read the temporary file back and return its content as the result.
17670 **     (4) Delete the temporary file
17671 **
17672 ** If the EDITOR argument is omitted, use the value in the VISUAL
17673 ** environment variable.  If still there is no EDITOR, through an error.
17674 **
17675 ** Also throw an error if the EDITOR program returns a non-zero exit code.
17676 */
17677 #ifndef SQLITE_NOHAVE_SYSTEM
17678 static void editFunc(
17679   sqlite3_context *context,
17680   int argc,
17681   sqlite3_value **argv
17682 ){
17683   const char *zEditor;
17684   char *zTempFile = 0;
17685   sqlite3 *db;
17686   char *zCmd = 0;
17687   int bBin;
17688   int rc;
17689   int hasCRNL = 0;
17690   FILE *f = 0;
17691   sqlite3_int64 sz;
17692   sqlite3_int64 x;
17693   unsigned char *p = 0;
17694 
17695   if( argc==2 ){
17696     zEditor = (const char*)sqlite3_value_text(argv[1]);
17697   }else{
17698     zEditor = getenv("VISUAL");
17699   }
17700   if( zEditor==0 ){
17701     sqlite3_result_error(context, "no editor for edit()", -1);
17702     return;
17703   }
17704   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
17705     sqlite3_result_error(context, "NULL input to edit()", -1);
17706     return;
17707   }
17708   db = sqlite3_context_db_handle(context);
17709   zTempFile = 0;
17710   sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
17711   if( zTempFile==0 ){
17712     sqlite3_uint64 r = 0;
17713     sqlite3_randomness(sizeof(r), &r);
17714     zTempFile = sqlite3_mprintf("temp%llx", r);
17715     if( zTempFile==0 ){
17716       sqlite3_result_error_nomem(context);
17717       return;
17718     }
17719   }
17720   bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
17721   /* When writing the file to be edited, do \n to \r\n conversions on systems
17722   ** that want \r\n line endings */
17723   f = fopen(zTempFile, bBin ? "wb" : "w");
17724   if( f==0 ){
17725     sqlite3_result_error(context, "edit() cannot open temp file", -1);
17726     goto edit_func_end;
17727   }
17728   sz = sqlite3_value_bytes(argv[0]);
17729   if( bBin ){
17730     x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
17731   }else{
17732     const char *z = (const char*)sqlite3_value_text(argv[0]);
17733     /* Remember whether or not the value originally contained \r\n */
17734     if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
17735     x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
17736   }
17737   fclose(f);
17738   f = 0;
17739   if( x!=sz ){
17740     sqlite3_result_error(context, "edit() could not write the whole file", -1);
17741     goto edit_func_end;
17742   }
17743   zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
17744   if( zCmd==0 ){
17745     sqlite3_result_error_nomem(context);
17746     goto edit_func_end;
17747   }
17748   rc = system(zCmd);
17749   sqlite3_free(zCmd);
17750   if( rc ){
17751     sqlite3_result_error(context, "EDITOR returned non-zero", -1);
17752     goto edit_func_end;
17753   }
17754   f = fopen(zTempFile, "rb");
17755   if( f==0 ){
17756     sqlite3_result_error(context,
17757       "edit() cannot reopen temp file after edit", -1);
17758     goto edit_func_end;
17759   }
17760   fseek(f, 0, SEEK_END);
17761   sz = ftell(f);
17762   rewind(f);
17763   p = sqlite3_malloc64( sz+1 );
17764   if( p==0 ){
17765     sqlite3_result_error_nomem(context);
17766     goto edit_func_end;
17767   }
17768   x = fread(p, 1, (size_t)sz, f);
17769   fclose(f);
17770   f = 0;
17771   if( x!=sz ){
17772     sqlite3_result_error(context, "could not read back the whole file", -1);
17773     goto edit_func_end;
17774   }
17775   if( bBin ){
17776     sqlite3_result_blob64(context, p, sz, sqlite3_free);
17777   }else{
17778     sqlite3_int64 i, j;
17779     if( hasCRNL ){
17780       /* If the original contains \r\n then do no conversions back to \n */
17781     }else{
17782       /* If the file did not originally contain \r\n then convert any new
17783       ** \r\n back into \n */
17784       p[sz] = 0;
17785       for(i=j=0; i<sz; i++){
17786         if( p[i]=='\r' && p[i+1]=='\n' ) i++;
17787         p[j++] = p[i];
17788       }
17789       sz = j;
17790       p[sz] = 0;
17791     }
17792     sqlite3_result_text64(context, (const char*)p, sz,
17793                           sqlite3_free, SQLITE_UTF8);
17794   }
17795   p = 0;
17796 
17797 edit_func_end:
17798   if( f ) fclose(f);
17799   unlink(zTempFile);
17800   sqlite3_free(zTempFile);
17801   sqlite3_free(p);
17802 }
17803 #endif /* SQLITE_NOHAVE_SYSTEM */
17804 
17805 /*
17806 ** Save or restore the current output mode
17807 */
17808 static void outputModePush(ShellState *p){
17809   p->modePrior = p->mode;
17810   p->priorShFlgs = p->shellFlgs;
17811   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
17812   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
17813 }
17814 static void outputModePop(ShellState *p){
17815   p->mode = p->modePrior;
17816   p->shellFlgs = p->priorShFlgs;
17817   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
17818   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
17819 }
17820 
17821 /*
17822 ** Output the given string as a hex-encoded blob (eg. X'1234' )
17823 */
17824 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
17825   int i;
17826   unsigned char *aBlob = (unsigned char*)pBlob;
17827 
17828   char *zStr = sqlite3_malloc(nBlob*2 + 1);
17829   shell_check_oom(zStr);
17830 
17831   for(i=0; i<nBlob; i++){
17832     static const char aHex[] = {
17833         '0', '1', '2', '3', '4', '5', '6', '7',
17834         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
17835     };
17836     zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
17837     zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
17838   }
17839   zStr[i*2] = '\0';
17840 
17841   raw_printf(out,"X'%s'", zStr);
17842   sqlite3_free(zStr);
17843 }
17844 
17845 /*
17846 ** Find a string that is not found anywhere in z[].  Return a pointer
17847 ** to that string.
17848 **
17849 ** Try to use zA and zB first.  If both of those are already found in z[]
17850 ** then make up some string and store it in the buffer zBuf.
17851 */
17852 static const char *unused_string(
17853   const char *z,                    /* Result must not appear anywhere in z */
17854   const char *zA, const char *zB,   /* Try these first */
17855   char *zBuf                        /* Space to store a generated string */
17856 ){
17857   unsigned i = 0;
17858   if( strstr(z, zA)==0 ) return zA;
17859   if( strstr(z, zB)==0 ) return zB;
17860   do{
17861     sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
17862   }while( strstr(z,zBuf)!=0 );
17863   return zBuf;
17864 }
17865 
17866 /*
17867 ** Output the given string as a quoted string using SQL quoting conventions.
17868 **
17869 ** See also: output_quoted_escaped_string()
17870 */
17871 static void output_quoted_string(FILE *out, const char *z){
17872   int i;
17873   char c;
17874   setBinaryMode(out, 1);
17875   if( z==0 ) return;
17876   for(i=0; (c = z[i])!=0 && c!='\''; i++){}
17877   if( c==0 ){
17878     utf8_printf(out,"'%s'",z);
17879   }else{
17880     raw_printf(out, "'");
17881     while( *z ){
17882       for(i=0; (c = z[i])!=0 && c!='\''; i++){}
17883       if( c=='\'' ) i++;
17884       if( i ){
17885         utf8_printf(out, "%.*s", i, z);
17886         z += i;
17887       }
17888       if( c=='\'' ){
17889         raw_printf(out, "'");
17890         continue;
17891       }
17892       if( c==0 ){
17893         break;
17894       }
17895       z++;
17896     }
17897     raw_printf(out, "'");
17898   }
17899   setTextMode(out, 1);
17900 }
17901 
17902 /*
17903 ** Output the given string as a quoted string using SQL quoting conventions.
17904 ** Additionallly , escape the "\n" and "\r" characters so that they do not
17905 ** get corrupted by end-of-line translation facilities in some operating
17906 ** systems.
17907 **
17908 ** This is like output_quoted_string() but with the addition of the \r\n
17909 ** escape mechanism.
17910 */
17911 static void output_quoted_escaped_string(FILE *out, const char *z){
17912   int i;
17913   char c;
17914   setBinaryMode(out, 1);
17915   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
17916   if( c==0 ){
17917     utf8_printf(out,"'%s'",z);
17918   }else{
17919     const char *zNL = 0;
17920     const char *zCR = 0;
17921     int nNL = 0;
17922     int nCR = 0;
17923     char zBuf1[20], zBuf2[20];
17924     for(i=0; z[i]; i++){
17925       if( z[i]=='\n' ) nNL++;
17926       if( z[i]=='\r' ) nCR++;
17927     }
17928     if( nNL ){
17929       raw_printf(out, "replace(");
17930       zNL = unused_string(z, "\\n", "\\012", zBuf1);
17931     }
17932     if( nCR ){
17933       raw_printf(out, "replace(");
17934       zCR = unused_string(z, "\\r", "\\015", zBuf2);
17935     }
17936     raw_printf(out, "'");
17937     while( *z ){
17938       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
17939       if( c=='\'' ) i++;
17940       if( i ){
17941         utf8_printf(out, "%.*s", i, z);
17942         z += i;
17943       }
17944       if( c=='\'' ){
17945         raw_printf(out, "'");
17946         continue;
17947       }
17948       if( c==0 ){
17949         break;
17950       }
17951       z++;
17952       if( c=='\n' ){
17953         raw_printf(out, "%s", zNL);
17954         continue;
17955       }
17956       raw_printf(out, "%s", zCR);
17957     }
17958     raw_printf(out, "'");
17959     if( nCR ){
17960       raw_printf(out, ",'%s',char(13))", zCR);
17961     }
17962     if( nNL ){
17963       raw_printf(out, ",'%s',char(10))", zNL);
17964     }
17965   }
17966   setTextMode(out, 1);
17967 }
17968 
17969 /*
17970 ** Output the given string as a quoted according to C or TCL quoting rules.
17971 */
17972 static void output_c_string(FILE *out, const char *z){
17973   unsigned int c;
17974   fputc('"', out);
17975   while( (c = *(z++))!=0 ){
17976     if( c=='\\' ){
17977       fputc(c, out);
17978       fputc(c, out);
17979     }else if( c=='"' ){
17980       fputc('\\', out);
17981       fputc('"', out);
17982     }else if( c=='\t' ){
17983       fputc('\\', out);
17984       fputc('t', out);
17985     }else if( c=='\n' ){
17986       fputc('\\', out);
17987       fputc('n', out);
17988     }else if( c=='\r' ){
17989       fputc('\\', out);
17990       fputc('r', out);
17991     }else if( !isprint(c&0xff) ){
17992       raw_printf(out, "\\%03o", c&0xff);
17993     }else{
17994       fputc(c, out);
17995     }
17996   }
17997   fputc('"', out);
17998 }
17999 
18000 /*
18001 ** Output the given string as a quoted according to JSON quoting rules.
18002 */
18003 static void output_json_string(FILE *out, const char *z, i64 n){
18004   unsigned int c;
18005   if( z==0 ) z = "";
18006   if( n<0 ) n = strlen(z);
18007   fputc('"', out);
18008   while( n-- ){
18009     c = *(z++);
18010     if( c=='\\' || c=='"' ){
18011       fputc('\\', out);
18012       fputc(c, out);
18013     }else if( c<=0x1f ){
18014       fputc('\\', out);
18015       if( c=='\b' ){
18016         fputc('b', out);
18017       }else if( c=='\f' ){
18018         fputc('f', out);
18019       }else if( c=='\n' ){
18020         fputc('n', out);
18021       }else if( c=='\r' ){
18022         fputc('r', out);
18023       }else if( c=='\t' ){
18024         fputc('t', out);
18025       }else{
18026          raw_printf(out, "u%04x",c);
18027       }
18028     }else{
18029       fputc(c, out);
18030     }
18031   }
18032   fputc('"', out);
18033 }
18034 
18035 /*
18036 ** Output the given string with characters that are special to
18037 ** HTML escaped.
18038 */
18039 static void output_html_string(FILE *out, const char *z){
18040   int i;
18041   if( z==0 ) z = "";
18042   while( *z ){
18043     for(i=0;   z[i]
18044             && z[i]!='<'
18045             && z[i]!='&'
18046             && z[i]!='>'
18047             && z[i]!='\"'
18048             && z[i]!='\'';
18049         i++){}
18050     if( i>0 ){
18051       utf8_printf(out,"%.*s",i,z);
18052     }
18053     if( z[i]=='<' ){
18054       raw_printf(out,"&lt;");
18055     }else if( z[i]=='&' ){
18056       raw_printf(out,"&amp;");
18057     }else if( z[i]=='>' ){
18058       raw_printf(out,"&gt;");
18059     }else if( z[i]=='\"' ){
18060       raw_printf(out,"&quot;");
18061     }else if( z[i]=='\'' ){
18062       raw_printf(out,"&#39;");
18063     }else{
18064       break;
18065     }
18066     z += i + 1;
18067   }
18068 }
18069 
18070 /*
18071 ** If a field contains any character identified by a 1 in the following
18072 ** array, then the string must be quoted for CSV.
18073 */
18074 static const char needCsvQuote[] = {
18075   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18076   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18077   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
18078   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18079   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18080   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18081   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
18082   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
18083   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18084   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18085   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18086   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18087   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18088   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18089   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18090   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
18091 };
18092 
18093 /*
18094 ** Output a single term of CSV.  Actually, p->colSeparator is used for
18095 ** the separator, which may or may not be a comma.  p->nullValue is
18096 ** the null value.  Strings are quoted if necessary.  The separator
18097 ** is only issued if bSep is true.
18098 */
18099 static void output_csv(ShellState *p, const char *z, int bSep){
18100   FILE *out = p->out;
18101   if( z==0 ){
18102     utf8_printf(out,"%s",p->nullValue);
18103   }else{
18104     unsigned i;
18105     for(i=0; z[i]; i++){
18106       if( needCsvQuote[((unsigned char*)z)[i]] ){
18107         i = 0;
18108         break;
18109       }
18110     }
18111     if( i==0 || strstr(z, p->colSeparator)!=0 ){
18112       char *zQuoted = sqlite3_mprintf("\"%w\"", z);
18113       shell_check_oom(zQuoted);
18114       utf8_printf(out, "%s", zQuoted);
18115       sqlite3_free(zQuoted);
18116     }else{
18117       utf8_printf(out, "%s", z);
18118     }
18119   }
18120   if( bSep ){
18121     utf8_printf(p->out, "%s", p->colSeparator);
18122   }
18123 }
18124 
18125 /*
18126 ** This routine runs when the user presses Ctrl-C
18127 */
18128 static void interrupt_handler(int NotUsed){
18129   UNUSED_PARAMETER(NotUsed);
18130   if( ++seenInterrupt>1 ) exit(1);
18131   if( globalDb ) sqlite3_interrupt(globalDb);
18132 }
18133 
18134 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
18135 /*
18136 ** This routine runs for console events (e.g. Ctrl-C) on Win32
18137 */
18138 static BOOL WINAPI ConsoleCtrlHandler(
18139   DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
18140 ){
18141   if( dwCtrlType==CTRL_C_EVENT ){
18142     interrupt_handler(0);
18143     return TRUE;
18144   }
18145   return FALSE;
18146 }
18147 #endif
18148 
18149 #ifndef SQLITE_OMIT_AUTHORIZATION
18150 /*
18151 ** This authorizer runs in safe mode.
18152 */
18153 static int safeModeAuth(
18154   void *pClientData,
18155   int op,
18156   const char *zA1,
18157   const char *zA2,
18158   const char *zA3,
18159   const char *zA4
18160 ){
18161   ShellState *p = (ShellState*)pClientData;
18162   static const char *azProhibitedFunctions[] = {
18163     "edit",
18164     "fts3_tokenizer",
18165     "load_extension",
18166     "readfile",
18167     "writefile",
18168     "zipfile",
18169     "zipfile_cds",
18170   };
18171   UNUSED_PARAMETER(zA1);
18172   UNUSED_PARAMETER(zA3);
18173   UNUSED_PARAMETER(zA4);
18174   switch( op ){
18175     case SQLITE_ATTACH: {
18176 #ifndef SQLITE_SHELL_FIDDLE
18177       /* In WASM builds the filesystem is a virtual sandbox, so
18178       ** there's no harm in using ATTACH. */
18179       failIfSafeMode(p, "cannot run ATTACH in safe mode");
18180 #endif
18181       break;
18182     }
18183     case SQLITE_FUNCTION: {
18184       int i;
18185       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
18186         if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
18187           failIfSafeMode(p, "cannot use the %s() function in safe mode",
18188                          azProhibitedFunctions[i]);
18189         }
18190       }
18191       break;
18192     }
18193   }
18194   return SQLITE_OK;
18195 }
18196 
18197 /*
18198 ** When the ".auth ON" is set, the following authorizer callback is
18199 ** invoked.  It always returns SQLITE_OK.
18200 */
18201 static int shellAuth(
18202   void *pClientData,
18203   int op,
18204   const char *zA1,
18205   const char *zA2,
18206   const char *zA3,
18207   const char *zA4
18208 ){
18209   ShellState *p = (ShellState*)pClientData;
18210   static const char *azAction[] = { 0,
18211      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
18212      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
18213      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
18214      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
18215      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
18216      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
18217      "PRAGMA",               "READ",                 "SELECT",
18218      "TRANSACTION",          "UPDATE",               "ATTACH",
18219      "DETACH",               "ALTER_TABLE",          "REINDEX",
18220      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
18221      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
18222   };
18223   int i;
18224   const char *az[4];
18225   az[0] = zA1;
18226   az[1] = zA2;
18227   az[2] = zA3;
18228   az[3] = zA4;
18229   utf8_printf(p->out, "authorizer: %s", azAction[op]);
18230   for(i=0; i<4; i++){
18231     raw_printf(p->out, " ");
18232     if( az[i] ){
18233       output_c_string(p->out, az[i]);
18234     }else{
18235       raw_printf(p->out, "NULL");
18236     }
18237   }
18238   raw_printf(p->out, "\n");
18239   if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
18240   return SQLITE_OK;
18241 }
18242 #endif
18243 
18244 /*
18245 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
18246 **
18247 ** This routine converts some CREATE TABLE statements for shadow tables
18248 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
18249 **
18250 ** If the schema statement in z[] contains a start-of-comment and if
18251 ** sqlite3_complete() returns false, try to terminate the comment before
18252 ** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
18253 */
18254 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
18255   char *zToFree = 0;
18256   if( z==0 ) return;
18257   if( zTail==0 ) return;
18258   if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
18259     const char *zOrig = z;
18260     static const char *azTerm[] = { "", "*/", "\n" };
18261     int i;
18262     for(i=0; i<ArraySize(azTerm); i++){
18263       char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
18264       shell_check_oom(zNew);
18265       if( sqlite3_complete(zNew) ){
18266         size_t n = strlen(zNew);
18267         zNew[n-1] = 0;
18268         zToFree = zNew;
18269         z = zNew;
18270         break;
18271       }
18272       sqlite3_free(zNew);
18273     }
18274   }
18275   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
18276     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
18277   }else{
18278     utf8_printf(out, "%s%s", z, zTail);
18279   }
18280   sqlite3_free(zToFree);
18281 }
18282 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
18283   char c = z[n];
18284   z[n] = 0;
18285   printSchemaLine(out, z, zTail);
18286   z[n] = c;
18287 }
18288 
18289 /*
18290 ** Return true if string z[] has nothing but whitespace and comments to the
18291 ** end of the first line.
18292 */
18293 static int wsToEol(const char *z){
18294   int i;
18295   for(i=0; z[i]; i++){
18296     if( z[i]=='\n' ) return 1;
18297     if( IsSpace(z[i]) ) continue;
18298     if( z[i]=='-' && z[i+1]=='-' ) return 1;
18299     return 0;
18300   }
18301   return 1;
18302 }
18303 
18304 /*
18305 ** Add a new entry to the EXPLAIN QUERY PLAN data
18306 */
18307 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
18308   EQPGraphRow *pNew;
18309   i64 nText;
18310   if( zText==0 ) return;
18311   nText = strlen(zText);
18312   if( p->autoEQPtest ){
18313     utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
18314   }
18315   pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
18316   shell_check_oom(pNew);
18317   pNew->iEqpId = iEqpId;
18318   pNew->iParentId = p2;
18319   memcpy(pNew->zText, zText, nText+1);
18320   pNew->pNext = 0;
18321   if( p->sGraph.pLast ){
18322     p->sGraph.pLast->pNext = pNew;
18323   }else{
18324     p->sGraph.pRow = pNew;
18325   }
18326   p->sGraph.pLast = pNew;
18327 }
18328 
18329 /*
18330 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
18331 ** in p->sGraph.
18332 */
18333 static void eqp_reset(ShellState *p){
18334   EQPGraphRow *pRow, *pNext;
18335   for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
18336     pNext = pRow->pNext;
18337     sqlite3_free(pRow);
18338   }
18339   memset(&p->sGraph, 0, sizeof(p->sGraph));
18340 }
18341 
18342 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
18343 ** pOld, or return the first such line if pOld is NULL
18344 */
18345 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
18346   EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
18347   while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
18348   return pRow;
18349 }
18350 
18351 /* Render a single level of the graph that has iEqpId as its parent.  Called
18352 ** recursively to render sublevels.
18353 */
18354 static void eqp_render_level(ShellState *p, int iEqpId){
18355   EQPGraphRow *pRow, *pNext;
18356   i64 n = strlen(p->sGraph.zPrefix);
18357   char *z;
18358   for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
18359     pNext = eqp_next_row(p, iEqpId, pRow);
18360     z = pRow->zText;
18361     utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
18362                 pNext ? "|--" : "`--", z);
18363     if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
18364       memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
18365       eqp_render_level(p, pRow->iEqpId);
18366       p->sGraph.zPrefix[n] = 0;
18367     }
18368   }
18369 }
18370 
18371 /*
18372 ** Display and reset the EXPLAIN QUERY PLAN data
18373 */
18374 static void eqp_render(ShellState *p, i64 nCycle){
18375   EQPGraphRow *pRow = p->sGraph.pRow;
18376   if( pRow ){
18377     if( pRow->zText[0]=='-' ){
18378       if( pRow->pNext==0 ){
18379         eqp_reset(p);
18380         return;
18381       }
18382       utf8_printf(p->out, "%s\n", pRow->zText+3);
18383       p->sGraph.pRow = pRow->pNext;
18384       sqlite3_free(pRow);
18385     }else if( nCycle>0 ){
18386       utf8_printf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
18387     }else{
18388       utf8_printf(p->out, "QUERY PLAN\n");
18389     }
18390     p->sGraph.zPrefix[0] = 0;
18391     eqp_render_level(p, 0);
18392     eqp_reset(p);
18393   }
18394 }
18395 
18396 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
18397 /*
18398 ** Progress handler callback.
18399 */
18400 static int progress_handler(void *pClientData) {
18401   ShellState *p = (ShellState*)pClientData;
18402   p->nProgress++;
18403   if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
18404     raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
18405     if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
18406     if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
18407     return 1;
18408   }
18409   if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
18410     raw_printf(p->out, "Progress %u\n", p->nProgress);
18411   }
18412   return 0;
18413 }
18414 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
18415 
18416 /*
18417 ** Print N dashes
18418 */
18419 static void print_dashes(FILE *out, int N){
18420   const char zDash[] = "--------------------------------------------------";
18421   const int nDash = sizeof(zDash) - 1;
18422   while( N>nDash ){
18423     fputs(zDash, out);
18424     N -= nDash;
18425   }
18426   raw_printf(out, "%.*s", N, zDash);
18427 }
18428 
18429 /*
18430 ** Print a markdown or table-style row separator using ascii-art
18431 */
18432 static void print_row_separator(
18433   ShellState *p,
18434   int nArg,
18435   const char *zSep
18436 ){
18437   int i;
18438   if( nArg>0 ){
18439     fputs(zSep, p->out);
18440     print_dashes(p->out, p->actualWidth[0]+2);
18441     for(i=1; i<nArg; i++){
18442       fputs(zSep, p->out);
18443       print_dashes(p->out, p->actualWidth[i]+2);
18444     }
18445     fputs(zSep, p->out);
18446   }
18447   fputs("\n", p->out);
18448 }
18449 
18450 /*
18451 ** This is the callback routine that the shell
18452 ** invokes for each row of a query result.
18453 */
18454 static int shell_callback(
18455   void *pArg,
18456   int nArg,        /* Number of result columns */
18457   char **azArg,    /* Text of each result column */
18458   char **azCol,    /* Column names */
18459   int *aiType      /* Column types.  Might be NULL */
18460 ){
18461   int i;
18462   ShellState *p = (ShellState*)pArg;
18463 
18464   if( azArg==0 ) return 0;
18465   switch( p->cMode ){
18466     case MODE_Count:
18467     case MODE_Off: {
18468       break;
18469     }
18470     case MODE_Line: {
18471       int w = 5;
18472       if( azArg==0 ) break;
18473       for(i=0; i<nArg; i++){
18474         int len = strlen30(azCol[i] ? azCol[i] : "");
18475         if( len>w ) w = len;
18476       }
18477       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
18478       for(i=0; i<nArg; i++){
18479         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
18480                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
18481       }
18482       break;
18483     }
18484     case MODE_ScanExp:
18485     case MODE_Explain: {
18486       static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
18487       static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
18488       static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
18489       static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
18490 
18491       const int *aWidth = aExplainWidth;
18492       const int *aMap = aExplainMap;
18493       int nWidth = ArraySize(aExplainWidth);
18494       int iIndent = 1;
18495 
18496       if( p->cMode==MODE_ScanExp ){
18497         aWidth = aScanExpWidth;
18498         aMap = aScanExpMap;
18499         nWidth = ArraySize(aScanExpWidth);
18500         iIndent = 3;
18501       }
18502       if( nArg>nWidth ) nArg = nWidth;
18503 
18504       /* If this is the first row seen, print out the headers */
18505       if( p->cnt++==0 ){
18506         for(i=0; i<nArg; i++){
18507           utf8_width_print(p->out, aWidth[i], azCol[ aMap[i] ]);
18508           fputs(i==nArg-1 ? "\n" : "  ", p->out);
18509         }
18510         for(i=0; i<nArg; i++){
18511           print_dashes(p->out, aWidth[i]);
18512           fputs(i==nArg-1 ? "\n" : "  ", p->out);
18513         }
18514       }
18515 
18516       /* If there is no data, exit early. */
18517       if( azArg==0 ) break;
18518 
18519       for(i=0; i<nArg; i++){
18520         const char *zSep = "  ";
18521         int w = aWidth[i];
18522         const char *zVal = azArg[ aMap[i] ];
18523         if( i==nArg-1 ) w = 0;
18524         if( zVal && strlenChar(zVal)>w ){
18525           w = strlenChar(zVal);
18526           zSep = " ";
18527         }
18528         if( i==iIndent && p->aiIndent && p->pStmt ){
18529           if( p->iIndent<p->nIndent ){
18530             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
18531           }
18532           p->iIndent++;
18533         }
18534         utf8_width_print(p->out, w, zVal ? zVal : p->nullValue);
18535         fputs(i==nArg-1 ? "\n" : zSep, p->out);
18536       }
18537       break;
18538     }
18539     case MODE_Semi: {   /* .schema and .fullschema output */
18540       printSchemaLine(p->out, azArg[0], ";\n");
18541       break;
18542     }
18543     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
18544       char *z;
18545       int j;
18546       int nParen = 0;
18547       char cEnd = 0;
18548       char c;
18549       int nLine = 0;
18550       assert( nArg==1 );
18551       if( azArg[0]==0 ) break;
18552       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
18553        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
18554       ){
18555         utf8_printf(p->out, "%s;\n", azArg[0]);
18556         break;
18557       }
18558       z = sqlite3_mprintf("%s", azArg[0]);
18559       shell_check_oom(z);
18560       j = 0;
18561       for(i=0; IsSpace(z[i]); i++){}
18562       for(; (c = z[i])!=0; i++){
18563         if( IsSpace(c) ){
18564           if( z[j-1]=='\r' ) z[j-1] = '\n';
18565           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
18566         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
18567           j--;
18568         }
18569         z[j++] = c;
18570       }
18571       while( j>0 && IsSpace(z[j-1]) ){ j--; }
18572       z[j] = 0;
18573       if( strlen30(z)>=79 ){
18574         for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
18575           if( c==cEnd ){
18576             cEnd = 0;
18577           }else if( c=='"' || c=='\'' || c=='`' ){
18578             cEnd = c;
18579           }else if( c=='[' ){
18580             cEnd = ']';
18581           }else if( c=='-' && z[i+1]=='-' ){
18582             cEnd = '\n';
18583           }else if( c=='(' ){
18584             nParen++;
18585           }else if( c==')' ){
18586             nParen--;
18587             if( nLine>0 && nParen==0 && j>0 ){
18588               printSchemaLineN(p->out, z, j, "\n");
18589               j = 0;
18590             }
18591           }
18592           z[j++] = c;
18593           if( nParen==1 && cEnd==0
18594            && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
18595           ){
18596             if( c=='\n' ) j--;
18597             printSchemaLineN(p->out, z, j, "\n  ");
18598             j = 0;
18599             nLine++;
18600             while( IsSpace(z[i+1]) ){ i++; }
18601           }
18602         }
18603         z[j] = 0;
18604       }
18605       printSchemaLine(p->out, z, ";\n");
18606       sqlite3_free(z);
18607       break;
18608     }
18609     case MODE_List: {
18610       if( p->cnt++==0 && p->showHeader ){
18611         for(i=0; i<nArg; i++){
18612           utf8_printf(p->out,"%s%s",azCol[i],
18613                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
18614         }
18615       }
18616       if( azArg==0 ) break;
18617       for(i=0; i<nArg; i++){
18618         char *z = azArg[i];
18619         if( z==0 ) z = p->nullValue;
18620         utf8_printf(p->out, "%s", z);
18621         if( i<nArg-1 ){
18622           utf8_printf(p->out, "%s", p->colSeparator);
18623         }else{
18624           utf8_printf(p->out, "%s", p->rowSeparator);
18625         }
18626       }
18627       break;
18628     }
18629     case MODE_Html: {
18630       if( p->cnt++==0 && p->showHeader ){
18631         raw_printf(p->out,"<TR>");
18632         for(i=0; i<nArg; i++){
18633           raw_printf(p->out,"<TH>");
18634           output_html_string(p->out, azCol[i]);
18635           raw_printf(p->out,"</TH>\n");
18636         }
18637         raw_printf(p->out,"</TR>\n");
18638       }
18639       if( azArg==0 ) break;
18640       raw_printf(p->out,"<TR>");
18641       for(i=0; i<nArg; i++){
18642         raw_printf(p->out,"<TD>");
18643         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
18644         raw_printf(p->out,"</TD>\n");
18645       }
18646       raw_printf(p->out,"</TR>\n");
18647       break;
18648     }
18649     case MODE_Tcl: {
18650       if( p->cnt++==0 && p->showHeader ){
18651         for(i=0; i<nArg; i++){
18652           output_c_string(p->out,azCol[i] ? azCol[i] : "");
18653           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
18654         }
18655         utf8_printf(p->out, "%s", p->rowSeparator);
18656       }
18657       if( azArg==0 ) break;
18658       for(i=0; i<nArg; i++){
18659         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
18660         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
18661       }
18662       utf8_printf(p->out, "%s", p->rowSeparator);
18663       break;
18664     }
18665     case MODE_Csv: {
18666       setBinaryMode(p->out, 1);
18667       if( p->cnt++==0 && p->showHeader ){
18668         for(i=0; i<nArg; i++){
18669           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
18670         }
18671         utf8_printf(p->out, "%s", p->rowSeparator);
18672       }
18673       if( nArg>0 ){
18674         for(i=0; i<nArg; i++){
18675           output_csv(p, azArg[i], i<nArg-1);
18676         }
18677         utf8_printf(p->out, "%s", p->rowSeparator);
18678       }
18679       setTextMode(p->out, 1);
18680       break;
18681     }
18682     case MODE_Insert: {
18683       if( azArg==0 ) break;
18684       utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
18685       if( p->showHeader ){
18686         raw_printf(p->out,"(");
18687         for(i=0; i<nArg; i++){
18688           if( i>0 ) raw_printf(p->out, ",");
18689           if( quoteChar(azCol[i]) ){
18690             char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
18691             shell_check_oom(z);
18692             utf8_printf(p->out, "%s", z);
18693             sqlite3_free(z);
18694           }else{
18695             raw_printf(p->out, "%s", azCol[i]);
18696           }
18697         }
18698         raw_printf(p->out,")");
18699       }
18700       p->cnt++;
18701       for(i=0; i<nArg; i++){
18702         raw_printf(p->out, i>0 ? "," : " VALUES(");
18703         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
18704           utf8_printf(p->out,"NULL");
18705         }else if( aiType && aiType[i]==SQLITE_TEXT ){
18706           if( ShellHasFlag(p, SHFLG_Newlines) ){
18707             output_quoted_string(p->out, azArg[i]);
18708           }else{
18709             output_quoted_escaped_string(p->out, azArg[i]);
18710           }
18711         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
18712           utf8_printf(p->out,"%s", azArg[i]);
18713         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
18714           char z[50];
18715           double r = sqlite3_column_double(p->pStmt, i);
18716           sqlite3_uint64 ur;
18717           memcpy(&ur,&r,sizeof(r));
18718           if( ur==0x7ff0000000000000LL ){
18719             raw_printf(p->out, "9.0e+999");
18720           }else if( ur==0xfff0000000000000LL ){
18721             raw_printf(p->out, "-9.0e+999");
18722           }else{
18723             sqlite3_int64 ir = (sqlite3_int64)r;
18724             if( r==(double)ir ){
18725               sqlite3_snprintf(50,z,"%lld.0", ir);
18726             }else{
18727               sqlite3_snprintf(50,z,"%!.20g", r);
18728             }
18729             raw_printf(p->out, "%s", z);
18730           }
18731         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
18732           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
18733           int nBlob = sqlite3_column_bytes(p->pStmt, i);
18734           output_hex_blob(p->out, pBlob, nBlob);
18735         }else if( isNumber(azArg[i], 0) ){
18736           utf8_printf(p->out,"%s", azArg[i]);
18737         }else if( ShellHasFlag(p, SHFLG_Newlines) ){
18738           output_quoted_string(p->out, azArg[i]);
18739         }else{
18740           output_quoted_escaped_string(p->out, azArg[i]);
18741         }
18742       }
18743       raw_printf(p->out,");\n");
18744       break;
18745     }
18746     case MODE_Json: {
18747       if( azArg==0 ) break;
18748       if( p->cnt==0 ){
18749         fputs("[{", p->out);
18750       }else{
18751         fputs(",\n{", p->out);
18752       }
18753       p->cnt++;
18754       for(i=0; i<nArg; i++){
18755         output_json_string(p->out, azCol[i], -1);
18756         putc(':', p->out);
18757         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
18758           fputs("null",p->out);
18759         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
18760           char z[50];
18761           double r = sqlite3_column_double(p->pStmt, i);
18762           sqlite3_uint64 ur;
18763           memcpy(&ur,&r,sizeof(r));
18764           if( ur==0x7ff0000000000000LL ){
18765             raw_printf(p->out, "9.0e+999");
18766           }else if( ur==0xfff0000000000000LL ){
18767             raw_printf(p->out, "-9.0e+999");
18768           }else{
18769             sqlite3_snprintf(50,z,"%!.20g", r);
18770             raw_printf(p->out, "%s", z);
18771           }
18772         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
18773           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
18774           int nBlob = sqlite3_column_bytes(p->pStmt, i);
18775           output_json_string(p->out, pBlob, nBlob);
18776         }else if( aiType && aiType[i]==SQLITE_TEXT ){
18777           output_json_string(p->out, azArg[i], -1);
18778         }else{
18779           utf8_printf(p->out,"%s", azArg[i]);
18780         }
18781         if( i<nArg-1 ){
18782           putc(',', p->out);
18783         }
18784       }
18785       putc('}', p->out);
18786       break;
18787     }
18788     case MODE_Quote: {
18789       if( azArg==0 ) break;
18790       if( p->cnt==0 && p->showHeader ){
18791         for(i=0; i<nArg; i++){
18792           if( i>0 ) fputs(p->colSeparator, p->out);
18793           output_quoted_string(p->out, azCol[i]);
18794         }
18795         fputs(p->rowSeparator, p->out);
18796       }
18797       p->cnt++;
18798       for(i=0; i<nArg; i++){
18799         if( i>0 ) fputs(p->colSeparator, p->out);
18800         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
18801           utf8_printf(p->out,"NULL");
18802         }else if( aiType && aiType[i]==SQLITE_TEXT ){
18803           output_quoted_string(p->out, azArg[i]);
18804         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
18805           utf8_printf(p->out,"%s", azArg[i]);
18806         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
18807           char z[50];
18808           double r = sqlite3_column_double(p->pStmt, i);
18809           sqlite3_snprintf(50,z,"%!.20g", r);
18810           raw_printf(p->out, "%s", z);
18811         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
18812           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
18813           int nBlob = sqlite3_column_bytes(p->pStmt, i);
18814           output_hex_blob(p->out, pBlob, nBlob);
18815         }else if( isNumber(azArg[i], 0) ){
18816           utf8_printf(p->out,"%s", azArg[i]);
18817         }else{
18818           output_quoted_string(p->out, azArg[i]);
18819         }
18820       }
18821       fputs(p->rowSeparator, p->out);
18822       break;
18823     }
18824     case MODE_Ascii: {
18825       if( p->cnt++==0 && p->showHeader ){
18826         for(i=0; i<nArg; i++){
18827           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
18828           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
18829         }
18830         utf8_printf(p->out, "%s", p->rowSeparator);
18831       }
18832       if( azArg==0 ) break;
18833       for(i=0; i<nArg; i++){
18834         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
18835         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
18836       }
18837       utf8_printf(p->out, "%s", p->rowSeparator);
18838       break;
18839     }
18840     case MODE_EQP: {
18841       eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
18842       break;
18843     }
18844   }
18845   return 0;
18846 }
18847 
18848 /*
18849 ** This is the callback routine that the SQLite library
18850 ** invokes for each row of a query result.
18851 */
18852 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
18853   /* since we don't have type info, call the shell_callback with a NULL value */
18854   return shell_callback(pArg, nArg, azArg, azCol, NULL);
18855 }
18856 
18857 /*
18858 ** This is the callback routine from sqlite3_exec() that appends all
18859 ** output onto the end of a ShellText object.
18860 */
18861 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
18862   ShellText *p = (ShellText*)pArg;
18863   int i;
18864   UNUSED_PARAMETER(az);
18865   if( azArg==0 ) return 0;
18866   if( p->n ) appendText(p, "|", 0);
18867   for(i=0; i<nArg; i++){
18868     if( i ) appendText(p, ",", 0);
18869     if( azArg[i] ) appendText(p, azArg[i], 0);
18870   }
18871   return 0;
18872 }
18873 
18874 /*
18875 ** Generate an appropriate SELFTEST table in the main database.
18876 */
18877 static void createSelftestTable(ShellState *p){
18878   char *zErrMsg = 0;
18879   sqlite3_exec(p->db,
18880     "SAVEPOINT selftest_init;\n"
18881     "CREATE TABLE IF NOT EXISTS selftest(\n"
18882     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
18883     "  op TEXT,\n"                   /* Operator:  memo run */
18884     "  cmd TEXT,\n"                  /* Command text */
18885     "  ans TEXT\n"                   /* Desired answer */
18886     ");"
18887     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
18888     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
18889     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
18890     "         'memo','Tests generated by --init');\n"
18891     "INSERT INTO [_shell$self]\n"
18892     "  SELECT 'run',\n"
18893     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
18894                                  "FROM sqlite_schema ORDER BY 2'',224))',\n"
18895     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
18896                           "FROM sqlite_schema ORDER BY 2',224));\n"
18897     "INSERT INTO [_shell$self]\n"
18898     "  SELECT 'run',"
18899     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
18900     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
18901     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
18902     "  FROM (\n"
18903     "    SELECT name FROM sqlite_schema\n"
18904     "     WHERE type='table'\n"
18905     "       AND name<>'selftest'\n"
18906     "       AND coalesce(rootpage,0)>0\n"
18907     "  )\n"
18908     " ORDER BY name;\n"
18909     "INSERT INTO [_shell$self]\n"
18910     "  VALUES('run','PRAGMA integrity_check','ok');\n"
18911     "INSERT INTO selftest(tno,op,cmd,ans)"
18912     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
18913     "DROP TABLE [_shell$self];"
18914     ,0,0,&zErrMsg);
18915   if( zErrMsg ){
18916     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
18917     sqlite3_free(zErrMsg);
18918   }
18919   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
18920 }
18921 
18922 
18923 /*
18924 ** Set the destination table field of the ShellState structure to
18925 ** the name of the table given.  Escape any quote characters in the
18926 ** table name.
18927 */
18928 static void set_table_name(ShellState *p, const char *zName){
18929   int i, n;
18930   char cQuote;
18931   char *z;
18932 
18933   if( p->zDestTable ){
18934     free(p->zDestTable);
18935     p->zDestTable = 0;
18936   }
18937   if( zName==0 ) return;
18938   cQuote = quoteChar(zName);
18939   n = strlen30(zName);
18940   if( cQuote ) n += n+2;
18941   z = p->zDestTable = malloc( n+1 );
18942   shell_check_oom(z);
18943   n = 0;
18944   if( cQuote ) z[n++] = cQuote;
18945   for(i=0; zName[i]; i++){
18946     z[n++] = zName[i];
18947     if( zName[i]==cQuote ) z[n++] = cQuote;
18948   }
18949   if( cQuote ) z[n++] = cQuote;
18950   z[n] = 0;
18951 }
18952 
18953 /*
18954 ** Maybe construct two lines of text that point out the position of a
18955 ** syntax error.  Return a pointer to the text, in memory obtained from
18956 ** sqlite3_malloc().  Or, if the most recent error does not involve a
18957 ** specific token that we can point to, return an empty string.
18958 **
18959 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
18960 ** and should be released by the caller invoking sqlite3_free().
18961 */
18962 static char *shell_error_context(const char *zSql, sqlite3 *db){
18963   int iOffset;
18964   size_t len;
18965   char *zCode;
18966   char *zMsg;
18967   int i;
18968   if( db==0
18969    || zSql==0
18970    || (iOffset = sqlite3_error_offset(db))<0
18971    || iOffset>=(int)strlen(zSql)
18972   ){
18973     return sqlite3_mprintf("");
18974   }
18975   while( iOffset>50 ){
18976     iOffset--;
18977     zSql++;
18978     while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
18979   }
18980   len = strlen(zSql);
18981   if( len>78 ){
18982     len = 78;
18983     while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
18984   }
18985   zCode = sqlite3_mprintf("%.*s", len, zSql);
18986   shell_check_oom(zCode);
18987   for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
18988   if( iOffset<25 ){
18989     zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
18990   }else{
18991     zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
18992   }
18993   return zMsg;
18994 }
18995 
18996 
18997 /*
18998 ** Execute a query statement that will generate SQL output.  Print
18999 ** the result columns, comma-separated, on a line and then add a
19000 ** semicolon terminator to the end of that line.
19001 **
19002 ** If the number of columns is 1 and that column contains text "--"
19003 ** then write the semicolon on a separate line.  That way, if a
19004 ** "--" comment occurs at the end of the statement, the comment
19005 ** won't consume the semicolon terminator.
19006 */
19007 static int run_table_dump_query(
19008   ShellState *p,           /* Query context */
19009   const char *zSelect      /* SELECT statement to extract content */
19010 ){
19011   sqlite3_stmt *pSelect;
19012   int rc;
19013   int nResult;
19014   int i;
19015   const char *z;
19016   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
19017   if( rc!=SQLITE_OK || !pSelect ){
19018     char *zContext = shell_error_context(zSelect, p->db);
19019     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
19020                 sqlite3_errmsg(p->db), zContext);
19021     sqlite3_free(zContext);
19022     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19023     return rc;
19024   }
19025   rc = sqlite3_step(pSelect);
19026   nResult = sqlite3_column_count(pSelect);
19027   while( rc==SQLITE_ROW ){
19028     z = (const char*)sqlite3_column_text(pSelect, 0);
19029     utf8_printf(p->out, "%s", z);
19030     for(i=1; i<nResult; i++){
19031       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
19032     }
19033     if( z==0 ) z = "";
19034     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
19035     if( z[0] ){
19036       raw_printf(p->out, "\n;\n");
19037     }else{
19038       raw_printf(p->out, ";\n");
19039     }
19040     rc = sqlite3_step(pSelect);
19041   }
19042   rc = sqlite3_finalize(pSelect);
19043   if( rc!=SQLITE_OK ){
19044     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
19045                 sqlite3_errmsg(p->db));
19046     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
19047   }
19048   return rc;
19049 }
19050 
19051 /*
19052 ** Allocate space and save off string indicating current error.
19053 */
19054 static char *save_err_msg(
19055   sqlite3 *db,           /* Database to query */
19056   const char *zPhase,    /* When the error occurs */
19057   int rc,                /* Error code returned from API */
19058   const char *zSql       /* SQL string, or NULL */
19059 ){
19060   char *zErr;
19061   char *zContext;
19062   sqlite3_str *pStr = sqlite3_str_new(0);
19063   sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
19064   if( rc>1 ){
19065     sqlite3_str_appendf(pStr, " (%d)", rc);
19066   }
19067   zContext = shell_error_context(zSql, db);
19068   if( zContext ){
19069     sqlite3_str_appendall(pStr, zContext);
19070     sqlite3_free(zContext);
19071   }
19072   zErr = sqlite3_str_finish(pStr);
19073   shell_check_oom(zErr);
19074   return zErr;
19075 }
19076 
19077 #ifdef __linux__
19078 /*
19079 ** Attempt to display I/O stats on Linux using /proc/PID/io
19080 */
19081 static void displayLinuxIoStats(FILE *out){
19082   FILE *in;
19083   char z[200];
19084   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
19085   in = fopen(z, "rb");
19086   if( in==0 ) return;
19087   while( fgets(z, sizeof(z), in)!=0 ){
19088     static const struct {
19089       const char *zPattern;
19090       const char *zDesc;
19091     } aTrans[] = {
19092       { "rchar: ",                  "Bytes received by read():" },
19093       { "wchar: ",                  "Bytes sent to write():"    },
19094       { "syscr: ",                  "Read() system calls:"      },
19095       { "syscw: ",                  "Write() system calls:"     },
19096       { "read_bytes: ",             "Bytes read from storage:"  },
19097       { "write_bytes: ",            "Bytes written to storage:" },
19098       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
19099     };
19100     int i;
19101     for(i=0; i<ArraySize(aTrans); i++){
19102       int n = strlen30(aTrans[i].zPattern);
19103       if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
19104         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
19105         break;
19106       }
19107     }
19108   }
19109   fclose(in);
19110 }
19111 #endif
19112 
19113 /*
19114 ** Display a single line of status using 64-bit values.
19115 */
19116 static void displayStatLine(
19117   ShellState *p,            /* The shell context */
19118   char *zLabel,             /* Label for this one line */
19119   char *zFormat,            /* Format for the result */
19120   int iStatusCtrl,          /* Which status to display */
19121   int bReset                /* True to reset the stats */
19122 ){
19123   sqlite3_int64 iCur = -1;
19124   sqlite3_int64 iHiwtr = -1;
19125   int i, nPercent;
19126   char zLine[200];
19127   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
19128   for(i=0, nPercent=0; zFormat[i]; i++){
19129     if( zFormat[i]=='%' ) nPercent++;
19130   }
19131   if( nPercent>1 ){
19132     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
19133   }else{
19134     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
19135   }
19136   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
19137 }
19138 
19139 /*
19140 ** Display memory stats.
19141 */
19142 static int display_stats(
19143   sqlite3 *db,                /* Database to query */
19144   ShellState *pArg,           /* Pointer to ShellState */
19145   int bReset                  /* True to reset the stats */
19146 ){
19147   int iCur;
19148   int iHiwtr;
19149   FILE *out;
19150   if( pArg==0 || pArg->out==0 ) return 0;
19151   out = pArg->out;
19152 
19153   if( pArg->pStmt && pArg->statsOn==2 ){
19154     int nCol, i, x;
19155     sqlite3_stmt *pStmt = pArg->pStmt;
19156     char z[100];
19157     nCol = sqlite3_column_count(pStmt);
19158     raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
19159     for(i=0; i<nCol; i++){
19160       sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
19161       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
19162 #ifndef SQLITE_OMIT_DECLTYPE
19163       sqlite3_snprintf(30, z+x, "declared type:");
19164       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
19165 #endif
19166 #ifdef SQLITE_ENABLE_COLUMN_METADATA
19167       sqlite3_snprintf(30, z+x, "database name:");
19168       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
19169       sqlite3_snprintf(30, z+x, "table name:");
19170       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
19171       sqlite3_snprintf(30, z+x, "origin name:");
19172       utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
19173 #endif
19174     }
19175   }
19176 
19177   if( pArg->statsOn==3 ){
19178     if( pArg->pStmt ){
19179       iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
19180       raw_printf(pArg->out, "VM-steps: %d\n", iCur);
19181     }
19182     return 0;
19183   }
19184 
19185   displayStatLine(pArg, "Memory Used:",
19186      "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
19187   displayStatLine(pArg, "Number of Outstanding Allocations:",
19188      "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
19189   if( pArg->shellFlgs & SHFLG_Pagecache ){
19190     displayStatLine(pArg, "Number of Pcache Pages Used:",
19191        "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
19192   }
19193   displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
19194      "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
19195   displayStatLine(pArg, "Largest Allocation:",
19196      "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
19197   displayStatLine(pArg, "Largest Pcache Allocation:",
19198      "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
19199 #ifdef YYTRACKMAXSTACKDEPTH
19200   displayStatLine(pArg, "Deepest Parser Stack:",
19201      "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
19202 #endif
19203 
19204   if( db ){
19205     if( pArg->shellFlgs & SHFLG_Lookaside ){
19206       iHiwtr = iCur = -1;
19207       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
19208                         &iCur, &iHiwtr, bReset);
19209       raw_printf(pArg->out,
19210               "Lookaside Slots Used:                %d (max %d)\n",
19211               iCur, iHiwtr);
19212       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
19213                         &iCur, &iHiwtr, bReset);
19214       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
19215               iHiwtr);
19216       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
19217                         &iCur, &iHiwtr, bReset);
19218       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
19219               iHiwtr);
19220       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
19221                         &iCur, &iHiwtr, bReset);
19222       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
19223               iHiwtr);
19224     }
19225     iHiwtr = iCur = -1;
19226     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
19227     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
19228             iCur);
19229     iHiwtr = iCur = -1;
19230     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
19231     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
19232     iHiwtr = iCur = -1;
19233     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
19234     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
19235     iHiwtr = iCur = -1;
19236     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
19237     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
19238     iHiwtr = iCur = -1;
19239     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
19240     raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
19241     iHiwtr = iCur = -1;
19242     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
19243     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
19244             iCur);
19245     iHiwtr = iCur = -1;
19246     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
19247     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
19248             iCur);
19249   }
19250 
19251   if( pArg->pStmt ){
19252     int iHit, iMiss;
19253     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
19254                                bReset);
19255     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
19256     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
19257     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
19258     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
19259     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
19260     iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
19261                                bReset);
19262     iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
19263                                 bReset);
19264     if( iHit || iMiss ){
19265       raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
19266             iHit, iHit+iMiss);
19267     }
19268     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
19269     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
19270     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
19271     raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
19272     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
19273     raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
19274     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
19275     raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
19276   }
19277 
19278 #ifdef __linux__
19279   displayLinuxIoStats(pArg->out);
19280 #endif
19281 
19282   /* Do not remove this machine readable comment: extra-stats-output-here */
19283 
19284   return 0;
19285 }
19286 
19287 
19288 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
19289 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
19290   int iPid = 0;
19291   int ret = 1;
19292   sqlite3_stmt_scanstatus_v2(p, iEntry,
19293       SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
19294   );
19295   while( iPid!=0 ){
19296     int ii;
19297     for(ii=0; 1; ii++){
19298       int iId;
19299       int res;
19300       res = sqlite3_stmt_scanstatus_v2(p, ii,
19301           SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
19302       );
19303       if( res ) break;
19304       if( iId==iPid ){
19305         sqlite3_stmt_scanstatus_v2(p, ii,
19306             SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
19307         );
19308       }
19309     }
19310     ret++;
19311   }
19312   return ret;
19313 }
19314 #endif
19315 
19316 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
19317 static void display_explain_scanstats(
19318   sqlite3 *db,                    /* Database to query */
19319   ShellState *pArg                /* Pointer to ShellState */
19320 ){
19321   static const int f = SQLITE_SCANSTAT_COMPLEX;
19322   sqlite3_stmt *p = pArg->pStmt;
19323   int ii = 0;
19324   i64 nTotal = 0;
19325   int nWidth = 0;
19326   eqp_reset(pArg);
19327 
19328   for(ii=0; 1; ii++){
19329     const char *z = 0;
19330     int n = 0;
19331     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
19332       break;
19333     }
19334     n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
19335     if( n>nWidth ) nWidth = n;
19336   }
19337   nWidth += 4;
19338 
19339   sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
19340   for(ii=0; 1; ii++){
19341     i64 nLoop = 0;
19342     i64 nRow = 0;
19343     i64 nCycle = 0;
19344     int iId = 0;
19345     int iPid = 0;
19346     const char *zo = 0;
19347     const char *zName = 0;
19348     char *zText = 0;
19349     double rEst = 0.0;
19350 
19351     if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
19352       break;
19353     }
19354     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
19355     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
19356     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
19357     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
19358     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
19359     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
19360     sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
19361 
19362     zText = sqlite3_mprintf("%s", zo);
19363     if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
19364       char *z = 0;
19365       if( nCycle>=0 && nTotal>0 ){
19366         z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
19367             nCycle, ((nCycle*100)+nTotal/2) / nTotal
19368         );
19369       }
19370       if( nLoop>=0 ){
19371         z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
19372       }
19373       if( nRow>=0 ){
19374         z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
19375       }
19376 
19377       if( zName && pArg->scanstatsOn>1 ){
19378         double rpl = (double)nRow / (double)nLoop;
19379         z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
19380       }
19381 
19382       zText = sqlite3_mprintf(
19383           "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
19384       );
19385     }
19386 
19387     eqp_append(pArg, iId, iPid, zText);
19388     sqlite3_free(zText);
19389   }
19390 
19391   eqp_render(pArg, nTotal);
19392 }
19393 #endif
19394 
19395 
19396 /*
19397 ** Parameter azArray points to a zero-terminated array of strings. zStr
19398 ** points to a single nul-terminated string. Return non-zero if zStr
19399 ** is equal, according to strcmp(), to any of the strings in the array.
19400 ** Otherwise, return zero.
19401 */
19402 static int str_in_array(const char *zStr, const char **azArray){
19403   int i;
19404   for(i=0; azArray[i]; i++){
19405     if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
19406   }
19407   return 0;
19408 }
19409 
19410 /*
19411 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
19412 ** and populate the ShellState.aiIndent[] array with the number of
19413 ** spaces each opcode should be indented before it is output.
19414 **
19415 ** The indenting rules are:
19416 **
19417 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
19418 **       all opcodes that occur between the p2 jump destination and the opcode
19419 **       itself by 2 spaces.
19420 **
19421 **     * Do the previous for "Return" instructions for when P2 is positive.
19422 **       See tag-20220407a in wherecode.c and vdbe.c.
19423 **
19424 **     * For each "Goto", if the jump destination is earlier in the program
19425 **       and ends on one of:
19426 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
19427 **       or if the P1 parameter is one instead of zero,
19428 **       then indent all opcodes between the earlier instruction
19429 **       and "Goto" by 2 spaces.
19430 */
19431 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
19432   int *abYield = 0;               /* True if op is an OP_Yield */
19433   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
19434   int iOp;                        /* Index of operation in p->aiIndent[] */
19435 
19436   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
19437                            "Return", 0 };
19438   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
19439                             "Rewind", 0 };
19440   const char *azGoto[] = { "Goto", 0 };
19441 
19442   /* The caller guarantees that the leftmost 4 columns of the statement
19443   ** passed to this function are equivalent to the leftmost 4 columns
19444   ** of EXPLAIN statement output. In practice the statement may be
19445   ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
19446   assert( sqlite3_column_count(pSql)>=4 );
19447   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
19448   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
19449   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
19450   assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
19451 
19452   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
19453     int i;
19454     int iAddr = sqlite3_column_int(pSql, 0);
19455     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
19456     int p1 = sqlite3_column_int(pSql, 2);
19457     int p2 = sqlite3_column_int(pSql, 3);
19458 
19459     /* Assuming that p2 is an instruction address, set variable p2op to the
19460     ** index of that instruction in the aiIndent[] array. p2 and p2op may be
19461     ** different if the current instruction is part of a sub-program generated
19462     ** by an SQL trigger or foreign key.  */
19463     int p2op = (p2 + (iOp-iAddr));
19464 
19465     /* Grow the p->aiIndent array as required */
19466     if( iOp>=nAlloc ){
19467       nAlloc += 100;
19468       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
19469       shell_check_oom(p->aiIndent);
19470       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
19471       shell_check_oom(abYield);
19472     }
19473 
19474     abYield[iOp] = str_in_array(zOp, azYield);
19475     p->aiIndent[iOp] = 0;
19476     p->nIndent = iOp+1;
19477     if( str_in_array(zOp, azNext) && p2op>0 ){
19478       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
19479     }
19480     if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
19481       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
19482     }
19483   }
19484 
19485   p->iIndent = 0;
19486   sqlite3_free(abYield);
19487   sqlite3_reset(pSql);
19488 }
19489 
19490 /*
19491 ** Free the array allocated by explain_data_prepare().
19492 */
19493 static void explain_data_delete(ShellState *p){
19494   sqlite3_free(p->aiIndent);
19495   p->aiIndent = 0;
19496   p->nIndent = 0;
19497   p->iIndent = 0;
19498 }
19499 
19500 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
19501 
19502 /*
19503 ** Display scan stats.
19504 */
19505 static void display_scanstats(
19506   sqlite3 *db,                    /* Database to query */
19507   ShellState *pArg                /* Pointer to ShellState */
19508 ){
19509 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
19510   UNUSED_PARAMETER(db);
19511   UNUSED_PARAMETER(pArg);
19512 #else
19513   if( pArg->scanstatsOn==3 ){
19514     const char *zSql =
19515       "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
19516       "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
19517       "   FROM bytecode(?)";
19518 
19519     int rc = SQLITE_OK;
19520     sqlite3_stmt *pStmt = 0;
19521     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
19522     if( rc==SQLITE_OK ){
19523       sqlite3_stmt *pSave = pArg->pStmt;
19524       pArg->pStmt = pStmt;
19525       sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
19526 
19527       pArg->cnt = 0;
19528       pArg->cMode = MODE_ScanExp;
19529       explain_data_prepare(pArg, pStmt);
19530       exec_prepared_stmt(pArg, pStmt);
19531       explain_data_delete(pArg);
19532 
19533       sqlite3_finalize(pStmt);
19534       pArg->pStmt = pSave;
19535     }
19536   }else{
19537     display_explain_scanstats(db, pArg);
19538   }
19539 #endif
19540 }
19541 
19542 /*
19543 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
19544 */
19545 static unsigned int savedSelectTrace;
19546 static unsigned int savedWhereTrace;
19547 static void disable_debug_trace_modes(void){
19548   unsigned int zero = 0;
19549   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
19550   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
19551   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
19552   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
19553 }
19554 static void restore_debug_trace_modes(void){
19555   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
19556   sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
19557 }
19558 
19559 /* Create the TEMP table used to store parameter bindings */
19560 static void bind_table_init(ShellState *p){
19561   int wrSchema = 0;
19562   int defensiveMode = 0;
19563   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
19564   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
19565   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
19566   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
19567   sqlite3_exec(p->db,
19568     "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
19569     "  key TEXT PRIMARY KEY,\n"
19570     "  value\n"
19571     ") WITHOUT ROWID;",
19572     0, 0, 0);
19573   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
19574   sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
19575 }
19576 
19577 /*
19578 ** Bind parameters on a prepared statement.
19579 **
19580 ** Parameter bindings are taken from a TEMP table of the form:
19581 **
19582 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
19583 **    WITHOUT ROWID;
19584 **
19585 ** No bindings occur if this table does not exist.  The name of the table
19586 ** begins with "sqlite_" so that it will not collide with ordinary application
19587 ** tables.  The table must be in the TEMP schema.
19588 */
19589 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
19590   int nVar;
19591   int i;
19592   int rc;
19593   sqlite3_stmt *pQ = 0;
19594 
19595   nVar = sqlite3_bind_parameter_count(pStmt);
19596   if( nVar==0 ) return;  /* Nothing to do */
19597   if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
19598                                     "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
19599     rc = SQLITE_NOTFOUND;
19600     pQ = 0;
19601   }else{
19602     rc = sqlite3_prepare_v2(pArg->db,
19603             "SELECT value FROM temp.sqlite_parameters"
19604             " WHERE key=?1", -1, &pQ, 0);
19605   }
19606   for(i=1; i<=nVar; i++){
19607     char zNum[30];
19608     const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
19609     if( zVar==0 ){
19610       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
19611       zVar = zNum;
19612     }
19613     sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
19614     if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
19615       sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
19616 #ifdef NAN
19617     }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
19618       sqlite3_bind_double(pStmt, i, NAN);
19619 #endif
19620 #ifdef INFINITY
19621     }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
19622       sqlite3_bind_double(pStmt, i, INFINITY);
19623 #endif
19624     }else{
19625       sqlite3_bind_null(pStmt, i);
19626     }
19627     sqlite3_reset(pQ);
19628   }
19629   sqlite3_finalize(pQ);
19630 }
19631 
19632 /*
19633 ** UTF8 box-drawing characters.  Imagine box lines like this:
19634 **
19635 **           1
19636 **           |
19637 **       4 --+-- 2
19638 **           |
19639 **           3
19640 **
19641 ** Each box characters has between 2 and 4 of the lines leading from
19642 ** the center.  The characters are here identified by the numbers of
19643 ** their corresponding lines.
19644 */
19645 #define BOX_24   "\342\224\200"  /* U+2500 --- */
19646 #define BOX_13   "\342\224\202"  /* U+2502  |  */
19647 #define BOX_23   "\342\224\214"  /* U+250c  ,- */
19648 #define BOX_34   "\342\224\220"  /* U+2510 -,  */
19649 #define BOX_12   "\342\224\224"  /* U+2514  '- */
19650 #define BOX_14   "\342\224\230"  /* U+2518 -'  */
19651 #define BOX_123  "\342\224\234"  /* U+251c  |- */
19652 #define BOX_134  "\342\224\244"  /* U+2524 -|  */
19653 #define BOX_234  "\342\224\254"  /* U+252c -,- */
19654 #define BOX_124  "\342\224\264"  /* U+2534 -'- */
19655 #define BOX_1234 "\342\224\274"  /* U+253c -|- */
19656 
19657 /* Draw horizontal line N characters long using unicode box
19658 ** characters
19659 */
19660 static void print_box_line(FILE *out, int N){
19661   const char zDash[] =
19662       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
19663       BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
19664   const int nDash = sizeof(zDash) - 1;
19665   N *= 3;
19666   while( N>nDash ){
19667     utf8_printf(out, zDash);
19668     N -= nDash;
19669   }
19670   utf8_printf(out, "%.*s", N, zDash);
19671 }
19672 
19673 /*
19674 ** Draw a horizontal separator for a MODE_Box table.
19675 */
19676 static void print_box_row_separator(
19677   ShellState *p,
19678   int nArg,
19679   const char *zSep1,
19680   const char *zSep2,
19681   const char *zSep3
19682 ){
19683   int i;
19684   if( nArg>0 ){
19685     utf8_printf(p->out, "%s", zSep1);
19686     print_box_line(p->out, p->actualWidth[0]+2);
19687     for(i=1; i<nArg; i++){
19688       utf8_printf(p->out, "%s", zSep2);
19689       print_box_line(p->out, p->actualWidth[i]+2);
19690     }
19691     utf8_printf(p->out, "%s", zSep3);
19692   }
19693   fputs("\n", p->out);
19694 }
19695 
19696 /*
19697 ** z[] is a line of text that is to be displayed the .mode box or table or
19698 ** similar tabular formats.  z[] might contain control characters such
19699 ** as \n, \t, \f, or \r.
19700 **
19701 ** Compute characters to display on the first line of z[].  Stop at the
19702 ** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
19703 ** from malloc()) of that first line, which caller should free sometime.
19704 ** Write anything to display on the next line into *pzTail.  If this is
19705 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
19706 */
19707 static char *translateForDisplayAndDup(
19708   const unsigned char *z,            /* Input text to be transformed */
19709   const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
19710   int mxWidth,                       /* Max width.  0 means no limit */
19711   u8 bWordWrap                       /* If true, avoid breaking mid-word */
19712 ){
19713   int i;                 /* Input bytes consumed */
19714   int j;                 /* Output bytes generated */
19715   int k;                 /* Input bytes to be displayed */
19716   int n;                 /* Output column number */
19717   unsigned char *zOut;   /* Output text */
19718 
19719   if( z==0 ){
19720     *pzTail = 0;
19721     return 0;
19722   }
19723   if( mxWidth<0 ) mxWidth = -mxWidth;
19724   if( mxWidth==0 ) mxWidth = 1000000;
19725   i = j = n = 0;
19726   while( n<mxWidth ){
19727     if( z[i]>=' ' ){
19728       n++;
19729       do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
19730       continue;
19731     }
19732     if( z[i]=='\t' ){
19733       do{
19734         n++;
19735         j++;
19736       }while( (n&7)!=0 && n<mxWidth );
19737       i++;
19738       continue;
19739     }
19740     break;
19741   }
19742   if( n>=mxWidth && bWordWrap  ){
19743     /* Perhaps try to back up to a better place to break the line */
19744     for(k=i; k>i/2; k--){
19745       if( isspace(z[k-1]) ) break;
19746     }
19747     if( k<=i/2 ){
19748       for(k=i; k>i/2; k--){
19749         if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
19750       }
19751     }
19752     if( k<=i/2 ){
19753       k = i;
19754     }else{
19755       i = k;
19756       while( z[i]==' ' ) i++;
19757     }
19758   }else{
19759     k = i;
19760   }
19761   if( n>=mxWidth && z[i]>=' ' ){
19762    *pzTail = &z[i];
19763   }else if( z[i]=='\r' && z[i+1]=='\n' ){
19764     *pzTail = z[i+2] ? &z[i+2] : 0;
19765   }else if( z[i]==0 || z[i+1]==0 ){
19766     *pzTail = 0;
19767   }else{
19768     *pzTail = &z[i+1];
19769   }
19770   zOut = malloc( j+1 );
19771   shell_check_oom(zOut);
19772   i = j = n = 0;
19773   while( i<k ){
19774     if( z[i]>=' ' ){
19775       n++;
19776       do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
19777       continue;
19778     }
19779     if( z[i]=='\t' ){
19780       do{
19781         n++;
19782         zOut[j++] = ' ';
19783       }while( (n&7)!=0 && n<mxWidth );
19784       i++;
19785       continue;
19786     }
19787     break;
19788   }
19789   zOut[j] = 0;
19790   return (char*)zOut;
19791 }
19792 
19793 /* Extract the value of the i-th current column for pStmt as an SQL literal
19794 ** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
19795 ** the caller.
19796 */
19797 static char *quoted_column(sqlite3_stmt *pStmt, int i){
19798   switch( sqlite3_column_type(pStmt, i) ){
19799     case SQLITE_NULL: {
19800       return sqlite3_mprintf("NULL");
19801     }
19802     case SQLITE_INTEGER:
19803     case SQLITE_FLOAT: {
19804       return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
19805     }
19806     case SQLITE_TEXT: {
19807       return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
19808     }
19809     case SQLITE_BLOB: {
19810       int j;
19811       sqlite3_str *pStr = sqlite3_str_new(0);
19812       const unsigned char *a = sqlite3_column_blob(pStmt,i);
19813       int n = sqlite3_column_bytes(pStmt,i);
19814       sqlite3_str_append(pStr, "x'", 2);
19815       for(j=0; j<n; j++){
19816         sqlite3_str_appendf(pStr, "%02x", a[j]);
19817       }
19818       sqlite3_str_append(pStr, "'", 1);
19819       return sqlite3_str_finish(pStr);
19820     }
19821   }
19822   return 0; /* Not reached */
19823 }
19824 
19825 /*
19826 ** Run a prepared statement and output the result in one of the
19827 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
19828 ** or MODE_Box.
19829 **
19830 ** This is different from ordinary exec_prepared_stmt() in that
19831 ** it has to run the entire query and gather the results into memory
19832 ** first, in order to determine column widths, before providing
19833 ** any output.
19834 */
19835 static void exec_prepared_stmt_columnar(
19836   ShellState *p,                        /* Pointer to ShellState */
19837   sqlite3_stmt *pStmt                   /* Statement to run */
19838 ){
19839   sqlite3_int64 nRow = 0;
19840   int nColumn = 0;
19841   char **azData = 0;
19842   sqlite3_int64 nAlloc = 0;
19843   char *abRowDiv = 0;
19844   const unsigned char *uz;
19845   const char *z;
19846   char **azQuoted = 0;
19847   int rc;
19848   sqlite3_int64 i, nData;
19849   int j, nTotal, w, n;
19850   const char *colSep = 0;
19851   const char *rowSep = 0;
19852   const unsigned char **azNextLine = 0;
19853   int bNextLine = 0;
19854   int bMultiLineRowExists = 0;
19855   int bw = p->cmOpts.bWordWrap;
19856   const char *zEmpty = "";
19857   const char *zShowNull = p->nullValue;
19858 
19859   rc = sqlite3_step(pStmt);
19860   if( rc!=SQLITE_ROW ) return;
19861   nColumn = sqlite3_column_count(pStmt);
19862   nAlloc = nColumn*4;
19863   if( nAlloc<=0 ) nAlloc = 1;
19864   azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
19865   shell_check_oom(azData);
19866   azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
19867   shell_check_oom(azNextLine);
19868   memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
19869   if( p->cmOpts.bQuote ){
19870     azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
19871     shell_check_oom(azQuoted);
19872     memset(azQuoted, 0, nColumn*sizeof(char*) );
19873   }
19874   abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
19875   shell_check_oom(abRowDiv);
19876   if( nColumn>p->nWidth ){
19877     p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
19878     shell_check_oom(p->colWidth);
19879     for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
19880     p->nWidth = nColumn;
19881     p->actualWidth = &p->colWidth[nColumn];
19882   }
19883   memset(p->actualWidth, 0, nColumn*sizeof(int));
19884   for(i=0; i<nColumn; i++){
19885     w = p->colWidth[i];
19886     if( w<0 ) w = -w;
19887     p->actualWidth[i] = w;
19888   }
19889   for(i=0; i<nColumn; i++){
19890     const unsigned char *zNotUsed;
19891     int wx = p->colWidth[i];
19892     if( wx==0 ){
19893       wx = p->cmOpts.iWrap;
19894     }
19895     if( wx<0 ) wx = -wx;
19896     uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
19897     if( uz==0 ) uz = (u8*)"";
19898     azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
19899   }
19900   do{
19901     int useNextLine = bNextLine;
19902     bNextLine = 0;
19903     if( (nRow+2)*nColumn >= nAlloc ){
19904       nAlloc *= 2;
19905       azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
19906       shell_check_oom(azData);
19907       abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
19908       shell_check_oom(abRowDiv);
19909     }
19910     abRowDiv[nRow] = 1;
19911     nRow++;
19912     for(i=0; i<nColumn; i++){
19913       int wx = p->colWidth[i];
19914       if( wx==0 ){
19915         wx = p->cmOpts.iWrap;
19916       }
19917       if( wx<0 ) wx = -wx;
19918       if( useNextLine ){
19919         uz = azNextLine[i];
19920         if( uz==0 ) uz = (u8*)zEmpty;
19921       }else if( p->cmOpts.bQuote ){
19922         sqlite3_free(azQuoted[i]);
19923         azQuoted[i] = quoted_column(pStmt,i);
19924         uz = (const unsigned char*)azQuoted[i];
19925       }else{
19926         uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
19927         if( uz==0 ) uz = (u8*)zShowNull;
19928       }
19929       azData[nRow*nColumn + i]
19930         = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
19931       if( azNextLine[i] ){
19932         bNextLine = 1;
19933         abRowDiv[nRow-1] = 0;
19934         bMultiLineRowExists = 1;
19935       }
19936     }
19937   }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
19938   nTotal = nColumn*(nRow+1);
19939   for(i=0; i<nTotal; i++){
19940     z = azData[i];
19941     if( z==0 ) z = (char*)zEmpty;
19942     n = strlenChar(z);
19943     j = i%nColumn;
19944     if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
19945   }
19946   if( seenInterrupt ) goto columnar_end;
19947   if( nColumn==0 ) goto columnar_end;
19948   switch( p->cMode ){
19949     case MODE_Column: {
19950       colSep = "  ";
19951       rowSep = "\n";
19952       if( p->showHeader ){
19953         for(i=0; i<nColumn; i++){
19954           w = p->actualWidth[i];
19955           if( p->colWidth[i]<0 ) w = -w;
19956           utf8_width_print(p->out, w, azData[i]);
19957           fputs(i==nColumn-1?"\n":"  ", p->out);
19958         }
19959         for(i=0; i<nColumn; i++){
19960           print_dashes(p->out, p->actualWidth[i]);
19961           fputs(i==nColumn-1?"\n":"  ", p->out);
19962         }
19963       }
19964       break;
19965     }
19966     case MODE_Table: {
19967       colSep = " | ";
19968       rowSep = " |\n";
19969       print_row_separator(p, nColumn, "+");
19970       fputs("| ", p->out);
19971       for(i=0; i<nColumn; i++){
19972         w = p->actualWidth[i];
19973         n = strlenChar(azData[i]);
19974         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
19975         fputs(i==nColumn-1?" |\n":" | ", p->out);
19976       }
19977       print_row_separator(p, nColumn, "+");
19978       break;
19979     }
19980     case MODE_Markdown: {
19981       colSep = " | ";
19982       rowSep = " |\n";
19983       fputs("| ", p->out);
19984       for(i=0; i<nColumn; i++){
19985         w = p->actualWidth[i];
19986         n = strlenChar(azData[i]);
19987         utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
19988         fputs(i==nColumn-1?" |\n":" | ", p->out);
19989       }
19990       print_row_separator(p, nColumn, "|");
19991       break;
19992     }
19993     case MODE_Box: {
19994       colSep = " " BOX_13 " ";
19995       rowSep = " " BOX_13 "\n";
19996       print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
19997       utf8_printf(p->out, BOX_13 " ");
19998       for(i=0; i<nColumn; i++){
19999         w = p->actualWidth[i];
20000         n = strlenChar(azData[i]);
20001         utf8_printf(p->out, "%*s%s%*s%s",
20002             (w-n)/2, "", azData[i], (w-n+1)/2, "",
20003             i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
20004       }
20005       print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20006       break;
20007     }
20008   }
20009   for(i=nColumn, j=0; i<nTotal; i++, j++){
20010     if( j==0 && p->cMode!=MODE_Column ){
20011       utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
20012     }
20013     z = azData[i];
20014     if( z==0 ) z = p->nullValue;
20015     w = p->actualWidth[j];
20016     if( p->colWidth[j]<0 ) w = -w;
20017     utf8_width_print(p->out, w, z);
20018     if( j==nColumn-1 ){
20019       utf8_printf(p->out, "%s", rowSep);
20020       if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
20021         if( p->cMode==MODE_Table ){
20022           print_row_separator(p, nColumn, "+");
20023         }else if( p->cMode==MODE_Box ){
20024           print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
20025         }else if( p->cMode==MODE_Column ){
20026           raw_printf(p->out, "\n");
20027         }
20028       }
20029       j = -1;
20030       if( seenInterrupt ) goto columnar_end;
20031     }else{
20032       utf8_printf(p->out, "%s", colSep);
20033     }
20034   }
20035   if( p->cMode==MODE_Table ){
20036     print_row_separator(p, nColumn, "+");
20037   }else if( p->cMode==MODE_Box ){
20038     print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
20039   }
20040 columnar_end:
20041   if( seenInterrupt ){
20042     utf8_printf(p->out, "Interrupt\n");
20043   }
20044   nData = (nRow+1)*nColumn;
20045   for(i=0; i<nData; i++){
20046     z = azData[i];
20047     if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
20048   }
20049   sqlite3_free(azData);
20050   sqlite3_free((void*)azNextLine);
20051   sqlite3_free(abRowDiv);
20052   if( azQuoted ){
20053     for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
20054     sqlite3_free(azQuoted);
20055   }
20056 }
20057 
20058 /*
20059 ** Run a prepared statement
20060 */
20061 static void exec_prepared_stmt(
20062   ShellState *pArg,                                /* Pointer to ShellState */
20063   sqlite3_stmt *pStmt                              /* Statement to run */
20064 ){
20065   int rc;
20066   sqlite3_uint64 nRow = 0;
20067 
20068   if( pArg->cMode==MODE_Column
20069    || pArg->cMode==MODE_Table
20070    || pArg->cMode==MODE_Box
20071    || pArg->cMode==MODE_Markdown
20072   ){
20073     exec_prepared_stmt_columnar(pArg, pStmt);
20074     return;
20075   }
20076 
20077   /* perform the first step.  this will tell us if we
20078   ** have a result set or not and how wide it is.
20079   */
20080   rc = sqlite3_step(pStmt);
20081   /* if we have a result set... */
20082   if( SQLITE_ROW == rc ){
20083     /* allocate space for col name ptr, value ptr, and type */
20084     int nCol = sqlite3_column_count(pStmt);
20085     void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
20086     if( !pData ){
20087       shell_out_of_memory();
20088     }else{
20089       char **azCols = (char **)pData;      /* Names of result columns */
20090       char **azVals = &azCols[nCol];       /* Results */
20091       int *aiTypes = (int *)&azVals[nCol]; /* Result types */
20092       int i, x;
20093       assert(sizeof(int) <= sizeof(char *));
20094       /* save off ptrs to column names */
20095       for(i=0; i<nCol; i++){
20096         azCols[i] = (char *)sqlite3_column_name(pStmt, i);
20097       }
20098       do{
20099         nRow++;
20100         /* extract the data and data types */
20101         for(i=0; i<nCol; i++){
20102           aiTypes[i] = x = sqlite3_column_type(pStmt, i);
20103           if( x==SQLITE_BLOB
20104            && pArg
20105            && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
20106           ){
20107             azVals[i] = "";
20108           }else{
20109             azVals[i] = (char*)sqlite3_column_text(pStmt, i);
20110           }
20111           if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
20112             rc = SQLITE_NOMEM;
20113             break; /* from for */
20114           }
20115         } /* end for */
20116 
20117         /* if data and types extracted successfully... */
20118         if( SQLITE_ROW == rc ){
20119           /* call the supplied callback with the result row data */
20120           if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
20121             rc = SQLITE_ABORT;
20122           }else{
20123             rc = sqlite3_step(pStmt);
20124           }
20125         }
20126       } while( SQLITE_ROW == rc );
20127       sqlite3_free(pData);
20128       if( pArg->cMode==MODE_Json ){
20129         fputs("]\n", pArg->out);
20130       }else if( pArg->cMode==MODE_Count ){
20131         char zBuf[200];
20132         sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
20133                          nRow, nRow!=1 ? "s" : "");
20134         printf("%s", zBuf);
20135       }
20136     }
20137   }
20138 }
20139 
20140 #ifndef SQLITE_OMIT_VIRTUALTABLE
20141 /*
20142 ** This function is called to process SQL if the previous shell command
20143 ** was ".expert". It passes the SQL in the second argument directly to
20144 ** the sqlite3expert object.
20145 **
20146 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20147 ** code. In this case, (*pzErr) may be set to point to a buffer containing
20148 ** an English language error message. It is the responsibility of the
20149 ** caller to eventually free this buffer using sqlite3_free().
20150 */
20151 static int expertHandleSQL(
20152   ShellState *pState,
20153   const char *zSql,
20154   char **pzErr
20155 ){
20156   assert( pState->expert.pExpert );
20157   assert( pzErr==0 || *pzErr==0 );
20158   return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
20159 }
20160 
20161 /*
20162 ** This function is called either to silently clean up the object
20163 ** created by the ".expert" command (if bCancel==1), or to generate a
20164 ** report from it and then clean it up (if bCancel==0).
20165 **
20166 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
20167 ** code. In this case, (*pzErr) may be set to point to a buffer containing
20168 ** an English language error message. It is the responsibility of the
20169 ** caller to eventually free this buffer using sqlite3_free().
20170 */
20171 static int expertFinish(
20172   ShellState *pState,
20173   int bCancel,
20174   char **pzErr
20175 ){
20176   int rc = SQLITE_OK;
20177   sqlite3expert *p = pState->expert.pExpert;
20178   assert( p );
20179   assert( bCancel || pzErr==0 || *pzErr==0 );
20180   if( bCancel==0 ){
20181     FILE *out = pState->out;
20182     int bVerbose = pState->expert.bVerbose;
20183 
20184     rc = sqlite3_expert_analyze(p, pzErr);
20185     if( rc==SQLITE_OK ){
20186       int nQuery = sqlite3_expert_count(p);
20187       int i;
20188 
20189       if( bVerbose ){
20190         const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
20191         raw_printf(out, "-- Candidates -----------------------------\n");
20192         raw_printf(out, "%s\n", zCand);
20193       }
20194       for(i=0; i<nQuery; i++){
20195         const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
20196         const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
20197         const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
20198         if( zIdx==0 ) zIdx = "(no new indexes)\n";
20199         if( bVerbose ){
20200           raw_printf(out, "-- Query %d --------------------------------\n",i+1);
20201           raw_printf(out, "%s\n\n", zSql);
20202         }
20203         raw_printf(out, "%s\n", zIdx);
20204         raw_printf(out, "%s\n", zEQP);
20205       }
20206     }
20207   }
20208   sqlite3_expert_destroy(p);
20209   pState->expert.pExpert = 0;
20210   return rc;
20211 }
20212 
20213 /*
20214 ** Implementation of ".expert" dot command.
20215 */
20216 static int expertDotCommand(
20217   ShellState *pState,             /* Current shell tool state */
20218   char **azArg,                   /* Array of arguments passed to dot command */
20219   int nArg                        /* Number of entries in azArg[] */
20220 ){
20221   int rc = SQLITE_OK;
20222   char *zErr = 0;
20223   int i;
20224   int iSample = 0;
20225 
20226   assert( pState->expert.pExpert==0 );
20227   memset(&pState->expert, 0, sizeof(ExpertInfo));
20228 
20229   for(i=1; rc==SQLITE_OK && i<nArg; i++){
20230     char *z = azArg[i];
20231     int n;
20232     if( z[0]=='-' && z[1]=='-' ) z++;
20233     n = strlen30(z);
20234     if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
20235       pState->expert.bVerbose = 1;
20236     }
20237     else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
20238       if( i==(nArg-1) ){
20239         raw_printf(stderr, "option requires an argument: %s\n", z);
20240         rc = SQLITE_ERROR;
20241       }else{
20242         iSample = (int)integerValue(azArg[++i]);
20243         if( iSample<0 || iSample>100 ){
20244           raw_printf(stderr, "value out of range: %s\n", azArg[i]);
20245           rc = SQLITE_ERROR;
20246         }
20247       }
20248     }
20249     else{
20250       raw_printf(stderr, "unknown option: %s\n", z);
20251       rc = SQLITE_ERROR;
20252     }
20253   }
20254 
20255   if( rc==SQLITE_OK ){
20256     pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
20257     if( pState->expert.pExpert==0 ){
20258       raw_printf(stderr, "sqlite3_expert_new: %s\n",
20259                  zErr ? zErr : "out of memory");
20260       rc = SQLITE_ERROR;
20261     }else{
20262       sqlite3_expert_config(
20263           pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
20264       );
20265     }
20266   }
20267   sqlite3_free(zErr);
20268 
20269   return rc;
20270 }
20271 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
20272 
20273 /*
20274 ** Execute a statement or set of statements.  Print
20275 ** any result rows/columns depending on the current mode
20276 ** set via the supplied callback.
20277 **
20278 ** This is very similar to SQLite's built-in sqlite3_exec()
20279 ** function except it takes a slightly different callback
20280 ** and callback data argument.
20281 */
20282 static int shell_exec(
20283   ShellState *pArg,                         /* Pointer to ShellState */
20284   const char *zSql,                         /* SQL to be evaluated */
20285   char **pzErrMsg                           /* Error msg written here */
20286 ){
20287   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
20288   int rc = SQLITE_OK;             /* Return Code */
20289   int rc2;
20290   const char *zLeftover;          /* Tail of unprocessed SQL */
20291   sqlite3 *db = pArg->db;
20292 
20293   if( pzErrMsg ){
20294     *pzErrMsg = NULL;
20295   }
20296 
20297 #ifndef SQLITE_OMIT_VIRTUALTABLE
20298   if( pArg->expert.pExpert ){
20299     rc = expertHandleSQL(pArg, zSql, pzErrMsg);
20300     return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
20301   }
20302 #endif
20303 
20304   while( zSql[0] && (SQLITE_OK == rc) ){
20305     static const char *zStmtSql;
20306     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
20307     if( SQLITE_OK != rc ){
20308       if( pzErrMsg ){
20309         *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
20310       }
20311     }else{
20312       if( !pStmt ){
20313         /* this happens for a comment or white-space */
20314         zSql = zLeftover;
20315         while( IsSpace(zSql[0]) ) zSql++;
20316         continue;
20317       }
20318       zStmtSql = sqlite3_sql(pStmt);
20319       if( zStmtSql==0 ) zStmtSql = "";
20320       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
20321 
20322       /* save off the prepared statement handle and reset row count */
20323       if( pArg ){
20324         pArg->pStmt = pStmt;
20325         pArg->cnt = 0;
20326       }
20327 
20328       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
20329       if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
20330         sqlite3_stmt *pExplain;
20331         int triggerEQP = 0;
20332         disable_debug_trace_modes();
20333         sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
20334         if( pArg->autoEQP>=AUTOEQP_trigger ){
20335           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
20336         }
20337         pExplain = pStmt;
20338         sqlite3_reset(pExplain);
20339         rc = sqlite3_stmt_explain(pExplain, 2);
20340         if( rc==SQLITE_OK ){
20341           while( sqlite3_step(pExplain)==SQLITE_ROW ){
20342             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
20343             int iEqpId = sqlite3_column_int(pExplain, 0);
20344             int iParentId = sqlite3_column_int(pExplain, 1);
20345             if( zEQPLine==0 ) zEQPLine = "";
20346             if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
20347             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
20348           }
20349           eqp_render(pArg, 0);
20350         }
20351         if( pArg->autoEQP>=AUTOEQP_full ){
20352           /* Also do an EXPLAIN for ".eqp full" mode */
20353           sqlite3_reset(pExplain);
20354           rc = sqlite3_stmt_explain(pExplain, 1);
20355           if( rc==SQLITE_OK ){
20356             pArg->cMode = MODE_Explain;
20357             assert( sqlite3_stmt_isexplain(pExplain)==1 );
20358             explain_data_prepare(pArg, pExplain);
20359             exec_prepared_stmt(pArg, pExplain);
20360             explain_data_delete(pArg);
20361           }
20362         }
20363         if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
20364           sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
20365         }
20366         sqlite3_reset(pStmt);
20367         sqlite3_stmt_explain(pStmt, 0);
20368         restore_debug_trace_modes();
20369       }
20370 
20371       if( pArg ){
20372         int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
20373         pArg->cMode = pArg->mode;
20374         if( pArg->autoExplain ){
20375           if( bIsExplain ){
20376             pArg->cMode = MODE_Explain;
20377           }
20378           if( sqlite3_stmt_isexplain(pStmt)==2 ){
20379             pArg->cMode = MODE_EQP;
20380           }
20381         }
20382 
20383         /* If the shell is currently in ".explain" mode, gather the extra
20384         ** data required to add indents to the output.*/
20385         if( pArg->cMode==MODE_Explain && bIsExplain ){
20386           explain_data_prepare(pArg, pStmt);
20387         }
20388       }
20389 
20390       bind_prepared_stmt(pArg, pStmt);
20391       exec_prepared_stmt(pArg, pStmt);
20392       explain_data_delete(pArg);
20393       eqp_render(pArg, 0);
20394 
20395       /* print usage stats if stats on */
20396       if( pArg && pArg->statsOn ){
20397         display_stats(db, pArg, 0);
20398       }
20399 
20400       /* print loop-counters if required */
20401       if( pArg && pArg->scanstatsOn ){
20402         display_scanstats(db, pArg);
20403       }
20404 
20405       /* Finalize the statement just executed. If this fails, save a
20406       ** copy of the error message. Otherwise, set zSql to point to the
20407       ** next statement to execute. */
20408       rc2 = sqlite3_finalize(pStmt);
20409       if( rc!=SQLITE_NOMEM ) rc = rc2;
20410       if( rc==SQLITE_OK ){
20411         zSql = zLeftover;
20412         while( IsSpace(zSql[0]) ) zSql++;
20413       }else if( pzErrMsg ){
20414         *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
20415       }
20416 
20417       /* clear saved stmt handle */
20418       if( pArg ){
20419         pArg->pStmt = NULL;
20420       }
20421     }
20422   } /* end while */
20423 
20424   return rc;
20425 }
20426 
20427 /*
20428 ** Release memory previously allocated by tableColumnList().
20429 */
20430 static void freeColumnList(char **azCol){
20431   int i;
20432   for(i=1; azCol[i]; i++){
20433     sqlite3_free(azCol[i]);
20434   }
20435   /* azCol[0] is a static string */
20436   sqlite3_free(azCol);
20437 }
20438 
20439 /*
20440 ** Return a list of pointers to strings which are the names of all
20441 ** columns in table zTab.   The memory to hold the names is dynamically
20442 ** allocated and must be released by the caller using a subsequent call
20443 ** to freeColumnList().
20444 **
20445 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
20446 ** value that needs to be preserved, then azCol[0] is filled in with the
20447 ** name of the rowid column.
20448 **
20449 ** The first regular column in the table is azCol[1].  The list is terminated
20450 ** by an entry with azCol[i]==0.
20451 */
20452 static char **tableColumnList(ShellState *p, const char *zTab){
20453   char **azCol = 0;
20454   sqlite3_stmt *pStmt;
20455   char *zSql;
20456   int nCol = 0;
20457   int nAlloc = 0;
20458   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
20459   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
20460   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
20461   int rc;
20462 
20463   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
20464   shell_check_oom(zSql);
20465   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20466   sqlite3_free(zSql);
20467   if( rc ) return 0;
20468   while( sqlite3_step(pStmt)==SQLITE_ROW ){
20469     if( nCol>=nAlloc-2 ){
20470       nAlloc = nAlloc*2 + nCol + 10;
20471       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
20472       shell_check_oom(azCol);
20473     }
20474     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
20475     shell_check_oom(azCol[nCol]);
20476     if( sqlite3_column_int(pStmt, 5) ){
20477       nPK++;
20478       if( nPK==1
20479        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
20480                           "INTEGER")==0
20481       ){
20482         isIPK = 1;
20483       }else{
20484         isIPK = 0;
20485       }
20486     }
20487   }
20488   sqlite3_finalize(pStmt);
20489   if( azCol==0 ) return 0;
20490   azCol[0] = 0;
20491   azCol[nCol+1] = 0;
20492 
20493   /* The decision of whether or not a rowid really needs to be preserved
20494   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
20495   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
20496   ** rowids on tables where the rowid is inaccessible because there are other
20497   ** columns in the table named "rowid", "_rowid_", and "oid".
20498   */
20499   if( preserveRowid && isIPK ){
20500     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
20501     ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
20502     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
20503     ** ROWID aliases.  To distinguish these cases, check to see if
20504     ** there is a "pk" entry in "PRAGMA index_list".  There will be
20505     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
20506     */
20507     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
20508                            " WHERE origin='pk'", zTab);
20509     shell_check_oom(zSql);
20510     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
20511     sqlite3_free(zSql);
20512     if( rc ){
20513       freeColumnList(azCol);
20514       return 0;
20515     }
20516     rc = sqlite3_step(pStmt);
20517     sqlite3_finalize(pStmt);
20518     preserveRowid = rc==SQLITE_ROW;
20519   }
20520   if( preserveRowid ){
20521     /* Only preserve the rowid if we can find a name to use for the
20522     ** rowid */
20523     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
20524     int i, j;
20525     for(j=0; j<3; j++){
20526       for(i=1; i<=nCol; i++){
20527         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
20528       }
20529       if( i>nCol ){
20530         /* At this point, we know that azRowid[j] is not the name of any
20531         ** ordinary column in the table.  Verify that azRowid[j] is a valid
20532         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
20533         ** tables will fail this last check */
20534         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
20535         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
20536         break;
20537       }
20538     }
20539   }
20540   return azCol;
20541 }
20542 
20543 /*
20544 ** Toggle the reverse_unordered_selects setting.
20545 */
20546 static void toggleSelectOrder(sqlite3 *db){
20547   sqlite3_stmt *pStmt = 0;
20548   int iSetting = 0;
20549   char zStmt[100];
20550   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
20551   if( sqlite3_step(pStmt)==SQLITE_ROW ){
20552     iSetting = sqlite3_column_int(pStmt, 0);
20553   }
20554   sqlite3_finalize(pStmt);
20555   sqlite3_snprintf(sizeof(zStmt), zStmt,
20556        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
20557   sqlite3_exec(db, zStmt, 0, 0, 0);
20558 }
20559 
20560 /*
20561 ** This is a different callback routine used for dumping the database.
20562 ** Each row received by this callback consists of a table name,
20563 ** the table type ("index" or "table") and SQL to create the table.
20564 ** This routine should print text sufficient to recreate the table.
20565 */
20566 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
20567   int rc;
20568   const char *zTable;
20569   const char *zType;
20570   const char *zSql;
20571   ShellState *p = (ShellState *)pArg;
20572   int dataOnly;
20573   int noSys;
20574 
20575   UNUSED_PARAMETER(azNotUsed);
20576   if( nArg!=3 || azArg==0 ) return 0;
20577   zTable = azArg[0];
20578   zType = azArg[1];
20579   zSql = azArg[2];
20580   if( zTable==0 ) return 0;
20581   if( zType==0 ) return 0;
20582   dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
20583   noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
20584 
20585   if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
20586     if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
20587   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
20588     if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
20589   }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
20590     return 0;
20591   }else if( dataOnly ){
20592     /* no-op */
20593   }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
20594     char *zIns;
20595     if( !p->writableSchema ){
20596       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
20597       p->writableSchema = 1;
20598     }
20599     zIns = sqlite3_mprintf(
20600        "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
20601        "VALUES('table','%q','%q',0,'%q');",
20602        zTable, zTable, zSql);
20603     shell_check_oom(zIns);
20604     utf8_printf(p->out, "%s\n", zIns);
20605     sqlite3_free(zIns);
20606     return 0;
20607   }else{
20608     printSchemaLine(p->out, zSql, ";\n");
20609   }
20610 
20611   if( cli_strcmp(zType, "table")==0 ){
20612     ShellText sSelect;
20613     ShellText sTable;
20614     char **azCol;
20615     int i;
20616     char *savedDestTable;
20617     int savedMode;
20618 
20619     azCol = tableColumnList(p, zTable);
20620     if( azCol==0 ){
20621       p->nErr++;
20622       return 0;
20623     }
20624 
20625     /* Always quote the table name, even if it appears to be pure ascii,
20626     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
20627     initText(&sTable);
20628     appendText(&sTable, zTable, quoteChar(zTable));
20629     /* If preserving the rowid, add a column list after the table name.
20630     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
20631     ** instead of the usual "INSERT INTO tab VALUES(...)".
20632     */
20633     if( azCol[0] ){
20634       appendText(&sTable, "(", 0);
20635       appendText(&sTable, azCol[0], 0);
20636       for(i=1; azCol[i]; i++){
20637         appendText(&sTable, ",", 0);
20638         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
20639       }
20640       appendText(&sTable, ")", 0);
20641     }
20642 
20643     /* Build an appropriate SELECT statement */
20644     initText(&sSelect);
20645     appendText(&sSelect, "SELECT ", 0);
20646     if( azCol[0] ){
20647       appendText(&sSelect, azCol[0], 0);
20648       appendText(&sSelect, ",", 0);
20649     }
20650     for(i=1; azCol[i]; i++){
20651       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
20652       if( azCol[i+1] ){
20653         appendText(&sSelect, ",", 0);
20654       }
20655     }
20656     freeColumnList(azCol);
20657     appendText(&sSelect, " FROM ", 0);
20658     appendText(&sSelect, zTable, quoteChar(zTable));
20659 
20660     savedDestTable = p->zDestTable;
20661     savedMode = p->mode;
20662     p->zDestTable = sTable.z;
20663     p->mode = p->cMode = MODE_Insert;
20664     rc = shell_exec(p, sSelect.z, 0);
20665     if( (rc&0xff)==SQLITE_CORRUPT ){
20666       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
20667       toggleSelectOrder(p->db);
20668       shell_exec(p, sSelect.z, 0);
20669       toggleSelectOrder(p->db);
20670     }
20671     p->zDestTable = savedDestTable;
20672     p->mode = savedMode;
20673     freeText(&sTable);
20674     freeText(&sSelect);
20675     if( rc ) p->nErr++;
20676   }
20677   return 0;
20678 }
20679 
20680 /*
20681 ** Run zQuery.  Use dump_callback() as the callback routine so that
20682 ** the contents of the query are output as SQL statements.
20683 **
20684 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
20685 ** "ORDER BY rowid DESC" to the end.
20686 */
20687 static int run_schema_dump_query(
20688   ShellState *p,
20689   const char *zQuery
20690 ){
20691   int rc;
20692   char *zErr = 0;
20693   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
20694   if( rc==SQLITE_CORRUPT ){
20695     char *zQ2;
20696     int len = strlen30(zQuery);
20697     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
20698     if( zErr ){
20699       utf8_printf(p->out, "/****** %s ******/\n", zErr);
20700       sqlite3_free(zErr);
20701       zErr = 0;
20702     }
20703     zQ2 = malloc( len+100 );
20704     if( zQ2==0 ) return rc;
20705     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
20706     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
20707     if( rc ){
20708       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
20709     }else{
20710       rc = SQLITE_CORRUPT;
20711     }
20712     sqlite3_free(zErr);
20713     free(zQ2);
20714   }
20715   return rc;
20716 }
20717 
20718 /*
20719 ** Text of help messages.
20720 **
20721 ** The help text for each individual command begins with a line that starts
20722 ** with ".".  Subsequent lines are supplemental information.
20723 **
20724 ** There must be two or more spaces between the end of the command and the
20725 ** start of the description of what that command does.
20726 */
20727 static const char *(azHelp[]) = {
20728 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
20729   && !defined(SQLITE_SHELL_FIDDLE)
20730   ".archive ...             Manage SQL archives",
20731   "   Each command must have exactly one of the following options:",
20732   "     -c, --create               Create a new archive",
20733   "     -u, --update               Add or update files with changed mtime",
20734   "     -i, --insert               Like -u but always add even if unchanged",
20735   "     -r, --remove               Remove files from archive",
20736   "     -t, --list                 List contents of archive",
20737   "     -x, --extract              Extract files from archive",
20738   "   Optional arguments:",
20739   "     -v, --verbose              Print each filename as it is processed",
20740   "     -f FILE, --file FILE       Use archive FILE (default is current db)",
20741   "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
20742   "     -C DIR, --directory DIR    Read/extract files from directory DIR",
20743   "     -g, --glob                 Use glob matching for names in archive",
20744   "     -n, --dryrun               Show the SQL that would have occurred",
20745   "   Examples:",
20746   "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
20747   "     .ar -tf ARCHIVE          # List members of ARCHIVE",
20748   "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
20749   "   See also:",
20750   "      http://sqlite.org/cli.html#sqlite_archive_support",
20751 #endif
20752 #ifndef SQLITE_OMIT_AUTHORIZATION
20753   ".auth ON|OFF             Show authorizer callbacks",
20754 #endif
20755 #ifndef SQLITE_SHELL_FIDDLE
20756   ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
20757   "   Options:",
20758   "       --append            Use the appendvfs",
20759   "       --async             Write to FILE without journal and fsync()",
20760 #endif
20761   ".bail on|off             Stop after hitting an error.  Default OFF",
20762 #ifndef SQLITE_SHELL_FIDDLE
20763   ".cd DIRECTORY            Change the working directory to DIRECTORY",
20764 #endif
20765   ".changes on|off          Show number of rows changed by SQL",
20766 #ifndef SQLITE_SHELL_FIDDLE
20767   ".check GLOB              Fail if output since .testcase does not match",
20768   ".clone NEWDB             Clone data into NEWDB from the existing database",
20769 #endif
20770   ".connection [close] [#]  Open or close an auxiliary database connection",
20771 #if defined(_WIN32) || defined(WIN32)
20772   ".crnl on|off             Translate \\n to \\r\\n.  Default ON",
20773 #endif
20774   ".databases               List names and files of attached databases",
20775   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
20776 #if SQLITE_SHELL_HAVE_RECOVER
20777   ".dbinfo ?DB?             Show status information about the database",
20778 #endif
20779   ".dump ?OBJECTS?          Render database content as SQL",
20780   "   Options:",
20781   "     --data-only            Output only INSERT statements",
20782   "     --newlines             Allow unescaped newline characters in output",
20783   "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
20784   "     --preserve-rowids      Include ROWID values in the output",
20785   "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
20786   "   Additional LIKE patterns can be given in subsequent arguments",
20787   ".echo on|off             Turn command echo on or off",
20788   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
20789   "   Other Modes:",
20790 #ifdef SQLITE_DEBUG
20791   "      test                  Show raw EXPLAIN QUERY PLAN output",
20792   "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
20793 #endif
20794   "      trigger               Like \"full\" but also show trigger bytecode",
20795 #ifndef SQLITE_SHELL_FIDDLE
20796   ".excel                   Display the output of next command in spreadsheet",
20797   "   --bom                   Put a UTF8 byte-order mark on intermediate file",
20798 #endif
20799 #ifndef SQLITE_SHELL_FIDDLE
20800   ".exit ?CODE?             Exit this program with return-code CODE",
20801 #endif
20802   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
20803   ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
20804   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
20805   "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
20806   "   --help                  Show CMD details",
20807   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
20808   ".headers on|off          Turn display of headers on or off",
20809   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
20810 #ifndef SQLITE_SHELL_FIDDLE
20811   ".import FILE TABLE       Import data from FILE into TABLE",
20812   "   Options:",
20813   "     --ascii               Use \\037 and \\036 as column and row separators",
20814   "     --csv                 Use , and \\n as column and row separators",
20815   "     --skip N              Skip the first N rows of input",
20816   "     --schema S            Target table to be S.TABLE",
20817   "     -v                    \"Verbose\" - increase auxiliary output",
20818   "   Notes:",
20819   "     *  If TABLE does not exist, it is created.  The first row of input",
20820   "        determines the column names.",
20821   "     *  If neither --csv or --ascii are used, the input mode is derived",
20822   "        from the \".mode\" output mode",
20823   "     *  If FILE begins with \"|\" then it is a command that generates the",
20824   "        input text.",
20825 #endif
20826 #ifndef SQLITE_OMIT_TEST_CONTROL
20827   ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
20828 #endif
20829   ".indexes ?TABLE?         Show names of indexes",
20830   "                           If TABLE is specified, only show indexes for",
20831   "                           tables matching TABLE using the LIKE operator.",
20832 #ifdef SQLITE_ENABLE_IOTRACE
20833   ",iotrace FILE            Enable I/O diagnostic logging to FILE",
20834 #endif
20835   ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
20836   ".lint OPTIONS            Report potential schema issues.",
20837   "     Options:",
20838   "        fkey-indexes     Find missing foreign key indexes",
20839 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
20840   ".load FILE ?ENTRY?       Load an extension library",
20841 #endif
20842 #if !defined(SQLITE_SHELL_FIDDLE)
20843   ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
20844 #else
20845   ".log on|off              Turn logging on or off.",
20846 #endif
20847   ".mode MODE ?OPTIONS?     Set output mode",
20848   "   MODE is one of:",
20849   "     ascii       Columns/rows delimited by 0x1F and 0x1E",
20850   "     box         Tables using unicode box-drawing characters",
20851   "     csv         Comma-separated values",
20852   "     column      Output in columns.  (See .width)",
20853   "     html        HTML <table> code",
20854   "     insert      SQL insert statements for TABLE",
20855   "     json        Results in a JSON array",
20856   "     line        One value per line",
20857   "     list        Values delimited by \"|\"",
20858   "     markdown    Markdown table format",
20859   "     qbox        Shorthand for \"box --wrap 60 --quote\"",
20860   "     quote       Escape answers as for SQL",
20861   "     table       ASCII-art table",
20862   "     tabs        Tab-separated values",
20863   "     tcl         TCL list elements",
20864   "   OPTIONS: (for columnar modes or insert mode):",
20865   "     --wrap N       Wrap output lines to no longer than N characters",
20866   "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
20867   "     --ww           Shorthand for \"--wordwrap 1\"",
20868   "     --quote        Quote output text as SQL literals",
20869   "     --noquote      Do not quote output text",
20870   "     TABLE          The name of SQL table used for \"insert\" mode",
20871 #ifndef SQLITE_SHELL_FIDDLE
20872   ".nonce STRING            Suspend safe mode for one command if nonce matches",
20873 #endif
20874   ".nullvalue STRING        Use STRING in place of NULL values",
20875 #ifndef SQLITE_SHELL_FIDDLE
20876   ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
20877   "     If FILE begins with '|' then open as a pipe",
20878   "       --bom  Put a UTF8 byte-order mark at the beginning",
20879   "       -e     Send output to the system text editor",
20880   "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
20881   /* Note that .open is (partially) available in WASM builds but is
20882   ** currently only intended to be used by the fiddle tool, not
20883   ** end users, so is "undocumented." */
20884   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
20885   "     Options:",
20886   "        --append        Use appendvfs to append database to the end of FILE",
20887 #endif
20888 #ifndef SQLITE_OMIT_DESERIALIZE
20889   "        --deserialize   Load into memory using sqlite3_deserialize()",
20890   "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
20891   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
20892 #endif
20893   "        --new           Initialize FILE to an empty database",
20894   "        --nofollow      Do not follow symbolic links",
20895   "        --readonly      Open FILE readonly",
20896   "        --zip           FILE is a ZIP archive",
20897 #ifndef SQLITE_SHELL_FIDDLE
20898   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
20899   "   If FILE begins with '|' then open it as a pipe.",
20900   "   Options:",
20901   "     --bom                 Prefix output with a UTF8 byte-order mark",
20902   "     -e                    Send output to the system text editor",
20903   "     -x                    Send output as CSV to a spreadsheet",
20904 #endif
20905   ".parameter CMD ...       Manage SQL parameter bindings",
20906   "   clear                   Erase all bindings",
20907   "   init                    Initialize the TEMP table that holds bindings",
20908   "   list                    List the current parameter bindings",
20909   "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
20910   "                           PARAMETER should start with one of: $ : @ ?",
20911   "   unset PARAMETER         Remove PARAMETER from the binding table",
20912   ".print STRING...         Print literal STRING",
20913 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
20914   ".progress N              Invoke progress handler after every N opcodes",
20915   "   --limit N                 Interrupt after N progress callbacks",
20916   "   --once                    Do no more than one progress interrupt",
20917   "   --quiet|-q                No output except at interrupts",
20918   "   --reset                   Reset the count for each input and interrupt",
20919 #endif
20920   ".prompt MAIN CONTINUE    Replace the standard prompts",
20921 #ifndef SQLITE_SHELL_FIDDLE
20922   ".quit                    Stop interpreting input stream, exit if primary.",
20923   ".read FILE               Read input from FILE or command output",
20924   "    If FILE begins with \"|\", it is a command that generates the input.",
20925 #endif
20926 #if SQLITE_SHELL_HAVE_RECOVER
20927   ".recover                 Recover as much data as possible from corrupt db.",
20928   "   --ignore-freelist        Ignore pages that appear to be on db freelist",
20929   "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
20930   "   --no-rowids              Do not attempt to recover rowid values",
20931   "                            that are not also INTEGER PRIMARY KEYs",
20932 #endif
20933 #ifndef SQLITE_SHELL_FIDDLE
20934   ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
20935   ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
20936 #endif
20937   ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
20938   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
20939   "   Options:",
20940   "      --indent             Try to pretty-print the schema",
20941   "      --nosys              Omit objects whose names start with \"sqlite_\"",
20942   ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
20943   "    Options:",
20944   "       --init               Create a new SELFTEST table",
20945   "       -v                   Verbose output",
20946   ".separator COL ?ROW?     Change the column and row separators",
20947 #if defined(SQLITE_ENABLE_SESSION)
20948   ".session ?NAME? CMD ...  Create or control sessions",
20949   "   Subcommands:",
20950   "     attach TABLE             Attach TABLE",
20951   "     changeset FILE           Write a changeset into FILE",
20952   "     close                    Close one session",
20953   "     enable ?BOOLEAN?         Set or query the enable bit",
20954   "     filter GLOB...           Reject tables matching GLOBs",
20955   "     indirect ?BOOLEAN?       Mark or query the indirect status",
20956   "     isempty                  Query whether the session is empty",
20957   "     list                     List currently open session names",
20958   "     open DB NAME             Open a new session on DB",
20959   "     patchset FILE            Write a patchset into FILE",
20960   "   If ?NAME? is omitted, the first defined session is used.",
20961 #endif
20962   ".sha3sum ...             Compute a SHA3 hash of database content",
20963   "    Options:",
20964   "      --schema              Also hash the sqlite_schema table",
20965   "      --sha3-224            Use the sha3-224 algorithm",
20966   "      --sha3-256            Use the sha3-256 algorithm (default)",
20967   "      --sha3-384            Use the sha3-384 algorithm",
20968   "      --sha3-512            Use the sha3-512 algorithm",
20969   "    Any other argument is a LIKE pattern for tables to hash",
20970 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
20971   ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
20972 #endif
20973   ".show                    Show the current values for various settings",
20974   ".stats ?ARG?             Show stats or turn stats on or off",
20975   "   off                      Turn off automatic stat display",
20976   "   on                       Turn on automatic stat display",
20977   "   stmt                     Show statement stats",
20978   "   vmstep                   Show the virtual machine step count only",
20979 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
20980   ".system CMD ARGS...      Run CMD ARGS... in a system shell",
20981 #endif
20982   ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
20983 #ifndef SQLITE_SHELL_FIDDLE
20984   ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
20985 #endif
20986   ",testctrl CMD ...        Run various sqlite3_test_control() operations",
20987   "                           Run \".testctrl\" with no arguments for details",
20988   ".timeout MS              Try opening locked tables for MS milliseconds",
20989   ".timer on|off            Turn SQL timer on or off",
20990 #ifndef SQLITE_OMIT_TRACE
20991   ".trace ?OPTIONS?         Output each SQL statement as it is run",
20992   "    FILE                    Send output to FILE",
20993   "    stdout                  Send output to stdout",
20994   "    stderr                  Send output to stderr",
20995   "    off                     Disable tracing",
20996   "    --expanded              Expand query parameters",
20997 #ifdef SQLITE_ENABLE_NORMALIZE
20998   "    --normalized            Normal the SQL statements",
20999 #endif
21000   "    --plain                 Show SQL as it is input",
21001   "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
21002   "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
21003   "    --row                   Trace each row (SQLITE_TRACE_ROW)",
21004   "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
21005 #endif /* SQLITE_OMIT_TRACE */
21006 #ifdef SQLITE_DEBUG
21007   ".unmodule NAME ...       Unregister virtual table modules",
21008   "    --allexcept             Unregister everything except those named",
21009 #endif
21010   ".version                 Show source, library and compiler versions",
21011   ".vfsinfo ?AUX?           Information about the top-level VFS",
21012   ".vfslist                 List all available VFSes",
21013   ".vfsname ?AUX?           Print the name of the VFS stack",
21014   ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
21015   "     Negative values right-justify",
21016 };
21017 
21018 /*
21019 ** Output help text.
21020 **
21021 ** zPattern describes the set of commands for which help text is provided.
21022 ** If zPattern is NULL, then show all commands, but only give a one-line
21023 ** description of each.
21024 **
21025 ** Return the number of matches.
21026 */
21027 static int showHelp(FILE *out, const char *zPattern){
21028   int i = 0;
21029   int j = 0;
21030   int n = 0;
21031   char *zPat;
21032   if( zPattern==0
21033    || zPattern[0]=='0'
21034    || cli_strcmp(zPattern,"-a")==0
21035    || cli_strcmp(zPattern,"-all")==0
21036    || cli_strcmp(zPattern,"--all")==0
21037   ){
21038     enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
21039     enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
21040     /* Show all or most commands
21041     ** *zPattern==0   => summary of documented commands only
21042     ** *zPattern=='0' => whole help for undocumented commands
21043     ** Otherwise      => whole help for documented commands
21044     */
21045     enum HelpWanted hw = HW_SummaryOnly;
21046     enum HelpHave hh = HH_More;
21047     if( zPattern!=0 ){
21048       hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
21049     }
21050     for(i=0; i<ArraySize(azHelp); i++){
21051       switch( azHelp[i][0] ){
21052       case ',':
21053         hh = HH_Summary|HH_Undoc;
21054         break;
21055       case '.':
21056         hh = HH_Summary;
21057         break;
21058       default:
21059         hh &= ~HH_Summary;
21060         break;
21061       }
21062       if( ((hw^hh)&HH_Undoc)==0 ){
21063         if( (hh&HH_Summary)!=0 ){
21064           utf8_printf(out, ".%s\n", azHelp[i]+1);
21065           ++n;
21066         }else if( (hw&HW_SummaryOnly)==0 ){
21067           utf8_printf(out, "%s\n", azHelp[i]);
21068         }
21069       }
21070     }
21071   }else{
21072     /* Seek documented commands for which zPattern is an exact prefix */
21073     zPat = sqlite3_mprintf(".%s*", zPattern);
21074     shell_check_oom(zPat);
21075     for(i=0; i<ArraySize(azHelp); i++){
21076       if( sqlite3_strglob(zPat, azHelp[i])==0 ){
21077         utf8_printf(out, "%s\n", azHelp[i]);
21078         j = i+1;
21079         n++;
21080       }
21081     }
21082     sqlite3_free(zPat);
21083     if( n ){
21084       if( n==1 ){
21085         /* when zPattern is a prefix of exactly one command, then include
21086         ** the details of that command, which should begin at offset j */
21087         while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
21088           utf8_printf(out, "%s\n", azHelp[j]);
21089           j++;
21090         }
21091       }
21092       return n;
21093     }
21094     /* Look for documented commands that contain zPattern anywhere.
21095     ** Show complete text of all documented commands that match. */
21096     zPat = sqlite3_mprintf("%%%s%%", zPattern);
21097     shell_check_oom(zPat);
21098     for(i=0; i<ArraySize(azHelp); i++){
21099       if( azHelp[i][0]==',' ){
21100         while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
21101         continue;
21102       }
21103       if( azHelp[i][0]=='.' ) j = i;
21104       if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
21105         utf8_printf(out, "%s\n", azHelp[j]);
21106         while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
21107           j++;
21108           utf8_printf(out, "%s\n", azHelp[j]);
21109         }
21110         i = j;
21111         n++;
21112       }
21113     }
21114     sqlite3_free(zPat);
21115   }
21116   return n;
21117 }
21118 
21119 /* Forward reference */
21120 static int process_input(ShellState *p);
21121 
21122 /*
21123 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
21124 ** and return a pointer to the buffer. The caller is responsible for freeing
21125 ** the memory.
21126 **
21127 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
21128 ** read.
21129 **
21130 ** For convenience, a nul-terminator byte is always appended to the data read
21131 ** from the file before the buffer is returned. This byte is not included in
21132 ** the final value of (*pnByte), if applicable.
21133 **
21134 ** NULL is returned if any error is encountered. The final value of *pnByte
21135 ** is undefined in this case.
21136 */
21137 static char *readFile(const char *zName, int *pnByte){
21138   FILE *in = fopen(zName, "rb");
21139   long nIn;
21140   size_t nRead;
21141   char *pBuf;
21142   int rc;
21143   if( in==0 ) return 0;
21144   rc = fseek(in, 0, SEEK_END);
21145   if( rc!=0 ){
21146     raw_printf(stderr, "Error: '%s' not seekable\n", zName);
21147     fclose(in);
21148     return 0;
21149   }
21150   nIn = ftell(in);
21151   rewind(in);
21152   pBuf = sqlite3_malloc64( nIn+1 );
21153   if( pBuf==0 ){
21154     raw_printf(stderr, "Error: out of memory\n");
21155     fclose(in);
21156     return 0;
21157   }
21158   nRead = fread(pBuf, nIn, 1, in);
21159   fclose(in);
21160   if( nRead!=1 ){
21161     sqlite3_free(pBuf);
21162     raw_printf(stderr, "Error: cannot read '%s'\n", zName);
21163     return 0;
21164   }
21165   pBuf[nIn] = 0;
21166   if( pnByte ) *pnByte = nIn;
21167   return pBuf;
21168 }
21169 
21170 #if defined(SQLITE_ENABLE_SESSION)
21171 /*
21172 ** Close a single OpenSession object and release all of its associated
21173 ** resources.
21174 */
21175 static void session_close(OpenSession *pSession){
21176   int i;
21177   sqlite3session_delete(pSession->p);
21178   sqlite3_free(pSession->zName);
21179   for(i=0; i<pSession->nFilter; i++){
21180     sqlite3_free(pSession->azFilter[i]);
21181   }
21182   sqlite3_free(pSession->azFilter);
21183   memset(pSession, 0, sizeof(OpenSession));
21184 }
21185 #endif
21186 
21187 /*
21188 ** Close all OpenSession objects and release all associated resources.
21189 */
21190 #if defined(SQLITE_ENABLE_SESSION)
21191 static void session_close_all(ShellState *p, int i){
21192   int j;
21193   struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
21194   for(j=0; j<pAuxDb->nSession; j++){
21195     session_close(&pAuxDb->aSession[j]);
21196   }
21197   pAuxDb->nSession = 0;
21198 }
21199 #else
21200 # define session_close_all(X,Y)
21201 #endif
21202 
21203 /*
21204 ** Implementation of the xFilter function for an open session.  Omit
21205 ** any tables named by ".session filter" but let all other table through.
21206 */
21207 #if defined(SQLITE_ENABLE_SESSION)
21208 static int session_filter(void *pCtx, const char *zTab){
21209   OpenSession *pSession = (OpenSession*)pCtx;
21210   int i;
21211   for(i=0; i<pSession->nFilter; i++){
21212     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
21213   }
21214   return 1;
21215 }
21216 #endif
21217 
21218 /*
21219 ** Try to deduce the type of file for zName based on its content.  Return
21220 ** one of the SHELL_OPEN_* constants.
21221 **
21222 ** If the file does not exist or is empty but its name looks like a ZIP
21223 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
21224 ** Otherwise, assume an ordinary database regardless of the filename if
21225 ** the type cannot be determined from content.
21226 */
21227 int deduceDatabaseType(const char *zName, int dfltZip){
21228   FILE *f = fopen(zName, "rb");
21229   size_t n;
21230   int rc = SHELL_OPEN_UNSPEC;
21231   char zBuf[100];
21232   if( f==0 ){
21233     if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
21234        return SHELL_OPEN_ZIPFILE;
21235     }else{
21236        return SHELL_OPEN_NORMAL;
21237     }
21238   }
21239   n = fread(zBuf, 16, 1, f);
21240   if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
21241     fclose(f);
21242     return SHELL_OPEN_NORMAL;
21243   }
21244   fseek(f, -25, SEEK_END);
21245   n = fread(zBuf, 25, 1, f);
21246   if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
21247     rc = SHELL_OPEN_APPENDVFS;
21248   }else{
21249     fseek(f, -22, SEEK_END);
21250     n = fread(zBuf, 22, 1, f);
21251     if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
21252        && zBuf[3]==0x06 ){
21253       rc = SHELL_OPEN_ZIPFILE;
21254     }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
21255       rc = SHELL_OPEN_ZIPFILE;
21256     }
21257   }
21258   fclose(f);
21259   return rc;
21260 }
21261 
21262 #ifndef SQLITE_OMIT_DESERIALIZE
21263 /*
21264 ** Reconstruct an in-memory database using the output from the "dbtotxt"
21265 ** program.  Read content from the file in p->aAuxDb[].zDbFilename.
21266 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
21267 */
21268 static unsigned char *readHexDb(ShellState *p, int *pnData){
21269   unsigned char *a = 0;
21270   int nLine;
21271   int n = 0;
21272   int pgsz = 0;
21273   int iOffset = 0;
21274   int j, k;
21275   int rc;
21276   FILE *in;
21277   const char *zDbFilename = p->pAuxDb->zDbFilename;
21278   unsigned int x[16];
21279   char zLine[1000];
21280   if( zDbFilename ){
21281     in = fopen(zDbFilename, "r");
21282     if( in==0 ){
21283       utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
21284       return 0;
21285     }
21286     nLine = 0;
21287   }else{
21288     in = p->in;
21289     nLine = p->lineno;
21290     if( in==0 ) in = stdin;
21291   }
21292   *pnData = 0;
21293   nLine++;
21294   if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
21295   rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
21296   if( rc!=2 ) goto readHexDb_error;
21297   if( n<0 ) goto readHexDb_error;
21298   if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
21299   n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
21300   a = sqlite3_malloc( n ? n : 1 );
21301   shell_check_oom(a);
21302   memset(a, 0, n);
21303   if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
21304     utf8_printf(stderr, "invalid pagesize\n");
21305     goto readHexDb_error;
21306   }
21307   for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
21308     rc = sscanf(zLine, "| page %d offset %d", &j, &k);
21309     if( rc==2 ){
21310       iOffset = k;
21311       continue;
21312     }
21313     if( cli_strncmp(zLine, "| end ", 6)==0 ){
21314       break;
21315     }
21316     rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
21317                 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
21318                 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
21319     if( rc==17 ){
21320       k = iOffset+j;
21321       if( k+16<=n && k>=0 ){
21322         int ii;
21323         for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
21324       }
21325     }
21326   }
21327   *pnData = n;
21328   if( in!=p->in ){
21329     fclose(in);
21330   }else{
21331     p->lineno = nLine;
21332   }
21333   return a;
21334 
21335 readHexDb_error:
21336   if( in!=p->in ){
21337     fclose(in);
21338   }else{
21339     while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
21340       nLine++;
21341       if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
21342     }
21343     p->lineno = nLine;
21344   }
21345   sqlite3_free(a);
21346   utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
21347   return 0;
21348 }
21349 #endif /* SQLITE_OMIT_DESERIALIZE */
21350 
21351 /*
21352 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
21353 */
21354 static void shellUSleepFunc(
21355   sqlite3_context *context,
21356   int argcUnused,
21357   sqlite3_value **argv
21358 ){
21359   int sleep = sqlite3_value_int(argv[0]);
21360   (void)argcUnused;
21361   sqlite3_sleep(sleep/1000);
21362   sqlite3_result_int(context, sleep);
21363 }
21364 
21365 /* Flags for open_db().
21366 **
21367 ** The default behavior of open_db() is to exit(1) if the database fails to
21368 ** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
21369 ** but still returns without calling exit.
21370 **
21371 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
21372 ** ZIP archive if the file does not exist or is empty and its name matches
21373 ** the *.zip pattern.
21374 */
21375 #define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
21376 #define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
21377 
21378 /*
21379 ** Make sure the database is open.  If it is not, then open it.  If
21380 ** the database fails to open, print an error message and exit.
21381 */
21382 static void open_db(ShellState *p, int openFlags){
21383   if( p->db==0 ){
21384     const char *zDbFilename = p->pAuxDb->zDbFilename;
21385     if( p->openMode==SHELL_OPEN_UNSPEC ){
21386       if( zDbFilename==0 || zDbFilename[0]==0 ){
21387         p->openMode = SHELL_OPEN_NORMAL;
21388       }else{
21389         p->openMode = (u8)deduceDatabaseType(zDbFilename,
21390                              (openFlags & OPEN_DB_ZIPFILE)!=0);
21391       }
21392     }
21393     switch( p->openMode ){
21394       case SHELL_OPEN_APPENDVFS: {
21395         sqlite3_open_v2(zDbFilename, &p->db,
21396            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
21397         break;
21398       }
21399       case SHELL_OPEN_HEXDB:
21400       case SHELL_OPEN_DESERIALIZE: {
21401         sqlite3_open(0, &p->db);
21402         break;
21403       }
21404       case SHELL_OPEN_ZIPFILE: {
21405         sqlite3_open(":memory:", &p->db);
21406         break;
21407       }
21408       case SHELL_OPEN_READONLY: {
21409         sqlite3_open_v2(zDbFilename, &p->db,
21410             SQLITE_OPEN_READONLY|p->openFlags, 0);
21411         break;
21412       }
21413       case SHELL_OPEN_UNSPEC:
21414       case SHELL_OPEN_NORMAL: {
21415         sqlite3_open_v2(zDbFilename, &p->db,
21416            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
21417         break;
21418       }
21419     }
21420     globalDb = p->db;
21421     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
21422       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
21423           zDbFilename, sqlite3_errmsg(p->db));
21424       if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
21425         exit(1);
21426       }
21427       sqlite3_close(p->db);
21428       sqlite3_open(":memory:", &p->db);
21429       if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
21430         utf8_printf(stderr,
21431           "Also: unable to open substitute in-memory database.\n"
21432         );
21433         exit(1);
21434       }else{
21435         utf8_printf(stderr,
21436           "Notice: using substitute in-memory database instead of \"%s\"\n",
21437           zDbFilename);
21438       }
21439     }
21440     sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
21441 
21442     /* Reflect the use or absence of --unsafe-testing invocation. */
21443     {
21444       int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
21445       sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
21446       sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
21447     }
21448 
21449 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21450     sqlite3_enable_load_extension(p->db, 1);
21451 #endif
21452     sqlite3_shathree_init(p->db, 0, 0);
21453     sqlite3_uint_init(p->db, 0, 0);
21454     sqlite3_decimal_init(p->db, 0, 0);
21455     sqlite3_base64_init(p->db, 0, 0);
21456     sqlite3_base85_init(p->db, 0, 0);
21457     sqlite3_regexp_init(p->db, 0, 0);
21458     sqlite3_ieee_init(p->db, 0, 0);
21459     sqlite3_series_init(p->db, 0, 0);
21460 #ifndef SQLITE_SHELL_FIDDLE
21461     sqlite3_fileio_init(p->db, 0, 0);
21462     sqlite3_completion_init(p->db, 0, 0);
21463 #endif
21464 #ifdef SQLITE_HAVE_ZLIB
21465     if( !p->bSafeModePersist ){
21466       sqlite3_zipfile_init(p->db, 0, 0);
21467       sqlite3_sqlar_init(p->db, 0, 0);
21468     }
21469 #endif
21470 #ifdef SQLITE_SHELL_EXTFUNCS
21471     /* Create a preprocessing mechanism for extensions to make
21472      * their own provisions for being built into the shell.
21473      * This is a short-span macro. See further below for usage.
21474      */
21475 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
21476 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
21477     /* Let custom-included extensions get their ..._init() called.
21478      * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
21479      * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
21480      * initialization routine to be called.
21481      */
21482     {
21483       int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
21484     /* Let custom-included extensions expose their functionality.
21485      * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
21486      * the SQL functions, virtual tables, collating sequences or
21487      * VFS's implemented by the extension to be registered.
21488      */
21489       if( irc==SQLITE_OK
21490           || irc==SQLITE_OK_LOAD_PERMANENTLY ){
21491         SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
21492       }
21493 #undef SHELL_SUB_MACRO
21494 #undef SHELL_SUBMACRO
21495     }
21496 #endif
21497 
21498     sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
21499                             shellStrtod, 0, 0);
21500     sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
21501                             shellDtostr, 0, 0);
21502     sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
21503                             shellDtostr, 0, 0);
21504     sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
21505                             shellAddSchemaName, 0, 0);
21506     sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
21507                             shellModuleSchema, 0, 0);
21508     sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
21509                             shellPutsFunc, 0, 0);
21510     sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
21511                             shellUSleepFunc, 0, 0);
21512 #ifndef SQLITE_NOHAVE_SYSTEM
21513     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
21514                             editFunc, 0, 0);
21515     sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
21516                             editFunc, 0, 0);
21517 #endif
21518 
21519     if( p->openMode==SHELL_OPEN_ZIPFILE ){
21520       char *zSql = sqlite3_mprintf(
21521          "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
21522       shell_check_oom(zSql);
21523       sqlite3_exec(p->db, zSql, 0, 0, 0);
21524       sqlite3_free(zSql);
21525     }
21526 #ifndef SQLITE_OMIT_DESERIALIZE
21527     else
21528     if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
21529       int rc;
21530       int nData = 0;
21531       unsigned char *aData;
21532       if( p->openMode==SHELL_OPEN_DESERIALIZE ){
21533         aData = (unsigned char*)readFile(zDbFilename, &nData);
21534       }else{
21535         aData = readHexDb(p, &nData);
21536       }
21537       if( aData==0 ){
21538         return;
21539       }
21540       rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
21541                    SQLITE_DESERIALIZE_RESIZEABLE |
21542                    SQLITE_DESERIALIZE_FREEONCLOSE);
21543       if( rc ){
21544         utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
21545       }
21546       if( p->szMax>0 ){
21547         sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
21548       }
21549     }
21550 #endif
21551   }
21552   if( p->db!=0 ){
21553     if( p->bSafeModePersist ){
21554       sqlite3_set_authorizer(p->db, safeModeAuth, p);
21555     }
21556     sqlite3_db_config(
21557         p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
21558     );
21559   }
21560 }
21561 
21562 /*
21563 ** Attempt to close the database connection.  Report errors.
21564 */
21565 void close_db(sqlite3 *db){
21566   int rc = sqlite3_close(db);
21567   if( rc ){
21568     utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
21569         rc, sqlite3_errmsg(db));
21570   }
21571 }
21572 
21573 #if HAVE_READLINE || HAVE_EDITLINE
21574 /*
21575 ** Readline completion callbacks
21576 */
21577 static char *readline_completion_generator(const char *text, int state){
21578   static sqlite3_stmt *pStmt = 0;
21579   char *zRet;
21580   if( state==0 ){
21581     char *zSql;
21582     sqlite3_finalize(pStmt);
21583     zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
21584                            "  FROM completion(%Q) ORDER BY 1", text);
21585     shell_check_oom(zSql);
21586     sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
21587     sqlite3_free(zSql);
21588   }
21589   if( sqlite3_step(pStmt)==SQLITE_ROW ){
21590     const char *z = (const char*)sqlite3_column_text(pStmt,0);
21591     zRet = z ? strdup(z) : 0;
21592   }else{
21593     sqlite3_finalize(pStmt);
21594     pStmt = 0;
21595     zRet = 0;
21596   }
21597   return zRet;
21598 }
21599 static char **readline_completion(const char *zText, int iStart, int iEnd){
21600   (void)iStart;
21601   (void)iEnd;
21602   rl_attempted_completion_over = 1;
21603   return rl_completion_matches(zText, readline_completion_generator);
21604 }
21605 
21606 #elif HAVE_LINENOISE
21607 /*
21608 ** Linenoise completion callback
21609 */
21610 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
21611   i64 nLine = strlen(zLine);
21612   i64 i, iStart;
21613   sqlite3_stmt *pStmt = 0;
21614   char *zSql;
21615   char zBuf[1000];
21616 
21617   if( nLine>(i64)sizeof(zBuf)-30 ) return;
21618   if( zLine[0]=='.' || zLine[0]=='#') return;
21619   for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
21620   if( i==nLine-1 ) return;
21621   iStart = i+1;
21622   memcpy(zBuf, zLine, iStart);
21623   zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
21624                          "  FROM completion(%Q,%Q) ORDER BY 1",
21625                          &zLine[iStart], zLine);
21626   shell_check_oom(zSql);
21627   sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
21628   sqlite3_free(zSql);
21629   sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
21630   while( sqlite3_step(pStmt)==SQLITE_ROW ){
21631     const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
21632     int nCompletion = sqlite3_column_bytes(pStmt, 0);
21633     if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
21634       memcpy(zBuf+iStart, zCompletion, nCompletion+1);
21635       linenoiseAddCompletion(lc, zBuf);
21636     }
21637   }
21638   sqlite3_finalize(pStmt);
21639 }
21640 #endif
21641 
21642 /*
21643 ** Do C-language style dequoting.
21644 **
21645 **    \a    -> alarm
21646 **    \b    -> backspace
21647 **    \t    -> tab
21648 **    \n    -> newline
21649 **    \v    -> vertical tab
21650 **    \f    -> form feed
21651 **    \r    -> carriage return
21652 **    \s    -> space
21653 **    \"    -> "
21654 **    \'    -> '
21655 **    \\    -> backslash
21656 **    \NNN  -> ascii character NNN in octal
21657 **    \xHH  -> ascii character HH in hexadecimal
21658 */
21659 static void resolve_backslashes(char *z){
21660   int i, j;
21661   char c;
21662   while( *z && *z!='\\' ) z++;
21663   for(i=j=0; (c = z[i])!=0; i++, j++){
21664     if( c=='\\' && z[i+1]!=0 ){
21665       c = z[++i];
21666       if( c=='a' ){
21667         c = '\a';
21668       }else if( c=='b' ){
21669         c = '\b';
21670       }else if( c=='t' ){
21671         c = '\t';
21672       }else if( c=='n' ){
21673         c = '\n';
21674       }else if( c=='v' ){
21675         c = '\v';
21676       }else if( c=='f' ){
21677         c = '\f';
21678       }else if( c=='r' ){
21679         c = '\r';
21680       }else if( c=='"' ){
21681         c = '"';
21682       }else if( c=='\'' ){
21683         c = '\'';
21684       }else if( c=='\\' ){
21685         c = '\\';
21686       }else if( c=='x' ){
21687         int nhd = 0, hdv;
21688         u8 hv = 0;
21689         while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
21690           hv = (u8)((hv<<4)|hdv);
21691           ++nhd;
21692         }
21693         i += nhd;
21694         c = (u8)hv;
21695       }else if( c>='0' && c<='7' ){
21696         c -= '0';
21697         if( z[i+1]>='0' && z[i+1]<='7' ){
21698           i++;
21699           c = (c<<3) + z[i] - '0';
21700           if( z[i+1]>='0' && z[i+1]<='7' ){
21701             i++;
21702             c = (c<<3) + z[i] - '0';
21703           }
21704         }
21705       }
21706     }
21707     z[j] = c;
21708   }
21709   if( j<i ) z[j] = 0;
21710 }
21711 
21712 /*
21713 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
21714 ** for TRUE and FALSE.  Return the integer value if appropriate.
21715 */
21716 static int booleanValue(const char *zArg){
21717   int i;
21718   if( zArg[0]=='0' && zArg[1]=='x' ){
21719     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
21720   }else{
21721     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
21722   }
21723   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
21724   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
21725     return 1;
21726   }
21727   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
21728     return 0;
21729   }
21730   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
21731           zArg);
21732   return 0;
21733 }
21734 
21735 /*
21736 ** Set or clear a shell flag according to a boolean value.
21737 */
21738 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
21739   if( booleanValue(zArg) ){
21740     ShellSetFlag(p, mFlag);
21741   }else{
21742     ShellClearFlag(p, mFlag);
21743   }
21744 }
21745 
21746 /*
21747 ** Close an output file, assuming it is not stderr or stdout
21748 */
21749 static void output_file_close(FILE *f){
21750   if( f && f!=stdout && f!=stderr ) fclose(f);
21751 }
21752 
21753 /*
21754 ** Try to open an output file.   The names "stdout" and "stderr" are
21755 ** recognized and do the right thing.  NULL is returned if the output
21756 ** filename is "off".
21757 */
21758 static FILE *output_file_open(const char *zFile, int bTextMode){
21759   FILE *f;
21760   if( cli_strcmp(zFile,"stdout")==0 ){
21761     f = stdout;
21762   }else if( cli_strcmp(zFile, "stderr")==0 ){
21763     f = stderr;
21764   }else if( cli_strcmp(zFile, "off")==0 ){
21765     f = 0;
21766   }else{
21767     f = fopen(zFile, bTextMode ? "w" : "wb");
21768     if( f==0 ){
21769       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
21770     }
21771   }
21772   return f;
21773 }
21774 
21775 #ifndef SQLITE_OMIT_TRACE
21776 /*
21777 ** A routine for handling output from sqlite3_trace().
21778 */
21779 static int sql_trace_callback(
21780   unsigned mType,         /* The trace type */
21781   void *pArg,             /* The ShellState pointer */
21782   void *pP,               /* Usually a pointer to sqlite_stmt */
21783   void *pX                /* Auxiliary output */
21784 ){
21785   ShellState *p = (ShellState*)pArg;
21786   sqlite3_stmt *pStmt;
21787   const char *zSql;
21788   i64 nSql;
21789   if( p->traceOut==0 ) return 0;
21790   if( mType==SQLITE_TRACE_CLOSE ){
21791     utf8_printf(p->traceOut, "-- closing database connection\n");
21792     return 0;
21793   }
21794   if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
21795     zSql = (const char*)pX;
21796   }else{
21797     pStmt = (sqlite3_stmt*)pP;
21798     switch( p->eTraceType ){
21799       case SHELL_TRACE_EXPANDED: {
21800         zSql = sqlite3_expanded_sql(pStmt);
21801         break;
21802       }
21803 #ifdef SQLITE_ENABLE_NORMALIZE
21804       case SHELL_TRACE_NORMALIZED: {
21805         zSql = sqlite3_normalized_sql(pStmt);
21806         break;
21807       }
21808 #endif
21809       default: {
21810         zSql = sqlite3_sql(pStmt);
21811         break;
21812       }
21813     }
21814   }
21815   if( zSql==0 ) return 0;
21816   nSql = strlen(zSql);
21817   if( nSql>1000000000 ) nSql = 1000000000;
21818   while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
21819   switch( mType ){
21820     case SQLITE_TRACE_ROW:
21821     case SQLITE_TRACE_STMT: {
21822       utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
21823       break;
21824     }
21825     case SQLITE_TRACE_PROFILE: {
21826       sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
21827       utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
21828       break;
21829     }
21830   }
21831   return 0;
21832 }
21833 #endif
21834 
21835 /*
21836 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
21837 ** a useful spot to set a debugger breakpoint.
21838 **
21839 ** This routine does not do anything practical.  The code are there simply
21840 ** to prevent the compiler from optimizing this routine out.
21841 */
21842 static void test_breakpoint(void){
21843   static unsigned int nCall = 0;
21844   if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
21845 }
21846 
21847 /*
21848 ** An object used to read a CSV and other files for import.
21849 */
21850 typedef struct ImportCtx ImportCtx;
21851 struct ImportCtx {
21852   const char *zFile;  /* Name of the input file */
21853   FILE *in;           /* Read the CSV text from this input stream */
21854   int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
21855   char *z;            /* Accumulated text for a field */
21856   int n;              /* Number of bytes in z */
21857   int nAlloc;         /* Space allocated for z[] */
21858   int nLine;          /* Current line number */
21859   int nRow;           /* Number of rows imported */
21860   int nErr;           /* Number of errors encountered */
21861   int bNotFirst;      /* True if one or more bytes already read */
21862   int cTerm;          /* Character that terminated the most recent field */
21863   int cColSep;        /* The column separator character.  (Usually ",") */
21864   int cRowSep;        /* The row separator character.  (Usually "\n") */
21865 };
21866 
21867 /* Clean up resourced used by an ImportCtx */
21868 static void import_cleanup(ImportCtx *p){
21869   if( p->in!=0 && p->xCloser!=0 ){
21870     p->xCloser(p->in);
21871     p->in = 0;
21872   }
21873   sqlite3_free(p->z);
21874   p->z = 0;
21875 }
21876 
21877 /* Append a single byte to z[] */
21878 static void import_append_char(ImportCtx *p, int c){
21879   if( p->n+1>=p->nAlloc ){
21880     p->nAlloc += p->nAlloc + 100;
21881     p->z = sqlite3_realloc64(p->z, p->nAlloc);
21882     shell_check_oom(p->z);
21883   }
21884   p->z[p->n++] = (char)c;
21885 }
21886 
21887 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
21888 ** with the option of having a separator other than ",".
21889 **
21890 **   +  Input comes from p->in.
21891 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
21892 **      from sqlite3_malloc64().
21893 **   +  Use p->cSep as the column separator.  The default is ",".
21894 **   +  Use p->rSep as the row separator.  The default is "\n".
21895 **   +  Keep track of the line number in p->nLine.
21896 **   +  Store the character that terminates the field in p->cTerm.  Store
21897 **      EOF on end-of-file.
21898 **   +  Report syntax errors on stderr
21899 */
21900 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
21901   int c;
21902   int cSep = (u8)p->cColSep;
21903   int rSep = (u8)p->cRowSep;
21904   p->n = 0;
21905   c = fgetc(p->in);
21906   if( c==EOF || seenInterrupt ){
21907     p->cTerm = EOF;
21908     return 0;
21909   }
21910   if( c=='"' ){
21911     int pc, ppc;
21912     int startLine = p->nLine;
21913     int cQuote = c;
21914     pc = ppc = 0;
21915     while( 1 ){
21916       c = fgetc(p->in);
21917       if( c==rSep ) p->nLine++;
21918       if( c==cQuote ){
21919         if( pc==cQuote ){
21920           pc = 0;
21921           continue;
21922         }
21923       }
21924       if( (c==cSep && pc==cQuote)
21925        || (c==rSep && pc==cQuote)
21926        || (c==rSep && pc=='\r' && ppc==cQuote)
21927        || (c==EOF && pc==cQuote)
21928       ){
21929         do{ p->n--; }while( p->z[p->n]!=cQuote );
21930         p->cTerm = c;
21931         break;
21932       }
21933       if( pc==cQuote && c!='\r' ){
21934         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
21935                 p->zFile, p->nLine, cQuote);
21936       }
21937       if( c==EOF ){
21938         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
21939                 p->zFile, startLine, cQuote);
21940         p->cTerm = c;
21941         break;
21942       }
21943       import_append_char(p, c);
21944       ppc = pc;
21945       pc = c;
21946     }
21947   }else{
21948     /* If this is the first field being parsed and it begins with the
21949     ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
21950     if( (c&0xff)==0xef && p->bNotFirst==0 ){
21951       import_append_char(p, c);
21952       c = fgetc(p->in);
21953       if( (c&0xff)==0xbb ){
21954         import_append_char(p, c);
21955         c = fgetc(p->in);
21956         if( (c&0xff)==0xbf ){
21957           p->bNotFirst = 1;
21958           p->n = 0;
21959           return csv_read_one_field(p);
21960         }
21961       }
21962     }
21963     while( c!=EOF && c!=cSep && c!=rSep ){
21964       import_append_char(p, c);
21965       c = fgetc(p->in);
21966     }
21967     if( c==rSep ){
21968       p->nLine++;
21969       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
21970     }
21971     p->cTerm = c;
21972   }
21973   if( p->z ) p->z[p->n] = 0;
21974   p->bNotFirst = 1;
21975   return p->z;
21976 }
21977 
21978 /* Read a single field of ASCII delimited text.
21979 **
21980 **   +  Input comes from p->in.
21981 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
21982 **      from sqlite3_malloc64().
21983 **   +  Use p->cSep as the column separator.  The default is "\x1F".
21984 **   +  Use p->rSep as the row separator.  The default is "\x1E".
21985 **   +  Keep track of the row number in p->nLine.
21986 **   +  Store the character that terminates the field in p->cTerm.  Store
21987 **      EOF on end-of-file.
21988 **   +  Report syntax errors on stderr
21989 */
21990 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
21991   int c;
21992   int cSep = (u8)p->cColSep;
21993   int rSep = (u8)p->cRowSep;
21994   p->n = 0;
21995   c = fgetc(p->in);
21996   if( c==EOF || seenInterrupt ){
21997     p->cTerm = EOF;
21998     return 0;
21999   }
22000   while( c!=EOF && c!=cSep && c!=rSep ){
22001     import_append_char(p, c);
22002     c = fgetc(p->in);
22003   }
22004   if( c==rSep ){
22005     p->nLine++;
22006   }
22007   p->cTerm = c;
22008   if( p->z ) p->z[p->n] = 0;
22009   return p->z;
22010 }
22011 
22012 /*
22013 ** Try to transfer data for table zTable.  If an error is seen while
22014 ** moving forward, try to go backwards.  The backwards movement won't
22015 ** work for WITHOUT ROWID tables.
22016 */
22017 static void tryToCloneData(
22018   ShellState *p,
22019   sqlite3 *newDb,
22020   const char *zTable
22021 ){
22022   sqlite3_stmt *pQuery = 0;
22023   sqlite3_stmt *pInsert = 0;
22024   char *zQuery = 0;
22025   char *zInsert = 0;
22026   int rc;
22027   int i, j, n;
22028   int nTable = strlen30(zTable);
22029   int k = 0;
22030   int cnt = 0;
22031   const int spinRate = 10000;
22032 
22033   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
22034   shell_check_oom(zQuery);
22035   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22036   if( rc ){
22037     utf8_printf(stderr, "Error %d: %s on [%s]\n",
22038             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
22039             zQuery);
22040     goto end_data_xfer;
22041   }
22042   n = sqlite3_column_count(pQuery);
22043   zInsert = sqlite3_malloc64(200 + nTable + n*3);
22044   shell_check_oom(zInsert);
22045   sqlite3_snprintf(200+nTable,zInsert,
22046                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
22047   i = strlen30(zInsert);
22048   for(j=1; j<n; j++){
22049     memcpy(zInsert+i, ",?", 2);
22050     i += 2;
22051   }
22052   memcpy(zInsert+i, ");", 3);
22053   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
22054   if( rc ){
22055     utf8_printf(stderr, "Error %d: %s on [%s]\n",
22056             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
22057             zInsert);
22058     goto end_data_xfer;
22059   }
22060   for(k=0; k<2; k++){
22061     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22062       for(i=0; i<n; i++){
22063         switch( sqlite3_column_type(pQuery, i) ){
22064           case SQLITE_NULL: {
22065             sqlite3_bind_null(pInsert, i+1);
22066             break;
22067           }
22068           case SQLITE_INTEGER: {
22069             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
22070             break;
22071           }
22072           case SQLITE_FLOAT: {
22073             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
22074             break;
22075           }
22076           case SQLITE_TEXT: {
22077             sqlite3_bind_text(pInsert, i+1,
22078                              (const char*)sqlite3_column_text(pQuery,i),
22079                              -1, SQLITE_STATIC);
22080             break;
22081           }
22082           case SQLITE_BLOB: {
22083             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
22084                                             sqlite3_column_bytes(pQuery,i),
22085                                             SQLITE_STATIC);
22086             break;
22087           }
22088         }
22089       } /* End for */
22090       rc = sqlite3_step(pInsert);
22091       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
22092         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
22093                         sqlite3_errmsg(newDb));
22094       }
22095       sqlite3_reset(pInsert);
22096       cnt++;
22097       if( (cnt%spinRate)==0 ){
22098         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
22099         fflush(stdout);
22100       }
22101     } /* End while */
22102     if( rc==SQLITE_DONE ) break;
22103     sqlite3_finalize(pQuery);
22104     sqlite3_free(zQuery);
22105     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
22106                              zTable);
22107     shell_check_oom(zQuery);
22108     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22109     if( rc ){
22110       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
22111       break;
22112     }
22113   } /* End for(k=0...) */
22114 
22115 end_data_xfer:
22116   sqlite3_finalize(pQuery);
22117   sqlite3_finalize(pInsert);
22118   sqlite3_free(zQuery);
22119   sqlite3_free(zInsert);
22120 }
22121 
22122 
22123 /*
22124 ** Try to transfer all rows of the schema that match zWhere.  For
22125 ** each row, invoke xForEach() on the object defined by that row.
22126 ** If an error is encountered while moving forward through the
22127 ** sqlite_schema table, try again moving backwards.
22128 */
22129 static void tryToCloneSchema(
22130   ShellState *p,
22131   sqlite3 *newDb,
22132   const char *zWhere,
22133   void (*xForEach)(ShellState*,sqlite3*,const char*)
22134 ){
22135   sqlite3_stmt *pQuery = 0;
22136   char *zQuery = 0;
22137   int rc;
22138   const unsigned char *zName;
22139   const unsigned char *zSql;
22140   char *zErrMsg = 0;
22141 
22142   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22143                            " WHERE %s ORDER BY rowid ASC", zWhere);
22144   shell_check_oom(zQuery);
22145   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22146   if( rc ){
22147     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
22148                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
22149                     zQuery);
22150     goto end_schema_xfer;
22151   }
22152   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
22153     zName = sqlite3_column_text(pQuery, 0);
22154     zSql = sqlite3_column_text(pQuery, 1);
22155     if( zName==0 || zSql==0 ) continue;
22156     if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
22157       printf("%s... ", zName); fflush(stdout);
22158       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22159       if( zErrMsg ){
22160         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22161         sqlite3_free(zErrMsg);
22162         zErrMsg = 0;
22163       }
22164     }
22165     if( xForEach ){
22166       xForEach(p, newDb, (const char*)zName);
22167     }
22168     printf("done\n");
22169   }
22170   if( rc!=SQLITE_DONE ){
22171     sqlite3_finalize(pQuery);
22172     sqlite3_free(zQuery);
22173     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
22174                              " WHERE %s ORDER BY rowid DESC", zWhere);
22175     shell_check_oom(zQuery);
22176     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
22177     if( rc ){
22178       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
22179                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
22180                       zQuery);
22181       goto end_schema_xfer;
22182     }
22183     while( sqlite3_step(pQuery)==SQLITE_ROW ){
22184       zName = sqlite3_column_text(pQuery, 0);
22185       zSql = sqlite3_column_text(pQuery, 1);
22186       if( zName==0 || zSql==0 ) continue;
22187       if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
22188       printf("%s... ", zName); fflush(stdout);
22189       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
22190       if( zErrMsg ){
22191         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
22192         sqlite3_free(zErrMsg);
22193         zErrMsg = 0;
22194       }
22195       if( xForEach ){
22196         xForEach(p, newDb, (const char*)zName);
22197       }
22198       printf("done\n");
22199     }
22200   }
22201 end_schema_xfer:
22202   sqlite3_finalize(pQuery);
22203   sqlite3_free(zQuery);
22204 }
22205 
22206 /*
22207 ** Open a new database file named "zNewDb".  Try to recover as much information
22208 ** as possible out of the main database (which might be corrupt) and write it
22209 ** into zNewDb.
22210 */
22211 static void tryToClone(ShellState *p, const char *zNewDb){
22212   int rc;
22213   sqlite3 *newDb = 0;
22214   if( access(zNewDb,0)==0 ){
22215     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
22216     return;
22217   }
22218   rc = sqlite3_open(zNewDb, &newDb);
22219   if( rc ){
22220     utf8_printf(stderr, "Cannot create output database: %s\n",
22221             sqlite3_errmsg(newDb));
22222   }else{
22223     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
22224     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
22225     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
22226     tryToCloneSchema(p, newDb, "type!='table'", 0);
22227     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
22228     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
22229   }
22230   close_db(newDb);
22231 }
22232 
22233 /*
22234 ** Change the output file back to stdout.
22235 **
22236 ** If the p->doXdgOpen flag is set, that means the output was being
22237 ** redirected to a temporary file named by p->zTempFile.  In that case,
22238 ** launch start/open/xdg-open on that temporary file.
22239 */
22240 static void output_reset(ShellState *p){
22241   if( p->outfile[0]=='|' ){
22242 #ifndef SQLITE_OMIT_POPEN
22243     pclose(p->out);
22244 #endif
22245   }else{
22246     output_file_close(p->out);
22247 #ifndef SQLITE_NOHAVE_SYSTEM
22248     if( p->doXdgOpen ){
22249       const char *zXdgOpenCmd =
22250 #if defined(_WIN32)
22251       "start";
22252 #elif defined(__APPLE__)
22253       "open";
22254 #else
22255       "xdg-open";
22256 #endif
22257       char *zCmd;
22258       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
22259       if( system(zCmd) ){
22260         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
22261       }else{
22262         /* Give the start/open/xdg-open command some time to get
22263         ** going before we continue, and potential delete the
22264         ** p->zTempFile data file out from under it */
22265         sqlite3_sleep(2000);
22266       }
22267       sqlite3_free(zCmd);
22268       outputModePop(p);
22269       p->doXdgOpen = 0;
22270     }
22271 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
22272   }
22273   p->outfile[0] = 0;
22274   p->out = stdout;
22275 }
22276 
22277 /*
22278 ** Run an SQL command and return the single integer result.
22279 */
22280 static int db_int(sqlite3 *db, const char *zSql){
22281   sqlite3_stmt *pStmt;
22282   int res = 0;
22283   sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
22284   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
22285     res = sqlite3_column_int(pStmt,0);
22286   }
22287   sqlite3_finalize(pStmt);
22288   return res;
22289 }
22290 
22291 #if SQLITE_SHELL_HAVE_RECOVER
22292 /*
22293 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
22294 */
22295 static unsigned int get2byteInt(unsigned char *a){
22296   return (a[0]<<8) + a[1];
22297 }
22298 static unsigned int get4byteInt(unsigned char *a){
22299   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
22300 }
22301 
22302 /*
22303 ** Implementation of the ".dbinfo" command.
22304 **
22305 ** Return 1 on error, 2 to exit, and 0 otherwise.
22306 */
22307 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
22308   static const struct { const char *zName; int ofst; } aField[] = {
22309      { "file change counter:",  24  },
22310      { "database page count:",  28  },
22311      { "freelist page count:",  36  },
22312      { "schema cookie:",        40  },
22313      { "schema format:",        44  },
22314      { "default cache size:",   48  },
22315      { "autovacuum top root:",  52  },
22316      { "incremental vacuum:",   64  },
22317      { "text encoding:",        56  },
22318      { "user version:",         60  },
22319      { "application id:",       68  },
22320      { "software version:",     96  },
22321   };
22322   static const struct { const char *zName; const char *zSql; } aQuery[] = {
22323      { "number of tables:",
22324        "SELECT count(*) FROM %s WHERE type='table'" },
22325      { "number of indexes:",
22326        "SELECT count(*) FROM %s WHERE type='index'" },
22327      { "number of triggers:",
22328        "SELECT count(*) FROM %s WHERE type='trigger'" },
22329      { "number of views:",
22330        "SELECT count(*) FROM %s WHERE type='view'" },
22331      { "schema size:",
22332        "SELECT total(length(sql)) FROM %s" },
22333   };
22334   int i, rc;
22335   unsigned iDataVersion;
22336   char *zSchemaTab;
22337   char *zDb = nArg>=2 ? azArg[1] : "main";
22338   sqlite3_stmt *pStmt = 0;
22339   unsigned char aHdr[100];
22340   open_db(p, 0);
22341   if( p->db==0 ) return 1;
22342   rc = sqlite3_prepare_v2(p->db,
22343              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
22344              -1, &pStmt, 0);
22345   if( rc ){
22346     utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
22347     sqlite3_finalize(pStmt);
22348     return 1;
22349   }
22350   sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
22351   if( sqlite3_step(pStmt)==SQLITE_ROW
22352    && sqlite3_column_bytes(pStmt,0)>100
22353   ){
22354     const u8 *pb = sqlite3_column_blob(pStmt,0);
22355     shell_check_oom(pb);
22356     memcpy(aHdr, pb, 100);
22357     sqlite3_finalize(pStmt);
22358   }else{
22359     raw_printf(stderr, "unable to read database header\n");
22360     sqlite3_finalize(pStmt);
22361     return 1;
22362   }
22363   i = get2byteInt(aHdr+16);
22364   if( i==1 ) i = 65536;
22365   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
22366   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
22367   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
22368   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
22369   for(i=0; i<ArraySize(aField); i++){
22370     int ofst = aField[i].ofst;
22371     unsigned int val = get4byteInt(aHdr + ofst);
22372     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
22373     switch( ofst ){
22374       case 56: {
22375         if( val==1 ) raw_printf(p->out, " (utf8)");
22376         if( val==2 ) raw_printf(p->out, " (utf16le)");
22377         if( val==3 ) raw_printf(p->out, " (utf16be)");
22378       }
22379     }
22380     raw_printf(p->out, "\n");
22381   }
22382   if( zDb==0 ){
22383     zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
22384   }else if( cli_strcmp(zDb,"temp")==0 ){
22385     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
22386   }else{
22387     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
22388   }
22389   for(i=0; i<ArraySize(aQuery); i++){
22390     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
22391     int val = db_int(p->db, zSql);
22392     sqlite3_free(zSql);
22393     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
22394   }
22395   sqlite3_free(zSchemaTab);
22396   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
22397   utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
22398   return 0;
22399 }
22400 #endif /* SQLITE_SHELL_HAVE_RECOVER */
22401 
22402 /*
22403 ** Print the current sqlite3_errmsg() value to stderr and return 1.
22404 */
22405 static int shellDatabaseError(sqlite3 *db){
22406   const char *zErr = sqlite3_errmsg(db);
22407   utf8_printf(stderr, "Error: %s\n", zErr);
22408   return 1;
22409 }
22410 
22411 /*
22412 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
22413 ** if they match and FALSE (0) if they do not match.
22414 **
22415 ** Globbing rules:
22416 **
22417 **      '*'       Matches any sequence of zero or more characters.
22418 **
22419 **      '?'       Matches exactly one character.
22420 **
22421 **     [...]      Matches one character from the enclosed list of
22422 **                characters.
22423 **
22424 **     [^...]     Matches one character not in the enclosed list.
22425 **
22426 **      '#'       Matches any sequence of one or more digits with an
22427 **                optional + or - sign in front
22428 **
22429 **      ' '       Any span of whitespace matches any other span of
22430 **                whitespace.
22431 **
22432 ** Extra whitespace at the end of z[] is ignored.
22433 */
22434 static int testcase_glob(const char *zGlob, const char *z){
22435   int c, c2;
22436   int invert;
22437   int seen;
22438 
22439   while( (c = (*(zGlob++)))!=0 ){
22440     if( IsSpace(c) ){
22441       if( !IsSpace(*z) ) return 0;
22442       while( IsSpace(*zGlob) ) zGlob++;
22443       while( IsSpace(*z) ) z++;
22444     }else if( c=='*' ){
22445       while( (c=(*(zGlob++))) == '*' || c=='?' ){
22446         if( c=='?' && (*(z++))==0 ) return 0;
22447       }
22448       if( c==0 ){
22449         return 1;
22450       }else if( c=='[' ){
22451         while( *z && testcase_glob(zGlob-1,z)==0 ){
22452           z++;
22453         }
22454         return (*z)!=0;
22455       }
22456       while( (c2 = (*(z++)))!=0 ){
22457         while( c2!=c ){
22458           c2 = *(z++);
22459           if( c2==0 ) return 0;
22460         }
22461         if( testcase_glob(zGlob,z) ) return 1;
22462       }
22463       return 0;
22464     }else if( c=='?' ){
22465       if( (*(z++))==0 ) return 0;
22466     }else if( c=='[' ){
22467       int prior_c = 0;
22468       seen = 0;
22469       invert = 0;
22470       c = *(z++);
22471       if( c==0 ) return 0;
22472       c2 = *(zGlob++);
22473       if( c2=='^' ){
22474         invert = 1;
22475         c2 = *(zGlob++);
22476       }
22477       if( c2==']' ){
22478         if( c==']' ) seen = 1;
22479         c2 = *(zGlob++);
22480       }
22481       while( c2 && c2!=']' ){
22482         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
22483           c2 = *(zGlob++);
22484           if( c>=prior_c && c<=c2 ) seen = 1;
22485           prior_c = 0;
22486         }else{
22487           if( c==c2 ){
22488             seen = 1;
22489           }
22490           prior_c = c2;
22491         }
22492         c2 = *(zGlob++);
22493       }
22494       if( c2==0 || (seen ^ invert)==0 ) return 0;
22495     }else if( c=='#' ){
22496       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
22497       if( !IsDigit(z[0]) ) return 0;
22498       z++;
22499       while( IsDigit(z[0]) ){ z++; }
22500     }else{
22501       if( c!=(*(z++)) ) return 0;
22502     }
22503   }
22504   while( IsSpace(*z) ){ z++; }
22505   return *z==0;
22506 }
22507 
22508 
22509 /*
22510 ** Compare the string as a command-line option with either one or two
22511 ** initial "-" characters.
22512 */
22513 static int optionMatch(const char *zStr, const char *zOpt){
22514   if( zStr[0]!='-' ) return 0;
22515   zStr++;
22516   if( zStr[0]=='-' ) zStr++;
22517   return cli_strcmp(zStr, zOpt)==0;
22518 }
22519 
22520 /*
22521 ** Delete a file.
22522 */
22523 int shellDeleteFile(const char *zFilename){
22524   int rc;
22525 #ifdef _WIN32
22526   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
22527   rc = _wunlink(z);
22528   sqlite3_free(z);
22529 #else
22530   rc = unlink(zFilename);
22531 #endif
22532   return rc;
22533 }
22534 
22535 /*
22536 ** Try to delete the temporary file (if there is one) and free the
22537 ** memory used to hold the name of the temp file.
22538 */
22539 static void clearTempFile(ShellState *p){
22540   if( p->zTempFile==0 ) return;
22541   if( p->doXdgOpen ) return;
22542   if( shellDeleteFile(p->zTempFile) ) return;
22543   sqlite3_free(p->zTempFile);
22544   p->zTempFile = 0;
22545 }
22546 
22547 /*
22548 ** Create a new temp file name with the given suffix.
22549 */
22550 static void newTempFile(ShellState *p, const char *zSuffix){
22551   clearTempFile(p);
22552   sqlite3_free(p->zTempFile);
22553   p->zTempFile = 0;
22554   if( p->db ){
22555     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
22556   }
22557   if( p->zTempFile==0 ){
22558     /* If p->db is an in-memory database then the TEMPFILENAME file-control
22559     ** will not work and we will need to fallback to guessing */
22560     char *zTemp;
22561     sqlite3_uint64 r;
22562     sqlite3_randomness(sizeof(r), &r);
22563     zTemp = getenv("TEMP");
22564     if( zTemp==0 ) zTemp = getenv("TMP");
22565     if( zTemp==0 ){
22566 #ifdef _WIN32
22567       zTemp = "\\tmp";
22568 #else
22569       zTemp = "/tmp";
22570 #endif
22571     }
22572     p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
22573   }else{
22574     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
22575   }
22576   shell_check_oom(p->zTempFile);
22577 }
22578 
22579 
22580 /*
22581 ** The implementation of SQL scalar function fkey_collate_clause(), used
22582 ** by the ".lint fkey-indexes" command. This scalar function is always
22583 ** called with four arguments - the parent table name, the parent column name,
22584 ** the child table name and the child column name.
22585 **
22586 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
22587 **
22588 ** If either of the named tables or columns do not exist, this function
22589 ** returns an empty string. An empty string is also returned if both tables
22590 ** and columns exist but have the same default collation sequence. Or,
22591 ** if both exist but the default collation sequences are different, this
22592 ** function returns the string " COLLATE <parent-collation>", where
22593 ** <parent-collation> is the default collation sequence of the parent column.
22594 */
22595 static void shellFkeyCollateClause(
22596   sqlite3_context *pCtx,
22597   int nVal,
22598   sqlite3_value **apVal
22599 ){
22600   sqlite3 *db = sqlite3_context_db_handle(pCtx);
22601   const char *zParent;
22602   const char *zParentCol;
22603   const char *zParentSeq;
22604   const char *zChild;
22605   const char *zChildCol;
22606   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
22607   int rc;
22608 
22609   assert( nVal==4 );
22610   zParent = (const char*)sqlite3_value_text(apVal[0]);
22611   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
22612   zChild = (const char*)sqlite3_value_text(apVal[2]);
22613   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
22614 
22615   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
22616   rc = sqlite3_table_column_metadata(
22617       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
22618   );
22619   if( rc==SQLITE_OK ){
22620     rc = sqlite3_table_column_metadata(
22621         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
22622     );
22623   }
22624 
22625   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
22626     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
22627     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
22628     sqlite3_free(z);
22629   }
22630 }
22631 
22632 
22633 /*
22634 ** The implementation of dot-command ".lint fkey-indexes".
22635 */
22636 static int lintFkeyIndexes(
22637   ShellState *pState,             /* Current shell tool state */
22638   char **azArg,                   /* Array of arguments passed to dot command */
22639   int nArg                        /* Number of entries in azArg[] */
22640 ){
22641   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
22642   FILE *out = pState->out;        /* Stream to write non-error output to */
22643   int bVerbose = 0;               /* If -verbose is present */
22644   int bGroupByParent = 0;         /* If -groupbyparent is present */
22645   int i;                          /* To iterate through azArg[] */
22646   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
22647   int rc;                         /* Return code */
22648   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
22649 
22650   /*
22651   ** This SELECT statement returns one row for each foreign key constraint
22652   ** in the schema of the main database. The column values are:
22653   **
22654   ** 0. The text of an SQL statement similar to:
22655   **
22656   **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
22657   **
22658   **    This SELECT is similar to the one that the foreign keys implementation
22659   **    needs to run internally on child tables. If there is an index that can
22660   **    be used to optimize this query, then it can also be used by the FK
22661   **    implementation to optimize DELETE or UPDATE statements on the parent
22662   **    table.
22663   **
22664   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
22665   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
22666   **    contains an index that can be used to optimize the query.
22667   **
22668   ** 2. Human readable text that describes the child table and columns. e.g.
22669   **
22670   **       "child_table(child_key1, child_key2)"
22671   **
22672   ** 3. Human readable text that describes the parent table and columns. e.g.
22673   **
22674   **       "parent_table(parent_key1, parent_key2)"
22675   **
22676   ** 4. A full CREATE INDEX statement for an index that could be used to
22677   **    optimize DELETE or UPDATE statements on the parent table. e.g.
22678   **
22679   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
22680   **
22681   ** 5. The name of the parent table.
22682   **
22683   ** These six values are used by the C logic below to generate the report.
22684   */
22685   const char *zSql =
22686   "SELECT "
22687     "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
22688     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
22689     "  || fkey_collate_clause("
22690     "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
22691     ", "
22692     "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
22693     "  || group_concat('*=?', ' AND ') || ')'"
22694     ", "
22695     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
22696     ", "
22697     "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
22698     ", "
22699     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
22700     "  || ' ON ' || quote(s.name) || '('"
22701     "  || group_concat(quote(f.[from]) ||"
22702     "        fkey_collate_clause("
22703     "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
22704     "  || ');'"
22705     ", "
22706     "     f.[table] "
22707     "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
22708     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
22709     "GROUP BY s.name, f.id "
22710     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
22711   ;
22712   const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
22713 
22714   for(i=2; i<nArg; i++){
22715     int n = strlen30(azArg[i]);
22716     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
22717       bVerbose = 1;
22718     }
22719     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
22720       bGroupByParent = 1;
22721       zIndent = "    ";
22722     }
22723     else{
22724       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
22725           azArg[0], azArg[1]
22726       );
22727       return SQLITE_ERROR;
22728     }
22729   }
22730 
22731   /* Register the fkey_collate_clause() SQL function */
22732   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
22733       0, shellFkeyCollateClause, 0, 0
22734   );
22735 
22736 
22737   if( rc==SQLITE_OK ){
22738     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
22739   }
22740   if( rc==SQLITE_OK ){
22741     sqlite3_bind_int(pSql, 1, bGroupByParent);
22742   }
22743 
22744   if( rc==SQLITE_OK ){
22745     int rc2;
22746     char *zPrev = 0;
22747     while( SQLITE_ROW==sqlite3_step(pSql) ){
22748       int res = -1;
22749       sqlite3_stmt *pExplain = 0;
22750       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
22751       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
22752       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
22753       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
22754       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
22755       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
22756 
22757       if( zEQP==0 ) continue;
22758       if( zGlob==0 ) continue;
22759       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
22760       if( rc!=SQLITE_OK ) break;
22761       if( SQLITE_ROW==sqlite3_step(pExplain) ){
22762         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
22763         res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
22764                           || 0==sqlite3_strglob(zGlobIPK, zPlan));
22765       }
22766       rc = sqlite3_finalize(pExplain);
22767       if( rc!=SQLITE_OK ) break;
22768 
22769       if( res<0 ){
22770         raw_printf(stderr, "Error: internal error");
22771         break;
22772       }else{
22773         if( bGroupByParent
22774         && (bVerbose || res==0)
22775         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
22776         ){
22777           raw_printf(out, "-- Parent table %s\n", zParent);
22778           sqlite3_free(zPrev);
22779           zPrev = sqlite3_mprintf("%s", zParent);
22780         }
22781 
22782         if( res==0 ){
22783           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
22784         }else if( bVerbose ){
22785           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
22786               zIndent, zFrom, zTarget
22787           );
22788         }
22789       }
22790     }
22791     sqlite3_free(zPrev);
22792 
22793     if( rc!=SQLITE_OK ){
22794       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
22795     }
22796 
22797     rc2 = sqlite3_finalize(pSql);
22798     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
22799       rc = rc2;
22800       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
22801     }
22802   }else{
22803     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
22804   }
22805 
22806   return rc;
22807 }
22808 
22809 /*
22810 ** Implementation of ".lint" dot command.
22811 */
22812 static int lintDotCommand(
22813   ShellState *pState,             /* Current shell tool state */
22814   char **azArg,                   /* Array of arguments passed to dot command */
22815   int nArg                        /* Number of entries in azArg[] */
22816 ){
22817   int n;
22818   n = (nArg>=2 ? strlen30(azArg[1]) : 0);
22819   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
22820   return lintFkeyIndexes(pState, azArg, nArg);
22821 
22822  usage:
22823   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
22824   raw_printf(stderr, "Where sub-commands are:\n");
22825   raw_printf(stderr, "    fkey-indexes\n");
22826   return SQLITE_ERROR;
22827 }
22828 
22829 #if !defined SQLITE_OMIT_VIRTUALTABLE
22830 static void shellPrepare(
22831   sqlite3 *db,
22832   int *pRc,
22833   const char *zSql,
22834   sqlite3_stmt **ppStmt
22835 ){
22836   *ppStmt = 0;
22837   if( *pRc==SQLITE_OK ){
22838     int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
22839     if( rc!=SQLITE_OK ){
22840       raw_printf(stderr, "sql error: %s (%d)\n",
22841           sqlite3_errmsg(db), sqlite3_errcode(db)
22842       );
22843       *pRc = rc;
22844     }
22845   }
22846 }
22847 
22848 /*
22849 ** Create a prepared statement using printf-style arguments for the SQL.
22850 **
22851 ** This routine is could be marked "static".  But it is not always used,
22852 ** depending on compile-time options.  By omitting the "static", we avoid
22853 ** nuisance compiler warnings about "defined but not used".
22854 */
22855 void shellPreparePrintf(
22856   sqlite3 *db,
22857   int *pRc,
22858   sqlite3_stmt **ppStmt,
22859   const char *zFmt,
22860   ...
22861 ){
22862   *ppStmt = 0;
22863   if( *pRc==SQLITE_OK ){
22864     va_list ap;
22865     char *z;
22866     va_start(ap, zFmt);
22867     z = sqlite3_vmprintf(zFmt, ap);
22868     va_end(ap);
22869     if( z==0 ){
22870       *pRc = SQLITE_NOMEM;
22871     }else{
22872       shellPrepare(db, pRc, z, ppStmt);
22873       sqlite3_free(z);
22874     }
22875   }
22876 }
22877 
22878 /* Finalize the prepared statement created using shellPreparePrintf().
22879 **
22880 ** This routine is could be marked "static".  But it is not always used,
22881 ** depending on compile-time options.  By omitting the "static", we avoid
22882 ** nuisance compiler warnings about "defined but not used".
22883 */
22884 void shellFinalize(
22885   int *pRc,
22886   sqlite3_stmt *pStmt
22887 ){
22888   if( pStmt ){
22889     sqlite3 *db = sqlite3_db_handle(pStmt);
22890     int rc = sqlite3_finalize(pStmt);
22891     if( *pRc==SQLITE_OK ){
22892       if( rc!=SQLITE_OK ){
22893         raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
22894       }
22895       *pRc = rc;
22896     }
22897   }
22898 }
22899 
22900 /* Reset the prepared statement created using shellPreparePrintf().
22901 **
22902 ** This routine is could be marked "static".  But it is not always used,
22903 ** depending on compile-time options.  By omitting the "static", we avoid
22904 ** nuisance compiler warnings about "defined but not used".
22905 */
22906 void shellReset(
22907   int *pRc,
22908   sqlite3_stmt *pStmt
22909 ){
22910   int rc = sqlite3_reset(pStmt);
22911   if( *pRc==SQLITE_OK ){
22912     if( rc!=SQLITE_OK ){
22913       sqlite3 *db = sqlite3_db_handle(pStmt);
22914       raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
22915     }
22916     *pRc = rc;
22917   }
22918 }
22919 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
22920 
22921 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
22922 /******************************************************************************
22923 ** The ".archive" or ".ar" command.
22924 */
22925 /*
22926 ** Structure representing a single ".ar" command.
22927 */
22928 typedef struct ArCommand ArCommand;
22929 struct ArCommand {
22930   u8 eCmd;                        /* An AR_CMD_* value */
22931   u8 bVerbose;                    /* True if --verbose */
22932   u8 bZip;                        /* True if the archive is a ZIP */
22933   u8 bDryRun;                     /* True if --dry-run */
22934   u8 bAppend;                     /* True if --append */
22935   u8 bGlob;                       /* True if --glob */
22936   u8 fromCmdLine;                 /* Run from -A instead of .archive */
22937   int nArg;                       /* Number of command arguments */
22938   char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
22939   const char *zFile;              /* --file argument, or NULL */
22940   const char *zDir;               /* --directory argument, or NULL */
22941   char **azArg;                   /* Array of command arguments */
22942   ShellState *p;                  /* Shell state */
22943   sqlite3 *db;                    /* Database containing the archive */
22944 };
22945 
22946 /*
22947 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
22948 */
22949 static int arUsage(FILE *f){
22950   showHelp(f,"archive");
22951   return SQLITE_ERROR;
22952 }
22953 
22954 /*
22955 ** Print an error message for the .ar command to stderr and return
22956 ** SQLITE_ERROR.
22957 */
22958 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
22959   va_list ap;
22960   char *z;
22961   va_start(ap, zFmt);
22962   z = sqlite3_vmprintf(zFmt, ap);
22963   va_end(ap);
22964   utf8_printf(stderr, "Error: %s\n", z);
22965   if( pAr->fromCmdLine ){
22966     utf8_printf(stderr, "Use \"-A\" for more help\n");
22967   }else{
22968     utf8_printf(stderr, "Use \".archive --help\" for more help\n");
22969   }
22970   sqlite3_free(z);
22971   return SQLITE_ERROR;
22972 }
22973 
22974 /*
22975 ** Values for ArCommand.eCmd.
22976 */
22977 #define AR_CMD_CREATE       1
22978 #define AR_CMD_UPDATE       2
22979 #define AR_CMD_INSERT       3
22980 #define AR_CMD_EXTRACT      4
22981 #define AR_CMD_LIST         5
22982 #define AR_CMD_HELP         6
22983 #define AR_CMD_REMOVE       7
22984 
22985 /*
22986 ** Other (non-command) switches.
22987 */
22988 #define AR_SWITCH_VERBOSE     8
22989 #define AR_SWITCH_FILE        9
22990 #define AR_SWITCH_DIRECTORY  10
22991 #define AR_SWITCH_APPEND     11
22992 #define AR_SWITCH_DRYRUN     12
22993 #define AR_SWITCH_GLOB       13
22994 
22995 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
22996   switch( eSwitch ){
22997     case AR_CMD_CREATE:
22998     case AR_CMD_EXTRACT:
22999     case AR_CMD_LIST:
23000     case AR_CMD_REMOVE:
23001     case AR_CMD_UPDATE:
23002     case AR_CMD_INSERT:
23003     case AR_CMD_HELP:
23004       if( pAr->eCmd ){
23005         return arErrorMsg(pAr, "multiple command options");
23006       }
23007       pAr->eCmd = eSwitch;
23008       break;
23009 
23010     case AR_SWITCH_DRYRUN:
23011       pAr->bDryRun = 1;
23012       break;
23013     case AR_SWITCH_GLOB:
23014       pAr->bGlob = 1;
23015       break;
23016     case AR_SWITCH_VERBOSE:
23017       pAr->bVerbose = 1;
23018       break;
23019     case AR_SWITCH_APPEND:
23020       pAr->bAppend = 1;
23021       deliberate_fall_through;
23022     case AR_SWITCH_FILE:
23023       pAr->zFile = zArg;
23024       break;
23025     case AR_SWITCH_DIRECTORY:
23026       pAr->zDir = zArg;
23027       break;
23028   }
23029 
23030   return SQLITE_OK;
23031 }
23032 
23033 /*
23034 ** Parse the command line for an ".ar" command. The results are written into
23035 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
23036 ** successfully, otherwise an error message is written to stderr and
23037 ** SQLITE_ERROR returned.
23038 */
23039 static int arParseCommand(
23040   char **azArg,                   /* Array of arguments passed to dot command */
23041   int nArg,                       /* Number of entries in azArg[] */
23042   ArCommand *pAr                  /* Populate this object */
23043 ){
23044   struct ArSwitch {
23045     const char *zLong;
23046     char cShort;
23047     u8 eSwitch;
23048     u8 bArg;
23049   } aSwitch[] = {
23050     { "create",    'c', AR_CMD_CREATE,       0 },
23051     { "extract",   'x', AR_CMD_EXTRACT,      0 },
23052     { "insert",    'i', AR_CMD_INSERT,       0 },
23053     { "list",      't', AR_CMD_LIST,         0 },
23054     { "remove",    'r', AR_CMD_REMOVE,       0 },
23055     { "update",    'u', AR_CMD_UPDATE,       0 },
23056     { "help",      'h', AR_CMD_HELP,         0 },
23057     { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
23058     { "file",      'f', AR_SWITCH_FILE,      1 },
23059     { "append",    'a', AR_SWITCH_APPEND,    1 },
23060     { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
23061     { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
23062     { "glob",      'g', AR_SWITCH_GLOB,      0 },
23063   };
23064   int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
23065   struct ArSwitch *pEnd = &aSwitch[nSwitch];
23066 
23067   if( nArg<=1 ){
23068     utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
23069     return arUsage(stderr);
23070   }else{
23071     char *z = azArg[1];
23072     if( z[0]!='-' ){
23073       /* Traditional style [tar] invocation */
23074       int i;
23075       int iArg = 2;
23076       for(i=0; z[i]; i++){
23077         const char *zArg = 0;
23078         struct ArSwitch *pOpt;
23079         for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23080           if( z[i]==pOpt->cShort ) break;
23081         }
23082         if( pOpt==pEnd ){
23083           return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23084         }
23085         if( pOpt->bArg ){
23086           if( iArg>=nArg ){
23087             return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
23088           }
23089           zArg = azArg[iArg++];
23090         }
23091         if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23092       }
23093       pAr->nArg = nArg-iArg;
23094       if( pAr->nArg>0 ){
23095         pAr->azArg = &azArg[iArg];
23096       }
23097     }else{
23098       /* Non-traditional invocation */
23099       int iArg;
23100       for(iArg=1; iArg<nArg; iArg++){
23101         int n;
23102         z = azArg[iArg];
23103         if( z[0]!='-' ){
23104           /* All remaining command line words are command arguments. */
23105           pAr->azArg = &azArg[iArg];
23106           pAr->nArg = nArg-iArg;
23107           break;
23108         }
23109         n = strlen30(z);
23110 
23111         if( z[1]!='-' ){
23112           int i;
23113           /* One or more short options */
23114           for(i=1; i<n; i++){
23115             const char *zArg = 0;
23116             struct ArSwitch *pOpt;
23117             for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23118               if( z[i]==pOpt->cShort ) break;
23119             }
23120             if( pOpt==pEnd ){
23121               return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
23122             }
23123             if( pOpt->bArg ){
23124               if( i<(n-1) ){
23125                 zArg = &z[i+1];
23126                 i = n;
23127               }else{
23128                 if( iArg>=(nArg-1) ){
23129                   return arErrorMsg(pAr, "option requires an argument: %c",
23130                                     z[i]);
23131                 }
23132                 zArg = azArg[++iArg];
23133               }
23134             }
23135             if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
23136           }
23137         }else if( z[2]=='\0' ){
23138           /* A -- option, indicating that all remaining command line words
23139           ** are command arguments.  */
23140           pAr->azArg = &azArg[iArg+1];
23141           pAr->nArg = nArg-iArg-1;
23142           break;
23143         }else{
23144           /* A long option */
23145           const char *zArg = 0;             /* Argument for option, if any */
23146           struct ArSwitch *pMatch = 0;      /* Matching option */
23147           struct ArSwitch *pOpt;            /* Iterator */
23148           for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
23149             const char *zLong = pOpt->zLong;
23150             if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
23151               if( pMatch ){
23152                 return arErrorMsg(pAr, "ambiguous option: %s",z);
23153               }else{
23154                 pMatch = pOpt;
23155               }
23156             }
23157           }
23158 
23159           if( pMatch==0 ){
23160             return arErrorMsg(pAr, "unrecognized option: %s", z);
23161           }
23162           if( pMatch->bArg ){
23163             if( iArg>=(nArg-1) ){
23164               return arErrorMsg(pAr, "option requires an argument: %s", z);
23165             }
23166             zArg = azArg[++iArg];
23167           }
23168           if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
23169         }
23170       }
23171     }
23172   }
23173   if( pAr->eCmd==0 ){
23174     utf8_printf(stderr, "Required argument missing.  Usage:\n");
23175     return arUsage(stderr);
23176   }
23177   return SQLITE_OK;
23178 }
23179 
23180 /*
23181 ** This function assumes that all arguments within the ArCommand.azArg[]
23182 ** array refer to archive members, as for the --extract, --list or --remove
23183 ** commands. It checks that each of them are "present". If any specified
23184 ** file is not present in the archive, an error is printed to stderr and an
23185 ** error code returned. Otherwise, if all specified arguments are present
23186 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
23187 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
23188 ** when pAr->bGlob is true.
23189 **
23190 ** This function strips any trailing '/' characters from each argument.
23191 ** This is consistent with the way the [tar] command seems to work on
23192 ** Linux.
23193 */
23194 static int arCheckEntries(ArCommand *pAr){
23195   int rc = SQLITE_OK;
23196   if( pAr->nArg ){
23197     int i, j;
23198     sqlite3_stmt *pTest = 0;
23199     const char *zSel = (pAr->bGlob)
23200       ? "SELECT name FROM %s WHERE glob($name,name)"
23201       : "SELECT name FROM %s WHERE name=$name";
23202 
23203     shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
23204     j = sqlite3_bind_parameter_index(pTest, "$name");
23205     for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
23206       char *z = pAr->azArg[i];
23207       int n = strlen30(z);
23208       int bOk = 0;
23209       while( n>0 && z[n-1]=='/' ) n--;
23210       z[n] = '\0';
23211       sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
23212       if( SQLITE_ROW==sqlite3_step(pTest) ){
23213         bOk = 1;
23214       }
23215       shellReset(&rc, pTest);
23216       if( rc==SQLITE_OK && bOk==0 ){
23217         utf8_printf(stderr, "not found in archive: %s\n", z);
23218         rc = SQLITE_ERROR;
23219       }
23220     }
23221     shellFinalize(&rc, pTest);
23222   }
23223   return rc;
23224 }
23225 
23226 /*
23227 ** Format a WHERE clause that can be used against the "sqlar" table to
23228 ** identify all archive members that match the command arguments held
23229 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
23230 ** The caller is responsible for eventually calling sqlite3_free() on
23231 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
23232 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
23233 */
23234 static void arWhereClause(
23235   int *pRc,
23236   ArCommand *pAr,
23237   char **pzWhere                  /* OUT: New WHERE clause */
23238 ){
23239   char *zWhere = 0;
23240   const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
23241   if( *pRc==SQLITE_OK ){
23242     if( pAr->nArg==0 ){
23243       zWhere = sqlite3_mprintf("1");
23244     }else{
23245       int i;
23246       const char *zSep = "";
23247       for(i=0; i<pAr->nArg; i++){
23248         const char *z = pAr->azArg[i];
23249         zWhere = sqlite3_mprintf(
23250           "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
23251           zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
23252         );
23253         if( zWhere==0 ){
23254           *pRc = SQLITE_NOMEM;
23255           break;
23256         }
23257         zSep = " OR ";
23258       }
23259     }
23260   }
23261   *pzWhere = zWhere;
23262 }
23263 
23264 /*
23265 ** Implementation of .ar "lisT" command.
23266 */
23267 static int arListCommand(ArCommand *pAr){
23268   const char *zSql = "SELECT %s FROM %s WHERE %s";
23269   const char *azCols[] = {
23270     "name",
23271     "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
23272   };
23273 
23274   char *zWhere = 0;
23275   sqlite3_stmt *pSql = 0;
23276   int rc;
23277 
23278   rc = arCheckEntries(pAr);
23279   arWhereClause(&rc, pAr, &zWhere);
23280 
23281   shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
23282                      pAr->zSrcTable, zWhere);
23283   if( pAr->bDryRun ){
23284     utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
23285   }else{
23286     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
23287       if( pAr->bVerbose ){
23288         utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
23289             sqlite3_column_text(pSql, 0),
23290             sqlite3_column_int(pSql, 1),
23291             sqlite3_column_text(pSql, 2),
23292             sqlite3_column_text(pSql, 3)
23293         );
23294       }else{
23295         utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
23296       }
23297     }
23298   }
23299   shellFinalize(&rc, pSql);
23300   sqlite3_free(zWhere);
23301   return rc;
23302 }
23303 
23304 
23305 /*
23306 ** Implementation of .ar "Remove" command.
23307 */
23308 static int arRemoveCommand(ArCommand *pAr){
23309   int rc = 0;
23310   char *zSql = 0;
23311   char *zWhere = 0;
23312 
23313   if( pAr->nArg ){
23314     /* Verify that args actually exist within the archive before proceeding.
23315     ** And formulate a WHERE clause to match them.  */
23316     rc = arCheckEntries(pAr);
23317     arWhereClause(&rc, pAr, &zWhere);
23318   }
23319   if( rc==SQLITE_OK ){
23320     zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
23321                            pAr->zSrcTable, zWhere);
23322     if( pAr->bDryRun ){
23323       utf8_printf(pAr->p->out, "%s\n", zSql);
23324     }else{
23325       char *zErr = 0;
23326       rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
23327       if( rc==SQLITE_OK ){
23328         rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
23329         if( rc!=SQLITE_OK ){
23330           sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
23331         }else{
23332           rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
23333         }
23334       }
23335       if( zErr ){
23336         utf8_printf(stdout, "ERROR: %s\n", zErr);
23337         sqlite3_free(zErr);
23338       }
23339     }
23340   }
23341   sqlite3_free(zWhere);
23342   sqlite3_free(zSql);
23343   return rc;
23344 }
23345 
23346 /*
23347 ** Implementation of .ar "eXtract" command.
23348 */
23349 static int arExtractCommand(ArCommand *pAr){
23350   const char *zSql1 =
23351     "SELECT "
23352     " ($dir || name),"
23353     " writefile(($dir || name), %s, mode, mtime) "
23354     "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
23355     " AND name NOT GLOB '*..[/\\]*'";
23356 
23357   const char *azExtraArg[] = {
23358     "sqlar_uncompress(data, sz)",
23359     "data"
23360   };
23361 
23362   sqlite3_stmt *pSql = 0;
23363   int rc = SQLITE_OK;
23364   char *zDir = 0;
23365   char *zWhere = 0;
23366   int i, j;
23367 
23368   /* If arguments are specified, check that they actually exist within
23369   ** the archive before proceeding. And formulate a WHERE clause to
23370   ** match them.  */
23371   rc = arCheckEntries(pAr);
23372   arWhereClause(&rc, pAr, &zWhere);
23373 
23374   if( rc==SQLITE_OK ){
23375     if( pAr->zDir ){
23376       zDir = sqlite3_mprintf("%s/", pAr->zDir);
23377     }else{
23378       zDir = sqlite3_mprintf("");
23379     }
23380     if( zDir==0 ) rc = SQLITE_NOMEM;
23381   }
23382 
23383   shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
23384       azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
23385   );
23386 
23387   if( rc==SQLITE_OK ){
23388     j = sqlite3_bind_parameter_index(pSql, "$dir");
23389     sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
23390 
23391     /* Run the SELECT statement twice. The first time, writefile() is called
23392     ** for all archive members that should be extracted. The second time,
23393     ** only for the directories. This is because the timestamps for
23394     ** extracted directories must be reset after they are populated (as
23395     ** populating them changes the timestamp).  */
23396     for(i=0; i<2; i++){
23397       j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
23398       sqlite3_bind_int(pSql, j, i);
23399       if( pAr->bDryRun ){
23400         utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
23401       }else{
23402         while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
23403           if( i==0 && pAr->bVerbose ){
23404             utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
23405           }
23406         }
23407       }
23408       shellReset(&rc, pSql);
23409     }
23410     shellFinalize(&rc, pSql);
23411   }
23412 
23413   sqlite3_free(zDir);
23414   sqlite3_free(zWhere);
23415   return rc;
23416 }
23417 
23418 /*
23419 ** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
23420 */
23421 static int arExecSql(ArCommand *pAr, const char *zSql){
23422   int rc;
23423   if( pAr->bDryRun ){
23424     utf8_printf(pAr->p->out, "%s\n", zSql);
23425     rc = SQLITE_OK;
23426   }else{
23427     char *zErr = 0;
23428     rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
23429     if( zErr ){
23430       utf8_printf(stdout, "ERROR: %s\n", zErr);
23431       sqlite3_free(zErr);
23432     }
23433   }
23434   return rc;
23435 }
23436 
23437 
23438 /*
23439 ** Implementation of .ar "create", "insert", and "update" commands.
23440 **
23441 **     create    ->     Create a new SQL archive
23442 **     insert    ->     Insert or reinsert all files listed
23443 **     update    ->     Insert files that have changed or that were not
23444 **                      previously in the archive
23445 **
23446 ** Create the "sqlar" table in the database if it does not already exist.
23447 ** Then add each file in the azFile[] array to the archive. Directories
23448 ** are added recursively. If argument bVerbose is non-zero, a message is
23449 ** printed on stdout for each file archived.
23450 **
23451 ** The create command is the same as update, except that it drops
23452 ** any existing "sqlar" table before beginning.  The "insert" command
23453 ** always overwrites every file named on the command-line, where as
23454 ** "update" only overwrites if the size or mtime or mode has changed.
23455 */
23456 static int arCreateOrUpdateCommand(
23457   ArCommand *pAr,                 /* Command arguments and options */
23458   int bUpdate,                    /* true for a --create. */
23459   int bOnlyIfChanged              /* Only update if file has changed */
23460 ){
23461   const char *zCreate =
23462       "CREATE TABLE IF NOT EXISTS sqlar(\n"
23463       "  name TEXT PRIMARY KEY,  -- name of the file\n"
23464       "  mode INT,               -- access permissions\n"
23465       "  mtime INT,              -- last modification time\n"
23466       "  sz INT,                 -- original file size\n"
23467       "  data BLOB               -- compressed content\n"
23468       ")";
23469   const char *zDrop = "DROP TABLE IF EXISTS sqlar";
23470   const char *zInsertFmt[2] = {
23471      "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
23472      "  SELECT\n"
23473      "    %s,\n"
23474      "    mode,\n"
23475      "    mtime,\n"
23476      "    CASE substr(lsmode(mode),1,1)\n"
23477      "      WHEN '-' THEN length(data)\n"
23478      "      WHEN 'd' THEN 0\n"
23479      "      ELSE -1 END,\n"
23480      "    sqlar_compress(data)\n"
23481      "  FROM fsdir(%Q,%Q) AS disk\n"
23482      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
23483      ,
23484      "REPLACE INTO %s(name,mode,mtime,data)\n"
23485      "  SELECT\n"
23486      "    %s,\n"
23487      "    mode,\n"
23488      "    mtime,\n"
23489      "    data\n"
23490      "  FROM fsdir(%Q,%Q) AS disk\n"
23491      "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
23492   };
23493   int i;                          /* For iterating through azFile[] */
23494   int rc;                         /* Return code */
23495   const char *zTab = 0;           /* SQL table into which to insert */
23496   char *zSql;
23497   char zTemp[50];
23498   char *zExists = 0;
23499 
23500   arExecSql(pAr, "PRAGMA page_size=512");
23501   rc = arExecSql(pAr, "SAVEPOINT ar;");
23502   if( rc!=SQLITE_OK ) return rc;
23503   zTemp[0] = 0;
23504   if( pAr->bZip ){
23505     /* Initialize the zipfile virtual table, if necessary */
23506     if( pAr->zFile ){
23507       sqlite3_uint64 r;
23508       sqlite3_randomness(sizeof(r),&r);
23509       sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
23510       zTab = zTemp;
23511       zSql = sqlite3_mprintf(
23512          "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
23513          zTab, pAr->zFile
23514       );
23515       rc = arExecSql(pAr, zSql);
23516       sqlite3_free(zSql);
23517     }else{
23518       zTab = "zip";
23519     }
23520   }else{
23521     /* Initialize the table for an SQLAR */
23522     zTab = "sqlar";
23523     if( bUpdate==0 ){
23524       rc = arExecSql(pAr, zDrop);
23525       if( rc!=SQLITE_OK ) goto end_ar_transaction;
23526     }
23527     rc = arExecSql(pAr, zCreate);
23528   }
23529   if( bOnlyIfChanged ){
23530     zExists = sqlite3_mprintf(
23531       " AND NOT EXISTS("
23532           "SELECT 1 FROM %s AS mem"
23533           " WHERE mem.name=disk.name"
23534           " AND mem.mtime=disk.mtime"
23535           " AND mem.mode=disk.mode)", zTab);
23536   }else{
23537     zExists = sqlite3_mprintf("");
23538   }
23539   if( zExists==0 ) rc = SQLITE_NOMEM;
23540   for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
23541     char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
23542         pAr->bVerbose ? "shell_putsnl(name)" : "name",
23543         pAr->azArg[i], pAr->zDir, zExists);
23544     rc = arExecSql(pAr, zSql2);
23545     sqlite3_free(zSql2);
23546   }
23547 end_ar_transaction:
23548   if( rc!=SQLITE_OK ){
23549     sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
23550   }else{
23551     rc = arExecSql(pAr, "RELEASE ar;");
23552     if( pAr->bZip && pAr->zFile ){
23553       zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
23554       arExecSql(pAr, zSql);
23555       sqlite3_free(zSql);
23556     }
23557   }
23558   sqlite3_free(zExists);
23559   return rc;
23560 }
23561 
23562 /*
23563 ** Implementation of ".ar" dot command.
23564 */
23565 static int arDotCommand(
23566   ShellState *pState,          /* Current shell tool state */
23567   int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
23568   char **azArg,                /* Array of arguments passed to dot command */
23569   int nArg                     /* Number of entries in azArg[] */
23570 ){
23571   ArCommand cmd;
23572   int rc;
23573   memset(&cmd, 0, sizeof(cmd));
23574   cmd.fromCmdLine = fromCmdLine;
23575   rc = arParseCommand(azArg, nArg, &cmd);
23576   if( rc==SQLITE_OK ){
23577     int eDbType = SHELL_OPEN_UNSPEC;
23578     cmd.p = pState;
23579     cmd.db = pState->db;
23580     if( cmd.zFile ){
23581       eDbType = deduceDatabaseType(cmd.zFile, 1);
23582     }else{
23583       eDbType = pState->openMode;
23584     }
23585     if( eDbType==SHELL_OPEN_ZIPFILE ){
23586       if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
23587         if( cmd.zFile==0 ){
23588           cmd.zSrcTable = sqlite3_mprintf("zip");
23589         }else{
23590           cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
23591         }
23592       }
23593       cmd.bZip = 1;
23594     }else if( cmd.zFile ){
23595       int flags;
23596       if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
23597       if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
23598            || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
23599         flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
23600       }else{
23601         flags = SQLITE_OPEN_READONLY;
23602       }
23603       cmd.db = 0;
23604       if( cmd.bDryRun ){
23605         utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
23606              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
23607       }
23608       rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
23609              eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
23610       if( rc!=SQLITE_OK ){
23611         utf8_printf(stderr, "cannot open file: %s (%s)\n",
23612             cmd.zFile, sqlite3_errmsg(cmd.db)
23613         );
23614         goto end_ar_command;
23615       }
23616       sqlite3_fileio_init(cmd.db, 0, 0);
23617       sqlite3_sqlar_init(cmd.db, 0, 0);
23618       sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
23619                               shellPutsFunc, 0, 0);
23620 
23621     }
23622     if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
23623       if( cmd.eCmd!=AR_CMD_CREATE
23624        && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
23625       ){
23626         utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
23627         rc = SQLITE_ERROR;
23628         goto end_ar_command;
23629       }
23630       cmd.zSrcTable = sqlite3_mprintf("sqlar");
23631     }
23632 
23633     switch( cmd.eCmd ){
23634       case AR_CMD_CREATE:
23635         rc = arCreateOrUpdateCommand(&cmd, 0, 0);
23636         break;
23637 
23638       case AR_CMD_EXTRACT:
23639         rc = arExtractCommand(&cmd);
23640         break;
23641 
23642       case AR_CMD_LIST:
23643         rc = arListCommand(&cmd);
23644         break;
23645 
23646       case AR_CMD_HELP:
23647         arUsage(pState->out);
23648         break;
23649 
23650       case AR_CMD_INSERT:
23651         rc = arCreateOrUpdateCommand(&cmd, 1, 0);
23652         break;
23653 
23654       case AR_CMD_REMOVE:
23655         rc = arRemoveCommand(&cmd);
23656         break;
23657 
23658       default:
23659         assert( cmd.eCmd==AR_CMD_UPDATE );
23660         rc = arCreateOrUpdateCommand(&cmd, 1, 1);
23661         break;
23662     }
23663   }
23664 end_ar_command:
23665   if( cmd.db!=pState->db ){
23666     close_db(cmd.db);
23667   }
23668   sqlite3_free(cmd.zSrcTable);
23669 
23670   return rc;
23671 }
23672 /* End of the ".archive" or ".ar" command logic
23673 *******************************************************************************/
23674 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
23675 
23676 #if SQLITE_SHELL_HAVE_RECOVER
23677 
23678 /*
23679 ** This function is used as a callback by the recover extension. Simply
23680 ** print the supplied SQL statement to stdout.
23681 */
23682 static int recoverSqlCb(void *pCtx, const char *zSql){
23683   ShellState *pState = (ShellState*)pCtx;
23684   utf8_printf(pState->out, "%s;\n", zSql);
23685   return SQLITE_OK;
23686 }
23687 
23688 /*
23689 ** This function is called to recover data from the database. A script
23690 ** to construct a new database containing all recovered data is output
23691 ** on stream pState->out.
23692 */
23693 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
23694   int rc = SQLITE_OK;
23695   const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
23696   const char *zLAF = "lost_and_found";
23697   int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
23698   int bRowids = 1;                /* 0 if --no-rowids */
23699   sqlite3_recover *p = 0;
23700   int i = 0;
23701 
23702   for(i=1; i<nArg; i++){
23703     char *z = azArg[i];
23704     int n;
23705     if( z[0]=='-' && z[1]=='-' ) z++;
23706     n = strlen30(z);
23707     if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
23708       bFreelist = 0;
23709     }else
23710     if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
23711       /* This option determines the name of the ATTACH-ed database used
23712       ** internally by the recovery extension.  The default is "" which
23713       ** means to use a temporary database that is automatically deleted
23714       ** when closed.  This option is undocumented and might disappear at
23715       ** any moment. */
23716       i++;
23717       zRecoveryDb = azArg[i];
23718     }else
23719     if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
23720       i++;
23721       zLAF = azArg[i];
23722     }else
23723     if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
23724       bRowids = 0;
23725     }
23726     else{
23727       utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
23728       showHelp(pState->out, azArg[0]);
23729       return 1;
23730     }
23731   }
23732 
23733   p = sqlite3_recover_init_sql(
23734       pState->db, "main", recoverSqlCb, (void*)pState
23735   );
23736 
23737   sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
23738   sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
23739   sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
23740   sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
23741 
23742   sqlite3_recover_run(p);
23743   if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
23744     const char *zErr = sqlite3_recover_errmsg(p);
23745     int errCode = sqlite3_recover_errcode(p);
23746     raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
23747   }
23748   rc = sqlite3_recover_finish(p);
23749   return rc;
23750 }
23751 #endif /* SQLITE_SHELL_HAVE_RECOVER */
23752 
23753 
23754 /*
23755  * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
23756  * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
23757  *   close db and set it to 0, and return the columns spec, to later
23758  *   be sqlite3_free()'ed by the caller.
23759  * The return is 0 when either:
23760  *   (a) The db was not initialized and zCol==0 (There are no columns.)
23761  *   (b) zCol!=0  (Column was added, db initialized as needed.)
23762  * The 3rd argument, pRenamed, references an out parameter. If the
23763  * pointer is non-zero, its referent will be set to a summary of renames
23764  * done if renaming was necessary, or set to 0 if none was done. The out
23765  * string (if any) must be sqlite3_free()'ed by the caller.
23766  */
23767 #ifdef SHELL_DEBUG
23768 #define rc_err_oom_die(rc) \
23769   if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
23770   else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
23771     fprintf(stderr,"E:%d\n",rc), assert(0)
23772 #else
23773 static void rc_err_oom_die(int rc){
23774   if( rc==SQLITE_NOMEM ) shell_check_oom(0);
23775   assert(rc==SQLITE_OK||rc==SQLITE_DONE);
23776 }
23777 #endif
23778 
23779 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
23780 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
23781 #else  /* Otherwise, memory is faster/better for the transient DB. */
23782 static const char *zCOL_DB = ":memory:";
23783 #endif
23784 
23785 /* Define character (as C string) to separate generated column ordinal
23786  * from protected part of incoming column names. This defaults to "_"
23787  * so that incoming column identifiers that did not need not be quoted
23788  * remain usable without being quoted. It must be one character.
23789  */
23790 #ifndef SHELL_AUTOCOLUMN_SEP
23791 # define AUTOCOLUMN_SEP "_"
23792 #else
23793 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
23794 #endif
23795 
23796 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
23797   /* Queries and D{D,M}L used here */
23798   static const char * const zTabMake = "\
23799 CREATE TABLE ColNames(\
23800  cpos INTEGER PRIMARY KEY,\
23801  name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
23802 CREATE VIEW RepeatedNames AS \
23803 SELECT DISTINCT t.name FROM ColNames t \
23804 WHERE t.name COLLATE NOCASE IN (\
23805  SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
23806 );\
23807 ";
23808   static const char * const zTabFill = "\
23809 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
23810  VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
23811 ";
23812   static const char * const zHasDupes = "\
23813 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
23814  <count(name) FROM ColNames\
23815 ";
23816 #ifdef SHELL_COLUMN_RENAME_CLEAN
23817   static const char * const zDedoctor = "\
23818 UPDATE ColNames SET chop=iif(\
23819   (substring(name,nlen,1) BETWEEN '0' AND '9')\
23820   AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
23821  nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
23822  0\
23823 )\
23824 ";
23825 #endif
23826   static const char * const zSetReps = "\
23827 UPDATE ColNames AS t SET reps=\
23828 (SELECT count(*) FROM ColNames d \
23829  WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
23830  COLLATE NOCASE\
23831 )\
23832 ";
23833 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
23834   static const char * const zColDigits = "\
23835 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
23836 ";
23837 #else
23838   /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
23839   static const char * const zColDigits = "\
23840 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
23841  WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
23842  ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
23843 ";
23844 #endif
23845   static const char * const zRenameRank =
23846 #ifdef SHELL_COLUMN_RENAME_CLEAN
23847     "UPDATE ColNames AS t SET suff="
23848     "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
23849 #else /* ...RENAME_MINIMAL_ONE_PASS */
23850 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
23851 "  SELECT 0 AS nlz"
23852 "  UNION"
23853 "  SELECT nlz+1 AS nlz FROM Lzn"
23854 "  WHERE EXISTS("
23855 "   SELECT 1"
23856 "   FROM ColNames t, ColNames o"
23857 "   WHERE"
23858 "    iif(t.name IN (SELECT * FROM RepeatedNames),"
23859 "     printf('%s"AUTOCOLUMN_SEP"%s',"
23860 "      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
23861 "     t.name"
23862 "    )"
23863 "    ="
23864 "    iif(o.name IN (SELECT * FROM RepeatedNames),"
23865 "     printf('%s"AUTOCOLUMN_SEP"%s',"
23866 "      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
23867 "     o.name"
23868 "    )"
23869 "    COLLATE NOCASE"
23870 "    AND o.cpos<>t.cpos"
23871 "   GROUP BY t.cpos"
23872 "  )"
23873 ") UPDATE Colnames AS t SET"
23874 " chop = 0," /* No chopping, never touch incoming names. */
23875 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
23876 "  printf('"AUTOCOLUMN_SEP"%s', substring("
23877 "   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
23878 "  ''"
23879 " )"
23880 #endif
23881     ;
23882   static const char * const zCollectVar = "\
23883 SELECT\
23884  '('||x'0a'\
23885  || group_concat(\
23886   cname||' TEXT',\
23887   ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
23888  ||')' AS ColsSpec \
23889 FROM (\
23890  SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
23891  FROM ColNames ORDER BY cpos\
23892 )";
23893   static const char * const zRenamesDone =
23894     "SELECT group_concat("
23895     " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
23896     " ','||x'0a')"
23897     "FROM ColNames WHERE suff<>'' OR chop!=0"
23898     ;
23899   int rc;
23900   sqlite3_stmt *pStmt = 0;
23901   assert(pDb!=0);
23902   if( zColNew ){
23903     /* Add initial or additional column. Init db if necessary. */
23904     if( *pDb==0 ){
23905       if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
23906 #ifdef SHELL_COLFIX_DB
23907       if(*zCOL_DB!=':')
23908         sqlite3_exec(*pDb,"drop table if exists ColNames;"
23909                      "drop view if exists RepeatedNames;",0,0,0);
23910 #endif
23911       rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
23912       rc_err_oom_die(rc);
23913     }
23914     assert(*pDb!=0);
23915     rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
23916     rc_err_oom_die(rc);
23917     rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
23918     rc_err_oom_die(rc);
23919     rc = sqlite3_step(pStmt);
23920     rc_err_oom_die(rc);
23921     sqlite3_finalize(pStmt);
23922     return 0;
23923   }else if( *pDb==0 ){
23924     return 0;
23925   }else{
23926     /* Formulate the columns spec, close the DB, zero *pDb. */
23927     char *zColsSpec = 0;
23928     int hasDupes = db_int(*pDb, zHasDupes);
23929     int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
23930     if( hasDupes ){
23931 #ifdef SHELL_COLUMN_RENAME_CLEAN
23932       rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
23933       rc_err_oom_die(rc);
23934 #endif
23935       rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
23936       rc_err_oom_die(rc);
23937       rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
23938       rc_err_oom_die(rc);
23939       sqlite3_bind_int(pStmt, 1, nDigits);
23940       rc = sqlite3_step(pStmt);
23941       sqlite3_finalize(pStmt);
23942       if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
23943     }
23944     assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
23945     rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
23946     rc_err_oom_die(rc);
23947     rc = sqlite3_step(pStmt);
23948     if( rc==SQLITE_ROW ){
23949       zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
23950     }else{
23951       zColsSpec = 0;
23952     }
23953     if( pzRenamed!=0 ){
23954       if( !hasDupes ) *pzRenamed = 0;
23955       else{
23956         sqlite3_finalize(pStmt);
23957         if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
23958             && SQLITE_ROW==sqlite3_step(pStmt) ){
23959           *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
23960         }else
23961           *pzRenamed = 0;
23962       }
23963     }
23964     sqlite3_finalize(pStmt);
23965     sqlite3_close(*pDb);
23966     *pDb = 0;
23967     return zColsSpec;
23968   }
23969 }
23970 
23971 /*
23972 ** If an input line begins with "." then invoke this routine to
23973 ** process that line.
23974 **
23975 ** Return 1 on error, 2 to exit, and 0 otherwise.
23976 */
23977 static int do_meta_command(char *zLine, ShellState *p){
23978   int h = 1;
23979   int nArg = 0;
23980   int n, c;
23981   int rc = 0;
23982   char *azArg[52];
23983 
23984 #ifndef SQLITE_OMIT_VIRTUALTABLE
23985   if( p->expert.pExpert ){
23986     expertFinish(p, 1, 0);
23987   }
23988 #endif
23989 
23990   /* Parse the input line into tokens.
23991   */
23992   while( zLine[h] && nArg<ArraySize(azArg)-1 ){
23993     while( IsSpace(zLine[h]) ){ h++; }
23994     if( zLine[h]==0 ) break;
23995     if( zLine[h]=='\'' || zLine[h]=='"' ){
23996       int delim = zLine[h++];
23997       azArg[nArg++] = &zLine[h];
23998       while( zLine[h] && zLine[h]!=delim ){
23999         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
24000         h++;
24001       }
24002       if( zLine[h]==delim ){
24003         zLine[h++] = 0;
24004       }
24005       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
24006     }else{
24007       azArg[nArg++] = &zLine[h];
24008       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
24009       if( zLine[h] ) zLine[h++] = 0;
24010     }
24011   }
24012   azArg[nArg] = 0;
24013 
24014   /* Process the input line.
24015   */
24016   if( nArg==0 ) return 0; /* no tokens, no error */
24017   n = strlen30(azArg[0]);
24018   c = azArg[0][0];
24019   clearTempFile(p);
24020 
24021 #ifndef SQLITE_OMIT_AUTHORIZATION
24022   if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
24023     if( nArg!=2 ){
24024       raw_printf(stderr, "Usage: .auth ON|OFF\n");
24025       rc = 1;
24026       goto meta_command_exit;
24027     }
24028     open_db(p, 0);
24029     if( booleanValue(azArg[1]) ){
24030       sqlite3_set_authorizer(p->db, shellAuth, p);
24031     }else if( p->bSafeModePersist ){
24032       sqlite3_set_authorizer(p->db, safeModeAuth, p);
24033     }else{
24034       sqlite3_set_authorizer(p->db, 0, 0);
24035     }
24036   }else
24037 #endif
24038 
24039 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
24040   && !defined(SQLITE_SHELL_FIDDLE)
24041   if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
24042     open_db(p, 0);
24043     failIfSafeMode(p, "cannot run .archive in safe mode");
24044     rc = arDotCommand(p, 0, azArg, nArg);
24045   }else
24046 #endif
24047 
24048 #ifndef SQLITE_SHELL_FIDDLE
24049   if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
24050    || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
24051   ){
24052     const char *zDestFile = 0;
24053     const char *zDb = 0;
24054     sqlite3 *pDest;
24055     sqlite3_backup *pBackup;
24056     int j;
24057     int bAsync = 0;
24058     const char *zVfs = 0;
24059     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
24060     for(j=1; j<nArg; j++){
24061       const char *z = azArg[j];
24062       if( z[0]=='-' ){
24063         if( z[1]=='-' ) z++;
24064         if( cli_strcmp(z, "-append")==0 ){
24065           zVfs = "apndvfs";
24066         }else
24067         if( cli_strcmp(z, "-async")==0 ){
24068           bAsync = 1;
24069         }else
24070         {
24071           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
24072           return 1;
24073         }
24074       }else if( zDestFile==0 ){
24075         zDestFile = azArg[j];
24076       }else if( zDb==0 ){
24077         zDb = zDestFile;
24078         zDestFile = azArg[j];
24079       }else{
24080         raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
24081         return 1;
24082       }
24083     }
24084     if( zDestFile==0 ){
24085       raw_printf(stderr, "missing FILENAME argument on .backup\n");
24086       return 1;
24087     }
24088     if( zDb==0 ) zDb = "main";
24089     rc = sqlite3_open_v2(zDestFile, &pDest,
24090                   SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
24091     if( rc!=SQLITE_OK ){
24092       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
24093       close_db(pDest);
24094       return 1;
24095     }
24096     if( bAsync ){
24097       sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
24098                    0, 0, 0);
24099     }
24100     open_db(p, 0);
24101     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
24102     if( pBackup==0 ){
24103       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
24104       close_db(pDest);
24105       return 1;
24106     }
24107     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
24108     sqlite3_backup_finish(pBackup);
24109     if( rc==SQLITE_DONE ){
24110       rc = 0;
24111     }else{
24112       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
24113       rc = 1;
24114     }
24115     close_db(pDest);
24116   }else
24117 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24118 
24119   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
24120     if( nArg==2 ){
24121       bail_on_error = booleanValue(azArg[1]);
24122     }else{
24123       raw_printf(stderr, "Usage: .bail on|off\n");
24124       rc = 1;
24125     }
24126   }else
24127 
24128   /* Undocumented.  Legacy only.  See "crnl" below */
24129   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
24130     if( nArg==2 ){
24131       if( booleanValue(azArg[1]) ){
24132         setBinaryMode(p->out, 1);
24133       }else{
24134         setTextMode(p->out, 1);
24135       }
24136     }else{
24137       raw_printf(stderr, "The \".binary\" command is deprecated."
24138                          " Use \".crnl\" instead.\n");
24139       raw_printf(stderr, "Usage: .binary on|off\n");
24140       rc = 1;
24141     }
24142   }else
24143 
24144   /* The undocumented ".breakpoint" command causes a call to the no-op
24145   ** routine named test_breakpoint().
24146   */
24147   if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
24148     test_breakpoint();
24149   }else
24150 
24151 #ifndef SQLITE_SHELL_FIDDLE
24152   if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
24153     failIfSafeMode(p, "cannot run .cd in safe mode");
24154     if( nArg==2 ){
24155 #if defined(_WIN32) || defined(WIN32)
24156       wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
24157       rc = !SetCurrentDirectoryW(z);
24158       sqlite3_free(z);
24159 #else
24160       rc = chdir(azArg[1]);
24161 #endif
24162       if( rc ){
24163         utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
24164         rc = 1;
24165       }
24166     }else{
24167       raw_printf(stderr, "Usage: .cd DIRECTORY\n");
24168       rc = 1;
24169     }
24170   }else
24171 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24172 
24173   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
24174     if( nArg==2 ){
24175       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
24176     }else{
24177       raw_printf(stderr, "Usage: .changes on|off\n");
24178       rc = 1;
24179     }
24180   }else
24181 
24182 #ifndef SQLITE_SHELL_FIDDLE
24183   /* Cancel output redirection, if it is currently set (by .testcase)
24184   ** Then read the content of the testcase-out.txt file and compare against
24185   ** azArg[1].  If there are differences, report an error and exit.
24186   */
24187   if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
24188     char *zRes = 0;
24189     output_reset(p);
24190     if( nArg!=2 ){
24191       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
24192       rc = 2;
24193     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
24194       rc = 2;
24195     }else if( testcase_glob(azArg[1],zRes)==0 ){
24196       utf8_printf(stderr,
24197                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
24198                  p->zTestcase, azArg[1], zRes);
24199       rc = 1;
24200     }else{
24201       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
24202       p->nCheck++;
24203     }
24204     sqlite3_free(zRes);
24205   }else
24206 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24207 
24208 #ifndef SQLITE_SHELL_FIDDLE
24209   if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
24210     failIfSafeMode(p, "cannot run .clone in safe mode");
24211     if( nArg==2 ){
24212       tryToClone(p, azArg[1]);
24213     }else{
24214       raw_printf(stderr, "Usage: .clone FILENAME\n");
24215       rc = 1;
24216     }
24217   }else
24218 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
24219 
24220   if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
24221     if( nArg==1 ){
24222       /* List available connections */
24223       int i;
24224       for(i=0; i<ArraySize(p->aAuxDb); i++){
24225         const char *zFile = p->aAuxDb[i].zDbFilename;
24226         if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
24227           zFile = "(not open)";
24228         }else if( zFile==0 ){
24229           zFile = "(memory)";
24230         }else if( zFile[0]==0 ){
24231           zFile = "(temporary-file)";
24232         }
24233         if( p->pAuxDb == &p->aAuxDb[i] ){
24234           utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
24235         }else if( p->aAuxDb[i].db!=0 ){
24236           utf8_printf(stdout, "       %d: %s\n", i, zFile);
24237         }
24238       }
24239     }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
24240       int i = azArg[1][0] - '0';
24241       if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
24242         p->pAuxDb->db = p->db;
24243         p->pAuxDb = &p->aAuxDb[i];
24244         globalDb = p->db = p->pAuxDb->db;
24245         p->pAuxDb->db = 0;
24246       }
24247     }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
24248            && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
24249       int i = azArg[2][0] - '0';
24250       if( i<0 || i>=ArraySize(p->aAuxDb) ){
24251         /* No-op */
24252       }else if( p->pAuxDb == &p->aAuxDb[i] ){
24253         raw_printf(stderr, "cannot close the active database connection\n");
24254         rc = 1;
24255       }else if( p->aAuxDb[i].db ){
24256         session_close_all(p, i);
24257         close_db(p->aAuxDb[i].db);
24258         p->aAuxDb[i].db = 0;
24259       }
24260     }else{
24261       raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
24262       rc = 1;
24263     }
24264   }else
24265 
24266   if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
24267     if( nArg==2 ){
24268       if( booleanValue(azArg[1]) ){
24269         setTextMode(p->out, 1);
24270       }else{
24271         setBinaryMode(p->out, 1);
24272       }
24273     }else{
24274 #if !defined(_WIN32) && !defined(WIN32)
24275       raw_printf(stderr, "The \".crnl\" is a no-op on non-Windows machines.\n");
24276 #endif
24277       raw_printf(stderr, "Usage: .crnl on|off\n");
24278       rc = 1;
24279     }
24280   }else
24281 
24282   if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
24283     char **azName = 0;
24284     int nName = 0;
24285     sqlite3_stmt *pStmt;
24286     int i;
24287     open_db(p, 0);
24288     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
24289     if( rc ){
24290       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
24291       rc = 1;
24292     }else{
24293       while( sqlite3_step(pStmt)==SQLITE_ROW ){
24294         const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
24295         const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
24296         if( zSchema==0 || zFile==0 ) continue;
24297         azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
24298         shell_check_oom(azName);
24299         azName[nName*2] = strdup(zSchema);
24300         azName[nName*2+1] = strdup(zFile);
24301         nName++;
24302       }
24303     }
24304     sqlite3_finalize(pStmt);
24305     for(i=0; i<nName; i++){
24306       int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
24307       int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
24308       const char *z = azName[i*2+1];
24309       utf8_printf(p->out, "%s: %s %s%s\n",
24310          azName[i*2],
24311          z && z[0] ? z : "\"\"",
24312          bRdonly ? "r/o" : "r/w",
24313          eTxn==SQLITE_TXN_NONE ? "" :
24314             eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
24315       free(azName[i*2]);
24316       free(azName[i*2+1]);
24317     }
24318     sqlite3_free(azName);
24319   }else
24320 
24321   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
24322     static const struct DbConfigChoices {
24323       const char *zName;
24324       int op;
24325     } aDbConfig[] = {
24326         { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
24327         { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
24328         { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
24329         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
24330         { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
24331         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
24332         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
24333         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
24334         { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
24335         { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
24336         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
24337         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
24338         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
24339         { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
24340         { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
24341         { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
24342         { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
24343         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
24344     };
24345     int ii, v;
24346     open_db(p, 0);
24347     for(ii=0; ii<ArraySize(aDbConfig); ii++){
24348       if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
24349       if( nArg>=3 ){
24350         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
24351       }
24352       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
24353       utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
24354       if( nArg>1 ) break;
24355     }
24356     if( nArg>1 && ii==ArraySize(aDbConfig) ){
24357       utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
24358       utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
24359     }
24360   }else
24361 
24362 #if SQLITE_SHELL_HAVE_RECOVER
24363   if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
24364     rc = shell_dbinfo_command(p, nArg, azArg);
24365   }else
24366 
24367   if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
24368     open_db(p, 0);
24369     rc = recoverDatabaseCmd(p, nArg, azArg);
24370   }else
24371 #endif /* SQLITE_SHELL_HAVE_RECOVER */
24372 
24373   if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
24374     char *zLike = 0;
24375     char *zSql;
24376     int i;
24377     int savedShowHeader = p->showHeader;
24378     int savedShellFlags = p->shellFlgs;
24379     ShellClearFlag(p,
24380        SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
24381        |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
24382     for(i=1; i<nArg; i++){
24383       if( azArg[i][0]=='-' ){
24384         const char *z = azArg[i]+1;
24385         if( z[0]=='-' ) z++;
24386         if( cli_strcmp(z,"preserve-rowids")==0 ){
24387 #ifdef SQLITE_OMIT_VIRTUALTABLE
24388           raw_printf(stderr, "The --preserve-rowids option is not compatible"
24389                              " with SQLITE_OMIT_VIRTUALTABLE\n");
24390           rc = 1;
24391           sqlite3_free(zLike);
24392           goto meta_command_exit;
24393 #else
24394           ShellSetFlag(p, SHFLG_PreserveRowid);
24395 #endif
24396         }else
24397         if( cli_strcmp(z,"newlines")==0 ){
24398           ShellSetFlag(p, SHFLG_Newlines);
24399         }else
24400         if( cli_strcmp(z,"data-only")==0 ){
24401           ShellSetFlag(p, SHFLG_DumpDataOnly);
24402         }else
24403         if( cli_strcmp(z,"nosys")==0 ){
24404           ShellSetFlag(p, SHFLG_DumpNoSys);
24405         }else
24406         {
24407           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
24408           rc = 1;
24409           sqlite3_free(zLike);
24410           goto meta_command_exit;
24411         }
24412       }else{
24413         /* azArg[i] contains a LIKE pattern. This ".dump" request should
24414         ** only dump data for tables for which either the table name matches
24415         ** the LIKE pattern, or the table appears to be a shadow table of
24416         ** a virtual table for which the name matches the LIKE pattern.
24417         */
24418         char *zExpr = sqlite3_mprintf(
24419             "name LIKE %Q ESCAPE '\\' OR EXISTS ("
24420             "  SELECT 1 FROM sqlite_schema WHERE "
24421             "    name LIKE %Q ESCAPE '\\' AND"
24422             "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
24423             "    substr(o.name, 1, length(name)+1) == (name||'_')"
24424             ")", azArg[i], azArg[i]
24425         );
24426 
24427         if( zLike ){
24428           zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
24429         }else{
24430           zLike = zExpr;
24431         }
24432       }
24433     }
24434 
24435     open_db(p, 0);
24436 
24437     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
24438       /* When playing back a "dump", the content might appear in an order
24439       ** which causes immediate foreign key constraints to be violated.
24440       ** So disable foreign-key constraint enforcement to prevent problems. */
24441       raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
24442       raw_printf(p->out, "BEGIN TRANSACTION;\n");
24443     }
24444     p->writableSchema = 0;
24445     p->showHeader = 0;
24446     /* Set writable_schema=ON since doing so forces SQLite to initialize
24447     ** as much of the schema as it can even if the sqlite_schema table is
24448     ** corrupt. */
24449     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
24450     p->nErr = 0;
24451     if( zLike==0 ) zLike = sqlite3_mprintf("true");
24452     zSql = sqlite3_mprintf(
24453       "SELECT name, type, sql FROM sqlite_schema AS o "
24454       "WHERE (%s) AND type=='table'"
24455       "  AND sql NOT NULL"
24456       " ORDER BY tbl_name='sqlite_sequence', rowid",
24457       zLike
24458     );
24459     run_schema_dump_query(p,zSql);
24460     sqlite3_free(zSql);
24461     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
24462       zSql = sqlite3_mprintf(
24463         "SELECT sql FROM sqlite_schema AS o "
24464         "WHERE (%s) AND sql NOT NULL"
24465         "  AND type IN ('index','trigger','view')",
24466         zLike
24467       );
24468       run_table_dump_query(p, zSql);
24469       sqlite3_free(zSql);
24470     }
24471     sqlite3_free(zLike);
24472     if( p->writableSchema ){
24473       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
24474       p->writableSchema = 0;
24475     }
24476     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
24477     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
24478     if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
24479       raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
24480     }
24481     p->showHeader = savedShowHeader;
24482     p->shellFlgs = savedShellFlags;
24483   }else
24484 
24485   if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
24486     if( nArg==2 ){
24487       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
24488     }else{
24489       raw_printf(stderr, "Usage: .echo on|off\n");
24490       rc = 1;
24491     }
24492   }else
24493 
24494   if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
24495     if( nArg==2 ){
24496       p->autoEQPtest = 0;
24497       if( p->autoEQPtrace ){
24498         if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
24499         p->autoEQPtrace = 0;
24500       }
24501       if( cli_strcmp(azArg[1],"full")==0 ){
24502         p->autoEQP = AUTOEQP_full;
24503       }else if( cli_strcmp(azArg[1],"trigger")==0 ){
24504         p->autoEQP = AUTOEQP_trigger;
24505 #ifdef SQLITE_DEBUG
24506       }else if( cli_strcmp(azArg[1],"test")==0 ){
24507         p->autoEQP = AUTOEQP_on;
24508         p->autoEQPtest = 1;
24509       }else if( cli_strcmp(azArg[1],"trace")==0 ){
24510         p->autoEQP = AUTOEQP_full;
24511         p->autoEQPtrace = 1;
24512         open_db(p, 0);
24513         sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
24514         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
24515 #endif
24516       }else{
24517         p->autoEQP = (u8)booleanValue(azArg[1]);
24518       }
24519     }else{
24520       raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
24521       rc = 1;
24522     }
24523   }else
24524 
24525 #ifndef SQLITE_SHELL_FIDDLE
24526   if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
24527     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
24528     rc = 2;
24529   }else
24530 #endif
24531 
24532   /* The ".explain" command is automatic now.  It is largely pointless.  It
24533   ** retained purely for backwards compatibility */
24534   if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
24535     int val = 1;
24536     if( nArg>=2 ){
24537       if( cli_strcmp(azArg[1],"auto")==0 ){
24538         val = 99;
24539       }else{
24540         val =  booleanValue(azArg[1]);
24541       }
24542     }
24543     if( val==1 && p->mode!=MODE_Explain ){
24544       p->normalMode = p->mode;
24545       p->mode = MODE_Explain;
24546       p->autoExplain = 0;
24547     }else if( val==0 ){
24548       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
24549       p->autoExplain = 0;
24550     }else if( val==99 ){
24551       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
24552       p->autoExplain = 1;
24553     }
24554   }else
24555 
24556 #ifndef SQLITE_OMIT_VIRTUALTABLE
24557   if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
24558     if( p->bSafeMode ){
24559       raw_printf(stderr,
24560         "Cannot run experimental commands such as \"%s\" in safe mode\n",
24561         azArg[0]);
24562       rc = 1;
24563     }else{
24564       open_db(p, 0);
24565       expertDotCommand(p, azArg, nArg);
24566     }
24567   }else
24568 #endif
24569 
24570   if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
24571     static const struct {
24572        const char *zCtrlName;   /* Name of a test-control option */
24573        int ctrlCode;            /* Integer code for that option */
24574        const char *zUsage;      /* Usage notes */
24575     } aCtrl[] = {
24576       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
24577       { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
24578       { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
24579       { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
24580       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
24581    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
24582       { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
24583       { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
24584       { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
24585       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
24586    /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
24587     };
24588     int filectrl = -1;
24589     int iCtrl = -1;
24590     sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
24591     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
24592     int n2, i;
24593     const char *zCmd = 0;
24594     const char *zSchema = 0;
24595 
24596     open_db(p, 0);
24597     zCmd = nArg>=2 ? azArg[1] : "help";
24598 
24599     if( zCmd[0]=='-'
24600      && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
24601      && nArg>=4
24602     ){
24603       zSchema = azArg[2];
24604       for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
24605       nArg -= 2;
24606       zCmd = azArg[1];
24607     }
24608 
24609     /* The argument can optionally begin with "-" or "--" */
24610     if( zCmd[0]=='-' && zCmd[1] ){
24611       zCmd++;
24612       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
24613     }
24614 
24615     /* --help lists all file-controls */
24616     if( cli_strcmp(zCmd,"help")==0 ){
24617       utf8_printf(p->out, "Available file-controls:\n");
24618       for(i=0; i<ArraySize(aCtrl); i++){
24619         utf8_printf(p->out, "  .filectrl %s %s\n",
24620                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
24621       }
24622       rc = 1;
24623       goto meta_command_exit;
24624     }
24625 
24626     /* convert filectrl text option to value. allow any unique prefix
24627     ** of the option name, or a numerical value. */
24628     n2 = strlen30(zCmd);
24629     for(i=0; i<ArraySize(aCtrl); i++){
24630       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
24631         if( filectrl<0 ){
24632           filectrl = aCtrl[i].ctrlCode;
24633           iCtrl = i;
24634         }else{
24635           utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
24636                               "Use \".filectrl --help\" for help\n", zCmd);
24637           rc = 1;
24638           goto meta_command_exit;
24639         }
24640       }
24641     }
24642     if( filectrl<0 ){
24643       utf8_printf(stderr,"Error: unknown file-control: %s\n"
24644                          "Use \".filectrl --help\" for help\n", zCmd);
24645     }else{
24646       switch(filectrl){
24647         case SQLITE_FCNTL_SIZE_LIMIT: {
24648           if( nArg!=2 && nArg!=3 ) break;
24649           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
24650           sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
24651           isOk = 1;
24652           break;
24653         }
24654         case SQLITE_FCNTL_LOCK_TIMEOUT:
24655         case SQLITE_FCNTL_CHUNK_SIZE: {
24656           int x;
24657           if( nArg!=3 ) break;
24658           x = (int)integerValue(azArg[2]);
24659           sqlite3_file_control(p->db, zSchema, filectrl, &x);
24660           isOk = 2;
24661           break;
24662         }
24663         case SQLITE_FCNTL_PERSIST_WAL:
24664         case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
24665           int x;
24666           if( nArg!=2 && nArg!=3 ) break;
24667           x = nArg==3 ? booleanValue(azArg[2]) : -1;
24668           sqlite3_file_control(p->db, zSchema, filectrl, &x);
24669           iRes = x;
24670           isOk = 1;
24671           break;
24672         }
24673         case SQLITE_FCNTL_DATA_VERSION:
24674         case SQLITE_FCNTL_HAS_MOVED: {
24675           int x;
24676           if( nArg!=2 ) break;
24677           sqlite3_file_control(p->db, zSchema, filectrl, &x);
24678           iRes = x;
24679           isOk = 1;
24680           break;
24681         }
24682         case SQLITE_FCNTL_TEMPFILENAME: {
24683           char *z = 0;
24684           if( nArg!=2 ) break;
24685           sqlite3_file_control(p->db, zSchema, filectrl, &z);
24686           if( z ){
24687             utf8_printf(p->out, "%s\n", z);
24688             sqlite3_free(z);
24689           }
24690           isOk = 2;
24691           break;
24692         }
24693         case SQLITE_FCNTL_RESERVE_BYTES: {
24694           int x;
24695           if( nArg>=3 ){
24696             x = atoi(azArg[2]);
24697             sqlite3_file_control(p->db, zSchema, filectrl, &x);
24698           }
24699           x = -1;
24700           sqlite3_file_control(p->db, zSchema, filectrl, &x);
24701           utf8_printf(p->out,"%d\n", x);
24702           isOk = 2;
24703           break;
24704         }
24705       }
24706     }
24707     if( isOk==0 && iCtrl>=0 ){
24708       utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
24709       rc = 1;
24710     }else if( isOk==1 ){
24711       char zBuf[100];
24712       sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
24713       raw_printf(p->out, "%s\n", zBuf);
24714     }
24715   }else
24716 
24717   if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
24718     ShellState data;
24719     int doStats = 0;
24720     memcpy(&data, p, sizeof(data));
24721     data.showHeader = 0;
24722     data.cMode = data.mode = MODE_Semi;
24723     if( nArg==2 && optionMatch(azArg[1], "indent") ){
24724       data.cMode = data.mode = MODE_Pretty;
24725       nArg = 1;
24726     }
24727     if( nArg!=1 ){
24728       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
24729       rc = 1;
24730       goto meta_command_exit;
24731     }
24732     open_db(p, 0);
24733     rc = sqlite3_exec(p->db,
24734        "SELECT sql FROM"
24735        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
24736        "     FROM sqlite_schema UNION ALL"
24737        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
24738        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
24739        "ORDER BY x",
24740        callback, &data, 0
24741     );
24742     if( rc==SQLITE_OK ){
24743       sqlite3_stmt *pStmt;
24744       rc = sqlite3_prepare_v2(p->db,
24745                "SELECT rowid FROM sqlite_schema"
24746                " WHERE name GLOB 'sqlite_stat[134]'",
24747                -1, &pStmt, 0);
24748       if( rc==SQLITE_OK ){
24749         doStats = sqlite3_step(pStmt)==SQLITE_ROW;
24750         sqlite3_finalize(pStmt);
24751       }
24752     }
24753     if( doStats==0 ){
24754       raw_printf(p->out, "/* No STAT tables available */\n");
24755     }else{
24756       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
24757       data.cMode = data.mode = MODE_Insert;
24758       data.zDestTable = "sqlite_stat1";
24759       shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
24760       data.zDestTable = "sqlite_stat4";
24761       shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
24762       raw_printf(p->out, "ANALYZE sqlite_schema;\n");
24763     }
24764   }else
24765 
24766   if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
24767     if( nArg==2 ){
24768       p->showHeader = booleanValue(azArg[1]);
24769       p->shellFlgs |= SHFLG_HeaderSet;
24770     }else{
24771       raw_printf(stderr, "Usage: .headers on|off\n");
24772       rc = 1;
24773     }
24774   }else
24775 
24776   if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
24777     if( nArg>=2 ){
24778       n = showHelp(p->out, azArg[1]);
24779       if( n==0 ){
24780         utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
24781       }
24782     }else{
24783       showHelp(p->out, 0);
24784     }
24785   }else
24786 
24787 #ifndef SQLITE_SHELL_FIDDLE
24788   if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
24789     char *zTable = 0;           /* Insert data into this table */
24790     char *zSchema = 0;          /* within this schema (may default to "main") */
24791     char *zFile = 0;            /* Name of file to extra content from */
24792     sqlite3_stmt *pStmt = NULL; /* A statement */
24793     int nCol;                   /* Number of columns in the table */
24794     int nByte;                  /* Number of bytes in an SQL string */
24795     int i, j;                   /* Loop counters */
24796     int needCommit;             /* True to COMMIT or ROLLBACK at end */
24797     int nSep;                   /* Number of bytes in p->colSeparator[] */
24798     char *zSql;                 /* An SQL statement */
24799     char *zFullTabName;         /* Table name with schema if applicable */
24800     ImportCtx sCtx;             /* Reader context */
24801     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
24802     int eVerbose = 0;           /* Larger for more console output */
24803     int nSkip = 0;              /* Initial lines to skip */
24804     int useOutputMode = 1;      /* Use output mode to determine separators */
24805     char *zCreate = 0;          /* CREATE TABLE statement text */
24806 
24807     failIfSafeMode(p, "cannot run .import in safe mode");
24808     memset(&sCtx, 0, sizeof(sCtx));
24809     if( p->mode==MODE_Ascii ){
24810       xRead = ascii_read_one_field;
24811     }else{
24812       xRead = csv_read_one_field;
24813     }
24814     rc = 1;
24815     for(i=1; i<nArg; i++){
24816       char *z = azArg[i];
24817       if( z[0]=='-' && z[1]=='-' ) z++;
24818       if( z[0]!='-' ){
24819         if( zFile==0 ){
24820           zFile = z;
24821         }else if( zTable==0 ){
24822           zTable = z;
24823         }else{
24824           utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
24825           showHelp(p->out, "import");
24826           goto meta_command_exit;
24827         }
24828       }else if( cli_strcmp(z,"-v")==0 ){
24829         eVerbose++;
24830       }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
24831         zSchema = azArg[++i];
24832       }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
24833         nSkip = integerValue(azArg[++i]);
24834       }else if( cli_strcmp(z,"-ascii")==0 ){
24835         sCtx.cColSep = SEP_Unit[0];
24836         sCtx.cRowSep = SEP_Record[0];
24837         xRead = ascii_read_one_field;
24838         useOutputMode = 0;
24839       }else if( cli_strcmp(z,"-csv")==0 ){
24840         sCtx.cColSep = ',';
24841         sCtx.cRowSep = '\n';
24842         xRead = csv_read_one_field;
24843         useOutputMode = 0;
24844       }else{
24845         utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
24846         showHelp(p->out, "import");
24847         goto meta_command_exit;
24848       }
24849     }
24850     if( zTable==0 ){
24851       utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
24852                   zFile==0 ? "FILE" : "TABLE");
24853       showHelp(p->out, "import");
24854       goto meta_command_exit;
24855     }
24856     seenInterrupt = 0;
24857     open_db(p, 0);
24858     if( useOutputMode ){
24859       /* If neither the --csv or --ascii options are specified, then set
24860       ** the column and row separator characters from the output mode. */
24861       nSep = strlen30(p->colSeparator);
24862       if( nSep==0 ){
24863         raw_printf(stderr,
24864                    "Error: non-null column separator required for import\n");
24865         goto meta_command_exit;
24866       }
24867       if( nSep>1 ){
24868         raw_printf(stderr,
24869               "Error: multi-character column separators not allowed"
24870               " for import\n");
24871         goto meta_command_exit;
24872       }
24873       nSep = strlen30(p->rowSeparator);
24874       if( nSep==0 ){
24875         raw_printf(stderr,
24876             "Error: non-null row separator required for import\n");
24877         goto meta_command_exit;
24878       }
24879       if( nSep==2 && p->mode==MODE_Csv
24880        && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
24881       ){
24882         /* When importing CSV (only), if the row separator is set to the
24883         ** default output row separator, change it to the default input
24884         ** row separator.  This avoids having to maintain different input
24885         ** and output row separators. */
24886         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
24887         nSep = strlen30(p->rowSeparator);
24888       }
24889       if( nSep>1 ){
24890         raw_printf(stderr, "Error: multi-character row separators not allowed"
24891                            " for import\n");
24892         goto meta_command_exit;
24893       }
24894       sCtx.cColSep = (u8)p->colSeparator[0];
24895       sCtx.cRowSep = (u8)p->rowSeparator[0];
24896     }
24897     sCtx.zFile = zFile;
24898     sCtx.nLine = 1;
24899     if( sCtx.zFile[0]=='|' ){
24900 #ifdef SQLITE_OMIT_POPEN
24901       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
24902       goto meta_command_exit;
24903 #else
24904       sCtx.in = popen(sCtx.zFile+1, "r");
24905       sCtx.zFile = "<pipe>";
24906       sCtx.xCloser = pclose;
24907 #endif
24908     }else{
24909       sCtx.in = fopen(sCtx.zFile, "rb");
24910       sCtx.xCloser = fclose;
24911     }
24912     if( sCtx.in==0 ){
24913       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
24914       goto meta_command_exit;
24915     }
24916     if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
24917       char zSep[2];
24918       zSep[1] = 0;
24919       zSep[0] = sCtx.cColSep;
24920       utf8_printf(p->out, "Column separator ");
24921       output_c_string(p->out, zSep);
24922       utf8_printf(p->out, ", row separator ");
24923       zSep[0] = sCtx.cRowSep;
24924       output_c_string(p->out, zSep);
24925       utf8_printf(p->out, "\n");
24926     }
24927     sCtx.z = sqlite3_malloc64(120);
24928     if( sCtx.z==0 ){
24929       import_cleanup(&sCtx);
24930       shell_out_of_memory();
24931     }
24932     /* Below, resources must be freed before exit. */
24933     while( (nSkip--)>0 ){
24934       while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
24935     }
24936     if( zSchema!=0 ){
24937       zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
24938     }else{
24939       zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
24940     }
24941     zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
24942     if( zSql==0 || zFullTabName==0 ){
24943       import_cleanup(&sCtx);
24944       shell_out_of_memory();
24945     }
24946     nByte = strlen30(zSql);
24947     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24948     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
24949     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
24950       sqlite3 *dbCols = 0;
24951       char *zRenames = 0;
24952       char *zColDefs;
24953       zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
24954       while( xRead(&sCtx) ){
24955         zAutoColumn(sCtx.z, &dbCols, 0);
24956         if( sCtx.cTerm!=sCtx.cColSep ) break;
24957       }
24958       zColDefs = zAutoColumn(0, &dbCols, &zRenames);
24959       if( zRenames!=0 ){
24960         utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
24961                     "Columns renamed during .import %s due to duplicates:\n"
24962                     "%s\n", sCtx.zFile, zRenames);
24963         sqlite3_free(zRenames);
24964       }
24965       assert(dbCols==0);
24966       if( zColDefs==0 ){
24967         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
24968       import_fail:
24969         sqlite3_free(zCreate);
24970         sqlite3_free(zSql);
24971         sqlite3_free(zFullTabName);
24972         import_cleanup(&sCtx);
24973         rc = 1;
24974         goto meta_command_exit;
24975       }
24976       zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
24977       if( eVerbose>=1 ){
24978         utf8_printf(p->out, "%s\n", zCreate);
24979       }
24980       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
24981       if( rc ){
24982         utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
24983         goto import_fail;
24984       }
24985       sqlite3_free(zCreate);
24986       zCreate = 0;
24987       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
24988     }
24989     if( rc ){
24990       if (pStmt) sqlite3_finalize(pStmt);
24991       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
24992       goto import_fail;
24993     }
24994     sqlite3_free(zSql);
24995     nCol = sqlite3_column_count(pStmt);
24996     sqlite3_finalize(pStmt);
24997     pStmt = 0;
24998     if( nCol==0 ) return 0; /* no columns, no error */
24999     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
25000     if( zSql==0 ){
25001       import_cleanup(&sCtx);
25002       shell_out_of_memory();
25003     }
25004     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
25005     j = strlen30(zSql);
25006     for(i=1; i<nCol; i++){
25007       zSql[j++] = ',';
25008       zSql[j++] = '?';
25009     }
25010     zSql[j++] = ')';
25011     zSql[j] = 0;
25012     if( eVerbose>=2 ){
25013       utf8_printf(p->out, "Insert using: %s\n", zSql);
25014     }
25015     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25016     if( rc ){
25017       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
25018       if (pStmt) sqlite3_finalize(pStmt);
25019       goto import_fail;
25020     }
25021     sqlite3_free(zSql);
25022     sqlite3_free(zFullTabName);
25023     needCommit = sqlite3_get_autocommit(p->db);
25024     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
25025     do{
25026       int startLine = sCtx.nLine;
25027       for(i=0; i<nCol; i++){
25028         char *z = xRead(&sCtx);
25029         /*
25030         ** Did we reach end-of-file before finding any columns?
25031         ** If so, stop instead of NULL filling the remaining columns.
25032         */
25033         if( z==0 && i==0 ) break;
25034         /*
25035         ** Did we reach end-of-file OR end-of-line before finding any
25036         ** columns in ASCII mode?  If so, stop instead of NULL filling
25037         ** the remaining columns.
25038         */
25039         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
25040         /*
25041         ** For CSV mode, per RFC 4180, accept EOF in lieu of final
25042         ** record terminator but only for last field of multi-field row.
25043         ** (If there are too few fields, it's not valid CSV anyway.)
25044         */
25045         if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
25046           z = "";
25047         }
25048         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
25049         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
25050           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
25051                           "filling the rest with NULL\n",
25052                           sCtx.zFile, startLine, nCol, i+1);
25053           i += 2;
25054           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
25055         }
25056       }
25057       if( sCtx.cTerm==sCtx.cColSep ){
25058         do{
25059           xRead(&sCtx);
25060           i++;
25061         }while( sCtx.cTerm==sCtx.cColSep );
25062         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
25063                         "extras ignored\n",
25064                         sCtx.zFile, startLine, nCol, i);
25065       }
25066       if( i>=nCol ){
25067         sqlite3_step(pStmt);
25068         rc = sqlite3_reset(pStmt);
25069         if( rc!=SQLITE_OK ){
25070           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
25071                       startLine, sqlite3_errmsg(p->db));
25072           sCtx.nErr++;
25073         }else{
25074           sCtx.nRow++;
25075         }
25076       }
25077     }while( sCtx.cTerm!=EOF );
25078 
25079     import_cleanup(&sCtx);
25080     sqlite3_finalize(pStmt);
25081     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
25082     if( eVerbose>0 ){
25083       utf8_printf(p->out,
25084           "Added %d rows with %d errors using %d lines of input\n",
25085           sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
25086     }
25087   }else
25088 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25089 
25090 #ifndef SQLITE_UNTESTABLE
25091   if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
25092     char *zSql;
25093     char *zCollist = 0;
25094     sqlite3_stmt *pStmt;
25095     int tnum = 0;
25096     int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
25097     int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
25098     int i;
25099     if( !ShellHasFlag(p,SHFLG_TestingMode) ){
25100       utf8_printf(stderr, ".%s unavailable without --unsafe-testing\n",
25101                   "imposter");
25102       rc = 1;
25103       goto meta_command_exit;
25104     }
25105     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
25106       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
25107                           "       .imposter off\n");
25108       /* Also allowed, but not documented:
25109       **
25110       **    .imposter TABLE IMPOSTER
25111       **
25112       ** where TABLE is a WITHOUT ROWID table.  In that case, the
25113       ** imposter is another WITHOUT ROWID table with the columns in
25114       ** storage order. */
25115       rc = 1;
25116       goto meta_command_exit;
25117     }
25118     open_db(p, 0);
25119     if( nArg==2 ){
25120       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
25121       goto meta_command_exit;
25122     }
25123     zSql = sqlite3_mprintf(
25124       "SELECT rootpage, 0 FROM sqlite_schema"
25125       " WHERE name='%q' AND type='index'"
25126       "UNION ALL "
25127       "SELECT rootpage, 1 FROM sqlite_schema"
25128       " WHERE name='%q' AND type='table'"
25129       "   AND sql LIKE '%%without%%rowid%%'",
25130       azArg[1], azArg[1]
25131     );
25132     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25133     sqlite3_free(zSql);
25134     if( sqlite3_step(pStmt)==SQLITE_ROW ){
25135       tnum = sqlite3_column_int(pStmt, 0);
25136       isWO = sqlite3_column_int(pStmt, 1);
25137     }
25138     sqlite3_finalize(pStmt);
25139     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
25140     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25141     sqlite3_free(zSql);
25142     i = 0;
25143     while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
25144       char zLabel[20];
25145       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
25146       i++;
25147       if( zCol==0 ){
25148         if( sqlite3_column_int(pStmt,1)==-1 ){
25149           zCol = "_ROWID_";
25150         }else{
25151           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
25152           zCol = zLabel;
25153         }
25154       }
25155       if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
25156         lenPK = (int)strlen(zCollist);
25157       }
25158       if( zCollist==0 ){
25159         zCollist = sqlite3_mprintf("\"%w\"", zCol);
25160       }else{
25161         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
25162       }
25163     }
25164     sqlite3_finalize(pStmt);
25165     if( i==0 || tnum==0 ){
25166       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
25167       rc = 1;
25168       sqlite3_free(zCollist);
25169       goto meta_command_exit;
25170     }
25171     if( lenPK==0 ) lenPK = 100000;
25172     zSql = sqlite3_mprintf(
25173           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
25174           azArg[2], zCollist, lenPK, zCollist);
25175     sqlite3_free(zCollist);
25176     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
25177     if( rc==SQLITE_OK ){
25178       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
25179       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
25180       if( rc ){
25181         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
25182       }else{
25183         utf8_printf(stdout, "%s;\n", zSql);
25184         raw_printf(stdout,
25185           "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
25186           azArg[1], isWO ? "table" : "index"
25187         );
25188       }
25189     }else{
25190       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
25191       rc = 1;
25192     }
25193     sqlite3_free(zSql);
25194   }else
25195 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
25196 
25197 #ifdef SQLITE_ENABLE_IOTRACE
25198   if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
25199     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
25200     if( iotrace && iotrace!=stdout ) fclose(iotrace);
25201     iotrace = 0;
25202     if( nArg<2 ){
25203       sqlite3IoTrace = 0;
25204     }else if( cli_strcmp(azArg[1], "-")==0 ){
25205       sqlite3IoTrace = iotracePrintf;
25206       iotrace = stdout;
25207     }else{
25208       iotrace = fopen(azArg[1], "w");
25209       if( iotrace==0 ){
25210         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
25211         sqlite3IoTrace = 0;
25212         rc = 1;
25213       }else{
25214         sqlite3IoTrace = iotracePrintf;
25215       }
25216     }
25217   }else
25218 #endif
25219 
25220   if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
25221     static const struct {
25222        const char *zLimitName;   /* Name of a limit */
25223        int limitCode;            /* Integer code for that limit */
25224     } aLimit[] = {
25225       { "length",                SQLITE_LIMIT_LENGTH                    },
25226       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
25227       { "column",                SQLITE_LIMIT_COLUMN                    },
25228       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
25229       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
25230       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
25231       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
25232       { "attached",              SQLITE_LIMIT_ATTACHED                  },
25233       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
25234       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
25235       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
25236       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
25237     };
25238     int i, n2;
25239     open_db(p, 0);
25240     if( nArg==1 ){
25241       for(i=0; i<ArraySize(aLimit); i++){
25242         printf("%20s %d\n", aLimit[i].zLimitName,
25243                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
25244       }
25245     }else if( nArg>3 ){
25246       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
25247       rc = 1;
25248       goto meta_command_exit;
25249     }else{
25250       int iLimit = -1;
25251       n2 = strlen30(azArg[1]);
25252       for(i=0; i<ArraySize(aLimit); i++){
25253         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
25254           if( iLimit<0 ){
25255             iLimit = i;
25256           }else{
25257             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
25258             rc = 1;
25259             goto meta_command_exit;
25260           }
25261         }
25262       }
25263       if( iLimit<0 ){
25264         utf8_printf(stderr, "unknown limit: \"%s\"\n"
25265                         "enter \".limits\" with no arguments for a list.\n",
25266                          azArg[1]);
25267         rc = 1;
25268         goto meta_command_exit;
25269       }
25270       if( nArg==3 ){
25271         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
25272                       (int)integerValue(azArg[2]));
25273       }
25274       printf("%20s %d\n", aLimit[iLimit].zLimitName,
25275              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
25276     }
25277   }else
25278 
25279   if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
25280     open_db(p, 0);
25281     lintDotCommand(p, azArg, nArg);
25282   }else
25283 
25284 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
25285   if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
25286     const char *zFile, *zProc;
25287     char *zErrMsg = 0;
25288     failIfSafeMode(p, "cannot run .load in safe mode");
25289     if( nArg<2 || azArg[1][0]==0 ){
25290       /* Must have a non-empty FILE. (Will not load self.) */
25291       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
25292       rc = 1;
25293       goto meta_command_exit;
25294     }
25295     zFile = azArg[1];
25296     zProc = nArg>=3 ? azArg[2] : 0;
25297     open_db(p, 0);
25298     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
25299     if( rc!=SQLITE_OK ){
25300       utf8_printf(stderr, "Error: %s\n", zErrMsg);
25301       sqlite3_free(zErrMsg);
25302       rc = 1;
25303     }
25304   }else
25305 #endif
25306 
25307   if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
25308     if( nArg!=2 ){
25309       raw_printf(stderr, "Usage: .log FILENAME\n");
25310       rc = 1;
25311     }else{
25312       const char *zFile = azArg[1];
25313       if( p->bSafeMode
25314        && cli_strcmp(zFile,"on")!=0
25315        && cli_strcmp(zFile,"off")!=0
25316       ){
25317         raw_printf(stdout, "cannot set .log to anything other "
25318                    "than \"on\" or \"off\"\n");
25319         zFile = "off";
25320       }
25321       output_file_close(p->pLog);
25322       if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
25323       p->pLog = output_file_open(zFile, 0);
25324     }
25325   }else
25326 
25327   if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
25328     const char *zMode = 0;
25329     const char *zTabname = 0;
25330     int i, n2;
25331     ColModeOpts cmOpts = ColModeOpts_default;
25332     for(i=1; i<nArg; i++){
25333       const char *z = azArg[i];
25334       if( optionMatch(z,"wrap") && i+1<nArg ){
25335         cmOpts.iWrap = integerValue(azArg[++i]);
25336       }else if( optionMatch(z,"ww") ){
25337         cmOpts.bWordWrap = 1;
25338       }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
25339         cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
25340       }else if( optionMatch(z,"quote") ){
25341         cmOpts.bQuote = 1;
25342       }else if( optionMatch(z,"noquote") ){
25343         cmOpts.bQuote = 0;
25344       }else if( zMode==0 ){
25345         zMode = z;
25346         /* Apply defaults for qbox pseudo-mode.  If that
25347          * overwrites already-set values, user was informed of this.
25348          */
25349         if( cli_strcmp(z, "qbox")==0 ){
25350           ColModeOpts cmo = ColModeOpts_default_qbox;
25351           zMode = "box";
25352           cmOpts = cmo;
25353         }
25354       }else if( zTabname==0 ){
25355         zTabname = z;
25356       }else if( z[0]=='-' ){
25357         utf8_printf(stderr, "unknown option: %s\n", z);
25358         utf8_printf(stderr, "options:\n"
25359                             "  --noquote\n"
25360                             "  --quote\n"
25361                             "  --wordwrap on/off\n"
25362                             "  --wrap N\n"
25363                             "  --ww\n");
25364         rc = 1;
25365         goto meta_command_exit;
25366       }else{
25367         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
25368         rc = 1;
25369         goto meta_command_exit;
25370       }
25371     }
25372     if( zMode==0 ){
25373       if( p->mode==MODE_Column
25374        || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
25375       ){
25376         raw_printf
25377           (p->out,
25378            "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
25379            modeDescr[p->mode], p->cmOpts.iWrap,
25380            p->cmOpts.bWordWrap ? "on" : "off",
25381            p->cmOpts.bQuote ? "" : "no");
25382       }else{
25383         raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
25384       }
25385       zMode = modeDescr[p->mode];
25386     }
25387     n2 = strlen30(zMode);
25388     if( cli_strncmp(zMode,"lines",n2)==0 ){
25389       p->mode = MODE_Line;
25390       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25391     }else if( cli_strncmp(zMode,"columns",n2)==0 ){
25392       p->mode = MODE_Column;
25393       if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
25394         p->showHeader = 1;
25395       }
25396       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25397       p->cmOpts = cmOpts;
25398     }else if( cli_strncmp(zMode,"list",n2)==0 ){
25399       p->mode = MODE_List;
25400       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
25401       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25402     }else if( cli_strncmp(zMode,"html",n2)==0 ){
25403       p->mode = MODE_Html;
25404     }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
25405       p->mode = MODE_Tcl;
25406       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
25407       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25408     }else if( cli_strncmp(zMode,"csv",n2)==0 ){
25409       p->mode = MODE_Csv;
25410       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
25411       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
25412     }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
25413       p->mode = MODE_List;
25414       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
25415     }else if( cli_strncmp(zMode,"insert",n2)==0 ){
25416       p->mode = MODE_Insert;
25417       set_table_name(p, zTabname ? zTabname : "table");
25418     }else if( cli_strncmp(zMode,"quote",n2)==0 ){
25419       p->mode = MODE_Quote;
25420       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
25421       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
25422     }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
25423       p->mode = MODE_Ascii;
25424       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
25425       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
25426     }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
25427       p->mode = MODE_Markdown;
25428       p->cmOpts = cmOpts;
25429     }else if( cli_strncmp(zMode,"table",n2)==0 ){
25430       p->mode = MODE_Table;
25431       p->cmOpts = cmOpts;
25432     }else if( cli_strncmp(zMode,"box",n2)==0 ){
25433       p->mode = MODE_Box;
25434       p->cmOpts = cmOpts;
25435     }else if( cli_strncmp(zMode,"count",n2)==0 ){
25436       p->mode = MODE_Count;
25437     }else if( cli_strncmp(zMode,"off",n2)==0 ){
25438       p->mode = MODE_Off;
25439     }else if( cli_strncmp(zMode,"json",n2)==0 ){
25440       p->mode = MODE_Json;
25441     }else{
25442       raw_printf(stderr, "Error: mode should be one of: "
25443          "ascii box column csv html insert json line list markdown "
25444          "qbox quote table tabs tcl\n");
25445       rc = 1;
25446     }
25447     p->cMode = p->mode;
25448   }else
25449 
25450 #ifndef SQLITE_SHELL_FIDDLE
25451   if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
25452     if( nArg!=2 ){
25453       raw_printf(stderr, "Usage: .nonce NONCE\n");
25454       rc = 1;
25455     }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
25456       raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
25457                  p->lineno, azArg[1]);
25458       exit(1);
25459     }else{
25460       p->bSafeMode = 0;
25461       return 0;  /* Return immediately to bypass the safe mode reset
25462                  ** at the end of this procedure */
25463     }
25464   }else
25465 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25466 
25467   if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
25468     if( nArg==2 ){
25469       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
25470                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
25471     }else{
25472       raw_printf(stderr, "Usage: .nullvalue STRING\n");
25473       rc = 1;
25474     }
25475   }else
25476 
25477   if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
25478     const char *zFN = 0;     /* Pointer to constant filename */
25479     char *zNewFilename = 0;  /* Name of the database file to open */
25480     int iName = 1;           /* Index in azArg[] of the filename */
25481     int newFlag = 0;         /* True to delete file before opening */
25482     int openMode = SHELL_OPEN_UNSPEC;
25483 
25484     /* Check for command-line arguments */
25485     for(iName=1; iName<nArg; iName++){
25486       const char *z = azArg[iName];
25487 #ifndef SQLITE_SHELL_FIDDLE
25488       if( optionMatch(z,"new") ){
25489         newFlag = 1;
25490 #ifdef SQLITE_HAVE_ZLIB
25491       }else if( optionMatch(z, "zip") ){
25492         openMode = SHELL_OPEN_ZIPFILE;
25493 #endif
25494       }else if( optionMatch(z, "append") ){
25495         openMode = SHELL_OPEN_APPENDVFS;
25496       }else if( optionMatch(z, "readonly") ){
25497         openMode = SHELL_OPEN_READONLY;
25498       }else if( optionMatch(z, "nofollow") ){
25499         p->openFlags |= SQLITE_OPEN_NOFOLLOW;
25500 #ifndef SQLITE_OMIT_DESERIALIZE
25501       }else if( optionMatch(z, "deserialize") ){
25502         openMode = SHELL_OPEN_DESERIALIZE;
25503       }else if( optionMatch(z, "hexdb") ){
25504         openMode = SHELL_OPEN_HEXDB;
25505       }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
25506         p->szMax = integerValue(azArg[++iName]);
25507 #endif /* SQLITE_OMIT_DESERIALIZE */
25508       }else
25509 #endif /* !SQLITE_SHELL_FIDDLE */
25510       if( z[0]=='-' ){
25511         utf8_printf(stderr, "unknown option: %s\n", z);
25512         rc = 1;
25513         goto meta_command_exit;
25514       }else if( zFN ){
25515         utf8_printf(stderr, "extra argument: \"%s\"\n", z);
25516         rc = 1;
25517         goto meta_command_exit;
25518       }else{
25519         zFN = z;
25520       }
25521     }
25522 
25523     /* Close the existing database */
25524     session_close_all(p, -1);
25525     close_db(p->db);
25526     p->db = 0;
25527     p->pAuxDb->zDbFilename = 0;
25528     sqlite3_free(p->pAuxDb->zFreeOnClose);
25529     p->pAuxDb->zFreeOnClose = 0;
25530     p->openMode = openMode;
25531     p->openFlags = 0;
25532     p->szMax = 0;
25533 
25534     /* If a filename is specified, try to open it first */
25535     if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
25536       if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
25537 #ifndef SQLITE_SHELL_FIDDLE
25538       if( p->bSafeMode
25539        && p->openMode!=SHELL_OPEN_HEXDB
25540        && zFN
25541        && cli_strcmp(zFN,":memory:")!=0
25542       ){
25543         failIfSafeMode(p, "cannot open disk-based database files in safe mode");
25544       }
25545 #else
25546       /* WASM mode has its own sandboxed pseudo-filesystem. */
25547 #endif
25548       if( zFN ){
25549         zNewFilename = sqlite3_mprintf("%s", zFN);
25550         shell_check_oom(zNewFilename);
25551       }else{
25552         zNewFilename = 0;
25553       }
25554       p->pAuxDb->zDbFilename = zNewFilename;
25555       open_db(p, OPEN_DB_KEEPALIVE);
25556       if( p->db==0 ){
25557         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
25558         sqlite3_free(zNewFilename);
25559       }else{
25560         p->pAuxDb->zFreeOnClose = zNewFilename;
25561       }
25562     }
25563     if( p->db==0 ){
25564       /* As a fall-back open a TEMP database */
25565       p->pAuxDb->zDbFilename = 0;
25566       open_db(p, 0);
25567     }
25568   }else
25569 
25570 #ifndef SQLITE_SHELL_FIDDLE
25571   if( (c=='o'
25572         && (cli_strncmp(azArg[0], "output", n)==0
25573             || cli_strncmp(azArg[0], "once", n)==0))
25574    || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
25575   ){
25576     char *zFile = 0;
25577     int bTxtMode = 0;
25578     int i;
25579     int eMode = 0;
25580     int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
25581     unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
25582 
25583     zBOM[0] = 0;
25584     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
25585     if( c=='e' ){
25586       eMode = 'x';
25587       bOnce = 2;
25588     }else if( cli_strncmp(azArg[0],"once",n)==0 ){
25589       bOnce = 1;
25590     }
25591     for(i=1; i<nArg; i++){
25592       char *z = azArg[i];
25593       if( z[0]=='-' ){
25594         if( z[1]=='-' ) z++;
25595         if( cli_strcmp(z,"-bom")==0 ){
25596           zBOM[0] = 0xef;
25597           zBOM[1] = 0xbb;
25598           zBOM[2] = 0xbf;
25599           zBOM[3] = 0;
25600         }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
25601           eMode = 'x';  /* spreadsheet */
25602         }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
25603           eMode = 'e';  /* text editor */
25604         }else{
25605           utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
25606                       azArg[i]);
25607           showHelp(p->out, azArg[0]);
25608           rc = 1;
25609           goto meta_command_exit;
25610         }
25611       }else if( zFile==0 && eMode!='e' && eMode!='x' ){
25612         zFile = sqlite3_mprintf("%s", z);
25613         if( zFile && zFile[0]=='|' ){
25614           while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
25615           break;
25616         }
25617       }else{
25618         utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
25619                     azArg[i]);
25620         showHelp(p->out, azArg[0]);
25621         rc = 1;
25622         sqlite3_free(zFile);
25623         goto meta_command_exit;
25624       }
25625     }
25626     if( zFile==0 ){
25627       zFile = sqlite3_mprintf("stdout");
25628     }
25629     if( bOnce ){
25630       p->outCount = 2;
25631     }else{
25632       p->outCount = 0;
25633     }
25634     output_reset(p);
25635 #ifndef SQLITE_NOHAVE_SYSTEM
25636     if( eMode=='e' || eMode=='x' ){
25637       p->doXdgOpen = 1;
25638       outputModePush(p);
25639       if( eMode=='x' ){
25640         /* spreadsheet mode.  Output as CSV. */
25641         newTempFile(p, "csv");
25642         ShellClearFlag(p, SHFLG_Echo);
25643         p->mode = MODE_Csv;
25644         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
25645         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
25646       }else{
25647         /* text editor mode */
25648         newTempFile(p, "txt");
25649         bTxtMode = 1;
25650       }
25651       sqlite3_free(zFile);
25652       zFile = sqlite3_mprintf("%s", p->zTempFile);
25653     }
25654 #endif /* SQLITE_NOHAVE_SYSTEM */
25655     shell_check_oom(zFile);
25656     if( zFile[0]=='|' ){
25657 #ifdef SQLITE_OMIT_POPEN
25658       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
25659       rc = 1;
25660       p->out = stdout;
25661 #else
25662       p->out = popen(zFile + 1, "w");
25663       if( p->out==0 ){
25664         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
25665         p->out = stdout;
25666         rc = 1;
25667       }else{
25668         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
25669         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
25670       }
25671 #endif
25672     }else{
25673       p->out = output_file_open(zFile, bTxtMode);
25674       if( p->out==0 ){
25675         if( cli_strcmp(zFile,"off")!=0 ){
25676           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
25677         }
25678         p->out = stdout;
25679         rc = 1;
25680       } else {
25681         if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
25682         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
25683       }
25684     }
25685     sqlite3_free(zFile);
25686   }else
25687 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25688 
25689   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
25690     open_db(p,0);
25691     if( nArg<=1 ) goto parameter_syntax_error;
25692 
25693     /* .parameter clear
25694     ** Clear all bind parameters by dropping the TEMP table that holds them.
25695     */
25696     if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
25697       sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
25698                    0, 0, 0);
25699     }else
25700 
25701     /* .parameter list
25702     ** List all bind parameters.
25703     */
25704     if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
25705       sqlite3_stmt *pStmt = 0;
25706       int rx;
25707       int len = 0;
25708       rx = sqlite3_prepare_v2(p->db,
25709              "SELECT max(length(key)) "
25710              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
25711       if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
25712         len = sqlite3_column_int(pStmt, 0);
25713         if( len>40 ) len = 40;
25714       }
25715       sqlite3_finalize(pStmt);
25716       pStmt = 0;
25717       if( len ){
25718         rx = sqlite3_prepare_v2(p->db,
25719              "SELECT key, quote(value) "
25720              "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
25721         while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
25722           utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
25723                       sqlite3_column_text(pStmt,1));
25724         }
25725         sqlite3_finalize(pStmt);
25726       }
25727     }else
25728 
25729     /* .parameter init
25730     ** Make sure the TEMP table used to hold bind parameters exists.
25731     ** Create it if necessary.
25732     */
25733     if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
25734       bind_table_init(p);
25735     }else
25736 
25737     /* .parameter set NAME VALUE
25738     ** Set or reset a bind parameter.  NAME should be the full parameter
25739     ** name exactly as it appears in the query.  (ex: $abc, @def).  The
25740     ** VALUE can be in either SQL literal notation, or if not it will be
25741     ** understood to be a text string.
25742     */
25743     if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
25744       int rx;
25745       char *zSql;
25746       sqlite3_stmt *pStmt;
25747       const char *zKey = azArg[2];
25748       const char *zValue = azArg[3];
25749       bind_table_init(p);
25750       zSql = sqlite3_mprintf(
25751                   "REPLACE INTO temp.sqlite_parameters(key,value)"
25752                   "VALUES(%Q,%s);", zKey, zValue);
25753       shell_check_oom(zSql);
25754       pStmt = 0;
25755       rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25756       sqlite3_free(zSql);
25757       if( rx!=SQLITE_OK ){
25758         sqlite3_finalize(pStmt);
25759         pStmt = 0;
25760         zSql = sqlite3_mprintf(
25761                    "REPLACE INTO temp.sqlite_parameters(key,value)"
25762                    "VALUES(%Q,%Q);", zKey, zValue);
25763         shell_check_oom(zSql);
25764         rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
25765         sqlite3_free(zSql);
25766         if( rx!=SQLITE_OK ){
25767           utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
25768           sqlite3_finalize(pStmt);
25769           pStmt = 0;
25770           rc = 1;
25771         }
25772       }
25773       sqlite3_step(pStmt);
25774       sqlite3_finalize(pStmt);
25775     }else
25776 
25777     /* .parameter unset NAME
25778     ** Remove the NAME binding from the parameter binding table, if it
25779     ** exists.
25780     */
25781     if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
25782       char *zSql = sqlite3_mprintf(
25783           "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
25784       shell_check_oom(zSql);
25785       sqlite3_exec(p->db, zSql, 0, 0, 0);
25786       sqlite3_free(zSql);
25787     }else
25788     /* If no command name matches, show a syntax error */
25789     parameter_syntax_error:
25790     showHelp(p->out, "parameter");
25791   }else
25792 
25793   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
25794     int i;
25795     for(i=1; i<nArg; i++){
25796       if( i>1 ) raw_printf(p->out, " ");
25797       utf8_printf(p->out, "%s", azArg[i]);
25798     }
25799     raw_printf(p->out, "\n");
25800   }else
25801 
25802 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
25803   if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
25804     int i;
25805     int nn = 0;
25806     p->flgProgress = 0;
25807     p->mxProgress = 0;
25808     p->nProgress = 0;
25809     for(i=1; i<nArg; i++){
25810       const char *z = azArg[i];
25811       if( z[0]=='-' ){
25812         z++;
25813         if( z[0]=='-' ) z++;
25814         if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
25815           p->flgProgress |= SHELL_PROGRESS_QUIET;
25816           continue;
25817         }
25818         if( cli_strcmp(z,"reset")==0 ){
25819           p->flgProgress |= SHELL_PROGRESS_RESET;
25820           continue;
25821         }
25822         if( cli_strcmp(z,"once")==0 ){
25823           p->flgProgress |= SHELL_PROGRESS_ONCE;
25824           continue;
25825         }
25826         if( cli_strcmp(z,"limit")==0 ){
25827           if( i+1>=nArg ){
25828             utf8_printf(stderr, "Error: missing argument on --limit\n");
25829             rc = 1;
25830             goto meta_command_exit;
25831           }else{
25832             p->mxProgress = (int)integerValue(azArg[++i]);
25833           }
25834           continue;
25835         }
25836         utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
25837         rc = 1;
25838         goto meta_command_exit;
25839       }else{
25840         nn = (int)integerValue(z);
25841       }
25842     }
25843     open_db(p, 0);
25844     sqlite3_progress_handler(p->db, nn, progress_handler, p);
25845   }else
25846 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
25847 
25848   if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
25849     if( nArg >= 2) {
25850       shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
25851     }
25852     if( nArg >= 3) {
25853       shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
25854     }
25855   }else
25856 
25857 #ifndef SQLITE_SHELL_FIDDLE
25858   if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
25859     rc = 2;
25860   }else
25861 #endif
25862 
25863 #ifndef SQLITE_SHELL_FIDDLE
25864   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
25865     FILE *inSaved = p->in;
25866     int savedLineno = p->lineno;
25867     failIfSafeMode(p, "cannot run .read in safe mode");
25868     if( nArg!=2 ){
25869       raw_printf(stderr, "Usage: .read FILE\n");
25870       rc = 1;
25871       goto meta_command_exit;
25872     }
25873     if( azArg[1][0]=='|' ){
25874 #ifdef SQLITE_OMIT_POPEN
25875       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
25876       rc = 1;
25877       p->out = stdout;
25878 #else
25879       p->in = popen(azArg[1]+1, "r");
25880       if( p->in==0 ){
25881         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
25882         rc = 1;
25883       }else{
25884         rc = process_input(p);
25885         pclose(p->in);
25886       }
25887 #endif
25888     }else if( (p->in = openChrSource(azArg[1]))==0 ){
25889       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
25890       rc = 1;
25891     }else{
25892       rc = process_input(p);
25893       fclose(p->in);
25894     }
25895     p->in = inSaved;
25896     p->lineno = savedLineno;
25897   }else
25898 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25899 
25900 #ifndef SQLITE_SHELL_FIDDLE
25901   if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
25902     const char *zSrcFile;
25903     const char *zDb;
25904     sqlite3 *pSrc;
25905     sqlite3_backup *pBackup;
25906     int nTimeout = 0;
25907 
25908     failIfSafeMode(p, "cannot run .restore in safe mode");
25909     if( nArg==2 ){
25910       zSrcFile = azArg[1];
25911       zDb = "main";
25912     }else if( nArg==3 ){
25913       zSrcFile = azArg[2];
25914       zDb = azArg[1];
25915     }else{
25916       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
25917       rc = 1;
25918       goto meta_command_exit;
25919     }
25920     rc = sqlite3_open(zSrcFile, &pSrc);
25921     if( rc!=SQLITE_OK ){
25922       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
25923       close_db(pSrc);
25924       return 1;
25925     }
25926     open_db(p, 0);
25927     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
25928     if( pBackup==0 ){
25929       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
25930       close_db(pSrc);
25931       return 1;
25932     }
25933     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
25934           || rc==SQLITE_BUSY  ){
25935       if( rc==SQLITE_BUSY ){
25936         if( nTimeout++ >= 3 ) break;
25937         sqlite3_sleep(100);
25938       }
25939     }
25940     sqlite3_backup_finish(pBackup);
25941     if( rc==SQLITE_DONE ){
25942       rc = 0;
25943     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
25944       raw_printf(stderr, "Error: source database is busy\n");
25945       rc = 1;
25946     }else{
25947       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
25948       rc = 1;
25949     }
25950     close_db(pSrc);
25951   }else
25952 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
25953 
25954   if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
25955     if( nArg==2 ){
25956       if( cli_strcmp(azArg[1], "vm")==0 ){
25957         p->scanstatsOn = 3;
25958       }else
25959       if( cli_strcmp(azArg[1], "est")==0 ){
25960         p->scanstatsOn = 2;
25961       }else{
25962         p->scanstatsOn = (u8)booleanValue(azArg[1]);
25963       }
25964       open_db(p, 0);
25965       sqlite3_db_config(
25966           p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
25967       );
25968 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
25969       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
25970 #endif
25971     }else{
25972       raw_printf(stderr, "Usage: .scanstats on|off|est\n");
25973       rc = 1;
25974     }
25975   }else
25976 
25977   if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
25978     ShellText sSelect;
25979     ShellState data;
25980     char *zErrMsg = 0;
25981     const char *zDiv = "(";
25982     const char *zName = 0;
25983     int iSchema = 0;
25984     int bDebug = 0;
25985     int bNoSystemTabs = 0;
25986     int ii;
25987 
25988     open_db(p, 0);
25989     memcpy(&data, p, sizeof(data));
25990     data.showHeader = 0;
25991     data.cMode = data.mode = MODE_Semi;
25992     initText(&sSelect);
25993     for(ii=1; ii<nArg; ii++){
25994       if( optionMatch(azArg[ii],"indent") ){
25995         data.cMode = data.mode = MODE_Pretty;
25996       }else if( optionMatch(azArg[ii],"debug") ){
25997         bDebug = 1;
25998       }else if( optionMatch(azArg[ii],"nosys") ){
25999         bNoSystemTabs = 1;
26000       }else if( azArg[ii][0]=='-' ){
26001         utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
26002         rc = 1;
26003         goto meta_command_exit;
26004       }else if( zName==0 ){
26005         zName = azArg[ii];
26006       }else{
26007         raw_printf(stderr,
26008                    "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
26009         rc = 1;
26010         goto meta_command_exit;
26011       }
26012     }
26013     if( zName!=0 ){
26014       int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
26015                   || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
26016                   || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
26017                   || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
26018       if( isSchema ){
26019         char *new_argv[2], *new_colv[2];
26020         new_argv[0] = sqlite3_mprintf(
26021                       "CREATE TABLE %s (\n"
26022                       "  type text,\n"
26023                       "  name text,\n"
26024                       "  tbl_name text,\n"
26025                       "  rootpage integer,\n"
26026                       "  sql text\n"
26027                       ")", zName);
26028         shell_check_oom(new_argv[0]);
26029         new_argv[1] = 0;
26030         new_colv[0] = "sql";
26031         new_colv[1] = 0;
26032         callback(&data, 1, new_argv, new_colv);
26033         sqlite3_free(new_argv[0]);
26034       }
26035     }
26036     if( zDiv ){
26037       sqlite3_stmt *pStmt = 0;
26038       rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
26039                               -1, &pStmt, 0);
26040       if( rc ){
26041         utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
26042         sqlite3_finalize(pStmt);
26043         rc = 1;
26044         goto meta_command_exit;
26045       }
26046       appendText(&sSelect, "SELECT sql FROM", 0);
26047       iSchema = 0;
26048       while( sqlite3_step(pStmt)==SQLITE_ROW ){
26049         const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
26050         char zScNum[30];
26051         sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
26052         appendText(&sSelect, zDiv, 0);
26053         zDiv = " UNION ALL ";
26054         appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
26055         if( sqlite3_stricmp(zDb, "main")!=0 ){
26056           appendText(&sSelect, zDb, '\'');
26057         }else{
26058           appendText(&sSelect, "NULL", 0);
26059         }
26060         appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
26061         appendText(&sSelect, zScNum, 0);
26062         appendText(&sSelect, " AS snum, ", 0);
26063         appendText(&sSelect, zDb, '\'');
26064         appendText(&sSelect, " AS sname FROM ", 0);
26065         appendText(&sSelect, zDb, quoteChar(zDb));
26066         appendText(&sSelect, ".sqlite_schema", 0);
26067       }
26068       sqlite3_finalize(pStmt);
26069 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
26070       if( zName ){
26071         appendText(&sSelect,
26072            " UNION ALL SELECT shell_module_schema(name),"
26073            " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
26074         0);
26075       }
26076 #endif
26077       appendText(&sSelect, ") WHERE ", 0);
26078       if( zName ){
26079         char *zQarg = sqlite3_mprintf("%Q", zName);
26080         int bGlob;
26081         shell_check_oom(zQarg);
26082         bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
26083                 strchr(zName, '[') != 0;
26084         if( strchr(zName, '.') ){
26085           appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
26086         }else{
26087           appendText(&sSelect, "lower(tbl_name)", 0);
26088         }
26089         appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
26090         appendText(&sSelect, zQarg, 0);
26091         if( !bGlob ){
26092           appendText(&sSelect, " ESCAPE '\\' ", 0);
26093         }
26094         appendText(&sSelect, " AND ", 0);
26095         sqlite3_free(zQarg);
26096       }
26097       if( bNoSystemTabs ){
26098         appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
26099       }
26100       appendText(&sSelect, "sql IS NOT NULL"
26101                            " ORDER BY snum, rowid", 0);
26102       if( bDebug ){
26103         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
26104       }else{
26105         rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
26106       }
26107       freeText(&sSelect);
26108     }
26109     if( zErrMsg ){
26110       utf8_printf(stderr,"Error: %s\n", zErrMsg);
26111       sqlite3_free(zErrMsg);
26112       rc = 1;
26113     }else if( rc != SQLITE_OK ){
26114       raw_printf(stderr,"Error: querying schema information\n");
26115       rc = 1;
26116     }else{
26117       rc = 0;
26118     }
26119   }else
26120 
26121   if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
26122    || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
26123   ){
26124     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
26125     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
26126   }else
26127 
26128 #if defined(SQLITE_ENABLE_SESSION)
26129   if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
26130     struct AuxDb *pAuxDb = p->pAuxDb;
26131     OpenSession *pSession = &pAuxDb->aSession[0];
26132     char **azCmd = &azArg[1];
26133     int iSes = 0;
26134     int nCmd = nArg - 1;
26135     int i;
26136     if( nArg<=1 ) goto session_syntax_error;
26137     open_db(p, 0);
26138     if( nArg>=3 ){
26139       for(iSes=0; iSes<pAuxDb->nSession; iSes++){
26140         if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
26141       }
26142       if( iSes<pAuxDb->nSession ){
26143         pSession = &pAuxDb->aSession[iSes];
26144         azCmd++;
26145         nCmd--;
26146       }else{
26147         pSession = &pAuxDb->aSession[0];
26148         iSes = 0;
26149       }
26150     }
26151 
26152     /* .session attach TABLE
26153     ** Invoke the sqlite3session_attach() interface to attach a particular
26154     ** table so that it is never filtered.
26155     */
26156     if( cli_strcmp(azCmd[0],"attach")==0 ){
26157       if( nCmd!=2 ) goto session_syntax_error;
26158       if( pSession->p==0 ){
26159         session_not_open:
26160         raw_printf(stderr, "ERROR: No sessions are open\n");
26161       }else{
26162         rc = sqlite3session_attach(pSession->p, azCmd[1]);
26163         if( rc ){
26164           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
26165           rc = 0;
26166         }
26167       }
26168     }else
26169 
26170     /* .session changeset FILE
26171     ** .session patchset FILE
26172     ** Write a changeset or patchset into a file.  The file is overwritten.
26173     */
26174     if( cli_strcmp(azCmd[0],"changeset")==0
26175      || cli_strcmp(azCmd[0],"patchset")==0
26176     ){
26177       FILE *out = 0;
26178       failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
26179       if( nCmd!=2 ) goto session_syntax_error;
26180       if( pSession->p==0 ) goto session_not_open;
26181       out = fopen(azCmd[1], "wb");
26182       if( out==0 ){
26183         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
26184                     azCmd[1]);
26185       }else{
26186         int szChng;
26187         void *pChng;
26188         if( azCmd[0][0]=='c' ){
26189           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
26190         }else{
26191           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
26192         }
26193         if( rc ){
26194           printf("Error: error code %d\n", rc);
26195           rc = 0;
26196         }
26197         if( pChng
26198           && fwrite(pChng, szChng, 1, out)!=1 ){
26199           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
26200                   szChng);
26201         }
26202         sqlite3_free(pChng);
26203         fclose(out);
26204       }
26205     }else
26206 
26207     /* .session close
26208     ** Close the identified session
26209     */
26210     if( cli_strcmp(azCmd[0], "close")==0 ){
26211       if( nCmd!=1 ) goto session_syntax_error;
26212       if( pAuxDb->nSession ){
26213         session_close(pSession);
26214         pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
26215       }
26216     }else
26217 
26218     /* .session enable ?BOOLEAN?
26219     ** Query or set the enable flag
26220     */
26221     if( cli_strcmp(azCmd[0], "enable")==0 ){
26222       int ii;
26223       if( nCmd>2 ) goto session_syntax_error;
26224       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
26225       if( pAuxDb->nSession ){
26226         ii = sqlite3session_enable(pSession->p, ii);
26227         utf8_printf(p->out, "session %s enable flag = %d\n",
26228                     pSession->zName, ii);
26229       }
26230     }else
26231 
26232     /* .session filter GLOB ....
26233     ** Set a list of GLOB patterns of table names to be excluded.
26234     */
26235     if( cli_strcmp(azCmd[0], "filter")==0 ){
26236       int ii, nByte;
26237       if( nCmd<2 ) goto session_syntax_error;
26238       if( pAuxDb->nSession ){
26239         for(ii=0; ii<pSession->nFilter; ii++){
26240           sqlite3_free(pSession->azFilter[ii]);
26241         }
26242         sqlite3_free(pSession->azFilter);
26243         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
26244         pSession->azFilter = sqlite3_malloc( nByte );
26245         if( pSession->azFilter==0 ){
26246           raw_printf(stderr, "Error: out or memory\n");
26247           exit(1);
26248         }
26249         for(ii=1; ii<nCmd; ii++){
26250           char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
26251           shell_check_oom(x);
26252         }
26253         pSession->nFilter = ii-1;
26254       }
26255     }else
26256 
26257     /* .session indirect ?BOOLEAN?
26258     ** Query or set the indirect flag
26259     */
26260     if( cli_strcmp(azCmd[0], "indirect")==0 ){
26261       int ii;
26262       if( nCmd>2 ) goto session_syntax_error;
26263       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
26264       if( pAuxDb->nSession ){
26265         ii = sqlite3session_indirect(pSession->p, ii);
26266         utf8_printf(p->out, "session %s indirect flag = %d\n",
26267                     pSession->zName, ii);
26268       }
26269     }else
26270 
26271     /* .session isempty
26272     ** Determine if the session is empty
26273     */
26274     if( cli_strcmp(azCmd[0], "isempty")==0 ){
26275       int ii;
26276       if( nCmd!=1 ) goto session_syntax_error;
26277       if( pAuxDb->nSession ){
26278         ii = sqlite3session_isempty(pSession->p);
26279         utf8_printf(p->out, "session %s isempty flag = %d\n",
26280                     pSession->zName, ii);
26281       }
26282     }else
26283 
26284     /* .session list
26285     ** List all currently open sessions
26286     */
26287     if( cli_strcmp(azCmd[0],"list")==0 ){
26288       for(i=0; i<pAuxDb->nSession; i++){
26289         utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
26290       }
26291     }else
26292 
26293     /* .session open DB NAME
26294     ** Open a new session called NAME on the attached database DB.
26295     ** DB is normally "main".
26296     */
26297     if( cli_strcmp(azCmd[0],"open")==0 ){
26298       char *zName;
26299       if( nCmd!=3 ) goto session_syntax_error;
26300       zName = azCmd[2];
26301       if( zName[0]==0 ) goto session_syntax_error;
26302       for(i=0; i<pAuxDb->nSession; i++){
26303         if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
26304           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
26305           goto meta_command_exit;
26306         }
26307       }
26308       if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
26309         raw_printf(stderr,
26310                    "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
26311         goto meta_command_exit;
26312       }
26313       pSession = &pAuxDb->aSession[pAuxDb->nSession];
26314       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
26315       if( rc ){
26316         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
26317         rc = 0;
26318         goto meta_command_exit;
26319       }
26320       pSession->nFilter = 0;
26321       sqlite3session_table_filter(pSession->p, session_filter, pSession);
26322       pAuxDb->nSession++;
26323       pSession->zName = sqlite3_mprintf("%s", zName);
26324       shell_check_oom(pSession->zName);
26325     }else
26326     /* If no command name matches, show a syntax error */
26327     session_syntax_error:
26328     showHelp(p->out, "session");
26329   }else
26330 #endif
26331 
26332 #ifdef SQLITE_DEBUG
26333   /* Undocumented commands for internal testing.  Subject to change
26334   ** without notice. */
26335   if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
26336     if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
26337       int i, v;
26338       for(i=1; i<nArg; i++){
26339         v = booleanValue(azArg[i]);
26340         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
26341       }
26342     }
26343     if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
26344       int i; sqlite3_int64 v;
26345       for(i=1; i<nArg; i++){
26346         char zBuf[200];
26347         v = integerValue(azArg[i]);
26348         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
26349         utf8_printf(p->out, "%s", zBuf);
26350       }
26351     }
26352   }else
26353 #endif
26354 
26355   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
26356     int bIsInit = 0;         /* True to initialize the SELFTEST table */
26357     int bVerbose = 0;        /* Verbose output */
26358     int bSelftestExists;     /* True if SELFTEST already exists */
26359     int i, k;                /* Loop counters */
26360     int nTest = 0;           /* Number of tests runs */
26361     int nErr = 0;            /* Number of errors seen */
26362     ShellText str;           /* Answer for a query */
26363     sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
26364 
26365     open_db(p,0);
26366     for(i=1; i<nArg; i++){
26367       const char *z = azArg[i];
26368       if( z[0]=='-' && z[1]=='-' ) z++;
26369       if( cli_strcmp(z,"-init")==0 ){
26370         bIsInit = 1;
26371       }else
26372       if( cli_strcmp(z,"-v")==0 ){
26373         bVerbose++;
26374       }else
26375       {
26376         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
26377                     azArg[i], azArg[0]);
26378         raw_printf(stderr, "Should be one of: --init -v\n");
26379         rc = 1;
26380         goto meta_command_exit;
26381       }
26382     }
26383     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
26384            != SQLITE_OK ){
26385       bSelftestExists = 0;
26386     }else{
26387       bSelftestExists = 1;
26388     }
26389     if( bIsInit ){
26390       createSelftestTable(p);
26391       bSelftestExists = 1;
26392     }
26393     initText(&str);
26394     appendText(&str, "x", 0);
26395     for(k=bSelftestExists; k>=0; k--){
26396       if( k==1 ){
26397         rc = sqlite3_prepare_v2(p->db,
26398             "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
26399             -1, &pStmt, 0);
26400       }else{
26401         rc = sqlite3_prepare_v2(p->db,
26402           "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
26403           "      (1,'run','PRAGMA integrity_check','ok')",
26404           -1, &pStmt, 0);
26405       }
26406       if( rc ){
26407         raw_printf(stderr, "Error querying the selftest table\n");
26408         rc = 1;
26409         sqlite3_finalize(pStmt);
26410         goto meta_command_exit;
26411       }
26412       for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
26413         int tno = sqlite3_column_int(pStmt, 0);
26414         const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
26415         const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
26416         const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
26417 
26418         if( zOp==0 ) continue;
26419         if( zSql==0 ) continue;
26420         if( zAns==0 ) continue;
26421         k = 0;
26422         if( bVerbose>0 ){
26423           printf("%d: %s %s\n", tno, zOp, zSql);
26424         }
26425         if( cli_strcmp(zOp,"memo")==0 ){
26426           utf8_printf(p->out, "%s\n", zSql);
26427         }else
26428         if( cli_strcmp(zOp,"run")==0 ){
26429           char *zErrMsg = 0;
26430           str.n = 0;
26431           str.z[0] = 0;
26432           rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
26433           nTest++;
26434           if( bVerbose ){
26435             utf8_printf(p->out, "Result: %s\n", str.z);
26436           }
26437           if( rc || zErrMsg ){
26438             nErr++;
26439             rc = 1;
26440             utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
26441             sqlite3_free(zErrMsg);
26442           }else if( cli_strcmp(zAns,str.z)!=0 ){
26443             nErr++;
26444             rc = 1;
26445             utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
26446             utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
26447           }
26448         }else
26449         {
26450           utf8_printf(stderr,
26451             "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
26452           rc = 1;
26453           break;
26454         }
26455       } /* End loop over rows of content from SELFTEST */
26456       sqlite3_finalize(pStmt);
26457     } /* End loop over k */
26458     freeText(&str);
26459     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
26460   }else
26461 
26462   if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
26463     if( nArg<2 || nArg>3 ){
26464       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
26465       rc = 1;
26466     }
26467     if( nArg>=2 ){
26468       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
26469                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
26470     }
26471     if( nArg>=3 ){
26472       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
26473                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
26474     }
26475   }else
26476 
26477   if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
26478     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
26479     int i;                   /* Loop counter */
26480     int bSchema = 0;         /* Also hash the schema */
26481     int bSeparate = 0;       /* Hash each table separately */
26482     int iSize = 224;         /* Hash algorithm to use */
26483     int bDebug = 0;          /* Only show the query that would have run */
26484     sqlite3_stmt *pStmt;     /* For querying tables names */
26485     char *zSql;              /* SQL to be run */
26486     char *zSep;              /* Separator */
26487     ShellText sSql;          /* Complete SQL for the query to run the hash */
26488     ShellText sQuery;        /* Set of queries used to read all content */
26489     open_db(p, 0);
26490     for(i=1; i<nArg; i++){
26491       const char *z = azArg[i];
26492       if( z[0]=='-' ){
26493         z++;
26494         if( z[0]=='-' ) z++;
26495         if( cli_strcmp(z,"schema")==0 ){
26496           bSchema = 1;
26497         }else
26498         if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
26499          || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
26500         ){
26501           iSize = atoi(&z[5]);
26502         }else
26503         if( cli_strcmp(z,"debug")==0 ){
26504           bDebug = 1;
26505         }else
26506         {
26507           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
26508                       azArg[i], azArg[0]);
26509           showHelp(p->out, azArg[0]);
26510           rc = 1;
26511           goto meta_command_exit;
26512         }
26513       }else if( zLike ){
26514         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
26515         rc = 1;
26516         goto meta_command_exit;
26517       }else{
26518         zLike = z;
26519         bSeparate = 1;
26520         if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
26521       }
26522     }
26523     if( bSchema ){
26524       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
26525              " WHERE type='table' AND coalesce(rootpage,0)>1"
26526              " UNION ALL SELECT 'sqlite_schema'"
26527              " ORDER BY 1 collate nocase";
26528     }else{
26529       zSql = "SELECT lower(name) as tname FROM sqlite_schema"
26530              " WHERE type='table' AND coalesce(rootpage,0)>1"
26531              " AND name NOT LIKE 'sqlite_%'"
26532              " ORDER BY 1 collate nocase";
26533     }
26534     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
26535     initText(&sQuery);
26536     initText(&sSql);
26537     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
26538     zSep = "VALUES(";
26539     while( SQLITE_ROW==sqlite3_step(pStmt) ){
26540       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
26541       if( zTab==0 ) continue;
26542       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
26543       if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
26544         appendText(&sQuery,"SELECT * FROM ", 0);
26545         appendText(&sQuery,zTab,'"');
26546         appendText(&sQuery," NOT INDEXED;", 0);
26547       }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
26548         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
26549                            " ORDER BY name;", 0);
26550       }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
26551         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
26552                            " ORDER BY name;", 0);
26553       }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
26554         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
26555                            " ORDER BY tbl,idx;", 0);
26556       }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
26557         appendText(&sQuery, "SELECT * FROM ", 0);
26558         appendText(&sQuery, zTab, 0);
26559         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
26560       }
26561       appendText(&sSql, zSep, 0);
26562       appendText(&sSql, sQuery.z, '\'');
26563       sQuery.n = 0;
26564       appendText(&sSql, ",", 0);
26565       appendText(&sSql, zTab, '\'');
26566       zSep = "),(";
26567     }
26568     sqlite3_finalize(pStmt);
26569     if( bSeparate ){
26570       zSql = sqlite3_mprintf(
26571           "%s))"
26572           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
26573           "   FROM [sha3sum$query]",
26574           sSql.z, iSize);
26575     }else{
26576       zSql = sqlite3_mprintf(
26577           "%s))"
26578           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
26579           "   FROM [sha3sum$query]",
26580           sSql.z, iSize);
26581     }
26582     shell_check_oom(zSql);
26583     freeText(&sQuery);
26584     freeText(&sSql);
26585     if( bDebug ){
26586       utf8_printf(p->out, "%s\n", zSql);
26587     }else{
26588       shell_exec(p, zSql, 0);
26589     }
26590 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
26591     {
26592       int lrc;
26593       char *zRevText = /* Query for reversible to-blob-to-text check */
26594         "SELECT lower(name) as tname FROM sqlite_schema\n"
26595         "WHERE type='table' AND coalesce(rootpage,0)>1\n"
26596         "AND name NOT LIKE 'sqlite_%%'%s\n"
26597         "ORDER BY 1 collate nocase";
26598       zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
26599       zRevText = sqlite3_mprintf(
26600           /* lower-case query is first run, producing upper-case query. */
26601           "with tabcols as materialized(\n"
26602           "select tname, cname\n"
26603           "from ("
26604           " select printf('\"%%w\"',ss.tname) as tname,"
26605           " printf('\"%%w\"',ti.name) as cname\n"
26606           " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
26607           "select 'SELECT total(bad_text_count) AS bad_text_count\n"
26608           "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
26609           " from (select 'SELECT COUNT(*) AS bad_text_count\n"
26610           "FROM '||tname||' WHERE '\n"
26611           "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
26612           "|| ' AND typeof('||cname||')=''text'' ',\n"
26613           "' OR ') as query, tname from tabcols group by tname)"
26614           , zRevText);
26615       shell_check_oom(zRevText);
26616       if( bDebug ) utf8_printf(p->out, "%s\n", zRevText);
26617       lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
26618       if( lrc!=SQLITE_OK ){
26619         /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
26620         ** user does cruel and unnatural things like ".limit expr_depth 0". */
26621         rc = 1;
26622       }else{
26623         if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
26624         lrc = SQLITE_ROW==sqlite3_step(pStmt);
26625         if( lrc ){
26626           const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
26627           sqlite3_stmt *pCheckStmt;
26628           lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
26629           if( bDebug ) utf8_printf(p->out, "%s\n", zGenQuery);
26630           if( lrc!=SQLITE_OK ){
26631             rc = 1;
26632           }else{
26633             if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
26634               double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
26635               if( countIrreversible>0 ){
26636                 int sz = (int)(countIrreversible + 0.5);
26637                 utf8_printf(stderr,
26638                      "Digest includes %d invalidly encoded text field%s.\n",
26639                             sz, (sz>1)? "s": "");
26640               }
26641             }
26642             sqlite3_finalize(pCheckStmt);
26643           }
26644           sqlite3_finalize(pStmt);
26645         }
26646       }
26647       if( rc ) utf8_printf(stderr, ".sha3sum failed.\n");
26648       sqlite3_free(zRevText);
26649     }
26650 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
26651     sqlite3_free(zSql);
26652   }else
26653 
26654 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
26655   if( c=='s'
26656    && (cli_strncmp(azArg[0], "shell", n)==0
26657        || cli_strncmp(azArg[0],"system",n)==0)
26658   ){
26659     char *zCmd;
26660     int i, x;
26661     failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
26662     if( nArg<2 ){
26663       raw_printf(stderr, "Usage: .system COMMAND\n");
26664       rc = 1;
26665       goto meta_command_exit;
26666     }
26667     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
26668     for(i=2; i<nArg && zCmd!=0; i++){
26669       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
26670                              zCmd, azArg[i]);
26671     }
26672     x = zCmd!=0 ? system(zCmd) : 1;
26673     sqlite3_free(zCmd);
26674     if( x ) raw_printf(stderr, "System command returns %d\n", x);
26675   }else
26676 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
26677 
26678   if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
26679     static const char *azBool[] = { "off", "on", "trigger", "full"};
26680     const char *zOut;
26681     int i;
26682     if( nArg!=1 ){
26683       raw_printf(stderr, "Usage: .show\n");
26684       rc = 1;
26685       goto meta_command_exit;
26686     }
26687     utf8_printf(p->out, "%12.12s: %s\n","echo",
26688                 azBool[ShellHasFlag(p, SHFLG_Echo)]);
26689     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
26690     utf8_printf(p->out, "%12.12s: %s\n","explain",
26691          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
26692     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
26693     if( p->mode==MODE_Column
26694      || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
26695     ){
26696       utf8_printf
26697         (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
26698          modeDescr[p->mode], p->cmOpts.iWrap,
26699          p->cmOpts.bWordWrap ? "on" : "off",
26700          p->cmOpts.bQuote ? "" : "no");
26701     }else{
26702       utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
26703     }
26704     utf8_printf(p->out, "%12.12s: ", "nullvalue");
26705       output_c_string(p->out, p->nullValue);
26706       raw_printf(p->out, "\n");
26707     utf8_printf(p->out,"%12.12s: %s\n","output",
26708             strlen30(p->outfile) ? p->outfile : "stdout");
26709     utf8_printf(p->out,"%12.12s: ", "colseparator");
26710       output_c_string(p->out, p->colSeparator);
26711       raw_printf(p->out, "\n");
26712     utf8_printf(p->out,"%12.12s: ", "rowseparator");
26713       output_c_string(p->out, p->rowSeparator);
26714       raw_printf(p->out, "\n");
26715     switch( p->statsOn ){
26716       case 0:  zOut = "off";     break;
26717       default: zOut = "on";      break;
26718       case 2:  zOut = "stmt";    break;
26719       case 3:  zOut = "vmstep";  break;
26720     }
26721     utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
26722     utf8_printf(p->out, "%12.12s: ", "width");
26723     for (i=0;i<p->nWidth;i++) {
26724       raw_printf(p->out, "%d ", p->colWidth[i]);
26725     }
26726     raw_printf(p->out, "\n");
26727     utf8_printf(p->out, "%12.12s: %s\n", "filename",
26728                 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
26729   }else
26730 
26731   if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
26732     if( nArg==2 ){
26733       if( cli_strcmp(azArg[1],"stmt")==0 ){
26734         p->statsOn = 2;
26735       }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
26736         p->statsOn = 3;
26737       }else{
26738         p->statsOn = (u8)booleanValue(azArg[1]);
26739       }
26740     }else if( nArg==1 ){
26741       display_stats(p->db, p, 0);
26742     }else{
26743       raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
26744       rc = 1;
26745     }
26746   }else
26747 
26748   if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
26749    || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
26750                  || cli_strncmp(azArg[0], "indexes", n)==0) )
26751   ){
26752     sqlite3_stmt *pStmt;
26753     char **azResult;
26754     int nRow, nAlloc;
26755     int ii;
26756     ShellText s;
26757     initText(&s);
26758     open_db(p, 0);
26759     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
26760     if( rc ){
26761       sqlite3_finalize(pStmt);
26762       return shellDatabaseError(p->db);
26763     }
26764 
26765     if( nArg>2 && c=='i' ){
26766       /* It is an historical accident that the .indexes command shows an error
26767       ** when called with the wrong number of arguments whereas the .tables
26768       ** command does not. */
26769       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
26770       rc = 1;
26771       sqlite3_finalize(pStmt);
26772       goto meta_command_exit;
26773     }
26774     for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
26775       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
26776       if( zDbName==0 ) continue;
26777       if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
26778       if( sqlite3_stricmp(zDbName, "main")==0 ){
26779         appendText(&s, "SELECT name FROM ", 0);
26780       }else{
26781         appendText(&s, "SELECT ", 0);
26782         appendText(&s, zDbName, '\'');
26783         appendText(&s, "||'.'||name FROM ", 0);
26784       }
26785       appendText(&s, zDbName, '"');
26786       appendText(&s, ".sqlite_schema ", 0);
26787       if( c=='t' ){
26788         appendText(&s," WHERE type IN ('table','view')"
26789                       "   AND name NOT LIKE 'sqlite_%'"
26790                       "   AND name LIKE ?1", 0);
26791       }else{
26792         appendText(&s," WHERE type='index'"
26793                       "   AND tbl_name LIKE ?1", 0);
26794       }
26795     }
26796     rc = sqlite3_finalize(pStmt);
26797     if( rc==SQLITE_OK ){
26798       appendText(&s, " ORDER BY 1", 0);
26799       rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
26800     }
26801     freeText(&s);
26802     if( rc ) return shellDatabaseError(p->db);
26803 
26804     /* Run the SQL statement prepared by the above block. Store the results
26805     ** as an array of nul-terminated strings in azResult[].  */
26806     nRow = nAlloc = 0;
26807     azResult = 0;
26808     if( nArg>1 ){
26809       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
26810     }else{
26811       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
26812     }
26813     while( sqlite3_step(pStmt)==SQLITE_ROW ){
26814       if( nRow>=nAlloc ){
26815         char **azNew;
26816         int n2 = nAlloc*2 + 10;
26817         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
26818         shell_check_oom(azNew);
26819         nAlloc = n2;
26820         azResult = azNew;
26821       }
26822       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
26823       shell_check_oom(azResult[nRow]);
26824       nRow++;
26825     }
26826     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
26827       rc = shellDatabaseError(p->db);
26828     }
26829 
26830     /* Pretty-print the contents of array azResult[] to the output */
26831     if( rc==0 && nRow>0 ){
26832       int len, maxlen = 0;
26833       int i, j;
26834       int nPrintCol, nPrintRow;
26835       for(i=0; i<nRow; i++){
26836         len = strlen30(azResult[i]);
26837         if( len>maxlen ) maxlen = len;
26838       }
26839       nPrintCol = 80/(maxlen+2);
26840       if( nPrintCol<1 ) nPrintCol = 1;
26841       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
26842       for(i=0; i<nPrintRow; i++){
26843         for(j=i; j<nRow; j+=nPrintRow){
26844           char *zSp = j<nPrintRow ? "" : "  ";
26845           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
26846                       azResult[j] ? azResult[j]:"");
26847         }
26848         raw_printf(p->out, "\n");
26849       }
26850     }
26851 
26852     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
26853     sqlite3_free(azResult);
26854   }else
26855 
26856 #ifndef SQLITE_SHELL_FIDDLE
26857   /* Begin redirecting output to the file "testcase-out.txt" */
26858   if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
26859     output_reset(p);
26860     p->out = output_file_open("testcase-out.txt", 0);
26861     if( p->out==0 ){
26862       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
26863     }
26864     if( nArg>=2 ){
26865       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
26866     }else{
26867       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
26868     }
26869   }else
26870 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
26871 
26872 #ifndef SQLITE_UNTESTABLE
26873   if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
26874     static const struct {
26875        const char *zCtrlName;   /* Name of a test-control option */
26876        int ctrlCode;            /* Integer code for that option */
26877        int unSafe;              /* Not valid unless --unsafe-testing */
26878        const char *zUsage;      /* Usage notes */
26879     } aCtrl[] = {
26880     {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
26881     {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
26882   /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
26883   /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
26884     {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
26885     {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
26886   /*{"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
26887     {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
26888     {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
26889     {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
26890     {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
26891     {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
26892     {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
26893 #ifdef YYCOVERAGE
26894     {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
26895 #endif
26896     {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
26897     {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
26898     {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
26899     {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
26900     {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
26901     {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
26902     {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
26903     {"uselongdouble",    SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
26904     };
26905     int testctrl = -1;
26906     int iCtrl = -1;
26907     int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
26908     int isOk = 0;
26909     int i, n2;
26910     const char *zCmd = 0;
26911 
26912     open_db(p, 0);
26913     zCmd = nArg>=2 ? azArg[1] : "help";
26914 
26915     /* The argument can optionally begin with "-" or "--" */
26916     if( zCmd[0]=='-' && zCmd[1] ){
26917       zCmd++;
26918       if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
26919     }
26920 
26921     /* --help lists all test-controls */
26922     if( cli_strcmp(zCmd,"help")==0 ){
26923       utf8_printf(p->out, "Available test-controls:\n");
26924       for(i=0; i<ArraySize(aCtrl); i++){
26925         if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
26926         utf8_printf(p->out, "  .testctrl %s %s\n",
26927                     aCtrl[i].zCtrlName, aCtrl[i].zUsage);
26928       }
26929       rc = 1;
26930       goto meta_command_exit;
26931     }
26932 
26933     /* convert testctrl text option to value. allow any unique prefix
26934     ** of the option name, or a numerical value. */
26935     n2 = strlen30(zCmd);
26936     for(i=0; i<ArraySize(aCtrl); i++){
26937       if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
26938       if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
26939         if( testctrl<0 ){
26940           testctrl = aCtrl[i].ctrlCode;
26941           iCtrl = i;
26942         }else{
26943           utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
26944                               "Use \".testctrl --help\" for help\n", zCmd);
26945           rc = 1;
26946           goto meta_command_exit;
26947         }
26948       }
26949     }
26950     if( testctrl<0 ){
26951       utf8_printf(stderr,"Error: unknown test-control: %s\n"
26952                          "Use \".testctrl --help\" for help\n", zCmd);
26953     }else{
26954       switch(testctrl){
26955 
26956         /* sqlite3_test_control(int, db, int) */
26957         case SQLITE_TESTCTRL_OPTIMIZATIONS:
26958         case SQLITE_TESTCTRL_FK_NO_ACTION:
26959           if( nArg==3 ){
26960             unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
26961             rc2 = sqlite3_test_control(testctrl, p->db, opt);
26962             isOk = 3;
26963           }
26964           break;
26965 
26966         /* sqlite3_test_control(int) */
26967         case SQLITE_TESTCTRL_PRNG_SAVE:
26968         case SQLITE_TESTCTRL_PRNG_RESTORE:
26969         case SQLITE_TESTCTRL_BYTEORDER:
26970           if( nArg==2 ){
26971             rc2 = sqlite3_test_control(testctrl);
26972             isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
26973           }
26974           break;
26975 
26976         /* sqlite3_test_control(int, uint) */
26977         case SQLITE_TESTCTRL_PENDING_BYTE:
26978           if( nArg==3 ){
26979             unsigned int opt = (unsigned int)integerValue(azArg[2]);
26980             rc2 = sqlite3_test_control(testctrl, opt);
26981             isOk = 3;
26982           }
26983           break;
26984 
26985         /* sqlite3_test_control(int, int, sqlite3*) */
26986         case SQLITE_TESTCTRL_PRNG_SEED:
26987           if( nArg==3 || nArg==4 ){
26988             int ii = (int)integerValue(azArg[2]);
26989             sqlite3 *db;
26990             if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
26991               sqlite3_randomness(sizeof(ii),&ii);
26992               printf("-- random seed: %d\n", ii);
26993             }
26994             if( nArg==3 ){
26995               db = 0;
26996             }else{
26997               db = p->db;
26998               /* Make sure the schema has been loaded */
26999               sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
27000             }
27001             rc2 = sqlite3_test_control(testctrl, ii, db);
27002             isOk = 3;
27003           }
27004           break;
27005 
27006         /* sqlite3_test_control(int, int) */
27007         case SQLITE_TESTCTRL_ASSERT:
27008         case SQLITE_TESTCTRL_ALWAYS:
27009           if( nArg==3 ){
27010             int opt = booleanValue(azArg[2]);
27011             rc2 = sqlite3_test_control(testctrl, opt);
27012             isOk = 1;
27013           }
27014           break;
27015 
27016         /* sqlite3_test_control(int, int) */
27017         case SQLITE_TESTCTRL_LOCALTIME_FAULT:
27018         case SQLITE_TESTCTRL_NEVER_CORRUPT:
27019           if( nArg==3 ){
27020             int opt = booleanValue(azArg[2]);
27021             rc2 = sqlite3_test_control(testctrl, opt);
27022             isOk = 3;
27023           }
27024           break;
27025 
27026         /* sqlite3_test_control(int, int) */
27027         case SQLITE_TESTCTRL_USELONGDOUBLE: {
27028           int opt = -1;
27029           if( nArg==3 ){
27030             if( cli_strcmp(azArg[2],"default")==0 ){
27031               opt = 2;
27032             }else{
27033               opt = booleanValue(azArg[2]);
27034             }
27035           }
27036           rc2 = sqlite3_test_control(testctrl, opt);
27037           isOk = 1;
27038           break;
27039         }
27040 
27041         /* sqlite3_test_control(sqlite3*) */
27042         case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
27043           rc2 = sqlite3_test_control(testctrl, p->db);
27044           isOk = 3;
27045           break;
27046 
27047         case SQLITE_TESTCTRL_IMPOSTER:
27048           if( nArg==5 ){
27049             rc2 = sqlite3_test_control(testctrl, p->db,
27050                           azArg[2],
27051                           integerValue(azArg[3]),
27052                           integerValue(azArg[4]));
27053             isOk = 3;
27054           }
27055           break;
27056 
27057         case SQLITE_TESTCTRL_SEEK_COUNT: {
27058           u64 x = 0;
27059           rc2 = sqlite3_test_control(testctrl, p->db, &x);
27060           utf8_printf(p->out, "%llu\n", x);
27061           isOk = 3;
27062           break;
27063         }
27064 
27065 #ifdef YYCOVERAGE
27066         case SQLITE_TESTCTRL_PARSER_COVERAGE: {
27067           if( nArg==2 ){
27068             sqlite3_test_control(testctrl, p->out);
27069             isOk = 3;
27070           }
27071           break;
27072         }
27073 #endif
27074 #ifdef SQLITE_DEBUG
27075         case SQLITE_TESTCTRL_TUNE: {
27076           if( nArg==4 ){
27077             int id = (int)integerValue(azArg[2]);
27078             int val = (int)integerValue(azArg[3]);
27079             sqlite3_test_control(testctrl, id, &val);
27080             isOk = 3;
27081           }else if( nArg==3 ){
27082             int id = (int)integerValue(azArg[2]);
27083             sqlite3_test_control(testctrl, -id, &rc2);
27084             isOk = 1;
27085           }else if( nArg==2 ){
27086             int id = 1;
27087             while(1){
27088               int val = 0;
27089               rc2 = sqlite3_test_control(testctrl, -id, &val);
27090               if( rc2!=SQLITE_OK ) break;
27091               if( id>1 ) utf8_printf(p->out, "  ");
27092               utf8_printf(p->out, "%d: %d", id, val);
27093               id++;
27094             }
27095             if( id>1 ) utf8_printf(p->out, "\n");
27096             isOk = 3;
27097           }
27098           break;
27099         }
27100 #endif
27101         case SQLITE_TESTCTRL_SORTER_MMAP:
27102           if( nArg==3 ){
27103             int opt = (unsigned int)integerValue(azArg[2]);
27104             rc2 = sqlite3_test_control(testctrl, p->db, opt);
27105             isOk = 3;
27106           }
27107           break;
27108       }
27109     }
27110     if( isOk==0 && iCtrl>=0 ){
27111       utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
27112       rc = 1;
27113     }else if( isOk==1 ){
27114       raw_printf(p->out, "%d\n", rc2);
27115     }else if( isOk==2 ){
27116       raw_printf(p->out, "0x%08x\n", rc2);
27117     }
27118   }else
27119 #endif /* !defined(SQLITE_UNTESTABLE) */
27120 
27121   if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
27122     open_db(p, 0);
27123     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
27124   }else
27125 
27126   if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
27127     if( nArg==2 ){
27128       enableTimer = booleanValue(azArg[1]);
27129       if( enableTimer && !HAS_TIMER ){
27130         raw_printf(stderr, "Error: timer not available on this system.\n");
27131         enableTimer = 0;
27132       }
27133     }else{
27134       raw_printf(stderr, "Usage: .timer on|off\n");
27135       rc = 1;
27136     }
27137   }else
27138 
27139 #ifndef SQLITE_OMIT_TRACE
27140   if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
27141     int mType = 0;
27142     int jj;
27143     open_db(p, 0);
27144     for(jj=1; jj<nArg; jj++){
27145       const char *z = azArg[jj];
27146       if( z[0]=='-' ){
27147         if( optionMatch(z, "expanded") ){
27148           p->eTraceType = SHELL_TRACE_EXPANDED;
27149         }
27150 #ifdef SQLITE_ENABLE_NORMALIZE
27151         else if( optionMatch(z, "normalized") ){
27152           p->eTraceType = SHELL_TRACE_NORMALIZED;
27153         }
27154 #endif
27155         else if( optionMatch(z, "plain") ){
27156           p->eTraceType = SHELL_TRACE_PLAIN;
27157         }
27158         else if( optionMatch(z, "profile") ){
27159           mType |= SQLITE_TRACE_PROFILE;
27160         }
27161         else if( optionMatch(z, "row") ){
27162           mType |= SQLITE_TRACE_ROW;
27163         }
27164         else if( optionMatch(z, "stmt") ){
27165           mType |= SQLITE_TRACE_STMT;
27166         }
27167         else if( optionMatch(z, "close") ){
27168           mType |= SQLITE_TRACE_CLOSE;
27169         }
27170         else {
27171           raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
27172           rc = 1;
27173           goto meta_command_exit;
27174         }
27175       }else{
27176         output_file_close(p->traceOut);
27177         p->traceOut = output_file_open(z, 0);
27178       }
27179     }
27180     if( p->traceOut==0 ){
27181       sqlite3_trace_v2(p->db, 0, 0, 0);
27182     }else{
27183       if( mType==0 ) mType = SQLITE_TRACE_STMT;
27184       sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
27185     }
27186   }else
27187 #endif /* !defined(SQLITE_OMIT_TRACE) */
27188 
27189 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27190   if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
27191     int ii;
27192     int lenOpt;
27193     char *zOpt;
27194     if( nArg<2 ){
27195       raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
27196       rc = 1;
27197       goto meta_command_exit;
27198     }
27199     open_db(p, 0);
27200     zOpt = azArg[1];
27201     if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
27202     lenOpt = (int)strlen(zOpt);
27203     if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
27204       assert( azArg[nArg]==0 );
27205       sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
27206     }else{
27207       for(ii=1; ii<nArg; ii++){
27208         sqlite3_create_module(p->db, azArg[ii], 0, 0);
27209       }
27210     }
27211   }else
27212 #endif
27213 
27214 #if SQLITE_USER_AUTHENTICATION
27215   if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
27216     if( nArg<2 ){
27217       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
27218       rc = 1;
27219       goto meta_command_exit;
27220     }
27221     open_db(p, 0);
27222     if( cli_strcmp(azArg[1],"login")==0 ){
27223       if( nArg!=4 ){
27224         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
27225         rc = 1;
27226         goto meta_command_exit;
27227       }
27228       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
27229                                      strlen30(azArg[3]));
27230       if( rc ){
27231         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
27232         rc = 1;
27233       }
27234     }else if( cli_strcmp(azArg[1],"add")==0 ){
27235       if( nArg!=5 ){
27236         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
27237         rc = 1;
27238         goto meta_command_exit;
27239       }
27240       rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27241                             booleanValue(azArg[4]));
27242       if( rc ){
27243         raw_printf(stderr, "User-Add failed: %d\n", rc);
27244         rc = 1;
27245       }
27246     }else if( cli_strcmp(azArg[1],"edit")==0 ){
27247       if( nArg!=5 ){
27248         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
27249         rc = 1;
27250         goto meta_command_exit;
27251       }
27252       rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
27253                               booleanValue(azArg[4]));
27254       if( rc ){
27255         raw_printf(stderr, "User-Edit failed: %d\n", rc);
27256         rc = 1;
27257       }
27258     }else if( cli_strcmp(azArg[1],"delete")==0 ){
27259       if( nArg!=3 ){
27260         raw_printf(stderr, "Usage: .user delete USER\n");
27261         rc = 1;
27262         goto meta_command_exit;
27263       }
27264       rc = sqlite3_user_delete(p->db, azArg[2]);
27265       if( rc ){
27266         raw_printf(stderr, "User-Delete failed: %d\n", rc);
27267         rc = 1;
27268       }
27269     }else{
27270       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
27271       rc = 1;
27272       goto meta_command_exit;
27273     }
27274   }else
27275 #endif /* SQLITE_USER_AUTHENTICATION */
27276 
27277   if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
27278     char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
27279     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
27280         sqlite3_libversion(), sqlite3_sourceid());
27281 #if SQLITE_HAVE_ZLIB
27282     utf8_printf(p->out, "zlib version %s\n", zlibVersion());
27283 #endif
27284 #define CTIMEOPT_VAL_(opt) #opt
27285 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
27286 #if defined(__clang__) && defined(__clang_major__)
27287     utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
27288                     CTIMEOPT_VAL(__clang_minor__) "."
27289                     CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
27290 #elif defined(_MSC_VER)
27291     utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
27292 #elif defined(__GNUC__) && defined(__VERSION__)
27293     utf8_printf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz);
27294 #endif
27295   }else
27296 
27297   if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
27298     const char *zDbName = nArg==2 ? azArg[1] : "main";
27299     sqlite3_vfs *pVfs = 0;
27300     if( p->db ){
27301       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
27302       if( pVfs ){
27303         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
27304         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
27305         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
27306         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
27307       }
27308     }
27309   }else
27310 
27311   if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
27312     sqlite3_vfs *pVfs;
27313     sqlite3_vfs *pCurrent = 0;
27314     if( p->db ){
27315       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
27316     }
27317     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
27318       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
27319            pVfs==pCurrent ? "  <--- CURRENT" : "");
27320       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
27321       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
27322       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
27323       if( pVfs->pNext ){
27324         raw_printf(p->out, "-----------------------------------\n");
27325       }
27326     }
27327   }else
27328 
27329   if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
27330     const char *zDbName = nArg==2 ? azArg[1] : "main";
27331     char *zVfsName = 0;
27332     if( p->db ){
27333       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
27334       if( zVfsName ){
27335         utf8_printf(p->out, "%s\n", zVfsName);
27336         sqlite3_free(zVfsName);
27337       }
27338     }
27339   }else
27340 
27341   if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
27342     unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
27343     sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
27344   }else
27345 
27346   if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
27347     int j;
27348     assert( nArg<=ArraySize(azArg) );
27349     p->nWidth = nArg-1;
27350     p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
27351     if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
27352     if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
27353     for(j=1; j<nArg; j++){
27354       p->colWidth[j-1] = (int)integerValue(azArg[j]);
27355     }
27356   }else
27357 
27358   {
27359     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
27360       " \"%s\". Enter \".help\" for help\n", azArg[0]);
27361     rc = 1;
27362   }
27363 
27364 meta_command_exit:
27365   if( p->outCount ){
27366     p->outCount--;
27367     if( p->outCount==0 ) output_reset(p);
27368   }
27369   p->bSafeMode = p->bSafeModePersist;
27370   return rc;
27371 }
27372 
27373 /* Line scan result and intermediate states (supporting scan resumption)
27374 */
27375 #ifndef CHAR_BIT
27376 # define CHAR_BIT 8
27377 #endif
27378 typedef enum {
27379   QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
27380   QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
27381   QSS_Start = 0
27382 } QuickScanState;
27383 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
27384 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
27385 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
27386 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
27387 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
27388 
27389 /*
27390 ** Scan line for classification to guide shell's handling.
27391 ** The scan is resumable for subsequent lines when prior
27392 ** return values are passed as the 2nd argument.
27393 */
27394 static QuickScanState quickscan(char *zLine, QuickScanState qss,
27395                                 SCAN_TRACKER_REFTYPE pst){
27396   char cin;
27397   char cWait = (char)qss; /* intentional narrowing loss */
27398   if( cWait==0 ){
27399   PlainScan:
27400     assert( cWait==0 );
27401     while( (cin = *zLine++)!=0 ){
27402       if( IsSpace(cin) )
27403         continue;
27404       switch (cin){
27405       case '-':
27406         if( *zLine!='-' )
27407           break;
27408         while((cin = *++zLine)!=0 )
27409           if( cin=='\n')
27410             goto PlainScan;
27411         return qss;
27412       case ';':
27413         qss |= QSS_EndingSemi;
27414         continue;
27415       case '/':
27416         if( *zLine=='*' ){
27417           ++zLine;
27418           cWait = '*';
27419           CONTINUE_PROMPT_AWAITS(pst, "/*");
27420           qss = QSS_SETV(qss, cWait);
27421           goto TermScan;
27422         }
27423         break;
27424       case '[':
27425         cin = ']';
27426         deliberate_fall_through;
27427       case '`': case '\'': case '"':
27428         cWait = cin;
27429         qss = QSS_HasDark | cWait;
27430         CONTINUE_PROMPT_AWAITC(pst, cin);
27431         goto TermScan;
27432       case '(':
27433         CONTINUE_PAREN_INCR(pst, 1);
27434         break;
27435       case ')':
27436         CONTINUE_PAREN_INCR(pst, -1);
27437         break;
27438       default:
27439         break;
27440       }
27441       qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
27442     }
27443   }else{
27444   TermScan:
27445     while( (cin = *zLine++)!=0 ){
27446       if( cin==cWait ){
27447         switch( cWait ){
27448         case '*':
27449           if( *zLine != '/' )
27450             continue;
27451           ++zLine;
27452           cWait = 0;
27453           CONTINUE_PROMPT_AWAITC(pst, 0);
27454           qss = QSS_SETV(qss, 0);
27455           goto PlainScan;
27456         case '`': case '\'': case '"':
27457           if(*zLine==cWait){
27458             /* Swallow doubled end-delimiter.*/
27459             ++zLine;
27460             continue;
27461           }
27462           deliberate_fall_through;
27463         case ']':
27464           cWait = 0;
27465           CONTINUE_PROMPT_AWAITC(pst, 0);
27466           qss = QSS_SETV(qss, 0);
27467           goto PlainScan;
27468         default: assert(0);
27469         }
27470       }
27471     }
27472   }
27473   return qss;
27474 }
27475 
27476 /*
27477 ** Return TRUE if the line typed in is an SQL command terminator other
27478 ** than a semi-colon.  The SQL Server style "go" command is understood
27479 ** as is the Oracle "/".
27480 */
27481 static int line_is_command_terminator(char *zLine){
27482   while( IsSpace(zLine[0]) ){ zLine++; };
27483   if( zLine[0]=='/' )
27484     zLine += 1; /* Oracle */
27485   else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
27486     zLine += 2; /* SQL Server */
27487   else
27488     return 0;
27489   return quickscan(zLine, QSS_Start, 0)==QSS_Start;
27490 }
27491 
27492 /*
27493 ** The CLI needs a working sqlite3_complete() to work properly.  So error
27494 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
27495 */
27496 #ifdef SQLITE_OMIT_COMPLETE
27497 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
27498 #endif
27499 
27500 /*
27501 ** Return true if zSql is a complete SQL statement.  Return false if it
27502 ** ends in the middle of a string literal or C-style comment.
27503 */
27504 static int line_is_complete(char *zSql, int nSql){
27505   int rc;
27506   if( zSql==0 ) return 1;
27507   zSql[nSql] = ';';
27508   zSql[nSql+1] = 0;
27509   rc = sqlite3_complete(zSql);
27510   zSql[nSql] = 0;
27511   return rc;
27512 }
27513 
27514 /*
27515 ** Run a single line of SQL.  Return the number of errors.
27516 */
27517 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
27518   int rc;
27519   char *zErrMsg = 0;
27520 
27521   open_db(p, 0);
27522   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
27523   if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
27524   BEGIN_TIMER;
27525   rc = shell_exec(p, zSql, &zErrMsg);
27526   END_TIMER;
27527   if( rc || zErrMsg ){
27528     char zPrefix[100];
27529     const char *zErrorTail;
27530     const char *zErrorType;
27531     if( zErrMsg==0 ){
27532       zErrorType = "Error";
27533       zErrorTail = sqlite3_errmsg(p->db);
27534     }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
27535       zErrorType = "Parse error";
27536       zErrorTail = &zErrMsg[12];
27537     }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
27538       zErrorType = "Runtime error";
27539       zErrorTail = &zErrMsg[10];
27540     }else{
27541       zErrorType = "Error";
27542       zErrorTail = zErrMsg;
27543     }
27544     if( in!=0 || !stdin_is_interactive ){
27545       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
27546                        "%s near line %d:", zErrorType, startline);
27547     }else{
27548       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
27549     }
27550     utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
27551     sqlite3_free(zErrMsg);
27552     zErrMsg = 0;
27553     return 1;
27554   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
27555     char zLineBuf[2000];
27556     sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
27557             "changes: %lld   total_changes: %lld",
27558             sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
27559     raw_printf(p->out, "%s\n", zLineBuf);
27560   }
27561   return 0;
27562 }
27563 
27564 static void echo_group_input(ShellState *p, const char *zDo){
27565   if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
27566 }
27567 
27568 #ifdef SQLITE_SHELL_FIDDLE
27569 /*
27570 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
27571 ** impl because we need the global shellState and cannot access it from that
27572 ** function without moving lots of code around (creating a larger/messier diff).
27573 */
27574 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
27575   /* Parse the next line from shellState.wasm.zInput. */
27576   const char *zBegin = shellState.wasm.zPos;
27577   const char *z = zBegin;
27578   char *zLine = 0;
27579   i64 nZ = 0;
27580 
27581   UNUSED_PARAMETER(in);
27582   UNUSED_PARAMETER(isContinuation);
27583   if(!z || !*z){
27584     return 0;
27585   }
27586   while(*z && isspace(*z)) ++z;
27587   zBegin = z;
27588   for(; *z && '\n'!=*z; ++nZ, ++z){}
27589   if(nZ>0 && '\r'==zBegin[nZ-1]){
27590     --nZ;
27591   }
27592   shellState.wasm.zPos = z;
27593   zLine = realloc(zPrior, nZ+1);
27594   shell_check_oom(zLine);
27595   memcpy(zLine, zBegin, nZ);
27596   zLine[nZ] = 0;
27597   return zLine;
27598 }
27599 #endif /* SQLITE_SHELL_FIDDLE */
27600 
27601 /*
27602 ** Read input from *in and process it.  If *in==0 then input
27603 ** is interactive - the user is typing it it.  Otherwise, input
27604 ** is coming from a file or device.  A prompt is issued and history
27605 ** is saved only if input is interactive.  An interrupt signal will
27606 ** cause this routine to exit immediately, unless input is interactive.
27607 **
27608 ** Return the number of errors.
27609 */
27610 static int process_input(ShellState *p){
27611   char *zLine = 0;          /* A single input line */
27612   char *zSql = 0;           /* Accumulated SQL text */
27613   i64 nLine;                /* Length of current line */
27614   i64 nSql = 0;             /* Bytes of zSql[] used */
27615   i64 nAlloc = 0;           /* Allocated zSql[] space */
27616   int rc;                   /* Error code */
27617   int errCnt = 0;           /* Number of errors seen */
27618   i64 startline = 0;        /* Line number for start of current input */
27619   QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
27620 
27621   if( p->inputNesting==MAX_INPUT_NESTING ){
27622     /* This will be more informative in a later version. */
27623     utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
27624                 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
27625     return 1;
27626   }
27627   ++p->inputNesting;
27628   p->lineno = 0;
27629   CONTINUE_PROMPT_RESET;
27630   while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
27631     fflush(p->out);
27632     zLine = one_input_line(p->in, zLine, nSql>0);
27633     if( zLine==0 ){
27634       /* End of input */
27635       if( p->in==0 && stdin_is_interactive ) printf("\n");
27636       break;
27637     }
27638     if( seenInterrupt ){
27639       if( p->in!=0 ) break;
27640       seenInterrupt = 0;
27641     }
27642     p->lineno++;
27643     if( QSS_INPLAIN(qss)
27644         && line_is_command_terminator(zLine)
27645         && line_is_complete(zSql, nSql) ){
27646       memcpy(zLine,";",2);
27647     }
27648     qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
27649     if( QSS_PLAINWHITE(qss) && nSql==0 ){
27650       /* Just swallow single-line whitespace */
27651       echo_group_input(p, zLine);
27652       qss = QSS_Start;
27653       continue;
27654     }
27655     if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
27656       CONTINUE_PROMPT_RESET;
27657       echo_group_input(p, zLine);
27658       if( zLine[0]=='.' ){
27659         rc = do_meta_command(zLine, p);
27660         if( rc==2 ){ /* exit requested */
27661           break;
27662         }else if( rc ){
27663           errCnt++;
27664         }
27665       }
27666       qss = QSS_Start;
27667       continue;
27668     }
27669     /* No single-line dispositions remain; accumulate line(s). */
27670     nLine = strlen(zLine);
27671     if( nSql+nLine+2>=nAlloc ){
27672       /* Grow buffer by half-again increments when big. */
27673       nAlloc = nSql+(nSql>>1)+nLine+100;
27674       zSql = realloc(zSql, nAlloc);
27675       shell_check_oom(zSql);
27676     }
27677     if( nSql==0 ){
27678       i64 i;
27679       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
27680       assert( nAlloc>0 && zSql!=0 );
27681       memcpy(zSql, zLine+i, nLine+1-i);
27682       startline = p->lineno;
27683       nSql = nLine-i;
27684     }else{
27685       zSql[nSql++] = '\n';
27686       memcpy(zSql+nSql, zLine, nLine+1);
27687       nSql += nLine;
27688     }
27689     if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
27690       echo_group_input(p, zSql);
27691       errCnt += runOneSqlLine(p, zSql, p->in, startline);
27692       CONTINUE_PROMPT_RESET;
27693       nSql = 0;
27694       if( p->outCount ){
27695         output_reset(p);
27696         p->outCount = 0;
27697       }else{
27698         clearTempFile(p);
27699       }
27700       p->bSafeMode = p->bSafeModePersist;
27701       qss = QSS_Start;
27702     }else if( nSql && QSS_PLAINWHITE(qss) ){
27703       echo_group_input(p, zSql);
27704       nSql = 0;
27705       qss = QSS_Start;
27706     }
27707   }
27708   if( nSql ){
27709     /* This may be incomplete. Let the SQL parser deal with that. */
27710     echo_group_input(p, zSql);
27711     errCnt += runOneSqlLine(p, zSql, p->in, startline);
27712     CONTINUE_PROMPT_RESET;
27713   }
27714   free(zSql);
27715   free(zLine);
27716   --p->inputNesting;
27717   return errCnt>0;
27718 }
27719 
27720 /*
27721 ** Return a pathname which is the user's home directory.  A
27722 ** 0 return indicates an error of some kind.
27723 */
27724 static char *find_home_dir(int clearFlag){
27725   static char *home_dir = NULL;
27726   if( clearFlag ){
27727     free(home_dir);
27728     home_dir = 0;
27729     return 0;
27730   }
27731   if( home_dir ) return home_dir;
27732 
27733 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
27734      && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
27735   {
27736     struct passwd *pwent;
27737     uid_t uid = getuid();
27738     if( (pwent=getpwuid(uid)) != NULL) {
27739       home_dir = pwent->pw_dir;
27740     }
27741   }
27742 #endif
27743 
27744 #if defined(_WIN32_WCE)
27745   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
27746    */
27747   home_dir = "/";
27748 #else
27749 
27750 #if defined(_WIN32) || defined(WIN32)
27751   if (!home_dir) {
27752     home_dir = getenv("USERPROFILE");
27753   }
27754 #endif
27755 
27756   if (!home_dir) {
27757     home_dir = getenv("HOME");
27758   }
27759 
27760 #if defined(_WIN32) || defined(WIN32)
27761   if (!home_dir) {
27762     char *zDrive, *zPath;
27763     int n;
27764     zDrive = getenv("HOMEDRIVE");
27765     zPath = getenv("HOMEPATH");
27766     if( zDrive && zPath ){
27767       n = strlen30(zDrive) + strlen30(zPath) + 1;
27768       home_dir = malloc( n );
27769       if( home_dir==0 ) return 0;
27770       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
27771       return home_dir;
27772     }
27773     home_dir = "c:\\";
27774   }
27775 #endif
27776 
27777 #endif /* !_WIN32_WCE */
27778 
27779   if( home_dir ){
27780     i64 n = strlen(home_dir) + 1;
27781     char *z = malloc( n );
27782     if( z ) memcpy(z, home_dir, n);
27783     home_dir = z;
27784   }
27785 
27786   return home_dir;
27787 }
27788 
27789 /*
27790 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
27791 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
27792 ** the path to it, else return 0. The result is cached for
27793 ** subsequent calls.
27794 */
27795 static const char *find_xdg_config(void){
27796 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
27797      || defined(__RTP__) || defined(_WRS_KERNEL)
27798   return 0;
27799 #else
27800   static int alreadyTried = 0;
27801   static char *zConfig = 0;
27802   const char *zXdgHome;
27803 
27804   if( alreadyTried!=0 ){
27805     return zConfig;
27806   }
27807   alreadyTried = 1;
27808   zXdgHome = getenv("XDG_CONFIG_HOME");
27809   if( zXdgHome==0 ){
27810     return 0;
27811   }
27812   zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
27813   shell_check_oom(zConfig);
27814   if( access(zConfig,0)!=0 ){
27815     sqlite3_free(zConfig);
27816     zConfig = 0;
27817   }
27818   return zConfig;
27819 #endif
27820 }
27821 
27822 /*
27823 ** Read input from the file given by sqliterc_override.  Or if that
27824 ** parameter is NULL, take input from the first of find_xdg_config()
27825 ** or ~/.sqliterc which is found.
27826 **
27827 ** Returns the number of errors.
27828 */
27829 static void process_sqliterc(
27830   ShellState *p,                  /* Configuration data */
27831   const char *sqliterc_override   /* Name of config file. NULL to use default */
27832 ){
27833   char *home_dir = NULL;
27834   const char *sqliterc = sqliterc_override;
27835   char *zBuf = 0;
27836   FILE *inSaved = p->in;
27837   int savedLineno = p->lineno;
27838 
27839   if( sqliterc == NULL ){
27840     sqliterc = find_xdg_config();
27841   }
27842   if( sqliterc == NULL ){
27843     home_dir = find_home_dir(0);
27844     if( home_dir==0 ){
27845       raw_printf(stderr, "-- warning: cannot find home directory;"
27846                       " cannot read ~/.sqliterc\n");
27847       return;
27848     }
27849     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
27850     shell_check_oom(zBuf);
27851     sqliterc = zBuf;
27852   }
27853   p->in = fopen(sqliterc,"rb");
27854   if( p->in ){
27855     if( stdin_is_interactive ){
27856       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
27857     }
27858     if( process_input(p) && bail_on_error ) exit(1);
27859     fclose(p->in);
27860   }else if( sqliterc_override!=0 ){
27861     utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
27862     if( bail_on_error ) exit(1);
27863   }
27864   p->in = inSaved;
27865   p->lineno = savedLineno;
27866   sqlite3_free(zBuf);
27867 }
27868 
27869 /*
27870 ** Show available command line options
27871 */
27872 static const char zOptions[] =
27873   "   --                   treat no subsequent arguments as options\n"
27874 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
27875   "   -A ARGS...           run \".archive ARGS\" and exit\n"
27876 #endif
27877   "   -append              append the database to the end of the file\n"
27878   "   -ascii               set output mode to 'ascii'\n"
27879   "   -bail                stop after hitting an error\n"
27880   "   -batch               force batch I/O\n"
27881   "   -box                 set output mode to 'box'\n"
27882   "   -column              set output mode to 'column'\n"
27883   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
27884   "   -csv                 set output mode to 'csv'\n"
27885 #if !defined(SQLITE_OMIT_DESERIALIZE)
27886   "   -deserialize         open the database using sqlite3_deserialize()\n"
27887 #endif
27888   "   -echo                print inputs before execution\n"
27889   "   -init FILENAME       read/process named file\n"
27890   "   -[no]header          turn headers on or off\n"
27891 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
27892   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
27893 #endif
27894   "   -help                show this message\n"
27895   "   -html                set output mode to HTML\n"
27896   "   -interactive         force interactive I/O\n"
27897   "   -json                set output mode to 'json'\n"
27898   "   -line                set output mode to 'line'\n"
27899   "   -list                set output mode to 'list'\n"
27900   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
27901   "   -markdown            set output mode to 'markdown'\n"
27902 #if !defined(SQLITE_OMIT_DESERIALIZE)
27903   "   -maxsize N           maximum size for a --deserialize database\n"
27904 #endif
27905   "   -memtrace            trace all memory allocations and deallocations\n"
27906   "   -mmap N              default mmap size set to N\n"
27907 #ifdef SQLITE_ENABLE_MULTIPLEX
27908   "   -multiplex           enable the multiplexor VFS\n"
27909 #endif
27910   "   -newline SEP         set output row separator. Default: '\\n'\n"
27911 #if SHELL_WIN_UTF8_OPT
27912   "   -no-utf8             do not try to set up UTF-8 output (for legacy)\n"
27913 #endif
27914   "   -nofollow            refuse to open symbolic links to database files\n"
27915   "   -nonce STRING        set the safe-mode escape nonce\n"
27916   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
27917   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
27918   "   -pcachetrace         trace all page cache operations\n"
27919   "   -quote               set output mode to 'quote'\n"
27920   "   -readonly            open the database read-only\n"
27921   "   -safe                enable safe-mode\n"
27922   "   -separator SEP       set output column separator. Default: '|'\n"
27923 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
27924   "   -sorterref SIZE      sorter references threshold size\n"
27925 #endif
27926   "   -stats               print memory stats before each finalize\n"
27927   "   -table               set output mode to 'table'\n"
27928   "   -tabs                set output mode to 'tabs'\n"
27929   "   -unsafe-testing      allow unsafe commands and modes for testing\n"
27930 #if SHELL_WIN_UTF8_OPT && 0 /* Option is accepted, but is now the default. */
27931   "   -utf8                setup interactive console code page for UTF-8\n"
27932 #endif
27933   "   -version             show SQLite version\n"
27934   "   -vfs NAME            use NAME as the default VFS\n"
27935 #ifdef SQLITE_ENABLE_VFSTRACE
27936   "   -vfstrace            enable tracing of all VFS calls\n"
27937 #endif
27938 #ifdef SQLITE_HAVE_ZLIB
27939   "   -zip                 open the file as a ZIP Archive\n"
27940 #endif
27941 ;
27942 static void usage(int showDetail){
27943   utf8_printf(stderr,
27944       "Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
27945       "FILENAME is the name of an SQLite database. A new database is created\n"
27946       "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
27947   if( showDetail ){
27948     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
27949   }else{
27950     raw_printf(stderr, "Use the -help option for additional information\n");
27951   }
27952   exit(1);
27953 }
27954 
27955 /*
27956 ** Internal check:  Verify that the SQLite is uninitialized.  Print a
27957 ** error message if it is initialized.
27958 */
27959 static void verify_uninitialized(void){
27960   if( sqlite3_config(-1)==SQLITE_MISUSE ){
27961     utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
27962                         " initialization.\n");
27963   }
27964 }
27965 
27966 /*
27967 ** Initialize the state information in data
27968 */
27969 static void main_init(ShellState *data) {
27970   memset(data, 0, sizeof(*data));
27971   data->normalMode = data->cMode = data->mode = MODE_List;
27972   data->autoExplain = 1;
27973   data->pAuxDb = &data->aAuxDb[0];
27974   memcpy(data->colSeparator,SEP_Column, 2);
27975   memcpy(data->rowSeparator,SEP_Row, 2);
27976   data->showHeader = 0;
27977   data->shellFlgs = SHFLG_Lookaside;
27978   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
27979 #if !defined(SQLITE_SHELL_FIDDLE)
27980   verify_uninitialized();
27981 #endif
27982   sqlite3_config(SQLITE_CONFIG_URI, 1);
27983   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
27984   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
27985   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
27986 }
27987 
27988 /*
27989 ** Output text to the console in a font that attracts extra attention.
27990 */
27991 #ifdef _WIN32
27992 static void printBold(const char *zText){
27993 #if !SQLITE_OS_WINRT
27994   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
27995   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
27996   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
27997   SetConsoleTextAttribute(out,
27998          FOREGROUND_RED|FOREGROUND_INTENSITY
27999   );
28000 #endif
28001   printf("%s", zText);
28002 #if !SQLITE_OS_WINRT
28003   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
28004 #endif
28005 }
28006 #else
28007 static void printBold(const char *zText){
28008   printf("\033[1m%s\033[0m", zText);
28009 }
28010 #endif
28011 
28012 /*
28013 ** Get the argument to an --option.  Throw an error and die if no argument
28014 ** is available.
28015 */
28016 static char *cmdline_option_value(int argc, char **argv, int i){
28017   if( i==argc ){
28018     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
28019             argv[0], argv[argc-1]);
28020     exit(1);
28021   }
28022   return argv[i];
28023 }
28024 
28025 static void sayAbnormalExit(void){
28026   if( seenInterrupt ) fprintf(stderr, "Program interrupted.\n");
28027 }
28028 
28029 #ifndef SQLITE_SHELL_IS_UTF8
28030 #  if (defined(_WIN32) || defined(WIN32)) \
28031    && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
28032 #    define SQLITE_SHELL_IS_UTF8          (0)
28033 #  else
28034 #    define SQLITE_SHELL_IS_UTF8          (1)
28035 #  endif
28036 #endif
28037 
28038 #ifdef SQLITE_SHELL_FIDDLE
28039 #  define main fiddle_main
28040 #endif
28041 
28042 #if SQLITE_SHELL_IS_UTF8
28043 int SQLITE_CDECL main(int argc, char **argv){
28044 #else
28045 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
28046   char **argv;
28047 #endif
28048 #ifdef SQLITE_DEBUG
28049   sqlite3_int64 mem_main_enter = 0;
28050 #endif
28051   char *zErrMsg = 0;
28052 #ifdef SQLITE_SHELL_FIDDLE
28053 #  define data shellState
28054 #else
28055   ShellState data;
28056 #endif
28057   const char *zInitFile = 0;
28058   int i;
28059   int rc = 0;
28060   int warnInmemoryDb = 0;
28061   int readStdin = 1;
28062   int nCmd = 0;
28063   int nOptsEnd = argc;
28064   char **azCmd = 0;
28065   const char *zVfs = 0;           /* Value of -vfs command-line option */
28066 #if !SQLITE_SHELL_IS_UTF8
28067   char **argvToFree = 0;
28068   int argcToFree = 0;
28069 #endif
28070   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
28071 
28072 #ifdef SQLITE_SHELL_FIDDLE
28073   stdin_is_interactive = 0;
28074   stdout_is_console = 1;
28075   data.wasm.zDefaultDbName = "/fiddle.sqlite3";
28076 #else
28077   stdin_is_interactive = isatty(0);
28078   stdout_is_console = isatty(1);
28079 #endif
28080 #if SHELL_WIN_UTF8_OPT
28081   probe_console(); /* Check for console I/O and UTF-8 capability. */
28082   if( !mbcs_opted ) atexit(console_restore);
28083 #endif
28084   atexit(sayAbnormalExit);
28085 #ifdef SQLITE_DEBUG
28086   mem_main_enter = sqlite3_memory_used();
28087 #endif
28088 #if !defined(_WIN32_WCE)
28089   if( getenv("SQLITE_DEBUG_BREAK") ){
28090     if( isatty(0) && isatty(2) ){
28091       fprintf(stderr,
28092           "attach debugger to process %d and press any key to continue.\n",
28093           GETPID());
28094       fgetc(stdin);
28095     }else{
28096 #if defined(_WIN32) || defined(WIN32)
28097 #if SQLITE_OS_WINRT
28098       __debugbreak();
28099 #else
28100       DebugBreak();
28101 #endif
28102 #elif defined(SIGTRAP)
28103       raise(SIGTRAP);
28104 #endif
28105     }
28106   }
28107 #endif
28108   /* Register a valid signal handler early, before much else is done. */
28109 #ifdef SIGINT
28110   signal(SIGINT, interrupt_handler);
28111 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
28112   if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
28113     fprintf(stderr, "No ^C handler.\n");
28114   }
28115 #endif
28116 
28117 #if USE_SYSTEM_SQLITE+0!=1
28118   if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
28119     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
28120             sqlite3_sourceid(), SQLITE_SOURCE_ID);
28121     exit(1);
28122   }
28123 #endif
28124   main_init(&data);
28125 
28126   /* On Windows, we must translate command-line arguments into UTF-8.
28127   ** The SQLite memory allocator subsystem has to be enabled in order to
28128   ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
28129   ** subsequent sqlite3_config() calls will work.  So copy all results into
28130   ** memory that does not come from the SQLite memory allocator.
28131   */
28132 #if !SQLITE_SHELL_IS_UTF8
28133   sqlite3_initialize();
28134   argvToFree = malloc(sizeof(argv[0])*argc*2);
28135   shell_check_oom(argvToFree);
28136   argcToFree = argc;
28137   argv = argvToFree + argc;
28138   for(i=0; i<argc; i++){
28139     char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
28140     i64 n;
28141     shell_check_oom(z);
28142     n = strlen(z);
28143     argv[i] = malloc( n+1 );
28144     shell_check_oom(argv[i]);
28145     memcpy(argv[i], z, n+1);
28146     argvToFree[i] = argv[i];
28147     sqlite3_free(z);
28148   }
28149   sqlite3_shutdown();
28150 #endif
28151 
28152   assert( argc>=1 && argv && argv[0] );
28153   Argv0 = argv[0];
28154 
28155 #ifdef SQLITE_SHELL_DBNAME_PROC
28156   {
28157     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
28158     ** of a C-function that will provide the name of the database file.  Use
28159     ** this compile-time option to embed this shell program in larger
28160     ** applications. */
28161     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
28162     SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
28163     warnInmemoryDb = 0;
28164   }
28165 #endif
28166 
28167   /* Do an initial pass through the command-line argument to locate
28168   ** the name of the database file, the name of the initialization file,
28169   ** the size of the alternative malloc heap, options affecting commands
28170   ** or SQL run from the command line, and the first command to execute.
28171   */
28172 #ifndef SQLITE_SHELL_FIDDLE
28173   verify_uninitialized();
28174 #endif
28175   for(i=1; i<argc; i++){
28176     char *z;
28177     z = argv[i];
28178     if( z[0]!='-' || i>nOptsEnd ){
28179       if( data.aAuxDb->zDbFilename==0 ){
28180         data.aAuxDb->zDbFilename = z;
28181       }else{
28182         /* Excess arguments are interpreted as SQL (or dot-commands) and
28183         ** mean that nothing is read from stdin */
28184         readStdin = 0;
28185         nCmd++;
28186         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
28187         shell_check_oom(azCmd);
28188         azCmd[nCmd-1] = z;
28189       }
28190       continue;
28191     }
28192     if( z[1]=='-' ) z++;
28193     if( cli_strcmp(z, "-")==0 ){
28194       nOptsEnd = i;
28195       continue;
28196     }else if( cli_strcmp(z,"-separator")==0
28197      || cli_strcmp(z,"-nullvalue")==0
28198      || cli_strcmp(z,"-newline")==0
28199      || cli_strcmp(z,"-cmd")==0
28200     ){
28201       (void)cmdline_option_value(argc, argv, ++i);
28202     }else if( cli_strcmp(z,"-init")==0 ){
28203       zInitFile = cmdline_option_value(argc, argv, ++i);
28204     }else if( cli_strcmp(z,"-interactive")==0 ){
28205       /* Need to check for interactive override here to so that it can
28206       ** affect console setup (for Windows only) and testing thereof.
28207       */
28208       stdin_is_interactive = 1;
28209     }else if( cli_strcmp(z,"-batch")==0 ){
28210       /* Need to check for batch mode here to so we can avoid printing
28211       ** informational messages (like from process_sqliterc) before
28212       ** we do the actual processing of arguments later in a second pass.
28213       */
28214       stdin_is_interactive = 0;
28215     }else if( cli_strcmp(z,"-utf8")==0 ){
28216 #if SHELL_WIN_UTF8_OPT
28217       /* Option accepted, but is ignored except for this diagnostic. */
28218       if( mbcs_opted ) fprintf(stderr, "Cannot do UTF-8 at this console.\n");
28219 #endif /* SHELL_WIN_UTF8_OPT */
28220     }else if( cli_strcmp(z,"-no-utf8")==0 ){
28221 #if SHELL_WIN_UTF8_OPT
28222       mbcs_opted = 1;
28223 #endif /* SHELL_WIN_UTF8_OPT */
28224     }else if( cli_strcmp(z,"-heap")==0 ){
28225 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
28226       const char *zSize;
28227       sqlite3_int64 szHeap;
28228 
28229       zSize = cmdline_option_value(argc, argv, ++i);
28230       szHeap = integerValue(zSize);
28231       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
28232       verify_uninitialized();
28233       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
28234 #else
28235       (void)cmdline_option_value(argc, argv, ++i);
28236 #endif
28237     }else if( cli_strcmp(z,"-pagecache")==0 ){
28238       sqlite3_int64 n, sz;
28239       sz = integerValue(cmdline_option_value(argc,argv,++i));
28240       if( sz>70000 ) sz = 70000;
28241       if( sz<0 ) sz = 0;
28242       n = integerValue(cmdline_option_value(argc,argv,++i));
28243       if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
28244         n = 0xffffffffffffLL/sz;
28245       }
28246       verify_uninitialized();
28247       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
28248                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
28249       data.shellFlgs |= SHFLG_Pagecache;
28250     }else if( cli_strcmp(z,"-lookaside")==0 ){
28251       int n, sz;
28252       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
28253       if( sz<0 ) sz = 0;
28254       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
28255       if( n<0 ) n = 0;
28256       verify_uninitialized();
28257       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
28258       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
28259     }else if( cli_strcmp(z,"-threadsafe")==0 ){
28260       int n;
28261       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
28262       verify_uninitialized();
28263       switch( n ){
28264          case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
28265          case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
28266          default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
28267       }
28268 #ifdef SQLITE_ENABLE_VFSTRACE
28269     }else if( cli_strcmp(z,"-vfstrace")==0 ){
28270       extern int vfstrace_register(
28271          const char *zTraceName,
28272          const char *zOldVfsName,
28273          int (*xOut)(const char*,void*),
28274          void *pOutArg,
28275          int makeDefault
28276       );
28277       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
28278 #endif
28279 #ifdef SQLITE_ENABLE_MULTIPLEX
28280     }else if( cli_strcmp(z,"-multiplex")==0 ){
28281       extern int sqlite3_multiplex_initialize(const char*,int);
28282       sqlite3_multiplex_initialize(0, 1);
28283 #endif
28284     }else if( cli_strcmp(z,"-mmap")==0 ){
28285       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
28286       verify_uninitialized();
28287       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
28288 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
28289     }else if( cli_strcmp(z,"-sorterref")==0 ){
28290       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
28291       verify_uninitialized();
28292       sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
28293 #endif
28294     }else if( cli_strcmp(z,"-vfs")==0 ){
28295       zVfs = cmdline_option_value(argc, argv, ++i);
28296 #ifdef SQLITE_HAVE_ZLIB
28297     }else if( cli_strcmp(z,"-zip")==0 ){
28298       data.openMode = SHELL_OPEN_ZIPFILE;
28299 #endif
28300     }else if( cli_strcmp(z,"-append")==0 ){
28301       data.openMode = SHELL_OPEN_APPENDVFS;
28302 #ifndef SQLITE_OMIT_DESERIALIZE
28303     }else if( cli_strcmp(z,"-deserialize")==0 ){
28304       data.openMode = SHELL_OPEN_DESERIALIZE;
28305     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
28306       data.szMax = integerValue(argv[++i]);
28307 #endif
28308     }else if( cli_strcmp(z,"-readonly")==0 ){
28309       data.openMode = SHELL_OPEN_READONLY;
28310     }else if( cli_strcmp(z,"-nofollow")==0 ){
28311       data.openFlags = SQLITE_OPEN_NOFOLLOW;
28312 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
28313     }else if( cli_strncmp(z, "-A",2)==0 ){
28314       /* All remaining command-line arguments are passed to the ".archive"
28315       ** command, so ignore them */
28316       break;
28317 #endif
28318     }else if( cli_strcmp(z, "-memtrace")==0 ){
28319       sqlite3MemTraceActivate(stderr);
28320     }else if( cli_strcmp(z, "-pcachetrace")==0 ){
28321       sqlite3PcacheTraceActivate(stderr);
28322     }else if( cli_strcmp(z,"-bail")==0 ){
28323       bail_on_error = 1;
28324     }else if( cli_strcmp(z,"-nonce")==0 ){
28325       free(data.zNonce);
28326       data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
28327     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
28328       ShellSetFlag(&data,SHFLG_TestingMode);
28329     }else if( cli_strcmp(z,"-safe")==0 ){
28330       /* no-op - catch this on the second pass */
28331     }
28332   }
28333 #ifndef SQLITE_SHELL_FIDDLE
28334   verify_uninitialized();
28335 #endif
28336 
28337 
28338 #ifdef SQLITE_SHELL_INIT_PROC
28339   {
28340     /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
28341     ** of a C-function that will perform initialization actions on SQLite that
28342     ** occur just before or after sqlite3_initialize(). Use this compile-time
28343     ** option to embed this shell program in larger applications. */
28344     extern void SQLITE_SHELL_INIT_PROC(void);
28345     SQLITE_SHELL_INIT_PROC();
28346   }
28347 #else
28348   /* All the sqlite3_config() calls have now been made. So it is safe
28349   ** to call sqlite3_initialize() and process any command line -vfs option. */
28350   sqlite3_initialize();
28351 #endif
28352 
28353   if( zVfs ){
28354     sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
28355     if( pVfs ){
28356       sqlite3_vfs_register(pVfs, 1);
28357     }else{
28358       utf8_printf(stderr, "no such VFS: \"%s\"\n", zVfs);
28359       exit(1);
28360     }
28361   }
28362 #if SHELL_WIN_UTF8_OPT
28363   /* Get indicated Windows console setup done before running invocation commands. */
28364   if( in_console || out_console ){
28365     console_prepare_utf8();
28366   }
28367   if( !in_console ){
28368     setBinaryMode(stdin, 0);
28369   }
28370 #endif
28371 
28372   if( data.pAuxDb->zDbFilename==0 ){
28373 #ifndef SQLITE_OMIT_MEMORYDB
28374     data.pAuxDb->zDbFilename = ":memory:";
28375     warnInmemoryDb = argc==1;
28376 #else
28377     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
28378     return 1;
28379 #endif
28380   }
28381   data.out = stdout;
28382 #ifndef SQLITE_SHELL_FIDDLE
28383   sqlite3_appendvfs_init(0,0,0);
28384 #endif
28385 
28386   /* Go ahead and open the database file if it already exists.  If the
28387   ** file does not exist, delay opening it.  This prevents empty database
28388   ** files from being created if a user mistypes the database name argument
28389   ** to the sqlite command-line tool.
28390   */
28391   if( access(data.pAuxDb->zDbFilename, 0)==0 ){
28392     open_db(&data, 0);
28393   }
28394 
28395   /* Process the initialization file if there is one.  If no -init option
28396   ** is given on the command line, look for a file named ~/.sqliterc and
28397   ** try to process it.
28398   */
28399   process_sqliterc(&data,zInitFile);
28400 
28401   /* Make a second pass through the command-line argument and set
28402   ** options.  This second pass is delayed until after the initialization
28403   ** file is processed so that the command-line arguments will override
28404   ** settings in the initialization file.
28405   */
28406   for(i=1; i<argc; i++){
28407     char *z = argv[i];
28408     if( z[0]!='-' || i>=nOptsEnd ) continue;
28409     if( z[1]=='-' ){ z++; }
28410     if( cli_strcmp(z,"-init")==0 ){
28411       i++;
28412     }else if( cli_strcmp(z,"-html")==0 ){
28413       data.mode = MODE_Html;
28414     }else if( cli_strcmp(z,"-list")==0 ){
28415       data.mode = MODE_List;
28416     }else if( cli_strcmp(z,"-quote")==0 ){
28417       data.mode = MODE_Quote;
28418       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
28419       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
28420     }else if( cli_strcmp(z,"-line")==0 ){
28421       data.mode = MODE_Line;
28422     }else if( cli_strcmp(z,"-column")==0 ){
28423       data.mode = MODE_Column;
28424     }else if( cli_strcmp(z,"-json")==0 ){
28425       data.mode = MODE_Json;
28426     }else if( cli_strcmp(z,"-markdown")==0 ){
28427       data.mode = MODE_Markdown;
28428     }else if( cli_strcmp(z,"-table")==0 ){
28429       data.mode = MODE_Table;
28430     }else if( cli_strcmp(z,"-box")==0 ){
28431       data.mode = MODE_Box;
28432     }else if( cli_strcmp(z,"-csv")==0 ){
28433       data.mode = MODE_Csv;
28434       memcpy(data.colSeparator,",",2);
28435 #ifdef SQLITE_HAVE_ZLIB
28436     }else if( cli_strcmp(z,"-zip")==0 ){
28437       data.openMode = SHELL_OPEN_ZIPFILE;
28438 #endif
28439     }else if( cli_strcmp(z,"-append")==0 ){
28440       data.openMode = SHELL_OPEN_APPENDVFS;
28441 #ifndef SQLITE_OMIT_DESERIALIZE
28442     }else if( cli_strcmp(z,"-deserialize")==0 ){
28443       data.openMode = SHELL_OPEN_DESERIALIZE;
28444     }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
28445       data.szMax = integerValue(argv[++i]);
28446 #endif
28447     }else if( cli_strcmp(z,"-readonly")==0 ){
28448       data.openMode = SHELL_OPEN_READONLY;
28449     }else if( cli_strcmp(z,"-nofollow")==0 ){
28450       data.openFlags |= SQLITE_OPEN_NOFOLLOW;
28451     }else if( cli_strcmp(z,"-ascii")==0 ){
28452       data.mode = MODE_Ascii;
28453       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
28454       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
28455     }else if( cli_strcmp(z,"-tabs")==0 ){
28456       data.mode = MODE_List;
28457       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
28458       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
28459     }else if( cli_strcmp(z,"-separator")==0 ){
28460       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
28461                        "%s",cmdline_option_value(argc,argv,++i));
28462     }else if( cli_strcmp(z,"-newline")==0 ){
28463       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
28464                        "%s",cmdline_option_value(argc,argv,++i));
28465     }else if( cli_strcmp(z,"-nullvalue")==0 ){
28466       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
28467                        "%s",cmdline_option_value(argc,argv,++i));
28468     }else if( cli_strcmp(z,"-header")==0 ){
28469       data.showHeader = 1;
28470       ShellSetFlag(&data, SHFLG_HeaderSet);
28471      }else if( cli_strcmp(z,"-noheader")==0 ){
28472       data.showHeader = 0;
28473       ShellSetFlag(&data, SHFLG_HeaderSet);
28474     }else if( cli_strcmp(z,"-echo")==0 ){
28475       ShellSetFlag(&data, SHFLG_Echo);
28476     }else if( cli_strcmp(z,"-eqp")==0 ){
28477       data.autoEQP = AUTOEQP_on;
28478     }else if( cli_strcmp(z,"-eqpfull")==0 ){
28479       data.autoEQP = AUTOEQP_full;
28480     }else if( cli_strcmp(z,"-stats")==0 ){
28481       data.statsOn = 1;
28482     }else if( cli_strcmp(z,"-scanstats")==0 ){
28483       data.scanstatsOn = 1;
28484     }else if( cli_strcmp(z,"-backslash")==0 ){
28485       /* Undocumented command-line option: -backslash
28486       ** Causes C-style backslash escapes to be evaluated in SQL statements
28487       ** prior to sending the SQL into SQLite.  Useful for injecting
28488       ** crazy bytes in the middle of SQL statements for testing and debugging.
28489       */
28490       ShellSetFlag(&data, SHFLG_Backslash);
28491     }else if( cli_strcmp(z,"-bail")==0 ){
28492       /* No-op.  The bail_on_error flag should already be set. */
28493     }else if( cli_strcmp(z,"-version")==0 ){
28494       printf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
28495              8*(int)sizeof(char*));
28496       return 0;
28497     }else if( cli_strcmp(z,"-interactive")==0 ){
28498       /* already handled */
28499     }else if( cli_strcmp(z,"-batch")==0 ){
28500       /* already handled */
28501     }else if( cli_strcmp(z,"-utf8")==0 ){
28502       /* already handled */
28503     }else if( cli_strcmp(z,"-no-utf8")==0 ){
28504       /* already handled */
28505     }else if( cli_strcmp(z,"-heap")==0 ){
28506       i++;
28507     }else if( cli_strcmp(z,"-pagecache")==0 ){
28508       i+=2;
28509     }else if( cli_strcmp(z,"-lookaside")==0 ){
28510       i+=2;
28511     }else if( cli_strcmp(z,"-threadsafe")==0 ){
28512       i+=2;
28513     }else if( cli_strcmp(z,"-nonce")==0 ){
28514       i += 2;
28515     }else if( cli_strcmp(z,"-mmap")==0 ){
28516       i++;
28517     }else if( cli_strcmp(z,"-memtrace")==0 ){
28518       i++;
28519     }else if( cli_strcmp(z,"-pcachetrace")==0 ){
28520       i++;
28521 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
28522     }else if( cli_strcmp(z,"-sorterref")==0 ){
28523       i++;
28524 #endif
28525     }else if( cli_strcmp(z,"-vfs")==0 ){
28526       i++;
28527 #ifdef SQLITE_ENABLE_VFSTRACE
28528     }else if( cli_strcmp(z,"-vfstrace")==0 ){
28529       i++;
28530 #endif
28531 #ifdef SQLITE_ENABLE_MULTIPLEX
28532     }else if( cli_strcmp(z,"-multiplex")==0 ){
28533       i++;
28534 #endif
28535     }else if( cli_strcmp(z,"-help")==0 ){
28536       usage(1);
28537     }else if( cli_strcmp(z,"-cmd")==0 ){
28538       /* Run commands that follow -cmd first and separately from commands
28539       ** that simply appear on the command-line.  This seems goofy.  It would
28540       ** be better if all commands ran in the order that they appear.  But
28541       ** we retain the goofy behavior for historical compatibility. */
28542       if( i==argc-1 ) break;
28543       z = cmdline_option_value(argc,argv,++i);
28544       if( z[0]=='.' ){
28545         rc = do_meta_command(z, &data);
28546         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
28547       }else{
28548         open_db(&data, 0);
28549         rc = shell_exec(&data, z, &zErrMsg);
28550         if( zErrMsg!=0 ){
28551           utf8_printf(stderr,"Error: %s\n", zErrMsg);
28552           if( bail_on_error ) return rc!=0 ? rc : 1;
28553         }else if( rc!=0 ){
28554           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
28555           if( bail_on_error ) return rc;
28556         }
28557       }
28558 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
28559     }else if( cli_strncmp(z, "-A", 2)==0 ){
28560       if( nCmd>0 ){
28561         utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
28562                             " with \"%s\"\n", z);
28563         return 1;
28564       }
28565       open_db(&data, OPEN_DB_ZIPFILE);
28566       if( z[2] ){
28567         argv[i] = &z[2];
28568         arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
28569       }else{
28570         arDotCommand(&data, 1, argv+i, argc-i);
28571       }
28572       readStdin = 0;
28573       break;
28574 #endif
28575     }else if( cli_strcmp(z,"-safe")==0 ){
28576       data.bSafeMode = data.bSafeModePersist = 1;
28577     }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
28578       /* Acted upon in first pass. */
28579     }else{
28580       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
28581       raw_printf(stderr,"Use -help for a list of options.\n");
28582       return 1;
28583     }
28584     data.cMode = data.mode;
28585   }
28586 
28587   if( !readStdin ){
28588     /* Run all arguments that do not begin with '-' as if they were separate
28589     ** command-line inputs, except for the argToSkip argument which contains
28590     ** the database filename.
28591     */
28592     for(i=0; i<nCmd; i++){
28593       if( azCmd[i][0]=='.' ){
28594         rc = do_meta_command(azCmd[i], &data);
28595         if( rc ){
28596           free(azCmd);
28597           return rc==2 ? 0 : rc;
28598         }
28599       }else{
28600         open_db(&data, 0);
28601         echo_group_input(&data, azCmd[i]);
28602         rc = shell_exec(&data, azCmd[i], &zErrMsg);
28603         if( zErrMsg || rc ){
28604           if( zErrMsg!=0 ){
28605             utf8_printf(stderr,"Error: %s\n", zErrMsg);
28606           }else{
28607             utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
28608           }
28609           sqlite3_free(zErrMsg);
28610           free(azCmd);
28611           return rc!=0 ? rc : 1;
28612         }
28613       }
28614     }
28615   }else{
28616     /* Run commands received from standard input
28617     */
28618     if( stdin_is_interactive ){
28619       char *zHome;
28620       char *zHistory;
28621       const char *zCharset = "";
28622       int nHistory;
28623 #if SHELL_WIN_UTF8_OPT
28624       switch( console_utf8_in+2*console_utf8_out ){
28625       default: case 0: break;
28626       case 1: zCharset = " (utf8 in)"; break;
28627       case 2: zCharset = " (utf8 out)"; break;
28628       case 3: zCharset = " (utf8 I/O)"; break;
28629       }
28630 #endif
28631       printf(
28632         "SQLite version %s %.19s%s\n" /*extra-version-info*/
28633         "Enter \".help\" for usage hints.\n",
28634         sqlite3_libversion(), sqlite3_sourceid(), zCharset
28635       );
28636       if( warnInmemoryDb ){
28637         printf("Connected to a ");
28638         printBold("transient in-memory database");
28639         printf(".\nUse \".open FILENAME\" to reopen on a "
28640                "persistent database.\n");
28641       }
28642       zHistory = getenv("SQLITE_HISTORY");
28643       if( zHistory ){
28644         zHistory = strdup(zHistory);
28645       }else if( (zHome = find_home_dir(0))!=0 ){
28646         nHistory = strlen30(zHome) + 20;
28647         if( (zHistory = malloc(nHistory))!=0 ){
28648           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
28649         }
28650       }
28651       if( zHistory ){ shell_read_history(zHistory); }
28652 #if HAVE_READLINE || HAVE_EDITLINE
28653       rl_attempted_completion_function = readline_completion;
28654 #elif HAVE_LINENOISE
28655       linenoiseSetCompletionCallback(linenoise_completion);
28656 #endif
28657       data.in = 0;
28658       rc = process_input(&data);
28659       if( zHistory ){
28660         shell_stifle_history(2000);
28661         shell_write_history(zHistory);
28662         free(zHistory);
28663       }
28664     }else{
28665       data.in = stdin;
28666       rc = process_input(&data);
28667     }
28668   }
28669 #ifndef SQLITE_SHELL_FIDDLE
28670   /* In WASM mode we have to leave the db state in place so that
28671   ** client code can "push" SQL into it after this call returns. */
28672   free(azCmd);
28673   set_table_name(&data, 0);
28674   if( data.db ){
28675     session_close_all(&data, -1);
28676     close_db(data.db);
28677   }
28678   for(i=0; i<ArraySize(data.aAuxDb); i++){
28679     sqlite3_free(data.aAuxDb[i].zFreeOnClose);
28680     if( data.aAuxDb[i].db ){
28681       session_close_all(&data, i);
28682       close_db(data.aAuxDb[i].db);
28683     }
28684   }
28685   find_home_dir(1);
28686   output_reset(&data);
28687   data.doXdgOpen = 0;
28688   clearTempFile(&data);
28689 #if !SQLITE_SHELL_IS_UTF8
28690   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
28691   free(argvToFree);
28692 #endif
28693   free(data.colWidth);
28694   free(data.zNonce);
28695   /* Clear the global data structure so that valgrind will detect memory
28696   ** leaks */
28697   memset(&data, 0, sizeof(data));
28698 #ifdef SQLITE_DEBUG
28699   if( sqlite3_memory_used()>mem_main_enter ){
28700     utf8_printf(stderr, "Memory leaked: %u bytes\n",
28701                 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
28702   }
28703 #endif
28704 #endif /* !SQLITE_SHELL_FIDDLE */
28705   return rc;
28706 }
28707 
28708 
28709 #ifdef SQLITE_SHELL_FIDDLE
28710 /* Only for emcc experimentation purposes. */
28711 int fiddle_experiment(int a,int b){
28712   return a + b;
28713 }
28714 
28715 /*
28716 ** Returns a pointer to the current DB handle.
28717 */
28718 sqlite3 * fiddle_db_handle(){
28719   return globalDb;
28720 }
28721 
28722 /*
28723 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
28724 ** "main" is assumed. Returns 0 if no db with the given name is
28725 ** open.
28726 */
28727 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
28728   sqlite3_vfs * pVfs = 0;
28729   if(globalDb){
28730     sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
28731                          SQLITE_FCNTL_VFS_POINTER, &pVfs);
28732   }
28733   return pVfs;
28734 }
28735 
28736 /* Only for emcc experimentation purposes. */
28737 sqlite3 * fiddle_db_arg(sqlite3 *arg){
28738     printf("fiddle_db_arg(%p)\n", (const void*)arg);
28739     return arg;
28740 }
28741 
28742 /*
28743 ** Intended to be called via a SharedWorker() while a separate
28744 ** SharedWorker() (which manages the wasm module) is performing work
28745 ** which should be interrupted. Unfortunately, SharedWorker is not
28746 ** portable enough to make real use of.
28747 */
28748 void fiddle_interrupt(void){
28749   if( globalDb ) sqlite3_interrupt(globalDb);
28750 }
28751 
28752 /*
28753 ** Returns the filename of the given db name, assuming "main" if
28754 ** zDbName is NULL. Returns NULL if globalDb is not opened.
28755 */
28756 const char * fiddle_db_filename(const char * zDbName){
28757     return globalDb
28758       ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
28759       : NULL;
28760 }
28761 
28762 /*
28763 ** Completely wipes out the contents of the currently-opened database
28764 ** but leaves its storage intact for reuse.
28765 */
28766 void fiddle_reset_db(void){
28767   if( globalDb ){
28768     int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
28769     if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
28770     sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
28771   }
28772 }
28773 
28774 /*
28775 ** Uses the current database's VFS xRead to stream the db file's
28776 ** contents out to the given callback. The callback gets a single
28777 ** chunk of size n (its 2nd argument) on each call and must return 0
28778 ** on success, non-0 on error. This function returns 0 on success,
28779 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
28780 ** code from the callback. Note that this is not thread-friendly: it
28781 ** expects that it will be the only thread reading the db file and
28782 ** takes no measures to ensure that is the case.
28783 */
28784 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
28785   sqlite3_int64 nSize = 0;
28786   sqlite3_int64 nPos = 0;
28787   sqlite3_file * pFile = 0;
28788   unsigned char buf[1024 * 8];
28789   int nBuf = (int)sizeof(buf);
28790   int rc = shellState.db
28791     ? sqlite3_file_control(shellState.db, "main",
28792                            SQLITE_FCNTL_FILE_POINTER, &pFile)
28793     : SQLITE_NOTFOUND;
28794   if( rc ) return rc;
28795   rc = pFile->pMethods->xFileSize(pFile, &nSize);
28796   if( rc ) return rc;
28797   if(nSize % nBuf){
28798     /* DB size is not an even multiple of the buffer size. Reduce
28799     ** buffer size so that we do not unduly inflate the db size when
28800     ** exporting. */
28801     if(0 == nSize % 4096) nBuf = 4096;
28802     else if(0 == nSize % 2048) nBuf = 2048;
28803     else if(0 == nSize % 1024) nBuf = 1024;
28804     else nBuf = 512;
28805   }
28806   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
28807     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
28808     if(SQLITE_IOERR_SHORT_READ == rc){
28809       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
28810     }
28811     if( 0==rc ) rc = xCallback(buf, nBuf);
28812   }
28813   return rc;
28814 }
28815 
28816 /*
28817 ** Trivial exportable function for emscripten. It processes zSql as if
28818 ** it were input to the sqlite3 shell and redirects all output to the
28819 ** wasm binding. fiddle_main() must have been called before this
28820 ** is called, or results are undefined.
28821 */
28822 void fiddle_exec(const char * zSql){
28823   if(zSql && *zSql){
28824     if('.'==*zSql) puts(zSql);
28825     shellState.wasm.zInput = zSql;
28826     shellState.wasm.zPos = zSql;
28827     process_input(&shellState);
28828     shellState.wasm.zInput = shellState.wasm.zPos = 0;
28829   }
28830 }
28831 #endif /* SQLITE_SHELL_FIDDLE */
28832